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
use std::hash::Hasher;
use crate::merkle::Element;
use crate::hash::H256;
use crate::ser::FixedLength;
const LEAF: u8 = 0x00;
const INTERIOR: u8 = 0x01;
pub trait Hashable<H: Hasher> {
fn hash(&self, state: &mut H);
fn hash_slice(data: &[Self], state: &mut H)
where
Self: Sized,
{
for piece in data {
piece.hash(state);
}
}
}
pub trait Algorithm<T>: Hasher + Default
where
T: Clone + AsRef<[u8]>,
{
fn hash(&mut self) -> T;
#[inline]
fn reset(&mut self) {
*self = Self::default();
}
#[inline]
fn leaf(&mut self, leaf: T) -> T {
self.write(&[LEAF]);
self.write(leaf.as_ref());
self.hash()
}
#[inline]
fn node(&mut self, left: T, right: T, _height: usize) -> T {
self.write(&[INTERIOR]);
self.write(left.as_ref());
self.write(right.as_ref());
self.hash()
}
}
impl Element for H256 {
fn byte_len() -> usize {
H256::LEN
}
fn from_slice(bytes: &[u8]) -> Self {
if bytes.len() != Self::LEN {
panic!("invalid length {}, expected 32", bytes.len());
}
H256::from_vec(bytes)
}
fn copy_to_slice(&self, bytes: &mut [u8]) {
bytes.copy_from_slice(self.as_bytes());
}
}