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::{Encode, FullCodec, MaxEncodedLen};
22use core::marker::PhantomData;
23use impl_trait_for_tuples::impl_for_tuples;
24use scale_info::TypeInfo;
25pub use sp_core::storage::TrackedStorageKey;
26use sp_core::Get;
27use sp_runtime::{
28 traits::{Convert, Member, Saturating},
29 DispatchError, RuntimeDebug,
30};
31
32/// An instance of a pallet in the storage.
33///
34/// It is required that these instances are unique, to support multiple instances per pallet in the
35/// same runtime!
36///
37/// E.g. for module MyModule default instance will have prefix "MyModule" and other instances
38/// "InstanceNMyModule".
39pub trait Instance: 'static {
40 /// Unique module prefix. E.g. "InstanceNMyModule" or "MyModule"
41 const PREFIX: &'static str;
42 /// Unique numerical identifier for an instance.
43 const INDEX: u8;
44}
45
46// Dummy implementation for `()`.
47impl Instance for () {
48 const PREFIX: &'static str = "";
49 const INDEX: u8 = 0;
50}
51
52/// An instance of a storage in a pallet.
53///
54/// Define an instance for an individual storage inside a pallet.
55/// The pallet prefix is used to isolate the storage between pallets, and the storage prefix is
56/// used to isolate storages inside a pallet.
57///
58/// NOTE: These information can be used to define storages in pallet such as a `StorageMap` which
59/// can use keys after `twox_128(pallet_prefix())++twox_128(STORAGE_PREFIX)`
60pub trait StorageInstance {
61 /// Prefix of a pallet to isolate it from other pallets.
62 fn pallet_prefix() -> &'static str;
63
64 /// Return the prefix hash of pallet instance.
65 ///
66 /// NOTE: This hash must be `twox_128(pallet_prefix())`.
67 /// Should not impl this function by hand. Only use the default or macro generated impls.
68 fn pallet_prefix_hash() -> [u8; 16] {
69 sp_io::hashing::twox_128(Self::pallet_prefix().as_bytes())
70 }
71
72 /// Prefix given to a storage to isolate from other storages in the pallet.
73 const STORAGE_PREFIX: &'static str;
74
75 /// Return the prefix hash of storage instance.
76 ///
77 /// NOTE: This hash must be `twox_128(STORAGE_PREFIX)`.
78 fn storage_prefix_hash() -> [u8; 16] {
79 sp_io::hashing::twox_128(Self::STORAGE_PREFIX.as_bytes())
80 }
81
82 /// Return the prefix hash of instance.
83 ///
84 /// NOTE: This hash must be `twox_128(pallet_prefix())++twox_128(STORAGE_PREFIX)`.
85 /// Should not impl this function by hand. Only use the default or macro generated impls.
86 fn prefix_hash() -> [u8; 32] {
87 let mut final_key = [0u8; 32];
88 final_key[..16].copy_from_slice(&Self::pallet_prefix_hash());
89 final_key[16..].copy_from_slice(&Self::storage_prefix_hash());
90
91 final_key
92 }
93}
94
95/// Metadata about storage from the runtime.
96#[derive(Debug, codec::Encode, codec::Decode, Eq, PartialEq, Clone, scale_info::TypeInfo)]
97pub struct StorageInfo {
98 /// Encoded string of pallet name.
99 pub pallet_name: Vec<u8>,
100 /// Encoded string of storage name.
101 pub storage_name: Vec<u8>,
102 /// The prefix of the storage. All keys after the prefix are considered part of this storage.
103 pub prefix: Vec<u8>,
104 /// The maximum number of values in the storage, or none if no maximum specified.
105 pub max_values: Option<u32>,
106 /// The maximum size of key/values in the storage, or none if no maximum specified.
107 pub max_size: Option<u32>,
108}
109
110/// A trait to give information about storage.
111///
112/// It can be used to calculate PoV worst case size.
113pub trait StorageInfoTrait {
114 fn storage_info() -> Vec<StorageInfo>;
115}
116
117#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
118#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
119#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
120impl StorageInfoTrait for Tuple {
121 fn storage_info() -> Vec<StorageInfo> {
122 let mut res = vec![];
123 for_tuples!( #( res.extend_from_slice(&Tuple::storage_info()); )* );
124 res
125 }
126}
127
128/// Similar to [`StorageInfoTrait`], a trait to give partial information about storage.
129///
130/// This is useful when a type can give some partial information with its generic parameter doesn't
131/// implement some bounds.
132pub trait PartialStorageInfoTrait {
133 fn partial_storage_info() -> Vec<StorageInfo>;
134}
135
136/// Allows a pallet to specify storage keys to whitelist during benchmarking.
137/// This means those keys will be excluded from the benchmarking performance
138/// calculation.
139pub trait WhitelistedStorageKeys {
140 /// Returns a [`Vec<TrackedStorageKey>`] indicating the storage keys that
141 /// should be whitelisted during benchmarking. This means that those keys
142 /// will be excluded from the benchmarking performance calculation.
143 fn whitelisted_storage_keys() -> Vec<TrackedStorageKey>;
144}
145
146#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
147#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
148#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
149impl WhitelistedStorageKeys for Tuple {
150 fn whitelisted_storage_keys() -> Vec<TrackedStorageKey> {
151 // de-duplicate the storage keys
152 let mut combined_keys: BTreeSet<TrackedStorageKey> = BTreeSet::new();
153 for_tuples!( #(
154 for storage_key in Tuple::whitelisted_storage_keys() {
155 combined_keys.insert(storage_key);
156 }
157 )* );
158 combined_keys.into_iter().collect::<Vec<_>>()
159 }
160}
161
162/// The resource footprint of a bunch of blobs. We assume only the number of blobs and their total
163/// size in bytes matter.
164#[derive(Default, Copy, Clone, Eq, PartialEq, RuntimeDebug)]
165pub struct Footprint {
166 /// The number of blobs.
167 pub count: u64,
168 /// The total size of the blobs in bytes.
169 pub size: u64,
170}
171
172impl Footprint {
173 /// Construct a footprint directly from `items` and `len`.
174 pub fn from_parts(items: usize, len: usize) -> Self {
175 Self { count: items as u64, size: len as u64 }
176 }
177
178 /// Construct a footprint with one item, and size equal to the encoded size of `e`.
179 pub fn from_encodable(e: impl Encode) -> Self {
180 Self::from_parts(1, e.encoded_size())
181 }
182
183 /// Construct a footprint with one item, and size equal to the max encoded length of `E`.
184 pub fn from_mel<E: MaxEncodedLen>() -> Self {
185 Self::from_parts(1, E::max_encoded_len())
186 }
187}
188
189/// A storage price that increases linearly with the number of elements and their size.
190pub struct LinearStoragePrice<Base, Slope, Balance>(PhantomData<(Base, Slope, Balance)>);
191impl<Base, Slope, Balance> Convert<Footprint, Balance> for LinearStoragePrice<Base, Slope, Balance>
192where
193 Base: Get<Balance>,
194 Slope: Get<Balance>,
195 Balance: From<u64> + sp_runtime::Saturating,
196{
197 fn convert(a: Footprint) -> Balance {
198 let s: Balance = (a.count.saturating_mul(a.size)).into();
199 s.saturating_mul(Slope::get()).saturating_add(Base::get())
200 }
201}
202
203/// Some sort of cost taken from account temporarily in order to offset the cost to the chain of
204/// holding some data [`Footprint`] in state.
205///
206/// The cost may be increased, reduced or dropped entirely as the footprint changes.
207///
208/// A single ticket corresponding to some particular datum held in storage. This is an opaque
209/// type, but must itself be stored and generally it should be placed alongside whatever data
210/// the ticket was created for.
211///
212/// While not technically a linear type owing to the need for `FullCodec`, *this should be
213/// treated as one*. Don't type to duplicate it, and remember to drop it when you're done with
214/// it.
215#[must_use]
216pub trait Consideration<AccountId, Footprint>:
217 Member + FullCodec + TypeInfo + MaxEncodedLen
218{
219 /// Create a ticket for the `new` footprint attributable to `who`. This ticket *must* ultimately
220 /// be consumed through `update` or `drop` once the footprint changes or is removed.
221 fn new(who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
222
223 /// Optionally consume an old ticket and alter the footprint, enforcing the new cost to `who`
224 /// and returning the new ticket (or an error if there was an issue).
225 ///
226 /// For creating tickets and dropping them, you can use the simpler `new` and `drop` instead.
227 fn update(self, who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
228
229 /// Consume a ticket for some `old` footprint attributable to `who` which should now been freed.
230 fn drop(self, who: &AccountId) -> Result<(), DispatchError>;
231
232 /// Consume a ticket for some `old` footprint attributable to `who` which should be sacrificed.
233 ///
234 /// This is infallible. In the general case (and it is left unimplemented), then it is
235 /// equivalent to the consideration never being dropped. Cases which can handle this properly
236 /// should implement, but it *MUST* rely on the loss of the consideration to the owner.
237 fn burn(self, _: &AccountId) {
238 let _ = self;
239 }
240 /// Ensure that creating a ticket for a given account and footprint will be successful if done
241 /// immediately after this call.
242 #[cfg(feature = "runtime-benchmarks")]
243 fn ensure_successful(who: &AccountId, new: Footprint);
244}
245
246impl<A, F> Consideration<A, F> for () {
247 fn new(_: &A, _: F) -> Result<Self, DispatchError> {
248 Ok(())
249 }
250 fn update(self, _: &A, _: F) -> Result<(), DispatchError> {
251 Ok(())
252 }
253 fn drop(self, _: &A) -> Result<(), DispatchError> {
254 Ok(())
255 }
256 #[cfg(feature = "runtime-benchmarks")]
257 fn ensure_successful(_: &A, _: F) {}
258}
259
260#[cfg(feature = "experimental")]
261/// An extension of the [`Consideration`] trait that allows for the management of tickets that may
262/// represent no cost. While the [`MaybeConsideration`] still requires proper handling, it
263/// introduces the ability to determine if a ticket represents no cost and can be safely forgotten
264/// without any side effects.
265pub trait MaybeConsideration<AccountId, Footprint>: Consideration<AccountId, Footprint> {
266 /// Returns `true` if this [`Consideration`] represents a no-cost ticket and can be forgotten
267 /// without any side effects.
268 fn is_none(&self) -> bool;
269}
270
271#[cfg(feature = "experimental")]
272impl<A, F> MaybeConsideration<A, F> for () {
273 fn is_none(&self) -> bool {
274 true
275 }
276}
277
278macro_rules! impl_incrementable {
279 ($($type:ty),+) => {
280 $(
281 impl Incrementable for $type {
282 fn increment(&self) -> Option<Self> {
283 let mut val = self.clone();
284 val.saturating_inc();
285 Some(val)
286 }
287
288 fn initial_value() -> Option<Self> {
289 Some(0)
290 }
291 }
292 )+
293 };
294}
295
296/// A trait representing an incrementable type.
297///
298/// The `increment` and `initial_value` functions are fallible.
299/// They should either both return `Some` with a valid value, or `None`.
300pub trait Incrementable
301where
302 Self: Sized,
303{
304 /// Increments the value.
305 ///
306 /// Returns `Some` with the incremented value if it is possible, or `None` if it is not.
307 fn increment(&self) -> Option<Self>;
308
309 /// Returns the initial value.
310 ///
311 /// Returns `Some` with the initial value if it is available, or `None` if it is not.
312 fn initial_value() -> Option<Self>;
313}
314
315impl_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use crate::BoundedVec;
321 use sp_core::{ConstU32, ConstU64};
322
323 #[test]
324 fn linear_storage_price_works() {
325 type Linear = LinearStoragePrice<ConstU64<7>, ConstU64<3>, u64>;
326 let p = |count, size| Linear::convert(Footprint { count, size });
327
328 assert_eq!(p(0, 0), 7);
329 assert_eq!(p(0, 1), 7);
330 assert_eq!(p(1, 0), 7);
331
332 assert_eq!(p(1, 1), 10);
333 assert_eq!(p(8, 1), 31);
334 assert_eq!(p(1, 8), 31);
335
336 assert_eq!(p(u64::MAX, u64::MAX), u64::MAX);
337 }
338
339 #[test]
340 fn footprint_from_mel_works() {
341 let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<9>>)>();
342 let expected_size = BoundedVec::<u8, ConstU32<9>>::max_encoded_len() as u64;
343 assert_eq!(expected_size, 10);
344 assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
345
346 let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<999>>)>();
347 let expected_size = BoundedVec::<u8, ConstU32<999>>::max_encoded_len() as u64;
348 assert_eq!(expected_size, 1001);
349 assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
350 }
351}