1#![cfg_attr(not(feature = "std"), no_std)]
21
22extern crate alloc;
23
24#[cfg(feature = "serde")]
25use serde::{Deserialize, Serialize};
26
27use alloc::vec::Vec;
28use codec::{Decode, Encode};
29use core::{
30 fmt::Display,
31 ops::{Deref, DerefMut},
32};
33use ref_cast::RefCast;
34
35#[derive(PartialEq, Eq, Debug, Hash, PartialOrd, Ord, Clone, Encode, Decode)]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38pub struct StorageKey(
39 #[cfg_attr(feature = "serde", serde(with = "impl_serde::serialize"))] pub Vec<u8>,
40);
41
42impl AsRef<[u8]> for StorageKey {
43 fn as_ref(&self) -> &[u8] {
44 self.0.as_ref()
45 }
46}
47
48#[derive(PartialEq, Eq, Ord, PartialOrd, core::hash::Hash, Debug, Clone, Encode, Decode)]
50pub struct TrackedStorageKey {
51 pub key: Vec<u8>,
52 pub reads: u32,
53 pub writes: u32,
54 pub whitelisted: bool,
55}
56
57impl TrackedStorageKey {
58 pub fn new(key: Vec<u8>) -> Self {
60 Self { key, reads: 0, writes: 0, whitelisted: false }
61 }
62 pub fn has_been_read(&self) -> bool {
67 self.whitelisted || self.reads > 0u32 || self.has_been_written()
68 }
69 pub fn has_been_written(&self) -> bool {
73 self.whitelisted || self.writes > 0u32
74 }
75 pub fn add_read(&mut self) {
77 self.reads += 1;
78 }
79 pub fn add_write(&mut self) {
81 self.writes += 1;
82 }
83 pub fn whitelist(&mut self) {
85 self.whitelisted = true;
86 }
87}
88
89impl From<Vec<u8>> for TrackedStorageKey {
91 fn from(key: Vec<u8>) -> Self {
92 Self { key, reads: 0, writes: 0, whitelisted: true }
93 }
94}
95
96#[derive(PartialEq, Eq, Debug, Hash, PartialOrd, Ord, Clone)]
98#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
99#[repr(transparent)]
100#[derive(RefCast)]
101pub struct PrefixedStorageKey(
102 #[cfg_attr(feature = "serde", serde(with = "impl_serde::serialize"))] Vec<u8>,
103);
104
105impl Deref for PrefixedStorageKey {
106 type Target = Vec<u8>;
107
108 fn deref(&self) -> &Vec<u8> {
109 &self.0
110 }
111}
112
113impl DerefMut for PrefixedStorageKey {
114 fn deref_mut(&mut self) -> &mut Vec<u8> {
115 &mut self.0
116 }
117}
118
119impl PrefixedStorageKey {
120 pub fn new(inner: Vec<u8>) -> Self {
122 PrefixedStorageKey(inner)
123 }
124
125 pub fn new_ref(inner: &Vec<u8>) -> &Self {
127 PrefixedStorageKey::ref_cast(inner)
128 }
129
130 pub fn into_inner(self) -> Vec<u8> {
133 self.0
134 }
135}
136
137#[derive(PartialEq, Eq, Debug, Hash, PartialOrd, Ord, Clone, Encode, Decode, Default)]
139#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
140pub struct StorageData(
141 #[cfg_attr(feature = "serde", serde(with = "impl_serde::serialize"))] pub Vec<u8>,
142);
143
144pub type StorageMap = alloc::collections::BTreeMap<Vec<u8>, Vec<u8>>;
147
148#[cfg(feature = "std")]
150pub type ChildrenMap = std::collections::HashMap<Vec<u8>, StorageChild>;
151
152#[cfg(not(feature = "std"))]
153pub type ChildrenMap = alloc::collections::BTreeMap<Vec<u8>, StorageChild>;
154
155#[derive(Debug, PartialEq, Eq, Clone)]
157pub struct StorageChild {
158 pub data: StorageMap,
160 pub child_info: ChildInfo,
163}
164
165#[derive(Default, Debug, Clone)]
167pub struct Storage {
168 pub top: StorageMap,
170 pub children_default: ChildrenMap,
173}
174
175#[derive(Debug, PartialEq, Eq, Clone)]
177#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
178#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
179pub struct StorageChangeSet<Hash> {
180 pub block: Hash,
182 pub changes: Vec<(StorageKey, Option<StorageData>)>,
184}
185
186pub mod well_known_keys {
188 pub const CODE: &[u8] = b":code";
194
195 pub const HEAP_PAGES: &[u8] = b":heappages";
201
202 pub const EXTRINSIC_INDEX: &[u8] = b":extrinsic_index";
206
207 pub const INTRABLOCK_ENTROPY: &[u8] = b":intrablock_entropy";
211
212 pub const CHILD_STORAGE_KEY_PREFIX: &[u8] = b":child_storage:";
214
215 pub const DEFAULT_CHILD_STORAGE_KEY_PREFIX: &[u8] = b":child_storage:default:";
217
218 pub fn is_default_child_storage_key(key: &[u8]) -> bool {
223 key.starts_with(DEFAULT_CHILD_STORAGE_KEY_PREFIX)
224 }
225
226 pub fn is_child_storage_key(key: &[u8]) -> bool {
231 key.starts_with(CHILD_STORAGE_KEY_PREFIX)
233 }
234
235 pub fn starts_with_child_storage_key(key: &[u8]) -> bool {
237 if key.len() > CHILD_STORAGE_KEY_PREFIX.len() {
238 key.starts_with(CHILD_STORAGE_KEY_PREFIX)
239 } else {
240 CHILD_STORAGE_KEY_PREFIX.starts_with(key)
241 }
242 }
243}
244
245pub const TRIE_VALUE_NODE_THRESHOLD: u32 = 33;
247
248#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode, Debug, Clone)]
250pub enum ChildInfo {
251 ParentKeyId(ChildTrieParentKeyId),
253}
254
255impl ChildInfo {
256 pub fn new_default(storage_key: &[u8]) -> Self {
260 let data = storage_key.to_vec();
261 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data })
262 }
263
264 pub fn new_default_from_vec(storage_key: Vec<u8>) -> Self {
266 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data: storage_key })
267 }
268
269 pub fn try_update(&mut self, other: &ChildInfo) -> bool {
272 match self {
273 ChildInfo::ParentKeyId(child_trie) => child_trie.try_update(other),
274 }
275 }
276
277 #[inline]
281 pub fn keyspace(&self) -> &[u8] {
282 match self {
283 ChildInfo::ParentKeyId(..) => self.storage_key(),
284 }
285 }
286
287 pub fn storage_key(&self) -> &[u8] {
291 match self {
292 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data }) => &data[..],
293 }
294 }
295
296 pub fn prefixed_storage_key(&self) -> PrefixedStorageKey {
299 match self {
300 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data }) =>
301 ChildType::ParentKeyId.new_prefixed_key(data.as_slice()),
302 }
303 }
304
305 pub fn into_prefixed_storage_key(self) -> PrefixedStorageKey {
308 match self {
309 ChildInfo::ParentKeyId(ChildTrieParentKeyId { mut data }) => {
310 ChildType::ParentKeyId.do_prefix_key(&mut data);
311 PrefixedStorageKey(data)
312 },
313 }
314 }
315
316 pub fn child_type(&self) -> ChildType {
318 match self {
319 ChildInfo::ParentKeyId(..) => ChildType::ParentKeyId,
320 }
321 }
322}
323
324#[repr(u32)]
328#[derive(Clone, Copy, PartialEq)]
329#[cfg_attr(feature = "std", derive(Debug))]
330pub enum ChildType {
331 ParentKeyId = 1,
334}
335
336impl ChildType {
337 pub fn new(repr: u32) -> Option<ChildType> {
339 Some(match repr {
340 r if r == ChildType::ParentKeyId as u32 => ChildType::ParentKeyId,
341 _ => return None,
342 })
343 }
344
345 pub fn from_prefixed_key<'a>(storage_key: &'a PrefixedStorageKey) -> Option<(Self, &'a [u8])> {
348 let match_type = |storage_key: &'a [u8], child_type: ChildType| {
349 let prefix = child_type.parent_prefix();
350 if storage_key.starts_with(prefix) {
351 Some((child_type, &storage_key[prefix.len()..]))
352 } else {
353 None
354 }
355 };
356 match_type(storage_key, ChildType::ParentKeyId)
357 }
358
359 fn new_prefixed_key(&self, key: &[u8]) -> PrefixedStorageKey {
361 let parent_prefix = self.parent_prefix();
362 let mut result = Vec::with_capacity(parent_prefix.len() + key.len());
363 result.extend_from_slice(parent_prefix);
364 result.extend_from_slice(key);
365 PrefixedStorageKey(result)
366 }
367
368 fn do_prefix_key(&self, key: &mut Vec<u8>) {
370 let parent_prefix = self.parent_prefix();
371 let key_len = key.len();
372 if !parent_prefix.is_empty() {
373 key.resize(key_len + parent_prefix.len(), 0);
374 key.copy_within(..key_len, parent_prefix.len());
375 key[..parent_prefix.len()].copy_from_slice(parent_prefix);
376 }
377 }
378
379 pub fn parent_prefix(&self) -> &'static [u8] {
382 match self {
383 &ChildType::ParentKeyId => well_known_keys::DEFAULT_CHILD_STORAGE_KEY_PREFIX,
384 }
385 }
386}
387
388#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode, Debug, Clone)]
396pub struct ChildTrieParentKeyId {
397 data: Vec<u8>,
399}
400
401impl ChildTrieParentKeyId {
402 fn try_update(&mut self, other: &ChildInfo) -> bool {
405 match other {
406 ChildInfo::ParentKeyId(other) => self.data[..] == other.data[..],
407 }
408 }
409}
410
411#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
416#[cfg_attr(feature = "std", derive(Encode, Decode))]
417pub enum StateVersion {
418 V0 = 0,
420 #[default]
422 V1 = 1,
423}
424
425impl Display for StateVersion {
426 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
427 match self {
428 StateVersion::V0 => f.write_str("0"),
429 StateVersion::V1 => f.write_str("1"),
430 }
431 }
432}
433
434impl From<StateVersion> for u8 {
435 fn from(version: StateVersion) -> u8 {
436 version as u8
437 }
438}
439
440impl TryFrom<u8> for StateVersion {
441 type Error = ();
442 fn try_from(val: u8) -> core::result::Result<StateVersion, ()> {
443 match val {
444 0 => Ok(StateVersion::V0),
445 1 => Ok(StateVersion::V1),
446 2 => Ok(StateVersion::V1),
447 _ => Err(()),
448 }
449 }
450}
451
452impl StateVersion {
453 pub fn state_value_threshold(&self) -> Option<u32> {
458 match self {
459 StateVersion::V0 => None,
460 StateVersion::V1 => Some(TRIE_VALUE_NODE_THRESHOLD),
461 }
462 }
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468
469 #[test]
470 fn test_prefix_default_child_info() {
471 let child_info = ChildInfo::new_default(b"any key");
472 let prefix = child_info.child_type().parent_prefix();
473 assert!(prefix.starts_with(well_known_keys::CHILD_STORAGE_KEY_PREFIX));
474 assert!(prefix.starts_with(well_known_keys::DEFAULT_CHILD_STORAGE_KEY_PREFIX));
475 }
476}