referrerpolicy=no-referrer-when-downgrade

sp_state_machine/
backend.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//! State machine backends. These manage the code and storage of contracts.
19
20#[cfg(feature = "std")]
21use crate::trie_backend::TrieBackend;
22use crate::{
23	trie_backend_essence::TrieBackendStorage, ChildStorageCollection, DeltaKeyOp,
24	StorageCollection, StorageKey, StorageValue, UsageInfo,
25};
26use alloc::{collections::BTreeMap, vec::Vec};
27use codec::Encode;
28use core::marker::PhantomData;
29use hash_db::Hasher;
30use sp_core::storage::{ChildInfo, StateVersion, TrackedStorageKey};
31#[cfg(feature = "std")]
32use sp_core::traits::RuntimeCode;
33use sp_trie::{
34	DetachedTrieDBMut, InvalidSnapshot, LayoutV0, LayoutV1, MerkleValue, PrefixedMemoryDB,
35	RandomState, TrieDBMutSnapshot,
36};
37
38/// A struct containing arguments for iterating over the storage.
39#[derive(Default)]
40#[non_exhaustive]
41pub struct IterArgs<'a> {
42	/// The prefix of the keys over which to iterate.
43	pub prefix: Option<&'a [u8]>,
44
45	/// The prefix from which to start the iteration from.
46	///
47	/// This is inclusive and the iteration will include the key which is specified here.
48	pub start_at: Option<&'a [u8]>,
49
50	/// If this is `true` then the iteration will *not* include
51	/// the key specified in `start_at`, if there is such a key.
52	pub start_at_exclusive: bool,
53
54	/// The info of the child trie over which to iterate over.
55	pub child_info: Option<ChildInfo>,
56
57	/// Whether to stop iteration when a missing trie node is reached.
58	///
59	/// When a missing trie node is reached the iterator will:
60	///   - return an error if this is set to `false` (default)
61	///   - return `None` if this is set to `true`
62	pub stop_on_incomplete_database: bool,
63}
64
65/// A trait for a raw storage iterator.
66pub trait StorageIterator<H>
67where
68	H: Hasher,
69{
70	/// The state backend over which the iterator is iterating.
71	type Backend;
72
73	/// The error type.
74	type Error;
75
76	/// Fetches the next key from the storage.
77	fn next_key(
78		&mut self,
79		backend: &Self::Backend,
80	) -> Option<core::result::Result<StorageKey, Self::Error>>;
81
82	/// Fetches the next key and value from the storage.
83	fn next_pair(
84		&mut self,
85		backend: &Self::Backend,
86	) -> Option<core::result::Result<(StorageKey, StorageValue), Self::Error>>;
87
88	/// Returns whether the end of iteration was reached without an error.
89	fn was_complete(&self) -> bool;
90}
91
92/// An iterator over storage keys and values.
93pub struct PairsIter<'a, H, I>
94where
95	H: Hasher,
96	I: StorageIterator<H>,
97{
98	backend: Option<&'a I::Backend>,
99	raw_iter: I,
100	_phantom: PhantomData<H>,
101}
102
103impl<'a, H, I> Iterator for PairsIter<'a, H, I>
104where
105	H: Hasher,
106	I: StorageIterator<H>,
107{
108	type Item = Result<(Vec<u8>, Vec<u8>), <I as StorageIterator<H>>::Error>;
109	fn next(&mut self) -> Option<Self::Item> {
110		self.raw_iter.next_pair(self.backend.as_ref()?)
111	}
112}
113
114impl<'a, H, I> Default for PairsIter<'a, H, I>
115where
116	H: Hasher,
117	I: StorageIterator<H> + Default,
118{
119	fn default() -> Self {
120		Self {
121			backend: Default::default(),
122			raw_iter: Default::default(),
123			_phantom: Default::default(),
124		}
125	}
126}
127
128impl<'a, H, I> PairsIter<'a, H, I>
129where
130	H: Hasher,
131	I: StorageIterator<H> + Default,
132{
133	#[cfg(feature = "std")]
134	pub(crate) fn was_complete(&self) -> bool {
135		self.raw_iter.was_complete()
136	}
137}
138
139/// An iterator over storage keys.
140pub struct KeysIter<'a, H, I>
141where
142	H: Hasher,
143	I: StorageIterator<H>,
144{
145	backend: Option<&'a I::Backend>,
146	raw_iter: I,
147	_phantom: PhantomData<H>,
148}
149
150impl<'a, H, I> Iterator for KeysIter<'a, H, I>
151where
152	H: Hasher,
153	I: StorageIterator<H>,
154{
155	type Item = Result<Vec<u8>, <I as StorageIterator<H>>::Error>;
156	fn next(&mut self) -> Option<Self::Item> {
157		self.raw_iter.next_key(self.backend.as_ref()?)
158	}
159}
160
161impl<'a, H, I> Default for KeysIter<'a, H, I>
162where
163	H: Hasher,
164	I: StorageIterator<H> + Default,
165{
166	fn default() -> Self {
167		Self {
168			backend: Default::default(),
169			raw_iter: Default::default(),
170			_phantom: Default::default(),
171		}
172	}
173}
174
175/// The transaction type used by [`Backend`].
176///
177/// This transaction contains all the changes that need to be applied to the backend to create the
178/// state for a new block.
179pub type BackendTransaction<H> = PrefixedMemoryDB<H>;
180
181/// In-memory trie kept across PoV size estimation calls, so removals accumulate.
182pub enum EstimationTrie<H: Hasher> {
183	/// The trie of a chain with state version 0.
184	V0(DetachedTrieDBMut<LayoutV0<H>>),
185	/// The trie of a chain with state version 1.
186	V1(DetachedTrieDBMut<LayoutV1<H>>),
187}
188
189/// A point an [`EstimationTrie`] can be rolled back to.
190pub enum EstimationTrieSnapshot<H: Hasher> {
191	/// A snapshot of an [`EstimationTrie::V0`].
192	V0(TrieDBMutSnapshot<LayoutV0<H>>),
193	/// A snapshot of an [`EstimationTrie::V1`].
194	V1(TrieDBMutSnapshot<LayoutV1<H>>),
195}
196
197impl<H: Hasher> EstimationTrie<H> {
198	/// The trie at `root` without in-memory nodes, in the layout of `state_version`.
199	pub fn new(state_version: StateVersion, root: H::Out) -> Self {
200		match state_version {
201			StateVersion::V0 => Self::V0(DetachedTrieDBMut::new(root)),
202			StateVersion::V1 => Self::V1(DetachedTrieDBMut::new(root)),
203		}
204	}
205
206	/// Take a snapshot to roll back to, see [`DetachedTrieDBMut::snapshot`].
207	pub fn snapshot(&mut self) -> EstimationTrieSnapshot<H> {
208		match self {
209			Self::V0(trie) => EstimationTrieSnapshot::V0(trie.snapshot()),
210			Self::V1(trie) => EstimationTrieSnapshot::V1(trie.snapshot()),
211		}
212	}
213
214	/// Roll back to `snapshot`, see [`DetachedTrieDBMut::rollback_to`].
215	///
216	/// Panics if the snapshot was taken from a trie with a different layout.
217	pub fn rollback_to(
218		&mut self,
219		snapshot: &EstimationTrieSnapshot<H>,
220	) -> Result<(), InvalidSnapshot> {
221		match (self, snapshot) {
222			(Self::V0(trie), EstimationTrieSnapshot::V0(snapshot)) => trie.rollback_to(snapshot),
223			(Self::V1(trie), EstimationTrieSnapshot::V1(snapshot)) => trie.rollback_to(snapshot),
224			_ => unreachable!(
225				"a snapshot is taken from the trie it is rolled back to, and a trie keeps its \
226				 layout for its whole life; qed"
227			),
228		}
229	}
230
231	/// Discard `snapshot` and every later one, see [`DetachedTrieDBMut::discard_from`].
232	///
233	/// Panics if the snapshot was taken from a trie with a different layout.
234	pub fn discard_from(
235		&mut self,
236		snapshot: &EstimationTrieSnapshot<H>,
237	) -> Result<(), InvalidSnapshot> {
238		match (self, snapshot) {
239			(Self::V0(trie), EstimationTrieSnapshot::V0(snapshot)) => trie.discard_from(snapshot),
240			(Self::V1(trie), EstimationTrieSnapshot::V1(snapshot)) => trie.discard_from(snapshot),
241			_ => unreachable!(
242				"a snapshot is taken from the trie it is discarded from, and a trie keeps its \
243				 layout for its whole life; qed"
244			),
245		}
246	}
247}
248
249/// A state backend is used to read state data and can have changes committed
250/// to it.
251///
252/// The clone operation (if implemented) should be cheap.
253pub trait Backend<H: Hasher>: core::fmt::Debug {
254	/// An error type when fetching data is not possible.
255	type Error: super::Error;
256
257	/// Type of trie backend storage.
258	type TrieBackendStorage: TrieBackendStorage<H>;
259
260	/// Type of the raw storage iterator.
261	type RawIter: StorageIterator<H, Backend = Self, Error = Self::Error>;
262
263	/// Get keyed storage or None if there is nothing associated.
264	fn storage(&self, key: &[u8]) -> Result<Option<StorageValue>, Self::Error>;
265
266	/// Get keyed storage value hash or None if there is nothing associated.
267	fn storage_hash(&self, key: &[u8]) -> Result<Option<H::Out>, Self::Error>;
268
269	/// Get the merkle value or None if there is nothing associated.
270	fn closest_merkle_value(&self, key: &[u8]) -> Result<Option<MerkleValue<H::Out>>, Self::Error>;
271
272	/// Get the child merkle value or None if there is nothing associated.
273	fn child_closest_merkle_value(
274		&self,
275		child_info: &ChildInfo,
276		key: &[u8],
277	) -> Result<Option<MerkleValue<H::Out>>, Self::Error>;
278
279	/// Get child keyed child storage or None if there is nothing associated.
280	fn child_storage(
281		&self,
282		child_info: &ChildInfo,
283		key: &[u8],
284	) -> Result<Option<StorageValue>, Self::Error>;
285
286	/// Get child keyed storage value hash or None if there is nothing associated.
287	fn child_storage_hash(
288		&self,
289		child_info: &ChildInfo,
290		key: &[u8],
291	) -> Result<Option<H::Out>, Self::Error>;
292
293	/// true if a key exists in storage.
294	fn exists_storage(&self, key: &[u8]) -> Result<bool, Self::Error> {
295		Ok(self.storage_hash(key)?.is_some())
296	}
297
298	/// true if a key exists in child storage.
299	fn exists_child_storage(
300		&self,
301		child_info: &ChildInfo,
302		key: &[u8],
303	) -> Result<bool, Self::Error> {
304		Ok(self.child_storage_hash(child_info, key)?.is_some())
305	}
306
307	/// Return the next key in storage in lexicographic order or `None` if there is no value.
308	fn next_storage_key(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error>;
309
310	/// Return the next key in child storage in lexicographic order or `None` if there is no value.
311	fn next_child_storage_key(
312		&self,
313		child_info: &ChildInfo,
314		key: &[u8],
315	) -> Result<Option<StorageKey>, Self::Error>;
316
317	/// Calculate the storage root, with given delta over what is already stored in
318	/// the backend, and produce a "transaction" that can be used to commit.
319	/// Does not include child storage updates.
320	fn storage_root<'a>(
321		&self,
322		delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
323		state_version: StateVersion,
324	) -> (H::Out, BackendTransaction<H>)
325	where
326		H::Out: Ord;
327
328	/// Calculate the child storage root, with given delta over what is already stored in
329	/// the backend, and produce a "transaction" that can be used to commit. The second argument
330	/// is true if child storage root equals default storage root.
331	fn child_storage_root<'a>(
332		&self,
333		child_info: &ChildInfo,
334		delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
335		state_version: StateVersion,
336	) -> (H::Out, bool, BackendTransaction<H>)
337	where
338		H::Out: Ord;
339
340	/// Updates the recorder's proof size by recording trie nodes for a given delta.
341	///
342	/// Does not include child storage updates. The `estimation_trie` carries the removals of
343	/// earlier calls, see [`EstimationTrie`].
344	fn record_proof_for_dirty_keys<'a>(
345		&self,
346		delta: impl Iterator<Item = (&'a [u8], DeltaKeyOp)>,
347		estimation_trie: &mut Option<EstimationTrie<H>>,
348		state_version: StateVersion,
349	) where
350		H::Out: Ord;
351
352	/// Updates the recorder's proof size by recording child trie nodes for a given delta.
353	fn record_proof_for_child_dirty_keys<'a>(
354		&self,
355		child_info: &ChildInfo,
356		delta: impl Iterator<Item = (&'a [u8], DeltaKeyOp)>,
357		estimation_trie: &mut Option<EstimationTrie<H>>,
358		state_version: StateVersion,
359	) where
360		H::Out: Ord;
361
362	/// Returns a lifetimeless raw storage iterator.
363	fn raw_iter(&self, args: IterArgs) -> Result<Self::RawIter, Self::Error>;
364
365	/// Get an iterator over key/value pairs.
366	fn pairs<'a>(&'a self, args: IterArgs) -> Result<PairsIter<'a, H, Self::RawIter>, Self::Error> {
367		Ok(PairsIter {
368			backend: Some(self),
369			raw_iter: self.raw_iter(args)?,
370			_phantom: Default::default(),
371		})
372	}
373
374	/// Get an iterator over keys.
375	fn keys<'a>(&'a self, args: IterArgs) -> Result<KeysIter<'a, H, Self::RawIter>, Self::Error> {
376		Ok(KeysIter {
377			backend: Some(self),
378			raw_iter: self.raw_iter(args)?,
379			_phantom: Default::default(),
380		})
381	}
382
383	/// Calculate the storage root, with given delta over what is already stored
384	/// in the backend, and produce a "transaction" that can be used to commit.
385	/// Does include child storage updates.
386	fn full_storage_root<'a>(
387		&self,
388		delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
389		child_deltas: impl Iterator<
390			Item = (&'a ChildInfo, impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>),
391		>,
392		state_version: StateVersion,
393	) -> (H::Out, BackendTransaction<H>)
394	where
395		H::Out: Ord + Encode,
396	{
397		let (root, txs, _) =
398			self.full_storage_root_with_child_roots(delta, child_deltas, state_version);
399		(root, txs)
400	}
401
402	/// Like [`Self::full_storage_root`], but also returns the root of every child trie in
403	/// `child_deltas`, keyed by its storage key.
404	fn full_storage_root_with_child_roots<'a>(
405		&self,
406		delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
407		child_deltas: impl Iterator<
408			Item = (&'a ChildInfo, impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>),
409		>,
410		state_version: StateVersion,
411	) -> (H::Out, BackendTransaction<H>, BTreeMap<StorageKey, H::Out>)
412	where
413		H::Out: Ord + Encode,
414	{
415		let mut txs = BackendTransaction::with_hasher(RandomState::default());
416		let mut child_roots: Vec<_> = Default::default();
417		let mut child_roots_by_storage_key = BTreeMap::new();
418		// child first
419		for (child_info, child_delta) in child_deltas {
420			let (child_root, empty, child_txs) =
421				self.child_storage_root(child_info, child_delta, state_version);
422			let prefixed_storage_key = child_info.prefixed_storage_key();
423			txs.consolidate(child_txs);
424			if empty {
425				child_roots.push((prefixed_storage_key.into_inner(), None));
426			} else {
427				child_roots.push((prefixed_storage_key.into_inner(), Some(child_root.encode())));
428			}
429			child_roots_by_storage_key.insert(child_info.storage_key().to_vec(), child_root);
430		}
431		let (root, parent_txs) = self.storage_root(
432			delta
433				.map(|(k, v)| (k, v.as_ref().map(|v| &v[..])))
434				.chain(child_roots.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))),
435			state_version,
436		);
437		txs.consolidate(parent_txs);
438
439		(root, txs, child_roots_by_storage_key)
440	}
441
442	/// Register stats from overlay of state machine.
443	///
444	/// By default nothing is registered.
445	fn register_overlay_stats(&self, _stats: &crate::stats::StateMachineStats);
446
447	/// Query backend usage statistics (i/o, memory)
448	///
449	/// Not all implementations are expected to be able to do this. In the
450	/// case when they don't, empty statistics is returned.
451	fn usage_info(&self) -> UsageInfo;
452
453	/// Wipe the state database.
454	fn wipe(&self) -> Result<(), Self::Error> {
455		unimplemented!()
456	}
457
458	/// Commit given transaction to storage.
459	fn commit(
460		&self,
461		_: H::Out,
462		_: BackendTransaction<H>,
463		_: StorageCollection,
464		_: ChildStorageCollection,
465	) -> Result<(), Self::Error> {
466		unimplemented!()
467	}
468
469	/// Get the read/write count of the db
470	fn read_write_count(&self) -> (u32, u32, u32, u32) {
471		unimplemented!()
472	}
473
474	/// Get the read/write count of the db
475	fn reset_read_write_count(&self) {
476		unimplemented!()
477	}
478
479	/// Get the whitelist for tracking db reads/writes
480	fn get_whitelist(&self) -> Vec<TrackedStorageKey> {
481		Default::default()
482	}
483
484	/// Update the whitelist for tracking db reads/writes
485	fn set_whitelist(&self, _: Vec<TrackedStorageKey>) {}
486
487	/// Estimate proof size
488	fn proof_size(&self) -> Option<u32> {
489		unimplemented!()
490	}
491
492	/// Extend storage info for benchmarking db
493	fn get_read_and_written_keys(&self) -> Vec<(Vec<u8>, u32, u32, bool)> {
494		unimplemented!()
495	}
496}
497
498/// Something that can be converted into a [`TrieBackend`].
499#[cfg(feature = "std")]
500pub trait AsTrieBackend<H: Hasher, C = sp_trie::cache::LocalTrieCache<H>> {
501	/// Type of trie backend storage.
502	type TrieBackendStorage: TrieBackendStorage<H>;
503
504	/// Return the type as [`TrieBackend`].
505	fn as_trie_backend(&self) -> &TrieBackend<Self::TrieBackendStorage, H, C>;
506}
507
508/// Whether to take `:pending_code` into account
509/// when fetching the runtime code.
510///
511/// We want to use `:pending_code` in block production and import
512/// but avoid using it in runtime api calls.
513#[cfg(feature = "std")]
514pub enum TryPendingCode {
515	/// Used by runtime api calls.
516	No,
517	/// Used by block import and block production.
518	Yes,
519}
520
521#[cfg(feature = "std")]
522impl From<sp_core::traits::CallContext> for TryPendingCode {
523	fn from(context: sp_core::traits::CallContext) -> Self {
524		match context {
525			sp_core::traits::CallContext::Onchain { .. } => TryPendingCode::Yes,
526			sp_core::traits::CallContext::Offchain => TryPendingCode::No,
527		}
528	}
529}
530
531/// Wrapper to create a [`RuntimeCode`] from a type that implements [`Backend`].
532#[cfg(feature = "std")]
533pub struct BackendRuntimeCode<'a, B, H> {
534	backend: &'a B,
535	try_pending_code: TryPendingCode,
536	_marker: PhantomData<H>,
537}
538
539#[cfg(feature = "std")]
540impl<'a, B: Backend<H>, H: Hasher> sp_core::traits::FetchRuntimeCode
541	for BackendRuntimeCode<'a, B, H>
542{
543	fn fetch_runtime_code(&self) -> Option<std::borrow::Cow<'_, [u8]>> {
544		if matches!(self.try_pending_code, TryPendingCode::Yes) {
545			let pending_code = self
546				.backend
547				.storage(sp_core::storage::well_known_keys::PENDING_CODE)
548				.ok()
549				.flatten()
550				.map(Into::into);
551
552			if pending_code.is_some() {
553				return pending_code;
554			}
555		}
556		self.backend
557			.storage(sp_core::storage::well_known_keys::CODE)
558			.ok()
559			.flatten()
560			.map(Into::into)
561	}
562}
563
564#[cfg(feature = "std")]
565impl<'a, B: Backend<H>, H: Hasher> BackendRuntimeCode<'a, B, H>
566where
567	H::Out: Encode,
568{
569	/// Create a new instance.
570	pub fn new(backend: &'a B, try_pending_code: TryPendingCode) -> Self {
571		Self { backend, try_pending_code, _marker: PhantomData }
572	}
573
574	/// Return [`RuntimeCode`] build from the wrapped `backend`.
575	///
576	/// This method takes `:pending_code` into account.
577	pub fn runtime_code(&self) -> Result<RuntimeCode<'_>, &'static str> {
578		let maybe_pending_code_hash = match self.try_pending_code {
579			TryPendingCode::No => None,
580			TryPendingCode::Yes => self
581				.backend
582				.storage_hash(sp_core::storage::well_known_keys::PENDING_CODE)
583				.ok()
584				.flatten(),
585		};
586		let hash = if let Some(pending_code_hash) = maybe_pending_code_hash {
587			pending_code_hash.encode()
588		} else {
589			self.backend
590				.storage_hash(sp_core::storage::well_known_keys::CODE)
591				.ok()
592				.flatten()
593				.ok_or("`:code` hash not found")?
594				.encode()
595		};
596		let heap_pages = self
597			.backend
598			.storage(sp_core::storage::well_known_keys::HEAP_PAGES)
599			.ok()
600			.flatten()
601			.and_then(|d| codec::Decode::decode(&mut &d[..]).ok());
602
603		Ok(RuntimeCode { code_fetcher: self, hash, heap_pages })
604	}
605}