use crate::crypto::Hash;
use crate::storage::Node;
use merkle_tree_stream::{HashMethods, MerkleTreeStream, PartialNode};
use std::rc::Rc;
#[derive(Debug)]
struct H;
impl HashMethods for H {
type Node = Node;
type Hash = Hash;
fn leaf(&self, leaf: &PartialNode, _roots: &[Rc<Self::Node>]) -> Self::Hash {
let data = leaf.as_ref().unwrap(); Hash::from_leaf(&data)
}
fn parent(&self, left: &Self::Node, right: &Self::Node) -> Self::Hash {
Hash::from_hashes(left, right)
}
fn node(&self, partial: &PartialNode, hash: Self::Hash) -> Self::Node {
let data = match partial.data() {
Some(data) => Some(data.clone()),
None => None,
};
Node {
index: partial.index(),
parent: partial.parent,
length: partial.len(),
hash: hash.as_bytes().into(),
data,
}
}
}
#[derive(Debug)]
pub struct Merkle {
stream: MerkleTreeStream<H>,
nodes: Vec<Rc<Node>>,
}
impl Default for Merkle {
fn default() -> Self {
Merkle::new()
}
}
impl Merkle {
pub fn new() -> Self {
Self {
nodes: vec![],
stream: MerkleTreeStream::new(H, vec![]),
}
}
pub fn next(&mut self, data: &[u8]) {
self.stream.next(&data, &mut self.nodes);
}
pub fn roots(&self) -> &Vec<Rc<Node>> {
self.stream.roots()
}
pub fn nodes(&self) -> &Vec<Rc<Node>> {
&self.nodes
}
}