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 PENDING_CODE: &[u8] = b":pending_code";
201
202 pub const HEAP_PAGES: &[u8] = b":heappages";
208
209 pub const EXTRINSIC_INDEX: &[u8] = b":extrinsic_index";
213
214 pub const INTRABLOCK_ENTROPY: &[u8] = b":intrablock_entropy";
218
219 pub const CHILD_STORAGE_KEY_PREFIX: &[u8] = b":child_storage:";
221
222 pub const DEFAULT_CHILD_STORAGE_KEY_PREFIX: &[u8] = b":child_storage:default:";
224
225 pub fn is_default_child_storage_key(key: &[u8]) -> bool {
230 key.starts_with(DEFAULT_CHILD_STORAGE_KEY_PREFIX)
231 }
232
233 pub fn is_child_storage_key(key: &[u8]) -> bool {
238 key.starts_with(CHILD_STORAGE_KEY_PREFIX)
240 }
241
242 pub fn starts_with_child_storage_key(key: &[u8]) -> bool {
244 if key.len() > CHILD_STORAGE_KEY_PREFIX.len() {
245 key.starts_with(CHILD_STORAGE_KEY_PREFIX)
246 } else {
247 CHILD_STORAGE_KEY_PREFIX.starts_with(key)
248 }
249 }
250}
251
252pub const TRIE_VALUE_NODE_THRESHOLD: u32 = 33;
254
255#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode, Debug, Clone)]
257pub enum ChildInfo {
258 ParentKeyId(ChildTrieParentKeyId),
260}
261
262impl ChildInfo {
263 pub fn new_default(storage_key: &[u8]) -> Self {
267 let data = storage_key.to_vec();
268 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data })
269 }
270
271 pub fn new_default_from_vec(storage_key: Vec<u8>) -> Self {
273 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data: storage_key })
274 }
275
276 pub fn try_update(&mut self, other: &ChildInfo) -> bool {
279 match self {
280 ChildInfo::ParentKeyId(child_trie) => child_trie.try_update(other),
281 }
282 }
283
284 #[inline]
288 pub fn keyspace(&self) -> &[u8] {
289 match self {
290 ChildInfo::ParentKeyId(..) => self.storage_key(),
291 }
292 }
293
294 pub fn storage_key(&self) -> &[u8] {
298 match self {
299 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data }) => &data[..],
300 }
301 }
302
303 pub fn prefixed_storage_key(&self) -> PrefixedStorageKey {
306 match self {
307 ChildInfo::ParentKeyId(ChildTrieParentKeyId { data }) => {
308 ChildType::ParentKeyId.new_prefixed_key(data.as_slice())
309 },
310 }
311 }
312
313 pub fn into_prefixed_storage_key(self) -> PrefixedStorageKey {
316 match self {
317 ChildInfo::ParentKeyId(ChildTrieParentKeyId { mut data }) => {
318 ChildType::ParentKeyId.do_prefix_key(&mut data);
319 PrefixedStorageKey(data)
320 },
321 }
322 }
323
324 pub fn child_type(&self) -> ChildType {
326 match self {
327 ChildInfo::ParentKeyId(..) => ChildType::ParentKeyId,
328 }
329 }
330}
331
332#[repr(u32)]
336#[derive(Clone, Copy, PartialEq)]
337#[cfg_attr(feature = "std", derive(Debug))]
338pub enum ChildType {
339 ParentKeyId = 1,
342}
343
344impl ChildType {
345 pub fn new(repr: u32) -> Option<ChildType> {
347 Some(match repr {
348 r if r == ChildType::ParentKeyId as u32 => ChildType::ParentKeyId,
349 _ => return None,
350 })
351 }
352
353 pub fn from_prefixed_key<'a>(storage_key: &'a PrefixedStorageKey) -> Option<(Self, &'a [u8])> {
356 let match_type = |storage_key: &'a [u8], child_type: ChildType| {
357 let prefix = child_type.parent_prefix();
358 if storage_key.starts_with(prefix) {
359 Some((child_type, &storage_key[prefix.len()..]))
360 } else {
361 None
362 }
363 };
364 match_type(storage_key, ChildType::ParentKeyId)
365 }
366
367 fn new_prefixed_key(&self, key: &[u8]) -> PrefixedStorageKey {
369 let parent_prefix = self.parent_prefix();
370 let mut result = Vec::with_capacity(parent_prefix.len() + key.len());
371 result.extend_from_slice(parent_prefix);
372 result.extend_from_slice(key);
373 PrefixedStorageKey(result)
374 }
375
376 fn do_prefix_key(&self, key: &mut Vec<u8>) {
378 let parent_prefix = self.parent_prefix();
379 let key_len = key.len();
380 if !parent_prefix.is_empty() {
381 key.resize(key_len + parent_prefix.len(), 0);
382 key.copy_within(..key_len, parent_prefix.len());
383 key[..parent_prefix.len()].copy_from_slice(parent_prefix);
384 }
385 }
386
387 pub fn parent_prefix(&self) -> &'static [u8] {
390 match self {
391 &ChildType::ParentKeyId => well_known_keys::DEFAULT_CHILD_STORAGE_KEY_PREFIX,
392 }
393 }
394}
395
396#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode, Debug, Clone)]
404pub struct ChildTrieParentKeyId {
405 data: Vec<u8>,
407}
408
409impl ChildTrieParentKeyId {
410 fn try_update(&mut self, other: &ChildInfo) -> bool {
413 match other {
414 ChildInfo::ParentKeyId(other) => self.data[..] == other.data[..],
415 }
416 }
417}
418
419#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
424#[cfg_attr(feature = "std", derive(Encode, Decode))]
425pub enum StateVersion {
426 V0 = 0,
428 #[default]
430 V1 = 1,
431}
432
433impl Display for StateVersion {
434 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
435 match self {
436 StateVersion::V0 => f.write_str("0"),
437 StateVersion::V1 => f.write_str("1"),
438 }
439 }
440}
441
442impl From<StateVersion> for u8 {
443 fn from(version: StateVersion) -> u8 {
444 version as u8
445 }
446}
447
448impl TryFrom<u8> for StateVersion {
449 type Error = ();
450 fn try_from(val: u8) -> core::result::Result<StateVersion, ()> {
451 match val {
452 0 => Ok(StateVersion::V0),
453 1 => Ok(StateVersion::V1),
454 2 => Ok(StateVersion::V1),
455 _ => Err(()),
456 }
457 }
458}
459
460impl StateVersion {
461 pub fn state_value_threshold(&self) -> Option<u32> {
466 match self {
467 StateVersion::V0 => None,
468 StateVersion::V1 => Some(TRIE_VALUE_NODE_THRESHOLD),
469 }
470 }
471}
472
473#[cfg(test)]
474mod tests {
475 use super::*;
476
477 #[test]
478 fn test_prefix_default_child_info() {
479 let child_info = ChildInfo::new_default(b"any key");
480 let prefix = child_info.child_type().parent_prefix();
481 assert!(prefix.starts_with(well_known_keys::CHILD_STORAGE_KEY_PREFIX));
482 assert!(prefix.starts_with(well_known_keys::DEFAULT_CHILD_STORAGE_KEY_PREFIX));
483 }
484}