referrerpolicy=no-referrer-when-downgrade

sp_state_machine/
testing.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//! Test implementation for Externalities.
19
20use std::{
21	any::{Any, TypeId},
22	panic::{AssertUnwindSafe, UnwindSafe},
23};
24
25use crate::{
26	backend::Backend, ext::Ext, InMemoryBackend, OverlayedChanges, StorageKey, StorageValue,
27	TrieBackendBuilder,
28};
29
30use hash_db::{HashDB, Hasher};
31use sp_core::{
32	offchain::testing::TestPersistentOffchainDB,
33	storage::{
34		well_known_keys::{is_child_storage_key, CODE},
35		StateVersion, Storage,
36	},
37};
38use sp_externalities::{Extension, ExtensionStore, Extensions};
39use sp_trie::{recorder::Recorder, PrefixedMemoryDB, StorageProof};
40
41/// Simple HashMap-based Externalities impl.
42pub struct TestExternalities<H>
43where
44	H: Hasher + 'static,
45	H::Out: codec::Codec + Ord,
46{
47	/// The overlay changed storage.
48	overlay: OverlayedChanges<H>,
49	offchain_db: TestPersistentOffchainDB,
50	/// Storage backend.
51	pub backend: InMemoryBackend<H>,
52	/// Extensions.
53	pub extensions: Extensions,
54	/// State version to use during tests.
55	pub state_version: StateVersion,
56}
57
58impl<H> TestExternalities<H>
59where
60	H: Hasher + 'static,
61	H::Out: Ord + 'static + codec::Codec,
62{
63	/// Get externalities implementation.
64	pub fn ext(&mut self) -> Ext<'_, H, InMemoryBackend<H>> {
65		Ext::new(&mut self.overlay, &self.backend, Some(&mut self.extensions))
66	}
67
68	/// Create a new instance of `TestExternalities` with storage.
69	pub fn new(storage: Storage) -> Self {
70		Self::new_with_code_and_state(&[], storage, Default::default())
71	}
72
73	/// Create a new instance of `TestExternalities` with storage for a given state version.
74	pub fn new_with_state_version(storage: Storage, state_version: StateVersion) -> Self {
75		Self::new_with_code_and_state(&[], storage, state_version)
76	}
77
78	/// New empty test externalities.
79	pub fn new_empty() -> Self {
80		Self::new_with_code_and_state(&[], Storage::default(), Default::default())
81	}
82
83	/// Create a new instance of `TestExternalities` with code and storage.
84	pub fn new_with_code(code: &[u8], storage: Storage) -> Self {
85		Self::new_with_code_and_state(code, storage, Default::default())
86	}
87
88	/// Create a new instance of `TestExternalities` with code and storage for a given state
89	/// version.
90	pub fn new_with_code_and_state(
91		code: &[u8],
92		mut storage: Storage,
93		state_version: StateVersion,
94	) -> Self {
95		assert!(storage.top.keys().all(|key| !is_child_storage_key(key)));
96
97		storage.top.insert(CODE.to_vec(), code.to_vec());
98
99		let offchain_db = TestPersistentOffchainDB::new();
100
101		let backend = (storage, state_version).into();
102
103		TestExternalities {
104			overlay: OverlayedChanges::default(),
105			offchain_db,
106			extensions: Default::default(),
107			backend,
108			state_version,
109		}
110	}
111
112	/// Returns the overlayed changes.
113	pub fn overlayed_changes(&self) -> &OverlayedChanges<H> {
114		&self.overlay
115	}
116
117	/// Move offchain changes from overlay to the persistent store.
118	pub fn persist_offchain_overlay(&mut self) {
119		self.offchain_db.apply_offchain_changes(self.overlay.offchain_drain_committed());
120	}
121
122	/// A shared reference type around the offchain worker storage.
123	pub fn offchain_db(&self) -> TestPersistentOffchainDB {
124		self.offchain_db.clone()
125	}
126
127	/// Batch insert key/values into backend
128	pub fn batch_insert<I>(&mut self, kvs: I)
129	where
130		I: IntoIterator<Item = (StorageKey, StorageValue)>,
131	{
132		self.backend.insert(
133			Some((None, kvs.into_iter().map(|(k, v)| (k, Some(v))).collect())),
134			self.state_version,
135		);
136	}
137
138	/// Insert key/value into backend
139	pub fn insert(&mut self, k: StorageKey, v: StorageValue) {
140		self.backend.insert(vec![(None, vec![(k, Some(v))])], self.state_version);
141	}
142
143	/// Insert key/value into backend.
144	///
145	/// This only supports inserting keys in child tries.
146	pub fn insert_child(&mut self, c: sp_core::storage::ChildInfo, k: StorageKey, v: StorageValue) {
147		self.backend.insert(vec![(Some(c), vec![(k, Some(v))])], self.state_version);
148	}
149
150	/// Registers the given extension for this instance.
151	pub fn register_extension<E: Any + Extension>(&mut self, ext: E) {
152		self.extensions.register(ext);
153	}
154
155	/// Sets raw storage key/values and a root.
156	///
157	/// This can be used as a fast way to restore the storage state from a backup because the trie
158	/// does not need to be computed.
159	pub fn from_raw_snapshot(
160		raw_storage: Vec<(Vec<u8>, (Vec<u8>, i32))>,
161		storage_root: H::Out,
162		state_version: StateVersion,
163	) -> Self {
164		let mut backend = PrefixedMemoryDB::default();
165
166		for (key, (v, ref_count)) in raw_storage {
167			let mut hash = H::Out::default();
168			let hash_len = hash.as_ref().len();
169
170			if key.len() < hash_len {
171				log::warn!("Invalid key in `from_raw_snapshot`: {key:?}");
172				continue
173			}
174
175			hash.as_mut().copy_from_slice(&key[(key.len() - hash_len)..]);
176
177			// Each time .emplace is called the internal MemoryDb ref count increments.
178			// Repeatedly call emplace to initialise the ref count to the correct value.
179			for _ in 0..ref_count {
180				backend.emplace(hash, (&key[..(key.len() - hash_len)], None), v.clone());
181			}
182		}
183
184		Self {
185			backend: TrieBackendBuilder::new(backend, storage_root).build(),
186			overlay: Default::default(),
187			offchain_db: Default::default(),
188			extensions: Default::default(),
189			state_version,
190		}
191	}
192
193	/// Drains the underlying raw storage key/values and returns the root hash.
194	///
195	/// Useful for backing up the storage in a format that can be quickly re-loaded.
196	pub fn into_raw_snapshot(mut self) -> (Vec<(Vec<u8>, (Vec<u8>, i32))>, H::Out) {
197		let raw_key_values = self
198			.backend
199			.backend_storage_mut()
200			.drain()
201			.into_iter()
202			.filter(|(_, (_, r))| *r > 0)
203			.collect::<Vec<(Vec<u8>, (Vec<u8>, i32))>>();
204
205		(raw_key_values, *self.backend.root())
206	}
207
208	/// Return a new backend with all pending changes.
209	///
210	/// In contrast to [`commit_all`](Self::commit_all) this will not panic if there are open
211	/// transactions.
212	pub fn as_backend(&mut self) -> InMemoryBackend<H> {
213		let top: Vec<_> = self
214			.overlay
215			.changes_mut()
216			.map(|(k, v)| (k.clone(), v.value().cloned()))
217			.collect();
218		let mut transaction = vec![(None, top)];
219
220		for (child_changes, child_info) in self.overlay.children_mut() {
221			transaction.push((
222				Some(child_info.clone()),
223				child_changes.map(|(k, v)| (k.clone(), v.value().cloned())).collect(),
224			))
225		}
226
227		self.backend.update(transaction, self.state_version)
228	}
229
230	/// Commit all pending changes to the underlying backend.
231	///
232	/// # Panic
233	///
234	/// This will panic if there are still open transactions.
235	pub fn commit_all(&mut self) -> Result<(), String> {
236		let changes = self.overlay.drain_storage_changes(&self.backend, self.state_version)?;
237
238		self.backend
239			.apply_transaction(changes.transaction_storage_root, changes.transaction);
240		Ok(())
241	}
242
243	/// Execute the given closure while `self` is set as externalities.
244	///
245	/// Returns the result of the given closure.
246	pub fn execute_with<R>(&mut self, execute: impl FnOnce() -> R) -> R {
247		let mut ext = self.ext();
248		sp_externalities::set_and_run_with_externalities(&mut ext, execute)
249	}
250
251	/// Execute the given closure while `self`, with `proving_backend` as backend, is set as
252	/// externalities.
253	///
254	/// This implementation will wipe the proof recorded in between calls. Consecutive calls will
255	/// get their own proof from scratch.
256	pub fn execute_and_prove<R>(&mut self, execute: impl FnOnce() -> R) -> (R, StorageProof) {
257		let proving_backend = TrieBackendBuilder::wrap(&self.backend)
258			.with_recorder(Default::default())
259			.build();
260		let mut proving_ext =
261			Ext::new(&mut self.overlay, &proving_backend, Some(&mut self.extensions));
262
263		let outcome = sp_externalities::set_and_run_with_externalities(&mut proving_ext, execute);
264		let proof = proving_backend.extract_proof().expect("Failed to extract storage proof");
265
266		(outcome, proof)
267	}
268
269	/// Execute the given closure while `self` set as externalities and the given `proof_recorder`
270	/// enabled.
271	pub fn execute_with_recorder<R>(
272		&mut self,
273		proof_recorder: Recorder<H>,
274		execute: impl FnOnce() -> R,
275	) -> R {
276		let proving_backend =
277			TrieBackendBuilder::wrap(&self.backend).with_recorder(proof_recorder).build();
278		let mut proving_ext =
279			Ext::new(&mut self.overlay, &proving_backend, Some(&mut self.extensions));
280
281		sp_externalities::set_and_run_with_externalities(&mut proving_ext, execute)
282	}
283
284	/// Execute the given closure while `self` is set as externalities.
285	///
286	/// Returns the result of the given closure, if no panics occurred.
287	/// Otherwise, returns `Err`.
288	pub fn execute_with_safe<R>(
289		&mut self,
290		f: impl FnOnce() -> R + UnwindSafe,
291	) -> Result<R, String> {
292		let mut ext = AssertUnwindSafe(self.ext());
293		std::panic::catch_unwind(move || {
294			sp_externalities::set_and_run_with_externalities(&mut *ext, f)
295		})
296		.map_err(|e| format!("Closure panicked: {:?}", e))
297	}
298
299	/// Resets the overlay to its default state.
300	pub fn reset_overlay(&mut self) {
301		self.overlay = Default::default();
302	}
303}
304
305impl<H: Hasher> std::fmt::Debug for TestExternalities<H>
306where
307	H::Out: Ord + codec::Codec,
308{
309	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
310		let pairs: Vec<_> = self
311			.backend
312			.pairs(Default::default())
313			.expect("creating an iterator over all of the pairs doesn't fail in tests")
314			.collect();
315		write!(f, "overlay: {:?}\nbackend: {:?}", self.overlay, pairs)
316	}
317}
318
319impl<H> TestExternalities<H>
320where
321	H: Hasher,
322	H::Out: Ord + 'static + codec::Codec,
323{
324	/// This doesn't test if they are in the same state, only if they contains the
325	/// same data at this state
326	pub fn eq(&mut self, other: &mut TestExternalities<H>) -> bool {
327		self.as_backend().eq(&other.as_backend())
328	}
329}
330
331impl<H: Hasher> Default for TestExternalities<H>
332where
333	H::Out: Ord + 'static + codec::Codec,
334{
335	fn default() -> Self {
336		// default to default version.
337		Self::new_with_state_version(Storage::default(), Default::default())
338	}
339}
340
341impl<H: Hasher> From<Storage> for TestExternalities<H>
342where
343	H::Out: Ord + 'static + codec::Codec,
344{
345	fn from(storage: Storage) -> Self {
346		Self::new_with_state_version(storage, Default::default())
347	}
348}
349
350impl<H: Hasher> From<(Storage, StateVersion)> for TestExternalities<H>
351where
352	H::Out: Ord + 'static + codec::Codec,
353{
354	fn from((storage, state_version): (Storage, StateVersion)) -> Self {
355		Self::new_with_state_version(storage, state_version)
356	}
357}
358
359impl<H> sp_externalities::ExtensionStore for TestExternalities<H>
360where
361	H: Hasher,
362	H::Out: Ord + codec::Codec,
363{
364	fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> {
365		self.extensions.get_mut(type_id)
366	}
367
368	fn register_extension_with_type_id(
369		&mut self,
370		type_id: TypeId,
371		extension: Box<dyn Extension>,
372	) -> Result<(), sp_externalities::Error> {
373		self.extensions.register_with_type_id(type_id, extension)
374	}
375
376	fn deregister_extension_by_type_id(
377		&mut self,
378		type_id: TypeId,
379	) -> Result<(), sp_externalities::Error> {
380		if self.extensions.deregister(type_id) {
381			Ok(())
382		} else {
383			Err(sp_externalities::Error::ExtensionIsNotRegistered(type_id))
384		}
385	}
386}
387
388impl<H> sp_externalities::ExternalitiesExt for TestExternalities<H>
389where
390	H: Hasher,
391	H::Out: Ord + codec::Codec,
392{
393	fn extension<T: Any + Extension>(&mut self) -> Option<&mut T> {
394		self.extension_by_type_id(TypeId::of::<T>()).and_then(<dyn Any>::downcast_mut)
395	}
396
397	fn register_extension<T: Extension>(&mut self, ext: T) -> Result<(), sp_externalities::Error> {
398		self.register_extension_with_type_id(TypeId::of::<T>(), Box::new(ext))
399	}
400
401	fn deregister_extension<T: Extension>(&mut self) -> Result<(), sp_externalities::Error> {
402		self.deregister_extension_by_type_id(TypeId::of::<T>())
403	}
404}
405
406#[cfg(test)]
407mod tests {
408	use super::*;
409	use sp_core::{storage::ChildInfo, traits::Externalities, H256};
410	use sp_runtime::traits::BlakeTwo256;
411
412	#[test]
413	fn commit_should_work() {
414		let storage = Storage::default(); // avoid adding the trie threshold.
415		let mut ext = TestExternalities::<BlakeTwo256>::from((storage, Default::default()));
416		let mut ext = ext.ext();
417		ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
418		ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
419		ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
420		let root = array_bytes::hex_n_into_unchecked::<_, H256, 32>(
421			"ed4d8c799d996add422395a6abd7545491d40bd838d738afafa1b8a4de625489",
422		);
423		assert_eq!(H256::from_slice(ext.storage_root(Default::default()).as_slice()), root);
424	}
425
426	#[test]
427	fn raw_storage_drain_and_restore() {
428		// Create a TestExternalities with some data in it.
429		let mut original_ext =
430			TestExternalities::<BlakeTwo256>::from((Default::default(), Default::default()));
431		original_ext.insert(b"doe".to_vec(), b"reindeer".to_vec());
432		original_ext.insert(b"dog".to_vec(), b"puppy".to_vec());
433		original_ext.insert(b"dogglesworth".to_vec(), b"cat".to_vec());
434		let child_info = ChildInfo::new_default(&b"test_child"[..]);
435		original_ext.insert_child(child_info.clone(), b"cattytown".to_vec(), b"is_dark".to_vec());
436		original_ext.insert_child(child_info.clone(), b"doggytown".to_vec(), b"is_sunny".to_vec());
437
438		// Apply the backend to itself again to increase the ref count of all nodes.
439		original_ext.backend.apply_transaction(
440			*original_ext.backend.root(),
441			original_ext.backend.clone().into_storage(),
442		);
443
444		// Ensure all have the correct ref count
445		assert!(original_ext.backend.backend_storage().keys().values().all(|r| *r == 2));
446
447		// Drain the raw storage and root.
448		let root = *original_ext.backend.root();
449		let (raw_storage, storage_root) = original_ext.into_raw_snapshot();
450
451		// Load the raw storage and root into a new TestExternalities.
452		let recovered_ext = TestExternalities::<BlakeTwo256>::from_raw_snapshot(
453			raw_storage,
454			storage_root,
455			Default::default(),
456		);
457
458		// Check the storage root is the same as the original
459		assert_eq!(root, *recovered_ext.backend.root());
460
461		// Check the original storage key/values were recovered correctly
462		assert_eq!(recovered_ext.backend.storage(b"doe").unwrap(), Some(b"reindeer".to_vec()));
463		assert_eq!(recovered_ext.backend.storage(b"dog").unwrap(), Some(b"puppy".to_vec()));
464		assert_eq!(recovered_ext.backend.storage(b"dogglesworth").unwrap(), Some(b"cat".to_vec()));
465
466		// Check the original child storage key/values were recovered correctly
467		assert_eq!(
468			recovered_ext.backend.child_storage(&child_info, b"cattytown").unwrap(),
469			Some(b"is_dark".to_vec())
470		);
471		assert_eq!(
472			recovered_ext.backend.child_storage(&child_info, b"doggytown").unwrap(),
473			Some(b"is_sunny".to_vec())
474		);
475
476		// Ensure all have the correct ref count after importing
477		assert!(recovered_ext.backend.backend_storage().keys().values().all(|r| *r == 2));
478	}
479
480	#[test]
481	fn set_and_retrieve_code() {
482		let mut ext = TestExternalities::<BlakeTwo256>::default();
483		let mut ext = ext.ext();
484
485		let code = vec![1, 2, 3];
486		ext.set_storage(CODE.to_vec(), code.clone());
487
488		assert_eq!(&ext.storage(CODE).unwrap(), &code);
489	}
490
491	#[test]
492	fn check_send() {
493		fn assert_send<T: Send>() {}
494		assert_send::<TestExternalities<BlakeTwo256>>();
495	}
496
497	#[test]
498	fn commit_all_and_kill_child_storage() {
499		let mut ext = TestExternalities::<BlakeTwo256>::default();
500		let child_info = ChildInfo::new_default(&b"test_child"[..]);
501
502		{
503			let mut ext = ext.ext();
504			ext.place_child_storage(&child_info, b"doe".to_vec(), Some(b"reindeer".to_vec()));
505			ext.place_child_storage(&child_info, b"dog".to_vec(), Some(b"puppy".to_vec()));
506			ext.place_child_storage(&child_info, b"dog2".to_vec(), Some(b"puppy2".to_vec()));
507		}
508
509		ext.commit_all().unwrap();
510
511		{
512			let mut ext = ext.ext();
513
514			assert!(
515				ext.kill_child_storage(&child_info, Some(2), None).maybe_cursor.is_some(),
516				"Should not delete all keys"
517			);
518
519			assert!(ext.child_storage(&child_info, &b"doe"[..]).is_none());
520			assert!(ext.child_storage(&child_info, &b"dog"[..]).is_none());
521			assert!(ext.child_storage(&child_info, &b"dog2"[..]).is_some());
522		}
523	}
524
525	#[test]
526	fn as_backend_generates_same_backend_as_commit_all() {
527		let mut ext = TestExternalities::<BlakeTwo256>::default();
528		{
529			let mut ext = ext.ext();
530			ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
531			ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
532			ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
533		}
534
535		let backend = ext.as_backend();
536
537		ext.commit_all().unwrap();
538		assert!(ext.backend.eq(&backend), "Both backend should be equal.");
539	}
540}