-
Notifications
You must be signed in to change notification settings - Fork 33
/
test_accumulate_headers.rs
193 lines (175 loc) · 5.34 KB
/
test_accumulate_headers.rs
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
use super::new_blake2b;
use crate::{leaf_index_to_pos, util::MemStore, MMRStoreReadOps, Merge, MerkleProof, Result, MMR};
use bytes::{Bytes, BytesMut};
use std::fmt;
#[derive(Clone)]
struct Header {
number: u64,
parent_hash: Bytes,
difficulty: u64,
// MMR root
chain_root: Bytes,
}
impl Header {
fn default() -> Self {
Header {
number: 0,
parent_hash: vec![0; 32].into(),
difficulty: 0,
chain_root: vec![0; 32].into(),
}
}
fn hash(&self) -> Bytes {
let mut hasher = new_blake2b();
let mut hash = [0u8; 32];
hasher.update(&self.number.to_le_bytes());
hasher.update(&self.parent_hash);
hasher.update(&self.difficulty.to_le_bytes());
hasher.update(&self.chain_root);
hasher.finalize(&mut hash);
hash.to_vec().into()
}
}
#[derive(Eq, PartialEq, Clone, Default)]
struct HashWithTD {
hash: Bytes,
td: u64,
}
impl HashWithTD {
fn serialize(&self) -> Bytes {
let mut data = BytesMut::from(self.hash.as_ref());
data.extend(&self.td.to_le_bytes());
data.into()
}
fn deserialize(mut data: Bytes) -> Self {
assert_eq!(data.len(), 40);
let mut td_bytes = [0u8; 8];
td_bytes.copy_from_slice(&data[32..]);
let td = u64::from_le_bytes(td_bytes);
data.truncate(32);
HashWithTD { hash: data, td }
}
}
impl fmt::Debug for HashWithTD {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"HashWithTD {{ hash: {}, td: {} }}",
faster_hex::hex_string(&self.hash),
self.td
)
}
}
struct MergeHashWithTD;
impl Merge for MergeHashWithTD {
type Item = HashWithTD;
fn merge(lhs: &Self::Item, rhs: &Self::Item) -> Result<Self::Item> {
let mut hasher = new_blake2b();
let mut hash = [0u8; 32];
hasher.update(&lhs.serialize());
hasher.update(&rhs.serialize());
hasher.finalize(&mut hash);
let td = lhs.td + rhs.td;
Ok(HashWithTD {
hash: hash.to_vec().into(),
td,
})
}
}
struct Prover {
headers: Vec<(Header, u64)>,
positions: Vec<u64>,
store: MemStore<HashWithTD>,
}
impl Prover {
fn new() -> Prover {
let store = MemStore::default();
Prover {
headers: Vec::new(),
positions: Vec::new(),
store,
}
}
fn gen_blocks(&mut self, count: u64) -> Result<()> {
let mut mmr = MMR::<_, MergeHashWithTD, _>::new(self.positions.len() as u64, &self.store);
// get previous element
let mut previous = if let Some(pos) = self.positions.last() {
mmr.store().get_elem(*pos)?.expect("exists")
} else {
let genesis = Header::default();
let previous = HashWithTD {
hash: genesis.hash(),
td: genesis.difficulty,
};
self.headers.push((genesis, previous.td));
let pos = mmr.push(previous.clone())?;
self.positions.push(pos);
previous
};
let last_number = self.headers.last().unwrap().0.number;
for i in (last_number + 1)..=(last_number + count) {
let block = Header {
number: i,
parent_hash: previous.hash.clone(),
difficulty: i,
chain_root: mmr.get_root()?.serialize(),
};
previous = HashWithTD {
hash: block.hash(),
td: block.difficulty,
};
let pos = mmr.push(previous.clone())?;
self.positions.push(pos);
self.headers.push((block, previous.td));
}
mmr.commit()
}
fn get_header(&self, number: u64) -> (Header, u64) {
self.headers[number as usize].clone()
}
// generate proof that headers are in same chain
fn gen_proof(
&mut self,
number: u64,
later_number: u64,
) -> Result<MerkleProof<HashWithTD, MergeHashWithTD>> {
assert!(number < later_number);
let pos = self.positions[number as usize];
let later_pos = self.positions[later_number as usize];
let mmr = MMR::new(later_pos, &self.store);
assert_eq!(
mmr.get_root()?.serialize(),
self.headers[later_number as usize].0.chain_root
);
mmr.gen_proof(vec![pos])
}
fn get_pos(&self, number: u64) -> u64 {
self.positions[number as usize]
}
}
#[test]
fn test_insert_header() {
let mut prover = Prover::new();
prover.gen_blocks(30).expect("gen blocks");
let h1 = 11;
let h2 = 19;
// get headers from prover
let prove_elem = {
let (header, td) = prover.get_header(h1);
HashWithTD {
hash: header.hash(),
td,
}
};
let root = {
let (later_header, _later_td) = prover.get_header(h2);
HashWithTD::deserialize(later_header.chain_root)
};
// gen proof, blocks are in the same chain
let proof = prover.gen_proof(h1, h2).expect("gen proof");
let pos = leaf_index_to_pos(h1);
assert_eq!(pos, prover.get_pos(h1));
assert_eq!(prove_elem, (&prover.store).get_elem(pos).unwrap().unwrap());
let result = proof.verify(root, vec![(pos, prove_elem)]).expect("verify");
assert!(result);
}