frame_support/storage/
mod.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
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 sp_core::storage::ChildInfo;
31use sp_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 sp_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 substrate 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>) -> sp_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	) -> sp_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>) -> sp_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`](sp_io::MultiRemovalResults) to inform about the result. Once
889	/// the resultant `maybe_cursor` field is `None`, then no further items remain to be deleted.
890	///
891	/// NOTE: After the initial call for any given map, it is important that no further items
892	/// are inserted into the map which match the `partial key`. If so, then the map may not be
893	/// empty when the resultant `maybe_cursor` is `None`.
894	///
895	/// # Limit
896	///
897	/// A `limit` must be provided in order to cap the maximum
898	/// amount of deletions done in a single call. This is one fewer than the
899	/// maximum number of backend iterations which may be done by this operation and as such
900	/// represents the maximum number of backend deletions which may happen. A `limit` of zero
901	/// implies that no keys will be deleted, though there may be a single iteration done.
902	///
903	/// # Cursor
904	///
905	/// A *cursor* may be passed in to this operation with `maybe_cursor`. `None` should only be
906	/// passed once (in the initial call) for any given storage map and `partial_key`. Subsequent
907	/// calls operating on the same map/`partial_key` should always pass `Some`, and this should be
908	/// equal to the previous call result's `maybe_cursor` field.
909	fn clear_prefix<KP>(
910		partial_key: KP,
911		limit: u32,
912		maybe_cursor: Option<&[u8]>,
913	) -> sp_io::MultiRemovalResults
914	where
915		K: HasKeyPrefix<KP>;
916
917	/// Does any value under a `partial_key` prefix (explicitly) exist in storage?
918	/// Might have unexpected behaviour with empty keys, e.g. `[]`.
919	fn contains_prefix<KP>(partial_key: KP) -> bool
920	where
921		K: HasKeyPrefix<KP>;
922
923	/// Iterate over values that share the partial prefix key.
924	fn iter_prefix_values<KP>(partial_key: KP) -> PrefixIterator<V>
925	where
926		K: HasKeyPrefix<KP>;
927
928	/// Mutate the value under a key.
929	fn mutate<KArg, R, F>(key: KArg, f: F) -> R
930	where
931		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
932		F: FnOnce(&mut Self::Query) -> R;
933
934	/// Mutate the item, only if an `Ok` value is returned.
935	fn try_mutate<KArg, R, E, F>(key: KArg, f: F) -> Result<R, E>
936	where
937		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
938		F: FnOnce(&mut Self::Query) -> Result<R, E>;
939
940	/// Mutate the value under a key.
941	///
942	/// Deletes the item if mutated to a `None`.
943	fn mutate_exists<KArg, R, F>(key: KArg, f: F) -> R
944	where
945		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
946		F: FnOnce(&mut Option<V>) -> R;
947
948	/// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`.
949	/// `f` will always be called with an option representing if the storage item exists (`Some<V>`)
950	/// or if the storage item does not exist (`None`), independent of the `QueryType`.
951	fn try_mutate_exists<KArg, R, E, F>(key: KArg, f: F) -> Result<R, E>
952	where
953		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
954		F: FnOnce(&mut Option<V>) -> Result<R, E>;
955
956	/// Take the value under a key.
957	fn take<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> Self::Query;
958
959	/// Append the given items to the value in the storage.
960	///
961	/// `V` is required to implement `codec::EncodeAppend`.
962	///
963	/// # Warning
964	///
965	/// If the storage item is not encoded properly, the storage will be overwritten
966	/// and set to `[item]`. Any default value set for the storage item will be ignored
967	/// on overwrite.
968	fn append<Item, EncodeLikeItem, KArg>(key: KArg, item: EncodeLikeItem)
969	where
970		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter,
971		Item: Encode,
972		EncodeLikeItem: EncodeLike<Item>,
973		V: StorageAppend<Item>;
974
975	/// Read the length of the storage value without decoding the entire value under the
976	/// given `key`.
977	///
978	/// `V` is required to implement [`StorageDecodeLength`].
979	///
980	/// If the value does not exists or it fails to decode the length, `None` is returned.
981	/// Otherwise `Some(len)` is returned.
982	///
983	/// # Warning
984	///
985	/// `None` does not mean that `get()` does not return a value. The default value is completely
986	/// ignored by this function.
987	fn decode_len<KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter>(key: KArg) -> Option<usize>
988	where
989		V: StorageDecodeLength,
990	{
991		V::decode_len(&Self::hashed_key_for(key))
992	}
993
994	/// Migrate an item with the given `key` from defunct `hash_fns` to the current hashers.
995	///
996	/// If the key doesn't exist, then it's a no-op. If it does, then it returns its value.
997	fn migrate_keys<KArg>(key: KArg, hash_fns: K::HArg) -> Option<V>
998	where
999		KArg: EncodeLikeTuple<K::KArg> + TupleToEncodedIter;
1000}
1001
1002/// Iterate or drain over a prefix and decode raw_key and raw_value into `T`.
1003///
1004/// If any decoding fails it skips it and continues to the next key.
1005///
1006/// If draining, then the hook `OnRemoval::on_removal` is called after each removal.
1007pub struct PrefixIterator<T, OnRemoval = ()> {
1008	prefix: Vec<u8>,
1009	previous_key: Vec<u8>,
1010	/// If true then value are removed while iterating
1011	drain: bool,
1012	/// Function that take `(raw_key_without_prefix, raw_value)` and decode `T`.
1013	/// `raw_key_without_prefix` is the raw storage key without the prefix iterated on.
1014	closure: fn(&[u8], &[u8]) -> Result<T, codec::Error>,
1015	phantom: core::marker::PhantomData<OnRemoval>,
1016}
1017
1018impl<T, OnRemoval1> PrefixIterator<T, OnRemoval1> {
1019	/// Converts to the same iterator but with the different 'OnRemoval' type
1020	pub fn convert_on_removal<OnRemoval2>(self) -> PrefixIterator<T, OnRemoval2> {
1021		PrefixIterator::<T, OnRemoval2> {
1022			prefix: self.prefix,
1023			previous_key: self.previous_key,
1024			drain: self.drain,
1025			closure: self.closure,
1026			phantom: Default::default(),
1027		}
1028	}
1029}
1030
1031/// Trait for specialising on removal logic of [`PrefixIterator`].
1032pub trait PrefixIteratorOnRemoval {
1033	/// This function is called whenever a key/value is removed.
1034	fn on_removal(key: &[u8], value: &[u8]);
1035}
1036
1037/// No-op implementation.
1038impl PrefixIteratorOnRemoval for () {
1039	fn on_removal(_key: &[u8], _value: &[u8]) {}
1040}
1041
1042impl<T, OnRemoval> PrefixIterator<T, OnRemoval> {
1043	/// Creates a new `PrefixIterator`, iterating after `previous_key` and filtering out keys that
1044	/// are not prefixed with `prefix`.
1045	///
1046	/// A `decode_fn` function must also be supplied, and it takes in two `&[u8]` parameters,
1047	/// returning a `Result` containing the decoded type `T` if successful, and a `codec::Error` on
1048	/// failure. The first `&[u8]` argument represents the raw, undecoded key without the prefix of
1049	/// the current item, while the second `&[u8]` argument denotes the corresponding raw,
1050	/// undecoded value.
1051	pub fn new(
1052		prefix: Vec<u8>,
1053		previous_key: Vec<u8>,
1054		decode_fn: fn(&[u8], &[u8]) -> Result<T, codec::Error>,
1055	) -> Self {
1056		PrefixIterator {
1057			prefix,
1058			previous_key,
1059			drain: false,
1060			closure: decode_fn,
1061			phantom: Default::default(),
1062		}
1063	}
1064
1065	/// Get the last key that has been iterated upon and return it.
1066	pub fn last_raw_key(&self) -> &[u8] {
1067		&self.previous_key
1068	}
1069
1070	/// Get the prefix that is being iterated upon for this iterator and return it.
1071	pub fn prefix(&self) -> &[u8] {
1072		&self.prefix
1073	}
1074
1075	/// Set the key that the iterator should start iterating after.
1076	pub fn set_last_raw_key(&mut self, previous_key: Vec<u8>) {
1077		self.previous_key = previous_key;
1078	}
1079
1080	/// Mutate this iterator into a draining iterator; items iterated are removed from storage.
1081	pub fn drain(mut self) -> Self {
1082		self.drain = true;
1083		self
1084	}
1085}
1086
1087impl<T, OnRemoval: PrefixIteratorOnRemoval> Iterator for PrefixIterator<T, OnRemoval> {
1088	type Item = T;
1089
1090	fn next(&mut self) -> Option<Self::Item> {
1091		loop {
1092			let maybe_next = sp_io::storage::next_key(&self.previous_key)
1093				.filter(|n| n.starts_with(&self.prefix));
1094			break match maybe_next {
1095				Some(next) => {
1096					self.previous_key = next;
1097					let raw_value = match unhashed::get_raw(&self.previous_key) {
1098						Some(raw_value) => raw_value,
1099						None => {
1100							log::error!(
1101								"next_key returned a key with no value at {:?}",
1102								self.previous_key,
1103							);
1104							continue
1105						},
1106					};
1107					if self.drain {
1108						unhashed::kill(&self.previous_key);
1109						OnRemoval::on_removal(&self.previous_key, &raw_value);
1110					}
1111					let raw_key_without_prefix = &self.previous_key[self.prefix.len()..];
1112					let item = match (self.closure)(raw_key_without_prefix, &raw_value[..]) {
1113						Ok(item) => item,
1114						Err(e) => {
1115							log::error!(
1116								"(key, value) failed to decode at {:?}: {:?}",
1117								self.previous_key,
1118								e,
1119							);
1120							continue
1121						},
1122					};
1123
1124					Some(item)
1125				},
1126				None => None,
1127			}
1128		}
1129	}
1130}
1131
1132/// Iterate over a prefix and decode raw_key into `T`.
1133///
1134/// If any decoding fails it skips it and continues to the next key.
1135pub struct KeyPrefixIterator<T> {
1136	prefix: Vec<u8>,
1137	previous_key: Vec<u8>,
1138	/// If true then value are removed while iterating
1139	drain: bool,
1140	/// Function that take `raw_key_without_prefix` and decode `T`.
1141	/// `raw_key_without_prefix` is the raw storage key without the prefix iterated on.
1142	closure: fn(&[u8]) -> Result<T, codec::Error>,
1143}
1144
1145impl<T> KeyPrefixIterator<T> {
1146	/// Creates a new `KeyPrefixIterator`, iterating after `previous_key` and filtering out keys
1147	/// that are not prefixed with `prefix`.
1148	///
1149	/// A `decode_fn` function must also be supplied, and it takes in a `&[u8]` parameter, returning
1150	/// a `Result` containing the decoded key type `T` if successful, and a `codec::Error` on
1151	/// failure. The `&[u8]` argument represents the raw, undecoded key without the prefix of the
1152	/// current item.
1153	pub fn new(
1154		prefix: Vec<u8>,
1155		previous_key: Vec<u8>,
1156		decode_fn: fn(&[u8]) -> Result<T, codec::Error>,
1157	) -> Self {
1158		KeyPrefixIterator { prefix, previous_key, drain: false, closure: decode_fn }
1159	}
1160
1161	/// Get the last key that has been iterated upon and return it.
1162	pub fn last_raw_key(&self) -> &[u8] {
1163		&self.previous_key
1164	}
1165
1166	/// Get the prefix that is being iterated upon for this iterator and return it.
1167	pub fn prefix(&self) -> &[u8] {
1168		&self.prefix
1169	}
1170
1171	/// Set the key that the iterator should start iterating after.
1172	pub fn set_last_raw_key(&mut self, previous_key: Vec<u8>) {
1173		self.previous_key = previous_key;
1174	}
1175
1176	/// Mutate this iterator into a draining iterator; items iterated are removed from storage.
1177	pub fn drain(mut self) -> Self {
1178		self.drain = true;
1179		self
1180	}
1181}
1182
1183impl<T> Iterator for KeyPrefixIterator<T> {
1184	type Item = T;
1185
1186	fn next(&mut self) -> Option<Self::Item> {
1187		loop {
1188			let maybe_next = sp_io::storage::next_key(&self.previous_key)
1189				.filter(|n| n.starts_with(&self.prefix));
1190
1191			if let Some(next) = maybe_next {
1192				self.previous_key = next;
1193				if self.drain {
1194					unhashed::kill(&self.previous_key);
1195				}
1196				let raw_key_without_prefix = &self.previous_key[self.prefix.len()..];
1197
1198				match (self.closure)(raw_key_without_prefix) {
1199					Ok(item) => return Some(item),
1200					Err(e) => {
1201						log::error!("key failed to decode at {:?}: {:?}", self.previous_key, e);
1202						continue
1203					},
1204				}
1205			}
1206
1207			return None
1208		}
1209	}
1210}
1211
1212/// Iterate over a prefix of a child trie and decode raw_key and raw_value into `T`.
1213///
1214/// If any decoding fails it skips the key and continues to the next one.
1215pub struct ChildTriePrefixIterator<T> {
1216	/// The prefix iterated on
1217	prefix: Vec<u8>,
1218	/// child info for child trie
1219	child_info: ChildInfo,
1220	/// The last key iterated on
1221	previous_key: Vec<u8>,
1222	/// If true then values are removed while iterating
1223	drain: bool,
1224	/// Whether or not we should fetch the previous key
1225	fetch_previous_key: bool,
1226	/// Function that takes `(raw_key_without_prefix, raw_value)` and decode `T`.
1227	/// `raw_key_without_prefix` is the raw storage key without the prefix iterated on.
1228	closure: fn(&[u8], &[u8]) -> Result<T, codec::Error>,
1229}
1230
1231impl<T> ChildTriePrefixIterator<T> {
1232	/// Mutate this iterator into a draining iterator; items iterated are removed from storage.
1233	pub fn drain(mut self) -> Self {
1234		self.drain = true;
1235		self
1236	}
1237}
1238
1239impl<T: Decode + Sized> ChildTriePrefixIterator<(Vec<u8>, T)> {
1240	/// Construct iterator to iterate over child trie items in `child_info` with the prefix
1241	/// `prefix`.
1242	///
1243	/// NOTE: Iterator with [`Self::drain`] will remove any value who failed to decode
1244	pub fn with_prefix(child_info: &ChildInfo, prefix: &[u8]) -> Self {
1245		let prefix = prefix.to_vec();
1246		let previous_key = prefix.clone();
1247		let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
1248			let value = T::decode(&mut raw_value)?;
1249			Ok((raw_key_without_prefix.to_vec(), value))
1250		};
1251
1252		Self {
1253			prefix,
1254			child_info: child_info.clone(),
1255			previous_key,
1256			drain: false,
1257			fetch_previous_key: true,
1258			closure,
1259		}
1260	}
1261}
1262
1263impl<K: Decode + Sized, T: Decode + Sized> ChildTriePrefixIterator<(K, T)> {
1264	/// Construct iterator to iterate over child trie items in `child_info` with the prefix
1265	/// `prefix`.
1266	///
1267	/// NOTE: Iterator with [`Self::drain`] will remove any key or value who failed to decode
1268	pub fn with_prefix_over_key<H: ReversibleStorageHasher>(
1269		child_info: &ChildInfo,
1270		prefix: &[u8],
1271	) -> Self {
1272		let prefix = prefix.to_vec();
1273		let previous_key = prefix.clone();
1274		let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
1275			let mut key_material = H::reverse(raw_key_without_prefix);
1276			let key = K::decode(&mut key_material)?;
1277			let value = T::decode(&mut raw_value)?;
1278			Ok((key, value))
1279		};
1280
1281		Self {
1282			prefix,
1283			child_info: child_info.clone(),
1284			previous_key,
1285			drain: false,
1286			fetch_previous_key: true,
1287			closure,
1288		}
1289	}
1290}
1291
1292impl<T> Iterator for ChildTriePrefixIterator<T> {
1293	type Item = T;
1294
1295	fn next(&mut self) -> Option<Self::Item> {
1296		loop {
1297			let maybe_next = if self.fetch_previous_key {
1298				self.fetch_previous_key = false;
1299				Some(self.previous_key.clone())
1300			} else {
1301				sp_io::default_child_storage::next_key(
1302					self.child_info.storage_key(),
1303					&self.previous_key,
1304				)
1305				.filter(|n| n.starts_with(&self.prefix))
1306			};
1307			break match maybe_next {
1308				Some(next) => {
1309					self.previous_key = next;
1310					let raw_value = match child::get_raw(&self.child_info, &self.previous_key) {
1311						Some(raw_value) => raw_value,
1312						None => {
1313							log::error!(
1314								"next_key returned a key with no value at {:?}",
1315								self.previous_key,
1316							);
1317							continue
1318						},
1319					};
1320					if self.drain {
1321						child::kill(&self.child_info, &self.previous_key)
1322					}
1323					let raw_key_without_prefix = &self.previous_key[self.prefix.len()..];
1324					let item = match (self.closure)(raw_key_without_prefix, &raw_value[..]) {
1325						Ok(item) => item,
1326						Err(e) => {
1327							log::error!(
1328								"(key, value) failed to decode at {:?}: {:?}",
1329								self.previous_key,
1330								e,
1331							);
1332							continue
1333						},
1334					};
1335
1336					Some(item)
1337				},
1338				None => None,
1339			}
1340		}
1341	}
1342}
1343
1344/// Trait for storage types that store all its value after a unique prefix.
1345pub trait StoragePrefixedContainer {
1346	/// Pallet prefix. Used for generating final key.
1347	fn pallet_prefix() -> &'static [u8];
1348
1349	/// Storage prefix. Used for generating final key.
1350	fn storage_prefix() -> &'static [u8];
1351
1352	/// Final full prefix that prefixes all keys.
1353	fn final_prefix() -> [u8; 32] {
1354		crate::storage::storage_prefix(Self::pallet_prefix(), Self::storage_prefix())
1355	}
1356}
1357
1358/// Trait for maps that store all its value after a unique prefix.
1359///
1360/// By default the final prefix is:
1361/// ```nocompile
1362/// Twox128(pallet_prefix) ++ Twox128(storage_prefix)
1363/// ```
1364pub trait StoragePrefixedMap<Value: FullCodec> {
1365	/// Pallet prefix. Used for generating final key.
1366	fn pallet_prefix() -> &'static [u8]; // TODO move to StoragePrefixedContainer
1367
1368	/// Storage prefix. Used for generating final key.
1369	fn storage_prefix() -> &'static [u8];
1370
1371	/// Final full prefix that prefixes all keys.
1372	fn final_prefix() -> [u8; 32] {
1373		crate::storage::storage_prefix(Self::pallet_prefix(), Self::storage_prefix())
1374	}
1375
1376	/// Remove all values in the overlay and up to `limit` in the backend.
1377	///
1378	/// All values in the client overlay will be deleted, if there is some `limit` then up to
1379	/// `limit` values are deleted from the client backend, if `limit` is none then all values in
1380	/// the client backend are deleted.
1381	///
1382	/// # Note
1383	///
1384	/// Calling this multiple times per block with a `limit` set leads always to the same keys being
1385	/// removed and the same result being returned. This happens because the keys to delete in the
1386	/// overlay are not taken into account when deleting keys in the backend.
1387	#[deprecated = "Use `clear` instead"]
1388	fn remove_all(limit: Option<u32>) -> sp_io::KillStorageResult {
1389		unhashed::clear_prefix(&Self::final_prefix(), limit, None).into()
1390	}
1391
1392	/// Attempt to remove all items from the map.
1393	///
1394	/// Returns [`MultiRemovalResults`](sp_io::MultiRemovalResults) to inform about the result. Once
1395	/// the resultant `maybe_cursor` field is `None`, then no further items remain to be deleted.
1396	///
1397	/// NOTE: After the initial call for any given map, it is important that no further items
1398	/// are inserted into the map. If so, then the map may not be empty when the resultant
1399	/// `maybe_cursor` is `None`.
1400	///
1401	/// # Limit
1402	///
1403	/// A `limit` must always be provided through in order to cap the maximum
1404	/// amount of deletions done in a single call. This is one fewer than the
1405	/// maximum number of backend iterations which may be done by this operation and as such
1406	/// represents the maximum number of backend deletions which may happen. A `limit` of zero
1407	/// implies that no keys will be deleted, though there may be a single iteration done.
1408	///
1409	/// # Cursor
1410	///
1411	/// A *cursor* may be passed in to this operation with `maybe_cursor`. `None` should only be
1412	/// passed once (in the initial call) for any given storage map. Subsequent calls
1413	/// operating on the same map should always pass `Some`, and this should be equal to the
1414	/// previous call result's `maybe_cursor` field.
1415	fn clear(limit: u32, maybe_cursor: Option<&[u8]>) -> sp_io::MultiRemovalResults {
1416		unhashed::clear_prefix(&Self::final_prefix(), Some(limit), maybe_cursor)
1417	}
1418
1419	/// Iter over all value of the storage.
1420	///
1421	/// NOTE: If a value failed to decode because storage is corrupted then it is skipped.
1422	fn iter_values() -> PrefixIterator<Value> {
1423		let prefix = Self::final_prefix();
1424		PrefixIterator {
1425			prefix: prefix.to_vec(),
1426			previous_key: prefix.to_vec(),
1427			drain: false,
1428			closure: |_raw_key, mut raw_value| Value::decode(&mut raw_value),
1429			phantom: Default::default(),
1430		}
1431	}
1432
1433	/// Translate the values of all elements by a function `f`, in the map in no particular order.
1434	/// By returning `None` from `f` for an element, you'll remove it from the map.
1435	///
1436	/// NOTE: If a value fail to decode because storage is corrupted then it is skipped.
1437	///
1438	/// # Warning
1439	///
1440	/// This function must be used with care, before being updated the storage still contains the
1441	/// old type, thus other calls (such as `get`) will fail at decoding it.
1442	///
1443	/// # Usage
1444	///
1445	/// This would typically be called inside the module implementation of on_runtime_upgrade.
1446	fn translate_values<OldValue: Decode, F: FnMut(OldValue) -> Option<Value>>(mut f: F) {
1447		let prefix = Self::final_prefix();
1448		let mut previous_key = prefix.clone().to_vec();
1449		while let Some(next) =
1450			sp_io::storage::next_key(&previous_key).filter(|n| n.starts_with(&prefix))
1451		{
1452			previous_key = next;
1453			let maybe_value = unhashed::get::<OldValue>(&previous_key);
1454			match maybe_value {
1455				Some(value) => match f(value) {
1456					Some(new) => unhashed::put::<Value>(&previous_key, &new),
1457					None => unhashed::kill(&previous_key),
1458				},
1459				None => {
1460					log::error!("old key failed to decode at {:?}", previous_key);
1461					continue
1462				},
1463			}
1464		}
1465	}
1466}
1467
1468/// Marker trait that will be implemented for types that support the `storage::append` api.
1469///
1470/// This trait is sealed.
1471pub trait StorageAppend<Item: Encode>: private::Sealed {}
1472
1473/// It is expected that the length is at the beginning of the encoded object
1474/// and that the length is a `Compact<u32>`.
1475///
1476/// This trait is sealed.
1477pub trait StorageDecodeLength: private::Sealed + codec::DecodeLength {
1478	/// Decode the length of the storage value at `key`.
1479	///
1480	/// This function assumes that the length is at the beginning of the encoded object
1481	/// and is a `Compact<u32>`.
1482	///
1483	/// Returns `None` if the storage value does not exist or the decoding failed.
1484	fn decode_len(key: &[u8]) -> Option<usize> {
1485		// `Compact<u32>` is 5 bytes in maximum.
1486		let mut data = [0u8; 5];
1487		let len = sp_io::storage::read(key, &mut data, 0)?;
1488		let len = data.len().min(len as usize);
1489		<Self as codec::DecodeLength>::len(&data[..len]).ok()
1490	}
1491}
1492
1493/// It is expected that the length is at the beginning of the encoded object and that the length is
1494/// a `Compact<u32>`.
1495///
1496/// # Note
1497/// The length returned by this trait is not deduplicated, i.e. it is the length of the underlying
1498/// stored Vec.
1499///
1500/// This trait is sealed.
1501pub trait StorageDecodeNonDedupLength: private::Sealed + codec::DecodeLength {
1502	/// Decode the length of the storage value at `key`.
1503	///
1504	/// This function assumes that the length is at the beginning of the encoded object and is a
1505	/// `Compact<u32>`.
1506	///
1507	/// Returns `None` if the storage value does not exist or the decoding failed.
1508	fn decode_non_dedup_len(key: &[u8]) -> Option<usize> {
1509		let mut data = [0u8; 5];
1510		let len = sp_io::storage::read(key, &mut data, 0)?;
1511		let len = data.len().min(len as usize);
1512		<Self as codec::DecodeLength>::len(&data[..len]).ok()
1513	}
1514}
1515
1516/// Provides `Sealed` trait to prevent implementing trait `StorageAppend` & `StorageDecodeLength`
1517/// & `EncodeLikeTuple` outside of this crate.
1518mod private {
1519	use super::*;
1520	use bounded_vec::BoundedVec;
1521	use weak_bounded_vec::WeakBoundedVec;
1522
1523	pub trait Sealed {}
1524
1525	impl<T: Encode> Sealed for Vec<T> {}
1526	impl Sealed for Digest {}
1527	impl<T, S> Sealed for BoundedVec<T, S> {}
1528	impl<T, S> Sealed for WeakBoundedVec<T, S> {}
1529	impl<K, V, S> Sealed for bounded_btree_map::BoundedBTreeMap<K, V, S> {}
1530	impl<T, S> Sealed for bounded_btree_set::BoundedBTreeSet<T, S> {}
1531	impl<T: Encode> Sealed for BTreeSet<T> {}
1532	impl<'a, T: EncodeLike<U>, U: Encode> Sealed for codec::Ref<'a, T, U> {}
1533
1534	macro_rules! impl_sealed_for_tuple {
1535		($($elem:ident),+) => {
1536			paste::paste! {
1537				impl<$($elem: Encode,)+> Sealed for ($($elem,)+) {}
1538				impl<$($elem: Encode,)+> Sealed for &($($elem,)+) {}
1539			}
1540		};
1541	}
1542
1543	impl_sealed_for_tuple!(A);
1544	impl_sealed_for_tuple!(A, B);
1545	impl_sealed_for_tuple!(A, B, C);
1546	impl_sealed_for_tuple!(A, B, C, D);
1547	impl_sealed_for_tuple!(A, B, C, D, E);
1548	impl_sealed_for_tuple!(A, B, C, D, E, F);
1549	impl_sealed_for_tuple!(A, B, C, D, E, F, G);
1550	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H);
1551	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I);
1552	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J);
1553	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
1554	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
1555	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
1556	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O);
1557	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O, P);
1558	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O, P, Q);
1559	impl_sealed_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, O, P, Q, R);
1560}
1561
1562impl<T: Encode> StorageAppend<T> for Vec<T> {}
1563impl<T: Encode> StorageDecodeLength for Vec<T> {}
1564
1565impl<T: Encode> StorageAppend<T> for BTreeSet<T> {}
1566impl<T: Encode> StorageDecodeNonDedupLength for BTreeSet<T> {}
1567
1568// Blanket implementation StorageDecodeNonDedupLength for all types that are StorageDecodeLength.
1569impl<T: StorageDecodeLength> StorageDecodeNonDedupLength for T {
1570	fn decode_non_dedup_len(key: &[u8]) -> Option<usize> {
1571		T::decode_len(key)
1572	}
1573}
1574
1575/// We abuse the fact that SCALE does not put any marker into the encoding, i.e. we only encode the
1576/// internal vec and we can append to this vec. We have a test that ensures that if the `Digest`
1577/// format ever changes, we need to remove this here.
1578impl StorageAppend<DigestItem> for Digest {}
1579
1580/// Marker trait that is implemented for types that support the `storage::append` api with a limit
1581/// on the number of element.
1582///
1583/// This trait is sealed.
1584pub trait StorageTryAppend<Item>: StorageDecodeLength + private::Sealed {
1585	fn bound() -> usize;
1586}
1587
1588/// Storage value that is capable of [`StorageTryAppend`].
1589pub trait TryAppendValue<T: StorageTryAppend<I>, I: Encode> {
1590	/// Try and append the `item` into the storage item.
1591	///
1592	/// This might fail if bounds are not respected.
1593	fn try_append<LikeI: EncodeLike<I>>(item: LikeI) -> Result<(), ()>;
1594}
1595
1596impl<T, I, StorageValueT> TryAppendValue<T, I> for StorageValueT
1597where
1598	I: Encode,
1599	T: FullCodec + StorageTryAppend<I>,
1600	StorageValueT: generator::StorageValue<T>,
1601{
1602	fn try_append<LikeI: EncodeLike<I>>(item: LikeI) -> Result<(), ()> {
1603		let bound = T::bound();
1604		let current = Self::decode_len().unwrap_or_default();
1605		if current < bound {
1606			// NOTE: we cannot reuse the implementation for `Vec<T>` here because we never want to
1607			// mark `BoundedVec<T, S>` as `StorageAppend`.
1608			let key = Self::storage_value_final_key();
1609			sp_io::storage::append(&key, item.encode());
1610			Ok(())
1611		} else {
1612			Err(())
1613		}
1614	}
1615}
1616
1617/// Storage map that is capable of [`StorageTryAppend`].
1618pub trait TryAppendMap<K: Encode, T: StorageTryAppend<I>, I: Encode> {
1619	/// Try and append the `item` into the storage map at the given `key`.
1620	///
1621	/// This might fail if bounds are not respected.
1622	fn try_append<LikeK: EncodeLike<K> + Clone, LikeI: EncodeLike<I>>(
1623		key: LikeK,
1624		item: LikeI,
1625	) -> Result<(), ()>;
1626}
1627
1628impl<K, T, I, StorageMapT> TryAppendMap<K, T, I> for StorageMapT
1629where
1630	K: FullCodec,
1631	T: FullCodec + StorageTryAppend<I>,
1632	I: Encode,
1633	StorageMapT: generator::StorageMap<K, T>,
1634{
1635	fn try_append<LikeK: EncodeLike<K> + Clone, LikeI: EncodeLike<I>>(
1636		key: LikeK,
1637		item: LikeI,
1638	) -> Result<(), ()> {
1639		let bound = T::bound();
1640		let current = Self::decode_len(key.clone()).unwrap_or_default();
1641		if current < bound {
1642			let key = Self::storage_map_final_key(key);
1643			sp_io::storage::append(&key, item.encode());
1644			Ok(())
1645		} else {
1646			Err(())
1647		}
1648	}
1649}
1650
1651/// Storage double map that is capable of [`StorageTryAppend`].
1652pub trait TryAppendDoubleMap<K1: Encode, K2: Encode, T: StorageTryAppend<I>, I: Encode> {
1653	/// Try and append the `item` into the storage double map at the given `key`.
1654	///
1655	/// This might fail if bounds are not respected.
1656	fn try_append<
1657		LikeK1: EncodeLike<K1> + Clone,
1658		LikeK2: EncodeLike<K2> + Clone,
1659		LikeI: EncodeLike<I>,
1660	>(
1661		key1: LikeK1,
1662		key2: LikeK2,
1663		item: LikeI,
1664	) -> Result<(), ()>;
1665}
1666
1667impl<K1, K2, T, I, StorageDoubleMapT> TryAppendDoubleMap<K1, K2, T, I> for StorageDoubleMapT
1668where
1669	K1: FullCodec,
1670	K2: FullCodec,
1671	T: FullCodec + StorageTryAppend<I>,
1672	I: Encode,
1673	StorageDoubleMapT: generator::StorageDoubleMap<K1, K2, T>,
1674{
1675	fn try_append<
1676		LikeK1: EncodeLike<K1> + Clone,
1677		LikeK2: EncodeLike<K2> + Clone,
1678		LikeI: EncodeLike<I>,
1679	>(
1680		key1: LikeK1,
1681		key2: LikeK2,
1682		item: LikeI,
1683	) -> Result<(), ()> {
1684		let bound = T::bound();
1685		let current = Self::decode_len(key1.clone(), key2.clone()).unwrap_or_default();
1686		if current < bound {
1687			let double_map_key = Self::storage_double_map_final_key(key1, key2);
1688			sp_io::storage::append(&double_map_key, item.encode());
1689			Ok(())
1690		} else {
1691			Err(())
1692		}
1693	}
1694}
1695
1696/// Storage N map that is capable of [`StorageTryAppend`].
1697pub trait TryAppendNMap<K: KeyGenerator, T: StorageTryAppend<I>, I: Encode> {
1698	/// Try and append the `item` into the storage N map at the given `key`.
1699	///
1700	/// This might fail if bounds are not respected.
1701	fn try_append<
1702		LikeK: EncodeLikeTuple<K::KArg> + TupleToEncodedIter + Clone,
1703		LikeI: EncodeLike<I>,
1704	>(
1705		key: LikeK,
1706		item: LikeI,
1707	) -> Result<(), ()>;
1708}
1709
1710impl<K, T, I, StorageNMapT> TryAppendNMap<K, T, I> for StorageNMapT
1711where
1712	K: KeyGenerator,
1713	T: FullCodec + StorageTryAppend<I>,
1714	I: Encode,
1715	StorageNMapT: generator::StorageNMap<K, T>,
1716{
1717	fn try_append<
1718		LikeK: EncodeLikeTuple<K::KArg> + TupleToEncodedIter + Clone,
1719		LikeI: EncodeLike<I>,
1720	>(
1721		key: LikeK,
1722		item: LikeI,
1723	) -> Result<(), ()> {
1724		let bound = T::bound();
1725		let current = Self::decode_len(key.clone()).unwrap_or_default();
1726		if current < bound {
1727			let key = Self::storage_n_map_final_key::<K, _>(key);
1728			sp_io::storage::append(&key, item.encode());
1729			Ok(())
1730		} else {
1731			Err(())
1732		}
1733	}
1734}
1735
1736/// Returns the storage prefix for a specific pallet name and storage name.
1737///
1738/// The storage prefix is `concat(twox_128(pallet_name), twox_128(storage_name))`.
1739pub fn storage_prefix(pallet_name: &[u8], storage_name: &[u8]) -> [u8; 32] {
1740	let pallet_hash = sp_io::hashing::twox_128(pallet_name);
1741	let storage_hash = sp_io::hashing::twox_128(storage_name);
1742
1743	let mut final_key = [0u8; 32];
1744	final_key[..16].copy_from_slice(&pallet_hash);
1745	final_key[16..].copy_from_slice(&storage_hash);
1746
1747	final_key
1748}
1749
1750#[cfg(test)]
1751mod test {
1752	use super::*;
1753	use crate::{assert_ok, hash::Identity, pallet_prelude::NMapKey, Twox128};
1754	use bounded_vec::BoundedVec;
1755	use frame_support::traits::ConstU32;
1756	use generator::StorageValue as _;
1757	use sp_crypto_hashing::twox_128;
1758	use sp_io::TestExternalities;
1759	use weak_bounded_vec::WeakBoundedVec;
1760
1761	#[test]
1762	fn prefixed_map_works() {
1763		TestExternalities::default().execute_with(|| {
1764			struct MyStorage;
1765			impl StoragePrefixedMap<u64> for MyStorage {
1766				fn pallet_prefix() -> &'static [u8] {
1767					b"MyModule"
1768				}
1769
1770				fn storage_prefix() -> &'static [u8] {
1771					b"MyStorage"
1772				}
1773			}
1774
1775			let key_before = {
1776				let mut k = MyStorage::final_prefix();
1777				let last = k.iter_mut().last().unwrap();
1778				*last = last.checked_sub(1).unwrap();
1779				k
1780			};
1781			let key_after = {
1782				let mut k = MyStorage::final_prefix();
1783				let last = k.iter_mut().last().unwrap();
1784				*last = last.checked_add(1).unwrap();
1785				k
1786			};
1787
1788			unhashed::put(&key_before[..], &32u64);
1789			unhashed::put(&key_after[..], &33u64);
1790
1791			let k = [twox_128(b"MyModule"), twox_128(b"MyStorage")].concat();
1792			assert_eq!(MyStorage::final_prefix().to_vec(), k);
1793
1794			// test iteration
1795			assert!(MyStorage::iter_values().collect::<Vec<_>>().is_empty());
1796
1797			unhashed::put(&[&k[..], &vec![1][..]].concat(), &1u64);
1798			unhashed::put(&[&k[..], &vec![1, 1][..]].concat(), &2u64);
1799			unhashed::put(&[&k[..], &vec![8][..]].concat(), &3u64);
1800			unhashed::put(&[&k[..], &vec![10][..]].concat(), &4u64);
1801
1802			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2, 3, 4]);
1803
1804			// test removal
1805			let _ = MyStorage::clear(u32::max_value(), None);
1806			assert!(MyStorage::iter_values().collect::<Vec<_>>().is_empty());
1807
1808			// test migration
1809			unhashed::put(&[&k[..], &vec![1][..]].concat(), &1u32);
1810			unhashed::put(&[&k[..], &vec![8][..]].concat(), &2u32);
1811
1812			assert!(MyStorage::iter_values().collect::<Vec<_>>().is_empty());
1813			MyStorage::translate_values(|v: u32| Some(v as u64));
1814			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2]);
1815			let _ = MyStorage::clear(u32::max_value(), None);
1816
1817			// test migration 2
1818			unhashed::put(&[&k[..], &vec![1][..]].concat(), &1u128);
1819			unhashed::put(&[&k[..], &vec![1, 1][..]].concat(), &2u64);
1820			unhashed::put(&[&k[..], &vec![8][..]].concat(), &3u128);
1821			unhashed::put(&[&k[..], &vec![10][..]].concat(), &4u32);
1822
1823			// (contains some value that successfully decoded to u64)
1824			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2, 3]);
1825			MyStorage::translate_values(|v: u128| Some(v as u64));
1826			assert_eq!(MyStorage::iter_values().collect::<Vec<_>>(), vec![1, 2, 3]);
1827			let _ = MyStorage::clear(u32::max_value(), None);
1828
1829			// test that other values are not modified.
1830			assert_eq!(unhashed::get(&key_before[..]), Some(32u64));
1831			assert_eq!(unhashed::get(&key_after[..]), Some(33u64));
1832		});
1833	}
1834
1835	// This test ensures that the Digest encoding does not change without being noticed.
1836	#[test]
1837	fn digest_storage_append_works_as_expected() {
1838		TestExternalities::default().execute_with(|| {
1839			struct Storage;
1840			impl generator::StorageValue<Digest> for Storage {
1841				type Query = Digest;
1842
1843				fn pallet_prefix() -> &'static [u8] {
1844					b"MyModule"
1845				}
1846
1847				fn storage_prefix() -> &'static [u8] {
1848					b"Storage"
1849				}
1850
1851				fn from_optional_value_to_query(v: Option<Digest>) -> Self::Query {
1852					v.unwrap()
1853				}
1854
1855				fn from_query_to_optional_value(v: Self::Query) -> Option<Digest> {
1856					Some(v)
1857				}
1858
1859				fn storage_value_final_key() -> [u8; 32] {
1860					storage_prefix(Self::pallet_prefix(), Self::storage_prefix())
1861				}
1862			}
1863
1864			Storage::append(DigestItem::Other(Vec::new()));
1865
1866			let value = unhashed::get_raw(&Storage::storage_value_final_key()).unwrap();
1867
1868			let expected = Digest { logs: vec![DigestItem::Other(Vec::new())] };
1869			assert_eq!(Digest::decode(&mut &value[..]).unwrap(), expected);
1870		});
1871	}
1872
1873	#[test]
1874	fn key_prefix_iterator_works() {
1875		TestExternalities::default().execute_with(|| {
1876			use crate::{hash::Twox64Concat, storage::generator::StorageMap};
1877			struct MyStorageMap;
1878			impl StorageMap<u64, u64> for MyStorageMap {
1879				type Query = u64;
1880				type Hasher = Twox64Concat;
1881
1882				fn pallet_prefix() -> &'static [u8] {
1883					b"MyModule"
1884				}
1885
1886				fn storage_prefix() -> &'static [u8] {
1887					b"MyStorageMap"
1888				}
1889
1890				fn prefix_hash() -> [u8; 32] {
1891					storage_prefix(Self::pallet_prefix(), Self::storage_prefix())
1892				}
1893
1894				fn from_optional_value_to_query(v: Option<u64>) -> Self::Query {
1895					v.unwrap_or_default()
1896				}
1897
1898				fn from_query_to_optional_value(v: Self::Query) -> Option<u64> {
1899					Some(v)
1900				}
1901			}
1902
1903			let k = [twox_128(b"MyModule"), twox_128(b"MyStorageMap")].concat();
1904			assert_eq!(MyStorageMap::prefix_hash().to_vec(), k);
1905
1906			// empty to start
1907			assert!(MyStorageMap::iter_keys().collect::<Vec<_>>().is_empty());
1908
1909			MyStorageMap::insert(1, 10);
1910			MyStorageMap::insert(2, 20);
1911			MyStorageMap::insert(3, 30);
1912			MyStorageMap::insert(4, 40);
1913
1914			// just looking
1915			let mut keys = MyStorageMap::iter_keys().collect::<Vec<_>>();
1916			keys.sort();
1917			assert_eq!(keys, vec![1, 2, 3, 4]);
1918
1919			// draining the keys and values
1920			let mut drained_keys = MyStorageMap::iter_keys().drain().collect::<Vec<_>>();
1921			drained_keys.sort();
1922			assert_eq!(drained_keys, vec![1, 2, 3, 4]);
1923
1924			// empty again
1925			assert!(MyStorageMap::iter_keys().collect::<Vec<_>>().is_empty());
1926		});
1927	}
1928
1929	#[test]
1930	fn prefix_iterator_pagination_works() {
1931		TestExternalities::default().execute_with(|| {
1932			use crate::{hash::Identity, storage::generator::map::StorageMap};
1933			#[crate::storage_alias]
1934			type MyStorageMap = StorageMap<MyModule, Identity, u64, u64>;
1935
1936			MyStorageMap::insert(1, 10);
1937			MyStorageMap::insert(2, 20);
1938			MyStorageMap::insert(3, 30);
1939			MyStorageMap::insert(4, 40);
1940			MyStorageMap::insert(5, 50);
1941			MyStorageMap::insert(6, 60);
1942			MyStorageMap::insert(7, 70);
1943			MyStorageMap::insert(8, 80);
1944			MyStorageMap::insert(9, 90);
1945			MyStorageMap::insert(10, 100);
1946
1947			let op = |(_, v)| v / 10;
1948			let mut final_vec = vec![];
1949			let mut iter = MyStorageMap::iter();
1950
1951			let elem = iter.next().unwrap();
1952			assert_eq!(elem, (1, 10));
1953			final_vec.push(op(elem));
1954
1955			let elem = iter.next().unwrap();
1956			assert_eq!(elem, (2, 20));
1957			final_vec.push(op(elem));
1958
1959			let stored_key = iter.last_raw_key().to_owned();
1960			assert_eq!(stored_key, MyStorageMap::storage_map_final_key(2));
1961
1962			let mut iter = MyStorageMap::iter_from(stored_key.clone());
1963
1964			final_vec.push(op(iter.next().unwrap()));
1965			final_vec.push(op(iter.next().unwrap()));
1966			final_vec.push(op(iter.next().unwrap()));
1967
1968			assert_eq!(final_vec, vec![1, 2, 3, 4, 5]);
1969
1970			let mut iter = PrefixIterator::<_>::new(
1971				iter.prefix().to_vec(),
1972				stored_key,
1973				|mut raw_key_without_prefix, mut raw_value| {
1974					let key = u64::decode(&mut raw_key_without_prefix)?;
1975					Ok((key, u64::decode(&mut raw_value)?))
1976				},
1977			);
1978			let previous_key = MyStorageMap::storage_map_final_key(5);
1979			iter.set_last_raw_key(previous_key);
1980
1981			let remaining = iter.map(op).collect::<Vec<_>>();
1982			assert_eq!(remaining.len(), 5);
1983			assert_eq!(remaining, vec![6, 7, 8, 9, 10]);
1984
1985			final_vec.extend_from_slice(&remaining);
1986
1987			assert_eq!(final_vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1988		});
1989	}
1990
1991	#[test]
1992	fn child_trie_prefixed_map_works() {
1993		TestExternalities::default().execute_with(|| {
1994			let child_info_a = child::ChildInfo::new_default(b"a");
1995			child::put(&child_info_a, &[1, 2, 3], &8u16);
1996			child::put(&child_info_a, &[2], &8u16);
1997			child::put(&child_info_a, &[2, 1, 3], &8u8);
1998			child::put(&child_info_a, &[2, 2, 3], &8u16);
1999			child::put(&child_info_a, &[3], &8u16);
2000
2001			assert_eq!(
2002				ChildTriePrefixIterator::with_prefix(&child_info_a, &[2])
2003					.collect::<Vec<(Vec<u8>, u16)>>(),
2004				vec![(vec![], 8), (vec![2, 3], 8),],
2005			);
2006
2007			assert_eq!(
2008				ChildTriePrefixIterator::with_prefix(&child_info_a, &[2])
2009					.drain()
2010					.collect::<Vec<(Vec<u8>, u16)>>(),
2011				vec![(vec![], 8), (vec![2, 3], 8),],
2012			);
2013
2014			// The only remaining is the ones outside prefix
2015			assert_eq!(
2016				ChildTriePrefixIterator::with_prefix(&child_info_a, &[])
2017					.collect::<Vec<(Vec<u8>, u8)>>(),
2018				vec![(vec![1, 2, 3], 8), (vec![3], 8),],
2019			);
2020
2021			child::put(&child_info_a, &[1, 2, 3], &8u16);
2022			child::put(&child_info_a, &[2], &8u16);
2023			child::put(&child_info_a, &[2, 1, 3], &8u8);
2024			child::put(&child_info_a, &[2, 2, 3], &8u16);
2025			child::put(&child_info_a, &[3], &8u16);
2026
2027			assert_eq!(
2028				ChildTriePrefixIterator::with_prefix_over_key::<Identity>(&child_info_a, &[2])
2029					.collect::<Vec<(u16, u16)>>(),
2030				vec![(u16::decode(&mut &[2, 3][..]).unwrap(), 8),],
2031			);
2032
2033			assert_eq!(
2034				ChildTriePrefixIterator::with_prefix_over_key::<Identity>(&child_info_a, &[2])
2035					.drain()
2036					.collect::<Vec<(u16, u16)>>(),
2037				vec![(u16::decode(&mut &[2, 3][..]).unwrap(), 8),],
2038			);
2039
2040			// The only remaining is the ones outside prefix
2041			assert_eq!(
2042				ChildTriePrefixIterator::with_prefix(&child_info_a, &[])
2043					.collect::<Vec<(Vec<u8>, u8)>>(),
2044				vec![(vec![1, 2, 3], 8), (vec![3], 8),],
2045			);
2046		});
2047	}
2048
2049	#[crate::storage_alias]
2050	type Foo = StorageValue<Prefix, WeakBoundedVec<u32, ConstU32<7>>>;
2051	#[crate::storage_alias]
2052	type FooMap = StorageMap<Prefix, Twox128, u32, BoundedVec<u32, ConstU32<7>>>;
2053	#[crate::storage_alias]
2054	type FooDoubleMap =
2055		StorageDoubleMap<Prefix, Twox128, u32, Twox128, u32, BoundedVec<u32, ConstU32<7>>>;
2056	#[crate::storage_alias]
2057	type FooTripleMap = StorageNMap<
2058		Prefix,
2059		(NMapKey<Twox128, u32>, NMapKey<Twox128, u32>, NMapKey<Twox128, u32>),
2060		u64,
2061	>;
2062	#[crate::storage_alias]
2063	type FooQuadMap = StorageNMap<
2064		Prefix,
2065		(
2066			NMapKey<Twox128, u32>,
2067			NMapKey<Twox128, u32>,
2068			NMapKey<Twox128, u32>,
2069			NMapKey<Twox128, u32>,
2070		),
2071		BoundedVec<u32, ConstU32<7>>,
2072	>;
2073
2074	#[test]
2075	fn contains_prefix_works() {
2076		TestExternalities::default().execute_with(|| {
2077			// Test double maps
2078			assert!(FooDoubleMap::iter_prefix_values(1).next().is_none());
2079			assert_eq!(FooDoubleMap::contains_prefix(1), false);
2080
2081			assert_ok!(FooDoubleMap::try_append(1, 1, 4));
2082			assert_ok!(FooDoubleMap::try_append(2, 1, 4));
2083			assert!(FooDoubleMap::iter_prefix_values(1).next().is_some());
2084			assert!(FooDoubleMap::contains_prefix(1));
2085			FooDoubleMap::remove(1, 1);
2086			assert_eq!(FooDoubleMap::contains_prefix(1), false);
2087
2088			// Test N Maps
2089			assert!(FooTripleMap::iter_prefix_values((1,)).next().is_none());
2090			assert_eq!(FooTripleMap::contains_prefix((1,)), false);
2091
2092			FooTripleMap::insert((1, 1, 1), 4);
2093			FooTripleMap::insert((2, 1, 1), 4);
2094			assert!(FooTripleMap::iter_prefix_values((1,)).next().is_some());
2095			assert!(FooTripleMap::contains_prefix((1,)));
2096			FooTripleMap::remove((1, 1, 1));
2097			assert_eq!(FooTripleMap::contains_prefix((1,)), false);
2098		});
2099	}
2100
2101	#[test]
2102	fn try_append_works() {
2103		TestExternalities::default().execute_with(|| {
2104			let bounded: WeakBoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2105			Foo::put(bounded);
2106			assert_ok!(Foo::try_append(4));
2107			assert_ok!(Foo::try_append(5));
2108			assert_ok!(Foo::try_append(6));
2109			assert_ok!(Foo::try_append(7));
2110			assert_eq!(Foo::decode_len().unwrap(), 7);
2111			assert!(Foo::try_append(8).is_err());
2112		});
2113
2114		TestExternalities::default().execute_with(|| {
2115			let bounded: BoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2116			FooMap::insert(1, bounded);
2117
2118			assert_ok!(FooMap::try_append(1, 4));
2119			assert_ok!(FooMap::try_append(1, 5));
2120			assert_ok!(FooMap::try_append(1, 6));
2121			assert_ok!(FooMap::try_append(1, 7));
2122			assert_eq!(FooMap::decode_len(1).unwrap(), 7);
2123			assert!(FooMap::try_append(1, 8).is_err());
2124
2125			// append to a non-existing
2126			assert!(FooMap::get(2).is_none());
2127			assert_ok!(FooMap::try_append(2, 4));
2128			assert_eq!(
2129				FooMap::get(2).unwrap(),
2130				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4]).unwrap(),
2131			);
2132			assert_ok!(FooMap::try_append(2, 5));
2133			assert_eq!(
2134				FooMap::get(2).unwrap(),
2135				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4, 5]).unwrap(),
2136			);
2137		});
2138
2139		TestExternalities::default().execute_with(|| {
2140			let bounded: BoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2141			FooDoubleMap::insert(1, 1, bounded);
2142
2143			assert_ok!(FooDoubleMap::try_append(1, 1, 4));
2144			assert_ok!(FooDoubleMap::try_append(1, 1, 5));
2145			assert_ok!(FooDoubleMap::try_append(1, 1, 6));
2146			assert_ok!(FooDoubleMap::try_append(1, 1, 7));
2147			assert_eq!(FooDoubleMap::decode_len(1, 1).unwrap(), 7);
2148			assert!(FooDoubleMap::try_append(1, 1, 8).is_err());
2149
2150			// append to a non-existing
2151			assert!(FooDoubleMap::get(2, 1).is_none());
2152			assert_ok!(FooDoubleMap::try_append(2, 1, 4));
2153			assert_eq!(
2154				FooDoubleMap::get(2, 1).unwrap(),
2155				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4]).unwrap(),
2156			);
2157			assert_ok!(FooDoubleMap::try_append(2, 1, 5));
2158			assert_eq!(
2159				FooDoubleMap::get(2, 1).unwrap(),
2160				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4, 5]).unwrap(),
2161			);
2162		});
2163
2164		TestExternalities::default().execute_with(|| {
2165			let bounded: BoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
2166			FooQuadMap::insert((1, 1, 1, 1), bounded);
2167
2168			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 4));
2169			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 5));
2170			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 6));
2171			assert_ok!(FooQuadMap::try_append((1, 1, 1, 1), 7));
2172			assert_eq!(FooQuadMap::decode_len((1, 1, 1, 1)).unwrap(), 7);
2173			assert!(FooQuadMap::try_append((1, 1, 1, 1), 8).is_err());
2174
2175			// append to a non-existing
2176			assert!(FooQuadMap::get((2, 1, 1, 1)).is_none());
2177			assert_ok!(FooQuadMap::try_append((2, 1, 1, 1), 4));
2178			assert_eq!(
2179				FooQuadMap::get((2, 1, 1, 1)).unwrap(),
2180				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4]).unwrap(),
2181			);
2182			assert_ok!(FooQuadMap::try_append((2, 1, 1, 1), 5));
2183			assert_eq!(
2184				FooQuadMap::get((2, 1, 1, 1)).unwrap(),
2185				BoundedVec::<u32, ConstU32<7>>::try_from(vec![4, 5]).unwrap(),
2186			);
2187		});
2188	}
2189
2190	#[crate::storage_alias]
2191	type FooSet = StorageValue<Prefix, BTreeSet<u32>>;
2192
2193	#[test]
2194	fn btree_set_append_and_decode_len_works() {
2195		TestExternalities::default().execute_with(|| {
2196			let btree = BTreeSet::from([1, 2, 3]);
2197			FooSet::put(btree);
2198
2199			FooSet::append(4);
2200			FooSet::append(5);
2201			FooSet::append(6);
2202			FooSet::append(7);
2203
2204			assert_eq!(FooSet::decode_non_dedup_len().unwrap(), 7);
2205		});
2206	}
2207
2208	#[docify::export]
2209	#[test]
2210	fn btree_set_decode_non_dedup_len() {
2211		#[crate::storage_alias]
2212		type Store = StorageValue<Prefix, BTreeSet<u32>>;
2213
2214		TestExternalities::default().execute_with(|| {
2215			Store::append(4);
2216			Store::append(4); // duplicate value
2217			Store::append(5);
2218
2219			let length_with_dup_items = 3;
2220
2221			assert_eq!(Store::decode_non_dedup_len().unwrap(), length_with_dup_items);
2222		});
2223	}
2224}