1mod changeset;
21mod offchain;
22
23use self::changeset::OverlayedChangeSet;
24use crate::{backend::Backend, stats::StateMachineStats, BackendTransaction, DefaultError};
25use alloc::{collections::btree_set::BTreeSet, vec::Vec};
26use codec::{Decode, Encode};
27use hash_db::Hasher;
28pub use offchain::OffchainOverlayedChanges;
29use sp_core::{
30 offchain::OffchainOverlayedChange,
31 storage::{well_known_keys::EXTRINSIC_INDEX, ChildInfo, StateVersion},
32};
33#[cfg(feature = "std")]
34use sp_externalities::{Extension, Extensions, TransactionType};
35use sp_trie::{empty_child_trie_root, LayoutV1};
36
37#[cfg(not(feature = "std"))]
38use alloc::collections::btree_map::BTreeMap as Map;
39#[cfg(feature = "std")]
40use std::collections::{hash_map::Entry as MapEntry, HashMap as Map};
41
42#[cfg(feature = "std")]
43use std::{
44 any::{Any, TypeId},
45 boxed::Box,
46};
47
48pub use self::changeset::{AlreadyInRuntime, NoOpenTransaction, NotInRuntime, OverlayedValue};
49
50pub const NO_EXTRINSIC_INDEX: u32 = 0xffffffff;
52
53pub type StorageKey = Vec<u8>;
55
56pub type StorageValue = Vec<u8>;
58
59pub type StorageCollection = Vec<(StorageKey, Option<StorageValue>)>;
61
62pub type ChildStorageCollection = Vec<(StorageKey, StorageCollection)>;
64
65pub type OffchainChangesCollection = Vec<((Vec<u8>, Vec<u8>), OffchainOverlayedChange)>;
67
68#[derive(Debug, Default, Eq, PartialEq, Clone)]
70pub struct Extrinsics(Vec<u32>);
71
72impl Extrinsics {
73 fn copy_extrinsics_into(&self, dest: &mut BTreeSet<u32>) {
75 dest.extend(self.0.iter())
76 }
77
78 fn insert(&mut self, ext: u32) {
80 if Some(&ext) != self.0.last() {
81 self.0.push(ext);
82 }
83 }
84
85 fn extend(&mut self, other: Self) {
87 self.0.extend(other.0.into_iter());
88 }
89}
90
91pub struct OverlayedChanges<H: Hasher> {
95 top: OverlayedChangeSet,
97 children: Map<StorageKey, (OverlayedChangeSet, ChildInfo)>,
99 offchain: OffchainOverlayedChanges,
101 transaction_index_ops: Vec<IndexOperation>,
103 transaction_index_ops_checkpoints: Vec<usize>,
105 collect_extrinsics: bool,
107 stats: StateMachineStats,
109 storage_transaction_cache: Option<StorageTransactionCache<H>>,
113}
114
115impl<H: Hasher> Default for OverlayedChanges<H> {
116 fn default() -> Self {
117 Self {
118 top: Default::default(),
119 children: Default::default(),
120 offchain: Default::default(),
121 transaction_index_ops: Default::default(),
122 transaction_index_ops_checkpoints: Default::default(),
123 collect_extrinsics: Default::default(),
124 stats: Default::default(),
125 storage_transaction_cache: None,
126 }
127 }
128}
129
130impl<H: Hasher> Clone for OverlayedChanges<H> {
131 fn clone(&self) -> Self {
132 Self {
133 top: self.top.clone(),
134 children: self.children.clone(),
135 offchain: self.offchain.clone(),
136 transaction_index_ops: self.transaction_index_ops.clone(),
137 transaction_index_ops_checkpoints: self.transaction_index_ops_checkpoints.clone(),
138 collect_extrinsics: self.collect_extrinsics,
139 stats: self.stats.clone(),
140 storage_transaction_cache: self.storage_transaction_cache.clone(),
141 }
142 }
143}
144
145impl<H: Hasher> core::fmt::Debug for OverlayedChanges<H> {
146 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
147 f.debug_struct("OverlayedChanges")
148 .field("top", &self.top)
149 .field("children", &self.children)
150 .field("offchain", &self.offchain)
151 .field("transaction_index_ops", &self.transaction_index_ops)
152 .field("collect_extrinsics", &self.collect_extrinsics)
153 .field("stats", &self.stats)
154 .field("storage_transaction_cache", &self.storage_transaction_cache)
155 .finish()
156 }
157}
158
159#[derive(Debug, Clone)]
161pub enum IndexOperation {
162 Insert {
164 extrinsic: u32,
166 hash: Vec<u8>,
168 size: u32,
170 },
171 Renew {
173 extrinsic: u32,
175 hash: Vec<u8>,
177 },
178}
179
180pub struct StorageChanges<H: Hasher> {
185 pub main_storage_changes: StorageCollection,
189 pub child_storage_changes: ChildStorageCollection,
191 pub offchain_storage_changes: OffchainChangesCollection,
193 pub transaction: BackendTransaction<H>,
198 pub transaction_storage_root: H::Out,
200 #[cfg(feature = "std")]
202 pub transaction_index_changes: Vec<IndexOperation>,
203}
204
205#[cfg(feature = "std")]
206impl<H: Hasher> StorageChanges<H> {
207 pub fn into_inner(
209 self,
210 ) -> (
211 StorageCollection,
212 ChildStorageCollection,
213 OffchainChangesCollection,
214 BackendTransaction<H>,
215 H::Out,
216 Vec<IndexOperation>,
217 ) {
218 (
219 self.main_storage_changes,
220 self.child_storage_changes,
221 self.offchain_storage_changes,
222 self.transaction,
223 self.transaction_storage_root,
224 self.transaction_index_changes,
225 )
226 }
227}
228
229impl<H: Hasher> Default for StorageChanges<H> {
230 fn default() -> Self {
231 Self {
232 main_storage_changes: Default::default(),
233 child_storage_changes: Default::default(),
234 offchain_storage_changes: Default::default(),
235 transaction: BackendTransaction::with_hasher(Default::default()),
236 transaction_storage_root: Default::default(),
237 #[cfg(feature = "std")]
238 transaction_index_changes: Default::default(),
239 }
240 }
241}
242
243struct StorageTransactionCache<H: Hasher> {
247 transaction: BackendTransaction<H>,
249 transaction_storage_root: H::Out,
251 state_version: StateVersion,
253}
254
255impl<H: Hasher> StorageTransactionCache<H> {
256 fn into_inner(self) -> (BackendTransaction<H>, H::Out) {
257 (self.transaction, self.transaction_storage_root)
258 }
259}
260
261impl<H: Hasher> Clone for StorageTransactionCache<H> {
262 fn clone(&self) -> Self {
263 Self {
264 transaction: self.transaction.clone(),
265 transaction_storage_root: self.transaction_storage_root,
266 state_version: self.state_version,
267 }
268 }
269}
270
271impl<H: Hasher> core::fmt::Debug for StorageTransactionCache<H> {
272 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
273 let mut debug = f.debug_struct("StorageTransactionCache");
274
275 #[cfg(feature = "std")]
276 debug.field("transaction_storage_root", &self.transaction_storage_root);
277
278 #[cfg(not(feature = "std"))]
279 debug.field("transaction_storage_root", &self.transaction_storage_root.as_ref());
280
281 debug.finish()
282 }
283}
284
285impl<H: Hasher> OverlayedChanges<H> {
286 pub fn is_empty(&self) -> bool {
288 self.top.is_empty() && self.children.is_empty()
289 }
290
291 pub fn set_collect_extrinsics(&mut self, collect_extrinsics: bool) {
293 self.collect_extrinsics = collect_extrinsics;
294 }
295
296 pub fn storage(&mut self, key: &[u8]) -> Option<Option<&[u8]>> {
300 self.top.get(key).map(|x| {
301 let value = x.value();
302 let size_read = value.map(|x| x.len() as u64).unwrap_or(0);
303 self.stats.tally_read_modified(size_read);
304 value.map(AsRef::as_ref)
305 })
306 }
307
308 fn mark_dirty(&mut self) {
311 self.storage_transaction_cache = None;
312 }
313
314 pub fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option<Option<&[u8]>> {
318 let map = self.children.get_mut(child_info.storage_key())?;
319 let value = map.0.get(key)?.value();
320 let size_read = value.map(|x| x.len() as u64).unwrap_or(0);
321 self.stats.tally_read_modified(size_read);
322 Some(value.map(AsRef::as_ref))
323 }
324
325 pub fn set_storage(&mut self, key: StorageKey, val: Option<StorageValue>) {
329 self.mark_dirty();
330
331 let size_write = val.as_ref().map(|x| x.len() as u64).unwrap_or(0);
332 self.stats.tally_write_overlay(size_write);
333 let extrinsic_index = self.extrinsic_index();
334 self.top.set(key, val, extrinsic_index);
335 }
336
337 pub fn append_storage(
339 &mut self,
340 key: StorageKey,
341 element: StorageValue,
342 init: impl Fn() -> StorageValue,
343 ) {
344 let extrinsic_index = self.extrinsic_index();
345 let size_write = element.len() as u64;
346 self.stats.tally_write_overlay(size_write);
347 self.top.append_storage(key, element, init, extrinsic_index);
348 }
349
350 pub fn set_child_storage(
356 &mut self,
357 child_info: &ChildInfo,
358 key: StorageKey,
359 val: Option<StorageValue>,
360 ) {
361 self.mark_dirty();
362
363 let extrinsic_index = self.extrinsic_index();
364 let size_write = val.as_ref().map(|x| x.len() as u64).unwrap_or(0);
365 self.stats.tally_write_overlay(size_write);
366 let storage_key = child_info.storage_key().to_vec();
367 let top = &self.top;
368 let (changeset, info) = self
369 .children
370 .entry(storage_key)
371 .or_insert_with(|| (top.spawn_child(), child_info.clone()));
372 let updatable = info.try_update(child_info);
373 debug_assert!(updatable);
374 changeset.set(key, val, extrinsic_index);
375 }
376
377 pub fn clear_child_storage(&mut self, child_info: &ChildInfo) -> u32 {
381 self.mark_dirty();
382
383 let extrinsic_index = self.extrinsic_index();
384 let storage_key = child_info.storage_key().to_vec();
385 let top = &self.top;
386 let (changeset, info) = self
387 .children
388 .entry(storage_key)
389 .or_insert_with(|| (top.spawn_child(), child_info.clone()));
390 let updatable = info.try_update(child_info);
391 debug_assert!(updatable);
392 changeset.clear_where(|_, _| true, extrinsic_index)
393 }
394
395 pub fn clear_prefix(&mut self, prefix: &[u8]) -> u32 {
399 self.mark_dirty();
400
401 let extrinsic_index = self.extrinsic_index();
402 self.top.clear_where(|key, _| key.starts_with(prefix), extrinsic_index)
403 }
404
405 pub fn clear_child_prefix(&mut self, child_info: &ChildInfo, prefix: &[u8]) -> u32 {
409 self.mark_dirty();
410
411 let extrinsic_index = self.extrinsic_index();
412 let storage_key = child_info.storage_key().to_vec();
413 let top = &self.top;
414 let (changeset, info) = self
415 .children
416 .entry(storage_key)
417 .or_insert_with(|| (top.spawn_child(), child_info.clone()));
418 let updatable = info.try_update(child_info);
419 debug_assert!(updatable);
420 changeset.clear_where(|key, _| key.starts_with(prefix), extrinsic_index)
421 }
422
423 pub fn transaction_depth(&self) -> usize {
427 self.top.transaction_depth()
430 }
431
432 pub fn start_transaction(&mut self) {
440 self.top.start_transaction();
441 for (_, (changeset, _)) in self.children.iter_mut() {
442 changeset.start_transaction();
443 }
444 self.offchain.overlay_mut().start_transaction();
445 self.transaction_index_ops_checkpoints.push(self.transaction_index_ops.len());
446 }
447
448 pub fn rollback_transaction(&mut self) -> Result<(), NoOpenTransaction> {
453 self.mark_dirty();
454
455 self.top.rollback_transaction()?;
456 retain_map(&mut self.children, |_, (changeset, _)| {
457 changeset
458 .rollback_transaction()
459 .expect("Top and children changesets are started in lockstep; qed");
460 !changeset.is_empty()
461 });
462 self.offchain
463 .overlay_mut()
464 .rollback_transaction_offchain()
465 .expect("Top and offchain changesets are started in lockstep; qed");
466 self.rollback_transaction_index_ops_to_depth(self.top.transaction_depth());
467 Ok(())
468 }
469
470 pub fn commit_transaction(&mut self) -> Result<(), NoOpenTransaction> {
475 self.top.commit_transaction()?;
476 for (_, (changeset, _)) in self.children.iter_mut() {
477 changeset
478 .commit_transaction()
479 .expect("Top and children changesets are started in lockstep; qed");
480 }
481 self.offchain
482 .overlay_mut()
483 .commit_transaction_offchain()
484 .expect("Top and offchain changesets are started in lockstep; qed");
485 self.transaction_index_ops_checkpoints.pop();
486 Ok(())
487 }
488
489 pub fn enter_runtime(&mut self) -> Result<(), AlreadyInRuntime> {
494 self.top.enter_runtime()?;
495 for (_, (changeset, _)) in self.children.iter_mut() {
496 changeset
497 .enter_runtime()
498 .expect("Top and children changesets are entering runtime in lockstep; qed")
499 }
500 self.offchain
501 .overlay_mut()
502 .enter_runtime()
503 .expect("Top and offchain changesets are started in lockstep; qed");
504 Ok(())
505 }
506
507 pub fn exit_runtime(&mut self) -> Result<(), NotInRuntime> {
512 self.top.exit_runtime()?;
513 for (_, (changeset, _)) in self.children.iter_mut() {
514 changeset
515 .exit_runtime()
516 .expect("Top and children changesets are entering runtime in lockstep; qed");
517 }
518 self.offchain
519 .overlay_mut()
520 .exit_runtime_offchain()
521 .expect("Top and offchain changesets are started in lockstep; qed");
522 self.rollback_transaction_index_ops_to_depth(self.top.transaction_depth());
523 Ok(())
524 }
525
526 fn rollback_transaction_index_ops_to_depth(&mut self, depth: usize) {
527 let oldest_rolled_back = self.transaction_index_ops_checkpoints.drain(depth..).next();
528 if let Some(ops_len) = oldest_rolled_back {
529 self.transaction_index_ops.truncate(ops_len);
530 }
531 }
532
533 pub fn offchain_drain_committed(
540 &mut self,
541 ) -> impl Iterator<Item = ((StorageKey, StorageKey), OffchainOverlayedChange)> {
542 self.offchain.drain()
543 }
544
545 pub fn children(
547 &self,
548 ) -> impl Iterator<Item = (impl Iterator<Item = (&StorageKey, &OverlayedValue)>, &ChildInfo)> {
549 self.children.values().map(|v| (v.0.changes(), &v.1))
550 }
551
552 pub fn children_mut(
554 &mut self,
555 ) -> impl Iterator<Item = (impl Iterator<Item = (&StorageKey, &mut OverlayedValue)>, &ChildInfo)>
556 {
557 self.children.values_mut().map(|v| (v.0.changes_mut(), &v.1))
558 }
559
560 pub fn changes(&self) -> impl Iterator<Item = (&StorageKey, &OverlayedValue)> {
562 self.top.changes()
563 }
564
565 pub fn changes_mut(&mut self) -> impl Iterator<Item = (&StorageKey, &mut OverlayedValue)> {
567 self.top.changes_mut()
568 }
569
570 pub fn child_changes(
572 &self,
573 key: &[u8],
574 ) -> Option<(impl Iterator<Item = (&StorageKey, &OverlayedValue)>, &ChildInfo)> {
575 self.children.get(key).map(|(overlay, info)| (overlay.changes(), info))
576 }
577
578 pub fn child_changes_mut(
580 &mut self,
581 key: &[u8],
582 ) -> Option<(impl Iterator<Item = (&StorageKey, &mut OverlayedValue)>, &ChildInfo)> {
583 self.children
584 .get_mut(key)
585 .map(|(overlay, info)| (overlay.changes_mut(), &*info))
586 }
587
588 pub fn transaction_index_ops(&self) -> &[IndexOperation] {
590 &self.transaction_index_ops
591 }
592
593 pub fn drain_storage_changes<B: Backend<H>>(
595 &mut self,
596 backend: &B,
597 state_version: StateVersion,
598 ) -> Result<StorageChanges<H>, DefaultError>
599 where
600 H::Out: Ord + Encode + 'static,
601 {
602 let (transaction, transaction_storage_root) = match self.storage_transaction_cache.take() {
603 Some(cache) => cache.into_inner(),
604 None => {
606 self.storage_root(backend, state_version);
607 self.storage_transaction_cache
608 .take()
609 .expect("`storage_transaction_cache` was just initialized; qed")
610 .into_inner()
611 },
612 };
613
614 use core::mem::take;
615 let main_storage_changes =
616 take(&mut self.top).drain_committed().map(|(k, v)| (k, v.to_option()));
617 let child_storage_changes =
618 take(&mut self.children).into_iter().map(|(key, (val, info))| {
619 (key, (val.drain_committed().map(|(k, v)| (k, v.to_option())), info))
620 });
621 let offchain_storage_changes = self.offchain_drain_committed().collect();
622
623 #[cfg(feature = "std")]
624 let transaction_index_changes = std::mem::take(&mut self.transaction_index_ops);
625
626 Ok(StorageChanges {
627 main_storage_changes: main_storage_changes.collect(),
628 child_storage_changes: child_storage_changes
629 .map(|(sk, it)| (sk, it.0.collect()))
630 .collect(),
631 offchain_storage_changes,
632 transaction,
633 transaction_storage_root,
634 #[cfg(feature = "std")]
635 transaction_index_changes,
636 })
637 }
638
639 #[cfg(test)]
641 pub(crate) fn set_extrinsic_index(&mut self, extrinsic_index: u32) {
642 self.top.set(EXTRINSIC_INDEX.to_vec(), Some(extrinsic_index.encode()), None);
643 }
644
645 fn extrinsic_index(&mut self) -> Option<u32> {
652 self.collect_extrinsics.then(|| {
653 self.storage(EXTRINSIC_INDEX)
654 .and_then(|idx| idx.and_then(|idx| Decode::decode(&mut &*idx).ok()))
655 .unwrap_or(NO_EXTRINSIC_INDEX)
656 })
657 }
658
659 pub fn storage_root<B: Backend<H>>(
664 &mut self,
665 backend: &B,
666 state_version: StateVersion,
667 ) -> (H::Out, bool)
668 where
669 H::Out: Ord + Encode,
670 {
671 if let Some(cache) = &self.storage_transaction_cache {
672 if cache.state_version == state_version {
673 return (cache.transaction_storage_root, true);
674 }
675 }
676
677 let delta = self.top.changes_mut().map(|(k, v)| (&k[..], v.value().map(|v| &v[..])));
678
679 let child_delta = self
680 .children
681 .values_mut()
682 .map(|v| (&v.1, v.0.changes_mut().map(|(k, v)| (&k[..], v.value().map(|v| &v[..])))));
683
684 let (root, transaction) = backend.full_storage_root(delta, child_delta, state_version);
685
686 self.storage_transaction_cache = Some(StorageTransactionCache {
687 transaction,
688 transaction_storage_root: root,
689 state_version,
690 });
691
692 (root, false)
693 }
694
695 pub fn child_storage_root<B: Backend<H>>(
700 &mut self,
701 child_info: &ChildInfo,
702 backend: &B,
703 state_version: StateVersion,
704 ) -> Result<(H::Out, bool), B::Error>
705 where
706 H::Out: Ord + Encode + Decode,
707 {
708 let storage_key = child_info.storage_key();
709 let prefixed_storage_key = child_info.prefixed_storage_key();
710
711 if self.storage_transaction_cache.is_some() {
712 let root = self
713 .storage(prefixed_storage_key.as_slice())
714 .map(|v| Ok(v.map(|v| v.to_vec())))
715 .or_else(|| backend.storage(prefixed_storage_key.as_slice()).map(Some).transpose())
716 .transpose()?
717 .flatten()
718 .and_then(|k| Decode::decode(&mut &k[..]).ok())
719 .unwrap_or_else(empty_child_trie_root::<LayoutV1<H>>);
721
722 return Ok((root, true));
723 }
724
725 let root = if let Some((changes, info)) = self.child_changes_mut(storage_key) {
726 let delta = changes.map(|(k, v)| (k.as_ref(), v.value().map(AsRef::as_ref)));
727 Some(backend.child_storage_root(info, delta, state_version))
728 } else {
729 None
730 };
731
732 let root = if let Some((root, is_empty, _)) = root {
733 self.set_storage(prefixed_storage_key.into_inner(), (!is_empty).then(|| root.encode()));
739
740 self.mark_dirty();
741
742 root
743 } else {
744 let root = backend
746 .storage(prefixed_storage_key.as_slice())?
747 .and_then(|k| Decode::decode(&mut &k[..]).ok())
748 .unwrap_or_else(empty_child_trie_root::<LayoutV1<H>>);
750
751 root
752 };
753
754 Ok((root, false))
755 }
756
757 pub fn iter_after(&mut self, key: &[u8]) -> impl Iterator<Item = (&[u8], &mut OverlayedValue)> {
760 self.top.changes_after(key)
761 }
762
763 pub fn child_iter_after(
766 &mut self,
767 storage_key: &[u8],
768 key: &[u8],
769 ) -> impl Iterator<Item = (&[u8], &mut OverlayedValue)> {
770 self.children
771 .get_mut(storage_key)
772 .map(|(overlay, _)| overlay.changes_after(key))
773 .into_iter()
774 .flatten()
775 }
776
777 pub fn offchain(&self) -> &OffchainOverlayedChanges {
779 &self.offchain
780 }
781
782 pub fn set_offchain_storage(&mut self, key: &[u8], value: Option<&[u8]>) {
784 use sp_core::offchain::STORAGE_PREFIX;
785 match value {
786 Some(value) => self.offchain.set(STORAGE_PREFIX, key, value),
787 None => self.offchain.remove(STORAGE_PREFIX, key),
788 }
789 }
790
791 pub fn add_transaction_index(&mut self, op: IndexOperation) {
793 self.transaction_index_ops.push(op)
794 }
795}
796
797#[cfg(not(substrate_runtime))]
798impl<H: Hasher> From<sp_core::storage::Storage> for OverlayedChanges<H> {
799 fn from(storage: sp_core::storage::Storage) -> Self {
800 Self {
801 top: storage.top.into(),
802 children: storage
803 .children_default
804 .into_iter()
805 .map(|(k, v)| (k, (v.data.into(), v.child_info)))
806 .collect(),
807 ..Default::default()
808 }
809 }
810}
811
812#[cfg(feature = "std")]
813fn retain_map<K, V, F>(map: &mut Map<K, V>, f: F)
814where
815 K: std::cmp::Eq + std::hash::Hash,
816 F: FnMut(&K, &mut V) -> bool,
817{
818 map.retain(f);
819}
820
821#[cfg(not(feature = "std"))]
822fn retain_map<K, V, F>(map: &mut Map<K, V>, mut f: F)
823where
824 K: Ord,
825 F: FnMut(&K, &mut V) -> bool,
826{
827 let old = core::mem::replace(map, Map::default());
828 for (k, mut v) in old.into_iter() {
829 if f(&k, &mut v) {
830 map.insert(k, v);
831 }
832 }
833}
834
835#[cfg(feature = "std")]
838pub enum OverlayedExtension<'a> {
839 MutRef(&'a mut Box<dyn Extension>),
840 Owned(Box<dyn Extension>),
841}
842
843#[cfg(feature = "std")]
844impl OverlayedExtension<'_> {
845 fn extension(&mut self) -> &mut dyn Extension {
846 match self {
847 Self::MutRef(ext) => *ext,
848 Self::Owned(ext) => &mut *ext,
849 }
850 }
851}
852
853#[cfg(feature = "std")]
861pub struct OverlayedExtensions<'a> {
862 extensions: Map<TypeId, OverlayedExtension<'a>>,
863}
864
865#[cfg(feature = "std")]
866impl<'a> OverlayedExtensions<'a> {
867 pub fn new(extensions: &'a mut Extensions) -> Self {
869 Self {
870 extensions: extensions
871 .iter_mut()
872 .map(|(k, v)| (*k, OverlayedExtension::MutRef(v)))
873 .collect(),
874 }
875 }
876
877 pub fn get_mut(&mut self, ext_type_id: TypeId) -> Option<&mut dyn Any> {
879 self.extensions.get_mut(&ext_type_id).map(|ext| match ext {
880 OverlayedExtension::MutRef(ext) => ext.as_mut_any(),
881 OverlayedExtension::Owned(ext) => ext.as_mut_any(),
882 })
883 }
884
885 pub fn register(
887 &mut self,
888 type_id: TypeId,
889 extension: Box<dyn Extension>,
890 ) -> Result<(), sp_externalities::Error> {
891 match self.extensions.entry(type_id) {
892 MapEntry::Vacant(vacant) => {
893 vacant.insert(OverlayedExtension::Owned(extension));
894 Ok(())
895 },
896 MapEntry::Occupied(_) => Err(sp_externalities::Error::ExtensionAlreadyRegistered),
897 }
898 }
899
900 pub fn deregister(&mut self, type_id: TypeId) -> bool {
904 self.extensions.remove(&type_id).is_some()
905 }
906
907 pub fn start_transaction(&mut self, ty: TransactionType) {
911 self.extensions.values_mut().for_each(|e| e.extension().start_transaction(ty));
912 }
913
914 pub fn commit_transaction(&mut self, ty: TransactionType) {
918 self.extensions.values_mut().for_each(|e| e.extension().commit_transaction(ty));
919 }
920
921 pub fn rollback_transaction(&mut self, ty: TransactionType) {
925 self.extensions
926 .values_mut()
927 .for_each(|e| e.extension().rollback_transaction(ty));
928 }
929}
930
931#[cfg(test)]
932mod tests {
933 use super::*;
934 use crate::{ext::Ext, new_in_mem, InMemoryBackend};
935 use array_bytes::bytes2hex;
936 use sp_core::{traits::Externalities, Blake2Hasher};
937 use std::collections::BTreeMap;
938
939 fn assert_extrinsics(
940 overlay: &mut OverlayedChangeSet,
941 key: impl AsRef<[u8]>,
942 expected: Vec<u32>,
943 ) {
944 assert_eq!(
945 overlay.get(key.as_ref()).unwrap().extrinsics().into_iter().collect::<Vec<_>>(),
946 expected
947 )
948 }
949
950 #[test]
951 fn overlayed_storage_works() {
952 let mut overlayed = OverlayedChanges::<Blake2Hasher>::default();
953
954 let key = vec![42, 69, 169, 142];
955
956 assert!(overlayed.storage(&key).is_none());
957
958 overlayed.start_transaction();
959
960 overlayed.set_storage(key.clone(), Some(vec![1, 2, 3]));
961 assert_eq!(overlayed.storage(&key).unwrap(), Some(&[1, 2, 3][..]));
962
963 overlayed.commit_transaction().unwrap();
964
965 assert_eq!(overlayed.storage(&key).unwrap(), Some(&[1, 2, 3][..]));
966
967 overlayed.start_transaction();
968
969 overlayed.set_storage(key.clone(), Some(vec![]));
970 assert_eq!(overlayed.storage(&key).unwrap(), Some(&[][..]));
971
972 overlayed.set_storage(key.clone(), None);
973 assert!(overlayed.storage(&key).unwrap().is_none());
974
975 overlayed.rollback_transaction().unwrap();
976
977 assert_eq!(overlayed.storage(&key).unwrap(), Some(&[1, 2, 3][..]));
978
979 overlayed.set_storage(key.clone(), None);
980 assert!(overlayed.storage(&key).unwrap().is_none());
981 }
982
983 #[test]
984 fn offchain_overlayed_storage_transactions_works() {
985 use sp_core::offchain::STORAGE_PREFIX;
986 fn check_offchain_content(
987 state: &OverlayedChanges<Blake2Hasher>,
988 nb_commit: usize,
989 expected: Vec<(Vec<u8>, Option<Vec<u8>>)>,
990 ) {
991 let mut state = state.clone();
992 for _ in 0..nb_commit {
993 state.commit_transaction().unwrap();
994 }
995 let offchain_data: Vec<_> = state.offchain_drain_committed().collect();
996 let expected: Vec<_> = expected
997 .into_iter()
998 .map(|(key, value)| {
999 let change = match value {
1000 Some(value) => OffchainOverlayedChange::SetValue(value),
1001 None => OffchainOverlayedChange::Remove,
1002 };
1003 ((STORAGE_PREFIX.to_vec(), key), change)
1004 })
1005 .collect();
1006 assert_eq!(offchain_data, expected);
1007 }
1008
1009 let mut overlayed = OverlayedChanges::default();
1010
1011 let key = vec![42, 69, 169, 142];
1012
1013 check_offchain_content(&overlayed, 0, vec![]);
1014
1015 overlayed.start_transaction();
1016
1017 overlayed.set_offchain_storage(key.as_slice(), Some(&[1, 2, 3][..]));
1018 check_offchain_content(&overlayed, 1, vec![(key.clone(), Some(vec![1, 2, 3]))]);
1019
1020 overlayed.commit_transaction().unwrap();
1021
1022 check_offchain_content(&overlayed, 0, vec![(key.clone(), Some(vec![1, 2, 3]))]);
1023
1024 overlayed.start_transaction();
1025
1026 overlayed.set_offchain_storage(key.as_slice(), Some(&[][..]));
1027 check_offchain_content(&overlayed, 1, vec![(key.clone(), Some(vec![]))]);
1028
1029 overlayed.set_offchain_storage(key.as_slice(), None);
1030 check_offchain_content(&overlayed, 1, vec![(key.clone(), None)]);
1031
1032 overlayed.rollback_transaction().unwrap();
1033
1034 check_offchain_content(&overlayed, 0, vec![(key.clone(), Some(vec![1, 2, 3]))]);
1035
1036 overlayed.set_offchain_storage(key.as_slice(), None);
1037 check_offchain_content(&overlayed, 0, vec![(key.clone(), None)]);
1038 }
1039
1040 fn add_renew(overlayed: &mut OverlayedChanges<Blake2Hasher>, extrinsic: u32) {
1041 overlayed.add_transaction_index(IndexOperation::Renew { extrinsic, hash: vec![] });
1042 }
1043
1044 fn renewed_extrinsics(overlayed: &OverlayedChanges<Blake2Hasher>) -> Vec<u32> {
1045 overlayed
1046 .transaction_index_ops()
1047 .iter()
1048 .map(|op| match op {
1049 IndexOperation::Renew { extrinsic, .. } => *extrinsic,
1050 IndexOperation::Insert { .. } => panic!("only renews are added"),
1051 })
1052 .collect()
1053 }
1054
1055 #[test]
1058 fn transaction_index_ops_follow_storage_transactions() {
1059 let mut overlayed = OverlayedChanges::default();
1060
1061 add_renew(&mut overlayed, 0);
1062
1063 overlayed.start_transaction();
1064 add_renew(&mut overlayed, 1);
1065 overlayed.rollback_transaction().unwrap();
1066 assert_eq!(renewed_extrinsics(&overlayed), vec![0]);
1067
1068 overlayed.start_transaction();
1069 add_renew(&mut overlayed, 2);
1070 overlayed.commit_transaction().unwrap();
1071 assert_eq!(renewed_extrinsics(&overlayed), vec![0, 2]);
1072
1073 overlayed.start_transaction();
1074 add_renew(&mut overlayed, 3);
1075 overlayed.start_transaction();
1076 add_renew(&mut overlayed, 4);
1077 overlayed.rollback_transaction().unwrap();
1078 add_renew(&mut overlayed, 5);
1079 overlayed.commit_transaction().unwrap();
1080 assert_eq!(renewed_extrinsics(&overlayed), vec![0, 2, 3, 5]);
1081
1082 overlayed.start_transaction();
1083 overlayed.start_transaction();
1084 add_renew(&mut overlayed, 6);
1085 overlayed.commit_transaction().unwrap();
1086 overlayed.rollback_transaction().unwrap();
1087 assert_eq!(renewed_extrinsics(&overlayed), vec![0, 2, 3, 5]);
1088 }
1089
1090 #[test]
1091 fn transaction_index_ops_of_transactions_left_open_by_runtime_are_dropped() {
1092 let mut overlayed = OverlayedChanges::default();
1093
1094 overlayed.start_transaction();
1095 add_renew(&mut overlayed, 0);
1096
1097 overlayed.enter_runtime().unwrap();
1098 add_renew(&mut overlayed, 1);
1099 overlayed.start_transaction();
1100 add_renew(&mut overlayed, 2);
1101 overlayed.start_transaction();
1102 add_renew(&mut overlayed, 3);
1103 overlayed.exit_runtime().unwrap();
1104
1105 assert_eq!(renewed_extrinsics(&overlayed), vec![0, 1]);
1106
1107 overlayed.rollback_transaction().unwrap();
1108 assert_eq!(renewed_extrinsics(&overlayed), Vec::<u32>::new());
1109 }
1110
1111 #[test]
1112 fn overlayed_storage_root_works() {
1113 let state_version = StateVersion::default();
1114 let initial: BTreeMap<_, _> = vec![
1115 (b"doe".to_vec(), b"reindeer".to_vec()),
1116 (b"dog".to_vec(), b"puppyXXX".to_vec()),
1117 (b"dogglesworth".to_vec(), b"catXXX".to_vec()),
1118 (b"doug".to_vec(), b"notadog".to_vec()),
1119 ]
1120 .into_iter()
1121 .collect();
1122 let backend = InMemoryBackend::<Blake2Hasher>::from((initial, state_version));
1123 let mut overlay = OverlayedChanges::default();
1124
1125 overlay.start_transaction();
1126 overlay.set_storage(b"dog".to_vec(), Some(b"puppy".to_vec()));
1127 overlay.set_storage(b"dogglesworth".to_vec(), Some(b"catYYY".to_vec()));
1128 overlay.set_storage(b"doug".to_vec(), Some(vec![]));
1129 overlay.commit_transaction().unwrap();
1130
1131 overlay.start_transaction();
1132 overlay.set_storage(b"dogglesworth".to_vec(), Some(b"cat".to_vec()));
1133 overlay.set_storage(b"doug".to_vec(), None);
1134
1135 {
1136 let mut ext = Ext::new(&mut overlay, &backend, None, state_version);
1137 let root = "39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa";
1138
1139 assert_eq!(bytes2hex("", &ext.storage_root()), root);
1140 assert_eq!(bytes2hex("", &ext.storage_root()), root);
1142 }
1143
1144 overlay.set_storage(b"doug2".to_vec(), Some(b"yes".to_vec()));
1146
1147 let mut ext = Ext::new(&mut overlay, &backend, None, state_version);
1148 let root = "5c0a4e35cb967de785e1cb8743e6f24b6ff6d45155317f2078f6eb3fc4ff3e3d";
1149 assert_eq!(bytes2hex("", &ext.storage_root()), root);
1150 }
1151
1152 #[test]
1153 fn storage_root_cache_invalidates_on_state_version_change() {
1154 let backend = InMemoryBackend::<Blake2Hasher>::default();
1157 let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1158 overlay.start_transaction();
1159 overlay.set_storage(b"key".to_vec(), Some(vec![0x42; 64]));
1160 overlay.commit_transaction().unwrap();
1161
1162 let (root_v0_first, cached) = overlay.storage_root(&backend, StateVersion::V0);
1163 assert!(!cached);
1164 let (root_v0_second, cached) = overlay.storage_root(&backend, StateVersion::V0);
1165 assert!(cached);
1166 assert_eq!(root_v0_first, root_v0_second);
1167
1168 let (root_v1, cached) = overlay.storage_root(&backend, StateVersion::V1);
1170 assert!(!cached, "cache must be invalidated when state version changes");
1171 assert_ne!(
1172 root_v0_first, root_v1,
1173 "V0 and V1 roots must differ for values exceeding the inline threshold",
1174 );
1175
1176 let (root_v0_third, cached) = overlay.storage_root(&backend, StateVersion::V0);
1178 assert!(!cached);
1179 assert_eq!(root_v0_first, root_v0_third);
1180 }
1181
1182 #[test]
1183 fn overlayed_child_storage_root_works() {
1184 let child_info = ChildInfo::new_default(b"Child1");
1185 let child_info = &child_info;
1186 let backend = new_in_mem::<Blake2Hasher>();
1187 let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1188 overlay.start_transaction();
1189 overlay.set_child_storage(child_info, vec![20], Some(vec![20]));
1190 overlay.set_child_storage(child_info, vec![30], Some(vec![30]));
1191 overlay.set_child_storage(child_info, vec![40], Some(vec![40]));
1192 overlay.commit_transaction().unwrap();
1193 overlay.set_child_storage(child_info, vec![10], Some(vec![10]));
1194 overlay.set_child_storage(child_info, vec![30], None);
1195
1196 {
1197 let mut ext = Ext::new(&mut overlay, &backend, None, StateVersion::default());
1198 let child_root = "c02965e1df4dc5baf6977390ce67dab1d7a9b27a87c1afe27b50d29cc990e0f5";
1199 let root = "eafb765909c3ed5afd92a0c564acf4620d0234b31702e8e8e9b48da72a748838";
1200
1201 assert_eq!(bytes2hex("", &ext.child_storage_root(child_info)), child_root,);
1202
1203 assert_eq!(bytes2hex("", &ext.storage_root()), root);
1204
1205 assert_eq!(bytes2hex("", &ext.child_storage_root(child_info)), child_root,);
1207 }
1208 }
1209
1210 #[test]
1211 fn extrinsic_changes_are_collected() {
1212 let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1213 overlay.set_collect_extrinsics(true);
1214
1215 overlay.start_transaction();
1216
1217 overlay.set_storage(vec![100], Some(vec![101]));
1218
1219 overlay.set_extrinsic_index(0);
1220 overlay.set_storage(vec![1], Some(vec![2]));
1221
1222 overlay.set_extrinsic_index(1);
1223 overlay.set_storage(vec![3], Some(vec![4]));
1224
1225 overlay.set_extrinsic_index(2);
1226 overlay.set_storage(vec![1], Some(vec![6]));
1227
1228 assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2]);
1229 assert_extrinsics(&mut overlay.top, vec![3], vec![1]);
1230 assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]);
1231
1232 overlay.start_transaction();
1233
1234 overlay.set_extrinsic_index(3);
1235 overlay.set_storage(vec![3], Some(vec![7]));
1236
1237 overlay.set_extrinsic_index(4);
1238 overlay.set_storage(vec![1], Some(vec![8]));
1239
1240 assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2, 4]);
1241 assert_extrinsics(&mut overlay.top, vec![3], vec![1, 3]);
1242 assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]);
1243
1244 overlay.rollback_transaction().unwrap();
1245
1246 assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2]);
1247 assert_extrinsics(&mut overlay.top, vec![3], vec![1]);
1248 assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]);
1249 }
1250
1251 #[test]
1252 fn next_storage_key_change_works() {
1253 let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1254 overlay.start_transaction();
1255 overlay.set_storage(vec![20], Some(vec![20]));
1256 overlay.set_storage(vec![30], Some(vec![30]));
1257 overlay.set_storage(vec![40], Some(vec![40]));
1258 overlay.commit_transaction().unwrap();
1259 overlay.set_storage(vec![10], Some(vec![10]));
1260 overlay.set_storage(vec![30], None);
1261
1262 let next_to_5 = overlay.iter_after(&[5]).next().unwrap();
1264 assert_eq!(next_to_5.0.to_vec(), vec![10]);
1265 assert_eq!(next_to_5.1.value(), Some(&vec![10]));
1266
1267 let next_to_10 = overlay.iter_after(&[10]).next().unwrap();
1269 assert_eq!(next_to_10.0.to_vec(), vec![20]);
1270 assert_eq!(next_to_10.1.value(), Some(&vec![20]));
1271
1272 let next_to_20 = overlay.iter_after(&[20]).next().unwrap();
1274 assert_eq!(next_to_20.0.to_vec(), vec![30]);
1275 assert_eq!(next_to_20.1.value(), None);
1276
1277 let next_to_30 = overlay.iter_after(&[30]).next().unwrap();
1279 assert_eq!(next_to_30.0.to_vec(), vec![40]);
1280 assert_eq!(next_to_30.1.value(), Some(&vec![40]));
1281
1282 overlay.set_storage(vec![50], Some(vec![50]));
1283 let next_to_40 = overlay.iter_after(&[40]).next().unwrap();
1285 assert_eq!(next_to_40.0.to_vec(), vec![50]);
1286 assert_eq!(next_to_40.1.value(), Some(&vec![50]));
1287 }
1288
1289 #[test]
1290 fn next_child_storage_key_change_works() {
1291 let child_info = ChildInfo::new_default(b"Child1");
1292 let child_info = &child_info;
1293 let child = child_info.storage_key();
1294 let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1295 overlay.start_transaction();
1296 overlay.set_child_storage(child_info, vec![20], Some(vec![20]));
1297 overlay.set_child_storage(child_info, vec![30], Some(vec![30]));
1298 overlay.set_child_storage(child_info, vec![40], Some(vec![40]));
1299 overlay.commit_transaction().unwrap();
1300 overlay.set_child_storage(child_info, vec![10], Some(vec![10]));
1301 overlay.set_child_storage(child_info, vec![30], None);
1302
1303 let next_to_5 = overlay.child_iter_after(child, &[5]).next().unwrap();
1305 assert_eq!(next_to_5.0.to_vec(), vec![10]);
1306 assert_eq!(next_to_5.1.value(), Some(&vec![10]));
1307
1308 let next_to_10 = overlay.child_iter_after(child, &[10]).next().unwrap();
1310 assert_eq!(next_to_10.0.to_vec(), vec![20]);
1311 assert_eq!(next_to_10.1.value(), Some(&vec![20]));
1312
1313 let next_to_20 = overlay.child_iter_after(child, &[20]).next().unwrap();
1315 assert_eq!(next_to_20.0.to_vec(), vec![30]);
1316 assert_eq!(next_to_20.1.value(), None);
1317
1318 let next_to_30 = overlay.child_iter_after(child, &[30]).next().unwrap();
1320 assert_eq!(next_to_30.0.to_vec(), vec![40]);
1321 assert_eq!(next_to_30.1.value(), Some(&vec![40]));
1322
1323 overlay.set_child_storage(child_info, vec![50], Some(vec![50]));
1324 let next_to_40 = overlay.child_iter_after(child, &[40]).next().unwrap();
1326 assert_eq!(next_to_40.0.to_vec(), vec![50]);
1327 assert_eq!(next_to_40.1.value(), Some(&vec![50]));
1328 }
1329}