trie_db/
lib.rs

1// Copyright 2017, 2021 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#![cfg_attr(not(feature = "std"), no_std)]
15
16//! Trie interface and implementation.
17
18#[cfg(not(feature = "std"))]
19extern crate alloc;
20
21#[cfg(feature = "std")]
22mod rstd {
23	pub use std::{
24		borrow, boxed, cmp,
25		collections::{BTreeMap, VecDeque},
26		convert,
27		error::Error,
28		fmt, hash, iter, marker, mem, ops, result, sync, vec,
29	};
30}
31
32#[cfg(not(feature = "std"))]
33mod rstd {
34	pub use alloc::{
35		borrow, boxed,
36		collections::{btree_map::BTreeMap, VecDeque},
37		rc, sync, vec,
38	};
39	pub use core::{cmp, convert, fmt, hash, iter, marker, mem, ops, result};
40	pub trait Error {}
41	impl<T> Error for T {}
42}
43
44#[cfg(feature = "std")]
45use self::rstd::{fmt, Error};
46
47use self::rstd::{boxed::Box, vec::Vec};
48use hash_db::MaybeDebug;
49pub use iterator::TrieDBNodeDoubleEndedIterator;
50use node::NodeOwned;
51
52pub mod node;
53pub mod proof;
54pub mod recorder;
55pub mod sectriedb;
56pub mod sectriedbmut;
57pub mod triedb;
58pub mod triedbmut;
59
60mod fatdb;
61mod fatdbmut;
62mod iter_build;
63mod iterator;
64mod lookup;
65mod nibble;
66mod node_codec;
67mod trie_codec;
68
69pub use self::{
70	fatdb::{FatDB, FatDBIterator},
71	fatdbmut::FatDBMut,
72	lookup::Lookup,
73	nibble::{nibble_ops, NibbleSlice, NibbleVec},
74	recorder::Recorder,
75	sectriedb::SecTrieDB,
76	sectriedbmut::SecTrieDBMut,
77	triedb::{TrieDB, TrieDBBuilder, TrieDBIterator, TrieDBKeyIterator},
78	triedbmut::{ChildReference, TrieDBMut, TrieDBMutBuilder, Value},
79};
80pub use crate::{
81	iter_build::{trie_visit, ProcessEncodedNode, TrieBuilder, TrieRoot, TrieRootUnhashed},
82	iterator::{TrieDBNodeIterator, TrieDBRawIterator},
83	node_codec::{NodeCodec, Partial},
84	trie_codec::{decode_compact, decode_compact_from_iter, encode_compact},
85};
86pub use hash_db::{HashDB, HashDBRef, Hasher};
87
88#[cfg(feature = "std")]
89pub use crate::iter_build::TrieRootPrint;
90
91/// Database value
92pub type DBValue = Vec<u8>;
93
94/// Trie Errors.
95///
96/// These borrow the data within them to avoid excessive copying on every
97/// trie operation.
98#[derive(PartialEq, Eq, Clone, Debug)]
99pub enum TrieError<T, E> {
100	/// Attempted to create a trie with a state root not in the DB.
101	InvalidStateRoot(T),
102	/// Trie item not found in the database,
103	IncompleteDatabase(T),
104	/// A value was found in the trie with a nibble key that was not byte-aligned.
105	/// The first parameter is the byte-aligned part of the prefix and the second parameter is the
106	/// remaining nibble.
107	ValueAtIncompleteKey(Vec<u8>, u8),
108	/// Corrupt Trie item.
109	DecoderError(T, E),
110	/// Hash is not value.
111	InvalidHash(T, Vec<u8>),
112}
113
114#[cfg(feature = "std")]
115impl<T, E> fmt::Display for TrieError<T, E>
116where
117	T: MaybeDebug,
118	E: MaybeDebug,
119{
120	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121		match *self {
122			TrieError::InvalidStateRoot(ref root) => write!(f, "Invalid state root: {:?}", root),
123			TrieError::IncompleteDatabase(ref missing) =>
124				write!(f, "Database missing expected key: {:?}", missing),
125			TrieError::ValueAtIncompleteKey(ref bytes, ref extra) =>
126				write!(f, "Value found in trie at incomplete key {:?} + {:?}", bytes, extra),
127			TrieError::DecoderError(ref hash, ref decoder_err) => {
128				write!(f, "Decoding failed for hash {:?}; err: {:?}", hash, decoder_err)
129			},
130			TrieError::InvalidHash(ref hash, ref data) => write!(
131				f,
132				"Encoded node {:?} contains invalid hash reference with length: {}",
133				hash,
134				data.len()
135			),
136		}
137	}
138}
139
140#[cfg(feature = "std")]
141impl<T, E> Error for TrieError<T, E>
142where
143	T: fmt::Debug,
144	E: Error,
145{
146}
147
148/// Trie result type.
149/// Boxed to avoid copying around extra space for the `Hasher`s `Out` on successful queries.
150pub type Result<T, H, E> = crate::rstd::result::Result<T, Box<TrieError<H, E>>>;
151
152/// Trie-Item type used for iterators over trie data.
153pub type TrieItem<U, E> = Result<(Vec<u8>, DBValue), U, E>;
154
155/// Trie-Item type used for iterators over trie key only.
156pub type TrieKeyItem<U, E> = Result<Vec<u8>, U, E>;
157
158/// Description of what kind of query will be made to the trie.
159pub trait Query<H: Hasher> {
160	/// Output item.
161	type Item;
162
163	/// Decode a byte-slice into the desired item.
164	fn decode(self, data: &[u8]) -> Self::Item;
165}
166
167/// Used to report the trie access to the [`TrieRecorder`].
168///
169/// As the trie can use a [`TrieCache`], there are multiple kinds of accesses.
170/// If a cache is used, [`Self::Key`] and [`Self::NodeOwned`] are possible
171/// values. Otherwise only [`Self::EncodedNode`] is a possible value.
172#[cfg_attr(feature = "std", derive(Debug))]
173pub enum TrieAccess<'a, H> {
174	/// The given [`NodeOwned`] was accessed using its `hash`.
175	NodeOwned { hash: H, node_owned: &'a NodeOwned<H> },
176	/// The given `encoded_node` was accessed using its `hash`.
177	EncodedNode { hash: H, encoded_node: rstd::borrow::Cow<'a, [u8]> },
178	/// The given `value` was accessed using its `hash`.
179	///
180	/// The given `full_key` is the key to access this value in the trie.
181	///
182	/// Should map to [`RecordedForKey::Value`] when checking the recorder.
183	Value { hash: H, value: rstd::borrow::Cow<'a, [u8]>, full_key: &'a [u8] },
184	/// A value was accessed that is stored inline a node.
185	///
186	/// As the value is stored inline there is no need to separately record the value as it is part
187	/// of a node. The given `full_key` is the key to access this value in the trie.
188	///
189	/// Should map to [`RecordedForKey::Value`] when checking the recorder.
190	InlineValue { full_key: &'a [u8] },
191	/// The hash of the value for the given `full_key` was accessed.
192	///
193	/// Should map to [`RecordedForKey::Hash`] when checking the recorder.
194	Hash { full_key: &'a [u8] },
195	/// The value/hash for `full_key` was accessed, but it couldn't be found in the trie.
196	///
197	/// Should map to [`RecordedForKey::Value`] when checking the recorder.
198	NonExisting { full_key: &'a [u8] },
199}
200
201/// Result of [`TrieRecorder::trie_nodes_recorded_for_key`].
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum RecordedForKey {
204	/// We recorded all trie nodes up to the value for a storage key.
205	///
206	/// This should be returned when the recorder has seen the following [`TrieAccess`]:
207	///
208	/// - [`TrieAccess::Value`]: If we see this [`TrieAccess`], it means we have recorded all the
209	///   trie nodes up to the value.
210	/// - [`TrieAccess::NonExisting`]: If we see this [`TrieAccess`], it means we have recorded all
211	///   the necessary  trie nodes to prove that the value doesn't exist in the trie.
212	Value,
213	/// We recorded all trie nodes up to the value hash for a storage key.
214	///
215	/// If we have a [`RecordedForKey::Value`], it means that we also have the hash of this value.
216	/// This also means that if we first have recorded the hash of a value and then also record the
217	/// value, the access should be upgraded to [`RecordedForKey::Value`].
218	///
219	/// This should be returned when the recorder has seen the following [`TrieAccess`]:
220	///
221	/// - [`TrieAccess::Hash`]: If we see this [`TrieAccess`], it means we have recorded all trie
222	///   nodes to have the hash of the value.
223	Hash,
224	/// We haven't recorded any trie nodes yet for a storage key.
225	///
226	/// This means we have not seen any [`TrieAccess`] referencing the searched key.
227	None,
228}
229
230impl RecordedForKey {
231	/// Is `self` equal to [`Self::None`]?
232	pub fn is_none(&self) -> bool {
233		matches!(self, Self::None)
234	}
235}
236
237/// A trie recorder that can be used to record all kind of [`TrieAccess`]'s.
238///
239/// To build a trie proof a recorder is required that records all trie accesses. These recorded trie
240/// accesses can then be used to create the proof.
241pub trait TrieRecorder<H> {
242	/// Record the given [`TrieAccess`].
243	///
244	/// Depending on the [`TrieAccess`] a call of [`Self::trie_nodes_recorded_for_key`] afterwards
245	/// must return the correct recorded state.
246	fn record<'a>(&mut self, access: TrieAccess<'a, H>);
247
248	/// Check if we have recorded any trie nodes for the given `key`.
249	///
250	/// Returns [`RecordedForKey`] to express the state of the recorded trie nodes.
251	fn trie_nodes_recorded_for_key(&self, key: &[u8]) -> RecordedForKey;
252}
253
254impl<F, T, H: Hasher> Query<H> for F
255where
256	F: for<'a> FnOnce(&'a [u8]) -> T,
257{
258	type Item = T;
259	fn decode(self, value: &[u8]) -> T {
260		(self)(value)
261	}
262}
263
264/// A key-value datastore implemented as a database-backed modified Merkle tree.
265pub trait Trie<L: TrieLayout> {
266	/// Return the root of the trie.
267	fn root(&self) -> &TrieHash<L>;
268
269	/// Is the trie empty?
270	fn is_empty(&self) -> bool {
271		*self.root() == L::Codec::hashed_null_node()
272	}
273
274	/// Does the trie contain a given key?
275	fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
276		self.get(key).map(|x| x.is_some())
277	}
278
279	/// Returns the hash of the value for `key`.
280	fn get_hash(&self, key: &[u8]) -> Result<Option<TrieHash<L>>, TrieHash<L>, CError<L>>;
281
282	/// What is the value of the given key in this trie?
283	fn get(&self, key: &[u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>> {
284		self.get_with(key, |v: &[u8]| v.to_vec())
285	}
286
287	/// Search for the key with the given query parameter. See the docs of the `Query`
288	/// trait for more details.
289	fn get_with<Q: Query<L::Hash>>(
290		&self,
291		key: &[u8],
292		query: Q,
293	) -> Result<Option<Q::Item>, TrieHash<L>, CError<L>>;
294
295	/// Look up the [`MerkleValue`] of the node that is the closest descendant for the provided
296	/// key.
297	///
298	/// When the provided key leads to a node, then the merkle value of that node
299	/// is returned. However, if the key does not lead to a node, then the merkle value
300	/// of the closest descendant is returned. `None` if no such descendant exists.
301	fn lookup_first_descendant(
302		&self,
303		key: &[u8],
304	) -> Result<Option<MerkleValue<TrieHash<L>>>, TrieHash<L>, CError<L>>;
305
306	/// Returns a depth-first iterator over the elements of trie.
307	fn iter<'a>(
308		&'a self,
309	) -> Result<
310		Box<dyn TrieIterator<L, Item = TrieItem<TrieHash<L>, CError<L>>> + 'a>,
311		TrieHash<L>,
312		CError<L>,
313	>;
314
315	/// Returns a depth-first iterator over the keys of elemets of trie.
316	fn key_iter<'a>(
317		&'a self,
318	) -> Result<
319		Box<dyn TrieIterator<L, Item = TrieKeyItem<TrieHash<L>, CError<L>>> + 'a>,
320		TrieHash<L>,
321		CError<L>,
322	>;
323}
324
325/// A key-value datastore implemented as a database-backed modified Merkle tree.
326pub trait TrieMut<L: TrieLayout> {
327	/// Return the root of the trie.
328	fn root(&mut self) -> &TrieHash<L>;
329
330	/// Is the trie empty?
331	fn is_empty(&self) -> bool;
332
333	/// Does the trie contain a given key?
334	fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
335		self.get(key).map(|x| x.is_some())
336	}
337
338	/// What is the value of the given key in this trie?
339	fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>>
340	where
341		'a: 'key;
342
343	/// Insert a `key`/`value` pair into the trie. An empty value is equivalent to removing
344	/// `key` from the trie. Returns the old value associated with this key, if it existed.
345	fn insert(
346		&mut self,
347		key: &[u8],
348		value: &[u8],
349	) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>>;
350
351	/// Remove a `key` from the trie. Equivalent to making it equal to the empty
352	/// value. Returns the old value associated with this key, if it existed.
353	fn remove(&mut self, key: &[u8]) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>>;
354}
355
356/// A trie iterator that also supports random access (`seek()`).
357pub trait TrieIterator<L: TrieLayout>: Iterator {
358	/// Position the iterator on the first element with key >= `key`
359	fn seek(&mut self, key: &[u8]) -> Result<(), TrieHash<L>, CError<L>>;
360}
361
362/// Extending the `TrieIterator` trait with `DoubleEndedIterator` trait.
363pub trait TrieDoubleEndedIterator<L: TrieLayout>: TrieIterator<L> + DoubleEndedIterator {}
364
365/// Trie types
366#[derive(PartialEq, Clone)]
367#[cfg_attr(feature = "std", derive(Debug))]
368pub enum TrieSpec {
369	/// Generic trie.
370	Generic,
371	/// Secure trie.
372	Secure,
373	///	Secure trie with fat database.
374	Fat,
375}
376
377impl Default for TrieSpec {
378	fn default() -> TrieSpec {
379		TrieSpec::Secure
380	}
381}
382
383/// Trie factory.
384#[derive(Default, Clone)]
385pub struct TrieFactory {
386	spec: TrieSpec,
387}
388
389/// All different kinds of tries.
390/// This is used to prevent a heap allocation for every created trie.
391pub enum TrieKinds<'db, 'cache, L: TrieLayout> {
392	/// A generic trie db.
393	Generic(TrieDB<'db, 'cache, L>),
394	/// A secure trie db.
395	Secure(SecTrieDB<'db, 'cache, L>),
396	/// A fat trie db.
397	Fat(FatDB<'db, 'cache, L>),
398}
399
400// wrapper macro for making the match easier to deal with.
401macro_rules! wrapper {
402	($me: ident, $f_name: ident, $($param: ident),*) => {
403		match *$me {
404			TrieKinds::Generic(ref t) => t.$f_name($($param),*),
405			TrieKinds::Secure(ref t) => t.$f_name($($param),*),
406			TrieKinds::Fat(ref t) => t.$f_name($($param),*),
407		}
408	}
409}
410
411impl<'db, 'cache, L: TrieLayout> Trie<L> for TrieKinds<'db, 'cache, L> {
412	fn root(&self) -> &TrieHash<L> {
413		wrapper!(self, root,)
414	}
415
416	fn is_empty(&self) -> bool {
417		wrapper!(self, is_empty,)
418	}
419
420	fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
421		wrapper!(self, contains, key)
422	}
423
424	fn get_hash(&self, key: &[u8]) -> Result<Option<TrieHash<L>>, TrieHash<L>, CError<L>> {
425		wrapper!(self, get_hash, key)
426	}
427
428	fn get_with<Q: Query<L::Hash>>(
429		&self,
430		key: &[u8],
431		query: Q,
432	) -> Result<Option<Q::Item>, TrieHash<L>, CError<L>> {
433		wrapper!(self, get_with, key, query)
434	}
435
436	fn lookup_first_descendant(
437		&self,
438		key: &[u8],
439	) -> Result<Option<MerkleValue<TrieHash<L>>>, TrieHash<L>, CError<L>> {
440		wrapper!(self, lookup_first_descendant, key)
441	}
442
443	fn iter<'a>(
444		&'a self,
445	) -> Result<
446		Box<dyn TrieIterator<L, Item = TrieItem<TrieHash<L>, CError<L>>> + 'a>,
447		TrieHash<L>,
448		CError<L>,
449	> {
450		wrapper!(self, iter,)
451	}
452
453	fn key_iter<'a>(
454		&'a self,
455	) -> Result<
456		Box<dyn TrieIterator<L, Item = TrieKeyItem<TrieHash<L>, CError<L>>> + 'a>,
457		TrieHash<L>,
458		CError<L>,
459	> {
460		wrapper!(self, key_iter,)
461	}
462}
463
464impl TrieFactory {
465	/// Creates new factory.
466	pub fn new(spec: TrieSpec) -> Self {
467		TrieFactory { spec }
468	}
469
470	/// Create new immutable instance of Trie.
471	pub fn readonly<'db, 'cache, L: TrieLayout>(
472		&self,
473		db: &'db dyn HashDBRef<L::Hash, DBValue>,
474		root: &'db TrieHash<L>,
475	) -> TrieKinds<'db, 'cache, L> {
476		match self.spec {
477			TrieSpec::Generic => TrieKinds::Generic(TrieDBBuilder::new(db, root).build()),
478			TrieSpec::Secure => TrieKinds::Secure(SecTrieDB::new(db, root)),
479			TrieSpec::Fat => TrieKinds::Fat(FatDB::new(db, root)),
480		}
481	}
482
483	/// Create new mutable instance of Trie.
484	pub fn create<'db, L: TrieLayout + 'db>(
485		&self,
486		db: &'db mut dyn HashDB<L::Hash, DBValue>,
487		root: &'db mut TrieHash<L>,
488	) -> Box<dyn TrieMut<L> + 'db> {
489		match self.spec {
490			TrieSpec::Generic => Box::new(TrieDBMutBuilder::<L>::new(db, root).build()),
491			TrieSpec::Secure => Box::new(SecTrieDBMut::<L>::new(db, root)),
492			TrieSpec::Fat => Box::new(FatDBMut::<L>::new(db, root)),
493		}
494	}
495
496	/// Create new mutable instance of trie and check for errors.
497	pub fn from_existing<'db, L: TrieLayout + 'db>(
498		&self,
499		db: &'db mut dyn HashDB<L::Hash, DBValue>,
500		root: &'db mut TrieHash<L>,
501	) -> Box<dyn TrieMut<L> + 'db> {
502		match self.spec {
503			TrieSpec::Generic => Box::new(TrieDBMutBuilder::<L>::from_existing(db, root).build()),
504			TrieSpec::Secure => Box::new(SecTrieDBMut::<L>::from_existing(db, root)),
505			TrieSpec::Fat => Box::new(FatDBMut::<L>::from_existing(db, root)),
506		}
507	}
508
509	/// Returns true iff the trie DB is a fat DB (allows enumeration of keys).
510	pub fn is_fat(&self) -> bool {
511		self.spec == TrieSpec::Fat
512	}
513}
514
515/// Trait with definition of trie layout.
516/// Contains all associated trait needed for
517/// a trie definition or implementation.
518pub trait TrieLayout {
519	/// If true, the trie will use extension nodes and
520	/// no partial in branch, if false the trie will only
521	/// use branch and node with partials in both.
522	const USE_EXTENSION: bool;
523	/// If true, the trie will allow empty values into `TrieDBMut`
524	const ALLOW_EMPTY: bool = false;
525	/// Threshold above which an external node should be
526	/// use to store a node value.
527	const MAX_INLINE_VALUE: Option<u32>;
528
529	/// Hasher to use for this trie.
530	type Hash: Hasher;
531	/// Codec to use (needs to match hasher and nibble ops).
532	type Codec: NodeCodec<HashOut = <Self::Hash as Hasher>::Out>;
533}
534
535/// This trait associates a trie definition with preferred methods.
536/// It also contains own default implementations and can be
537/// used to allow switching implementation.
538pub trait TrieConfiguration: Sized + TrieLayout {
539	/// Operation to build a trie db from its ordered iterator over its key/values.
540	fn trie_build<DB, I, A, B>(db: &mut DB, input: I) -> <Self::Hash as Hasher>::Out
541	where
542		DB: HashDB<Self::Hash, DBValue>,
543		I: IntoIterator<Item = (A, B)>,
544		A: AsRef<[u8]> + Ord,
545		B: AsRef<[u8]>,
546	{
547		let mut cb = TrieBuilder::<Self, DB>::new(db);
548		trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
549		cb.root.unwrap_or_default()
550	}
551	/// Determines a trie root given its ordered contents, closed form.
552	fn trie_root<I, A, B>(input: I) -> <Self::Hash as Hasher>::Out
553	where
554		I: IntoIterator<Item = (A, B)>,
555		A: AsRef<[u8]> + Ord,
556		B: AsRef<[u8]>,
557	{
558		let mut cb = TrieRoot::<Self>::default();
559		trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
560		cb.root.unwrap_or_default()
561	}
562	/// Determines a trie root node's data given its ordered contents, closed form.
563	fn trie_root_unhashed<I, A, B>(input: I) -> Vec<u8>
564	where
565		I: IntoIterator<Item = (A, B)>,
566		A: AsRef<[u8]> + Ord,
567		B: AsRef<[u8]>,
568	{
569		let mut cb = TrieRootUnhashed::<Self>::default();
570		trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
571		cb.root.unwrap_or_default()
572	}
573	/// Encoding of index as a key (when reusing general trie for
574	/// indexed trie).
575	fn encode_index(input: u32) -> Vec<u8> {
576		// be for byte ordering
577		input.to_be_bytes().to_vec()
578	}
579	/// A trie root formed from the items, with keys attached according to their
580	/// compact-encoded index (using `parity-codec` crate).
581	fn ordered_trie_root<I, A>(input: I) -> <Self::Hash as Hasher>::Out
582	where
583		I: IntoIterator<Item = A>,
584		A: AsRef<[u8]>,
585	{
586		Self::trie_root(
587			input.into_iter().enumerate().map(|(i, v)| (Self::encode_index(i as u32), v)),
588		)
589	}
590}
591
592/// Alias accessor to hasher hash output type from a `TrieLayout`.
593pub type TrieHash<L> = <<L as TrieLayout>::Hash as Hasher>::Out;
594/// Alias accessor to `NodeCodec` associated `Error` type from a `TrieLayout`.
595pub type CError<L> = <<L as TrieLayout>::Codec as NodeCodec>::Error;
596
597/// A value as cached by the [`TrieCache`].
598#[derive(Clone, Debug)]
599pub enum CachedValue<H> {
600	/// The value doesn't exist in the trie.
601	NonExisting,
602	/// We cached the hash, because we did not yet accessed the data.
603	ExistingHash(H),
604	/// The value exists in the trie.
605	Existing {
606		/// The hash of the value.
607		hash: H,
608		/// The actual data of the value stored as [`BytesWeak`].
609		///
610		/// The original data [`Bytes`] is stored in the trie node
611		/// that is also cached by the [`TrieCache`]. If this node is dropped,
612		/// this data will also not be "upgradeable" anymore.
613		data: BytesWeak,
614	},
615}
616
617impl<H: Copy> CachedValue<H> {
618	/// Returns the data of the value.
619	///
620	/// If a value doesn't exist in the trie or only the value hash is cached, this function returns
621	/// `None`. If the reference to the data couldn't be upgraded (see [`Bytes::upgrade`]), this
622	/// function returns `Some(None)`, aka the data needs to be fetched again from the trie.
623	pub fn data(&self) -> Option<Option<Bytes>> {
624		match self {
625			Self::Existing { data, .. } => Some(data.upgrade()),
626			_ => None,
627		}
628	}
629
630	/// Returns the hash of the value.
631	///
632	/// Returns only `None` when the value doesn't exist.
633	pub fn hash(&self) -> Option<H> {
634		match self {
635			Self::ExistingHash(hash) | Self::Existing { hash, .. } => Some(*hash),
636			Self::NonExisting => None,
637		}
638	}
639}
640
641impl<H> From<(Bytes, H)> for CachedValue<H> {
642	fn from(value: (Bytes, H)) -> Self {
643		Self::Existing { hash: value.1, data: value.0.into() }
644	}
645}
646
647impl<H> From<H> for CachedValue<H> {
648	fn from(value: H) -> Self {
649		Self::ExistingHash(value)
650	}
651}
652
653impl<H> From<Option<(Bytes, H)>> for CachedValue<H> {
654	fn from(value: Option<(Bytes, H)>) -> Self {
655		value.map_or(Self::NonExisting, |v| Self::Existing { hash: v.1, data: v.0.into() })
656	}
657}
658
659impl<H> From<Option<H>> for CachedValue<H> {
660	fn from(value: Option<H>) -> Self {
661		value.map_or(Self::NonExisting, |v| Self::ExistingHash(v))
662	}
663}
664
665/// A cache that can be used to speed-up certain operations when accessing the trie.
666///
667/// The [`TrieDB`]/[`TrieDBMut`] by default are working with the internal hash-db in a non-owning
668/// mode. This means that for every lookup in the trie, every node is always fetched and decoded on
669/// the fly. Fetching and decoding a node always takes some time and can kill the performance of any
670/// application that is doing quite a lot of trie lookups. To circumvent this performance
671/// degradation, a cache can be used when looking up something in the trie. Any cache that should be
672/// used with the [`TrieDB`]/[`TrieDBMut`] needs to implement this trait.
673///
674/// The trait is laying out a two level cache, first the trie nodes cache and then the value cache.
675/// The trie nodes cache, as the name indicates, is for caching trie nodes as [`NodeOwned`]. These
676/// trie nodes are referenced by their hash. The value cache is caching [`CachedValue`]'s and these
677/// are referenced by the key to look them up in the trie. As multiple different tries can have
678/// different values under the same key, it up to the cache implementation to ensure that the
679/// correct value is returned. As each trie has a different root, this root can be used to
680/// differentiate values under the same key.
681pub trait TrieCache<NC: NodeCodec> {
682	/// Lookup value for the given `key`.
683	///
684	/// Returns the `None` if the `key` is unknown or otherwise `Some(_)` with the associated
685	/// value.
686	///
687	/// [`Self::cache_data_for_key`] is used to make the cache aware of data that is associated
688	/// to a `key`.
689	///
690	/// # Attention
691	///
692	/// The cache can be used for different tries, aka with different roots. This means
693	/// that the cache implementation needs to take care of always returning the correct value
694	/// for the current trie root.
695	fn lookup_value_for_key(&mut self, key: &[u8]) -> Option<&CachedValue<NC::HashOut>>;
696
697	/// Cache the given `value` for the given `key`.
698	///
699	/// # Attention
700	///
701	/// The cache can be used for different tries, aka with different roots. This means
702	/// that the cache implementation needs to take care of caching `value` for the current
703	/// trie root.
704	fn cache_value_for_key(&mut self, key: &[u8], value: CachedValue<NC::HashOut>);
705
706	/// Get or insert a [`NodeOwned`].
707	///
708	/// The cache implementation should look up based on the given `hash` if the node is already
709	/// known. If the node is not yet known, the given `fetch_node` function can be used to fetch
710	/// the particular node.
711	///
712	/// Returns the [`NodeOwned`] or an error that happened on fetching the node.
713	fn get_or_insert_node(
714		&mut self,
715		hash: NC::HashOut,
716		fetch_node: &mut dyn FnMut() -> Result<NodeOwned<NC::HashOut>, NC::HashOut, NC::Error>,
717	) -> Result<&NodeOwned<NC::HashOut>, NC::HashOut, NC::Error>;
718
719	/// Get the [`NodeOwned`] that corresponds to the given `hash`.
720	fn get_node(&mut self, hash: &NC::HashOut) -> Option<&NodeOwned<NC::HashOut>>;
721}
722
723/// A container for storing bytes.
724///
725/// This uses a reference counted pointer internally, so it is cheap to clone this object.
726#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
727pub struct Bytes(rstd::sync::Arc<[u8]>);
728
729impl rstd::ops::Deref for Bytes {
730	type Target = [u8];
731
732	fn deref(&self) -> &Self::Target {
733		self.0.deref()
734	}
735}
736
737impl From<Vec<u8>> for Bytes {
738	fn from(bytes: Vec<u8>) -> Self {
739		Self(bytes.into())
740	}
741}
742
743impl From<&[u8]> for Bytes {
744	fn from(bytes: &[u8]) -> Self {
745		Self(bytes.into())
746	}
747}
748
749impl<T: AsRef<[u8]>> PartialEq<T> for Bytes {
750	fn eq(&self, other: &T) -> bool {
751		self.as_ref() == other.as_ref()
752	}
753}
754
755/// A weak reference of [`Bytes`].
756///
757/// A weak reference means that it doesn't prevent [`Bytes`] from being dropped because
758/// it holds a non-owning reference to the associated [`Bytes`] object. With [`Self::upgrade`] it
759/// is possible to upgrade it again to [`Bytes`] if the reference is still valid.
760#[derive(Clone, Debug)]
761pub struct BytesWeak(rstd::sync::Weak<[u8]>);
762
763impl BytesWeak {
764	/// Upgrade to [`Bytes`].
765	///
766	/// Returns `None` when the inner value was already dropped.
767	pub fn upgrade(&self) -> Option<Bytes> {
768		self.0.upgrade().map(Bytes)
769	}
770}
771
772impl From<Bytes> for BytesWeak {
773	fn from(bytes: Bytes) -> Self {
774		Self(rstd::sync::Arc::downgrade(&bytes.0))
775	}
776}
777
778/// Either the `hash` or `value` of a node depending on its size.
779///
780/// If the size of the node `value` is bigger or equal than `MAX_INLINE_VALUE` the `hash` is
781/// returned.
782#[derive(Clone, Debug, PartialEq, Eq)]
783pub enum MerkleValue<H> {
784	/// The merkle value is the node data itself when the
785	/// node data is smaller than `MAX_INLINE_VALUE`.
786	///
787	/// Note: The case of inline nodes.
788	Node(Vec<u8>),
789	/// The merkle value is the hash of the node.
790	Hash(H),
791}