Skip to content

Commit

Permalink
improve debug
Browse files Browse the repository at this point in the history
  • Loading branch information
lightsing committed Sep 13, 2024
1 parent e3f163d commit e794f01
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 12 deletions.
84 changes: 76 additions & 8 deletions src/trie/node/imp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::*;
use once_cell::sync::Lazy;
use std::fmt::Debug;
use std::fmt::{Debug, Formatter};

impl From<ZkHash> for LazyNodeHash {
fn from(hash: ZkHash) -> Self {
Expand All @@ -16,14 +16,23 @@ impl From<&ZkHash> for LazyNodeHash {

impl LazyNodeHash {
/// Check if the hash value is zero.
///
/// If the hash is lazy and unresolved, `false` will be returned.
pub fn is_zero(&self) -> bool {
#[inline]
pub fn is_zero(&self) -> Option<bool> {
self.try_as_hash().map(|hash| hash.is_zero())
}

/// Check if the hash value is resolved.
#[inline]
pub fn is_resolved(&self) -> bool {
self.try_as_hash().is_some()
}

/// Try to get the hash value.
#[inline]
pub fn try_as_hash(&self) -> Option<&ZkHash> {
match self {
LazyNodeHash::Hash(hash) => hash.is_zero(),
LazyNodeHash::LazyBranch(LazyBranchHash { resolved, .. }) => {
resolved.get().map_or(false, ZkHash::is_zero)
}
LazyNodeHash::Hash(hash) => Some(hash),
LazyNodeHash::LazyBranch(LazyBranchHash { resolved, .. }) => resolved.get(),
}
}

Expand All @@ -40,6 +49,18 @@ impl LazyNodeHash {
}
}

impl Debug for LazyNodeHash {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
LazyNodeHash::Hash(hash) => write!(f, "{}", hash),
LazyNodeHash::LazyBranch(LazyBranchHash { index, resolved }) => match resolved.get() {
Some(hash) => write!(f, "{}", hash),
None => write!(f, "LazyBranch({})", index),
},
}
}
}

impl LeafNode {
/// Get the `node_key` stored in a leaf node.
#[inline]
Expand Down Expand Up @@ -126,6 +147,16 @@ impl BranchNode {
}
}

impl Debug for NodeKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
NodeKind::Empty => write!(f, "Empty"),
NodeKind::Leaf(leaf) => leaf.fmt(f),
NodeKind::Branch(branch) => branch.fmt(f),
}
}
}

impl<H: HashScheme> Node<H> {
/// Empty node.
pub fn empty() -> Node<H> {
Expand Down Expand Up @@ -313,6 +344,43 @@ impl<H: HashScheme> Node<H> {
}
}

impl<H: HashScheme> Debug for Node<H> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut debug = f.debug_struct("Node");
debug.field("hash_scheme", &std::any::type_name::<H>());
match self.node_hash.get() {
Some(hash) => debug.field("node_hash", hash),
None => debug.field("node_hash", &"Unresolved"),
};
match &self.data {
NodeKind::Empty => debug.field("node_type", &Empty),
NodeKind::Leaf(leaf) => debug
.field("node_type", &Leaf)
.field("node_key", &leaf.node_key)
.field(
"node_key_preimage",
&leaf.node_key_preimage.map(hex::encode),
)
.field(
"value_preimages",
&leaf
.value_preimages
.iter()
.map(hex::encode)
.collect::<Vec<_>>(),
)
.field("compress_flags", &leaf.compress_flags)
.field("value_hash", &leaf.value_hash),
NodeKind::Branch(branch) => debug
.field("node_type", &branch.node_type)
.field("child_left", &branch.child_left)
.field("child_right", &branch.child_right),
};

debug.finish()
}
}

impl<H: HashScheme> TryFrom<&[u8]> for Node<H> {
type Error = ParseNodeError<H::Error>;

Expand Down
6 changes: 3 additions & 3 deletions src/trie/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub struct LazyBranchHash {
}

/// A lazy hash wrapper may be resolved later.
#[derive(Clone, Debug)]
#[derive(Clone)]
pub enum LazyNodeHash {
/// A node hash that is already calculated.
Hash(ZkHash),
Expand Down Expand Up @@ -90,7 +90,7 @@ pub struct BranchNode {
}

/// Three kinds of nodes in the merkle tree.
#[derive(Clone, Debug)]
#[derive(Clone)]
pub enum NodeKind {
/// An empty node.
Empty,
Expand All @@ -107,7 +107,7 @@ pub enum NodeKind {
/// The `node_hash` is computed by [`HashScheme::hash`]:
/// - For `Leaf` node, it's computed by the hash of `Leaf` type and `[node_key, value_hash]`.
/// - For `Branch` node, it's computed by the hash of `Branch` type and `[child_left, child_right]`.
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct Node<H> {
/// nodeHash is the cache of the hash of the node to avoid recalculating
pub(crate) node_hash: Arc<OnceCell<ZkHash>>,
Expand Down
5 changes: 4 additions & 1 deletion src/trie/zktrie/imp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ impl<H: HashScheme, Db: KVDatabase, K: KeyHasher<H>> Debug for ZkTrie<H, Db, K>
f.debug_struct("ZkTrie")
.field("MAX_LEVEL", &H::TRIE_MAX_LEVELS)
.field("hash_scheme", &std::any::type_name::<H>())
.field("db", &self.db)
.field("key_hasher", &self.key_hasher)
.field("root", &self.root)
.field("is_dirty", &self.is_dirty())
.finish()
Expand Down Expand Up @@ -134,7 +136,7 @@ impl<H: HashScheme, Db: KVDatabase, K: KeyHasher<H>> ZkTrie<H, Db, K> {
#[instrument(level = "trace", skip(self, node_hash), ret)]
pub fn get_node_by_hash(&self, node_hash: impl Into<LazyNodeHash>) -> Result<Node<H>, H, Db> {
let node_hash = node_hash.into();
if node_hash.is_zero() {
if node_hash.is_zero().unwrap_or(false) {
return Ok(Node::<H>::empty());
}
trace!(node_hash = ?node_hash);
Expand Down Expand Up @@ -435,6 +437,7 @@ impl<H: HashScheme, Db: KVDatabase, K: KeyHasher<H>> ZkTrie<H, Db, K> {
}
}

#[instrument(level = "trace", skip(self), ret)]
fn resolve_commit(&mut self, node_hash: LazyNodeHash) -> Result<ZkHash, H, Db> {
match node_hash {
LazyNodeHash::Hash(node_hash) => {
Expand Down

0 comments on commit e794f01

Please sign in to comment.