sp_state_machine/overlayed_changes/
mod.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//! The overlayed changes to state.
19
20mod 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};
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
50/// Changes that are made outside of extrinsics are marked with this index;
51pub const NO_EXTRINSIC_INDEX: u32 = 0xffffffff;
52
53/// Storage key.
54pub type StorageKey = Vec<u8>;
55
56/// Storage value.
57pub type StorageValue = Vec<u8>;
58
59/// In memory array of storage values.
60pub type StorageCollection = Vec<(StorageKey, Option<StorageValue>)>;
61
62/// In memory arrays of storage values for multiple child tries.
63pub type ChildStorageCollection = Vec<(StorageKey, StorageCollection)>;
64
65/// In memory array of storage values.
66pub type OffchainChangesCollection = Vec<((Vec<u8>, Vec<u8>), OffchainOverlayedChange)>;
67
68/// Keep trace of extrinsics index for a modified value.
69#[derive(Debug, Default, Eq, PartialEq, Clone)]
70pub struct Extrinsics(Vec<u32>);
71
72impl Extrinsics {
73	/// Extracts extrinsics into a `BTreeSets`.
74	fn copy_extrinsics_into(&self, dest: &mut BTreeSet<u32>) {
75		dest.extend(self.0.iter())
76	}
77
78	/// Add an extrinsics.
79	fn insert(&mut self, ext: u32) {
80		if Some(&ext) != self.0.last() {
81			self.0.push(ext);
82		}
83	}
84
85	/// Extend `self` with `other`.
86	fn extend(&mut self, other: Self) {
87		self.0.extend(other.0.into_iter());
88	}
89}
90
91/// The set of changes that are overlaid onto the backend.
92///
93/// It allows changes to be modified using nestable transactions.
94pub struct OverlayedChanges<H: Hasher> {
95	/// Top level storage changes.
96	top: OverlayedChangeSet,
97	/// Child storage changes. The map key is the child storage key without the common prefix.
98	children: Map<StorageKey, (OverlayedChangeSet, ChildInfo)>,
99	/// Offchain related changes.
100	offchain: OffchainOverlayedChanges,
101	/// Transaction index changes,
102	transaction_index_ops: Vec<IndexOperation>,
103	/// True if extrinsics stats must be collected.
104	collect_extrinsics: bool,
105	/// Collect statistic on this execution.
106	stats: StateMachineStats,
107	/// Caches the "storage transaction" that is created while calling `storage_root`.
108	///
109	/// This transaction can be applied to the backend to persist the state changes.
110	storage_transaction_cache: Option<StorageTransactionCache<H>>,
111}
112
113impl<H: Hasher> Default for OverlayedChanges<H> {
114	fn default() -> Self {
115		Self {
116			top: Default::default(),
117			children: Default::default(),
118			offchain: Default::default(),
119			transaction_index_ops: Default::default(),
120			collect_extrinsics: Default::default(),
121			stats: Default::default(),
122			storage_transaction_cache: None,
123		}
124	}
125}
126
127impl<H: Hasher> Clone for OverlayedChanges<H> {
128	fn clone(&self) -> Self {
129		Self {
130			top: self.top.clone(),
131			children: self.children.clone(),
132			offchain: self.offchain.clone(),
133			transaction_index_ops: self.transaction_index_ops.clone(),
134			collect_extrinsics: self.collect_extrinsics,
135			stats: self.stats.clone(),
136			storage_transaction_cache: self.storage_transaction_cache.clone(),
137		}
138	}
139}
140
141impl<H: Hasher> core::fmt::Debug for OverlayedChanges<H> {
142	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
143		f.debug_struct("OverlayedChanges")
144			.field("top", &self.top)
145			.field("children", &self.children)
146			.field("offchain", &self.offchain)
147			.field("transaction_index_ops", &self.transaction_index_ops)
148			.field("collect_extrinsics", &self.collect_extrinsics)
149			.field("stats", &self.stats)
150			.field("storage_transaction_cache", &self.storage_transaction_cache)
151			.finish()
152	}
153}
154
155/// Transaction index operation.
156#[derive(Debug, Clone)]
157pub enum IndexOperation {
158	/// Insert transaction into index.
159	Insert {
160		/// Extrinsic index in the current block.
161		extrinsic: u32,
162		/// Data content hash.
163		hash: Vec<u8>,
164		/// Indexed data size.
165		size: u32,
166	},
167	/// Renew existing transaction storage.
168	Renew {
169		/// Extrinsic index in the current block.
170		extrinsic: u32,
171		/// Referenced index hash.
172		hash: Vec<u8>,
173	},
174}
175
176/// A storage changes structure that can be generated by the data collected in [`OverlayedChanges`].
177///
178/// This contains all the changes to the storage and transactions to apply theses changes to the
179/// backend.
180pub struct StorageChanges<H: Hasher> {
181	/// All changes to the main storage.
182	///
183	/// A value of `None` means that it was deleted.
184	pub main_storage_changes: StorageCollection,
185	/// All changes to the child storages.
186	pub child_storage_changes: ChildStorageCollection,
187	/// Offchain state changes to write to the offchain database.
188	pub offchain_storage_changes: OffchainChangesCollection,
189	/// A transaction for the backend that contains all changes from
190	/// [`main_storage_changes`](StorageChanges::main_storage_changes) and from
191	/// [`child_storage_changes`](StorageChanges::child_storage_changes).
192	/// [`offchain_storage_changes`](StorageChanges::offchain_storage_changes).
193	pub transaction: BackendTransaction<H>,
194	/// The storage root after applying the transaction.
195	pub transaction_storage_root: H::Out,
196	/// Changes to the transaction index,
197	#[cfg(feature = "std")]
198	pub transaction_index_changes: Vec<IndexOperation>,
199}
200
201#[cfg(feature = "std")]
202impl<H: Hasher> StorageChanges<H> {
203	/// Deconstruct into the inner values
204	pub fn into_inner(
205		self,
206	) -> (
207		StorageCollection,
208		ChildStorageCollection,
209		OffchainChangesCollection,
210		BackendTransaction<H>,
211		H::Out,
212		Vec<IndexOperation>,
213	) {
214		(
215			self.main_storage_changes,
216			self.child_storage_changes,
217			self.offchain_storage_changes,
218			self.transaction,
219			self.transaction_storage_root,
220			self.transaction_index_changes,
221		)
222	}
223}
224
225impl<H: Hasher> Default for StorageChanges<H> {
226	fn default() -> Self {
227		Self {
228			main_storage_changes: Default::default(),
229			child_storage_changes: Default::default(),
230			offchain_storage_changes: Default::default(),
231			transaction: Default::default(),
232			transaction_storage_root: Default::default(),
233			#[cfg(feature = "std")]
234			transaction_index_changes: Default::default(),
235		}
236	}
237}
238
239/// Storage transactions are calculated as part of the `storage_root`.
240/// These transactions can be reused for importing the block into the
241/// storage. So, we cache them to not require a recomputation of those transactions.
242struct StorageTransactionCache<H: Hasher> {
243	/// Contains the changes for the main and the child storages as one transaction.
244	transaction: BackendTransaction<H>,
245	/// The storage root after applying the transaction.
246	transaction_storage_root: H::Out,
247}
248
249impl<H: Hasher> StorageTransactionCache<H> {
250	fn into_inner(self) -> (BackendTransaction<H>, H::Out) {
251		(self.transaction, self.transaction_storage_root)
252	}
253}
254
255impl<H: Hasher> Clone for StorageTransactionCache<H> {
256	fn clone(&self) -> Self {
257		Self {
258			transaction: self.transaction.clone(),
259			transaction_storage_root: self.transaction_storage_root,
260		}
261	}
262}
263
264impl<H: Hasher> core::fmt::Debug for StorageTransactionCache<H> {
265	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
266		let mut debug = f.debug_struct("StorageTransactionCache");
267
268		#[cfg(feature = "std")]
269		debug.field("transaction_storage_root", &self.transaction_storage_root);
270
271		#[cfg(not(feature = "std"))]
272		debug.field("transaction_storage_root", &self.transaction_storage_root.as_ref());
273
274		debug.finish()
275	}
276}
277
278impl<H: Hasher> OverlayedChanges<H> {
279	/// Whether no changes are contained in the top nor in any of the child changes.
280	pub fn is_empty(&self) -> bool {
281		self.top.is_empty() && self.children.is_empty()
282	}
283
284	/// Ask to collect/not to collect extrinsics indices where key(s) has been changed.
285	pub fn set_collect_extrinsics(&mut self, collect_extrinsics: bool) {
286		self.collect_extrinsics = collect_extrinsics;
287	}
288
289	/// Returns a double-Option: None if the key is unknown (i.e. and the query should be referred
290	/// to the backend); Some(None) if the key has been deleted. Some(Some(...)) for a key whose
291	/// value has been set.
292	pub fn storage(&mut self, key: &[u8]) -> Option<Option<&[u8]>> {
293		self.top.get(key).map(|x| {
294			let value = x.value();
295			let size_read = value.map(|x| x.len() as u64).unwrap_or(0);
296			self.stats.tally_read_modified(size_read);
297			value.map(AsRef::as_ref)
298		})
299	}
300
301	/// Should be called when there are changes that require to reset the
302	/// `storage_transaction_cache`.
303	fn mark_dirty(&mut self) {
304		self.storage_transaction_cache = None;
305	}
306
307	/// Returns a double-Option: None if the key is unknown (i.e. and the query should be referred
308	/// to the backend); Some(None) if the key has been deleted. Some(Some(...)) for a key whose
309	/// value has been set.
310	pub fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option<Option<&[u8]>> {
311		let map = self.children.get_mut(child_info.storage_key())?;
312		let value = map.0.get(key)?.value();
313		let size_read = value.map(|x| x.len() as u64).unwrap_or(0);
314		self.stats.tally_read_modified(size_read);
315		Some(value.map(AsRef::as_ref))
316	}
317
318	/// Set a new value for the specified key.
319	///
320	/// Can be rolled back or committed when called inside a transaction.
321	pub fn set_storage(&mut self, key: StorageKey, val: Option<StorageValue>) {
322		self.mark_dirty();
323
324		let size_write = val.as_ref().map(|x| x.len() as u64).unwrap_or(0);
325		self.stats.tally_write_overlay(size_write);
326		let extrinsic_index = self.extrinsic_index();
327		self.top.set(key, val, extrinsic_index);
328	}
329
330	/// Append a element to storage, init with existing value if first write.
331	pub fn append_storage(
332		&mut self,
333		key: StorageKey,
334		element: StorageValue,
335		init: impl Fn() -> StorageValue,
336	) {
337		let extrinsic_index = self.extrinsic_index();
338		let size_write = element.len() as u64;
339		self.stats.tally_write_overlay(size_write);
340		self.top.append_storage(key, element, init, extrinsic_index);
341	}
342
343	/// Set a new value for the specified key and child.
344	///
345	/// `None` can be used to delete a value specified by the given key.
346	///
347	/// Can be rolled back or committed when called inside a transaction.
348	pub fn set_child_storage(
349		&mut self,
350		child_info: &ChildInfo,
351		key: StorageKey,
352		val: Option<StorageValue>,
353	) {
354		self.mark_dirty();
355
356		let extrinsic_index = self.extrinsic_index();
357		let size_write = val.as_ref().map(|x| x.len() as u64).unwrap_or(0);
358		self.stats.tally_write_overlay(size_write);
359		let storage_key = child_info.storage_key().to_vec();
360		let top = &self.top;
361		let (changeset, info) = self
362			.children
363			.entry(storage_key)
364			.or_insert_with(|| (top.spawn_child(), child_info.clone()));
365		let updatable = info.try_update(child_info);
366		debug_assert!(updatable);
367		changeset.set(key, val, extrinsic_index);
368	}
369
370	/// Clear child storage of given storage key.
371	///
372	/// Can be rolled back or committed when called inside a transaction.
373	pub fn clear_child_storage(&mut self, child_info: &ChildInfo) -> u32 {
374		self.mark_dirty();
375
376		let extrinsic_index = self.extrinsic_index();
377		let storage_key = child_info.storage_key().to_vec();
378		let top = &self.top;
379		let (changeset, info) = self
380			.children
381			.entry(storage_key)
382			.or_insert_with(|| (top.spawn_child(), child_info.clone()));
383		let updatable = info.try_update(child_info);
384		debug_assert!(updatable);
385		changeset.clear_where(|_, _| true, extrinsic_index)
386	}
387
388	/// Removes all key-value pairs which keys share the given prefix.
389	///
390	/// Can be rolled back or committed when called inside a transaction.
391	pub fn clear_prefix(&mut self, prefix: &[u8]) -> u32 {
392		self.mark_dirty();
393
394		let extrinsic_index = self.extrinsic_index();
395		self.top.clear_where(|key, _| key.starts_with(prefix), extrinsic_index)
396	}
397
398	/// Removes all key-value pairs which keys share the given prefix.
399	///
400	/// Can be rolled back or committed when called inside a transaction
401	pub fn clear_child_prefix(&mut self, child_info: &ChildInfo, prefix: &[u8]) -> u32 {
402		self.mark_dirty();
403
404		let extrinsic_index = self.extrinsic_index();
405		let storage_key = child_info.storage_key().to_vec();
406		let top = &self.top;
407		let (changeset, info) = self
408			.children
409			.entry(storage_key)
410			.or_insert_with(|| (top.spawn_child(), child_info.clone()));
411		let updatable = info.try_update(child_info);
412		debug_assert!(updatable);
413		changeset.clear_where(|key, _| key.starts_with(prefix), extrinsic_index)
414	}
415
416	/// Returns the current nesting depth of the transaction stack.
417	///
418	/// A value of zero means that no transaction is open and changes are committed on write.
419	pub fn transaction_depth(&self) -> usize {
420		// The top changeset and all child changesets transact in lockstep and are
421		// therefore always at the same transaction depth.
422		self.top.transaction_depth()
423	}
424
425	/// Start a new nested transaction.
426	///
427	/// This allows to either commit or roll back all changes that where made while this
428	/// transaction was open. Any transaction must be closed by either `rollback_transaction` or
429	/// `commit_transaction` before this overlay can be converted into storage changes.
430	///
431	/// Changes made without any open transaction are committed immediately.
432	pub fn start_transaction(&mut self) {
433		self.top.start_transaction();
434		for (_, (changeset, _)) in self.children.iter_mut() {
435			changeset.start_transaction();
436		}
437		self.offchain.overlay_mut().start_transaction();
438	}
439
440	/// Rollback the last transaction started by `start_transaction`.
441	///
442	/// Any changes made during that transaction are discarded. Returns an error if
443	/// there is no open transaction that can be rolled back.
444	pub fn rollback_transaction(&mut self) -> Result<(), NoOpenTransaction> {
445		self.mark_dirty();
446
447		self.top.rollback_transaction()?;
448		retain_map(&mut self.children, |_, (changeset, _)| {
449			changeset
450				.rollback_transaction()
451				.expect("Top and children changesets are started in lockstep; qed");
452			!changeset.is_empty()
453		});
454		self.offchain
455			.overlay_mut()
456			.rollback_transaction_offchain()
457			.expect("Top and offchain changesets are started in lockstep; qed");
458		Ok(())
459	}
460
461	/// Commit the last transaction started by `start_transaction`.
462	///
463	/// Any changes made during that transaction are committed. Returns an error if there
464	/// is no open transaction that can be committed.
465	pub fn commit_transaction(&mut self) -> Result<(), NoOpenTransaction> {
466		self.top.commit_transaction()?;
467		for (_, (changeset, _)) in self.children.iter_mut() {
468			changeset
469				.commit_transaction()
470				.expect("Top and children changesets are started in lockstep; qed");
471		}
472		self.offchain
473			.overlay_mut()
474			.commit_transaction_offchain()
475			.expect("Top and offchain changesets are started in lockstep; qed");
476		Ok(())
477	}
478
479	/// Call this before transferring control to the runtime.
480	///
481	/// This protects all existing transactions from being removed by the runtime.
482	/// Calling this while already inside the runtime will return an error.
483	pub fn enter_runtime(&mut self) -> Result<(), AlreadyInRuntime> {
484		self.top.enter_runtime()?;
485		for (_, (changeset, _)) in self.children.iter_mut() {
486			changeset
487				.enter_runtime()
488				.expect("Top and children changesets are entering runtime in lockstep; qed")
489		}
490		self.offchain
491			.overlay_mut()
492			.enter_runtime()
493			.expect("Top and offchain changesets are started in lockstep; qed");
494		Ok(())
495	}
496
497	/// Call this when control returns from the runtime.
498	///
499	/// This rollbacks all dangling transaction left open by the runtime.
500	/// Calling this while outside the runtime will return an error.
501	pub fn exit_runtime(&mut self) -> Result<(), NotInRuntime> {
502		self.top.exit_runtime()?;
503		for (_, (changeset, _)) in self.children.iter_mut() {
504			changeset
505				.exit_runtime()
506				.expect("Top and children changesets are entering runtime in lockstep; qed");
507		}
508		self.offchain
509			.overlay_mut()
510			.exit_runtime_offchain()
511			.expect("Top and offchain changesets are started in lockstep; qed");
512		Ok(())
513	}
514
515	/// Consume all changes (top + children) and return them.
516	///
517	/// After calling this function no more changes are contained in this changeset.
518	///
519	/// Panics:
520	/// Panics if `transaction_depth() > 0`
521	pub fn offchain_drain_committed(
522		&mut self,
523	) -> impl Iterator<Item = ((StorageKey, StorageKey), OffchainOverlayedChange)> {
524		self.offchain.drain()
525	}
526
527	/// Get an iterator over all child changes as seen by the current transaction.
528	pub fn children(
529		&self,
530	) -> impl Iterator<Item = (impl Iterator<Item = (&StorageKey, &OverlayedValue)>, &ChildInfo)> {
531		self.children.values().map(|v| (v.0.changes(), &v.1))
532	}
533
534	/// Get an iterator over all child changes as seen by the current transaction.
535	pub fn children_mut(
536		&mut self,
537	) -> impl Iterator<Item = (impl Iterator<Item = (&StorageKey, &mut OverlayedValue)>, &ChildInfo)>
538	{
539		self.children.values_mut().map(|v| (v.0.changes_mut(), &v.1))
540	}
541
542	/// Get an iterator over all top changes as been by the current transaction.
543	pub fn changes(&self) -> impl Iterator<Item = (&StorageKey, &OverlayedValue)> {
544		self.top.changes()
545	}
546
547	/// Get an iterator over all top changes as been by the current transaction.
548	pub fn changes_mut(&mut self) -> impl Iterator<Item = (&StorageKey, &mut OverlayedValue)> {
549		self.top.changes_mut()
550	}
551
552	/// Get an optional iterator over all child changes stored under the supplied key.
553	pub fn child_changes(
554		&self,
555		key: &[u8],
556	) -> Option<(impl Iterator<Item = (&StorageKey, &OverlayedValue)>, &ChildInfo)> {
557		self.children.get(key).map(|(overlay, info)| (overlay.changes(), info))
558	}
559
560	/// Get an optional iterator over all child changes stored under the supplied key.
561	pub fn child_changes_mut(
562		&mut self,
563		key: &[u8],
564	) -> Option<(impl Iterator<Item = (&StorageKey, &mut OverlayedValue)>, &ChildInfo)> {
565		self.children
566			.get_mut(key)
567			.map(|(overlay, info)| (overlay.changes_mut(), &*info))
568	}
569
570	/// Get an list of all index operations.
571	pub fn transaction_index_ops(&self) -> &[IndexOperation] {
572		&self.transaction_index_ops
573	}
574
575	/// Drain all changes into a [`StorageChanges`] instance. Leave empty overlay in place.
576	pub fn drain_storage_changes<B: Backend<H>>(
577		&mut self,
578		backend: &B,
579		state_version: StateVersion,
580	) -> Result<StorageChanges<H>, DefaultError>
581	where
582		H::Out: Ord + Encode + 'static,
583	{
584		let (transaction, transaction_storage_root) = match self.storage_transaction_cache.take() {
585			Some(cache) => cache.into_inner(),
586			// If the transaction does not exist, we generate it.
587			None => {
588				self.storage_root(backend, state_version);
589				self.storage_transaction_cache
590					.take()
591					.expect("`storage_transaction_cache` was just initialized; qed")
592					.into_inner()
593			},
594		};
595
596		use core::mem::take;
597		let main_storage_changes =
598			take(&mut self.top).drain_committed().map(|(k, v)| (k, v.to_option()));
599		let child_storage_changes =
600			take(&mut self.children).into_iter().map(|(key, (val, info))| {
601				(key, (val.drain_committed().map(|(k, v)| (k, v.to_option())), info))
602			});
603		let offchain_storage_changes = self.offchain_drain_committed().collect();
604
605		#[cfg(feature = "std")]
606		let transaction_index_changes = std::mem::take(&mut self.transaction_index_ops);
607
608		Ok(StorageChanges {
609			main_storage_changes: main_storage_changes.collect(),
610			child_storage_changes: child_storage_changes
611				.map(|(sk, it)| (sk, it.0.collect()))
612				.collect(),
613			offchain_storage_changes,
614			transaction,
615			transaction_storage_root,
616			#[cfg(feature = "std")]
617			transaction_index_changes,
618		})
619	}
620
621	/// Inserts storage entry responsible for current extrinsic index.
622	#[cfg(test)]
623	pub(crate) fn set_extrinsic_index(&mut self, extrinsic_index: u32) {
624		self.top.set(EXTRINSIC_INDEX.to_vec(), Some(extrinsic_index.encode()), None);
625	}
626
627	/// Returns current extrinsic index to use in changes trie construction.
628	/// None is returned if it is not set or changes trie config is not set.
629	/// Persistent value (from the backend) can be ignored because runtime must
630	/// set this index before first and unset after last extrinsic is executed.
631	/// Changes that are made outside of extrinsics, are marked with
632	/// `NO_EXTRINSIC_INDEX` index.
633	fn extrinsic_index(&mut self) -> Option<u32> {
634		self.collect_extrinsics.then(|| {
635			self.storage(EXTRINSIC_INDEX)
636				.and_then(|idx| idx.and_then(|idx| Decode::decode(&mut &*idx).ok()))
637				.unwrap_or(NO_EXTRINSIC_INDEX)
638		})
639	}
640
641	/// Generate the storage root using `backend` and all changes
642	/// as seen by the current transaction.
643	///
644	/// Returns the storage root and whether it was already cached.
645	pub fn storage_root<B: Backend<H>>(
646		&mut self,
647		backend: &B,
648		state_version: StateVersion,
649	) -> (H::Out, bool)
650	where
651		H::Out: Ord + Encode,
652	{
653		if let Some(cache) = &self.storage_transaction_cache {
654			return (cache.transaction_storage_root, true)
655		}
656
657		let delta = self.top.changes_mut().map(|(k, v)| (&k[..], v.value().map(|v| &v[..])));
658
659		let child_delta = self
660			.children
661			.values_mut()
662			.map(|v| (&v.1, v.0.changes_mut().map(|(k, v)| (&k[..], v.value().map(|v| &v[..])))));
663
664		let (root, transaction) = backend.full_storage_root(delta, child_delta, state_version);
665
666		self.storage_transaction_cache =
667			Some(StorageTransactionCache { transaction, transaction_storage_root: root });
668
669		(root, false)
670	}
671
672	/// Generate the child storage root using `backend` and all child changes
673	/// as seen by the current transaction.
674	///
675	/// Returns the child storage root and whether it was already cached.
676	pub fn child_storage_root<B: Backend<H>>(
677		&mut self,
678		child_info: &ChildInfo,
679		backend: &B,
680		state_version: StateVersion,
681	) -> Result<(H::Out, bool), B::Error>
682	where
683		H::Out: Ord + Encode + Decode,
684	{
685		let storage_key = child_info.storage_key();
686		let prefixed_storage_key = child_info.prefixed_storage_key();
687
688		if self.storage_transaction_cache.is_some() {
689			let root = self
690				.storage(prefixed_storage_key.as_slice())
691				.map(|v| Ok(v.map(|v| v.to_vec())))
692				.or_else(|| backend.storage(prefixed_storage_key.as_slice()).map(Some).transpose())
693				.transpose()?
694				.flatten()
695				.and_then(|k| Decode::decode(&mut &k[..]).ok())
696				// V1 is equivalent to V0 on empty root.
697				.unwrap_or_else(empty_child_trie_root::<LayoutV1<H>>);
698
699			return Ok((root, true))
700		}
701
702		let root = if let Some((changes, info)) = self.child_changes_mut(storage_key) {
703			let delta = changes.map(|(k, v)| (k.as_ref(), v.value().map(AsRef::as_ref)));
704			Some(backend.child_storage_root(info, delta, state_version))
705		} else {
706			None
707		};
708
709		let root = if let Some((root, is_empty, _)) = root {
710			// We store update in the overlay in order to be able to use
711			// 'self.storage_transaction' cache. This is brittle as it rely on Ext only querying
712			// the trie backend for storage root.
713			// A better design would be to manage 'child_storage_transaction' in a
714			// similar way as 'storage_transaction' but for each child trie.
715			self.set_storage(prefixed_storage_key.into_inner(), (!is_empty).then(|| root.encode()));
716
717			self.mark_dirty();
718
719			root
720		} else {
721			// empty overlay
722			let root = backend
723				.storage(prefixed_storage_key.as_slice())?
724				.and_then(|k| Decode::decode(&mut &k[..]).ok())
725				// V1 is equivalent to V0 on empty root.
726				.unwrap_or_else(empty_child_trie_root::<LayoutV1<H>>);
727
728			root
729		};
730
731		Ok((root, false))
732	}
733
734	/// Returns an iterator over the keys (in lexicographic order) following `key` (excluding `key`)
735	/// alongside its value.
736	pub fn iter_after(&mut self, key: &[u8]) -> impl Iterator<Item = (&[u8], &mut OverlayedValue)> {
737		self.top.changes_after(key)
738	}
739
740	/// Returns an iterator over the keys (in lexicographic order) following `key` (excluding `key`)
741	/// alongside its value for the given `storage_key` child.
742	pub fn child_iter_after(
743		&mut self,
744		storage_key: &[u8],
745		key: &[u8],
746	) -> impl Iterator<Item = (&[u8], &mut OverlayedValue)> {
747		self.children
748			.get_mut(storage_key)
749			.map(|(overlay, _)| overlay.changes_after(key))
750			.into_iter()
751			.flatten()
752	}
753
754	/// Read only access ot offchain overlay.
755	pub fn offchain(&self) -> &OffchainOverlayedChanges {
756		&self.offchain
757	}
758
759	/// Write a key value pair to the offchain storage overlay.
760	pub fn set_offchain_storage(&mut self, key: &[u8], value: Option<&[u8]>) {
761		use sp_core::offchain::STORAGE_PREFIX;
762		match value {
763			Some(value) => self.offchain.set(STORAGE_PREFIX, key, value),
764			None => self.offchain.remove(STORAGE_PREFIX, key),
765		}
766	}
767
768	/// Add transaction index operation.
769	pub fn add_transaction_index(&mut self, op: IndexOperation) {
770		self.transaction_index_ops.push(op)
771	}
772}
773
774#[cfg(feature = "std")]
775impl<H: Hasher> From<sp_core::storage::Storage> for OverlayedChanges<H> {
776	fn from(storage: sp_core::storage::Storage) -> Self {
777		Self {
778			top: storage.top.into(),
779			children: storage
780				.children_default
781				.into_iter()
782				.map(|(k, v)| (k, (v.data.into(), v.child_info)))
783				.collect(),
784			..Default::default()
785		}
786	}
787}
788
789#[cfg(feature = "std")]
790fn retain_map<K, V, F>(map: &mut Map<K, V>, f: F)
791where
792	K: std::cmp::Eq + std::hash::Hash,
793	F: FnMut(&K, &mut V) -> bool,
794{
795	map.retain(f);
796}
797
798#[cfg(not(feature = "std"))]
799fn retain_map<K, V, F>(map: &mut Map<K, V>, mut f: F)
800where
801	K: Ord,
802	F: FnMut(&K, &mut V) -> bool,
803{
804	let old = core::mem::replace(map, Map::default());
805	for (k, mut v) in old.into_iter() {
806		if f(&k, &mut v) {
807			map.insert(k, v);
808		}
809	}
810}
811
812/// An overlayed extension is either a mutable reference
813/// or an owned extension.
814#[cfg(feature = "std")]
815pub enum OverlayedExtension<'a> {
816	MutRef(&'a mut Box<dyn Extension>),
817	Owned(Box<dyn Extension>),
818}
819
820/// Overlayed extensions which are sourced from [`Extensions`].
821///
822/// The sourced extensions will be stored as mutable references,
823/// while extensions that are registered while execution are stored
824/// as owned references. After the execution of a runtime function, we
825/// can safely drop this object while not having modified the original
826/// list.
827#[cfg(feature = "std")]
828pub struct OverlayedExtensions<'a> {
829	extensions: Map<TypeId, OverlayedExtension<'a>>,
830}
831
832#[cfg(feature = "std")]
833impl<'a> OverlayedExtensions<'a> {
834	/// Create a new instance of overlaid extensions from the given extensions.
835	pub fn new(extensions: &'a mut Extensions) -> Self {
836		Self {
837			extensions: extensions
838				.iter_mut()
839				.map(|(k, v)| (*k, OverlayedExtension::MutRef(v)))
840				.collect(),
841		}
842	}
843
844	/// Return a mutable reference to the requested extension.
845	pub fn get_mut(&mut self, ext_type_id: TypeId) -> Option<&mut dyn Any> {
846		self.extensions.get_mut(&ext_type_id).map(|ext| match ext {
847			OverlayedExtension::MutRef(ext) => ext.as_mut_any(),
848			OverlayedExtension::Owned(ext) => ext.as_mut_any(),
849		})
850	}
851
852	/// Register extension `extension` with the given `type_id`.
853	pub fn register(
854		&mut self,
855		type_id: TypeId,
856		extension: Box<dyn Extension>,
857	) -> Result<(), sp_externalities::Error> {
858		match self.extensions.entry(type_id) {
859			MapEntry::Vacant(vacant) => {
860				vacant.insert(OverlayedExtension::Owned(extension));
861				Ok(())
862			},
863			MapEntry::Occupied(_) => Err(sp_externalities::Error::ExtensionAlreadyRegistered),
864		}
865	}
866
867	/// Deregister extension with the given `type_id`.
868	///
869	/// Returns `true` when there was an extension registered for the given `type_id`.
870	pub fn deregister(&mut self, type_id: TypeId) -> bool {
871		self.extensions.remove(&type_id).is_some()
872	}
873}
874
875#[cfg(test)]
876mod tests {
877	use super::*;
878	use crate::{ext::Ext, new_in_mem, InMemoryBackend};
879	use array_bytes::bytes2hex;
880	use sp_core::{traits::Externalities, Blake2Hasher};
881	use std::collections::BTreeMap;
882
883	fn assert_extrinsics(
884		overlay: &mut OverlayedChangeSet,
885		key: impl AsRef<[u8]>,
886		expected: Vec<u32>,
887	) {
888		assert_eq!(
889			overlay.get(key.as_ref()).unwrap().extrinsics().into_iter().collect::<Vec<_>>(),
890			expected
891		)
892	}
893
894	#[test]
895	fn overlayed_storage_works() {
896		let mut overlayed = OverlayedChanges::<Blake2Hasher>::default();
897
898		let key = vec![42, 69, 169, 142];
899
900		assert!(overlayed.storage(&key).is_none());
901
902		overlayed.start_transaction();
903
904		overlayed.set_storage(key.clone(), Some(vec![1, 2, 3]));
905		assert_eq!(overlayed.storage(&key).unwrap(), Some(&[1, 2, 3][..]));
906
907		overlayed.commit_transaction().unwrap();
908
909		assert_eq!(overlayed.storage(&key).unwrap(), Some(&[1, 2, 3][..]));
910
911		overlayed.start_transaction();
912
913		overlayed.set_storage(key.clone(), Some(vec![]));
914		assert_eq!(overlayed.storage(&key).unwrap(), Some(&[][..]));
915
916		overlayed.set_storage(key.clone(), None);
917		assert!(overlayed.storage(&key).unwrap().is_none());
918
919		overlayed.rollback_transaction().unwrap();
920
921		assert_eq!(overlayed.storage(&key).unwrap(), Some(&[1, 2, 3][..]));
922
923		overlayed.set_storage(key.clone(), None);
924		assert!(overlayed.storage(&key).unwrap().is_none());
925	}
926
927	#[test]
928	fn offchain_overlayed_storage_transactions_works() {
929		use sp_core::offchain::STORAGE_PREFIX;
930		fn check_offchain_content(
931			state: &OverlayedChanges<Blake2Hasher>,
932			nb_commit: usize,
933			expected: Vec<(Vec<u8>, Option<Vec<u8>>)>,
934		) {
935			let mut state = state.clone();
936			for _ in 0..nb_commit {
937				state.commit_transaction().unwrap();
938			}
939			let offchain_data: Vec<_> = state.offchain_drain_committed().collect();
940			let expected: Vec<_> = expected
941				.into_iter()
942				.map(|(key, value)| {
943					let change = match value {
944						Some(value) => OffchainOverlayedChange::SetValue(value),
945						None => OffchainOverlayedChange::Remove,
946					};
947					((STORAGE_PREFIX.to_vec(), key), change)
948				})
949				.collect();
950			assert_eq!(offchain_data, expected);
951		}
952
953		let mut overlayed = OverlayedChanges::default();
954
955		let key = vec![42, 69, 169, 142];
956
957		check_offchain_content(&overlayed, 0, vec![]);
958
959		overlayed.start_transaction();
960
961		overlayed.set_offchain_storage(key.as_slice(), Some(&[1, 2, 3][..]));
962		check_offchain_content(&overlayed, 1, vec![(key.clone(), Some(vec![1, 2, 3]))]);
963
964		overlayed.commit_transaction().unwrap();
965
966		check_offchain_content(&overlayed, 0, vec![(key.clone(), Some(vec![1, 2, 3]))]);
967
968		overlayed.start_transaction();
969
970		overlayed.set_offchain_storage(key.as_slice(), Some(&[][..]));
971		check_offchain_content(&overlayed, 1, vec![(key.clone(), Some(vec![]))]);
972
973		overlayed.set_offchain_storage(key.as_slice(), None);
974		check_offchain_content(&overlayed, 1, vec![(key.clone(), None)]);
975
976		overlayed.rollback_transaction().unwrap();
977
978		check_offchain_content(&overlayed, 0, vec![(key.clone(), Some(vec![1, 2, 3]))]);
979
980		overlayed.set_offchain_storage(key.as_slice(), None);
981		check_offchain_content(&overlayed, 0, vec![(key.clone(), None)]);
982	}
983
984	#[test]
985	fn overlayed_storage_root_works() {
986		let state_version = StateVersion::default();
987		let initial: BTreeMap<_, _> = vec![
988			(b"doe".to_vec(), b"reindeer".to_vec()),
989			(b"dog".to_vec(), b"puppyXXX".to_vec()),
990			(b"dogglesworth".to_vec(), b"catXXX".to_vec()),
991			(b"doug".to_vec(), b"notadog".to_vec()),
992		]
993		.into_iter()
994		.collect();
995		let backend = InMemoryBackend::<Blake2Hasher>::from((initial, state_version));
996		let mut overlay = OverlayedChanges::default();
997
998		overlay.start_transaction();
999		overlay.set_storage(b"dog".to_vec(), Some(b"puppy".to_vec()));
1000		overlay.set_storage(b"dogglesworth".to_vec(), Some(b"catYYY".to_vec()));
1001		overlay.set_storage(b"doug".to_vec(), Some(vec![]));
1002		overlay.commit_transaction().unwrap();
1003
1004		overlay.start_transaction();
1005		overlay.set_storage(b"dogglesworth".to_vec(), Some(b"cat".to_vec()));
1006		overlay.set_storage(b"doug".to_vec(), None);
1007
1008		{
1009			let mut ext = Ext::new(&mut overlay, &backend, None);
1010			let root = "39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa";
1011
1012			assert_eq!(bytes2hex("", &ext.storage_root(state_version)), root);
1013			// Calling a second time should use it from the cache
1014			assert_eq!(bytes2hex("", &ext.storage_root(state_version)), root);
1015		}
1016
1017		// Check that the storage root is recalculated
1018		overlay.set_storage(b"doug2".to_vec(), Some(b"yes".to_vec()));
1019
1020		let mut ext = Ext::new(&mut overlay, &backend, None);
1021		let root = "5c0a4e35cb967de785e1cb8743e6f24b6ff6d45155317f2078f6eb3fc4ff3e3d";
1022		assert_eq!(bytes2hex("", &ext.storage_root(state_version)), root);
1023	}
1024
1025	#[test]
1026	fn overlayed_child_storage_root_works() {
1027		let state_version = StateVersion::default();
1028		let child_info = ChildInfo::new_default(b"Child1");
1029		let child_info = &child_info;
1030		let backend = new_in_mem::<Blake2Hasher>();
1031		let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1032		overlay.start_transaction();
1033		overlay.set_child_storage(child_info, vec![20], Some(vec![20]));
1034		overlay.set_child_storage(child_info, vec![30], Some(vec![30]));
1035		overlay.set_child_storage(child_info, vec![40], Some(vec![40]));
1036		overlay.commit_transaction().unwrap();
1037		overlay.set_child_storage(child_info, vec![10], Some(vec![10]));
1038		overlay.set_child_storage(child_info, vec![30], None);
1039
1040		{
1041			let mut ext = Ext::new(&mut overlay, &backend, None);
1042			let child_root = "c02965e1df4dc5baf6977390ce67dab1d7a9b27a87c1afe27b50d29cc990e0f5";
1043			let root = "eafb765909c3ed5afd92a0c564acf4620d0234b31702e8e8e9b48da72a748838";
1044
1045			assert_eq!(
1046				bytes2hex("", &ext.child_storage_root(child_info, state_version)),
1047				child_root,
1048			);
1049
1050			assert_eq!(bytes2hex("", &ext.storage_root(state_version)), root);
1051
1052			// Calling a second time should use it from the cache
1053			assert_eq!(
1054				bytes2hex("", &ext.child_storage_root(child_info, state_version)),
1055				child_root,
1056			);
1057		}
1058	}
1059
1060	#[test]
1061	fn extrinsic_changes_are_collected() {
1062		let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1063		overlay.set_collect_extrinsics(true);
1064
1065		overlay.start_transaction();
1066
1067		overlay.set_storage(vec![100], Some(vec![101]));
1068
1069		overlay.set_extrinsic_index(0);
1070		overlay.set_storage(vec![1], Some(vec![2]));
1071
1072		overlay.set_extrinsic_index(1);
1073		overlay.set_storage(vec![3], Some(vec![4]));
1074
1075		overlay.set_extrinsic_index(2);
1076		overlay.set_storage(vec![1], Some(vec![6]));
1077
1078		assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2]);
1079		assert_extrinsics(&mut overlay.top, vec![3], vec![1]);
1080		assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]);
1081
1082		overlay.start_transaction();
1083
1084		overlay.set_extrinsic_index(3);
1085		overlay.set_storage(vec![3], Some(vec![7]));
1086
1087		overlay.set_extrinsic_index(4);
1088		overlay.set_storage(vec![1], Some(vec![8]));
1089
1090		assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2, 4]);
1091		assert_extrinsics(&mut overlay.top, vec![3], vec![1, 3]);
1092		assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]);
1093
1094		overlay.rollback_transaction().unwrap();
1095
1096		assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2]);
1097		assert_extrinsics(&mut overlay.top, vec![3], vec![1]);
1098		assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]);
1099	}
1100
1101	#[test]
1102	fn next_storage_key_change_works() {
1103		let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1104		overlay.start_transaction();
1105		overlay.set_storage(vec![20], Some(vec![20]));
1106		overlay.set_storage(vec![30], Some(vec![30]));
1107		overlay.set_storage(vec![40], Some(vec![40]));
1108		overlay.commit_transaction().unwrap();
1109		overlay.set_storage(vec![10], Some(vec![10]));
1110		overlay.set_storage(vec![30], None);
1111
1112		// next_prospective < next_committed
1113		let next_to_5 = overlay.iter_after(&[5]).next().unwrap();
1114		assert_eq!(next_to_5.0.to_vec(), vec![10]);
1115		assert_eq!(next_to_5.1.value(), Some(&vec![10]));
1116
1117		// next_committed < next_prospective
1118		let next_to_10 = overlay.iter_after(&[10]).next().unwrap();
1119		assert_eq!(next_to_10.0.to_vec(), vec![20]);
1120		assert_eq!(next_to_10.1.value(), Some(&vec![20]));
1121
1122		// next_committed == next_prospective
1123		let next_to_20 = overlay.iter_after(&[20]).next().unwrap();
1124		assert_eq!(next_to_20.0.to_vec(), vec![30]);
1125		assert_eq!(next_to_20.1.value(), None);
1126
1127		// next_committed, no next_prospective
1128		let next_to_30 = overlay.iter_after(&[30]).next().unwrap();
1129		assert_eq!(next_to_30.0.to_vec(), vec![40]);
1130		assert_eq!(next_to_30.1.value(), Some(&vec![40]));
1131
1132		overlay.set_storage(vec![50], Some(vec![50]));
1133		// next_prospective, no next_committed
1134		let next_to_40 = overlay.iter_after(&[40]).next().unwrap();
1135		assert_eq!(next_to_40.0.to_vec(), vec![50]);
1136		assert_eq!(next_to_40.1.value(), Some(&vec![50]));
1137	}
1138
1139	#[test]
1140	fn next_child_storage_key_change_works() {
1141		let child_info = ChildInfo::new_default(b"Child1");
1142		let child_info = &child_info;
1143		let child = child_info.storage_key();
1144		let mut overlay = OverlayedChanges::<Blake2Hasher>::default();
1145		overlay.start_transaction();
1146		overlay.set_child_storage(child_info, vec![20], Some(vec![20]));
1147		overlay.set_child_storage(child_info, vec![30], Some(vec![30]));
1148		overlay.set_child_storage(child_info, vec![40], Some(vec![40]));
1149		overlay.commit_transaction().unwrap();
1150		overlay.set_child_storage(child_info, vec![10], Some(vec![10]));
1151		overlay.set_child_storage(child_info, vec![30], None);
1152
1153		// next_prospective < next_committed
1154		let next_to_5 = overlay.child_iter_after(child, &[5]).next().unwrap();
1155		assert_eq!(next_to_5.0.to_vec(), vec![10]);
1156		assert_eq!(next_to_5.1.value(), Some(&vec![10]));
1157
1158		// next_committed < next_prospective
1159		let next_to_10 = overlay.child_iter_after(child, &[10]).next().unwrap();
1160		assert_eq!(next_to_10.0.to_vec(), vec![20]);
1161		assert_eq!(next_to_10.1.value(), Some(&vec![20]));
1162
1163		// next_committed == next_prospective
1164		let next_to_20 = overlay.child_iter_after(child, &[20]).next().unwrap();
1165		assert_eq!(next_to_20.0.to_vec(), vec![30]);
1166		assert_eq!(next_to_20.1.value(), None);
1167
1168		// next_committed, no next_prospective
1169		let next_to_30 = overlay.child_iter_after(child, &[30]).next().unwrap();
1170		assert_eq!(next_to_30.0.to_vec(), vec![40]);
1171		assert_eq!(next_to_30.1.value(), Some(&vec![40]));
1172
1173		overlay.set_child_storage(child_info, vec![50], Some(vec![50]));
1174		// next_prospective, no next_committed
1175		let next_to_40 = overlay.child_iter_after(child, &[40]).next().unwrap();
1176		assert_eq!(next_to_40.0.to_vec(), vec![50]);
1177		assert_eq!(next_to_40.1.value(), Some(&vec![50]));
1178	}
1179}