Skip to main content

frame_support/traits/
storage.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//! Traits for encoding data related to pallet's storage items.
19
20use alloc::{collections::btree_set::BTreeSet, vec, vec::Vec};
21use codec::{Decode, DecodeWithMemTracking, Encode, FullCodec, MaxEncodedLen};
22use core::{marker::PhantomData, mem, ops::Drop};
23use frame_support::CloneNoBound;
24use impl_trait_for_tuples::impl_for_tuples;
25use scale_info::TypeInfo;
26pub use sp_core::storage::TrackedStorageKey;
27use sp_core::Get;
28use sp_runtime::{
29	traits::{Convert, Member},
30	Debug, DispatchError,
31};
32
33/// An instance of a pallet in the storage.
34///
35/// It is required that these instances are unique, to support multiple instances per pallet in the
36/// same runtime!
37///
38/// E.g. for module MyModule default instance will have prefix "MyModule" and other instances
39/// "InstanceNMyModule".
40pub trait Instance: 'static {
41	/// Unique module prefix. E.g. "InstanceNMyModule" or "MyModule"
42	const PREFIX: &'static str;
43	/// Unique numerical identifier for an instance.
44	const INDEX: u8;
45}
46
47// Dummy implementation for `()`.
48impl Instance for () {
49	const PREFIX: &'static str = "";
50	const INDEX: u8 = 0;
51}
52
53/// An instance of a storage in a pallet.
54///
55/// Define an instance for an individual storage inside a pallet.
56/// The pallet prefix is used to isolate the storage between pallets, and the storage prefix is
57/// used to isolate storages inside a pallet.
58///
59/// NOTE: These information can be used to define storages in pallet such as a `StorageMap` which
60/// can use keys after `twox_128(pallet_prefix())++twox_128(STORAGE_PREFIX)`
61pub trait StorageInstance {
62	/// Prefix of a pallet to isolate it from other pallets.
63	fn pallet_prefix() -> &'static str;
64
65	/// Return the prefix hash of pallet instance.
66	///
67	/// NOTE: This hash must be `twox_128(pallet_prefix())`.
68	/// Should not impl this function by hand. Only use the default or macro generated impls.
69	fn pallet_prefix_hash() -> [u8; 16] {
70		sp_io::hashing::twox_128(Self::pallet_prefix().as_bytes())
71	}
72
73	/// Prefix given to a storage to isolate from other storages in the pallet.
74	const STORAGE_PREFIX: &'static str;
75
76	/// Return the prefix hash of storage instance.
77	///
78	/// NOTE: This hash must be `twox_128(STORAGE_PREFIX)`.
79	fn storage_prefix_hash() -> [u8; 16] {
80		sp_io::hashing::twox_128(Self::STORAGE_PREFIX.as_bytes())
81	}
82
83	/// Return the prefix hash of instance.
84	///
85	/// NOTE: This hash must be `twox_128(pallet_prefix())++twox_128(STORAGE_PREFIX)`.
86	/// Should not impl this function by hand. Only use the default or macro generated impls.
87	fn prefix_hash() -> [u8; 32] {
88		let mut final_key = [0u8; 32];
89		final_key[..16].copy_from_slice(&Self::pallet_prefix_hash());
90		final_key[16..].copy_from_slice(&Self::storage_prefix_hash());
91
92		final_key
93	}
94}
95
96/// Metadata about storage from the runtime.
97#[derive(Debug, codec::Encode, codec::Decode, Eq, PartialEq, Clone, scale_info::TypeInfo)]
98pub struct StorageInfo {
99	/// Encoded string of pallet name.
100	pub pallet_name: Vec<u8>,
101	/// Encoded string of storage name.
102	pub storage_name: Vec<u8>,
103	/// The prefix of the storage. All keys after the prefix are considered part of this storage.
104	pub prefix: Vec<u8>,
105	/// The maximum number of values in the storage, or none if no maximum specified.
106	pub max_values: Option<u32>,
107	/// The maximum size of key/values in the storage, or none if no maximum specified.
108	pub max_size: Option<u32>,
109}
110
111/// A trait to give information about storage.
112///
113/// It can be used to calculate PoV worst case size.
114pub trait StorageInfoTrait {
115	fn storage_info() -> Vec<StorageInfo>;
116}
117
118#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
119#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
120#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
121impl StorageInfoTrait for Tuple {
122	fn storage_info() -> Vec<StorageInfo> {
123		let mut res = vec![];
124		for_tuples!( #( res.extend_from_slice(&Tuple::storage_info()); )* );
125		res
126	}
127}
128
129/// Similar to [`StorageInfoTrait`], a trait to give partial information about storage.
130///
131/// This is useful when a type can give some partial information with its generic parameter doesn't
132/// implement some bounds.
133pub trait PartialStorageInfoTrait {
134	fn partial_storage_info() -> Vec<StorageInfo>;
135}
136
137/// Allows a pallet to specify storage keys to whitelist during benchmarking.
138/// This means those keys will be excluded from the benchmarking performance
139/// calculation.
140pub trait WhitelistedStorageKeys {
141	/// Returns a [`Vec<TrackedStorageKey>`] indicating the storage keys that
142	/// should be whitelisted during benchmarking. This means that those keys
143	/// will be excluded from the benchmarking performance calculation.
144	fn whitelisted_storage_keys() -> Vec<TrackedStorageKey>;
145}
146
147#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
148#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
149#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
150impl WhitelistedStorageKeys for Tuple {
151	fn whitelisted_storage_keys() -> Vec<TrackedStorageKey> {
152		// de-duplicate the storage keys
153		let mut combined_keys: BTreeSet<TrackedStorageKey> = BTreeSet::new();
154		for_tuples!( #(
155			for storage_key in Tuple::whitelisted_storage_keys() {
156				combined_keys.insert(storage_key);
157			}
158		 )* );
159		combined_keys.into_iter().collect::<Vec<_>>()
160	}
161}
162
163/// The resource footprint of a bunch of blobs. We assume only the number of blobs and their total
164/// size in bytes matter.
165#[derive(
166	Default,
167	Copy,
168	Clone,
169	Eq,
170	PartialEq,
171	Debug,
172	TypeInfo,
173	MaxEncodedLen,
174	Decode,
175	Encode,
176	DecodeWithMemTracking,
177)]
178pub struct Footprint {
179	/// The number of blobs.
180	pub count: u64,
181	/// The total size of the blobs in bytes.
182	pub size: u64,
183}
184
185impl Footprint {
186	/// Construct a footprint directly from `items` and `len`.
187	pub fn from_parts(items: usize, len: usize) -> Self {
188		Self { count: items as u64, size: len as u64 }
189	}
190
191	/// Construct a footprint with one item, and size equal to the encoded size of `e`.
192	pub fn from_encodable(e: impl Encode) -> Self {
193		Self::from_parts(1, e.encoded_size())
194	}
195
196	/// Construct a footprint with one item, and size equal to the max encoded length of `E`.
197	pub fn from_mel<E: MaxEncodedLen>() -> Self {
198		Self::from_parts(1, E::max_encoded_len())
199	}
200}
201
202/// A storage price that increases linearly with the number of elements and their size.
203pub struct LinearStoragePrice<Base, Slope, Balance>(PhantomData<(Base, Slope, Balance)>);
204impl<Base, Slope, Balance> Convert<Footprint, Balance> for LinearStoragePrice<Base, Slope, Balance>
205where
206	Base: Get<Balance>,
207	Slope: Get<Balance>,
208	Balance: From<u64> + sp_runtime::Saturating,
209{
210	fn convert(a: Footprint) -> Balance {
211		let s: Balance = (a.count.saturating_mul(a.size)).into();
212		s.saturating_mul(Slope::get()).saturating_add(Base::get())
213	}
214}
215
216/// Constant `Price` regardless of the given [`Footprint`].
217pub struct ConstantStoragePrice<Price, Balance>(PhantomData<(Price, Balance)>);
218impl<Price, Balance> Convert<Footprint, Balance> for ConstantStoragePrice<Price, Balance>
219where
220	Price: Get<Balance>,
221	Balance: From<u64> + sp_runtime::Saturating,
222{
223	fn convert(_: Footprint) -> Balance {
224		Price::get()
225	}
226}
227
228/// Placeholder marking functionality disabled. Useful for disabling various (sub)features.
229#[derive(CloneNoBound, Debug, Encode, Eq, Decode, TypeInfo, MaxEncodedLen, PartialEq)]
230pub struct Disabled;
231impl<A, F> Consideration<A, F> for Disabled {
232	fn new(_: &A, _: F) -> Result<Self, DispatchError> {
233		Err(DispatchError::Other("Disabled"))
234	}
235	fn update(self, _: &A, _: F) -> Result<Self, DispatchError> {
236		Err(DispatchError::Other("Disabled"))
237	}
238	fn drop(self, _: &A) -> Result<(), DispatchError> {
239		Ok(())
240	}
241	#[cfg(feature = "runtime-benchmarks")]
242	fn ensure_successful(_: &A, _: F) {}
243}
244
245/// Some sort of cost taken from account temporarily in order to offset the cost to the chain of
246/// holding some data [`Footprint`] in state.
247///
248/// The cost may be increased, reduced or dropped entirely as the footprint changes.
249///
250/// A single ticket corresponding to some particular datum held in storage. This is an opaque
251/// type, but must itself be stored and generally it should be placed alongside whatever data
252/// the ticket was created for and the attributable account.
253///
254/// Tickets are generally attributable to a single account for their whole lifetime. Calling
255/// `update`, `burn` or `drop` with a different account than `new` was called with may result in
256/// wrong accounting since the ticket type is not required to store the attributable account.
257///
258/// While not technically a linear type owing to the need for `FullCodec`, *this should be
259/// treated as one*. Don't type to duplicate it, and remember to drop it when you're done with
260/// it.
261#[must_use]
262pub trait Consideration<AccountId, Footprint>:
263	Member + FullCodec + TypeInfo + MaxEncodedLen
264{
265	/// Create a ticket for the `new` footprint attributable to `who`. This ticket *must* ultimately
266	/// be consumed through `update` or `drop` once the footprint changes or is removed.
267	fn new(who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
268
269	/// Consume an old ticket to modify its footprint without altering the attributable account.
270	///
271	/// For creating tickets and dropping them, you can use the simpler `new` and `drop` instead.
272	/// Note that this must be called with the same account as `new` was.
273	fn update(self, who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
274
275	/// Consume a ticket for some `old` footprint attributable to `who` which should now been freed.
276	fn drop(self, who: &AccountId) -> Result<(), DispatchError>;
277
278	/// Consume a ticket for some `old` footprint attributable to `who` which should be sacrificed.
279	///
280	/// This is infallible. In the general case (and it is left unimplemented), then it is
281	/// equivalent to the consideration never being dropped. Cases which can handle this properly
282	/// should implement, but it *MUST* rely on the loss of the consideration to the owner.
283	fn burn(self, _: &AccountId) {
284		let _ = self;
285	}
286	/// Ensure that creating a ticket for a given account and footprint will be successful if done
287	/// immediately after this call.
288	#[cfg(feature = "runtime-benchmarks")]
289	fn ensure_successful(who: &AccountId, new: Footprint);
290}
291
292impl<A, F> Consideration<A, F> for () {
293	fn new(_: &A, _: F) -> Result<Self, DispatchError> {
294		Ok(())
295	}
296	fn update(self, _: &A, _: F) -> Result<(), DispatchError> {
297		Ok(())
298	}
299	fn drop(self, _: &A) -> Result<(), DispatchError> {
300		Ok(())
301	}
302	#[cfg(feature = "runtime-benchmarks")]
303	fn ensure_successful(_: &A, _: F) {}
304}
305
306#[cfg(feature = "experimental")]
307/// An extension of the [`Consideration`] trait that allows for the management of tickets that may
308/// represent no cost. While the [`MaybeConsideration`] still requires proper handling, it
309/// introduces the ability to determine if a ticket represents no cost and can be safely forgotten
310/// without any side effects.
311pub trait MaybeConsideration<AccountId, Footprint>: Consideration<AccountId, Footprint> {
312	/// Returns `true` if this [`Consideration`] represents a no-cost ticket and can be forgotten
313	/// without any side effects.
314	fn is_none(&self) -> bool;
315}
316
317#[cfg(feature = "experimental")]
318impl<A, F> MaybeConsideration<A, F> for () {
319	fn is_none(&self) -> bool {
320		true
321	}
322}
323
324macro_rules! impl_incrementable {
325	($($type:ty),+) => {
326		$(
327			impl Incrementable for $type {
328				fn increment(&self) -> Option<Self> {
329					self.checked_add(1)
330				}
331
332				fn initial_value() -> Option<Self> {
333					Some(0)
334				}
335			}
336		)+
337	};
338}
339
340/// A trait representing an incrementable type.
341///
342/// The `increment` and `initial_value` functions are fallible.
343/// They should either both return `Some` with a valid value, or `None`.
344pub trait Incrementable
345where
346	Self: Sized,
347{
348	/// Increments the value.
349	///
350	/// Returns `Some` with the incremented value if it is possible, or `None` if it is not.
351	fn increment(&self) -> Option<Self>;
352
353	/// Returns the initial value.
354	///
355	/// Returns `Some` with the initial value if it is available, or `None` if it is not.
356	fn initial_value() -> Option<Self>;
357}
358
359impl_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);
360
361/// Wrap a type so that is `Drop` impl is never called.
362///
363/// Useful when storing types like `Imbalance` which would trigger their `Drop`
364/// implementation whenever they are written to storage as they are dropped after
365/// being serialized.
366#[derive(Default, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo)]
367pub struct NoDrop<T: Default>(T);
368
369impl<T: Default> Drop for NoDrop<T> {
370	fn drop(&mut self) {
371		mem::forget(mem::take(&mut self.0))
372	}
373}
374
375/// Sealed trait that marks a type with a suppressed Drop implementation.
376///
377/// Useful for constraining your storage items types by this bound to make
378/// sure they won't run drop when stored.
379pub trait SuppressedDrop: sealed::Sealed {
380	/// The wrapped whose drop function is ignored.
381	type Inner;
382
383	fn new(inner: Self::Inner) -> Self;
384	fn as_ref(&self) -> &Self::Inner;
385	fn as_mut(&mut self) -> &mut Self::Inner;
386	fn into_inner(self) -> Self::Inner;
387}
388
389impl SuppressedDrop for () {
390	type Inner = ();
391
392	fn new(inner: Self::Inner) -> Self {
393		inner
394	}
395
396	fn as_ref(&self) -> &Self::Inner {
397		self
398	}
399
400	fn as_mut(&mut self) -> &mut Self::Inner {
401		self
402	}
403
404	fn into_inner(self) -> Self::Inner {
405		self
406	}
407}
408
409impl<T: Default> SuppressedDrop for NoDrop<T> {
410	type Inner = T;
411
412	fn as_ref(&self) -> &Self::Inner {
413		&self.0
414	}
415
416	fn as_mut(&mut self) -> &mut Self::Inner {
417		&mut self.0
418	}
419
420	fn into_inner(mut self) -> Self::Inner {
421		mem::take(&mut self.0)
422	}
423
424	fn new(inner: Self::Inner) -> Self {
425		Self(inner)
426	}
427}
428
429mod sealed {
430	pub trait Sealed {}
431	impl Sealed for () {}
432	impl<T: Default> Sealed for super::NoDrop<T> {}
433}
434
435#[cfg(test)]
436mod tests {
437	use super::*;
438	use crate::BoundedVec;
439	use sp_core::{ConstU32, ConstU64};
440
441	#[test]
442	fn incrementable_works() {
443		assert_eq!(0u8.increment(), Some(1));
444		assert_eq!(1u8.increment(), Some(2));
445
446		assert_eq!(u8::MAX.increment(), None);
447	}
448
449	#[test]
450	fn linear_storage_price_works() {
451		type Linear = LinearStoragePrice<ConstU64<7>, ConstU64<3>, u64>;
452		let p = |count, size| Linear::convert(Footprint { count, size });
453
454		assert_eq!(p(0, 0), 7);
455		assert_eq!(p(0, 1), 7);
456		assert_eq!(p(1, 0), 7);
457
458		assert_eq!(p(1, 1), 10);
459		assert_eq!(p(8, 1), 31);
460		assert_eq!(p(1, 8), 31);
461
462		assert_eq!(p(u64::MAX, u64::MAX), u64::MAX);
463	}
464
465	#[test]
466	fn footprint_from_mel_works() {
467		let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<9>>)>();
468		let expected_size = BoundedVec::<u8, ConstU32<9>>::max_encoded_len() as u64;
469		assert_eq!(expected_size, 10);
470		assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
471
472		let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<999>>)>();
473		let expected_size = BoundedVec::<u8, ConstU32<999>>::max_encoded_len() as u64;
474		assert_eq!(expected_size, 1001);
475		assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
476	}
477}