tp_state_machine/
backend.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2017-2021 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//! State machine backends. These manage the code and storage of contracts.
19
20use tetsy_hash_db::Hasher;
21use codec::{Decode, Encode};
22use tet_core::{
23	storage::{ChildInfo, well_known_keys, TrackedStorageKey}
24};
25use crate::{
26	trie_backend::TrieBackend,
27	trie_backend_essence::TrieBackendStorage,
28	UsageInfo, StorageKey, StorageValue, StorageCollection, ChildStorageCollection,
29};
30use tetcore_std::vec::Vec;
31#[cfg(feature = "std")]
32use tet_core::traits::RuntimeCode;
33
34/// A state backend is used to read state data and can have changes committed
35/// to it.
36///
37/// The clone operation (if implemented) should be cheap.
38pub trait Backend<H: Hasher>: tetcore_std::fmt::Debug {
39	/// An error type when fetching data is not possible.
40	type Error: super::Error;
41
42	/// Storage changes to be applied if committing
43	type Transaction: Consolidate + Default + Send;
44
45	/// Type of trie backend storage.
46	type TrieBackendStorage: TrieBackendStorage<H>;
47
48	/// Get keyed storage or None if there is nothing associated.
49	fn storage(&self, key: &[u8]) -> Result<Option<StorageValue>, Self::Error>;
50
51	/// Get keyed storage value hash or None if there is nothing associated.
52	fn storage_hash(&self, key: &[u8]) -> Result<Option<H::Out>, Self::Error> {
53		self.storage(key).map(|v| v.map(|v| H::hash(&v)))
54	}
55
56	/// Get keyed child storage or None if there is nothing associated.
57	fn child_storage(
58		&self,
59		child_info: &ChildInfo,
60		key: &[u8],
61	) -> Result<Option<StorageValue>, Self::Error>;
62
63	/// Get child keyed storage value hash or None if there is nothing associated.
64	fn child_storage_hash(
65		&self,
66		child_info: &ChildInfo,
67		key: &[u8],
68	) -> Result<Option<H::Out>, Self::Error> {
69		self.child_storage(child_info, key).map(|v| v.map(|v| H::hash(&v)))
70	}
71
72	/// true if a key exists in storage.
73	fn exists_storage(&self, key: &[u8]) -> Result<bool, Self::Error> {
74		Ok(self.storage(key)?.is_some())
75	}
76
77	/// true if a key exists in child storage.
78	fn exists_child_storage(
79		&self,
80		child_info: &ChildInfo,
81		key: &[u8],
82	) -> Result<bool, Self::Error> {
83		Ok(self.child_storage(child_info, key)?.is_some())
84	}
85
86	/// Return the next key in storage in lexicographic order or `None` if there is no value.
87	fn next_storage_key(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error>;
88
89	/// Return the next key in child storage in lexicographic order or `None` if there is no value.
90	fn next_child_storage_key(
91		&self,
92		child_info: &ChildInfo,
93		key: &[u8]
94	) -> Result<Option<StorageKey>, Self::Error>;
95
96	/// Retrieve all entries keys of child storage and call `f` for each of those keys.
97	/// Aborts as soon as `f` returns false.
98	fn apply_to_child_keys_while<F: FnMut(&[u8]) -> bool>(
99		&self,
100		child_info: &ChildInfo,
101		f: F,
102	);
103
104	/// Retrieve all entries keys which start with the given prefix and
105	/// call `f` for each of those keys.
106	fn for_keys_with_prefix<F: FnMut(&[u8])>(&self, prefix: &[u8], mut f: F) {
107		self.for_key_values_with_prefix(prefix, |k, _v| f(k))
108	}
109
110	/// Retrieve all entries keys and values of which start with the given prefix and
111	/// call `f` for each of those keys.
112	fn for_key_values_with_prefix<F: FnMut(&[u8], &[u8])>(&self, prefix: &[u8], f: F);
113
114
115	/// Retrieve all child entries keys which start with the given prefix and
116	/// call `f` for each of those keys.
117	fn for_child_keys_with_prefix<F: FnMut(&[u8])>(
118		&self,
119		child_info: &ChildInfo,
120		prefix: &[u8],
121		f: F,
122	);
123
124	/// Calculate the storage root, with given delta over what is already stored in
125	/// the backend, and produce a "transaction" that can be used to commit.
126	/// Does not include child storage updates.
127	fn storage_root<'a>(
128		&self,
129		delta: impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
130	) -> (H::Out, Self::Transaction) where H::Out: Ord;
131
132	/// Calculate the child storage root, with given delta over what is already stored in
133	/// the backend, and produce a "transaction" that can be used to commit. The second argument
134	/// is true if child storage root equals default storage root.
135	fn child_storage_root<'a>(
136		&self,
137		child_info: &ChildInfo,
138		delta: impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
139	) -> (H::Out, bool, Self::Transaction) where H::Out: Ord;
140
141	/// Get all key/value pairs into a Vec.
142	fn pairs(&self) -> Vec<(StorageKey, StorageValue)>;
143
144	/// Get all keys with given prefix
145	fn keys(&self, prefix: &[u8]) -> Vec<StorageKey> {
146		let mut all = Vec::new();
147		self.for_keys_with_prefix(prefix, |k| all.push(k.to_vec()));
148		all
149	}
150
151	/// Get all keys of child storage with given prefix
152	fn child_keys(
153		&self,
154		child_info: &ChildInfo,
155		prefix: &[u8],
156	) -> Vec<StorageKey> {
157		let mut all = Vec::new();
158		self.for_child_keys_with_prefix(child_info, prefix, |k| all.push(k.to_vec()));
159		all
160	}
161
162	/// Try convert into trie backend.
163	fn as_trie_backend(&mut self) -> Option<&TrieBackend<Self::TrieBackendStorage, H>> {
164		None
165	}
166
167	/// Calculate the storage root, with given delta over what is already stored
168	/// in the backend, and produce a "transaction" that can be used to commit.
169	/// Does include child storage updates.
170	fn full_storage_root<'a>(
171		&self,
172		delta: impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
173		child_deltas: impl Iterator<Item = (
174			&'a ChildInfo,
175			impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
176		)>,
177	) -> (H::Out, Self::Transaction) where H::Out: Ord + Encode {
178		let mut txs: Self::Transaction = Default::default();
179		let mut child_roots: Vec<_> = Default::default();
180		// child first
181		for (child_info, child_delta) in child_deltas {
182			let (child_root, empty, child_txs) =
183				self.child_storage_root(&child_info, child_delta);
184			let prefixed_storage_key = child_info.prefixed_storage_key();
185			txs.consolidate(child_txs);
186			if empty {
187				child_roots.push((prefixed_storage_key.into_inner(), None));
188			} else {
189				child_roots.push((prefixed_storage_key.into_inner(), Some(child_root.encode())));
190			}
191		}
192		let (root, parent_txs) = self.storage_root(delta
193			.map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))
194			.chain(
195				child_roots
196					.iter()
197					.map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))
198			)
199		);
200		txs.consolidate(parent_txs);
201		(root, txs)
202	}
203
204	/// Register stats from overlay of state machine.
205	///
206	/// By default nothing is registered.
207	fn register_overlay_stats(&mut self, _stats: &crate::stats::StateMachineStats);
208
209	/// Query backend usage statistics (i/o, memory)
210	///
211	/// Not all implementations are expected to be able to do this. In the
212	/// case when they don't, empty statistics is returned.
213	fn usage_info(&self) -> UsageInfo;
214
215	/// Wipe the state database.
216	fn wipe(&self) -> Result<(), Self::Error> {
217		unimplemented!()
218	}
219
220	/// Commit given transaction to storage.
221	fn commit(
222		&self,
223		_: H::Out,
224		_: Self::Transaction,
225		_: StorageCollection,
226		_: ChildStorageCollection,
227	) -> Result<(), Self::Error> {
228		unimplemented!()
229	}
230
231	/// Get the read/write count of the db
232	fn read_write_count(&self) -> (u32, u32, u32, u32) {
233		unimplemented!()
234	}
235
236	/// Get the read/write count of the db
237	fn reset_read_write_count(&self) {
238		unimplemented!()
239	}
240
241	/// Get the whitelist for tracking db reads/writes
242	fn get_whitelist(&self) -> Vec<TrackedStorageKey> {
243		Default::default()
244	}
245
246	/// Update the whitelist for tracking db reads/writes
247	fn set_whitelist(&self, _: Vec<TrackedStorageKey>) {}
248}
249
250impl<'a, T: Backend<H>, H: Hasher> Backend<H> for &'a T {
251	type Error = T::Error;
252	type Transaction = T::Transaction;
253	type TrieBackendStorage = T::TrieBackendStorage;
254
255	fn storage(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error> {
256		(*self).storage(key)
257	}
258
259	fn child_storage(
260		&self,
261		child_info: &ChildInfo,
262		key: &[u8],
263	) -> Result<Option<StorageKey>, Self::Error> {
264		(*self).child_storage(child_info, key)
265	}
266
267	fn apply_to_child_keys_while<F: FnMut(&[u8]) -> bool>(
268		&self,
269		child_info: &ChildInfo,
270		f: F,
271	) {
272		(*self).apply_to_child_keys_while(child_info, f)
273	}
274
275	fn next_storage_key(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error> {
276		(*self).next_storage_key(key)
277	}
278
279	fn next_child_storage_key(
280		&self,
281		child_info: &ChildInfo,
282		key: &[u8],
283	) -> Result<Option<StorageKey>, Self::Error> {
284		(*self).next_child_storage_key(child_info, key)
285	}
286
287	fn for_keys_with_prefix<F: FnMut(&[u8])>(&self, prefix: &[u8], f: F) {
288		(*self).for_keys_with_prefix(prefix, f)
289	}
290
291	fn for_child_keys_with_prefix<F: FnMut(&[u8])>(
292		&self,
293		child_info: &ChildInfo,
294		prefix: &[u8],
295		f: F,
296	) {
297		(*self).for_child_keys_with_prefix(child_info, prefix, f)
298	}
299
300	fn storage_root<'b>(
301		&self,
302		delta: impl Iterator<Item=(&'b [u8], Option<&'b [u8]>)>,
303	) -> (H::Out, Self::Transaction) where H::Out: Ord {
304		(*self).storage_root(delta)
305	}
306
307	fn child_storage_root<'b>(
308		&self,
309		child_info: &ChildInfo,
310		delta: impl Iterator<Item=(&'b [u8], Option<&'b [u8]>)>,
311	) -> (H::Out, bool, Self::Transaction) where H::Out: Ord {
312		(*self).child_storage_root(child_info, delta)
313	}
314
315	fn pairs(&self) -> Vec<(StorageKey, StorageValue)> {
316		(*self).pairs()
317	}
318
319	fn for_key_values_with_prefix<F: FnMut(&[u8], &[u8])>(&self, prefix: &[u8], f: F) {
320		(*self).for_key_values_with_prefix(prefix, f);
321	}
322
323	fn register_overlay_stats(&mut self, _stats: &crate::stats::StateMachineStats) {	}
324
325	fn usage_info(&self) -> UsageInfo {
326		(*self).usage_info()
327	}
328}
329
330/// Trait that allows consolidate two transactions together.
331pub trait Consolidate {
332	/// Consolidate two transactions into one.
333	fn consolidate(&mut self, other: Self);
334}
335
336impl Consolidate for () {
337	fn consolidate(&mut self, _: Self) {
338		()
339	}
340}
341
342impl Consolidate for Vec<(
343		Option<ChildInfo>,
344		StorageCollection,
345	)> {
346	fn consolidate(&mut self, mut other: Self) {
347		self.append(&mut other);
348	}
349}
350
351impl<H: Hasher, KF: tp_trie::KeyFunction<H>> Consolidate for tp_trie::GenericMemoryDB<H, KF> {
352	fn consolidate(&mut self, other: Self) {
353		tp_trie::GenericMemoryDB::consolidate(self, other)
354	}
355}
356
357/// Insert input pairs into memory db.
358#[cfg(test)]
359pub(crate) fn insert_into_memory_db<H, I>(mdb: &mut tp_trie::MemoryDB<H>, input: I) -> Option<H::Out>
360	where
361		H: Hasher,
362		I: IntoIterator<Item=(StorageKey, StorageValue)>,
363{
364	use tp_trie::{TrieMut, trie_types::TrieDBMut};
365
366	let mut root = <H as Hasher>::Out::default();
367	{
368		let mut trie = TrieDBMut::<H>::new(mdb, &mut root);
369		for (key, value) in input {
370			if let Err(e) = trie.insert(&key, &value) {
371				log::warn!(target: "trie", "Failed to write to trie: {}", e);
372				return None;
373			}
374		}
375	}
376
377	Some(root)
378}
379
380/// Wrapper to create a [`RuntimeCode`] from a type that implements [`Backend`].
381#[cfg(feature = "std")]
382pub struct BackendRuntimeCode<'a, B, H> {
383	backend: &'a B,
384	_marker: std::marker::PhantomData<H>,
385}
386
387#[cfg(feature = "std")]
388impl<'a, B: Backend<H>, H: Hasher> tet_core::traits::FetchRuntimeCode for
389	BackendRuntimeCode<'a, B, H>
390{
391	fn fetch_runtime_code<'b>(&'b self) -> Option<std::borrow::Cow<'b, [u8]>> {
392		self.backend.storage(well_known_keys::CODE).ok().flatten().map(Into::into)
393	}
394}
395
396#[cfg(feature = "std")]
397impl<'a, B: Backend<H>, H: Hasher> BackendRuntimeCode<'a, B, H> where H::Out: Encode {
398	/// Create a new instance.
399	pub fn new(backend: &'a B) -> Self {
400		Self {
401			backend,
402			_marker: std::marker::PhantomData,
403		}
404	}
405
406	/// Return the [`RuntimeCode`] build from the wrapped `backend`.
407	pub fn runtime_code(&self) -> Result<RuntimeCode, &'static str> {
408		let hash = self.backend.storage_hash(well_known_keys::CODE)
409			.ok()
410			.flatten()
411			.ok_or("`:code` hash not found")?
412			.encode();
413		let heap_pages = self.backend.storage(well_known_keys::HEAP_PAGES)
414			.ok()
415			.flatten()
416			.and_then(|d| Decode::decode(&mut &d[..]).ok());
417
418		Ok(RuntimeCode { code_fetcher: self, hash, heap_pages })
419	}
420}