summaryrefslogtreecommitdiffstats
path: root/src/merkle/node.rs
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2025-06-13 11:29:29 +0000
committerSanto Cariotti <santo@dcariotti.me>2025-06-13 11:29:29 +0000
commit04891bbcaac75e887d57844548b61141cb6ebc07 (patch)
tree9be7b87519c95ab1bd1d03895042b67e79b127a0 /src/merkle/node.rs
Init
Diffstat (limited to 'src/merkle/node.rs')
-rw-r--r--src/merkle/node.rs56
1 files changed, 56 insertions, 0 deletions
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<Node>, Box<Node>),
+}
+
+impl NodeType {
+ pub fn left(&self) -> Option<&Box<Node>> {
+ match self {
+ NodeType::Leaf => None,
+ NodeType::Internal(l, _) => Some(l),
+ }
+ }
+
+ pub fn right(&self) -> Option<&Box<Node>> {
+ 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<T: ToString>(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
+ }
+}