pezframe_support/storage/
mod.rs

1// This file is part of Bizinikiwi.
2
3// Copyright (C) Parity Technologies (UK) Ltd. and Dijital Kurdistan Tech Institute
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Stuff to do with the runtime's storage.
19
20use crate::{
21	hash::{ReversibleStorageHasher, StorageHasher},
22	storage::types::{
23		EncodeLikeTuple, HasKeyPrefix, HasReversibleKeyPrefix, KeyGenerator,
24		ReversibleKeyGenerator, TupleToEncodedIter,
25	},
26};
27use alloc::{collections::btree_set::BTreeSet, vec::Vec};
28use codec::{Decode, Encode, EncodeLike, FullCodec, FullEncode};
29use core::marker::PhantomData;
30use pezsp_core::storage::ChildInfo;
31use pezsp_runtime::generic::{Digest, DigestItem};
32
33pub use self::{
34	stream_iter::StorageStreamIter,
35	transactional::{
36		in_storage_layer, with_storage_layer, with_transaction, with_transaction_unchecked,
37	},
38	types::StorageEntryMetadataBuilder,
39};
40pub use pezsp_runtime::TransactionOutcome;
41pub use types::Key;
42
43pub mod bounded_btree_map;
44pub mod bounded_btree_set;
45pub mod bounded_vec;
46pub mod child;
47#[doc(hidden)]
48pub mod generator;
49pub mod hashed;
50pub mod migration;
51pub mod storage_noop_guard;
52mod stream_iter;
53pub mod transactional;
54pub mod types;
55pub mod unhashed;
56pub mod weak_bounded_vec;
57
58/// Utility type for converting a storage map into a `Get<u32>` impl which returns the maximum
59/// key size.
60pub struct KeyLenOf<M>(PhantomData<M>);
61
62/// A trait for working with macro-generated storage values under the bizinikiwi storage API.
63///
64/// Details on implementation can be found at [`generator::StorageValue`].
65pub trait StorageValue<T: FullCodec> {
66	/// The type that get/take return.
67	type Query;
68
69	/// Get the storage key.
70	fn hashed_key() -> [u8; 32];
71
72	/// Does the value (explicitly) exist in storage?
73	fn exists() -> bool;
74
75	/// Load the value from the provided storage instance.
76	fn get() -> Self::Query;
77
78	/// Try to get the underlying value from the provided storage instance.
79	///
80	/// Returns `Ok` if it exists, `Err` if not.
81	fn try_get() -> Result<T, ()>;
82
83	/// Translate a value from some previous type (`O`) to the current type.
84	///
85	/// `f: F` is the translation function.
86	///
87	/// Returns `Err` if the storage item could not be interpreted as the old type, and Ok, along
88	/// with the new value if it could.
89	///
90	/// NOTE: This operates from and to `Option<_>` types; no effort is made to respect the default
91	/// value of the original type.
92	///
93	/// # Warning
94	///
95	/// This function must be used with care, before being updated the storage still contains the
96	/// old type, thus other calls (such as `get`) will fail at decoding it.
97	///
98	/// # Usage
99	///
100	/// This would typically be called inside the module implementation of on_runtime_upgrade, while
101	/// ensuring **no usage of this storage are made before the call to `on_runtime_upgrade`**.
102	/// (More precisely prior initialized modules doesn't make use of this storage).
103	fn translate<O: Decode, F: FnOnce(Option<O>) -> Option<T>>(f: F) -> Result<Option<T>, ()>;
104
105	/// Store a value under this key into the provided storage instance.
106	fn put<Arg: EncodeLike<T>>(val: Arg);
107
108	/// Store a value under this key into the provided storage instance; this uses the query
109	/// type rather than the underlying value.
110	fn set(val: Self::Query);
111
112	/// Mutate the value
113	fn mutate<R, F: FnOnce(&mut Self::Query) -> R>(f: F) -> R;
114
115	/// Mutate the value under a key if the value already exists. Do nothing and return the default
116	/// value if not.
117	fn mutate_extant<R: Default, F: FnOnce(&mut T) -> R>(f: F) -> R {
118		Self::mutate_exists(|maybe_v| match maybe_v {
119			Some(ref mut value) => f(value),
120			None => R::default(),
121		})
122	}
123
124	/// Mutate the value if closure returns `Ok`
125	fn try_mutate<R, E, F: FnOnce(&mut Self::Query) -> Result<R, E>>(f: F) -> Result<R, E>;
126
127	/// Mutate the value. Deletes the item if mutated to a `None`.
128	fn mutate_exists<R, F: FnOnce(&mut Option<T>) -> R>(f: F) -> R;
129
130	/// Mutate the value if closure returns `Ok`. Deletes the item if mutated to a `None`.
131	fn try_mutate_exists<R, E, F: FnOnce(&mut Option<T>) -> Result<R, E>>(f: F) -> Result<R, E>;
132
133	/// Clear the storage value.
134	fn kill();
135
136	/// Take a value from storage, removing it afterwards.
137	fn take() -> Self::Query;
138
139	/// Append the given item to the value in the storage.
140	///
141	/// `T` is required to implement [`StorageAppend`].
142	///
143	/// # Warning
144	///
145	/// If the storage item is not encoded properly, the storage item will be overwritten
146	/// and set to `[item]`. Any default value set for the storage item will be ignored
147	/// on overwrite.
148	fn append<Item, EncodeLikeItem>(item: EncodeLikeItem)
149	where
150		Item: Encode,
151		EncodeLikeItem: EncodeLike<Item>,
152		T: StorageAppend<Item>;
153
154	/// Read the length of the storage value without decoding the entire value.
155	///
156	/// `T` is required to implement [`StorageDecodeLength`].
157	///
158	/// If the value does not exists or it fails to decode the length, `None` is returned.
159	/// Otherwise `Some(len)` is returned.
160	///
161	/// # Warning
162	///
163	/// `None` does not mean that `get()` does not return a value. The default value is completely
164	/// ignored by this function.
165	fn decode_len() -> Option<usize>
166	where
167		T: StorageDecodeLength,
168	{
169		T::decode_len(&Self::hashed_key())
170	}
171
172	/// Read the length of the storage value without decoding the entire value.
173	///
174	/// `T` is required to implement [`StorageDecodeNonDedupLength`].
175	///
176	/// If the value does not exists or it fails to decode the length, `None` is returned.
177	/// Otherwise `Some(len)` is returned.
178	///
179	/// # Warning
180	///
181	/// - The value returned is the non-deduplicated length of the underlying Vector in storage.This
182	/// means that any duplicate items are included.
183	///
184	/// - `None` does not mean that `get()` does not return a value. The default value is completely
185	/// ignored by this function.
186	///
187	/// # Example
188	#[doc = docify::embed!("src/storage/mod.rs", btree_set_decode_non_dedup_len)]
189	/// This demonstrates how `decode_non_dedup_len` will count even the duplicate values in the
190	/// storage (in this case, the number `4` is counted twice).
191	fn decode_non_dedup_len() -> Option<usize>
192	where
193		T: StorageDecodeNonDedupLength,
194	{
195		T::decode_non_dedup_len(&Self::hashed_key())
196	}
197}
198
199/// A non-continuous container type.
200pub trait StorageList<V: FullCodec> {
201	/// Iterator for normal and draining iteration.
202	type Iterator: Iterator<Item = V>;
203
204	/// Append iterator for fast append operations.
205	type Appender: StorageAppender<V>;
206
207	/// List the elements in append order.
208	fn iter() -> Self::Iterator;
209
210	/// Drain the elements in append order.
211	///
212	/// Note that this drains a value as soon as it is being inspected. For example `take_while(|_|
213	/// false)` still drains the first element. This also applies to `peek()`.
214	fn drain() -> Self::Iterator;
215
216	/// A fast append iterator.
217	fn appender() -> Self::Appender;
218
219	/// Append a single element.
220	///
221	/// Should not be called repeatedly; use `append_many` instead.
222	/// Worst case linear `O(len)` with `len` being the number if elements in the list.
223	fn append_one<EncodeLikeValue>(item: EncodeLikeValue)
224	where
225		EncodeLikeValue: EncodeLike<V>,
226	{
227		Self::append_many(core::iter::once(item));
228	}
229
230	/// Append many elements.
231	///
232	/// Should not be called repeatedly; use `appender` instead.
233	/// Worst case linear `O(len + items.count())` with `len` beings the number if elements in the
234	/// list.
235	fn append_many<EncodeLikeValue, I>(items: I)
236	where
237		EncodeLikeValue: EncodeLike<V>,
238		I: IntoIterator<Item = EncodeLikeValue>,
239	{
240		let mut ap = Self::appender();
241		ap.append_many(items);
242	}
243}
244
245/// Append iterator to append values to a storage struct.
246///
247/// Can be used in situations where appending does not have constant time complexity.
248pub trait StorageAppender<V: FullCodec> {
249	/// Append a single item in constant time `O(1)`.
250	fn append<EncodeLikeValue>(&mut self, item: EncodeLikeValue)
251	where
252		EncodeLikeValue: EncodeLike<V>;
253
254	/// Append many items in linear time `O(items.count())`.
255	// Note: a default impl is provided since `Self` is already assumed to be optimal for single
256	// append operations.
257	fn append_many<EncodeLikeValue, I>(&mut self, items: I)
258	where
259		EncodeLikeValue: EncodeLike<V>,
260		I: IntoIterator<Item = EncodeLikeValue>,
261	{
262		for item in items.into_iter() {
263			self.append(item);
264		}
265	}
266}
267
268/// A strongly-typed map in storage.
269///
270/// Details on implementation can be found at [`generator::StorageMap`].
271pub trait StorageMap<K: FullEncode, V: FullCodec> {
272	/// The type that get/take return.
273	type Query;
274
275	/// Get the storage key used to fetch a value corresponding to a specific key.
276	fn hashed_key_for<KeyArg: EncodeLike<K>>(key: KeyArg) -> Vec<u8>;
277
278	/// Does the value (explicitly) exist in storage?
279	fn contains_key<KeyArg: EncodeLike<K>>(key: KeyArg) -> bool;
280
281	/// Load the value associated with the given key from the map.
282	fn get<KeyArg: EncodeLike<K>>(key: KeyArg) -> Self::Query;
283
284	/// Store or remove the value to be associated with `key` so that `get` returns the `query`.
285	fn set<KeyArg: EncodeLike<K>>(key: KeyArg, query: Self::Query);
286
287	/// Try to get the value for the given key from the map.
288	///
289	/// Returns `Ok` if it exists, `Err` if not.
290	fn try_get<KeyArg: EncodeLike<K>>(key: KeyArg) -> Result<V, ()>;
291
292	/// Swap the values of two keys.
293	fn swap<KeyArg1: EncodeLike<K>, KeyArg2: EncodeLike<K>>(key1: KeyArg1, key2: KeyArg2);
294
295	/// Store a value to be associated with the given key from the map.
296	fn insert<KeyArg: EncodeLike<K>, ValArg: EncodeLike<V>>(key: KeyArg, val: ValArg);
297
298	/// Remove the value under a key.
299	fn remove<KeyArg: EncodeLike<K>>(key: KeyArg);
300
301	/// Mutate the value under a key.
302	fn mutate<KeyArg: EncodeLike<K>, R, F: FnOnce(&mut Self::Query) -> R>(key: KeyArg, f: F) -> R;
303
304	/// Mutate the item, only if an `Ok` value is returned.
305	fn try_mutate<KeyArg: EncodeLike<K>, R, E, F: FnOnce(&mut Self::Query) -> Result<R, E>>(
306		key: KeyArg,
307		f: F,
308	) -> Result<R, E>;
309
310	/// Mutate the value under a key if the value already exists. Do nothing and return the default
311	/// value if not.
312	fn mutate_extant<KeyArg: EncodeLike<K>, R: Default, F: FnOnce(&mut V) -> R>(
313		key: KeyArg,
314		f: F,
315	) -> R {
316		Self::mutate_exists(key, |maybe_v| match maybe_v {
317			Some(ref mut value) => f(value),
318			None => R::default(),
319		})
320	}
321
322	/// Mutate the value under a key.
323	///
324	/// Deletes the item if mutated to a `None`.
325	fn mutate_exists<KeyArg: EncodeLike<K>, R, F: FnOnce(&mut Option<V>) -> R>(
326		key: KeyArg,
327		f: F,
328	) -> R;
329
330	/// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`.
331	/// `f` will always be called with an option representing if the storage item exists (`Some<V>`)
332	/// or if the storage item does not exist (`None`), independent of the `QueryType`.
333	fn try_mutate_exists<KeyArg: EncodeLike<K>, R, E, F: FnOnce(&mut Option<V>) -> Result<R, E>>(
334		key: KeyArg,
335		f: F,
336	) -> Result<R, E>;
337
338	/// Take the value under a key.
339	fn take<KeyArg: EncodeLike<K>>(key: KeyArg) -> Self::Query;
340
341	/// Append the given items to the value in the storage.
342	///
343	/// `V` is required to implement `codec::EncodeAppend`.
344	///
345	/// # Warning
346	///
347	/// If the storage item is not encoded properly, the storage will be overwritten
348	/// and set to `[item]`. Any default value set for the storage item will be ignored
349	/// on overwrite.
350	fn append<Item, EncodeLikeItem, EncodeLikeKey>(key: EncodeLikeKey, item: EncodeLikeItem)
351	where
352		EncodeLikeKey: EncodeLike<K>,
353		Item: Encode,
354		EncodeLikeItem: EncodeLike<Item>,
355		V: StorageAppend<Item>;
356
357	/// Read the length of the storage value without decoding the entire value under the
358	/// given `key`.
359	///
360	/// `V` is required to implement [`StorageDecodeLength`].
361	///
362	/// If the value does not exists or it fails to decode the length, `None` is returned.
363	/// Otherwise `Some(len)` is returned.
364	///
365	/// # Warning
366	///
367	/// `None` does not mean that `get()` does not return a value. The default value is completely
368	/// ignored by this function.
369	fn decode_len<KeyArg: EncodeLike<K>>(key: KeyArg) -> Option<usize>
370	where
371		V: StorageDecodeLength,
372	{
373		V::decode_len(&Self::hashed_key_for(key))
374	}
375
376	/// Read the length of the storage value without decoding the entire value.
377	///
378	/// `V` is required to implement [`StorageDecodeNonDedupLength`].
379	///
380	/// If the value does not exists or it fails to decode the length, `None` is returned.
381	/// Otherwise `Some(len)` is returned.
382	///
383	/// # Warning
384	///
385	///  - `None` does not mean that `get()` does not return a value. The default value is
386	///    completely
387	/// ignored by this function.
388	///
389	/// - The value returned is the non-deduplicated length of the underlying Vector in storage.This
390	/// means that any duplicate items are included.
391	fn decode_non_dedup_len<KeyArg: EncodeLike<K>>(key: KeyArg) -> Option<usize>
392	where
393		V: StorageDecodeNonDedupLength,
394	{
395		V::decode_non_dedup_len(&Self::hashed_key_for(key))
396	}
397
398	/// Migrate an item with the given `key` from a defunct `OldHasher` to the current hasher.
399	///
400	/// If the key doesn't exist, then it's a no-op. If it does, then it returns its value.
401	fn migrate_key<OldHasher: StorageHasher, KeyArg: EncodeLike<K>>(key: KeyArg) -> Option<V>;
402
403	/// Migrate an item with the given `key` from a `blake2_256` hasher to the current hasher.
404	///
405	/// If the key doesn't exist, then it's a no-op. If it does, then it returns its value.
406	fn migrate_key_from_blake<KeyArg: EncodeLike<K>>(key: KeyArg) -> Option<V> {
407		Self::migrate_key::<crate::hash::Blake2_256, KeyArg>(key)
408	}
409}
410
411/// A strongly-typed map in storage whose keys and values can be iterated over.
412pub trait IterableStorageMap<K: FullEncode, V: FullCodec>: StorageMap<K, V> {
413	/// The type that iterates over all `(key, value)`.
414	type Iterator: Iterator<Item = (K, V)>;
415	/// The type that iterates over all `key`s.
416	type KeyIterator: Iterator<Item = K>;
417
418	/// Enumerate all elements in the map in lexicographical order of the encoded key. If you
419	/// alter the map while doing this, you'll get undefined results.
420	fn iter() -> Self::Iterator;
421
422	/// Enumerate all elements in the map after a specified `starting_raw_key` in lexicographical
423	/// order of the encoded key. If you alter the map while doing this, you'll get undefined
424	/// results.
425	fn iter_from(starting_raw_key: Vec<u8>) -> Self::Iterator;
426
427	/// Enumerate all keys in the map in lexicographical order of the encoded key, skipping over
428	/// the elements. If you alter the map while doing this, you'll get undefined results.
429	fn iter_keys() -> Self::KeyIterator;
430
431	/// Enumerate all keys in the map after a specified `starting_raw_key` in lexicographical order
432	/// of the encoded key. If you alter the map while doing this, you'll get undefined results.
433	fn iter_keys_from(starting_raw_key: Vec<u8>) -> Self::KeyIterator;
434
435	/// Remove all elements from the map and iterate through them in lexicographical order of the
436	/// encoded key. If you add elements to the map while doing this, you'll get undefined results.
437	fn drain() -> Self::Iterator;
438
439	/// Translate the values of all elements by a function `f`, in the map in lexicographical order
440	/// of the encoded key.
441	/// By returning `None` from `f` for an element, you'll remove it from the map.
442	///
443	/// NOTE: If a value fail to decode because storage is corrupted then it is skipped.
444	fn translate<O: Decode, F: FnMut(K, O) -> Option<V>>(f: F);
445
446	/// Translate the next entry following `previous_key` by a function `f`.
447	/// By returning `None` from `f` for an element, you'll remove it from the map.
448	///
449	/// Returns the next key to iterate from in lexicographical order of the encoded key.
450	fn translate_next<O: Decode, F: FnMut(K, O) -> Option<V>>(
451		previous_key: Option<Vec<u8>>,
452		f: F,
453	) -> Option<Vec<u8>>;
454}
455
456/// A strongly-typed double map in storage whose secondary keys and values can be iterated over.
457pub trait IterableStorageDoubleMap<K1: FullCodec, K2: FullCodec, V: FullCodec>:
458	StorageDoubleMap<K1, K2, V>
459{
460	/// The type that iterates over all `key2`.
461	type PartialKeyIterator: Iterator<Item = K2>;
462
463	/// The type that iterates over all `(key2, value)`.
464	type PrefixIterator: Iterator<Item = (K2, V)>;
465
466	/// The type that iterates over all `(key1, key2)`.
467	type FullKeyIterator: Iterator<Item = (K1, K2)>;
468
469	/// The type that iterates over all `(key1, key2, value)`.
470	type Iterator: Iterator<Item = (K1, K2, V)>;
471
472	/// Enumerate all elements in the map with first key `k1` in lexicographical order of the
473	/// encoded key. If you add or remove values whose first key is `k1` to the map while doing
474	/// this, you'll get undefined results.
475	fn iter_prefix(k1: impl EncodeLike<K1>) -> Self::PrefixIterator;
476
477	/// Enumerate all elements in the map with first key `k1` after a specified `starting_raw_key`
478	/// in lexicographical order of the encoded key. If you add or remove values whose first key is
479	/// `k1` to the map while doing this, you'll get undefined results.
480	fn iter_prefix_from(k1: impl EncodeLike<K1>, starting_raw_key: Vec<u8>)
481		-> Self::PrefixIterator;
482
483	/// Enumerate all second keys `k2` in the map with the same first key `k1` in lexicographical
484	/// order of the encoded key. If you add or remove values whose first key is `k1` to the map
485	/// while doing this, you'll get undefined results.
486	fn iter_key_prefix(k1: impl EncodeLike<K1>) -> Self::PartialKeyIterator;
487
488	/// Enumerate all second keys `k2` in the map with the same first key `k1` after a specified
489	/// `starting_raw_key` in lexicographical order of the encoded key. If you add or remove values
490	/// whose first key is `k1` to the map while doing this, you'll get undefined results.
491	fn iter_key_prefix_from(
492		k1: impl EncodeLike<K1>,
493		starting_raw_key: Vec<u8>,
494	) -> Self::PartialKeyIterator;
495
496	/// Remove all elements from the map with first key `k1` and iterate through them in
497	/// lexicographical order of the encoded key. If you add elements with first key `k1` to the
498	/// map while doing this, you'll get undefined results.
499	fn drain_prefix(k1: impl EncodeLike<K1>) -> Self::PrefixIterator;
500
501	/// Enumerate all elements in the map in lexicographical order of the encoded key. If you add
502	/// or remove values to the map while doing this, you'll get undefined results.
503	fn iter() -> Self::Iterator;
504
505	/// Enumerate all elements in the map after a specified `starting_raw_key` in lexicographical
506	/// order of the encoded key. If you add or remove values to the map while doing this, you'll
507	/// get undefined results.
508	fn iter_from(starting_raw_key: Vec<u8>) -> Self::Iterator;
509
510	/// Enumerate all keys `k1` and `k2` in the map in lexicographical order of the encoded key. If
511	/// you add or remove values to the map while doing this, you'll get undefined results.
512	fn iter_keys() -> Self::FullKeyIterator;
513
514	/// Enumerate all keys `k1` and `k2` in the map after a specified `starting_raw_key` in
515	/// lexicographical order of the encoded key. If you add or remove values to the map while
516	/// doing this, you'll get undefined results.
517	fn iter_keys_from(starting_raw_key: Vec<u8>) -> Self::FullKeyIterator;
518
519	/// Remove all elements from the map and iterate through them in lexicographical order of the
520	/// encoded key. If you add elements to the map while doing this, you'll get undefined results.
521	fn drain() -> Self::Iterator;
522
523	/// Translate the values of all elements by a function `f`, in the map in lexicographical order
524	/// of the encoded key.
525	/// By returning `None` from `f` for an element, you'll remove it from the map.
526	///
527	/// NOTE: If a value fail to decode because storage is corrupted then it is skipped.
528	fn translate<O: Decode, F: FnMut(K1, K2, O) -> Option<V>>(f: F);
529}
530
531/// A strongly-typed map with arbitrary number of keys in storage whose keys and values can be
532/// iterated over.
533pub trait IterableStorageNMap<K: ReversibleKeyGenerator, V: FullCodec>: StorageNMap<K, V> {
534	/// The type that iterates over all `(key1, key2, key3, ... keyN)` tuples.
535	type KeyIterator: Iterator<Item = K::Key>;
536
537	/// The type that iterates over all `(key1, key2, key3, ... keyN), value)` tuples.
538	type Iterator: Iterator<Item = (K::Key, V)>;
539
540	/// Enumerate all elements in the map with prefix key `kp` in lexicographical order of the
541	/// encoded key. If you add or remove values whose prefix is `kp` to the map while doing this,
542	/// you'll get undefined results.
543	fn iter_prefix<KP>(kp: KP) -> PrefixIterator<(<K as HasKeyPrefix<KP>>::Suffix, V)>
544	where
545		K: HasReversibleKeyPrefix<KP>;
546
547	/// Enumerate all elements in the map with prefix key `kp` after a specified `starting_raw_key`
548	/// in lexicographical order of the encoded key. If you add or remove values whose prefix is
549	/// `kp` to the map while doing this, you'll get undefined results.
550	fn iter_prefix_from<KP>(
551		kp: KP,
552		starting_raw_key: Vec<u8>,
553	) -> PrefixIterator<(<K as HasKeyPrefix<KP>>::Suffix, V)>
554	where
555		K: HasReversibleKeyPrefix<KP>;
556
557	/// Enumerate all suffix keys in the map with prefix key `kp` in lexicographical order of the
558	/// encoded key. If you add or remove values whose prefix is `kp` to the map while doing this,
559	/// you'll get undefined results.
560	fn iter_key_prefix<KP>(kp: KP) -> KeyPrefixIterator<<K as HasKeyPrefix<KP>>::Suffix>
561	where
562		K: HasReversibleKeyPrefix<KP>;
563
564	/// Enumerate all suffix keys in the map with prefix key `kp` after a specified
565	/// `starting_raw_key` in lexicographical order of the encoded key. If you add or remove values
566	/// whose prefix is `kp` to the map while doing this, you'll get undefined results.
567	fn iter_key_prefix_from<KP>(
568		kp: KP,
569		starting_raw_key: Vec<u8>,
570	) -> KeyPrefixIterator<<K as HasKeyPrefix<KP>>::Suffix>
571	where
572		K: HasReversibleKeyPrefix<KP>;
573
574	/// Remove all elements from the map with prefix key `kp` and iterate through them in
575	/// lexicographical order of the encoded key. If you add elements with prefix key `kp` to the
576	/// map while doing this, you'll get undefined results.
577	fn drain_prefix<KP>(kp: KP) -> PrefixIterator<(<K as HasKeyPrefix<KP>>::Suffix, V)>
578	where
579		K: HasReversibleKeyPrefix<KP>;
580
581	/// Enumerate all elements in the map in lexicographical order of the encoded key. If you add
582	/// or remove values to the map while doing this, you'll get undefined results.
583	fn iter() -> Self::Iterator;
584
585	/// Enumerate all elements in the map after a specified `starting_raw_key` in lexicographical
586	/// order of the encoded key. If you add or remove values to the map while doing this, you'll
587	/// get undefined results.
588	fn iter_from(starting_raw_key: Vec<u8>) -> Self::Iterator;
589
590	/// Enumerate all keys in the map in lexicographical order of the encoded key. If you add or
591	/// remove values to the map while doing this, you'll get undefined results.
592	fn iter_keys() -> Self::KeyIterator;
593
594	/// Enumerate all keys in the map after `starting_raw_key` in lexicographical order of the
595	/// encoded key. If you add or remove values to the map while doing this, you'll get undefined
596	/// results.
597	fn iter_keys_from(starting_raw_key: Vec<u8>) -> Self::KeyIterator;
598
599	/// Remove all elements from the map and iterate through them in lexicographical order of the
600	/// encoded key. If you add elements to the map while doing this, you'll get undefined results.
601	fn drain() -> Self::Iterator;
602
603	/// Translate the values of all elements by a function `f`, in the map in lexicographical order
604	/// of the encoded key.
605	/// By returning `None` from `f` for an element, you'll remove it from the map.
606	///
607	/// NOTE: If a value fail to decode because storage is corrupted then it is skipped.
608	fn translate<O: Decode, F: FnMut(K::Key, O) -> Option<V>>(f: F);
609}
610
611/// An implementation of a map with a two keys.
612///
613/// Details on implementation can be found at [`generator::StorageDoubleMap`].
614pub trait StorageDoubleMap<K1: FullEncode, K2: FullEncode, V: FullCodec> {
615	/// The type that get/take returns.
616	type Query;
617
618	/// Get the storage key used to fetch a value corresponding to a specific key.
619	fn hashed_key_for<KArg1, KArg2>(k1: KArg1, k2: KArg2) -> Vec<u8>
620	where
621		KArg1: EncodeLike<K1>,
622		KArg2: EncodeLike<K2>;
623
624	/// Does the value (explicitly) exist in storage?
625	fn contains_key<KArg1, KArg2>(k1: KArg1, k2: KArg2) -> bool
626	where
627		KArg1: EncodeLike<K1>,
628		KArg2: EncodeLike<K2>;
629
630	/// Load the value associated with the given key from the double map.
631	fn get<KArg1, KArg2>(k1: KArg1, k2: KArg2) -> Self::Query
632	where
633		KArg1: EncodeLike<K1>,
634		KArg2: EncodeLike<K2>;
635
636	/// Try to get the value for the given key from the double map.
637	///
638	/// Returns `Ok` if it exists, `Err` if not.
639	fn try_get<KArg1, KArg2>(k1: KArg1, k2: KArg2) -> Result<V, ()>
640	where
641		KArg1: EncodeLike<K1>,
642		KArg2: EncodeLike<K2>;
643
644	/// Store or remove the value to be associated with `key` so that `get` returns the `query`.
645	fn set<KArg1: EncodeLike<K1>, KArg2: EncodeLike<K2>>(k1: KArg1, k2: KArg2, query: Self::Query);
646
647	/// Take a value from storage, removing it afterwards.
648	fn take<KArg1, KArg2>(k1: KArg1, k2: KArg2) -> Self::Query
649	where
650		KArg1: EncodeLike<K1>,
651		KArg2: EncodeLike<K2>;
652
653	/// Swap the values of two key-pairs.
654	fn swap<XKArg1, XKArg2, YKArg1, YKArg2>(x_k1: XKArg1, x_k2: XKArg2, y_k1: YKArg1, y_k2: YKArg2)
655	where
656		XKArg1: EncodeLike<K1>,
657		XKArg2: EncodeLike<K2>,
658		YKArg1: EncodeLike<K1>,
659		YKArg2: EncodeLike<K2>;
660
661	/// Store a value to be associated with the given keys from the double map.
662	fn insert<KArg1, KArg2, VArg>(k1: KArg1, k2: KArg2, val: VArg)
663	where
664		KArg1: EncodeLike<K1>,
665		KArg2: EncodeLike<K2>,
666		VArg: EncodeLike<V>;
667
668	/// Remove the value under the given keys.
669	fn remove<KArg1, KArg2>(k1: KArg1, k2: KArg2)
670	where
671		KArg1: EncodeLike<K1>,
672		KArg2: EncodeLike<K2>;
673
674	/// Remove all values under the first key `k1` in the overlay and up to `limit` in the
675	/// backend.
676	///
677	/// All values in the client overlay will be deleted, if there is some `limit` then up to
678	/// `limit` values are deleted from the client backend, if `limit` is none then all values in
679	/// the client backend are deleted.
680	///
681	/// # Note
682	///
683	/// Calling this multiple times per block with a `limit` set leads always to the same keys being
684	/// removed and the same result being returned. This happens because the keys to delete in the
685	/// overlay are not taken into account when deleting keys in the backend.
686	#[deprecated = "Use `clear_prefix` instead"]
687	fn remove_prefix<KArg1>(k1: KArg1, limit: Option<u32>) -> pezsp_io::KillStorageResult
688	where
689		KArg1: ?Sized + EncodeLike<K1>;
690
691	/// Remove all values under the first key `k1` in the overlay and up to `maybe_limit` in the
692	/// backend.
693	///
694	/// All values in the client overlay will be deleted, if `maybe_limit` is `Some` then up to
695	/// that number of values are deleted from the client backend, otherwise all values in the
696	/// client backend are deleted.
697	///
698	/// ## Cursors
699	///
700	/// The `maybe_cursor` parameter should be `None` for the first call to initial removal.
701	/// If the resultant `maybe_cursor` is `Some`, then another call is required to complete the
702	/// removal operation. This value must be passed in as the subsequent call's `maybe_cursor`
703	/// parameter. If the resultant `maybe_cursor` is `None`, then the operation is complete and no
704	/// items remain in storage provided that no items were added between the first calls and the
705	/// final call.
706	fn clear_prefix<KArg1>(
707		k1: KArg1,
708		limit: u32,
709		maybe_cursor: Option<&[u8]>,
710	) -> pezsp_io::MultiRemovalResults
711	where
712		KArg1: ?Sized + EncodeLike<K1>;
713
714	/// Does any value under the first key `k1` (explicitly) exist in storage?
715	/// Might have unexpected behaviour with empty keys, e.g. `[]`.
716	fn contains_prefix<KArg1>(k1: KArg1) -> bool
717	where
718		KArg1: EncodeLike<K1>;
719
720	/// Iterate over values that share the first key.
721	fn iter_prefix_values<KArg1>(k1: KArg1) -> PrefixIterator<V>
722	where
723		KArg1: ?Sized + EncodeLike<K1>;
724
725	/// Mutate the value under the given keys.
726	fn mutate<KArg1, KArg2, R, F>(k1: KArg1, k2: KArg2, f: F) -> R
727	where
728		KArg1: EncodeLike<K1>,
729		KArg2: EncodeLike<K2>,
730		F: FnOnce(&mut Self::Query) -> R;
731
732	/// Mutate the value under the given keys when the closure returns `Ok`.
733	fn try_mutate<KArg1, KArg2, R, E, F>(k1: KArg1, k2: KArg2, f: F) -> Result<R, E>
734	where
735		KArg1: EncodeLike<K1>,
736		KArg2: EncodeLike<K2>,
737		F: FnOnce(&mut Self::Query) -> Result<R, E>;
738
739	/// Mutate the value under the given keys. Deletes the item if mutated to a `None`.
740	fn mutate_exists<KArg1, KArg2, R, F>(k1: KArg1, k2: KArg2, f: F) -> R
741	where
742		KArg1: EncodeLike<K1>,
743		KArg2: EncodeLike<K2>,
744		F: FnOnce(&mut Option<V>) -> R;
745
746	/// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`.
747	/// `f` will always be called with an option representing if the storage item exists (`Some<V>`)
748	/// or if the storage item does not exist (`None`), independent of the `QueryType`.
749	fn try_mutate_exists<KArg1, KArg2, R, E, F>(k1: KArg1, k2: KArg2, f: F) -> Result<R, E>
750	where
751		KArg1: EncodeLike<K1>,
752		KArg2: EncodeLike<K2>,
753		F: FnOnce(&mut Option<V>) -> Result<R, E>;
754
755	/// Append the given item to the value in the storage.
756	///
757	/// `V` is required to implement [`StorageAppend`].
758	///
759	/// # Warning
760	///
761	/// If the storage item is not encoded properly, the storage will be overwritten
762	/// and set to `[item]`. Any default value set for the storage item will be ignored
763	/// on overwrite.
764	fn append<Item, EncodeLikeItem, KArg1, KArg2>(k1: KArg1, k2: KArg2, item: EncodeLikeItem)
765	where
766		KArg1: EncodeLike<K1>,
767		KArg2: EncodeLike<K2>,
768		Item: Encode,
769		EncodeLikeItem: EncodeLike<Item>,
770		V: StorageAppend<Item>;
771
772	/// Read the length of the storage value without decoding the entire value under the
773	/// given `key1` and `key2`.
774	///
775	/// `V` is required to implement [`StorageDecodeLength`].
776	///
777	/// If the value does not exists or it fails to decode the length, `None` is returned.
778	/// Otherwise `Some(len)` is returned.
779	///
780	/// # Warning
781	///
782	/// `None` does not mean that `get()` does not return a value. The default value is completely
783	/// ignored by this function.
784	fn decode_len<KArg1, KArg2>(key1: KArg1, key2: KArg2) -> Option<usize>
785	where
786		KArg1: EncodeLike<K1>,
787		KArg2: EncodeLike<K2>,
788		V: StorageDecodeLength,
789	{
790		V::decode_len(&Self::hashed_key_for(key1, key2))
791	}
792
793	/// Read the length of the storage value without decoding the entire value under the
794	/// given `key1` and `key2`.
795	///
796	/// `V` is required to implement [`StorageDecodeNonDedupLength`].
797	///
798	/// If the value does not exists or it fails to decode the length, `None` is returned.
799	/// Otherwise `Some(len)` is returned.
800	///
801	/// # Warning
802	///
803	/// `None` does not mean that `get()` does not return a value. The default value is completely
804	/// ignored by this function.
805	fn decode_non_dedup_len<KArg1, KArg2>(key1: KArg1, key2: KArg2) -> Option<usize>
806	where
807		KArg1: EncodeLike<K1>,
808		KArg2: EncodeLike<K2>,
809		V: StorageDecodeNonDedupLength,
810	{
811		V::decode_non_dedup_len(&Self::hashed_key_for(key1, key2))
812	}
813
814	/// Migrate an item with the given `key1` and `key2` from defunct `OldHasher1` and
815	/// `OldHasher2` to the current hashers.
816	///
817	/// If the key doesn't exist, then it's a no-op. If it does, then it returns its value.
818	fn migrate_keys<
819		OldHasher1: StorageHasher,
820		OldHasher2: StorageHasher,
821		KeyArg1: EncodeLike<K1>,
822		KeyArg2: EncodeLike<K2>,
823	>(
824		key1: KeyArg1,
825		key2: KeyArg2,
826	) -> Option<V>;
827}
828
829/// An implementation of a map with an arbitrary number of keys.
830///
831/// Details of implementation can be found at [`generator::StorageNMap`].
832pub trait StorageNMap<K: KeyGenerator, V: FullCodec> {
833	/// The type that get/take returns.
834	type Query;
835
836	/// Get the storage key used to fetch a value corresponding to a specific key.
837	fn hashed_key_for<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> Vec<u8>;
838
839	/// Does the value (explicitly) exist in storage?
840	fn contains_key<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> bool;
841
842	/// Load the value associated with the given key from the map.
843	fn get<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> Self::Query;
844
845	/// Try to get the value for the given key from the map.
846	///
847	/// Returns `Ok` if it exists, `Err` if not.
848	fn try_get<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> Result<V, ()>;
849
850	/// Store or remove the value to be associated with `key` so that `get` returns the `query`.
851	fn set<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg, query: Self::Query);
852
853	/// Swap the values of two keys.
854	fn swap<KOther, KArg1, KArg2>(key1: KArg1, key2: KArg2)
855	where
856		KOther: KeyGenerator,
857		KArg1: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
858		KArg2: EncodeLikeTuple<KOther::KArg> + TupleToEncodedIter;
859
860	/// Store a value to be associated with the given key from the map.
861	fn insert<KArg, VArg>(key: KArg, val: VArg)
862	where
863		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
864		VArg: EncodeLike<V>;
865
866	/// Remove the value under a key.
867	fn remove<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg);
868
869	/// Remove all values starting with `partial_key` in the overlay and up to `limit` in the
870	/// backend.
871	///
872	/// All values in the client overlay will be deleted, if there is some `limit` then up to
873	/// `limit` values are deleted from the client backend, if `limit` is none then all values in
874	/// the client backend are deleted.
875	///
876	/// # Note
877	///
878	/// Calling this multiple times per block with a `limit` set leads always to the same keys being
879	/// removed and the same result being returned. This happens because the keys to delete in the
880	/// overlay are not taken into account when deleting keys in the backend.
881	#[deprecated = "Use `clear_prefix` instead"]
882	fn remove_prefix<KP>(partial_key: KP, limit: Option<u32>) -> pezsp_io::KillStorageResult
883	where
884		K: HasKeyPrefix<KP>;
885
886	/// Attempt to remove items from the map matching a `partial_key` prefix.
887	///
888	/// Returns [`MultiRemovalResults`](pezsp_io::MultiRemovalResults) to inform about the result.
889	/// Once the resultant `maybe_cursor` field is `None`, then no further items remain to be
890	/// deleted.
891	///
892	/// NOTE: After the initial call for any given map, it is important that no further items
893	/// are inserted into the map which match the `partial key`. If so, then the map may not be
894	/// empty when the resultant `maybe_cursor` is `None`.
895	///
896	/// # Limit
897	///
898	/// A `limit` must be provided in order to cap the maximum
899	/// amount of deletions done in a single call. This is one fewer than the
900	/// maximum number of backend iterations which may be done by this operation and as such
901	/// represents the maximum number of backend deletions which may happen. A `limit` of zero
902	/// implies that no keys will be deleted, though there may be a single iteration done.
903	///
904	/// # Cursor
905	///
906	/// A *cursor* may be passed in to this operation with `maybe_cursor`. `None` should only be
907	/// passed once (in the initial call) for any given storage map and `partial_key`. Subsequent
908	/// calls operating on the same map/`partial_key` should always pass `Some`, and this should be
909	/// equal to the previous call result's `maybe_cursor` field.
910	fn clear_prefix<KP>(
911		partial_key: KP,
912		limit: u32,
913		maybe_cursor: Option<&[u8]>,
914	) -> pezsp_io::MultiRemovalResults
915	where
916		K: HasKeyPrefix<KP>;
917
918	/// Does any value under a `partial_key` prefix (explicitly) exist in storage?
919	/// Might have unexpected behaviour with empty keys, e.g. `[]`.
920	fn contains_prefix<KP>(partial_key: KP) -> bool
921	where
922		K: HasKeyPrefix<KP>;
923
924	/// Iterate over values that share the partial prefix key.
925	fn iter_prefix_values<KP>(partial_key: KP) -> PrefixIterator<V>
926	where
927		K: HasKeyPrefix<KP>;
928
929	/// Mutate the value under a key.
930	fn mutate<KArg, R, F>(key: KArg, f: F) -> R
931	where
932		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
933		F: FnOnce(&mut Self::Query) -> R;
934
935	/// Mutate the item, only if an `Ok` value is returned.
936	fn try_mutate<KArg, R, E, F>(key: KArg, f: F) -> Result<R, E>
937	where
938		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
939		F: FnOnce(&mut Self::Query) -> Result<R, E>;
940
941	/// Mutate the value under a key.
942	///
943	/// Deletes the item if mutated to a `None`.
944	fn mutate_exists<KArg, R, F>(key: KArg, f: F) -> R
945	where
946		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
947		F: FnOnce(&mut Option<V>) -> R;
948
949	/// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`.
950	/// `f` will always be called with an option representing if the storage item exists (`Some<V>`)
951	/// or if the storage item does not exist (`None`), independent of the `QueryType`.
952	fn try_mutate_exists<KArg, R, E, F>(key: KArg, f: F) -> Result<R, E>
953	where
954		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
955		F: FnOnce(&mut Option<V>) -> Result<R, E>;
956
957	/// Take the value under a key.
958	fn take<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> Self::Query;
959
960	/// Append the given items to the value in the storage.
961	///
962	/// `V` is required to implement `codec::EncodeAppend`.
963	///
964	/// # Warning
965	///
966	/// If the storage item is not encoded properly, the storage will be overwritten
967	/// and set to `[item]`. Any default value set for the storage item will be ignored
968	/// on overwrite.
969	fn append<Item, EncodeLikeItem, KArg>(key: KArg, item: EncodeLikeItem)
970	where
971		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
972		Item: Encode,
973		EncodeLikeItem: EncodeLike<Item>,
974		V: StorageAppend<Item>;
975
976	/// Read the length of the storage value without decoding the entire value under the
977	/// given `key`.
978	///
979	/// `V` is required to implement [`StorageDecodeLength`].
980	///
981	/// If the value does not exists or it fails to decode the length, `None` is returned.
982	/// Otherwise `Some(len)` is returned.
983	///
984	/// # Warning
985	///
986	/// `None` does not mean that `get()` does not return a value. The default value is completely
987	/// ignored by this function.
988	fn decode_len<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> Option<usize>
989	where
990		V: StorageDecodeLength,
991	{
992		V::decode_len(&Self::hashed_key_for(key))
993	}
994
995	/// Migrate an item with the given `key` from defunct `hash_fns` to the current hashers.
996	///
997	/// If the key doesn't exist, then it's a no-op. If it does, then it returns its value.
998	fn migrate_keys<KArg>(key: KArg, hash_fns: K::HArg) -> Option<V>
999	where
1000		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter;
1001}
1002
1003/// Iterate or drain over a prefix and decode raw_key and raw_value into `T`.
1004///
1005/// If any decoding fails it skips it and continues to the next key.
1006///
1007/// If draining, then the hook `OnRemoval::on_removal` is called after each removal.
1008pub struct PrefixIterator<T, OnRemoval = ()> {
1009	prefix: Vec<u8>,
1010	previous_key: Vec<u8>,
1011	/// If true then value are removed while iterating
1012	drain: bool,
1013	/// Function that take `(raw_key_without_prefix, raw_value)` and decode `T`.
1014	/// `raw_key_without_prefix` is the raw storage key without the prefix iterated on.
1015	closure: fn(&[u8], &[u8]) -> Result<T, codec::Error>,
1016	phantom: core::marker::PhantomData<OnRemoval>,
1017}
1018
1019impl<T, OnRemoval1> PrefixIterator<T, OnRemoval1> {
1020	/// Converts to the same iterator but with the different 'OnRemoval' type
1021	pub fn convert_on_removal<OnRemoval2>(self) -> PrefixIterator<T, OnRemoval2> {
1022		PrefixIterator::<T, OnRemoval2> {
1023			prefix: self.prefix,
1024			previous_key: self.previous_key,
1025			drain: self.drain,
1026			closure: self.closure,
1027			phantom: Default::default(),
1028		}
1029	}
1030}
1031
1032/// Trait for specialising on removal logic of [`PrefixIterator`].
1033pub trait PrefixIteratorOnRemoval {
1034	/// This function is called whenever a key/value is removed.
1035	fn on_removal(key: &[u8], value: &[u8]);
1036}
1037
1038/// No-op implementation.
1039impl PrefixIteratorOnRemoval for () {
1040	fn on_removal(_key: &[u8], _value: &[u8]) {}
1041}
1042
1043impl<T, OnRemoval> PrefixIterator<T, OnRemoval> {
1044	/// Creates a new `PrefixIterator`, iterating after `previous_key` and filtering out keys that
1045	/// are not prefixed with `prefix`.
1046	///
1047	/// A `decode_fn` function must also be supplied, and it takes in two `&[u8]` parameters,
1048	/// returning a `Result` containing the decoded type `T` if successful, and a `codec::Error` on
1049	/// failure. The first `&[u8]` argument represents the raw, undecoded key without the prefix of
1050	/// the current item, while the second `&[u8]` argument denotes the corresponding raw,
1051	/// undecoded value.
1052	pub fn new(
1053		prefix: Vec<u8>,
1054		previous_key: Vec<u8>,
1055		decode_fn: fn(&[u8], &[u8]) -> Result<T, codec::Error>,
1056	) -> Self {
1057		PrefixIterator {
1058			prefix,
1059			previous_key,
1060			drain: false,
1061			closure: decode_fn,
1062			phantom: Default::default(),
1063		}
1064	}
1065
1066	/// Get the last key that has been iterated upon and return it.
1067	pub fn last_raw_key(&self) -> &[u8] {
1068		&self.previous_key
1069	}
1070
1071	/// Get the prefix that is being iterated upon for this iterator and return it.
1072	pub fn prefix(&self) -> &[u8] {
1073		&self.prefix
1074	}
1075
1076	/// Set the key that the iterator should start iterating after.
1077	pub fn set_last_raw_key(&mut self, previous_key: Vec<u8>) {
1078		self.previous_key = previous_key;
1079	}
1080
1081	/// Mutate this iterator into a draining iterator; items iterated are removed from storage.
1082	pub fn drain(mut self) -> Self {
1083		self.drain = true;
1084		self
1085	}
1086}
1087
1088impl<T, OnRemoval: PrefixIteratorOnRemoval> Iterator for PrefixIterator<T, OnRemoval> {
1089	type Item = T;
1090
1091	fn next(&mut self) -> Option<Self::Item> {
1092		loop {
1093			let maybe_next = pezsp_io::storage::next_key(&self.previous_key)
1094				.filter(|n| n.starts_with(&self.prefix));
1095			break match maybe_next {
1096				Some(next) => {
1097					self.previous_key = next;
1098					let raw_value = match unhashed::get_raw(&self.previous_key) {
1099						Some(raw_value) => raw_value,
1100						None => {
1101							log::error!(
1102								"next_key returned a key with no value at {:?}",
1103								self.previous_key,
1104							);
1105							continue;
1106						},
1107					};
1108					if self.drain {
1109						unhashed::kill(&self.previous_key);
1110						OnRemoval::on_removal(&self.previous_key, &raw_value);
1111					}
1112					let raw_key_without_prefix = &self.previous_key[self.prefix.len()..];
1113					let item = match (self.closure)(raw_key_without_prefix, &raw_value[..]) {
1114						Ok(item) => item,
1115						Err(e) => {
1116							log::error!(
1117								"(key, value) failed to decode at {:?}: {:?}",
1118								self.previous_key,
1119								e,
1120							);
1121							continue;
1122						},
1123					};
1124
1125					Some(item)
1126				},
1127				None => None,
1128			};
1129		}
1130	}
1131}
1132
1133/// Iterate over a prefix and decode raw_key into `T`.
1134///
1135/// If any decoding fails it skips it and continues to the next key.
1136pub struct KeyPrefixIterator<T> {
1137	prefix: Vec<u8>,
1138	previous_key: Vec<u8>,
1139	/// If true then value are removed while iterating
1140	drain: bool,
1141	/// Function that take `raw_key_without_prefix` and decode `T`.
1142	/// `raw_key_without_prefix` is the raw storage key without the prefix iterated on.
1143	closure: fn(&[u8]) -> Result<T, codec::Error>,
1144}
1145
1146impl<T> KeyPrefixIterator<T> {
1147	/// Creates a new `KeyPrefixIterator`, iterating after `previous_key` and filtering out keys
1148	/// that are not prefixed with `prefix`.
1149	///
1150	/// A `decode_fn` function must also be supplied, and it takes in a `&[u8]` parameter, returning
1151	/// a `Result` containing the decoded key type `T` if successful, and a `codec::Error` on
1152	/// failure. The `&[u8]` argument represents the raw, undecoded key without the prefix of the
1153	/// current item.
1154	pub fn new(
1155		prefix: Vec<u8>,
1156		previous_key: Vec<u8>,
1157		decode_fn: fn(&[u8]) -> Result<T, codec::Error>,
1158	) -> Self {
1159		KeyPrefixIterator { prefix, previous_key, drain: false, closure: decode_fn }
1160	}
1161
1162	/// Get the last key that has been iterated upon and return it.
1163	pub fn last_raw_key(&self) -> &[u8] {
1164		&self.previous_key
1165	}
1166
1167	/// Get the prefix that is being iterated upon for this iterator and return it.
1168	pub fn prefix(&self) -> &[u8] {
1169		&self.prefix
1170	}
1171
1172	/// Set the key that the iterator should start iterating after.
1173	pub fn set_last_raw_key(&mut self, previous_key: Vec<u8>) {
1174		self.previous_key = previous_key;
1175	}
1176
1177	/// Mutate this iterator into a draining iterator; items iterated are removed from storage.
1178	pub fn drain(mut self) -> Self {
1179		self.drain = true;
1180		self
1181	}
1182}
1183
1184impl<T> Iterator for KeyPrefixIterator<T> {
1185	type Item = T;
1186
1187	fn next(&mut self) -> Option<Self::Item> {
1188		loop {
1189			let maybe_next = pezsp_io::storage::next_key(&self.previous_key)
1190				.filter(|n| n.starts_with(&self.prefix));
1191
1192			if let Some(next) = maybe_next {
1193				self.previous_key = next;
1194				if self.drain {
1195					unhashed::kill(&self.previous_key);
1196				}
1197				let raw_key_without_prefix = &self.previous_key[self.prefix.len()..];
1198
1199				match (self.closure)(raw_key_without_prefix) {
1200					Ok(item) => return Some(item),
1201					Err(e) => {
1202						log::error!("key failed to decode at {:?}: {:?}", self.previous_key, e);
1203						continue;
1204					},
1205				}
1206			}
1207
1208			return None;
1209		}
1210	}
1211}
1212
1213/// Iterate over a prefix of a child trie and decode raw_key and raw_value into `T`.
1214///
1215/// If any decoding fails it skips the key and continues to the next one.
1216pub struct ChildTriePrefixIterator<T> {
1217	/// The prefix iterated on
1218	prefix: Vec<u8>,
1219	/// child info for child trie
1220	child_info: ChildInfo,
1221	/// The last key iterated on
1222	previous_key: Vec<u8>,
1223	/// If true then values are removed while iterating
1224	drain: bool,
1225	/// Whether or not we should fetch the previous key
1226	fetch_previous_key: bool,
1227	/// Function that takes `(raw_key_without_prefix, raw_value)` and decode `T`.
1228	/// `raw_key_without_prefix` is the raw storage key without the prefix iterated on.
1229	closure: fn(&[u8], &[u8]) -> Result<T, codec::Error>,
1230}
1231
1232impl<T> ChildTriePrefixIterator<T> {
1233	/// Mutate this iterator into a draining iterator; items iterated are removed from storage.
1234	pub fn drain(mut self) -> Self {
1235		self.drain = true;
1236		self
1237	}
1238}
1239
1240impl<T: Decode + Sized> ChildTriePrefixIterator<(Vec<u8>, T)> {
1241	/// Construct iterator to iterate over child trie items in `child_info` with the prefix
1242	/// `prefix`.
1243	///
1244	/// NOTE: Iterator with [`Self::drain`] will remove any value who failed to decode
1245	pub fn with_prefix(child_info: &ChildInfo, prefix: &[u8]) -> Self {
1246		let prefix = prefix.to_vec();
1247		let previous_key = prefix.clone();
1248		let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
1249			let value = T::decode(&mut raw_value)?;
1250			Ok((raw_key_without_prefix.to_vec(), value))
1251		};
1252
1253		Self {
1254			prefix,
1255			child_info: child_info.clone(),
1256			previous_key,
1257			drain: false,
1258			fetch_previous_key: true,
1259			closure,
1260		}
1261	}
1262}
1263
1264impl<K: Decode + Sized, T: Decode + Sized> ChildTriePrefixIterator<(K, T)> {
1265	/// Construct iterator to iterate over child trie items in `child_info` with the prefix
1266	/// `prefix`.
1267	///
1268	/// NOTE: Iterator with [`Self::drain`] will remove any key or value who failed to decode
1269	pub fn with_prefix_over_key<H: ReversibleStorageHasher>(
1270		child_info: &ChildInfo,
1271		prefix: &[u8],
1272	) -> Self {
1273		let prefix = prefix.to_vec();
1274		let previous_key = prefix.clone();
1275		let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
1276			let mut key_material = H::reverse(raw_key_without_prefix);
1277			let key = K::decode(&mut key_material)?;
1278			let value = T::decode(&mut raw_value)?;
1279			Ok((key, value))
1280		};
1281
1282		Self {
1283			prefix,
1284			child_info: child_info.clone(),
1285			previous_key,
1286			drain: false,
1287			fetch_previous_key: true,
1288			closure,
1289		}
1290	}
1291}
1292
1293impl<T> Iterator for ChildTriePrefixIterator<T> {
1294	type Item = T;
1295
1296	fn next(&mut self) -> Option<Self::Item> {
1297		loop {
1298			let maybe_next = if self.fetch_previous_key {
1299				self.fetch_previous_key = false;
1300				Some(self.previous_key.clone())
1301			} else {
1302				pezsp_io::default_child_storage::next_key(
1303					self.child_info.storage_key(),
1304					&self.previous_key,
1305				)
1306				.filter(|n| n.starts_with(&self.prefix))
1307			};
1308			break match maybe_next {
1309				Some(next) => {
1310					self.previous_key = next;
1311					let raw_value = match child::get_raw(&self.child_info, &self.previous_key) {
1312						Some(raw_value) => raw_value,
1313						None => {
1314							log::error!(
1315								"next_key returned a key with no value at {:?}",
1316								self.previous_key,
1317							);
1318							continue;
1319						},
1320					};
1321					if self.drain {
1322						child::kill(&self.child_info, &self.previous_key)
1323					}
1324					let raw_key_without_prefix = &self.previous_key[self.prefix.len()..];
1325					let item = match (self.closure)(raw_key_without_prefix, &raw_value[..]) {
1326						Ok(item) => item,
1327						Err(e) => {
1328							log::error!(
1329								"(key, value) failed to decode at {:?}: {:?}",
1330								self.previous_key,
1331								e,
1332							);
1333							continue;
1334						},
1335					};
1336
1337					Some(item)
1338				},
1339				None => None,
1340			};
1341		}
1342	}
1343}
1344
1345/// Trait for storage types that store all its value after a unique prefix.
1346pub trait StoragePrefixedContainer {
1347	/// Pezpallet prefix. Used for generating final key.
1348	fn pezpallet_prefix() -> &'static [u8];
1349
1350	/// Storage prefix. Used for generating final key.
1351	fn storage_prefix() -> &'static [u8];
1352
1353	/// Final full prefix that prefixes all keys.
1354	fn final_prefix() -> [u8; 32] {
1355		crate::storage::storage_prefix(Self::pezpallet_prefix(), Self::storage_prefix())
1356	}
1357}
1358
1359/// Trait for maps that store all its value after a unique prefix.
1360///
1361/// By default the final prefix is:
1362/// ```nocompile
1363/// Twox128(pezpallet_prefix) ++ Twox128(storage_prefix)
1364/// ```
1365pub trait StoragePrefixedMap<Value: FullCodec> {
1366	/// Pezpallet prefix. Used for generating final key.
1367	fn pezpallet_prefix() -> &'static [u8]; // TODO move to StoragePrefixedContainer
1368
1369	/// Storage prefix. Used for generating final key.
1370	fn storage_prefix() -> &'static [u8];
1371
1372	/// Final full prefix that prefixes all keys.
1373	fn final_prefix() -> [u8; 32] {
1374		crate::storage::storage_prefix(Self::pezpallet_prefix(), Self::storage_prefix())
1375	}
1376
1377	/// Remove all values in the overlay and up to `limit` in the backend.
1378	///
1379	/// All values in the client overlay will be deleted, if there is some `limit` then up to
1380	/// `limit` values are deleted from the client backend, if `limit` is none then all values in
1381	/// the client backend are deleted.
1382	///
1383	/// # Note
1384	///
1385	/// Calling this multiple times per block with a `limit` set leads always to the same keys being
1386	/// removed and the same result being returned. This happens because the keys to delete in the
1387	/// overlay are not taken into account when deleting keys in the backend.
1388	#[deprecated = "Use `clear` instead"]
1389	fn remove_all(limit: Option<u32>) -> pezsp_io::KillStorageResult {
1390		unhashed::clear_prefix(&Self::final_prefix(), limit, None).into()
1391	}
1392
1393	/// Attempt to remove all items from the map.
1394	///
1395	/// Returns [`MultiRemovalResults`](pezsp_io::MultiRemovalResults) to inform about the result.
1396	/// Once the resultant `maybe_cursor` field is `None`, then no further items remain to be
1397	/// deleted.
1398	///
1399	/// NOTE: After the initial call for any given map, it is important that no further items
1400	/// are inserted into the map. If so, then the map may not be empty when the resultant
1401	/// `maybe_cursor` is `None`.
1402	///
1403	/// # Limit
1404	///
1405	/// A `limit` must always be provided through in order to cap the maximum
1406	/// amount of deletions done in a single call. This is one fewer than the
1407	/// maximum number of backend iterations which may be done by this operation and as such
1408	/// represents the maximum number of backend deletions which may happen. A `limit` of zero
1409	/// implies that no keys will be deleted, though there may be a single iteration done.
1410	///
1411	/// # Cursor
1412	///
1413	/// A *cursor* may be passed in to this operation with `maybe_cursor`. `None` should only be
1414	/// passed once (in the initial call) for any given storage map. Subsequent calls
1415	/// operating on the same map should always pass `Some`, and this should be equal to the
1416	/// previous call result's `maybe_cursor` field.
1417	fn clear(limit: u32, maybe_cursor: Option<&[u8]>) -> pezsp_io::MultiRemovalResults {
1418		unhashed::clear_prefix(&Self::final_prefix(), Some(limit), maybe_cursor)
1419	}
1420
1421	/// Iter over all value of the storage.
1422	///
1423	/// NOTE: If a value failed to decode because storage is corrupted then it is skipped.
1424	fn iter_values() -> PrefixIterator<Value> {
1425		let prefix = Self::final_prefix();
1426		PrefixIterator {
1427			prefix: prefix.to_vec(),
1428			previous_key: prefix.to_vec(),
1429			drain: false,
1430			closure: |_raw_key, mut raw_value| Value::decode(&mut raw_value),
1431			phantom: Default::default(),
1432		}
1433	}
1434
1435	/// Translate the values of all elements by a function `f`, in the map in no particular order.
1436	/// By returning `None` from `f` for an element, you'll remove it from the map.
1437	///
1438	/// NOTE: If a value fail to decode because storage is corrupted then it is skipped.
1439	///
1440	/// # Warning
1441	///
1442	/// This function must be used with care, before being updated the storage still contains the
1443	/// old type, thus other calls (such as `get`) will fail at decoding it.
1444	///
1445	/// # Usage
1446	///
1447	/// This would typically be called inside the module implementation of on_runtime_upgrade.
1448	fn translate_values<OldValue: Decode, F: FnMut(OldValue) -> Option<Value>>(mut f: F) {
1449		let prefix = Self::final_prefix();
1450		let mut previous_key = prefix.clone().to_vec();
1451		while let Some(next) =
1452			pezsp_io::storage::next_key(&previous_key).filter(|n| n.starts_with(&prefix))
1453		{
1454			previous_key = next;
1455			let maybe_value = unhashed::get::<OldValue>(&previous_key);
1456			match maybe_value {
1457				Some(value) => match f(value) {
1458					Some(new) => unhashed::put::<Value>(&previous_key, &new),
1459					None => unhashed::kill(&previous_key),
1460				},
1461				None => {
1462					log::error!("old key failed to decode at {:?}", previous_key);
1463					continue;
1464				},
1465			}
1466		}
1467	}
1468}
1469
1470/// Marker trait that will be implemented for types that support the `storage::append` api.
1471///
1472/// This trait is sealed.
1473pub trait StorageAppend<Item: Encode>: private::Sealed {}
1474
1475/// It is expected that the length is at the beginning of the encoded object
1476/// and that the length is a `Compact<u32>`.
1477///
1478/// This trait is sealed.
1479pub trait StorageDecodeLength: private::Sealed + codec::DecodeLength {
1480	/// Decode the length of the storage value at `key`.
1481	///
1482	/// This function assumes that the length is at the beginning of the encoded object
1483	/// and is a `Compact<u32>`.
1484	///
1485	/// Returns `None` if the storage value does not exist or the decoding failed.
1486	fn decode_len(key: &[u8]) -> Option<usize> {
1487		// `Compact<u32>` is 5 bytes in maximum.
1488		let mut data = [0u8; 5];
1489		let len = pezsp_io::storage::read(key, &mut data, 0)?;
1490		let len = data.len().min(len as usize);
1491		<Self as codec::DecodeLength>::len(&data[..len]).ok()
1492	}
1493}
1494
1495/// It is expected that the length is at the beginning of the encoded object and that the length is
1496/// a `Compact<u32>`.
1497///
1498/// # Note
1499/// The length returned by this trait is not deduplicated, i.e. it is the length of the underlying
1500/// stored Vec.
1501///
1502/// This trait is sealed.
1503pub trait StorageDecodeNonDedupLength: private::Sealed + codec::DecodeLength {
1504	/// Decode the length of the storage value at `key`.
1505	///
1506	/// This function assumes that the length is at the beginning of the encoded object and is a
1507	/// `Compact<u32>`.
1508	///
1509	/// Returns `None` if the storage value does not exist or the decoding failed.
1510	fn decode_non_dedup_len(key: &[u8]) -> Option<usize> {
1511		let mut data = [0u8; 5];
1512		let len = pezsp_io::storage::read(key, &mut data, 0)?;
1513		let len = data.len().min(len as usize);
1514		<Self as codec::DecodeLength>::len(&data[..len]).ok()
1515	}
1516}
1517
1518/// Provides `Sealed` trait to prevent implementing trait `StorageAppend` & `StorageDecodeLength`
1519/// & `EncodeLikeTuple` outside of this crate.
1520mod private {
1521	use super::*;
1522	use bounded_vec::BoundedVec;
1523	use weak_bounded_vec::WeakBoundedVec;
1524
1525	pub trait Sealed {}
1526
1527	impl<T: Encode> Sealed for Vec<T> {}
1528	impl Sealed for Digest {}
1529	impl<T, S> Sealed for BoundedVec<T, S> {}
1530	impl<T, S> Sealed for WeakBoundedVec<T, S> {}
1531	impl<K, V, S> Sealed for bounded_btree_map::BoundedBTreeMap<K, V, S> {}
1532	impl<T, S> Sealed for bounded_btree_set::BoundedBTreeSet<T, S> {}
1533	impl<T: Encode> Sealed for BTreeSet<T> {}
1534	impl<'a, T: EncodeLike<U>, U: Encode> Sealed for codec::Ref<'a, T, U> {}
1535
1536	macro_rules! impl_sealed_for_tuple {
1537		($($elem:ident),+) => {
1538			paste::paste! {
1539				impl<$($elem: Encode,)+> Sealed for ($($elem,)+) {}
1540				impl<$($elem: Encode,)+> Sealed for &($($elem,)+) {}
1541			}
1542		};
1543	}
1544
1545	impl_sealed_for_tuple!(A);
1546	impl_sealed_for_tuple!(A, B);
1547	impl_sealed_for_tuple!(A, B, C);
1548	impl_sealed_for_tuple!(A, B, C, D);
1549	impl_sealed_for_tuple!(A, B, C, D, E);
1550	impl_sealed_for_tuple!(A, B, C, D, E, F);
1551	impl_sealed_for_tuple!(A, B, C, D, E, F, G);
1552	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H);
1553	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I);
1554	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J);
1555	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
1556	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
1557	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
1558	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O);
1559	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O, P);
1560	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O, P, Q);
1561	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O, P, Q, R);
1562}
1563
1564impl<T: Encode> StorageAppend<T> for Vec<T> {}
1565impl<T: Encode> StorageDecodeLength for Vec<T> {}
1566
1567impl<T: Encode> StorageAppend<T> for BTreeSet<T> {}
1568impl<T: Encode> StorageDecodeNonDedupLength for BTreeSet<T> {}
1569
1570// Blanket implementation StorageDecodeNonDedupLength for all types that are StorageDecodeLength.
1571impl<T: StorageDecodeLength> StorageDecodeNonDedupLength for T {
1572	fn decode_non_dedup_len(key: &[u8]) -> Option<usize> {
1573		T::decode_len(key)
1574	}
1575}
1576
1577/// We abuse the fact that SCALE does not put any marker into the encoding, i.e. we only encode the
1578/// internal vec and we can append to this vec. We have a test that ensures that if the `Digest`
1579/// format ever changes, we need to remove this here.
1580impl StorageAppend<DigestItem> for Digest {}
1581
1582/// Marker trait that is implemented for types that support the `storage::append` api with a limit
1583/// on the number of element.
1584///
1585/// This trait is sealed.
1586pub trait StorageTryAppend<Item>: StorageDecodeLength + private::Sealed {
1587	fn bound() -> usize;
1588}
1589
1590/// Storage value that is capable of [`StorageTryAppend`].
1591pub trait TryAppendValue<T: StorageTryAppend<I>, I: Encode> {
1592	/// Try and append the `item` into the storage item.
1593	///
1594	/// This might fail if bounds are not respected.
1595	fn try_append<LikeI: EncodeLike<I>>(item: LikeI) -> Result<(), ()>;
1596}
1597
1598impl<T, I, StorageValueT> TryAppendValue<T, I> for StorageValueT
1599where
1600	I: Encode,
1601	T: FullCodec + StorageTryAppend<I>,
1602	StorageValueT: generator::StorageValue<T>,
1603{
1604	fn try_append<LikeI: EncodeLike<I>>(item: LikeI) -> Result<(), ()> {
1605		let bound = T::bound();
1606		let current = Self::decode_len().unwrap_or_default();
1607		if current < bound {
1608			// NOTE: we cannot reuse the implementation for `Vec<T>` here because we never want to
1609			// mark `BoundedVec<T, S>` as `StorageAppend`.
1610			let key = Self::storage_value_final_key();
1611			pezsp_io::storage::append(&key, item.encode());
1612			Ok(())
1613		} else {
1614			Err(())
1615		}
1616	}
1617}
1618
1619/// Storage map that is capable of [`StorageTryAppend`].
1620pub trait TryAppendMap<K: Encode, T: StorageTryAppend<I>, I: Encode> {
1621	/// Try and append the `item` into the storage map at the given `key`.
1622	///
1623	/// This might fail if bounds are not respected.
1624	fn try_append<LikeK: EncodeLike<K> + Clone, LikeI: EncodeLike<I>>(
1625		key: LikeK,
1626		item: LikeI,
1627	) -> Result<(), ()>;
1628}
1629
1630impl<K, T, I, StorageMapT> TryAppendMap<K, T, I> for StorageMapT
1631where
1632	K: FullCodec,
1633	T: FullCodec + StorageTryAppend<I>,
1634	I: Encode,
1635	StorageMapT: generator::StorageMap<K, T>,
1636{
1637	fn try_append<LikeK: EncodeLike<K> + Clone, LikeI: EncodeLike<I>>(
1638		key: LikeK,
1639		item: LikeI,
1640	) -> Result<(), ()> {
1641		let bound = T::bound();
1642		let current = Self::decode_len(key.clone()).unwrap_or_default();
1643		if current < bound {
1644			let key = Self::storage_map_final_key(key);
1645			pezsp_io::storage::append(&key, item.encode());
1646			Ok(())
1647		} else {
1648			Err(())
1649		}
1650	}
1651}
1652
1653/// Storage double map that is capable of [`StorageTryAppend`].
1654pub trait TryAppendDoubleMap<K1: Encode, K2: Encode, T: StorageTryAppend<I>, I: Encode> {
1655	/// Try and append the `item` into the storage double map at the given `key`.
1656	///
1657	/// This might fail if bounds are not respected.
1658	fn try_append<
1659		LikeK1: EncodeLike<K1> + Clone,
1660		LikeK2: EncodeLike<K2> + Clone,
1661		LikeI: EncodeLike<I>,
1662	>(
1663		key1: LikeK1,
1664		key2: LikeK2,
1665		item: LikeI,
1666	) -> Result<(), ()>;
1667}
1668
1669impl<K1, K2, T, I, StorageDoubleMapT> TryAppendDoubleMap<K1, K2, T, I> for StorageDoubleMapT
1670where
1671	K1: FullCodec,
1672	K2: FullCodec,
1673	T: FullCodec + StorageTryAppend<I>,
1674	I: Encode,
1675	StorageDoubleMapT: generator::StorageDoubleMap<K1, K2, T>,
1676{
1677	fn try_append<
1678		LikeK1: EncodeLike<K1> + Clone,
1679		LikeK2: EncodeLike<K2> + Clone,
1680		LikeI: EncodeLike<I>,
1681	>(
1682		key1: LikeK1,
1683		key2: LikeK2,
1684		item: LikeI,
1685	) -> Result<(), ()> {
1686		let bound = T::bound();
1687		let current = Self::decode_len(key1.clone(), key2.clone()).unwrap_or_default();
1688		if current < bound {
1689			let double_map_key = Self::storage_double_map_final_key(key1, key2);
1690			pezsp_io::storage::append(&double_map_key, item.encode());
1691			Ok(())
1692		} else {
1693			Err(())
1694		}
1695	}
1696}
1697
1698/// Storage N map that is capable of [`StorageTryAppend`].
1699pub trait TryAppendNMap<K: KeyGenerator, T: StorageTryAppend<I>, I: Encode> {
1700	/// Try and append the `item` into the storage N map at the given `key`.
1701	///
1702	/// This might fail if bounds are not respected.
1703	fn try_append<
1704		LikeK: EncodeLikeTuple<K::KArg> + TupleToEncodedIter + Clone,
1705		LikeI: EncodeLike<I>,
1706	>(
1707		key: LikeK,
1708		item: LikeI,
1709	) -> Result<(), ()>;
1710}
1711
1712impl<K, T, I, StorageNMapT> TryAppendNMap<K, T, I> for StorageNMapT
1713where
1714	K: KeyGenerator,
1715	T: FullCodec + StorageTryAppend<I>,
1716	I: Encode,
1717	StorageNMapT: generator::StorageNMap<K, T>,
1718{
1719	fn try_append<
1720		LikeK: EncodeLikeTuple<K::KArg> + TupleToEncodedIter + Clone,
1721		LikeI: EncodeLike<I>,
1722	>(
1723		key: LikeK,
1724		item: LikeI,
1725	) -> Result<(), ()> {
1726		let bound = T::bound();
1727		let current = Self::decode_len(key.clone()).unwrap_or_default();
1728		if current < bound {
1729			let key = Self::storage_n_map_final_key::<K, _>(key);
1730			pezsp_io::storage::append(&key, item.encode());
1731			Ok(())
1732		} else {
1733			Err(())
1734		}
1735	}
1736}
1737
1738/// Returns the storage prefix for a specific pezpallet name and storage name.
1739///
1740/// The storage prefix is `concat(twox_128(pezpallet_name), twox_128(storage_name))`.
1741pub fn storage_prefix(pezpallet_name: &[u8], storage_name: &[u8]) -> [u8; 32] {
1742	let pezpallet_hash = pezsp_io::hashing::twox_128(pezpallet_name);
1743	let storage_hash = pezsp_io::hashing::twox_128(storage_name);
1744
1745	let mut final_key = [0u8; 32];
1746	final_key[..16].copy_from_slice(&pezpallet_hash);
1747	final_key[16..].copy_from_slice(&storage_hash);
1748
1749	final_key
1750}
1751
1752#[cfg(test)]
1753mod test {
1754	use super::*;
1755	use crate::{assert_ok, hash::Identity, pezpallet_prelude::NMapKey, Twox128};
1756	use bounded_vec::BoundedVec;
1757	use generator::StorageValue as _;
1758	use pezframe_support::traits::ConstU32;
1759	use pezsp_crypto_hashing::twox_128;
1760	use pezsp_io::TestExternalities;
1761	use weak_bounded_vec::WeakBoundedVec;
1762
1763	#[test]
1764	fn prefixed_map_works() {
1765		TestExternalities::default().execute_with(|| {
1766			struct MyStorage;
1767			impl StoragePrefixedMap<u64> for MyStorage {
1768				fn pezpallet_prefix() -> &'static [u8] {
1769					b"MyModule"
1770				}
1771
1772				fn storage_prefix() -> &'static [u8] {
1773					b"MyStorage"
1774				}
1775			}
1776
1777			let key_before = {
1778				let mut k = MyStorage::final_prefix();
1779				let last = k.iter_mut().last().unwrap();
1780				*last = last.checked_sub(1).unwrap();
1781				k
1782			};
1783			let key_after = {
1784				let mut k = MyStorage::final_prefix();
1785				let last = k.iter_mut().last().unwrap();
1786				*last = last.checked_add(1).unwrap();
1787				k
1788			};
1789
1790			unhashed::put(&key_before[..], &32u64);
1791			unhashed::put(&key_after[..], &33u64);
1792
1793			let k = [twox_128(b"MyModule"), twox_128(b"MyStorage")].concat();
1794			assert_eq!(MyStorage::final_prefix().to_vec(), k);
1795
1796			// test iteration
1797			assert!(MyStorage::iter_values().collect::<Vec<_>>().is_empty());
1798
1799			unhashed::put(&[&k[..], &vec![1][..]].concat(), &1u64);
1800			unhashed::put(&[&k[..], &vec![1, 1][..]].concat(), &2u64);
1801			unhashed::put(&[&k[..], &vec![8][..]].concat(), &3u64);
1802			unhashed::put(&[&k[..], &vec![10][..]].concat(), &4u64);
1803
1804			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2, 3, 4]);
1805
1806			// test removal
1807			let _ = MyStorage::clear(u32::max_value(), None);
1808			assert!(MyStorage::iter_values().collect::<Vec<_>>().is_empty());
1809
1810			// test migration
1811			unhashed::put(&[&k[..], &vec![1][..]].concat(), &1u32);
1812			unhashed::put(&[&k[..], &vec![8][..]].concat(), &2u32);
1813
1814			assert!(MyStorage::iter_values().collect::<Vec<_>>().is_empty());
1815			MyStorage::translate_values(|v: u32| Some(v as u64));
1816			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2]);
1817			let _ = MyStorage::clear(u32::max_value(), None);
1818
1819			// test migration 2
1820			unhashed::put(&[&k[..], &vec![1][..]].concat(), &1u128);
1821			unhashed::put(&[&k[..], &vec![1, 1][..]].concat(), &2u64);
1822			unhashed::put(&[&k[..], &vec![8][..]].concat(), &3u128);
1823			unhashed::put(&[&k[..], &vec![10][..]].concat(), &4u32);
1824
1825			// (contains some value that successfully decoded to u64)
1826			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2, 3]);
1827			MyStorage::translate_values(|v: u128| Some(v as u64));
1828			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2, 3]);
1829			let _ = MyStorage::clear(u32::max_value(), None);
1830
1831			// test that other values are not modified.
1832			assert_eq!(unhashed::get(&key_before[..]), Some(32u64));
1833			assert_eq!(unhashed::get(&key_after[..]), Some(33u64));
1834		});
1835	}
1836
1837	// This test ensures that the Digest encoding does not change without being noticed.
1838	#[test]
1839	fn digest_storage_append_works_as_expected() {
1840		TestExternalities::default().execute_with(|| {
1841			struct Storage;
1842			impl generator::StorageValue<Digest> for Storage {
1843				type Query = Digest;
1844
1845				fn pezpallet_prefix() -> &'static [u8] {
1846					b"MyModule"
1847				}
1848
1849				fn storage_prefix() -> &'static [u8] {
1850					b"Storage"
1851				}
1852
1853				fn from_optional_value_to_query(v: Option<Digest>) -> Self::Query {
1854					v.unwrap()
1855				}
1856
1857				fn from_query_to_optional_value(v: Self::Query) -> Option<Digest> {
1858					Some(v)
1859				}
1860
1861				fn storage_value_final_key() -> [u8; 32] {
1862					storage_prefix(Self::pezpallet_prefix(), Self::storage_prefix())
1863				}
1864			}
1865
1866			Storage::append(DigestItem::Other(Vec::new()));
1867
1868			let value = unhashed::get_raw(&Storage::storage_value_final_key()).unwrap();
1869
1870			let expected = Digest { logs: vec![DigestItem::Other(Vec::new())] };
1871			assert_eq!(Digest::decode(&mut &value[..]).unwrap(), expected);
1872		});
1873	}
1874
1875	#[test]
1876	fn key_prefix_iterator_works() {
1877		TestExternalities::default().execute_with(|| {
1878			use crate::{hash::Twox64Concat, storage::generator::StorageMap};
1879			struct MyStorageMap;
1880			impl StorageMap<u64, u64> for MyStorageMap {
1881				type Query = u64;
1882				type Hasher = Twox64Concat;
1883
1884				fn pezpallet_prefix() -> &'static [u8] {
1885					b"MyModule"
1886				}
1887
1888				fn storage_prefix() -> &'static [u8] {
1889					b"MyStorageMap"
1890				}
1891
1892				fn prefix_hash() -> [u8; 32] {
1893					storage_prefix(Self::pezpallet_prefix(), Self::storage_prefix())
1894				}
1895
1896				fn from_optional_value_to_query(v: Option<u64>) -> Self::Query {
1897					v.unwrap_or_default()
1898				}
1899
1900				fn from_query_to_optional_value(v: Self::Query) -> Option<u64> {
1901					Some(v)
1902				}
1903			}
1904
1905			let k = [twox_128(b"MyModule"), twox_128(b"MyStorageMap")].concat();
1906			assert_eq!(MyStorageMap::prefix_hash().to_vec(), k);
1907
1908			// empty to start
1909			assert!(MyStorageMap::iter_keys().collect::<Vec<_>>().is_empty());
1910
1911			MyStorageMap::insert(1, 10);
1912			MyStorageMap::insert(2, 20);
1913			MyStorageMap::insert(3, 30);
1914			MyStorageMap::insert(4, 40);
1915
1916			// just looking
1917			let mut keys = MyStorageMap::iter_keys().collect::<Vec<_>>();
1918			keys.sort();
1919			assert_eq!(keys, vec![1, 2, 3, 4]);
1920
1921			// draining the keys and values
1922			let mut drained_keys = MyStorageMap::iter_keys().drain().collect::<Vec<_>>();
1923			drained_keys.sort();
1924			assert_eq!(drained_keys, vec![1, 2, 3, 4]);
1925
1926			// empty again
1927			assert!(MyStorageMap::iter_keys().collect::<Vec<_>>().is_empty());
1928		});
1929	}
1930
1931	#[test]
1932	fn prefix_iterator_pagination_works() {
1933		TestExternalities::default().execute_with(|| {
1934			use crate::{hash::Identity, storage::generator::map::StorageMap};
1935			#[crate::storage_alias]
1936			type MyStorageMap = StorageMap<MyModule, Identity, u64, u64>;
1937
1938			MyStorageMap::insert(1, 10);
1939			MyStorageMap::insert(2, 20);
1940			MyStorageMap::insert(3, 30);
1941			MyStorageMap::insert(4, 40);
1942			MyStorageMap::insert(5, 50);
1943			MyStorageMap::insert(6, 60);
1944			MyStorageMap::insert(7, 70);
1945			MyStorageMap::insert(8, 80);
1946			MyStorageMap::insert(9, 90);
1947			MyStorageMap::insert(10, 100);
1948
1949			let op = |(_, v)| v / 10;
1950			let mut final_vec = vec![];
1951			let mut iter = MyStorageMap::iter();
1952
1953			let elem = iter.next().unwrap();
1954			assert_eq!(elem, (1, 10));
1955			final_vec.push(op(elem));
1956
1957			let elem = iter.next().unwrap();
1958			assert_eq!(elem, (2, 20));
1959			final_vec.push(op(elem));
1960
1961			let stored_key = iter.last_raw_key().to_owned();
1962			assert_eq!(stored_key, MyStorageMap::storage_map_final_key(2));
1963
1964			let mut iter = MyStorageMap::iter_from(stored_key.clone());
1965
1966			final_vec.push(op(iter.next().unwrap()));
1967			final_vec.push(op(iter.next().unwrap()));
1968			final_vec.push(op(iter.next().unwrap()));
1969
1970			assert_eq!(final_vec, vec![1, 2, 3, 4, 5]);
1971
1972			let mut iter = PrefixIterator::<_>::new(
1973				iter.prefix().to_vec(),
1974				stored_key,
1975				|mut raw_key_without_prefix, mut raw_value| {
1976					let key = u64::decode(&mut raw_key_without_prefix)?;
1977					Ok((key, u64::decode(&mut raw_value)?))
1978				},
1979			);
1980			let previous_key = MyStorageMap::storage_map_final_key(5);
1981			iter.set_last_raw_key(previous_key);
1982
1983			let remaining = iter.map(op).collect::<Vec<_>>();
1984			assert_eq!(remaining.len(), 5);
1985			assert_eq!(remaining, vec![6, 7, 8, 9, 10]);
1986
1987			final_vec.extend_from_slice(&remaining);
1988
1989			assert_eq!(final_vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1990		});
1991	}
1992
1993	#[test]
1994	fn child_trie_prefixed_map_works() {
1995		TestExternalities::default().execute_with(|| {
1996			let child_info_a = child::ChildInfo::new_default(b"a");
1997			child::put(&child_info_a, &[1, 2, 3], &8u16);
1998			child::put(&child_info_a, &[2], &8u16);
1999			child::put(&child_info_a, &[2, 1, 3], &8u8);
2000			child::put(&child_info_a, &[2, 2, 3], &8u16);
2001			child::put(&child_info_a, &[3], &8u16);
2002
2003			assert_eq!(
2004				ChildTriePrefixIterator::with_prefix(&child_info_a, &[2])
2005					.collect::<Vec<(Vec<u8>, u16)>>(),
2006				vec![(vec![], 8), (vec![2, 3], 8),],
2007			);
2008
2009			assert_eq!(
2010				ChildTriePrefixIterator::with_prefix(&child_info_a, &[2])
2011					.drain()
2012					.collect::<Vec<(Vec<u8>, u16)>>(),
2013				vec![(vec![], 8), (vec![2, 3], 8),],
2014			);
2015
2016			// The only remaining is the ones outside prefix
2017			assert_eq!(
2018				ChildTriePrefixIterator::with_prefix(&child_info_a, &[])
2019					.collect::<Vec<(Vec<u8>, u8)>>(),
2020				vec![(vec![1, 2, 3], 8), (vec![3], 8),],
2021			);
2022
2023			child::put(&child_info_a, &[1, 2, 3], &8u16);
2024			child::put(&child_info_a, &[2], &8u16);
2025			child::put(&child_info_a, &[2, 1, 3], &8u8);
2026			child::put(&child_info_a, &[2, 2, 3], &8u16);
2027			child::put(&child_info_a, &[3], &8u16);
2028
2029			assert_eq!(
2030				ChildTriePrefixIterator::with_prefix_over_key::<Identity>(&child_info_a, &[2])
2031					.collect::<Vec<(u16, u16)>>(),
2032				vec![(u16::decode(&mut &[2, 3][..]).unwrap(), 8),],
2033			);
2034
2035			assert_eq!(
2036				ChildTriePrefixIterator::with_prefix_over_key::<Identity>(&child_info_a, &[2])
2037					.drain()
2038					.collect::<Vec<(u16, u16)>>(),
2039				vec![(u16::decode(&mut &[2, 3][..]).unwrap(), 8),],
2040			);
2041
2042			// The only remaining is the ones outside prefix
2043			assert_eq!(
2044				ChildTriePrefixIterator::with_prefix(&child_info_a, &[])
2045					.collect::<Vec<(Vec<u8>, u8)>>(),
2046				vec![(vec![1, 2, 3], 8), (vec![3], 8),],
2047			);
2048		});
2049	}
2050
2051	#[crate::storage_alias]
2052	type Foo = StorageValue<Prefix, WeakBoundedVec<u32, ConstU32<7>>>;
2053	#[crate::storage_alias]
2054	type FooMap = StorageMap<Prefix, Twox128, u32, BoundedVec<u32, ConstU32<7>>>;
2055	#[crate::storage_alias]
2056	type FooDoubleMap =
2057		StorageDoubleMap<Prefix, Twox128, u32, Twox128, u32, BoundedVec<u32, ConstU32<7>>>;
2058	#[crate::storage_alias]
2059	type FooTripleMap = StorageNMap<
2060		Prefix,
2061		(NMapKey<Twox128, u32>, NMapKey<Twox128, u32>, NMapKey<Twox128, u32>),
2062		u64,
2063	>;
2064	#[crate::storage_alias]
2065	type FooQuadMap = StorageNMap<
2066		Prefix,
2067		(
2068			NMapKey<Twox128, u32>,
2069			NMapKey<Twox128, u32>,
2070			NMapKey<Twox128, u32>,
2071			NMapKey<Twox128, u32>,
2072		),
2073		BoundedVec<u32, ConstU32<7>>,
2074	>;
2075
2076	#[test]
2077	fn contains_prefix_works() {
2078		TestExternalities::default().execute_with(|| {
2079			// Test double maps
2080			assert!(FooDoubleMap::iter_prefix_values(1).next().is_none());
2081			assert_eq!(FooDoubleMap::contains_prefix(1), false);
2082
2083			assert_ok!(FooDoubleMap::try_append(1, 1, 4));
2084			assert_ok!(FooDoubleMap::try_append(2, 1, 4));
2085			assert!(FooDoubleMap::iter_prefix_values(1).next().is_some());
2086			assert!(FooDoubleMap::contains_prefix(1));
2087			FooDoubleMap::remove(1, 1);
2088			assert_eq!(FooDoubleMap::contains_prefix(1), false);
2089
2090			// Test N Maps
2091			assert!(FooTripleMap::iter_prefix_values((1,)).next().is_none());
2092			assert_eq!(FooTripleMap::contains_prefix((1,)), false);
2093
2094			FooTripleMap::insert((1, 1, 1), 4);
2095			FooTripleMap::insert((2, 1, 1), 4);
2096			assert!(FooTripleMap::iter_prefix_values((1,)).next().is_some());
2097			assert!(FooTripleMap::contains_prefix((1,)));
2098			FooTripleMap::remove((1, 1, 1));
2099			assert_eq!(FooTripleMap::contains_prefix((1,)), false);
2100		});
2101	}
2102
2103	#[test]
2104	fn try_append_works() {
2105		TestExternalities::default().execute_with(|| {
2106			let bounded: WeakBoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2107			Foo::put(bounded);
2108			assert_ok!(Foo::try_append(4));
2109			assert_ok!(Foo::try_append(5));
2110			assert_ok!(Foo::try_append(6));
2111			assert_ok!(Foo::try_append(7));
2112			assert_eq!(Foo::decode_len().unwrap(), 7);
2113			assert!(Foo::try_append(8).is_err());
2114		});
2115
2116		TestExternalities::default().execute_with(|| {
2117			let bounded: BoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2118			FooMap::insert(1, bounded);
2119
2120			assert_ok!(FooMap::try_append(1, 4));
2121			assert_ok!(FooMap::try_append(1, 5));
2122			assert_ok!(FooMap::try_append(1, 6));
2123			assert_ok!(FooMap::try_append(1, 7));
2124			assert_eq!(FooMap::decode_len(1).unwrap(), 7);
2125			assert!(FooMap::try_append(1, 8).is_err());
2126
2127			// append to a non-existing
2128			assert!(FooMap::get(2).is_none());
2129			assert_ok!(FooMap::try_append(2, 4));
2130			assert_eq!(
2131				FooMap::get(2).unwrap(),
2132				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4]).unwrap(),
2133			);
2134			assert_ok!(FooMap::try_append(2, 5));
2135			assert_eq!(
2136				FooMap::get(2).unwrap(),
2137				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4, 5]).unwrap(),
2138			);
2139		});
2140
2141		TestExternalities::default().execute_with(|| {
2142			let bounded: BoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2143			FooDoubleMap::insert(1, 1, bounded);
2144
2145			assert_ok!(FooDoubleMap::try_append(1, 1, 4));
2146			assert_ok!(FooDoubleMap::try_append(1, 1, 5));
2147			assert_ok!(FooDoubleMap::try_append(1, 1, 6));
2148			assert_ok!(FooDoubleMap::try_append(1, 1, 7));
2149			assert_eq!(FooDoubleMap::decode_len(1, 1).unwrap(), 7);
2150			assert!(FooDoubleMap::try_append(1, 1, 8).is_err());
2151
2152			// append to a non-existing
2153			assert!(FooDoubleMap::get(2, 1).is_none());
2154			assert_ok!(FooDoubleMap::try_append(2, 1, 4));
2155			assert_eq!(
2156				FooDoubleMap::get(2, 1).unwrap(),
2157				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4]).unwrap(),
2158			);
2159			assert_ok!(FooDoubleMap::try_append(2, 1, 5));
2160			assert_eq!(
2161				FooDoubleMap::get(2, 1).unwrap(),
2162				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4, 5]).unwrap(),
2163			);
2164		});
2165
2166		TestExternalities::default().execute_with(|| {
2167			let bounded: BoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2168			FooQuadMap::insert((1, 1, 1, 1), bounded);
2169
2170			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 4));
2171			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 5));
2172			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 6));
2173			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 7));
2174			assert_eq!(FooQuadMap::decode_len((1, 1, 1, 1)).unwrap(), 7);
2175			assert!(FooQuadMap::try_append((1, 1, 1, 1), 8).is_err());
2176
2177			// append to a non-existing
2178			assert!(FooQuadMap::get((2, 1, 1, 1)).is_none());
2179			assert_ok!(FooQuadMap::try_append((2, 1, 1, 1), 4));
2180			assert_eq!(
2181				FooQuadMap::get((2, 1, 1, 1)).unwrap(),
2182				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4]).unwrap(),
2183			);
2184			assert_ok!(FooQuadMap::try_append((2, 1, 1, 1), 5));
2185			assert_eq!(
2186				FooQuadMap::get((2, 1, 1, 1)).unwrap(),
2187				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4, 5]).unwrap(),
2188			);
2189		});
2190	}
2191
2192	#[crate::storage_alias]
2193	type FooSet = StorageValue<Prefix, BTreeSet<u32>>;
2194
2195	#[test]
2196	fn btree_set_append_and_decode_len_works() {
2197		TestExternalities::default().execute_with(|| {
2198			let btree = BTreeSet::from([1, 2, 3]);
2199			FooSet::put(btree);
2200
2201			FooSet::append(4);
2202			FooSet::append(5);
2203			FooSet::append(6);
2204			FooSet::append(7);
2205
2206			assert_eq!(FooSet::decode_non_dedup_len().unwrap(), 7);
2207		});
2208	}
2209
2210	#[docify::export]
2211	#[test]
2212	fn btree_set_decode_non_dedup_len() {
2213		#[crate::storage_alias]
2214		type Store = StorageValue<Prefix, BTreeSet<u32>>;
2215
2216		TestExternalities::default().execute_with(|| {
2217			Store::append(4);
2218			Store::append(4); // duplicate value
2219			Store::append(5);
2220
2221			let length_with_dup_items = 3;
2222
2223			assert_eq!(Store::decode_non_dedup_len().unwrap(), length_with_dup_items);
2224		});
2225	}
2226}