use sha2::{Digest, Sha256};
use std::fmt;
#[derive(Clone)]
pub enum MerkleNode {
Leaf {
data: Vec<u8>,
hash: Vec<u8>,
},
Branch {
left: Box<MerkleNode>,
right: Box<MerkleNode>,
hash: Vec<u8>,
},
}
impl MerkleNode {
pub fn new_leaf(data: Vec<u8>) -> Self {
let hash = Sha256::digest(&data).to_vec();
MerkleNode::Leaf { data, hash }
}
pub fn new_branch(left: MerkleNode, right: MerkleNode) -> Self {
let mut hasher = Sha256::new();
hasher.update(left.hash());
hasher.update(right.hash());
let hash = hasher.finalize().to_vec();
MerkleNode::Branch {
left: Box::new(left),
right: Box::new(right),
hash,
}
}
pub fn hash(&self) -> Vec<u8> {
match self {
MerkleNode::Leaf { hash, .. } => hash.clone(),
MerkleNode::Branch { hash, .. } => hash.clone(),
}
}
}
impl fmt::Debug for MerkleNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MerkleNode::Leaf { data, hash } => {
write!(
f,
"Leaf {{ data: {:?}, hash: {} }}",
String::from_utf8_lossy(data),
hex::encode(hash)
)
}
MerkleNode::Branch { left, right, hash } => {
write!(
f,
"Branch {{ hash: {}, left: {:?}, right: {:?} }}",
hex::encode(hash),
left,
right
)
}
}
}
}