mt_rs/
node.rs

1//! Contains node definitions for Merkle trees, including leaf and internal node structures.
2
3/// Enum representing the type of the node child.
4#[derive(Debug, Clone)]
5pub enum NodeChildType {
6    /// Left child
7    Left,
8    /// Right child
9    Right,
10}
11
12/// Enum representing the type of a Merkle tree node.
13#[derive(Clone)]
14pub enum NodeStatus {
15    /// A leaf node that contains no children.
16    Leaf,
17    /// An internal node that has two children.
18    Internal(Box<Node>, Box<Node>),
19}
20
21impl NodeStatus {
22    /// Returns a reference to the left child if the node is internal.
23    pub fn left(&self) -> Option<&Node> {
24        match self {
25            NodeStatus::Leaf => None,
26            NodeStatus::Internal(l, _) => Some(l),
27        }
28    }
29
30    /// Returns a reference to the right child if the node is internal.
31    pub fn right(&self) -> Option<&Node> {
32        match self {
33            NodeStatus::Leaf => None,
34            NodeStatus::Internal(_, r) => Some(r),
35        }
36    }
37}
38
39/// Represents a node in a Merkle tree, either leaf or internal.
40#[derive(Clone)]
41pub struct Node {
42    /// Hash value stored at the node.
43    hash: String,
44    /// Type of the node: leaf or internal.
45    status: NodeStatus,
46}
47
48impl Node {
49    /// Constructs a new leaf node from input data.
50    ///
51    /// # Arguments
52    ///
53    /// * `hasher` - A reference to a hashing strategy.
54    pub fn new_leaf(hash: String) -> Self {
55        Self {
56            hash,
57            status: NodeStatus::Leaf,
58        }
59    }
60
61    /// Constructs a new internal node from two child nodes.
62    ///
63    /// # Arguments
64    ///
65    /// * `hash` - An hash value for the following node.
66    /// * `left` - Left child node.
67    /// * `right` - Right child node.
68    ///
69    /// # Behavior
70    ///
71    /// The internal node hash is computed as the hash of the concatenated children's hashes.
72    pub fn new_internal(hash: String, left: Node, right: Node) -> Self {
73        Self {
74            hash,
75            status: NodeStatus::Internal(Box::new(left), Box::new(right)),
76        }
77    }
78
79    /// Returns a reference to the hash of the node.
80    pub fn hash(&self) -> &str {
81        &self.hash
82    }
83
84    /// Returns a reference to the node's type (leaf or internal).
85    pub fn status(&self) -> &NodeStatus {
86        &self.status
87    }
88}