sp_state_machine/
basic.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//! Basic implementation for Externalities.
19
20use crate::{Backend, OverlayedChanges, StorageKey, StorageValue};
21use codec::Encode;
22use hash_db::Hasher;
23use log::warn;
24use sp_core::{
25	storage::{
26		well_known_keys::is_child_storage_key, ChildInfo, StateVersion, Storage, TrackedStorageKey,
27	},
28	traits::Externalities,
29	Blake2Hasher,
30};
31use sp_externalities::{Extension, Extensions, MultiRemovalResults};
32use sp_trie::{empty_child_trie_root, LayoutV0, LayoutV1, TrieConfiguration};
33use std::{
34	any::{Any, TypeId},
35	collections::BTreeMap,
36};
37
38/// Simple Map-based Externalities impl.
39#[derive(Debug)]
40pub struct BasicExternalities {
41	overlay: OverlayedChanges<Blake2Hasher>,
42	extensions: Extensions,
43}
44
45impl BasicExternalities {
46	/// Create a new instance of `BasicExternalities`
47	pub fn new(inner: Storage) -> Self {
48		BasicExternalities { overlay: inner.into(), extensions: Default::default() }
49	}
50
51	/// New basic externalities with empty storage.
52	pub fn new_empty() -> Self {
53		Self::new(Storage::default())
54	}
55
56	/// Insert key/value
57	pub fn insert(&mut self, k: StorageKey, v: StorageValue) {
58		self.overlay.set_storage(k, Some(v));
59	}
60
61	/// Consume self and returns inner storages
62	#[cfg(feature = "std")]
63	pub fn into_storages(mut self) -> Storage {
64		Storage {
65			top: self
66				.overlay
67				.changes_mut()
68				.filter_map(|(k, v)| v.value().map(|v| (k.to_vec(), v.to_vec())))
69				.collect(),
70			children_default: self
71				.overlay
72				.children_mut()
73				.map(|(iter, i)| {
74					(
75						i.storage_key().to_vec(),
76						sp_core::storage::StorageChild {
77							data: iter
78								.filter_map(|(k, v)| v.value().map(|v| (k.to_vec(), v.to_vec())))
79								.collect(),
80							child_info: i.clone(),
81						},
82					)
83				})
84				.collect(),
85		}
86	}
87
88	/// Execute the given closure `f` with the externalities set and initialized with `storage`.
89	///
90	/// Returns the result of the closure and updates `storage` with all changes.
91	#[cfg(feature = "std")]
92	pub fn execute_with_storage<R>(
93		storage: &mut sp_core::storage::Storage,
94		f: impl FnOnce() -> R,
95	) -> R {
96		let mut ext = Self::new(std::mem::take(storage));
97
98		let r = ext.execute_with(f);
99
100		*storage = ext.into_storages();
101
102		r
103	}
104
105	/// Execute the given closure while `self` is set as externalities.
106	///
107	/// Returns the result of the given closure.
108	pub fn execute_with<R>(&mut self, f: impl FnOnce() -> R) -> R {
109		sp_externalities::set_and_run_with_externalities(self, f)
110	}
111
112	/// List of active extensions.
113	pub fn extensions(&mut self) -> &mut Extensions {
114		&mut self.extensions
115	}
116
117	/// Register an extension.
118	pub fn register_extension(&mut self, ext: impl Extension) {
119		self.extensions.register(ext);
120	}
121}
122
123#[cfg(test)]
124impl PartialEq for BasicExternalities {
125	fn eq(&self, other: &Self) -> bool {
126		self.overlay
127			.changes()
128			.map(|(k, v)| (k, v.value_ref().materialize()))
129			.collect::<BTreeMap<_, _>>() ==
130			other
131				.overlay
132				.changes()
133				.map(|(k, v)| (k, v.value_ref().materialize()))
134				.collect::<BTreeMap<_, _>>() &&
135			self.overlay
136				.children()
137				.map(|(iter, i)| {
138					(
139						i,
140						iter.map(|(k, v)| (k, v.value_ref().materialize()))
141							.collect::<BTreeMap<_, _>>(),
142					)
143				})
144				.collect::<BTreeMap<_, _>>() ==
145				other
146					.overlay
147					.children()
148					.map(|(iter, i)| {
149						(
150							i,
151							iter.map(|(k, v)| (k, v.value_ref().materialize()))
152								.collect::<BTreeMap<_, _>>(),
153						)
154					})
155					.collect::<BTreeMap<_, _>>()
156	}
157}
158
159impl FromIterator<(StorageKey, StorageValue)> for BasicExternalities {
160	fn from_iter<I: IntoIterator<Item = (StorageKey, StorageValue)>>(iter: I) -> Self {
161		let mut t = Self::default();
162		iter.into_iter().for_each(|(k, v)| t.insert(k, v));
163		t
164	}
165}
166
167impl Default for BasicExternalities {
168	fn default() -> Self {
169		Self::new(Default::default())
170	}
171}
172
173impl From<BTreeMap<StorageKey, StorageValue>> for BasicExternalities {
174	fn from(map: BTreeMap<StorageKey, StorageValue>) -> Self {
175		Self::from_iter(map.into_iter())
176	}
177}
178
179impl Externalities for BasicExternalities {
180	fn set_offchain_storage(&mut self, _key: &[u8], _value: Option<&[u8]>) {}
181
182	fn storage(&mut self, key: &[u8]) -> Option<StorageValue> {
183		self.overlay.storage(key).and_then(|v| v.map(|v| v.to_vec()))
184	}
185
186	fn storage_hash(&mut self, key: &[u8]) -> Option<Vec<u8>> {
187		self.storage(key).map(|v| Blake2Hasher::hash(&v).encode())
188	}
189
190	fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option<StorageValue> {
191		self.overlay.child_storage(child_info, key).and_then(|v| v.map(|v| v.to_vec()))
192	}
193
194	fn child_storage_hash(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option<Vec<u8>> {
195		self.child_storage(child_info, key).map(|v| Blake2Hasher::hash(&v).encode())
196	}
197
198	fn next_storage_key(&mut self, key: &[u8]) -> Option<StorageKey> {
199		self.overlay.iter_after(key).find_map(|(k, v)| v.value().map(|_| k.to_vec()))
200	}
201
202	fn next_child_storage_key(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option<StorageKey> {
203		self.overlay
204			.child_iter_after(child_info.storage_key(), key)
205			.find_map(|(k, v)| v.value().map(|_| k.to_vec()))
206	}
207
208	fn place_storage(&mut self, key: StorageKey, maybe_value: Option<StorageValue>) {
209		if is_child_storage_key(&key) {
210			warn!(target: "trie", "Refuse to set child storage key via main storage");
211			return
212		}
213
214		self.overlay.set_storage(key, maybe_value)
215	}
216
217	fn place_child_storage(
218		&mut self,
219		child_info: &ChildInfo,
220		key: StorageKey,
221		value: Option<StorageValue>,
222	) {
223		self.overlay.set_child_storage(child_info, key, value);
224	}
225
226	fn kill_child_storage(
227		&mut self,
228		child_info: &ChildInfo,
229		_maybe_limit: Option<u32>,
230		_maybe_cursor: Option<&[u8]>,
231	) -> MultiRemovalResults {
232		let count = self.overlay.clear_child_storage(child_info);
233		MultiRemovalResults { maybe_cursor: None, backend: count, unique: count, loops: count }
234	}
235
236	fn clear_prefix(
237		&mut self,
238		prefix: &[u8],
239		_maybe_limit: Option<u32>,
240		_maybe_cursor: Option<&[u8]>,
241	) -> MultiRemovalResults {
242		if is_child_storage_key(prefix) {
243			warn!(
244				target: "trie",
245				"Refuse to clear prefix that is part of child storage key via main storage"
246			);
247			let maybe_cursor = Some(prefix.to_vec());
248			return MultiRemovalResults { maybe_cursor, backend: 0, unique: 0, loops: 0 }
249		}
250
251		let count = self.overlay.clear_prefix(prefix);
252		MultiRemovalResults { maybe_cursor: None, backend: count, unique: count, loops: count }
253	}
254
255	fn clear_child_prefix(
256		&mut self,
257		child_info: &ChildInfo,
258		prefix: &[u8],
259		_maybe_limit: Option<u32>,
260		_maybe_cursor: Option<&[u8]>,
261	) -> MultiRemovalResults {
262		let count = self.overlay.clear_child_prefix(child_info, prefix);
263		MultiRemovalResults { maybe_cursor: None, backend: count, unique: count, loops: count }
264	}
265
266	fn storage_append(&mut self, key: Vec<u8>, element: Vec<u8>) {
267		self.overlay.append_storage(key, element, Default::default);
268	}
269
270	fn storage_root(&mut self, state_version: StateVersion) -> Vec<u8> {
271		let mut top = self
272			.overlay
273			.changes_mut()
274			.filter_map(|(k, v)| v.value().map(|v| (k.clone(), v.clone())))
275			.collect::<BTreeMap<_, _>>();
276		// Single child trie implementation currently allows using the same child
277		// empty root for all child trie. Using null storage key until multiple
278		// type of child trie support.
279		let empty_hash = empty_child_trie_root::<LayoutV1<Blake2Hasher>>();
280		for child_info in self.overlay.children().map(|d| d.1.clone()).collect::<Vec<_>>() {
281			let child_root = self.child_storage_root(&child_info, state_version);
282			if empty_hash[..] == child_root[..] {
283				top.remove(child_info.prefixed_storage_key().as_slice());
284			} else {
285				top.insert(child_info.prefixed_storage_key().into_inner(), child_root);
286			}
287		}
288
289		match state_version {
290			StateVersion::V0 => LayoutV0::<Blake2Hasher>::trie_root(top).as_ref().into(),
291			StateVersion::V1 => LayoutV1::<Blake2Hasher>::trie_root(top).as_ref().into(),
292		}
293	}
294
295	fn child_storage_root(
296		&mut self,
297		child_info: &ChildInfo,
298		state_version: StateVersion,
299	) -> Vec<u8> {
300		if let Some((data, child_info)) = self.overlay.child_changes_mut(child_info.storage_key()) {
301			let delta =
302				data.into_iter().map(|(k, v)| (k.as_ref(), v.value().map(|v| v.as_slice())));
303			crate::in_memory_backend::new_in_mem::<Blake2Hasher>()
304				.child_storage_root(&child_info, delta, state_version)
305				.0
306		} else {
307			empty_child_trie_root::<LayoutV1<Blake2Hasher>>()
308		}
309		.encode()
310	}
311
312	fn storage_start_transaction(&mut self) {
313		self.overlay.start_transaction()
314	}
315
316	fn storage_rollback_transaction(&mut self) -> Result<(), ()> {
317		self.overlay.rollback_transaction().map_err(drop)
318	}
319
320	fn storage_commit_transaction(&mut self) -> Result<(), ()> {
321		self.overlay.commit_transaction().map_err(drop)
322	}
323
324	fn wipe(&mut self) {}
325
326	fn commit(&mut self) {}
327
328	fn read_write_count(&self) -> (u32, u32, u32, u32) {
329		unimplemented!("read_write_count is not supported in Basic")
330	}
331
332	fn reset_read_write_count(&mut self) {
333		unimplemented!("reset_read_write_count is not supported in Basic")
334	}
335
336	fn get_whitelist(&self) -> Vec<TrackedStorageKey> {
337		unimplemented!("get_whitelist is not supported in Basic")
338	}
339
340	fn set_whitelist(&mut self, _: Vec<TrackedStorageKey>) {
341		unimplemented!("set_whitelist is not supported in Basic")
342	}
343
344	fn get_read_and_written_keys(&self) -> Vec<(Vec<u8>, u32, u32, bool)> {
345		unimplemented!("get_read_and_written_keys is not supported in Basic")
346	}
347}
348
349impl sp_externalities::ExtensionStore for BasicExternalities {
350	fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> {
351		self.extensions.get_mut(type_id)
352	}
353
354	fn register_extension_with_type_id(
355		&mut self,
356		type_id: TypeId,
357		extension: Box<dyn sp_externalities::Extension>,
358	) -> Result<(), sp_externalities::Error> {
359		self.extensions.register_with_type_id(type_id, extension)
360	}
361
362	fn deregister_extension_by_type_id(
363		&mut self,
364		type_id: TypeId,
365	) -> Result<(), sp_externalities::Error> {
366		if self.extensions.deregister(type_id) {
367			Ok(())
368		} else {
369			Err(sp_externalities::Error::ExtensionIsNotRegistered(type_id))
370		}
371	}
372}
373
374#[cfg(test)]
375mod tests {
376	use super::*;
377	use sp_core::{
378		map,
379		storage::{well_known_keys::CODE, Storage, StorageChild},
380	};
381
382	#[test]
383	fn commit_should_work() {
384		let mut ext = BasicExternalities::default();
385		ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
386		ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
387		ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
388		let root = array_bytes::hex2bytes_unchecked(
389			"39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa",
390		);
391
392		assert_eq!(&ext.storage_root(StateVersion::default())[..], &root);
393	}
394
395	#[test]
396	fn set_and_retrieve_code() {
397		let mut ext = BasicExternalities::default();
398
399		let code = vec![1, 2, 3];
400		ext.set_storage(CODE.to_vec(), code.clone());
401
402		assert_eq!(&ext.storage(CODE).unwrap(), &code);
403	}
404
405	#[test]
406	fn children_works() {
407		let child_info = ChildInfo::new_default(b"storage_key");
408		let child_info = &child_info;
409		let mut ext = BasicExternalities::new(Storage {
410			top: Default::default(),
411			children_default: map![
412				child_info.storage_key().to_vec() => StorageChild {
413					data: map![	b"doe".to_vec() => b"reindeer".to_vec()	],
414					child_info: child_info.to_owned(),
415				}
416			],
417		});
418
419		assert_eq!(ext.child_storage(child_info, b"doe"), Some(b"reindeer".to_vec()));
420
421		ext.set_child_storage(child_info, b"dog".to_vec(), b"puppy".to_vec());
422		assert_eq!(ext.child_storage(child_info, b"dog"), Some(b"puppy".to_vec()));
423
424		ext.clear_child_storage(child_info, b"dog");
425		assert_eq!(ext.child_storage(child_info, b"dog"), None);
426
427		let _ = ext.kill_child_storage(child_info, None, None);
428		assert_eq!(ext.child_storage(child_info, b"doe"), None);
429	}
430
431	#[test]
432	fn kill_child_storage_returns_num_elements_removed() {
433		let child_info = ChildInfo::new_default(b"storage_key");
434		let child_info = &child_info;
435		let mut ext = BasicExternalities::new(Storage {
436			top: Default::default(),
437			children_default: map![
438				child_info.storage_key().to_vec() => StorageChild {
439					data: map![
440						b"doe".to_vec() => b"reindeer".to_vec(),
441						b"dog".to_vec() => b"puppy".to_vec(),
442						b"hello".to_vec() => b"world".to_vec(),
443					],
444					child_info: child_info.to_owned(),
445				}
446			],
447		});
448
449		let res = ext.kill_child_storage(child_info, None, None);
450		assert_eq!(res.deconstruct(), (None, 3, 3, 3));
451	}
452
453	#[test]
454	fn basic_externalities_is_empty() {
455		// Make sure no values are set by default in `BasicExternalities`.
456		let storage = BasicExternalities::new_empty().into_storages();
457		assert!(storage.top.is_empty());
458		assert!(storage.children_default.is_empty());
459	}
460}