referrerpolicy=no-referrer-when-downgrade

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, 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
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	/// Length of `transaction_index_ops` at the start of each open transaction.
104	transaction_index_ops_checkpoints: Vec<usize>,
105	/// True if extrinsics stats must be collected.
106	collect_extrinsics: bool,
107	/// Collect statistic on this execution.
108	stats: StateMachineStats,
109	/// Caches the "storage transaction" that is created while calling `storage_root`.
110	///
111	/// This transaction can be applied to the backend to persist the state changes.
112	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/// Transaction index operation.
160#[derive(Debug, Clone)]
161pub enum IndexOperation {
162	/// Insert transaction into index.
163	Insert {
164		/// Extrinsic index in the current block.
165		extrinsic: u32,
166		/// Data content hash.
167		hash: Vec<u8>,
168		/// Indexed data size.
169		size: u32,
170	},
171	/// Renew existing transaction storage.
172	Renew {
173		/// Extrinsic index in the current block.
174		extrinsic: u32,
175		/// Referenced index hash.
176		hash: Vec<u8>,
177	},
178}
179
180/// A storage changes structure that can be generated by the data collected in [`OverlayedChanges`].
181///
182/// This contains all the changes to the storage and transactions to apply theses changes to the
183/// backend.
184pub struct StorageChanges<H: Hasher> {
185	/// All changes to the main storage.
186	///
187	/// A value of `None` means that it was deleted.
188	pub main_storage_changes: StorageCollection,
189	/// All changes to the child storages.
190	pub child_storage_changes: ChildStorageCollection,
191	/// Offchain state changes to write to the offchain database.
192	pub offchain_storage_changes: OffchainChangesCollection,
193	/// A transaction for the backend that contains all changes from
194	/// [`main_storage_changes`](StorageChanges::main_storage_changes) and from
195	/// [`child_storage_changes`](StorageChanges::child_storage_changes).
196	/// [`offchain_storage_changes`](StorageChanges::offchain_storage_changes).
197	pub transaction: BackendTransaction<H>,
198	/// The storage root after applying the transaction.
199	pub transaction_storage_root: H::Out,
200	/// Changes to the transaction index,
201	#[cfg(feature = "std")]
202	pub transaction_index_changes: Vec<IndexOperation>,
203}
204
205#[cfg(feature = "std")]
206impl<H: Hasher> StorageChanges<H> {
207	/// Deconstruct into the inner values
208	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
243/// Storage transactions are calculated as part of the `storage_root`.
244/// These transactions can be reused for importing the block into the
245/// storage. So, we cache them to not require a recomputation of those transactions.
246struct StorageTransactionCache<H: Hasher> {
247	/// Contains the changes for the main and the child storages as one transaction.
248	transaction: BackendTransaction<H>,
249	/// The storage root after applying the transaction.
250	transaction_storage_root: H::Out,
251	/// The state version that was used to compute the transaction and the root.
252	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	/// Whether no changes are contained in the top nor in any of the child changes.
287	pub fn is_empty(&self) -> bool {
288		self.top.is_empty() && self.children.is_empty()
289	}
290
291	/// Ask to collect/not to collect extrinsics indices where key(s) has been changed.
292	pub fn set_collect_extrinsics(&mut self, collect_extrinsics: bool) {
293		self.collect_extrinsics = collect_extrinsics;
294	}
295
296	/// Returns a double-Option: None if the key is unknown (i.e. and the query should be referred
297	/// to the backend); Some(None) if the key has been deleted. Some(Some(...)) for a key whose
298	/// value has been set.
299	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	/// Should be called when there are changes that require to reset the
309	/// `storage_transaction_cache`.
310	fn mark_dirty(&mut self) {
311		self.storage_transaction_cache = None;
312	}
313
314	/// Returns a double-Option: None if the key is unknown (i.e. and the query should be referred
315	/// to the backend); Some(None) if the key has been deleted. Some(Some(...)) for a key whose
316	/// value has been set.
317	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	/// Set a new value for the specified key.
326	///
327	/// Can be rolled back or committed when called inside a transaction.
328	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	/// Append a element to storage, init with existing value if first write.
338	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	/// Set a new value for the specified key and child.
351	///
352	/// `None` can be used to delete a value specified by the given key.
353	///
354	/// Can be rolled back or committed when called inside a transaction.
355	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	/// Clear child storage of given storage key.
378	///
379	/// Can be rolled back or committed when called inside a transaction.
380	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	/// Removes all key-value pairs which keys share the given prefix.
396	///
397	/// Can be rolled back or committed when called inside a transaction.
398	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	/// Removes all key-value pairs which keys share the given prefix.
406	///
407	/// Can be rolled back or committed when called inside a transaction
408	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	/// Returns the current nesting depth of the transaction stack.
424	///
425	/// A value of zero means that no transaction is open and changes are committed on write.
426	pub fn transaction_depth(&self) -> usize {
427		// The top changeset and all child changesets transact in lockstep and are
428		// therefore always at the same transaction depth.
429		self.top.transaction_depth()
430	}
431
432	/// Start a new nested transaction.
433	///
434	/// This allows to either commit or roll back all changes that where made while this
435	/// transaction was open. Any transaction must be closed by either `rollback_transaction` or
436	/// `commit_transaction` before this overlay can be converted into storage changes.
437	///
438	/// Changes made without any open transaction are committed immediately.
439	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	/// Rollback the last transaction started by `start_transaction`.
449	///
450	/// Any changes made during that transaction are discarded. Returns an error if
451	/// there is no open transaction that can be rolled back.
452	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	/// Commit the last transaction started by `start_transaction`.
471	///
472	/// Any changes made during that transaction are committed. Returns an error if there
473	/// is no open transaction that can be committed.
474	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	/// Call this before transferring control to the runtime.
490	///
491	/// This protects all existing transactions from being removed by the runtime.
492	/// Calling this while already inside the runtime will return an error.
493	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	/// Call this when control returns from the runtime.
508	///
509	/// This rollbacks all dangling transaction left open by the runtime.
510	/// Calling this while outside the runtime will return an error.
511	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	/// Consume all changes (top + children) and return them.
534	///
535	/// After calling this function no more changes are contained in this changeset.
536	///
537	/// Panics:
538	/// Panics if `transaction_depth() > 0`
539	pub fn offchain_drain_committed(
540		&mut self,
541	) -> impl Iterator<Item = ((StorageKey, StorageKey), OffchainOverlayedChange)> {
542		self.offchain.drain()
543	}
544
545	/// Get an iterator over all child changes as seen by the current transaction.
546	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	/// Get an iterator over all child changes as seen by the current transaction.
553	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	/// Get an iterator over all top changes as been by the current transaction.
561	pub fn changes(&self) -> impl Iterator<Item = (&StorageKey, &OverlayedValue)> {
562		self.top.changes()
563	}
564
565	/// Get an iterator over all top changes as been by the current transaction.
566	pub fn changes_mut(&mut self) -> impl Iterator<Item = (&StorageKey, &mut OverlayedValue)> {
567		self.top.changes_mut()
568	}
569
570	/// Get an optional iterator over all child changes stored under the supplied key.
571	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	/// Get an optional iterator over all child changes stored under the supplied key.
579	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	/// Get an list of all index operations.
589	pub fn transaction_index_ops(&self) -> &[IndexOperation] {
590		&self.transaction_index_ops
591	}
592
593	/// Drain all changes into a [`StorageChanges`] instance. Leave empty overlay in place.
594	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			// If the transaction does not exist, we generate it.
605			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	/// Inserts storage entry responsible for current extrinsic index.
640	#[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	/// Returns current extrinsic index to use in changes trie construction.
646	/// None is returned if it is not set or changes trie config is not set.
647	/// Persistent value (from the backend) can be ignored because runtime must
648	/// set this index before first and unset after last extrinsic is executed.
649	/// Changes that are made outside of extrinsics, are marked with
650	/// `NO_EXTRINSIC_INDEX` index.
651	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	/// Generate the storage root using `backend` and all changes
660	/// as seen by the current transaction.
661	///
662	/// Returns the storage root and whether it was already cached.
663	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	/// Generate the child storage root using `backend` and all child changes
696	/// as seen by the current transaction.
697	///
698	/// Returns the child storage root and whether it was already cached.
699	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				// V1 is equivalent to V0 on empty root.
720				.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			// We store update in the overlay in order to be able to use
734			// 'self.storage_transaction' cache. This is brittle as it rely on Ext only querying
735			// the trie backend for storage root.
736			// A better design would be to manage 'child_storage_transaction' in a
737			// similar way as 'storage_transaction' but for each child trie.
738			self.set_storage(prefixed_storage_key.into_inner(), (!is_empty).then(|| root.encode()));
739
740			self.mark_dirty();
741
742			root
743		} else {
744			// empty overlay
745			let root = backend
746				.storage(prefixed_storage_key.as_slice())?
747				.and_then(|k| Decode::decode(&mut &k[..]).ok())
748				// V1 is equivalent to V0 on empty root.
749				.unwrap_or_else(empty_child_trie_root::<LayoutV1<H>>);
750
751			root
752		};
753
754		Ok((root, false))
755	}
756
757	/// Returns an iterator over the keys (in lexicographic order) following `key` (excluding `key`)
758	/// alongside its value.
759	pub fn iter_after(&mut self, key: &[u8]) -> impl Iterator<Item = (&[u8], &mut OverlayedValue)> {
760		self.top.changes_after(key)
761	}
762
763	/// Returns an iterator over the keys (in lexicographic order) following `key` (excluding `key`)
764	/// alongside its value for the given `storage_key` child.
765	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	/// Read only access ot offchain overlay.
778	pub fn offchain(&self) -> &OffchainOverlayedChanges {
779		&self.offchain
780	}
781
782	/// Write a key value pair to the offchain storage overlay.
783	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	/// Add transaction index operation.
792	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/// An overlayed extension is either a mutable reference
836/// or an owned extension.
837#[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/// Overlayed extensions which are sourced from [`Extensions`].
854///
855/// The sourced extensions will be stored as mutable references,
856/// while extensions that are registered while execution are stored
857/// as owned references. After the execution of a runtime function, we
858/// can safely drop this object while not having modified the original
859/// list.
860#[cfg(feature = "std")]
861pub struct OverlayedExtensions<'a> {
862	extensions: Map<TypeId, OverlayedExtension<'a>>,
863}
864
865#[cfg(feature = "std")]
866impl<'a> OverlayedExtensions<'a> {
867	/// Create a new instance of overlaid extensions from the given extensions.
868	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	/// Return a mutable reference to the requested extension.
878	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	/// Register extension `extension` with the given `type_id`.
886	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	/// Deregister extension with the given `type_id`.
901	///
902	/// Returns `true` when there was an extension registered for the given `type_id`.
903	pub fn deregister(&mut self, type_id: TypeId) -> bool {
904		self.extensions.remove(&type_id).is_some()
905	}
906
907	/// Start a transaction.
908	///
909	/// The `ty` declares the type of transaction.
910	pub fn start_transaction(&mut self, ty: TransactionType) {
911		self.extensions.values_mut().for_each(|e| e.extension().start_transaction(ty));
912	}
913
914	/// Commit a transaction.
915	///
916	/// The `ty` declares the type of transaction.
917	pub fn commit_transaction(&mut self, ty: TransactionType) {
918		self.extensions.values_mut().for_each(|e| e.extension().commit_transaction(ty));
919	}
920
921	/// Rollback a transaction.
922	///
923	/// The `ty` declares the type of transaction.
924	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	// The node indexes whatever these operations name, while the runtime only keeps a record of
1056	// it when the dispatch succeeds. An operation outliving a rollback makes the two disagree.
1057	#[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			// Calling a second time should use it from the cache
1141			assert_eq!(bytes2hex("", &ext.storage_root()), root);
1142		}
1143
1144		// Check that the storage root is recalculated
1145		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		// `TRIE_VALUE_NODE_THRESHOLD` is 33, so a value of 64 bytes is inlined under V0
1155		// but stored as a separate hashed node under V1, producing distinct roots.
1156		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		// A request for a different state version must NOT return the cached V0 root.
1169		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		// And switching back to V0 must again recompute, not reuse the V1 cache.
1177		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			// Calling a second time should use it from the cache
1206			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		// next_prospective < next_committed
1263		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		// next_committed < next_prospective
1268		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		// next_committed == next_prospective
1273		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		// next_committed, no next_prospective
1278		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		// next_prospective, no next_committed
1284		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		// next_prospective < next_committed
1304		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		// next_committed < next_prospective
1309		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		// next_committed == next_prospective
1314		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		// next_committed, no next_prospective
1319		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		// next_prospective, no next_committed
1325		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}