referrerpolicy=no-referrer-when-downgrade

sp_state_machine/
trie_backend_essence.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//! Trie-based state machine backend essence used to read values
19//! from storage.
20
21use crate::{
22	backend::{EstimationTrie, IterArgs, StorageIterator},
23	trie_backend::TrieCacheProvider,
24	warn, DeltaKeyOp, StorageKey, StorageValue,
25};
26#[cfg(feature = "std")]
27use alloc::sync::Arc;
28use alloc::{boxed::Box, vec::Vec};
29use codec::Codec;
30use core::marker::PhantomData;
31use hash_db::{self, AsHashDB, HashDB, HashDBRef, Hasher, MaybeDebug, Prefix};
32#[cfg(feature = "std")]
33use parking_lot::RwLock;
34use sp_core::storage::{ChildInfo, ChildType, StateVersion};
35use sp_trie::{
36	child_delta_trie_root, child_read_trie_keys_from_delta, child_remove_trie_keys_from_delta,
37	delta_trie_root, empty_child_trie_root, read_child_trie_first_descendant_value,
38	read_child_trie_hash, read_child_trie_value, read_trie_first_descendant_value,
39	read_trie_keys_from_delta, read_trie_value, remove_trie_keys_from_delta,
40	trie_types::{TrieDBBuilder, TrieError},
41	DBValue, KeySpacedDB, LayoutV1 as Layout, MerkleValue, NodeCodec, PrefixedMemoryDB,
42	RandomState, Trie, TrieCache, TrieDBRawIterator, TrieRecorder, TrieRecorderProvider,
43};
44#[cfg(feature = "std")]
45use std::collections::HashMap;
46// In this module, we only use layout for read operation and empty root,
47// where V1 and V0 are equivalent.
48
49#[cfg(not(feature = "std"))]
50macro_rules! format {
51	( $message:expr, $( $arg:expr )* ) => {
52		{
53			$( let _ = &$arg; )*
54			crate::DefaultError
55		}
56	};
57}
58
59type Result<V> = core::result::Result<V, crate::DefaultError>;
60
61/// Patricia trie-based storage trait.
62pub trait Storage<H: Hasher>: Send + Sync {
63	/// Get a trie node.
64	fn get(&self, key: &H::Out, prefix: Prefix) -> Result<Option<DBValue>>;
65}
66
67/// Local cache for child root.
68#[cfg(feature = "std")]
69pub(crate) struct Cache<H> {
70	pub child_root: HashMap<Vec<u8>, Option<H>>,
71}
72
73#[cfg(feature = "std")]
74impl<H> Cache<H> {
75	fn new() -> Self {
76		Cache { child_root: HashMap::new() }
77	}
78}
79
80enum IterState {
81	Pending,
82	FinishedComplete,
83	FinishedIncomplete,
84}
85
86/// A raw iterator over the storage.
87pub struct RawIter<S, H, C, R>
88where
89	H: Hasher,
90{
91	stop_on_incomplete_database: bool,
92	skip_if_first: Option<StorageKey>,
93	root: H::Out,
94	child_info: Option<ChildInfo>,
95	trie_iter: TrieDBRawIterator<Layout<H>>,
96	state: IterState,
97	_phantom: PhantomData<(S, C, R)>,
98}
99
100impl<S, H, C, R> RawIter<S, H, C, R>
101where
102	H: Hasher,
103	S: TrieBackendStorage<H>,
104	H::Out: Codec + Ord,
105	C: TrieCacheProvider<H> + Send + Sync,
106	R: TrieRecorderProvider<H> + Send + Sync,
107{
108	#[inline]
109	fn prepare<RE>(
110		&mut self,
111		backend: &TrieBackendEssence<S, H, C, R>,
112		callback: impl FnOnce(
113			&sp_trie::TrieDB<Layout<H>>,
114			&mut TrieDBRawIterator<Layout<H>>,
115		) -> Option<core::result::Result<RE, Box<TrieError<<H as Hasher>::Out>>>>,
116	) -> Option<Result<RE>> {
117		if !matches!(self.state, IterState::Pending) {
118			return None;
119		}
120
121		let result = backend.with_trie_db(self.root, self.child_info.as_ref(), |db| {
122			callback(&db, &mut self.trie_iter)
123		});
124		match result {
125			Some(Ok(key_value)) => Some(Ok(key_value)),
126			None => {
127				self.state = IterState::FinishedComplete;
128				None
129			},
130			Some(Err(error)) => {
131				if matches!(*error, TrieError::IncompleteDatabase(_)) &&
132					self.stop_on_incomplete_database
133				{
134					self.state = IterState::FinishedIncomplete;
135					None
136				} else {
137					Some(Err(format!("TrieDB iteration error: {}", error)))
138				}
139			},
140		}
141	}
142}
143
144impl<S, H, C, R> Default for RawIter<S, H, C, R>
145where
146	H: Hasher,
147{
148	fn default() -> Self {
149		Self {
150			stop_on_incomplete_database: false,
151			skip_if_first: None,
152			child_info: None,
153			root: Default::default(),
154			trie_iter: TrieDBRawIterator::empty(),
155			state: IterState::FinishedComplete,
156			_phantom: Default::default(),
157		}
158	}
159}
160
161impl<S, H, C, R> StorageIterator<H> for RawIter<S, H, C, R>
162where
163	H: Hasher,
164	S: TrieBackendStorage<H>,
165	H::Out: Codec + Ord,
166	C: TrieCacheProvider<H> + Send + Sync,
167	R: TrieRecorderProvider<H> + Send + Sync,
168{
169	type Backend = crate::TrieBackend<S, H, C, R>;
170	type Error = crate::DefaultError;
171
172	#[inline]
173	fn next_key(&mut self, backend: &Self::Backend) -> Option<Result<StorageKey>> {
174		let skip_if_first = self.skip_if_first.take();
175		self.prepare(&backend.essence, |trie, trie_iter| {
176			let mut result = trie_iter.next_key(&trie);
177			if let Some(skipped_key) = skip_if_first {
178				if let Some(Ok(ref key)) = result {
179					if *key == skipped_key {
180						result = trie_iter.next_key(&trie);
181					}
182				}
183			}
184			result
185		})
186	}
187
188	#[inline]
189	fn next_pair(&mut self, backend: &Self::Backend) -> Option<Result<(StorageKey, StorageValue)>> {
190		let skip_if_first = self.skip_if_first.take();
191		self.prepare(&backend.essence, |trie, trie_iter| {
192			let mut result = trie_iter.next_item(&trie);
193			if let Some(skipped_key) = skip_if_first {
194				if let Some(Ok((ref key, _))) = result {
195					if *key == skipped_key {
196						result = trie_iter.next_item(&trie);
197					}
198				}
199			}
200			result
201		})
202	}
203
204	fn was_complete(&self) -> bool {
205		matches!(self.state, IterState::FinishedComplete)
206	}
207}
208
209/// Patricia trie-based pairs storage essence.
210pub struct TrieBackendEssence<S: TrieBackendStorage<H>, H: Hasher, C, R> {
211	storage: S,
212	root: H::Out,
213	empty: H::Out,
214	#[cfg(feature = "std")]
215	pub(crate) cache: Arc<RwLock<Cache<H::Out>>>,
216	pub(crate) trie_node_cache: Option<C>,
217	pub(crate) recorder: Option<R>,
218}
219
220impl<S: TrieBackendStorage<H>, H: Hasher, C, R> TrieBackendEssence<S, H, C, R> {
221	/// Create new trie-based backend.
222	pub fn new(storage: S, root: H::Out) -> Self {
223		Self::new_with_cache(storage, root, None)
224	}
225
226	/// Create new trie-based backend.
227	pub fn new_with_cache(storage: S, root: H::Out, cache: Option<C>) -> Self {
228		TrieBackendEssence {
229			storage,
230			root,
231			empty: H::hash(&[0u8]),
232			#[cfg(feature = "std")]
233			cache: Arc::new(RwLock::new(Cache::new())),
234			trie_node_cache: cache,
235			recorder: None,
236		}
237	}
238
239	/// Create new trie-based backend.
240	pub fn new_with_cache_and_recorder(
241		storage: S,
242		root: H::Out,
243		cache: Option<C>,
244		recorder: Option<R>,
245	) -> Self {
246		TrieBackendEssence {
247			storage,
248			root,
249			empty: H::hash(&[0u8]),
250			#[cfg(feature = "std")]
251			cache: Arc::new(RwLock::new(Cache::new())),
252			trie_node_cache: cache,
253			recorder,
254		}
255	}
256
257	/// Get backend storage reference.
258	pub fn backend_storage(&self) -> &S {
259		&self.storage
260	}
261
262	/// Get backend storage mutable reference.
263	pub fn backend_storage_mut(&mut self) -> &mut S {
264		&mut self.storage
265	}
266
267	/// Get trie root.
268	pub fn root(&self) -> &H::Out {
269		&self.root
270	}
271
272	/// Set trie root. This is useful for testing.
273	pub fn set_root(&mut self, root: H::Out) {
274		// If root did change so can have cached content.
275		self.reset_cache();
276		self.root = root;
277	}
278
279	#[cfg(feature = "std")]
280	fn reset_cache(&mut self) {
281		self.cache = Arc::new(RwLock::new(Cache::new()));
282	}
283
284	#[cfg(not(feature = "std"))]
285	fn reset_cache(&mut self) {}
286
287	/// Consumes self and returns underlying storage.
288	pub fn into_storage(self) -> S {
289		self.storage
290	}
291}
292
293impl<S: TrieBackendStorage<H>, H: Hasher, C: TrieCacheProvider<H>, R: TrieRecorderProvider<H>>
294	TrieBackendEssence<S, H, C, R>
295{
296	/// Call the given closure passing it the recorder and the cache.
297	///
298	/// If the given `storage_root` is `None`, `self.root` will be used.
299	#[inline]
300	fn with_recorder_and_cache<RE>(
301		&self,
302		storage_root: Option<H::Out>,
303		callback: impl FnOnce(
304			Option<&mut dyn TrieRecorder<H::Out>>,
305			Option<&mut dyn TrieCache<NodeCodec<H>>>,
306		) -> RE,
307	) -> RE {
308		let storage_root = storage_root.unwrap_or_else(|| self.root);
309		let mut cache = self.trie_node_cache.as_ref().map(|c| c.as_trie_db_cache(storage_root));
310		let cache = cache.as_mut().map(|c| c as _);
311
312		let mut recorder = self.recorder.as_ref().map(|r| r.as_trie_recorder(storage_root));
313		let recorder = match recorder.as_mut() {
314			Some(recorder) => Some(recorder as &mut dyn TrieRecorder<H::Out>),
315			None => None,
316		};
317		callback(recorder, cache)
318	}
319
320	/// Call the given closure passing it the recorder and the cache.
321	///
322	/// This function must only be used when the operation in `callback` is
323	/// calculating a `storage_root`. It is expected that `callback` returns
324	/// the new storage root. This is required to register the changes in the cache
325	/// for the correct storage root. The given `storage_root` corresponds to the root of the "old"
326	/// trie. If the value is not given, `self.root` is used.
327	fn with_recorder_and_cache_for_storage_root<RE>(
328		&self,
329		storage_root: Option<H::Out>,
330		callback: impl FnOnce(
331			Option<&mut dyn TrieRecorder<H::Out>>,
332			Option<&mut dyn TrieCache<NodeCodec<H>>>,
333		) -> (Option<H::Out>, RE),
334	) -> RE {
335		let storage_root = storage_root.unwrap_or_else(|| self.root);
336		let mut recorder = self.recorder.as_ref().map(|r| r.as_trie_recorder(storage_root));
337		let recorder = match recorder.as_mut() {
338			Some(recorder) => Some(recorder as &mut dyn TrieRecorder<H::Out>),
339			None => None,
340		};
341
342		let result = if let Some(local_cache) = self.trie_node_cache.as_ref() {
343			let mut cache = local_cache.as_trie_db_mut_cache();
344
345			let (new_root, r) = callback(recorder, Some(&mut cache));
346
347			if let Some(new_root) = new_root {
348				local_cache.merge(cache, new_root);
349			}
350
351			r
352		} else {
353			callback(recorder, None).1
354		};
355
356		result
357	}
358}
359
360/// The estimation only reads nodes of the state the backend serves and never writes, so an error
361/// means a corrupt database or a bug, never an input.
362fn expect_existing_nodes<T, E: MaybeDebug>(result: core::result::Result<T, E>) -> T {
363	const PROOF: &str =
364		"the backend serves the block-start state, so every node the estimation reads exists; qed";
365	match result {
366		Ok(value) => value,
367		#[cfg(feature = "std")]
368		Err(error) => panic!("{PROOF}: {error:?}"),
369		#[cfg(not(feature = "std"))]
370		Err(_) => panic!("{}", PROOF),
371	}
372}
373
374impl<
375		S: TrieBackendStorage<H>,
376		H: Hasher,
377		C: TrieCacheProvider<H> + Send + Sync,
378		R: TrieRecorderProvider<H> + Send + Sync,
379	> TrieBackendEssence<S, H, C, R>
380where
381	H::Out: Codec + Ord,
382{
383	/// Calls the given closure with a [`TrieDb`] constructed for the given
384	/// storage root and (optionally) child trie.
385	#[inline]
386	fn with_trie_db<RE>(
387		&self,
388		root: H::Out,
389		child_info: Option<&ChildInfo>,
390		callback: impl FnOnce(&sp_trie::TrieDB<Layout<H>>) -> RE,
391	) -> RE {
392		let backend = self as &dyn HashDBRef<H, Vec<u8>>;
393		let db = child_info
394			.as_ref()
395			.map(|child_info| KeySpacedDB::new(backend, child_info.keyspace()));
396		let db = db.as_ref().map(|db| db as &dyn HashDBRef<H, Vec<u8>>).unwrap_or(backend);
397
398		self.with_recorder_and_cache(Some(root), |recorder, cache| {
399			let trie = TrieDBBuilder::<H>::new(db, &root)
400				.with_optional_recorder(recorder)
401				.with_optional_cache(cache)
402				.build();
403
404			callback(&trie)
405		})
406	}
407
408	/// Returns the next key in the trie i.e. the minimum key that is strictly superior to `key` in
409	/// lexicographic order.
410	///
411	/// Will always traverse the trie from scratch in search of the key, which is slow.
412	/// Used only when debug assertions are enabled to crosscheck the results of finding
413	/// the next key through an iterator.
414	#[cfg(debug_assertions)]
415	pub fn next_storage_key_slow(&self, key: &[u8]) -> Result<Option<StorageKey>> {
416		self.next_storage_key_from_root(&self.root, None, key)
417	}
418
419	/// Access the root of the child storage in its parent trie
420	fn child_root(&self, child_info: &ChildInfo) -> Result<Option<H::Out>> {
421		#[cfg(feature = "std")]
422		{
423			if let Some(result) = self.cache.read().child_root.get(child_info.storage_key()) {
424				return Ok(*result);
425			}
426		}
427
428		let result = self.storage(child_info.prefixed_storage_key().as_slice())?.map(|r| {
429			let mut hash = H::Out::default();
430
431			// root is fetched from DB, not writable by runtime, so it's always valid.
432			hash.as_mut().copy_from_slice(&r[..]);
433
434			hash
435		});
436
437		#[cfg(feature = "std")]
438		{
439			self.cache.write().child_root.insert(child_info.storage_key().to_vec(), result);
440		}
441
442		Ok(result)
443	}
444
445	/// Return the next key in the child trie i.e. the minimum key that is strictly superior to
446	/// `key` in lexicographic order.
447	pub fn next_child_storage_key(
448		&self,
449		child_info: &ChildInfo,
450		key: &[u8],
451	) -> Result<Option<StorageKey>> {
452		let child_root = match self.child_root(child_info)? {
453			Some(child_root) => child_root,
454			None => return Ok(None),
455		};
456
457		self.next_storage_key_from_root(&child_root, Some(child_info), key)
458	}
459
460	/// Return next key from main trie or child trie by providing corresponding root.
461	fn next_storage_key_from_root(
462		&self,
463		root: &H::Out,
464		child_info: Option<&ChildInfo>,
465		key: &[u8],
466	) -> Result<Option<StorageKey>> {
467		self.with_trie_db(*root, child_info, |trie| {
468			let mut iter = trie.key_iter().map_err(|e| format!("TrieDB iteration error: {}", e))?;
469
470			// The key just after the one given in input, basically `key++0`.
471			// Note: We are sure this is the next key if:
472			// * size of key has no limit (i.e. we can always add 0 to the path),
473			// * and no keys can be inserted between `key` and `key++0` (this is ensured by sp-io).
474			let mut potential_next_key = Vec::with_capacity(key.len() + 1);
475			potential_next_key.extend_from_slice(key);
476			potential_next_key.push(0);
477
478			iter.seek(&potential_next_key)
479				.map_err(|e| format!("TrieDB iterator seek error: {}", e))?;
480
481			let next_element = iter.next();
482
483			let next_key = if let Some(next_element) = next_element {
484				let next_key =
485					next_element.map_err(|e| format!("TrieDB iterator next error: {}", e))?;
486				Some(next_key)
487			} else {
488				None
489			};
490
491			Ok(next_key)
492		})
493	}
494
495	/// Returns the hash value
496	pub fn storage_hash(&self, key: &[u8]) -> Result<Option<H::Out>> {
497		let map_e = |e| format!("Trie lookup error: {}", e);
498
499		self.with_recorder_and_cache(None, |recorder, cache| {
500			TrieDBBuilder::new(self, &self.root)
501				.with_optional_cache(cache)
502				.with_optional_recorder(recorder)
503				.build()
504				.get_hash(key)
505				.map_err(map_e)
506		})
507	}
508
509	/// Get the value of storage at given key.
510	pub fn storage(&self, key: &[u8]) -> Result<Option<StorageValue>> {
511		let map_e = |e| format!("Trie lookup error: {}", e);
512
513		self.with_recorder_and_cache(None, |recorder, cache| {
514			read_trie_value::<Layout<H>, _>(self, &self.root, key, recorder, cache).map_err(map_e)
515		})
516	}
517
518	/// Returns the hash value
519	pub fn child_storage_hash(&self, child_info: &ChildInfo, key: &[u8]) -> Result<Option<H::Out>> {
520		let child_root = match self.child_root(child_info)? {
521			Some(root) => root,
522			None => return Ok(None),
523		};
524
525		let map_e = |e| format!("Trie lookup error: {}", e);
526
527		self.with_recorder_and_cache(Some(child_root), |recorder, cache| {
528			read_child_trie_hash::<Layout<H>, _>(
529				child_info.keyspace(),
530				self,
531				&child_root,
532				key,
533				recorder,
534				cache,
535			)
536			.map_err(map_e)
537		})
538	}
539
540	/// Get the value of child storage at given key.
541	pub fn child_storage(
542		&self,
543		child_info: &ChildInfo,
544		key: &[u8],
545	) -> Result<Option<StorageValue>> {
546		let child_root = match self.child_root(child_info)? {
547			Some(root) => root,
548			None => return Ok(None),
549		};
550
551		let map_e = |e| format!("Trie lookup error: {}", e);
552
553		self.with_recorder_and_cache(Some(child_root), |recorder, cache| {
554			read_child_trie_value::<Layout<H>, _>(
555				child_info.keyspace(),
556				self,
557				&child_root,
558				key,
559				recorder,
560				cache,
561			)
562			.map_err(map_e)
563		})
564	}
565
566	/// Get the closest merkle value at given key.
567	pub fn closest_merkle_value(&self, key: &[u8]) -> Result<Option<MerkleValue<H::Out>>> {
568		let map_e = |e| format!("Trie lookup error: {}", e);
569
570		self.with_recorder_and_cache(None, |recorder, cache| {
571			read_trie_first_descendant_value::<Layout<H>, _>(self, &self.root, key, recorder, cache)
572				.map_err(map_e)
573		})
574	}
575
576	/// Get the child closest merkle value at given key.
577	pub fn child_closest_merkle_value(
578		&self,
579		child_info: &ChildInfo,
580		key: &[u8],
581	) -> Result<Option<MerkleValue<H::Out>>> {
582		let Some(child_root) = self.child_root(child_info)? else { return Ok(None) };
583
584		let map_e = |e| format!("Trie lookup error: {}", e);
585
586		self.with_recorder_and_cache(Some(child_root), |recorder, cache| {
587			read_child_trie_first_descendant_value::<Layout<H>, _>(
588				child_info.keyspace(),
589				self,
590				&child_root,
591				key,
592				recorder,
593				cache,
594			)
595			.map_err(map_e)
596		})
597	}
598
599	/// Create a raw iterator over the storage.
600	pub fn raw_iter(&self, args: IterArgs) -> Result<RawIter<S, H, C, R>> {
601		let root = if let Some(child_info) = args.child_info.as_ref() {
602			let root = match self.child_root(&child_info)? {
603				Some(root) => root,
604				None => return Ok(Default::default()),
605			};
606			root
607		} else {
608			self.root
609		};
610
611		if self.root == Default::default() {
612			// A special-case for an empty storage root.
613			return Ok(Default::default());
614		}
615
616		let trie_iter = self
617			.with_trie_db(root, args.child_info.as_ref(), |db| {
618				let prefix = args.prefix.as_deref().unwrap_or(&[]);
619				if let Some(start_at) = args.start_at {
620					TrieDBRawIterator::new_prefixed_then_seek(db, prefix, &start_at)
621				} else {
622					TrieDBRawIterator::new_prefixed(db, prefix)
623				}
624			})
625			.map_err(|e| format!("TrieDB iteration error: {}", e))?;
626
627		Ok(RawIter {
628			stop_on_incomplete_database: args.stop_on_incomplete_database,
629			skip_if_first: if args.start_at_exclusive {
630				args.start_at.map(|key| key.to_vec())
631			} else {
632				None
633			},
634			child_info: args.child_info,
635			root,
636			trie_iter,
637			state: IterState::Pending,
638			_phantom: Default::default(),
639		})
640	}
641
642	/// Return the storage root after applying the given `delta`.
643	pub fn storage_root<'a>(
644		&self,
645		delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
646		state_version: StateVersion,
647	) -> (H::Out, PrefixedMemoryDB<H>) {
648		let mut write_overlay = PrefixedMemoryDB::with_hasher(RandomState::default());
649
650		let root = self.with_recorder_and_cache_for_storage_root(None, |recorder, cache| {
651			let mut eph = Ephemeral::new(self.backend_storage(), &mut write_overlay);
652			let res = match state_version {
653				StateVersion::V0 => delta_trie_root::<sp_trie::LayoutV0<H>, _, _, _, _, _>(
654					&mut eph, self.root, delta, recorder, cache,
655				),
656				StateVersion::V1 => delta_trie_root::<sp_trie::LayoutV1<H>, _, _, _, _, _>(
657					&mut eph, self.root, delta, recorder, cache,
658				),
659			};
660
661			match res {
662				Ok(ret) => (Some(ret), ret),
663				Err(e) => {
664					warn!(target: "trie", "Failed to write to trie: {}", e);
665					(None, self.root)
666				},
667			}
668		});
669
670		(root, write_overlay)
671	}
672
673	/// Partition delta keys into updated and deleted sets.
674	fn partition_delta<'a>(delta: Vec<(&'a [u8], DeltaKeyOp)>) -> (Vec<&'a [u8]>, Vec<&'a [u8]>) {
675		delta
676			.into_iter()
677			.fold((Vec::new(), Vec::new()), |(mut read, mut removed), (k, op)| {
678				match op {
679					DeltaKeyOp::Updated => read.push(k),
680					DeltaKeyOp::Deleted => removed.push(k),
681				}
682				(read, removed)
683			})
684	}
685
686	/// Updates the recorder's proof size by recording trie nodes for a given delta.
687	///
688	/// This function performs two operations to ensure accurate proof size calculation:
689	/// 1. Reads all keys that will be inserted or updated (`DeltaKeyOp::Updated`)
690	/// 2. Removes/touches all keys that will be deleted (`DeltaKeyOp::Deleted`)
691	/// All accessed trie nodes are recorded by the recorder, enabling accurate proof size
692	/// estimation for block production and validation.
693	///
694	/// Note: This function does not modify the actual storage state - it only reads and records
695	/// the trie nodes that would be affected by the given delta for proof size estimation.
696	pub fn record_proof_for_dirty_keys<'a>(
697		&self,
698		delta: impl Iterator<Item = (&'a [u8], DeltaKeyOp)>,
699		estimation_trie: &mut Option<EstimationTrie<H>>,
700		state_version: StateVersion,
701	) {
702		let mut write_overlay = PrefixedMemoryDB::with_hasher(Default::default());
703		let backend_storage = &self.backend_storage();
704		let eph = Ephemeral::new(backend_storage, &mut write_overlay);
705
706		let mut delta = delta.into_iter().collect::<Vec<_>>();
707		delta.sort();
708
709		let (keys_to_be_read, keys_to_be_removed) = Self::partition_delta(delta);
710
711		self.with_recorder_and_cache(None, |recorder, cache| match state_version {
712			StateVersion::V0 => {
713				expect_existing_nodes(read_trie_keys_from_delta::<sp_trie::LayoutV0<H>, _, _, _>(
714					&eph,
715					self.root,
716					keys_to_be_read,
717					recorder,
718					cache,
719				))
720			},
721			StateVersion::V1 => {
722				expect_existing_nodes(read_trie_keys_from_delta::<sp_trie::LayoutV1<H>, _, _, _>(
723					&eph,
724					self.root,
725					keys_to_be_read,
726					recorder,
727					cache,
728				))
729			},
730		});
731
732		if keys_to_be_removed.is_empty() {
733			return;
734		}
735		let trie =
736			estimation_trie.get_or_insert_with(|| EstimationTrie::new(state_version, self.root));
737		self.with_recorder_and_cache(None, |recorder, cache| match trie {
738			EstimationTrie::V0(trie) => {
739				expect_existing_nodes(remove_trie_keys_from_delta::<sp_trie::LayoutV0<H>, _, _, _>(
740					&eph,
741					keys_to_be_removed,
742					trie,
743					recorder,
744					cache,
745				))
746			},
747			EstimationTrie::V1(trie) => {
748				expect_existing_nodes(remove_trie_keys_from_delta::<sp_trie::LayoutV1<H>, _, _, _>(
749					&eph,
750					keys_to_be_removed,
751					trie,
752					recorder,
753					cache,
754				))
755			},
756		});
757	}
758
759	/// Returns the child storage root for the child trie `child_info` after applying the given
760	/// `delta`.
761	pub fn child_storage_root<'a>(
762		&self,
763		child_info: &ChildInfo,
764		delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
765		state_version: StateVersion,
766	) -> (H::Out, bool, PrefixedMemoryDB<H>) {
767		let default_root = match child_info.child_type() {
768			ChildType::ParentKeyId => empty_child_trie_root::<sp_trie::LayoutV1<H>>(),
769		};
770		let mut write_overlay = PrefixedMemoryDB::with_hasher(RandomState::default());
771		let child_root = match self.child_root(child_info) {
772			Ok(Some(hash)) => hash,
773			Ok(None) => default_root,
774			Err(e) => {
775				warn!(target: "trie", "Failed to read child storage root: {}", e);
776				default_root
777			},
778		};
779
780		let new_child_root =
781			self.with_recorder_and_cache_for_storage_root(Some(child_root), |recorder, cache| {
782				let mut eph = Ephemeral::new(self.backend_storage(), &mut write_overlay);
783				match match state_version {
784					StateVersion::V0 => {
785						child_delta_trie_root::<sp_trie::LayoutV0<H>, _, _, _, _, _, _>(
786							child_info.keyspace(),
787							&mut eph,
788							child_root,
789							delta,
790							recorder,
791							cache,
792						)
793					},
794					StateVersion::V1 => {
795						child_delta_trie_root::<sp_trie::LayoutV1<H>, _, _, _, _, _, _>(
796							child_info.keyspace(),
797							&mut eph,
798							child_root,
799							delta,
800							recorder,
801							cache,
802						)
803					},
804				} {
805					Ok(ret) => (Some(ret), ret),
806					Err(e) => {
807						warn!(target: "trie", "Failed to write to trie: {}", e);
808						(None, child_root)
809					},
810				}
811			});
812
813		let is_default = new_child_root == default_root;
814
815		(new_child_root, is_default, write_overlay)
816	}
817
818	/// Updates the recorder's proof size by recording child trie nodes for a given delta.
819	///
820	/// Refer to [`Self::record_proof_for_dirty_keys`] for more details.
821	pub fn record_proof_for_child_dirty_keys<'a>(
822		&self,
823		child_info: &ChildInfo,
824		delta: impl Iterator<Item = (&'a [u8], DeltaKeyOp)>,
825		estimation_trie: &mut Option<EstimationTrie<H>>,
826		state_version: StateVersion,
827	) {
828		let mut delta = delta.into_iter().collect::<Vec<_>>();
829		if delta.is_empty() {
830			return;
831		}
832		delta.sort();
833
834		let default_root = match child_info.child_type() {
835			ChildType::ParentKeyId => empty_child_trie_root::<sp_trie::LayoutV1<H>>(),
836		};
837		let mut write_overlay = PrefixedMemoryDB::with_hasher(RandomState::default());
838		let child_root = expect_existing_nodes(self.child_root(child_info)).unwrap_or(default_root);
839		let eph = Ephemeral::new(self.backend_storage(), &mut write_overlay);
840		let keyspace = child_info.keyspace();
841
842		let (keys_to_be_read, keys_to_be_removed) = Self::partition_delta(delta);
843
844		self.with_recorder_and_cache(Some(child_root), |recorder, cache| match state_version {
845			StateVersion::V0 => expect_existing_nodes(child_read_trie_keys_from_delta::<
846				sp_trie::LayoutV0<H>,
847				_,
848				_,
849				_,
850				_,
851			>(
852				keyspace,
853				&eph,
854				child_root,
855				keys_to_be_read,
856				recorder,
857				cache,
858			)),
859			StateVersion::V1 => expect_existing_nodes(child_read_trie_keys_from_delta::<
860				sp_trie::LayoutV1<H>,
861				_,
862				_,
863				_,
864				_,
865			>(
866				keyspace,
867				&eph,
868				child_root,
869				keys_to_be_read,
870				recorder,
871				cache,
872			)),
873		});
874
875		if keys_to_be_removed.is_empty() {
876			return;
877		}
878		let trie =
879			estimation_trie.get_or_insert_with(|| EstimationTrie::new(state_version, child_root));
880		self.with_recorder_and_cache(Some(child_root), |recorder, cache| match trie {
881			EstimationTrie::V0(trie) => {
882				expect_existing_nodes(child_remove_trie_keys_from_delta::<
883					sp_trie::LayoutV0<H>,
884					_,
885					_,
886					_,
887				>(
888					keyspace, &eph, keys_to_be_removed, trie, recorder, cache
889				))
890			},
891			EstimationTrie::V1(trie) => {
892				expect_existing_nodes(child_remove_trie_keys_from_delta::<
893					sp_trie::LayoutV1<H>,
894					_,
895					_,
896					_,
897				>(
898					keyspace, &eph, keys_to_be_removed, trie, recorder, cache
899				))
900			},
901		});
902	}
903}
904
905pub(crate) struct Ephemeral<'a, S: 'a + TrieBackendStorage<H>, H: 'a + Hasher> {
906	storage: &'a S,
907	overlay: &'a mut PrefixedMemoryDB<H>,
908}
909
910impl<'a, S: 'a + TrieBackendStorage<H>, H: 'a + Hasher> AsHashDB<H, DBValue>
911	for Ephemeral<'a, S, H>
912{
913	fn as_hash_db<'b>(&'b self) -> &'b (dyn HashDB<H, DBValue> + 'b) {
914		self
915	}
916	fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (dyn HashDB<H, DBValue> + 'b) {
917		self
918	}
919}
920
921impl<'a, S: TrieBackendStorage<H>, H: Hasher> Ephemeral<'a, S, H> {
922	pub fn new(storage: &'a S, overlay: &'a mut PrefixedMemoryDB<H>) -> Self {
923		Ephemeral { storage, overlay }
924	}
925}
926
927impl<'a, S: 'a + TrieBackendStorage<H>, H: Hasher> hash_db::HashDB<H, DBValue>
928	for Ephemeral<'a, S, H>
929{
930	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<DBValue> {
931		HashDB::get(self.overlay, key, prefix).or_else(|| {
932			self.storage.get(key, prefix).unwrap_or_else(|e| {
933				warn!(target: "trie", "Failed to read from DB: {}", e);
934				None
935			})
936		})
937	}
938
939	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool {
940		HashDB::get(self, key, prefix).is_some()
941	}
942
943	fn insert(&mut self, prefix: Prefix, value: &[u8]) -> H::Out {
944		HashDB::insert(self.overlay, prefix, value)
945	}
946
947	fn emplace(&mut self, key: H::Out, prefix: Prefix, value: DBValue) {
948		HashDB::emplace(self.overlay, key, prefix, value)
949	}
950
951	fn remove(&mut self, key: &H::Out, prefix: Prefix) {
952		HashDB::remove(self.overlay, key, prefix)
953	}
954}
955
956impl<'a, S: 'a + TrieBackendStorage<H>, H: Hasher> HashDBRef<H, DBValue> for Ephemeral<'a, S, H> {
957	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<DBValue> {
958		HashDB::get(self, key, prefix)
959	}
960
961	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool {
962		HashDB::contains(self, key, prefix)
963	}
964}
965
966/// Key-value pairs storage that is used by trie backend essence.
967pub trait TrieBackendStorage<H: Hasher>: Send + Sync {
968	/// Get the value stored at key.
969	fn get(&self, key: &H::Out, prefix: Prefix) -> Result<Option<DBValue>>;
970}
971
972impl<T: TrieBackendStorage<H>, H: Hasher> TrieBackendStorage<H> for &T {
973	fn get(&self, key: &H::Out, prefix: Prefix) -> Result<Option<DBValue>> {
974		(*self).get(key, prefix)
975	}
976}
977
978// This implementation is used by normal storage trie clients.
979#[cfg(feature = "std")]
980impl<H: Hasher> TrieBackendStorage<H> for Arc<dyn Storage<H>> {
981	fn get(&self, key: &H::Out, prefix: Prefix) -> Result<Option<DBValue>> {
982		Storage::<H>::get(std::ops::Deref::deref(self), key, prefix)
983	}
984}
985
986impl<H, KF> TrieBackendStorage<H> for sp_trie::GenericMemoryDB<H, KF>
987where
988	H: Hasher,
989	KF: sp_trie::KeyFunction<H> + Send + Sync,
990{
991	fn get(&self, key: &H::Out, prefix: Prefix) -> Result<Option<DBValue>> {
992		Ok(hash_db::HashDB::get(self, key, prefix))
993	}
994}
995
996impl<
997		S: TrieBackendStorage<H>,
998		H: Hasher,
999		C: TrieCacheProvider<H> + Send + Sync,
1000		R: TrieRecorderProvider<H> + Send + Sync,
1001	> AsHashDB<H, DBValue> for TrieBackendEssence<S, H, C, R>
1002{
1003	fn as_hash_db<'b>(&'b self) -> &'b (dyn HashDB<H, DBValue> + 'b) {
1004		self
1005	}
1006
1007	fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (dyn HashDB<H, DBValue> + 'b) {
1008		self
1009	}
1010}
1011
1012impl<
1013		S: TrieBackendStorage<H>,
1014		H: Hasher,
1015		C: TrieCacheProvider<H> + Send + Sync,
1016		R: TrieRecorderProvider<H> + Send + Sync,
1017	> HashDB<H, DBValue> for TrieBackendEssence<S, H, C, R>
1018{
1019	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<DBValue> {
1020		if *key == self.empty {
1021			return Some([0u8].to_vec());
1022		}
1023		match self.storage.get(key, prefix) {
1024			Ok(x) => x,
1025			Err(e) => {
1026				warn!(target: "trie", "Failed to read from DB: {}", e);
1027				None
1028			},
1029		}
1030	}
1031
1032	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool {
1033		HashDB::get(self, key, prefix).is_some()
1034	}
1035
1036	fn insert(&mut self, _prefix: Prefix, _value: &[u8]) -> H::Out {
1037		unimplemented!();
1038	}
1039
1040	fn emplace(&mut self, _key: H::Out, _prefix: Prefix, _value: DBValue) {
1041		unimplemented!();
1042	}
1043
1044	fn remove(&mut self, _key: &H::Out, _prefix: Prefix) {
1045		unimplemented!();
1046	}
1047}
1048
1049impl<
1050		S: TrieBackendStorage<H>,
1051		H: Hasher,
1052		C: TrieCacheProvider<H> + Send + Sync,
1053		R: TrieRecorderProvider<H> + Send + Sync,
1054	> HashDBRef<H, DBValue> for TrieBackendEssence<S, H, C, R>
1055{
1056	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<DBValue> {
1057		HashDB::get(self, key, prefix)
1058	}
1059
1060	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool {
1061		HashDB::contains(self, key, prefix)
1062	}
1063}
1064
1065#[cfg(test)]
1066mod test {
1067	use super::*;
1068	use crate::{Backend, TrieBackend};
1069	use sp_core::{Blake2Hasher, H256};
1070	use sp_trie::{
1071		cache::LocalTrieCache, trie_types::TrieDBMutBuilderV1 as TrieDBMutBuilder, KeySpacedDBMut,
1072		PrefixedMemoryDB, TrieMut,
1073	};
1074
1075	#[test]
1076	fn next_storage_key_and_next_child_storage_key_work() {
1077		let child_info = ChildInfo::new_default(b"MyChild");
1078		let child_info = &child_info;
1079		// Contains values
1080		let mut root_1 = H256::default();
1081		// Contains child trie
1082		let mut root_2 = H256::default();
1083
1084		let mut mdb = PrefixedMemoryDB::<Blake2Hasher>::default();
1085		{
1086			let mut trie = TrieDBMutBuilder::new(&mut mdb, &mut root_1).build();
1087			trie.insert(b"3", &[1]).expect("insert failed");
1088			trie.insert(b"4", &[1]).expect("insert failed");
1089			trie.insert(b"6", &[1]).expect("insert failed");
1090		}
1091		{
1092			let mut mdb = KeySpacedDBMut::new(&mut mdb, child_info.keyspace());
1093			// reuse of root_1 implicitly assert child trie root is same
1094			// as top trie (contents must remain the same).
1095			let mut trie = TrieDBMutBuilder::new(&mut mdb, &mut root_1).build();
1096			trie.insert(b"3", &[1]).expect("insert failed");
1097			trie.insert(b"4", &[1]).expect("insert failed");
1098			trie.insert(b"6", &[1]).expect("insert failed");
1099		}
1100		{
1101			let mut trie = TrieDBMutBuilder::new(&mut mdb, &mut root_2).build();
1102			trie.insert(child_info.prefixed_storage_key().as_slice(), root_1.as_ref())
1103				.expect("insert failed");
1104		};
1105
1106		let essence_1 =
1107			TrieBackendEssence::<_, _, LocalTrieCache<_>, sp_trie::recorder::Recorder<_>>::new(
1108				mdb, root_1,
1109			);
1110		let mdb = essence_1.backend_storage().clone();
1111		let essence_1 = TrieBackend::from_essence(essence_1);
1112
1113		assert_eq!(essence_1.next_storage_key(b"2"), Ok(Some(b"3".to_vec())));
1114		assert_eq!(essence_1.next_storage_key(b"3"), Ok(Some(b"4".to_vec())));
1115		assert_eq!(essence_1.next_storage_key(b"4"), Ok(Some(b"6".to_vec())));
1116		assert_eq!(essence_1.next_storage_key(b"5"), Ok(Some(b"6".to_vec())));
1117		assert_eq!(essence_1.next_storage_key(b"6"), Ok(None));
1118
1119		let essence_2 =
1120			TrieBackendEssence::<_, _, LocalTrieCache<_>, sp_trie::recorder::Recorder<_>>::new(
1121				mdb, root_2,
1122			);
1123
1124		assert_eq!(essence_2.next_child_storage_key(child_info, b"2"), Ok(Some(b"3".to_vec())));
1125		assert_eq!(essence_2.next_child_storage_key(child_info, b"3"), Ok(Some(b"4".to_vec())));
1126		assert_eq!(essence_2.next_child_storage_key(child_info, b"4"), Ok(Some(b"6".to_vec())));
1127		assert_eq!(essence_2.next_child_storage_key(child_info, b"5"), Ok(Some(b"6".to_vec())));
1128		assert_eq!(essence_2.next_child_storage_key(child_info, b"6"), Ok(None));
1129	}
1130}