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
use std::cmp::min;
use std::io;
use hashes::Hash;
use consensus::encode::Encodable;
pub fn bitcoin_merkle_root_inline<T>(data: &mut [T]) -> T
where T: Hash + Encodable,
<T as Hash>::Engine: io::Write,
{
if data.is_empty() {
return Default::default();
}
if data.len() < 2 {
return T::from_inner(data[0].into_inner());
}
for idx in 0..((data.len() + 1) / 2) {
let idx1 = 2 * idx;
let idx2 = min(idx1 + 1, data.len() - 1);
let mut encoder = T::engine();
data[idx1].consensus_encode(&mut encoder).unwrap();
data[idx2].consensus_encode(&mut encoder).unwrap();
data[idx] = T::from_engine(encoder);
}
let half_len = data.len() / 2 + data.len() % 2;
bitcoin_merkle_root_inline(&mut data[0..half_len])
}
pub fn bitcoin_merkle_root<T, I>(mut iter: I) -> T
where T: Hash + Encodable,
<T as Hash>::Engine: io::Write,
I: ExactSizeIterator<Item = T>,
{
if iter.len() == 0 {
return Default::default();
}
if iter.len() == 1 {
return T::from_inner(iter.next().unwrap().into_inner());
}
let half_len = iter.len() / 2 + iter.len() % 2;
let mut alloc = Vec::with_capacity(half_len);
while let Some(hash1) = iter.next() {
let hash2 = iter.next().unwrap_or(hash1);
let mut encoder = T::engine();
hash1.consensus_encode(&mut encoder).unwrap();
hash2.consensus_encode(&mut encoder).unwrap();
alloc.push(T::from_engine(encoder));
}
bitcoin_merkle_root_inline(&mut alloc)
}