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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
|
//! Provides the MerkleTree structure and associated methods for creating and interacting
//! with binary Merkle trees using custom hashers.
use crate::{hasher::Hasher, node::Node};
/// A binary Merkle tree implementation.
///
/// Merkle trees are hash-based data structures used for secure and efficient data verification.
/// Each leaf node contains the hash of a data item, and each internal node contains the hash
/// of the concatenation of its children's hashes.
pub struct MerkleTree {
/// Leaf nodes at the base of the tree (may include a duplicate for even pairing).
leaves: Vec<Node>,
/// Height of the tree (number of levels including root).
height: usize,
/// Root node of the Merkle tree.
root: Node,
}
impl MerkleTree {
/// Creates a new `MerkleTree` from a collection of data items and a hash function.
///
/// # Arguments
///
/// * `hasher` - A reference to an implementation of the `Hasher` trait.
/// * `data` - A vector of values to be converted into leaf nodes.
///
/// # Panics
///
/// Panics if the `data` vector is empty.
///
/// # Notes
///
/// If the number of leaf nodes is odd, the last node is duplicated to ensure all internal
/// nodes have exactly two children.
pub fn new<I, T, H>(hasher: H, data: I) -> Self
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
H: Hasher + 'static,
{
let owned_data: Vec<T> = data.into_iter().collect();
let data_slices: Vec<&[u8]> = owned_data.iter().map(|item| item.as_ref()).collect();
assert!(
!data_slices.is_empty(),
"Merkle Tree requires at least one element"
);
let mut leaves: Vec<Node> = data_slices
.iter()
.map(|data| Node::new_leaf(data, hasher.hash(data)))
.collect();
if leaves.len() % 2 != 0 {
leaves.push(leaves[leaves.len() - 1].clone());
}
Self::build(hasher, leaves)
}
/// Constructs the internal nodes of the tree from the leaves upward and computes the root.
fn build<H>(hasher: H, mut nodes: Vec<Node>) -> Self
where
H: Hasher + 'static,
{
let leaves = nodes.clone();
let mut height = 0;
while nodes.len() > 1 {
if nodes.len() % 2 != 0 {
// duplicate last node to make the count even
nodes.push(nodes[nodes.len() - 1].clone());
}
let mut next_level = Vec::new();
for pair in nodes.chunks(2) {
let (left, right) = (pair[0].clone(), pair[1].clone());
let mut buffer = Vec::<u8>::new();
buffer.extend_from_slice(left.hash().as_bytes());
buffer.extend_from_slice(right.hash().as_bytes());
let hash = hasher.hash(&buffer);
next_level.push(Node::new_internal(&buffer, hash, left, right));
}
nodes = next_level;
height += 1;
}
let root = nodes.remove(0);
MerkleTree {
leaves,
height: height + 1,
root,
}
}
/// Returns the height (number of levels) of the tree.
pub fn height(&self) -> usize {
self.height
}
/// Returns true if the tree has no leaves (should never happen if `new()` was used).
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the number of leaf nodes in the tree.
pub fn len(&self) -> usize {
self.leaves.len()
}
/// Returns the root node of the tree.
pub fn root(&self) -> Node {
self.root.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hasher::*;
use crate::proof::*;
#[test]
fn test_merkle_tree_with_default_hasher() {
let data = &["hello".as_bytes(), "world".as_bytes()];
let tree = MerkleTree::new(DummyHasher, data);
assert_eq!(tree.height(), 2);
assert_eq!(tree.root().hash(), "0xc0ff3");
}
#[test]
#[cfg(feature = "sha256")]
fn test_merkle_tree_hashing() {
let data = &["hello".as_bytes(), "world".as_bytes()];
let tree = MerkleTree::new(SHA256Hasher::new(), data);
assert_eq!(tree.height(), 2);
assert_eq!(
tree.root().hash(),
"15e178b71fae8849ee562c9cc0d7ea322fba6cd495411329d47234479167cc8b"
);
}
#[test]
#[cfg(feature = "sha256")]
fn test_merkle_tree_single_leaf() {
let data = &["hello".as_bytes()];
let tree = MerkleTree::new(SHA256Hasher::new(), data);
assert_eq!(tree.height(), 2);
assert_eq!(tree.len(), 2);
assert_eq!(
tree.root().hash(),
"286d189fda11bf4e906b6973a173009f47ede16532f1bae726223f8ee155d73b"
);
}
#[test]
#[cfg(feature = "sha256")]
fn test_merkle_tree_with_10_elements() {
let inputs = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
let data: Vec<&[u8]> = inputs.iter().map(|s| s.as_bytes()).collect();
let tree = MerkleTree::new(SHA256Hasher::new(), &data);
assert_eq!(tree.height(), 5); // 10 elements padded to 16 → log2(16) + 1 = 5
// You can print the root hash if you're unsure what it should be:
println!("Merkle root hash: {}", tree.root().hash());
// If you know the expected hash, use:
assert_eq!(
tree.root().hash(),
"9da1ff0dfa79217bdbea9ec96407b1e693646cc493f64059fa27182a37cadf94"
);
}
#[test]
fn test_proof_generation_and_verification_dummy() {
let hasher = DummyHasher;
let data = vec!["a", "b", "c", "d"];
let tree = MerkleTree::new(hasher.clone(), data.clone());
let proofer = DefaultProofer::new(hasher.clone(), tree.leaves.clone());
for (index, item) in data.iter().enumerate() {
let proof = proofer.generate(index).unwrap();
assert!(proofer.verify(&proof, item, tree.root().hash(), &hasher));
}
}
#[test]
#[cfg(feature = "sha256")]
fn test_proof_generation_and_verification_sha256() {
let hasher = SHA256Hasher::new();
let data = vec!["a", "b", "c", "d"];
let tree = MerkleTree::new(hasher.clone(), data.clone());
let proofer = DefaultProofer::new(hasher.clone(), tree.leaves.clone());
for (index, item) in data.iter().enumerate() {
let proof = proofer.generate(index).unwrap();
assert!(proofer.verify(&proof, item, tree.root().hash(), &hasher));
}
}
}
|