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, 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
91pub type DBValue = Vec<u8>;
93
94#[derive(PartialEq, Eq, Clone, Debug)]
99pub enum TrieError<T, E> {
100 InvalidStateRoot(T),
102 IncompleteDatabase(T),
104 ValueAtIncompleteKey(Vec<u8>, u8),
108 DecoderError(T, E),
110 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
148pub type Result<T, H, E> = crate::rstd::result::Result<T, Box<TrieError<H, E>>>;
151
152pub type TrieItem<U, E> = Result<(Vec<u8>, DBValue), U, E>;
154
155pub type TrieKeyItem<U, E> = Result<Vec<u8>, U, E>;
157
158pub trait Query<H: Hasher> {
160 type Item;
162
163 fn decode(self, data: &[u8]) -> Self::Item;
165}
166
167#[cfg_attr(feature = "std", derive(Debug))]
173pub enum TrieAccess<'a, H> {
174 NodeOwned { hash: H, node_owned: &'a NodeOwned<H> },
176 EncodedNode { hash: H, encoded_node: rstd::borrow::Cow<'a, [u8]> },
178 Value { hash: H, value: rstd::borrow::Cow<'a, [u8]>, full_key: &'a [u8] },
184 InlineValue { full_key: &'a [u8] },
191 Hash { full_key: &'a [u8] },
195 NonExisting { full_key: &'a [u8] },
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum RecordedForKey {
204 Value,
213 Hash,
224 None,
228}
229
230impl RecordedForKey {
231 pub fn is_none(&self) -> bool {
233 matches!(self, Self::None)
234 }
235}
236
237pub trait TrieRecorder<H> {
242 fn record<'a>(&mut self, access: TrieAccess<'a, H>);
247
248 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
264pub trait Trie<L: TrieLayout> {
266 fn root(&self) -> &TrieHash<L>;
268
269 fn is_empty(&self) -> bool {
271 *self.root() == L::Codec::hashed_null_node()
272 }
273
274 fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
276 self.get(key).map(|x| x.is_some())
277 }
278
279 fn get_hash(&self, key: &[u8]) -> Result<Option<TrieHash<L>>, TrieHash<L>, CError<L>>;
281
282 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 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 fn lookup_first_descendant(
302 &self,
303 key: &[u8],
304 ) -> Result<Option<MerkleValue<TrieHash<L>>>, TrieHash<L>, CError<L>>;
305
306 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 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
325pub trait TrieMut<L: TrieLayout> {
327 fn root(&mut self) -> &TrieHash<L>;
329
330 fn is_empty(&self) -> bool;
332
333 fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
335 self.get(key).map(|x| x.is_some())
336 }
337
338 fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>>
340 where
341 'a: 'key;
342
343 fn insert(
346 &mut self,
347 key: &[u8],
348 value: &[u8],
349 ) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>>;
350
351 fn remove(&mut self, key: &[u8]) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>>;
354}
355
356pub trait TrieIterator<L: TrieLayout>: Iterator {
358 fn seek(&mut self, key: &[u8]) -> Result<(), TrieHash<L>, CError<L>>;
360}
361
362pub trait TrieDoubleEndedIterator<L: TrieLayout>: TrieIterator<L> + DoubleEndedIterator {}
364
365#[derive(PartialEq, Clone)]
367#[cfg_attr(feature = "std", derive(Debug))]
368pub enum TrieSpec {
369 Generic,
371 Secure,
373 Fat,
375}
376
377impl Default for TrieSpec {
378 fn default() -> TrieSpec {
379 TrieSpec::Secure
380 }
381}
382
383#[derive(Default, Clone)]
385pub struct TrieFactory {
386 spec: TrieSpec,
387}
388
389pub enum TrieKinds<'db, 'cache, L: TrieLayout> {
392 Generic(TrieDB<'db, 'cache, L>),
394 Secure(SecTrieDB<'db, 'cache, L>),
396 Fat(FatDB<'db, 'cache, L>),
398}
399
400macro_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 pub fn new(spec: TrieSpec) -> Self {
467 TrieFactory { spec }
468 }
469
470 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 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 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 pub fn is_fat(&self) -> bool {
511 self.spec == TrieSpec::Fat
512 }
513}
514
515pub trait TrieLayout {
519 const USE_EXTENSION: bool;
523 const ALLOW_EMPTY: bool = false;
525 const MAX_INLINE_VALUE: Option<u32>;
528
529 type Hash: Hasher;
531 type Codec: NodeCodec<HashOut = <Self::Hash as Hasher>::Out>;
533}
534
535pub trait TrieConfiguration: Sized + TrieLayout {
539 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 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 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 fn encode_index(input: u32) -> Vec<u8> {
576 input.to_be_bytes().to_vec()
578 }
579 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
592pub type TrieHash<L> = <<L as TrieLayout>::Hash as Hasher>::Out;
594pub type CError<L> = <<L as TrieLayout>::Codec as NodeCodec>::Error;
596
597#[derive(Clone, Debug)]
599pub enum CachedValue<H> {
600 NonExisting,
602 ExistingHash(H),
604 Existing {
606 hash: H,
608 data: BytesWeak,
614 },
615}
616
617impl<H: Copy> CachedValue<H> {
618 pub fn data(&self) -> Option<Option<Bytes>> {
624 match self {
625 Self::Existing { data, .. } => Some(data.upgrade()),
626 _ => None,
627 }
628 }
629
630 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
665pub trait TrieCache<NC: NodeCodec> {
682 fn lookup_value_for_key(&mut self, key: &[u8]) -> Option<&CachedValue<NC::HashOut>>;
696
697 fn cache_value_for_key(&mut self, key: &[u8], value: CachedValue<NC::HashOut>);
705
706 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 fn get_node(&mut self, hash: &NC::HashOut) -> Option<&NodeOwned<NC::HashOut>>;
721}
722
723#[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#[derive(Clone, Debug)]
761pub struct BytesWeak(rstd::sync::Weak<[u8]>);
762
763impl BytesWeak {
764 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#[derive(Clone, Debug, PartialEq, Eq)]
783pub enum MerkleValue<H> {
784 Node(Vec<u8>),
789 Hash(H),
791}