diff options
Diffstat (limited to 'src/merkle/node.rs')
| -rw-r--r-- | src/merkle/node.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/src/merkle/node.rs b/src/merkle/node.rs index 19cf8d4..0e5e904 100644 --- a/src/merkle/node.rs +++ b/src/merkle/node.rs @@ -1,12 +1,18 @@ +//! Contains node definitions for Merkle trees, including leaf and internal node structures. + use crate::hasher::Hasher; +/// Enum representing the type of a Merkle tree node. #[derive(Debug, Clone)] pub enum NodeType { + /// A leaf node that contains no children. Leaf, + /// An internal node that has two children. Internal(Box<Node>, Box<Node>), } impl NodeType { + /// Returns a reference to the left child if the node is internal. pub fn left(&self) -> Option<&Node> { match self { NodeType::Leaf => None, @@ -14,6 +20,7 @@ impl NodeType { } } + /// Returns a reference to the right child if the node is internal. pub fn right(&self) -> Option<&Node> { match self { NodeType::Leaf => None, @@ -22,13 +29,22 @@ impl NodeType { } } +/// Represents a node in a Merkle tree, either leaf or internal. #[derive(Debug, Clone)] pub struct Node { + /// Hash value stored at the node. hash: String, + /// Type of the node: leaf or internal. kind: NodeType, } impl Node { + /// Constructs a new leaf node from input data. + /// + /// # Arguments + /// + /// * `hasher` - A reference to a hashing strategy. + /// * `data` - The data to be hashed and stored as a leaf. pub fn new_leaf<T: ToString>(hasher: &dyn Hasher, data: T) -> Self { let hash = hasher.hash(&data.to_string()); Self { @@ -37,6 +53,17 @@ impl Node { } } + /// Constructs a new internal node from two child nodes. + /// + /// # Arguments + /// + /// * `hasher` - A reference to a hashing strategy. + /// * `left` - Left child node. + /// * `right` - Right child node. + /// + /// # Behavior + /// + /// The internal node hash is computed as the hash of the concatenated children's hashes. pub fn new_internal(hasher: &dyn Hasher, left: Node, right: Node) -> Self { let combined = format!("{}{}", left.hash, right.hash); let hash = hasher.hash(&combined); @@ -46,10 +73,12 @@ impl Node { } } + /// Returns a reference to the hash of the node. pub fn hash(&self) -> &str { &self.hash } + /// Returns a reference to the node's type (leaf or internal). pub fn kind(&self) -> &NodeType { &self.kind } |
