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), self.state_version)
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 = Ext::new(
261			&mut self.overlay,
262			&proving_backend,
263			Some(&mut self.extensions),
264			self.state_version,
265		);
266
267		let outcome = sp_externalities::set_and_run_with_externalities(&mut proving_ext, execute);
268		let proof = proving_backend.extract_proof().expect("Failed to extract storage proof");
269
270		(outcome, proof)
271	}
272
273	/// Execute the given closure while `self` set as externalities and the given `proof_recorder`
274	/// enabled.
275	pub fn execute_with_recorder<R>(
276		&mut self,
277		proof_recorder: Recorder<H>,
278		execute: impl FnOnce() -> R,
279	) -> R {
280		let proving_backend =
281			TrieBackendBuilder::wrap(&self.backend).with_recorder(proof_recorder).build();
282		let mut proving_ext = Ext::new(
283			&mut self.overlay,
284			&proving_backend,
285			Some(&mut self.extensions),
286			self.state_version,
287		);
288
289		sp_externalities::set_and_run_with_externalities(&mut proving_ext, execute)
290	}
291
292	/// Execute the given closure while `self` is set as externalities.
293	///
294	/// Returns the result of the given closure, if no panics occurred.
295	/// Otherwise, returns `Err`.
296	pub fn execute_with_safe<R>(
297		&mut self,
298		f: impl FnOnce() -> R + UnwindSafe,
299	) -> Result<R, String> {
300		let mut ext = AssertUnwindSafe(self.ext());
301		std::panic::catch_unwind(move || {
302			sp_externalities::set_and_run_with_externalities(&mut *ext, f)
303		})
304		.map_err(|e| format!("Closure panicked: {:?}", e))
305	}
306
307	/// Resets the overlay to its default state.
308	pub fn reset_overlay(&mut self) {
309		self.overlay = Default::default();
310	}
311}
312
313impl<H: Hasher> std::fmt::Debug for TestExternalities<H>
314where
315	H::Out: Ord + codec::Codec,
316{
317	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
318		let pairs: Vec<_> = self
319			.backend
320			.pairs(Default::default())
321			.expect("creating an iterator over all of the pairs doesn't fail in tests")
322			.collect();
323		write!(f, "overlay: {:?}\nbackend: {:?}", self.overlay, pairs)
324	}
325}
326
327impl<H> TestExternalities<H>
328where
329	H: Hasher,
330	H::Out: Ord + 'static + codec::Codec,
331{
332	/// This doesn't test if they are in the same state, only if they contains the
333	/// same data at this state
334	pub fn eq(&mut self, other: &mut TestExternalities<H>) -> bool {
335		self.as_backend().eq(&other.as_backend())
336	}
337}
338
339impl<H: Hasher> Default for TestExternalities<H>
340where
341	H::Out: Ord + 'static + codec::Codec,
342{
343	fn default() -> Self {
344		// default to default version.
345		Self::new_with_state_version(Storage::default(), Default::default())
346	}
347}
348
349impl<H: Hasher> From<Storage> for TestExternalities<H>
350where
351	H::Out: Ord + 'static + codec::Codec,
352{
353	fn from(storage: Storage) -> Self {
354		Self::new_with_state_version(storage, Default::default())
355	}
356}
357
358impl<H: Hasher> From<(Storage, StateVersion)> for TestExternalities<H>
359where
360	H::Out: Ord + 'static + codec::Codec,
361{
362	fn from((storage, state_version): (Storage, StateVersion)) -> Self {
363		Self::new_with_state_version(storage, state_version)
364	}
365}
366
367impl<H> sp_externalities::ExtensionStore for TestExternalities<H>
368where
369	H: Hasher,
370	H::Out: Ord + codec::Codec,
371{
372	fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> {
373		self.extensions.get_mut(type_id)
374	}
375
376	fn register_extension_with_type_id(
377		&mut self,
378		type_id: TypeId,
379		extension: Box<dyn Extension>,
380	) -> Result<(), sp_externalities::Error> {
381		self.extensions.register_with_type_id(type_id, extension)
382	}
383
384	fn deregister_extension_by_type_id(
385		&mut self,
386		type_id: TypeId,
387	) -> Result<(), sp_externalities::Error> {
388		if self.extensions.deregister(type_id) {
389			Ok(())
390		} else {
391			Err(sp_externalities::Error::ExtensionIsNotRegistered(type_id))
392		}
393	}
394}
395
396impl<H> sp_externalities::ExternalitiesExt for TestExternalities<H>
397where
398	H: Hasher,
399	H::Out: Ord + codec::Codec,
400{
401	fn extension<T: Any + Extension>(&mut self) -> Option<&mut T> {
402		self.extension_by_type_id(TypeId::of::<T>()).and_then(<dyn Any>::downcast_mut)
403	}
404
405	fn register_extension<T: Extension>(&mut self, ext: T) -> Result<(), sp_externalities::Error> {
406		self.register_extension_with_type_id(TypeId::of::<T>(), Box::new(ext))
407	}
408
409	fn deregister_extension<T: Extension>(&mut self) -> Result<(), sp_externalities::Error> {
410		self.deregister_extension_by_type_id(TypeId::of::<T>())
411	}
412}
413
414#[cfg(test)]
415mod tests {
416	use super::*;
417	use sp_core::{storage::ChildInfo, traits::Externalities, H256};
418	use sp_runtime::traits::BlakeTwo256;
419
420	#[test]
421	fn commit_should_work() {
422		let storage = Storage::default(); // avoid adding the trie threshold.
423		let mut ext = TestExternalities::<BlakeTwo256>::from((storage, Default::default()));
424		let mut ext = ext.ext();
425		ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
426		ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
427		ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
428		let root = array_bytes::hex_n_into_unchecked::<_, H256, 32>(
429			"ed4d8c799d996add422395a6abd7545491d40bd838d738afafa1b8a4de625489",
430		);
431		assert_eq!(H256::from_slice(ext.storage_root().as_slice()), root);
432	}
433
434	#[test]
435	fn raw_storage_drain_and_restore() {
436		// Create a TestExternalities with some data in it.
437		let mut original_ext =
438			TestExternalities::<BlakeTwo256>::from((Default::default(), Default::default()));
439		original_ext.insert(b"doe".to_vec(), b"reindeer".to_vec());
440		original_ext.insert(b"dog".to_vec(), b"puppy".to_vec());
441		original_ext.insert(b"dogglesworth".to_vec(), b"cat".to_vec());
442		let child_info = ChildInfo::new_default(&b"test_child"[..]);
443		original_ext.insert_child(child_info.clone(), b"cattytown".to_vec(), b"is_dark".to_vec());
444		original_ext.insert_child(child_info.clone(), b"doggytown".to_vec(), b"is_sunny".to_vec());
445
446		// Apply the backend to itself again to increase the ref count of all nodes.
447		original_ext.backend.apply_transaction(
448			*original_ext.backend.root(),
449			original_ext.backend.clone().into_storage(),
450		);
451
452		// Ensure all have the correct ref count
453		assert!(original_ext.backend.backend_storage().keys().values().all(|r| *r == 2));
454
455		// Drain the raw storage and root.
456		let root = *original_ext.backend.root();
457		let (raw_storage, storage_root) = original_ext.into_raw_snapshot();
458
459		// Load the raw storage and root into a new TestExternalities.
460		let recovered_ext = TestExternalities::<BlakeTwo256>::from_raw_snapshot(
461			raw_storage,
462			storage_root,
463			Default::default(),
464		);
465
466		// Check the storage root is the same as the original
467		assert_eq!(root, *recovered_ext.backend.root());
468
469		// Check the original storage key/values were recovered correctly
470		assert_eq!(recovered_ext.backend.storage(b"doe").unwrap(), Some(b"reindeer".to_vec()));
471		assert_eq!(recovered_ext.backend.storage(b"dog").unwrap(), Some(b"puppy".to_vec()));
472		assert_eq!(recovered_ext.backend.storage(b"dogglesworth").unwrap(), Some(b"cat".to_vec()));
473
474		// Check the original child storage key/values were recovered correctly
475		assert_eq!(
476			recovered_ext.backend.child_storage(&child_info, b"cattytown").unwrap(),
477			Some(b"is_dark".to_vec())
478		);
479		assert_eq!(
480			recovered_ext.backend.child_storage(&child_info, b"doggytown").unwrap(),
481			Some(b"is_sunny".to_vec())
482		);
483
484		// Ensure all have the correct ref count after importing
485		assert!(recovered_ext.backend.backend_storage().keys().values().all(|r| *r == 2));
486	}
487
488	#[test]
489	fn set_and_retrieve_code() {
490		let mut ext = TestExternalities::<BlakeTwo256>::default();
491		let mut ext = ext.ext();
492
493		let code = vec![1, 2, 3];
494		ext.set_storage(CODE.to_vec(), code.clone());
495
496		assert_eq!(&ext.storage(CODE).unwrap(), &code);
497	}
498
499	#[test]
500	fn check_send() {
501		fn assert_send<T: Send>() {}
502		assert_send::<TestExternalities<BlakeTwo256>>();
503	}
504
505	#[test]
506	fn commit_all_and_kill_child_storage() {
507		let mut ext = TestExternalities::<BlakeTwo256>::default();
508		let child_info = ChildInfo::new_default(&b"test_child"[..]);
509
510		{
511			let mut ext = ext.ext();
512			ext.place_child_storage(&child_info, b"doe".to_vec(), Some(b"reindeer".to_vec()));
513			ext.place_child_storage(&child_info, b"dog".to_vec(), Some(b"puppy".to_vec()));
514			ext.place_child_storage(&child_info, b"dog2".to_vec(), Some(b"puppy2".to_vec()));
515		}
516
517		ext.commit_all().unwrap();
518
519		{
520			let mut ext = ext.ext();
521
522			assert!(
523				ext.kill_child_storage(&child_info, Some(2), None).maybe_cursor.is_some(),
524				"Should not delete all keys"
525			);
526
527			assert!(ext.child_storage(&child_info, &b"doe"[..]).is_none());
528			assert!(ext.child_storage(&child_info, &b"dog"[..]).is_none());
529			assert!(ext.child_storage(&child_info, &b"dog2"[..]).is_some());
530		}
531	}
532
533	#[test]
534	fn as_backend_generates_same_backend_as_commit_all() {
535		let mut ext = TestExternalities::<BlakeTwo256>::default();
536		{
537			let mut ext = ext.ext();
538			ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
539			ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
540			ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
541		}
542
543		let backend = ext.as_backend();
544
545		ext.commit_all().unwrap();
546		assert!(ext.backend.eq(&backend), "Both backend should be equal.");
547	}
548}