-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathmerkle.rs
More file actions
80 lines (68 loc) · 1.68 KB
/
merkle.rs
File metadata and controls
80 lines (68 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::crypto::Hash;
use crate::storage::Node;
use merkle_tree_stream::{
HashMethods, MerkleTreeStream, NodeKind, PartialNode,
};
use std::rc::Rc;
#[derive(Debug)]
struct Hasher;
impl HashMethods for Hasher {
type Node = Node;
type Hash = Hash;
fn leaf(&self, leaf: &PartialNode, _roots: &[Rc<Self::Node>]) -> Self::Hash {
match leaf.data() {
NodeKind::Leaf(data) => Hash::from_leaf(&data),
NodeKind::Parent => unreachable!(),
}
}
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() {
NodeKind::Leaf(data) => Some(data.clone()),
NodeKind::Parent => None,
};
Node {
index: partial.index(),
parent: partial.parent,
length: partial.len(),
hash: hash,
data,
}
}
}
/// Merkle Tree Stream
#[derive(Debug)]
pub struct Merkle {
stream: MerkleTreeStream<Hasher>,
nodes: Vec<Rc<Node>>,
}
impl Default for Merkle {
fn default() -> Self {
Merkle::new()
}
}
impl Merkle {
/// Create a new instance.
// TODO: figure out the right allocation size for `roots` and `nodes`.
pub fn new() -> Self {
Self {
nodes: vec![],
stream: MerkleTreeStream::new(Hasher, vec![]),
}
}
/// Access the next item.
// TODO: remove extra conversion alloc.
pub fn next(&mut self, data: &[u8]) {
self.stream.next(&data, &mut self.nodes);
}
/// Get the roots vector.
pub fn roots(&self) -> &Vec<Rc<Node>> {
self.stream.roots()
}
/// Get the nodes from the struct.
pub fn nodes(&self) -> &Vec<Rc<Node>> {
&self.nodes
}
}