Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mpt_trie missing docs #37

Merged
merged 6 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions mpt_trie/src/debug_tools/common.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Common utilities for the debugging tools.
use std::fmt::{self, Display};

use crate::{
Expand Down Expand Up @@ -88,6 +89,7 @@ pub(super) fn get_key_piece_from_node<T: PartialTrie>(n: &Node<T>) -> Nibbles {
}

#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
/// A vector of path segments representing a path in the trie.
pub struct NodePath(pub(super) Vec<PathSegment>);

impl NodePath {
Expand Down
8 changes: 8 additions & 0 deletions mpt_trie/src/debug_tools/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ use crate::{
};

#[derive(Debug, Eq, PartialEq)]
/// The difference between two Tries, represented as the highest
/// point of a structural divergence.
pub struct TrieDiff {
/// The highest point of structural divergence.
pub latest_diff_res: Option<DiffPoint>,
// TODO: Later add a second pass for finding diffs from the bottom up (`earliest_diff_res`).
}
Expand Down Expand Up @@ -77,10 +80,15 @@ impl DiffDetectionState {
/// A point (node) between the two tries where the children differ.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DiffPoint {
/// The depth of the point in both tries.
pub depth: usize,
/// The path of the point in both tries.
pub path: NodePath,
/// The node key in both tries.
pub key: Nibbles,
/// The node info in the first trie.
pub a_info: NodeInfo,
/// The node info in the second trie.
pub b_info: NodeInfo,
}

Expand Down
4 changes: 4 additions & 0 deletions mpt_trie/src/debug_tools/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ impl Default for DebugQueryParams {
}

#[derive(Debug, Default)]
/// A wrapper for `DebugQueryParams`.
pub struct DebugQueryParamsBuilder {
params: DebugQueryParams,
}
Expand All @@ -67,6 +68,7 @@ impl DebugQueryParamsBuilder {
self
}

/// Build a new debug query for a given key.
4l0n50 marked this conversation as resolved.
Show resolved Hide resolved
pub fn build<K: Into<Nibbles>>(self, k: K) -> DebugQuery {
DebugQuery {
k: k.into(),
Expand Down Expand Up @@ -153,6 +155,8 @@ fn count_non_empty_branch_children_from_mask(mask: u16) -> usize {
}

#[derive(Clone, Debug)]
/// The result of a debug query contains information
/// of the path used for searching for a key in the trie.
pub struct DebugQueryOutput {
k: Nibbles,
node_path: NodePath,
Expand Down
6 changes: 6 additions & 0 deletions mpt_trie/src/debug_tools/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use num_traits::ToPrimitive;
use crate::partial_trie::{Node, PartialTrie};

#[derive(Debug, Default)]
/// Statistics for a given trie, consisting of node count aggregated
/// by time, lowest depth and average depth of leaf of and hash nodes.
4l0n50 marked this conversation as resolved.
Show resolved Hide resolved
pub struct TrieStats {
name: Option<String>,
counts: NodeCounts,
Expand All @@ -31,6 +33,7 @@ impl Display for TrieStats {
}

impl TrieStats {
/// Compare with the statistics of another trie.
4l0n50 marked this conversation as resolved.
Show resolved Hide resolved
pub fn compare(&self, other: &Self) -> TrieComparison {
TrieComparison {
node_comp: self.counts.compare(&other.counts),
Expand Down Expand Up @@ -240,10 +243,13 @@ impl DepthStats {
}
}

/// Returns trie statistics consisting of node type counts as well as depth
/// statistics.
pub fn get_trie_stats<T: PartialTrie>(trie: &T) -> TrieStats {
get_trie_stats_common(trie, None)
}

/// Returns trie statistics with a given name.
pub fn get_trie_stats_with_name<T: PartialTrie>(trie: &T, name: String) -> TrieStats {
get_trie_stats_common(trie, Some(name))
}
Expand Down
3 changes: 3 additions & 0 deletions mpt_trie/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
//! hash of the node it replaces.

#![allow(incomplete_features)]
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]

pub mod nibbles;
pub mod partial_trie;
Expand Down
14 changes: 14 additions & 0 deletions mpt_trie/src/nibbles.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//! Define [`Nibbles`] and how to convert bytes, hex prefix encodings and
//! strings into nibbles.

use std::mem::size_of;
use std::{
fmt::{self, Debug},
Expand All @@ -18,7 +21,9 @@ use uint::FromHexError;
use crate::utils::{create_mask_of_1s, is_even};

// Use a whole byte for a Nibble just for convenience
/// A Nibble has 4 bits and is stored as `u8``.
4l0n50 marked this conversation as resolved.
Show resolved Hide resolved
pub type Nibble = u8;
/// Used for the internal representation of a sequence of nibbles.
pub type NibblesIntern = U512;

/// Because there are two different ways to convert to `Nibbles`, we don't want
Expand Down Expand Up @@ -46,25 +51,32 @@ pub trait ToNibbles {
}

#[derive(Debug, Error)]
/// Errors encountered when converting from `Bytes` to `Nibbles`.
pub enum BytesToNibblesError {
#[error("Tried constructing `Nibbles` from a zero byte slice")]
/// The size is zero.
ZeroSizedKey,

#[error("Tried constructing `Nibbles` from a byte slice with more than 33 bytes (len: {0})")]
/// The slice is too large.
TooManyBytes(usize),
}

#[derive(Debug, Error)]
/// Errors encountered when converting to hex prefix encoding to nibbles.
pub enum FromHexPrefixError {
#[error("Tried to convert a hex prefix byte string into `Nibbles` with invalid flags at the start: {0:#04b}")]
/// The hex prefix encoding flag is invalid.
InvalidFlags(Nibble),

#[error("Tried to convert a hex prefix byte string into `Nibbles` that was longer than 64 bytes: (length: {0}, bytes: {1})")]
/// The hex prefix encoding is too large.
TooLong(String, usize),
}

#[derive(Debug, Error)]
#[error(transparent)]
/// An error encountered when converting a string to a sequence of nibbles.
pub struct StrToNibblesError(#[from] FromHexError);

/// The default conversion to nibbles will be to be precise down to the
Expand Down Expand Up @@ -723,6 +735,7 @@ impl Nibbles {

// TODO: Make not terrible at some point... Consider moving away from `U256`
// internally?
/// Returns the nibbles btyes in big-endian format.
4l0n50 marked this conversation as resolved.
Show resolved Hide resolved
pub fn bytes_be(&self) -> Vec<u8> {
let mut byte_buf = [0; 64];
self.packed.to_big_endian(&mut byte_buf);
Expand Down Expand Up @@ -753,6 +766,7 @@ impl Nibbles {
}

// TODO: REMOVE BEFORE NEXT CRATE VERSION! THIS IS A TEMP HACK!
/// Converto to u256 returning an error if not possible.
4l0n50 marked this conversation as resolved.
Show resolved Hide resolved
pub fn try_into_u256(&self) -> Result<U256, String> {
match self.count <= 64 {
false => Err(format!(
Expand Down
13 changes: 12 additions & 1 deletion mpt_trie/src/partial_trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub trait PartialTrie:
+ TrieNodeIntern
+ Sized
{
/// Creates a new partial trie from a node.
fn new(n: Node<Self>) -> Self;

/// Inserts a node into the trie.
Expand Down Expand Up @@ -111,6 +112,7 @@ pub trait PartialTrie:
/// Part of the trait that is not really part of the public interface but
/// implementor of other node types still need to implement.
pub trait TrieNodeIntern {
/// Returns the hash of the rlp encoding of self.
fn hash_intern(&self) -> EncodedNode;
}

Expand All @@ -134,17 +136,26 @@ where
Hash(H256),
/// A branch node, which consists of 16 children and an optional value.
Branch {
/// A slice containing the 16 children of this branch node.
children: [WrappedNode<T>; 16],
/// The payload of this node.
value: Vec<u8>,
},
/// An extension node, which consists of a list of nibbles and a single
/// child.
Extension {
/// The path of this extension.
nibbles: Nibbles,
/// The child of this extension node.
child: WrappedNode<T>,
},
/// A leaf node, which consists of a list of nibbles and a value.
Leaf { nibbles: Nibbles, value: Vec<u8> },
Leaf {
/// The path of this leaf node.
nibbles: Nibbles,
/// The payload of this node
value: Vec<u8>,
},
}

impl<N: PartialTrie> Eq for Node<N> {}
Expand Down
2 changes: 2 additions & 0 deletions mpt_trie/src/trie_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ struct BranchStackEntry<N> {
}

#[derive(Debug)]
/// An iterator that ranges over all the leafs and hash nodes
/// of the trie, in lexicographic order.
pub struct PartialTrieIter<N> {
curr_key_after_last_branch: Nibbles,
trie_stack: Vec<IterStackEntry<N>>,
Expand Down
2 changes: 2 additions & 0 deletions mpt_trie/src/trie_subsets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ use crate::{
utils::{bytes_to_h256, TrieNodeType},
};

/// The output type of trie_subset operations.
pub type SubsetTrieResult<T> = Result<T, SubsetTrieError>;

/// Errors that may occur when creating a subset [`PartialTrie`].
#[derive(Debug, Error)]
pub enum SubsetTrieError {
#[error("Tried to mark nodes in a tracked trie for a key that does not exist! (Key: {0}, trie: {1})")]
/// The key does not exist in the trie.
UnexpectedKey(Nibbles, String),
}

Expand Down