#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(feature = "std")]
mod rstd {
pub use std::{borrow, boxed, cmp, convert, fmt, hash, iter, marker, mem, ops, rc, result, vec};
pub use std::collections::VecDeque;
pub use std::error::Error;
}
#[cfg(not(feature = "std"))]
mod rstd {
pub use core::{borrow, convert, cmp, iter, fmt, hash, marker, mem, ops, result};
pub use alloc::{boxed, rc, vec};
pub use alloc::collections::VecDeque;
pub trait Error {}
impl<T> Error for T {}
}
#[cfg(feature = "std")]
use self::rstd::{fmt, Error};
use hash_db::MaybeDebug;
use self::rstd::{boxed::Box, vec::Vec};
pub mod node;
pub mod proof;
pub mod triedb;
pub mod triedbmut;
pub mod sectriedb;
pub mod sectriedbmut;
pub mod recorder;
mod fatdb;
mod fatdbmut;
mod iter_build;
mod iterator;
mod lookup;
mod nibble;
mod node_codec;
mod trie_codec;
pub use hash_db::{HashDB, HashDBRef, Hasher};
pub use self::triedb::{TrieDB, TrieDBIterator};
pub use self::triedbmut::{TrieDBMut, ChildReference};
pub use self::sectriedbmut::SecTrieDBMut;
pub use self::sectriedb::SecTrieDB;
pub use self::fatdb::{FatDB, FatDBIterator};
pub use self::fatdbmut::FatDBMut;
pub use self::recorder::{Recorder, Record};
pub use self::lookup::Lookup;
pub use self::nibble::{NibbleSlice, NibbleVec, nibble_ops};
pub use crate::node_codec::{NodeCodec, Partial};
pub use crate::iter_build::{trie_visit, ProcessEncodedNode,
TrieBuilder, TrieRoot, TrieRootUnhashed};
pub use crate::iterator::TrieDBNodeIterator;
pub use crate::trie_codec::{decode_compact, decode_compact_from_iter, encode_compact};
#[cfg(feature = "std")]
pub use crate::iter_build::TrieRootPrint;
pub type DBValue = Vec<u8>;
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum TrieError<T, E> {
InvalidStateRoot(T),
IncompleteDatabase(T),
ValueAtIncompleteKey(Vec<u8>, u8),
DecoderError(T, E),
InvalidHash(T, Vec<u8>),
}
#[cfg(feature = "std")]
impl<T, E> fmt::Display for TrieError<T, E> where T: MaybeDebug, E: MaybeDebug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
TrieError::InvalidStateRoot(ref root) =>
write!(f, "Invalid state root: {:?}", root),
TrieError::IncompleteDatabase(ref missing) =>
write!(f, "Database missing expected key: {:?}", missing),
TrieError::ValueAtIncompleteKey(ref bytes, ref extra) =>
write!(f, "Value found in trie at incomplete key {:?} + {:?}", bytes, extra),
TrieError::DecoderError(ref hash, ref decoder_err) => {
write!(f, "Decoding failed for hash {:?}; err: {:?}", hash, decoder_err)
}
TrieError::InvalidHash(ref hash, ref data) =>
write!(
f,
"Encoded node {:?} contains invalid hash reference with length: {}",
hash, data.len()
),
}
}
}
#[cfg(feature = "std")]
impl<T, E> Error for TrieError<T, E> where T: fmt::Debug, E: Error {}
pub type Result<T, H, E> = crate::rstd::result::Result<T, Box<TrieError<H, E>>>;
pub type TrieItem<'a, U, E> = Result<(Vec<u8>, DBValue), U, E>;
pub trait Query<H: Hasher> {
type Item;
fn decode(self, data: &[u8]) -> Self::Item;
fn record(&mut self, _hash: &H::Out, _data: &[u8], _depth: u32) {}
}
impl<'a, H: Hasher> Query<H> for &'a mut Recorder<H::Out> {
type Item = DBValue;
fn decode(self, value: &[u8]) -> DBValue { value.to_vec() }
fn record(&mut self, hash: &H::Out, data: &[u8], depth: u32) {
(&mut **self).record(hash, data, depth);
}
}
impl<F, T, H: Hasher> Query<H> for F where F: for<'a> FnOnce(&'a [u8]) -> T {
type Item = T;
fn decode(self, value: &[u8]) -> T { (self)(value) }
}
impl<'a, F, T, H: Hasher> Query<H> for (&'a mut Recorder<H::Out>, F) where F: FnOnce(&[u8]) -> T {
type Item = T;
fn decode(self, value: &[u8]) -> T { (self.1)(value) }
fn record(&mut self, hash: &H::Out, data: &[u8], depth: u32) {
self.0.record(hash, data, depth)
}
}
pub trait Trie<L: TrieLayout> {
fn root(&self) -> &TrieHash<L>;
fn is_empty(&self) -> bool { *self.root() == L::Codec::hashed_null_node() }
fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
self.get(key).map(|x| x.is_some() )
}
fn get<'a, 'key>(
&'a self,
key: &'key [u8],
) -> Result<Option<DBValue>, TrieHash<L>, CError<L>> where 'a: 'key {
self.get_with(key, |v: &[u8]| v.to_vec() )
}
fn get_with<'a, 'key, Q: Query<L::Hash>>(
&'a self,
key: &'key [u8],
query: Q
) -> Result<Option<Q::Item>, TrieHash<L>, CError<L>> where 'a: 'key;
fn iter<'a>(&'a self) -> Result<
Box<dyn TrieIterator<L, Item = TrieItem<TrieHash<L>, CError<L> >> + 'a>,
TrieHash<L>,
CError<L>
>;
}
pub trait TrieMut<L: TrieLayout> {
fn root(&mut self) -> &TrieHash<L>;
fn is_empty(&self) -> bool;
fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
self.get(key).map(|x| x.is_some())
}
fn get<'a, 'key>(
&'a self,
key: &'key [u8],
) -> Result<Option<DBValue>, TrieHash<L>, CError<L>> where 'a: 'key;
fn insert(
&mut self,
key: &[u8],
value: &[u8],
) -> Result<Option<DBValue>, TrieHash<L>, CError<L>>;
fn remove(&mut self, key: &[u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>>;
}
pub trait TrieIterator<L: TrieLayout>: Iterator {
fn seek(&mut self, key: &[u8]) -> Result<(), TrieHash<L>, CError<L>>;
}
#[derive(PartialEq, Clone)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum TrieSpec {
Generic,
Secure,
Fat,
}
impl Default for TrieSpec {
fn default() -> TrieSpec {
TrieSpec::Secure
}
}
#[derive(Default, Clone)]
pub struct TrieFactory<L: TrieLayout> {
spec: TrieSpec,
layout: L,
}
pub enum TrieKinds<'db, L: TrieLayout> {
Generic(TrieDB<'db, L>),
Secure(SecTrieDB<'db, L>),
Fat(FatDB<'db, L>),
}
macro_rules! wrapper {
($me: ident, $f_name: ident, $($param: ident),*) => {
match *$me {
TrieKinds::Generic(ref t) => t.$f_name($($param),*),
TrieKinds::Secure(ref t) => t.$f_name($($param),*),
TrieKinds::Fat(ref t) => t.$f_name($($param),*),
}
}
}
impl<'db, L: TrieLayout> Trie<L> for TrieKinds<'db, L> {
fn root(&self) -> &TrieHash<L> {
wrapper!(self, root,)
}
fn is_empty(&self) -> bool {
wrapper!(self, is_empty,)
}
fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
wrapper!(self, contains, key)
}
fn get_with<'a, 'key, Q: Query<L::Hash>>(
&'a self, key: &'key [u8],
query: Q,
) -> Result<Option<Q::Item>, TrieHash<L>, CError<L>>
where 'a: 'key
{
wrapper!(self, get_with, key, query)
}
fn iter<'a>(&'a self) -> Result<
Box<dyn TrieIterator<L, Item = TrieItem<TrieHash<L>, CError<L>>> + 'a>,
TrieHash<L>,
CError<L>,
> {
wrapper!(self, iter,)
}
}
impl<'db, L> TrieFactory<L>
where
L: TrieLayout + 'db,
{
pub fn new(spec: TrieSpec, layout: L) -> Self {
TrieFactory { spec, layout }
}
pub fn readonly(
&self,
db: &'db dyn HashDBRef<L::Hash, DBValue>,
root: &'db TrieHash<L>
) -> Result<TrieKinds<'db, L>, TrieHash<L>, CError<L>> {
match self.spec {
TrieSpec::Generic => Ok(TrieKinds::Generic(TrieDB::new(db, root)?)),
TrieSpec::Secure => Ok(TrieKinds::Secure(SecTrieDB::new(db, root)?)),
TrieSpec::Fat => Ok(TrieKinds::Fat(FatDB::new(db, root)?)),
}
}
pub fn create(
&self,
db: &'db mut dyn HashDB<L::Hash, DBValue>,
root: &'db mut TrieHash<L>,
) -> Box<dyn TrieMut<L> + 'db> {
match self.spec {
TrieSpec::Generic => Box::new(TrieDBMut::<L>::new(db, root)),
TrieSpec::Secure => Box::new(SecTrieDBMut::<L>::new(db, root)),
TrieSpec::Fat => Box::new(FatDBMut::<L>::new(db, root)),
}
}
pub fn from_existing(
&self,
db: &'db mut dyn HashDB<L::Hash, DBValue>,
root: &'db mut TrieHash<L>,
) -> Result<Box<dyn TrieMut<L> + 'db>, TrieHash<L>, CError<L>> {
match self.spec {
TrieSpec::Generic => Ok(Box::new(TrieDBMut::<L>::from_existing(db, root)?)),
TrieSpec::Secure => Ok(Box::new(SecTrieDBMut::<L>::from_existing(db, root)?)),
TrieSpec::Fat => Ok(Box::new(FatDBMut::<L>::from_existing(db, root)?)),
}
}
pub fn is_fat(&self) -> bool { self.spec == TrieSpec::Fat }
}
pub trait TrieLayout {
const USE_EXTENSION: bool;
const ALLOW_EMPTY: bool = false;
type Hash: Hasher;
type Codec: NodeCodec<HashOut=<Self::Hash as Hasher>::Out>;
}
pub trait TrieConfiguration: Sized + TrieLayout {
fn trie_build<DB, I, A, B>(db: &mut DB, input: I) -> <Self::Hash as Hasher>::Out where
DB: HashDB<Self::Hash, usize>,
I: IntoIterator<Item = (A, B)>,
A: AsRef<[u8]> + Ord,
B: AsRef<[u8]>,
{
let mut cb = TrieBuilder::new(db);
trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
cb.root.unwrap_or_default()
}
fn trie_root<I, A, B>(input: I) -> <Self::Hash as Hasher>::Out where
I: IntoIterator<Item = (A, B)>,
A: AsRef<[u8]> + Ord,
B: AsRef<[u8]>,
{
let mut cb = TrieRoot::<Self::Hash, _>::default();
trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
cb.root.unwrap_or_default()
}
fn trie_root_unhashed<I, A, B>(input: I) -> Vec<u8> where
I: IntoIterator<Item = (A, B)>,
A: AsRef<[u8]> + Ord,
B: AsRef<[u8]>,
{
let mut cb = TrieRootUnhashed::<Self::Hash>::default();
trie_visit::<Self, _, _, _, _>(input.into_iter(), &mut cb);
cb.root.unwrap_or_default()
}
fn encode_index(input: u32) -> Vec<u8> {
input.to_be_bytes().to_vec()
}
fn ordered_trie_root<I, A>(input: I) -> <Self::Hash as Hasher>::Out
where
I: IntoIterator<Item = A>,
A: AsRef<[u8]>,
{
Self::trie_root(input
.into_iter()
.enumerate()
.map(|(i, v)| (Self::encode_index(i as u32), v))
)
}
}
pub type TrieHash<L> = <<L as TrieLayout>::Hash as Hasher>::Out;
pub type CError<L> = <<L as TrieLayout>::Codec as NodeCodec>::Error;