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
use sha2::Sha256;
use super::{DigestHasher, Digester};
impl Digester for Sha256 {
fn name() -> String {
"Sha256".into()
}
}
pub type Sha256Hasher = DigestHasher<Sha256>;
#[cfg(test)]
mod tests {
use super::*;
use std::fmt;
use std::iter::FromIterator;
use crate::merkle::VecMerkleTree;
use merkletree::hash::{Algorithm, Hashable};
use super::super::{DigestDomain, Hasher};
struct HexSlice<'a>(&'a [u8]);
impl<'a> HexSlice<'a> {
fn new<T>(data: &'a T) -> HexSlice<'a>
where
T: ?Sized + AsRef<[u8]> + 'a,
{
HexSlice(data.as_ref())
}
}
impl<'a> fmt::Display for HexSlice<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let len = self.0.len();
for i in 0..len {
let byte = self.0[len - 1 - i];
write!(f, "{:x}{:x}", byte >> 4, byte & 0xf)?;
}
Ok(())
}
}
#[test]
fn test_sha256_hash() {
let mut a = <Sha256Hasher as Hasher>::Function::default();
"hello".hash(&mut a);
let h1 = a.hash();
assert_eq!(
format!("{}", HexSlice::new(h1.as_ref())),
"24988b93623304735e42a71f5c1e161b9ee2b9c52a3be8260ea3b05fba4df22c"
);
}
#[test]
fn test_sha256_node() {
let mut h1 = [0u8; 32];
let mut h2 = [0u8; 32];
let mut h3 = [0u8; 32];
h1[0] = 0x00;
h2[0] = 0x11;
h3[0] = 0x22;
let mut a = <Sha256Hasher as Hasher>::Function::default();
let h11 = h1;
let h12 = h2;
let h13 = h3;
let h21 = a.node(h11.into(), h12.into(), 0);
a.reset();
let h22 = a.node(h13.into(), h13.into(), 0);
a.reset();
let _h31 = a.node(h21.into(), h22.into(), 1);
a.reset();
let l1 = a.leaf(h1.into());
a.reset();
let l2 = a.leaf(h2.into());
a.reset();
let v: Vec<DigestDomain> = vec![h1.into(), h2.into(), h3.into()];
let v2: Vec<DigestDomain> = vec![h1.into(), h2.into()];
let t = VecMerkleTree::<<Sha256Hasher as Hasher>::Domain, <Sha256Hasher as Hasher>::Function>::from_iter(v);
let t2 = VecMerkleTree::<
<Sha256Hasher as Hasher>::Domain,
<Sha256Hasher as Hasher>::Function,
>::from_iter(v2);
assert_eq!(t2.read_at(0).as_ref(), l1.as_ref());
assert_eq!(t2.read_at(1).as_ref(), l2.as_ref());
assert_eq!(t2.read_at(2).as_ref(), h21.as_ref());
assert_eq!(
format!("{}", HexSlice::new(t.root().as_ref())),
"1c1afe57ff6efa4204cf4e17e20bf4d7f6ebf3a4c27391f93993291560107f88"
);
}
}