From 04891bbcaac75e887d57844548b61141cb6ebc07 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Fri, 13 Jun 2025 13:29:29 +0200 Subject: Init --- src/merkle/node.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/merkle/node.rs (limited to 'src/merkle/node.rs') diff --git a/src/merkle/node.rs b/src/merkle/node.rs new file mode 100644 index 0000000..9d552cd --- /dev/null +++ b/src/merkle/node.rs @@ -0,0 +1,56 @@ +use crate::hasher::Hasher; + +#[derive(Debug, Clone)] +enum NodeType { + Leaf, + Internal(Box, Box), +} + +impl NodeType { + pub fn left(&self) -> Option<&Box> { + match self { + NodeType::Leaf => None, + NodeType::Internal(l, _) => Some(l), + } + } + + pub fn right(&self) -> Option<&Box> { + match self { + NodeType::Leaf => None, + NodeType::Internal(_, r) => Some(r), + } + } +} + +#[derive(Debug, Clone)] +pub struct Node { + hash: String, + kind: NodeType, +} + +impl Node { + pub fn new_leaf(hasher: &dyn Hasher, data: T) -> Self { + let hash = hasher.hash(&data.to_string()); + Self { + hash, + kind: NodeType::Leaf, + } + } + + pub fn new_internal(hasher: &dyn Hasher, left: Node, right: Node) -> Self { + let combined = format!("{}{}", left.hash, right.hash); + let hash = hasher.hash(&combined); + Self { + hash, + kind: NodeType::Internal(Box::new(left), Box::new(right)), + } + } + + pub fn hash(&self) -> &str { + &self.hash + } + + pub fn kind(&self) -> &NodeType { + &self.kind + } +} -- cgit v1.2.3-71-g8e6c