1#![cfg_attr(not(feature = "std"), no_std)]
15
16#[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, BTreeSet, 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, btree_set::BTreeSet, 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::{
85 decode_compact, decode_compact_from_iter, encode_compact, encode_compact_skip_duplicates,
86 SeenHashes,
87 },
88};
89pub use hash_db::{HashDB, HashDBRef, Hasher};
90
91#[cfg(feature = "std")]
92pub use crate::iter_build::TrieRootPrint;
93
94pub type DBValue = Vec<u8>;
96
97#[derive(PartialEq, Eq, Clone, Debug)]
102pub enum TrieError<T, E> {
103 InvalidStateRoot(T),
105 IncompleteDatabase(T),
107 ValueAtIncompleteKey(Vec<u8>, u8),
111 DecoderError(T, E),
113 InvalidHash(T, Vec<u8>),
115}
116
117#[cfg(feature = "std")]
118impl<T, E> fmt::Display for TrieError<T, E>
119where
120 T: MaybeDebug,
121 E: MaybeDebug,
122{
123 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
124 match *self {
125 TrieError::InvalidStateRoot(ref root) => write!(f, "Invalid state root: {:?}", root),
126 TrieError::IncompleteDatabase(ref missing) =>
127 write!(f, "Database missing expected key: {:?}", missing),
128 TrieError::ValueAtIncompleteKey(ref bytes, ref extra) =>
129 write!(f, "Value found in trie at incomplete key {:?} + {:?}", bytes, extra),
130 TrieError::DecoderError(ref hash, ref decoder_err) => {
131 write!(f, "Decoding failed for hash {:?}; err: {:?}", hash, decoder_err)
132 },
133 TrieError::InvalidHash(ref hash, ref data) => write!(
134 f,
135 "Encoded node {:?} contains invalid hash reference with length: {}",
136 hash,
137 data.len()
138 ),
139 }
140 }
141}
142
143#[cfg(feature = "std")]
144impl<T, E> Error for TrieError<T, E>
145where
146 T: fmt::Debug,
147 E: Error,
148{
149}
150
151pub type Result<T, H, E> = crate::rstd::result::Result<T, Box<TrieError<H, E>>>;
154
155pub type TrieItem<U, E> = Result<(Vec<u8>, DBValue), U, E>;
157
158pub type TrieKeyItem<U, E> = Result<Vec<u8>, U, E>;
160
161pub trait Query<H: Hasher> {
163 type Item;
165
166 fn decode(self, data: &[u8]) -> Self::Item;
168}
169
170#[cfg_attr(feature = "std", derive(Debug))]
176pub enum TrieAccess<'a, H> {
177 NodeOwned { hash: H, node_owned: &'a NodeOwned<H> },
179 EncodedNode { hash: H, encoded_node: rstd::borrow::Cow<'a, [u8]> },
181 Value { hash: H, value: rstd::borrow::Cow<'a, [u8]>, full_key: &'a [u8] },
187 InlineValue { full_key: &'a [u8] },
194 Hash { full_key: &'a [u8] },
198 NonExisting { full_key: &'a [u8] },
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum RecordedForKey {
207 Value,
216 Hash,
227 None,
231}
232
233impl RecordedForKey {
234 pub fn is_none(&self) -> bool {
236 matches!(self, Self::None)
237 }
238}
239
240pub trait TrieRecorder<H> {
245 fn record<'a>(&mut self, access: TrieAccess<'a, H>);
250
251 fn trie_nodes_recorded_for_key(&self, key: &[u8]) -> RecordedForKey;
255}
256
257impl<F, T, H: Hasher> Query<H> for F
258where
259 F: for<'a> FnOnce(&'a [u8]) -> T,
260{
261 type Item = T;
262 fn decode(self, value: &[u8]) -> T {
263 (self)(value)
264 }
265}
266
267pub trait Trie<L: TrieLayout> {
269 fn root(&self) -> &TrieHash<L>;
271
272 fn is_empty(&self) -> bool {
274 *self.root() == L::Codec::hashed_null_node()
275 }
276
277 fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
279 self.get(key).map(|x| x.is_some())
280 }
281
282 fn get_hash(&self, key: &[u8]) -> Result<Option<TrieHash<L>>, TrieHash<L>, CError<L>>;
284
285 fn get(&self, key: &[u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>> {
287 self.get_with(key, |v: &[u8]| v.to_vec())
288 }
289
290 fn get_with<Q: Query<L::Hash>>(
293 &self,
294 key: &[u8],
295 query: Q,
296 ) -> Result<Option<Q::Item>, TrieHash<L>, CError<L>>;
297
298 fn lookup_first_descendant(
305 &self,
306 key: &[u8],
307 ) -> Result<Option<MerkleValue<TrieHash<L>>>, TrieHash<L>, CError<L>>;
308
309 fn iter<'a>(
311 &'a self,
312 ) -> Result<
313 Box<dyn TrieIterator<L, Item = TrieItem<TrieHash<L>, CError<L>>> + 'a>,
314 TrieHash<L>,
315 CError<L>,
316 >;
317
318 fn key_iter<'a>(
320 &'a self,
321 ) -> Result<
322 Box<dyn TrieIterator<L, Item = TrieKeyItem<TrieHash<L>, CError<L>>> + 'a>,
323 TrieHash<L>,
324 CError<L>,
325 >;
326}
327
328pub trait TrieMut<L: TrieLayout> {
330 fn root(&mut self) -> &TrieHash<L>;
332
333 fn is_empty(&self) -> bool;
335
336 fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
338 self.get(key).map(|x| x.is_some())
339 }
340
341 fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>>
343 where
344 'a: 'key;
345
346 fn insert(
349 &mut self,
350 key: &[u8],
351 value: &[u8],
352 ) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>>;
353
354 fn remove(&mut self, key: &[u8]) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>>;
357}
358
359pub trait TrieIterator<L: TrieLayout>: Iterator {
361 fn seek(&mut self, key: &[u8]) -> Result<(), TrieHash<L>, CError<L>>;
363}
364
365pub trait TrieDoubleEndedIterator<L: TrieLayout>: TrieIterator<L> + DoubleEndedIterator {}
367
368#[derive(PartialEq, Clone)]
370#[cfg_attr(feature = "std", derive(Debug))]
371pub enum TrieSpec {
372 Generic,
374 Secure,
376 Fat,
378}
379
380impl Default for TrieSpec {
381 fn default() -> TrieSpec {
382 TrieSpec::Secure
383 }
384}
385
386#[derive(Default, Clone)]
388pub struct TrieFactory {
389 spec: TrieSpec,
390}
391
392pub enum TrieKinds<'db, 'cache, L: TrieLayout> {
395 Generic(TrieDB<'db, 'cache, L>),
397 Secure(SecTrieDB<'db, 'cache, L>),
399 Fat(FatDB<'db, 'cache, L>),
401}
402
403macro_rules! wrapper {
405 ($me: ident, $f_name: ident, $($param: ident),*) => {
406 match *$me {
407 TrieKinds::Generic(ref t) => t.$f_name($($param),*),
408 TrieKinds::Secure(ref t) => t.$f_name($($param),*),
409 TrieKinds::Fat(ref t) => t.$f_name($($param),*),
410 }
411 }
412}
413
414impl<'db, 'cache, L: TrieLayout> Trie<L> for TrieKinds<'db, 'cache, L> {
415 fn root(&self) -> &TrieHash<L> {
416 wrapper!(self, root,)
417 }
418
419 fn is_empty(&self) -> bool {
420 wrapper!(self, is_empty,)
421 }
422
423 fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
424 wrapper!(self, contains, key)
425 }
426
427 fn get_hash(&self, key: &[u8]) -> Result<Option<TrieHash<L>>, TrieHash<L>, CError<L>> {
428 wrapper!(self, get_hash, key)
429 }
430
431 fn get_with<Q: Query<L::Hash>>(
432 &self,
433 key: &[u8],
434 query: Q,
435 ) -> Result<Option<Q::Item>, TrieHash<L>, CError<L>> {
436 wrapper!(self, get_with, key, query)
437 }
438
439 fn lookup_first_descendant(
440 &self,
441 key: &[u8],
442 ) -> Result<Option<MerkleValue<TrieHash<L>>>, TrieHash<L>, CError<L>> {
443 wrapper!(self, lookup_first_descendant, key)
444 }
445
446 fn iter<'a>(
447 &'a self,
448 ) -> Result<
449 Box<dyn TrieIterator<L, Item = TrieItem<TrieHash<L>, CError<L>>> + 'a>,
450 TrieHash<L>,
451 CError<L>,
452 > {
453 wrapper!(self, iter,)
454 }
455
456 fn key_iter<'a>(
457 &'a self,
458 ) -> Result<
459 Box<dyn TrieIterator<L, Item = TrieKeyItem<TrieHash<L>, CError<L>>> + 'a>,
460 TrieHash<L>,
461 CError<L>,
462 > {
463 wrapper!(self, key_iter,)
464 }
465}
466
467impl TrieFactory {
468 pub fn new(spec: TrieSpec) -> Self {
470 TrieFactory { spec }
471 }
472
473 pub fn readonly<'db, 'cache, L: TrieLayout>(
475 &self,
476 db: &'db dyn HashDBRef<L::Hash, DBValue>,
477 root: &'db TrieHash<L>,
478 ) -> TrieKinds<'db, 'cache, L> {
479 match self.spec {
480 TrieSpec::Generic => TrieKinds::Generic(TrieDBBuilder::new(db, root).build()),
481 TrieSpec::Secure => TrieKinds::Secure(SecTrieDB::new(db, root)),
482 TrieSpec::Fat => TrieKinds::Fat(FatDB::new(db, root)),
483 }
484 }
485
486 pub fn create<'db, L: TrieLayout + 'db>(
488 &self,
489 db: &'db mut dyn HashDB<L::Hash, DBValue>,
490 root: &'db mut TrieHash<L>,
491 ) -> Box<dyn TrieMut<L> + 'db> {
492 match self.spec {
493 TrieSpec::Generic => Box::new(TrieDBMutBuilder::<L>::new(db, root).build()),
494 TrieSpec::Secure => Box::new(SecTrieDBMut::<L>::new(db, root)),
495 TrieSpec::Fat => Box::new(FatDBMut::<L>::new(db, root)),
496 }
497 }
498
499 pub fn from_existing<'db, L: TrieLayout + 'db>(
501 &self,
502 db: &'db mut dyn HashDB<L::Hash, DBValue>,
503 root: &'db mut TrieHash<L>,
504 ) -> Box<dyn TrieMut<L> + 'db> {
505 match self.spec {
506 TrieSpec::Generic => Box::new(TrieDBMutBuilder::<L>::from_existing(db, root).build()),
507 TrieSpec::Secure => Box::new(SecTrieDBMut::<L>::from_existing(db, root)),
508 TrieSpec::Fat => Box::new(FatDBMut::<L>::from_existing(db, root)),
509 }
510 }
511
512 pub fn is_fat(&self) -> bool {
514 self.spec == TrieSpec::Fat
515 }
516}
517
518pub trait TrieLayout {
522 const USE_EXTENSION: bool;
526 const ALLOW_EMPTY: bool = false;
528 const MAX_INLINE_VALUE: Option<u32>;
531
532 type Hash: Hasher;
534 type Codec: NodeCodec<HashOut = <Self::Hash as Hasher>::Out>;
536}
537
538pub trait TrieConfiguration: Sized + TrieLayout {
542 fn trie_build<DB, I, A, B>(db: &mut DB, input: I) -> <Self::Hash as Hasher>::Out
544 where
545 DB: HashDB<Self::Hash, DBValue>,
546 I: IntoIterator<Item = (A, B)>,
547 A: AsRef<[u8]> + Ord,
548 B: AsRef<[u8]>,
549 {
550 let mut cb = TrieBuilder::<Self, DB>::new(db);
551 trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
552 cb.root.unwrap_or_default()
553 }
554 fn trie_root<I, A, B>(input: I) -> <Self::Hash as Hasher>::Out
556 where
557 I: IntoIterator<Item = (A, B)>,
558 A: AsRef<[u8]> + Ord,
559 B: AsRef<[u8]>,
560 {
561 let mut cb = TrieRoot::<Self>::default();
562 trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
563 cb.root.unwrap_or_default()
564 }
565 fn trie_root_unhashed<I, A, B>(input: I) -> Vec<u8>
567 where
568 I: IntoIterator<Item = (A, B)>,
569 A: AsRef<[u8]> + Ord,
570 B: AsRef<[u8]>,
571 {
572 let mut cb = TrieRootUnhashed::<Self>::default();
573 trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
574 cb.root.unwrap_or_default()
575 }
576 fn encode_index(input: u32) -> Vec<u8> {
579 input.to_be_bytes().to_vec()
581 }
582 fn ordered_trie_root<I, A>(input: I) -> <Self::Hash as Hasher>::Out
585 where
586 I: IntoIterator<Item = A>,
587 A: AsRef<[u8]>,
588 {
589 Self::trie_root(
590 input.into_iter().enumerate().map(|(i, v)| (Self::encode_index(i as u32), v)),
591 )
592 }
593}
594
595pub type TrieHash<L> = <<L as TrieLayout>::Hash as Hasher>::Out;
597pub type CError<L> = <<L as TrieLayout>::Codec as NodeCodec>::Error;
599
600#[derive(Clone, Debug)]
602pub enum CachedValue<H> {
603 NonExisting,
605 ExistingHash(H),
607 Existing {
609 hash: H,
611 data: BytesWeak,
617 },
618}
619
620impl<H: Copy> CachedValue<H> {
621 pub fn data(&self) -> Option<Option<Bytes>> {
627 match self {
628 Self::Existing { data, .. } => Some(data.upgrade()),
629 _ => None,
630 }
631 }
632
633 pub fn hash(&self) -> Option<H> {
637 match self {
638 Self::ExistingHash(hash) | Self::Existing { hash, .. } => Some(*hash),
639 Self::NonExisting => None,
640 }
641 }
642}
643
644impl<H> From<(Bytes, H)> for CachedValue<H> {
645 fn from(value: (Bytes, H)) -> Self {
646 Self::Existing { hash: value.1, data: value.0.into() }
647 }
648}
649
650impl<H> From<H> for CachedValue<H> {
651 fn from(value: H) -> Self {
652 Self::ExistingHash(value)
653 }
654}
655
656impl<H> From<Option<(Bytes, H)>> for CachedValue<H> {
657 fn from(value: Option<(Bytes, H)>) -> Self {
658 value.map_or(Self::NonExisting, |v| Self::Existing { hash: v.1, data: v.0.into() })
659 }
660}
661
662impl<H> From<Option<H>> for CachedValue<H> {
663 fn from(value: Option<H>) -> Self {
664 value.map_or(Self::NonExisting, |v| Self::ExistingHash(v))
665 }
666}
667
668pub trait TrieCache<NC: NodeCodec> {
685 fn lookup_value_for_key(&mut self, key: &[u8]) -> Option<&CachedValue<NC::HashOut>>;
699
700 fn cache_value_for_key(&mut self, key: &[u8], value: CachedValue<NC::HashOut>);
708
709 fn get_or_insert_node(
717 &mut self,
718 hash: NC::HashOut,
719 fetch_node: &mut dyn FnMut() -> Result<NodeOwned<NC::HashOut>, NC::HashOut, NC::Error>,
720 ) -> Result<&NodeOwned<NC::HashOut>, NC::HashOut, NC::Error>;
721
722 fn get_node(&mut self, hash: &NC::HashOut) -> Option<&NodeOwned<NC::HashOut>>;
724}
725
726#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
730pub struct Bytes(rstd::sync::Arc<[u8]>);
731
732impl rstd::ops::Deref for Bytes {
733 type Target = [u8];
734
735 fn deref(&self) -> &Self::Target {
736 self.0.deref()
737 }
738}
739
740impl From<Vec<u8>> for Bytes {
741 fn from(bytes: Vec<u8>) -> Self {
742 Self(bytes.into())
743 }
744}
745
746impl From<&[u8]> for Bytes {
747 fn from(bytes: &[u8]) -> Self {
748 Self(bytes.into())
749 }
750}
751
752impl<T: AsRef<[u8]>> PartialEq<T> for Bytes {
753 fn eq(&self, other: &T) -> bool {
754 self.as_ref() == other.as_ref()
755 }
756}
757
758#[derive(Clone, Debug)]
764pub struct BytesWeak(rstd::sync::Weak<[u8]>);
765
766impl BytesWeak {
767 pub fn upgrade(&self) -> Option<Bytes> {
771 self.0.upgrade().map(Bytes)
772 }
773}
774
775impl From<Bytes> for BytesWeak {
776 fn from(bytes: Bytes) -> Self {
777 Self(rstd::sync::Arc::downgrade(&bytes.0))
778 }
779}
780
781#[derive(Clone, Debug, PartialEq, Eq)]
786pub enum MerkleValue<H> {
787 Node(Vec<u8>),
792 Hash(H),
794}