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

            
20
use std::{
21
	any::{Any, TypeId},
22
	panic::{AssertUnwindSafe, UnwindSafe},
23
};
24

            
25
use crate::{
26
	backend::Backend, ext::Ext, InMemoryBackend, OverlayedChanges, StorageKey, StorageValue,
27
	TrieBackendBuilder,
28
};
29

            
30
use hash_db::{HashDB, Hasher};
31
use sp_core::{
32
	offchain::testing::TestPersistentOffchainDB,
33
	storage::{
34
		well_known_keys::{is_child_storage_key, CODE},
35
		StateVersion, Storage,
36
	},
37
};
38
use sp_externalities::{Extension, ExtensionStore, Extensions};
39
use sp_trie::{PrefixedMemoryDB, StorageProof};
40

            
41
/// Simple HashMap-based Externalities impl.
42
pub struct TestExternalities<H>
43
where
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

            
58
impl<H> TestExternalities<H>
59
where
60
	H: Hasher + 'static,
61
	H::Out: Ord + 'static + codec::Codec,
62
{
63
	/// Get externalities implementation.
64
3540042
	pub fn ext(&mut self) -> Ext<H, InMemoryBackend<H>> {
65
3540042
		Ext::new(&mut self.overlay, &self.backend, Some(&mut self.extensions))
66
3540042
	}
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
3540042
	pub fn new_with_state_version(storage: Storage, state_version: StateVersion) -> Self {
75
3540042
		Self::new_with_code_and_state(&[], storage, state_version)
76
3540042
	}
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
3540042
	pub fn new_with_code_and_state(
91
3540042
		code: &[u8],
92
3540042
		mut storage: Storage,
93
3540042
		state_version: StateVersion,
94
3540042
	) -> Self {
95
3540042
		assert!(storage.top.keys().all(|key| !is_child_storage_key(key)));
96

            
97
3540042
		storage.top.insert(CODE.to_vec(), code.to_vec());
98
3540042

            
99
3540042
		let offchain_db = TestPersistentOffchainDB::new();
100
3540042

            
101
3540042
		let backend = (storage, state_version).into();
102
3540042

            
103
3540042
		TestExternalities {
104
3540042
			overlay: OverlayedChanges::default(),
105
3540042
			offchain_db,
106
3540042
			extensions: Default::default(),
107
3540042
			backend,
108
3540042
			state_version,
109
3540042
		}
110
3540042
	}
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
3540042
	pub fn execute_with<R>(&mut self, execute: impl FnOnce() -> R) -> R {
247
3540042
		let mut ext = self.ext();
248
3540042
		sp_externalities::set_and_run_with_externalities(&mut ext, execute)
249
3540042
	}
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` is set as externalities.
270
	///
271
	/// Returns the result of the given closure, if no panics occurred.
272
	/// Otherwise, returns `Err`.
273
	pub fn execute_with_safe<R>(
274
		&mut self,
275
		f: impl FnOnce() -> R + UnwindSafe,
276
	) -> Result<R, String> {
277
		let mut ext = AssertUnwindSafe(self.ext());
278
		std::panic::catch_unwind(move || {
279
			sp_externalities::set_and_run_with_externalities(&mut *ext, f)
280
		})
281
		.map_err(|e| format!("Closure panicked: {:?}", e))
282
	}
283
}
284

            
285
impl<H: Hasher> std::fmt::Debug for TestExternalities<H>
286
where
287
	H::Out: Ord + codec::Codec,
288
{
289
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
290
		let pairs: Vec<_> = self
291
			.backend
292
			.pairs(Default::default())
293
			.expect("creating an iterator over all of the pairs doesn't fail in tests")
294
			.collect();
295
		write!(f, "overlay: {:?}\nbackend: {:?}", self.overlay, pairs)
296
	}
297
}
298

            
299
impl<H> TestExternalities<H>
300
where
301
	H: Hasher,
302
	H::Out: Ord + 'static + codec::Codec,
303
{
304
	/// This doesn't test if they are in the same state, only if they contains the
305
	/// same data at this state
306
	pub fn eq(&mut self, other: &mut TestExternalities<H>) -> bool {
307
		self.as_backend().eq(&other.as_backend())
308
	}
309
}
310

            
311
impl<H: Hasher> Default for TestExternalities<H>
312
where
313
	H::Out: Ord + 'static + codec::Codec,
314
{
315
3540042
	fn default() -> Self {
316
3540042
		// default to default version.
317
3540042
		Self::new_with_state_version(Storage::default(), Default::default())
318
3540042
	}
319
}
320

            
321
impl<H: Hasher> From<Storage> for TestExternalities<H>
322
where
323
	H::Out: Ord + 'static + codec::Codec,
324
{
325
	fn from(storage: Storage) -> Self {
326
		Self::new_with_state_version(storage, Default::default())
327
	}
328
}
329

            
330
impl<H: Hasher> From<(Storage, StateVersion)> for TestExternalities<H>
331
where
332
	H::Out: Ord + 'static + codec::Codec,
333
{
334
	fn from((storage, state_version): (Storage, StateVersion)) -> Self {
335
		Self::new_with_state_version(storage, state_version)
336
	}
337
}
338

            
339
impl<H> sp_externalities::ExtensionStore for TestExternalities<H>
340
where
341
	H: Hasher,
342
	H::Out: Ord + codec::Codec,
343
{
344
	fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> {
345
		self.extensions.get_mut(type_id)
346
	}
347

            
348
	fn register_extension_with_type_id(
349
		&mut self,
350
		type_id: TypeId,
351
		extension: Box<dyn Extension>,
352
	) -> Result<(), sp_externalities::Error> {
353
		self.extensions.register_with_type_id(type_id, extension)
354
	}
355

            
356
	fn deregister_extension_by_type_id(
357
		&mut self,
358
		type_id: TypeId,
359
	) -> Result<(), sp_externalities::Error> {
360
		if self.extensions.deregister(type_id) {
361
			Ok(())
362
		} else {
363
			Err(sp_externalities::Error::ExtensionIsNotRegistered(type_id))
364
		}
365
	}
366
}
367

            
368
impl<H> sp_externalities::ExternalitiesExt for TestExternalities<H>
369
where
370
	H: Hasher,
371
	H::Out: Ord + codec::Codec,
372
{
373
	fn extension<T: Any + Extension>(&mut self) -> Option<&mut T> {
374
		self.extension_by_type_id(TypeId::of::<T>()).and_then(<dyn Any>::downcast_mut)
375
	}
376

            
377
	fn register_extension<T: Extension>(&mut self, ext: T) -> Result<(), sp_externalities::Error> {
378
		self.register_extension_with_type_id(TypeId::of::<T>(), Box::new(ext))
379
	}
380

            
381
	fn deregister_extension<T: Extension>(&mut self) -> Result<(), sp_externalities::Error> {
382
		self.deregister_extension_by_type_id(TypeId::of::<T>())
383
	}
384
}
385

            
386
#[cfg(test)]
387
mod tests {
388
	use super::*;
389
	use sp_core::{storage::ChildInfo, traits::Externalities, H256};
390
	use sp_runtime::traits::BlakeTwo256;
391

            
392
	#[test]
393
	fn commit_should_work() {
394
		let storage = Storage::default(); // avoid adding the trie threshold.
395
		let mut ext = TestExternalities::<BlakeTwo256>::from((storage, Default::default()));
396
		let mut ext = ext.ext();
397
		ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
398
		ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
399
		ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
400
		let root = array_bytes::hex_n_into_unchecked::<_, H256, 32>(
401
			"ed4d8c799d996add422395a6abd7545491d40bd838d738afafa1b8a4de625489",
402
		);
403
		assert_eq!(H256::from_slice(ext.storage_root(Default::default()).as_slice()), root);
404
	}
405

            
406
	#[test]
407
	fn raw_storage_drain_and_restore() {
408
		// Create a TestExternalities with some data in it.
409
		let mut original_ext =
410
			TestExternalities::<BlakeTwo256>::from((Default::default(), Default::default()));
411
		original_ext.insert(b"doe".to_vec(), b"reindeer".to_vec());
412
		original_ext.insert(b"dog".to_vec(), b"puppy".to_vec());
413
		original_ext.insert(b"dogglesworth".to_vec(), b"cat".to_vec());
414
		let child_info = ChildInfo::new_default(&b"test_child"[..]);
415
		original_ext.insert_child(child_info.clone(), b"cattytown".to_vec(), b"is_dark".to_vec());
416
		original_ext.insert_child(child_info.clone(), b"doggytown".to_vec(), b"is_sunny".to_vec());
417

            
418
		// Apply the backend to itself again to increase the ref count of all nodes.
419
		original_ext.backend.apply_transaction(
420
			*original_ext.backend.root(),
421
			original_ext.backend.clone().into_storage(),
422
		);
423

            
424
		// Ensure all have the correct ref count
425
		assert!(original_ext.backend.backend_storage().keys().values().all(|r| *r == 2));
426

            
427
		// Drain the raw storage and root.
428
		let root = *original_ext.backend.root();
429
		let (raw_storage, storage_root) = original_ext.into_raw_snapshot();
430

            
431
		// Load the raw storage and root into a new TestExternalities.
432
		let recovered_ext = TestExternalities::<BlakeTwo256>::from_raw_snapshot(
433
			raw_storage,
434
			storage_root,
435
			Default::default(),
436
		);
437

            
438
		// Check the storage root is the same as the original
439
		assert_eq!(root, *recovered_ext.backend.root());
440

            
441
		// Check the original storage key/values were recovered correctly
442
		assert_eq!(recovered_ext.backend.storage(b"doe").unwrap(), Some(b"reindeer".to_vec()));
443
		assert_eq!(recovered_ext.backend.storage(b"dog").unwrap(), Some(b"puppy".to_vec()));
444
		assert_eq!(recovered_ext.backend.storage(b"dogglesworth").unwrap(), Some(b"cat".to_vec()));
445

            
446
		// Check the original child storage key/values were recovered correctly
447
		assert_eq!(
448
			recovered_ext.backend.child_storage(&child_info, b"cattytown").unwrap(),
449
			Some(b"is_dark".to_vec())
450
		);
451
		assert_eq!(
452
			recovered_ext.backend.child_storage(&child_info, b"doggytown").unwrap(),
453
			Some(b"is_sunny".to_vec())
454
		);
455

            
456
		// Ensure all have the correct ref count after importing
457
		assert!(recovered_ext.backend.backend_storage().keys().values().all(|r| *r == 2));
458
	}
459

            
460
	#[test]
461
	fn set_and_retrieve_code() {
462
		let mut ext = TestExternalities::<BlakeTwo256>::default();
463
		let mut ext = ext.ext();
464

            
465
		let code = vec![1, 2, 3];
466
		ext.set_storage(CODE.to_vec(), code.clone());
467

            
468
		assert_eq!(&ext.storage(CODE).unwrap(), &code);
469
	}
470

            
471
	#[test]
472
	fn check_send() {
473
		fn assert_send<T: Send>() {}
474
		assert_send::<TestExternalities<BlakeTwo256>>();
475
	}
476

            
477
	#[test]
478
	fn commit_all_and_kill_child_storage() {
479
		let mut ext = TestExternalities::<BlakeTwo256>::default();
480
		let child_info = ChildInfo::new_default(&b"test_child"[..]);
481

            
482
		{
483
			let mut ext = ext.ext();
484
			ext.place_child_storage(&child_info, b"doe".to_vec(), Some(b"reindeer".to_vec()));
485
			ext.place_child_storage(&child_info, b"dog".to_vec(), Some(b"puppy".to_vec()));
486
			ext.place_child_storage(&child_info, b"dog2".to_vec(), Some(b"puppy2".to_vec()));
487
		}
488

            
489
		ext.commit_all().unwrap();
490

            
491
		{
492
			let mut ext = ext.ext();
493

            
494
			assert!(
495
				ext.kill_child_storage(&child_info, Some(2), None).maybe_cursor.is_some(),
496
				"Should not delete all keys"
497
			);
498

            
499
			assert!(ext.child_storage(&child_info, &b"doe"[..]).is_none());
500
			assert!(ext.child_storage(&child_info, &b"dog"[..]).is_none());
501
			assert!(ext.child_storage(&child_info, &b"dog2"[..]).is_some());
502
		}
503
	}
504

            
505
	#[test]
506
	fn as_backend_generates_same_backend_as_commit_all() {
507
		let mut ext = TestExternalities::<BlakeTwo256>::default();
508
		{
509
			let mut ext = ext.ext();
510
			ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
511
			ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
512
			ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
513
		}
514

            
515
		let backend = ext.as_backend();
516

            
517
		ext.commit_all().unwrap();
518
		assert!(ext.backend.eq(&backend), "Both backend should be equal.");
519
	}
520
}