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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use super::{ChunkSink, Rebuilder, SnapshotComponents};
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use engines::{EpochTransition, EpochVerifier, EthEngine};
use machine::EthereumMachine;
use snapshot::{Error, ManifestData, Progress};
use blockchain::{BlockChain, BlockChainDB, BlockProvider};
use bytes::Bytes;
use db::KeyValueDB;
use ethereum_types::{H256, U256};
use itertools::{Itertools, Position};
use rlp::{Rlp, RlpStream};
use types::{
encoded, header::Header, ids::BlockId, receipt::TypedReceipt, transaction::TypedTransaction,
BlockNumber,
};
pub struct PoaSnapshot;
impl SnapshotComponents for PoaSnapshot {
fn chunk_all(
&mut self,
chain: &BlockChain,
block_at: H256,
sink: &mut ChunkSink,
_progress: &Progress,
preferred_size: usize,
eip1559_transition: BlockNumber,
) -> Result<(), Error> {
let number = chain
.block_number(&block_at)
.ok_or_else(|| Error::InvalidStartingBlock(BlockId::Hash(block_at)))?;
let mut pending_size = 0;
let mut rlps = Vec::new();
for (_, transition) in chain
.epoch_transitions()
.take_while(|&(_, ref t)| t.block_number <= number)
{
if transition.block_number == number && transition.block_hash != block_at {
break;
}
let header = chain
.block_header_data(&transition.block_hash)
.ok_or_else(|| Error::BlockNotFound(transition.block_hash))?;
let entry = {
let mut entry_stream = RlpStream::new_list(2);
entry_stream
.append_raw(&header.into_inner(), 1)
.append(&transition.proof);
entry_stream.out()
};
let new_loaded_size = pending_size + entry.len();
pending_size = if new_loaded_size > preferred_size && !rlps.is_empty() {
write_chunk(false, &mut rlps, sink)?;
entry.len()
} else {
new_loaded_size
};
rlps.push(entry);
}
let (block, receipts) = chain
.block(&block_at)
.and_then(|b| chain.block_receipts(&block_at).map(|r| (b, r)))
.ok_or_else(|| Error::BlockNotFound(block_at))?;
let block = block.decode(eip1559_transition)?;
let parent_td = chain
.block_details(block.header.parent_hash())
.map(|d| d.total_difficulty)
.ok_or_else(|| Error::BlockNotFound(block_at))?;
rlps.push({
let mut stream = RlpStream::new_list(5);
stream.append(&block.header);
TypedTransaction::rlp_append_list(&mut stream, &block.transactions);
stream
.append_list(&block.uncles)
.append(&receipts)
.append(&parent_td);
stream.out()
});
write_chunk(true, &mut rlps, sink)?;
Ok(())
}
fn rebuilder(
&self,
chain: BlockChain,
db: Arc<dyn BlockChainDB>,
manifest: &ManifestData,
) -> Result<Box<dyn Rebuilder>, ::error::Error> {
Ok(Box::new(ChunkRebuilder {
manifest: manifest.clone(),
warp_target: None,
chain: chain,
db: db.key_value().clone(),
had_genesis: false,
unverified_firsts: Vec::new(),
last_epochs: Vec::new(),
}))
}
fn min_supported_version(&self) -> u64 {
3
}
fn current_version(&self) -> u64 {
3
}
}
fn write_chunk(last: bool, chunk_data: &mut Vec<Bytes>, sink: &mut ChunkSink) -> Result<(), Error> {
let mut stream = RlpStream::new_list(1 + chunk_data.len());
stream.append(&last);
for item in chunk_data.drain(..) {
stream.append_raw(&item, 1);
}
(sink)(stream.out().as_slice()).map_err(Into::into)
}
struct ChunkRebuilder {
manifest: ManifestData,
warp_target: Option<Header>,
chain: BlockChain,
db: Arc<dyn KeyValueDB>,
had_genesis: bool,
unverified_firsts: Vec<(Header, Bytes, H256)>,
last_epochs: Vec<(Header, Box<dyn EpochVerifier<EthereumMachine>>)>,
}
struct Verified {
epoch_transition: EpochTransition,
header: Header,
}
impl ChunkRebuilder {
fn verify_transition(
&mut self,
last_verifier: &mut Option<Box<dyn EpochVerifier<EthereumMachine>>>,
transition_rlp: Rlp,
engine: &dyn EthEngine,
) -> Result<Verified, ::error::Error> {
use engines::ConstructedVerifier;
let header =
Header::decode_rlp(&transition_rlp.at(0)?, engine.params().eip1559_transition)?;
let epoch_data: Bytes = transition_rlp.val_at(1)?;
trace!(target: "snapshot", "verifying transition to epoch at block {}", header.number());
let new_verifier = match engine.epoch_verifier(&header, &epoch_data) {
ConstructedVerifier::Trusted(v) => v,
ConstructedVerifier::Unconfirmed(v, finality_proof, hash) => {
match *last_verifier {
Some(ref last) => {
if last
.check_finality_proof(finality_proof)
.map_or(true, |hashes| !hashes.contains(&hash))
{
return Err(Error::BadEpochProof(header.number()).into());
}
}
None if header.number() != 0 => {
let idx = self
.unverified_firsts
.binary_search_by_key(&header.number(), |&(ref h, _, _)| h.number())
.unwrap_or_else(|x| x);
let entry = (header.clone(), finality_proof.to_owned(), hash);
self.unverified_firsts.insert(idx, entry);
}
None => {}
}
v
}
ConstructedVerifier::Err(e) => return Err(e),
};
*last_verifier = Some(new_verifier);
Ok(Verified {
epoch_transition: EpochTransition {
block_hash: header.hash(),
block_number: header.number(),
proof: epoch_data,
},
header: header,
})
}
}
impl Rebuilder for ChunkRebuilder {
fn feed(
&mut self,
chunk: &[u8],
engine: &dyn EthEngine,
abort_flag: &AtomicBool,
) -> Result<(), ::error::Error> {
let rlp = Rlp::new(chunk);
let is_last_chunk: bool = rlp.val_at(0)?;
let num_items = rlp.item_count()?;
let num_transitions = if is_last_chunk {
num_items - 2
} else {
num_items - 1
};
if num_transitions == 0 && !is_last_chunk {
return Err(
Error::WrongChunkFormat("Found non-last chunk without any data.".into()).into(),
);
}
let mut last_verifier = None;
let mut last_number = None;
for transition_rlp in rlp.iter().skip(1).take(num_transitions).with_position() {
if !abort_flag.load(Ordering::SeqCst) {
return Err(Error::RestorationAborted.into());
}
let (is_first, is_last) = match transition_rlp {
Position::First(_) => (true, false),
Position::Middle(_) => (false, false),
Position::Last(_) => (false, true),
Position::Only(_) => (true, true),
};
let transition_rlp = transition_rlp.into_inner();
let verified = self.verify_transition(&mut last_verifier, transition_rlp, engine)?;
if last_number.map_or(false, |num| verified.header.number() <= num) {
return Err(Error::WrongChunkFormat(
"Later epoch transition in earlier or same block.".into(),
)
.into());
}
last_number = Some(verified.header.number());
if is_first {
if verified.header.number() == 0 {
if verified.header.hash() != self.chain.genesis_hash() {
return Err(Error::WrongBlockHash(
0,
verified.header.hash(),
self.chain.genesis_hash(),
)
.into());
}
self.had_genesis = true;
}
}
if is_last {
let idx = self
.last_epochs
.binary_search_by_key(&verified.header.number(), |&(ref h, _)| h.number())
.unwrap_or_else(|x| x);
let entry = (
verified.header.clone(),
last_verifier
.take()
.expect("last_verifier always set after verify_transition; qed"),
);
self.last_epochs.insert(idx, entry);
}
let mut batch = self.db.transaction();
self.chain.insert_epoch_transition(
&mut batch,
verified.header.number(),
verified.epoch_transition,
);
self.db.write_buffered(batch);
trace!(target: "snapshot", "Verified epoch transition for epoch at block {}", verified.header.number());
}
if is_last_chunk {
use types::block::Block;
let last_rlp = rlp.at(num_items - 1)?;
let block = Block {
header: Header::decode_rlp(&last_rlp.at(0)?, engine.params().eip1559_transition)?,
transactions: TypedTransaction::decode_rlp_list(&last_rlp.at(1)?)?,
uncles: Header::decode_rlp_list(
&last_rlp.at(2)?,
engine.params().eip1559_transition,
)?,
};
let block_data = block.rlp_bytes();
let receipts = TypedReceipt::decode_rlp_list(&last_rlp.at(3)?)?;
{
let hash = block.header.hash();
let best_hash = self.manifest.block_hash;
if hash != best_hash {
return Err(
Error::WrongBlockHash(block.header.number(), best_hash, hash).into(),
);
}
}
let parent_td: U256 = last_rlp.val_at(4)?;
let mut batch = self.db.transaction();
self.chain.insert_unordered_block(
&mut batch,
encoded::Block::new(block_data),
receipts,
Some(parent_td),
true,
false,
);
self.db.write_buffered(batch);
self.warp_target = Some(block.header);
}
Ok(())
}
fn finalize(&mut self, _engine: &dyn EthEngine) -> Result<(), ::error::Error> {
if !self.had_genesis {
return Err(Error::WrongChunkFormat("No genesis transition included.".into()).into());
}
let target_header = match self.warp_target.take() {
Some(x) => x,
None => {
return Err(
Error::WrongChunkFormat("Warp target block not included.".into()).into(),
)
}
};
let mut lasts_reversed = self.last_epochs.iter().rev();
for &(ref header, ref finality_proof, hash) in self.unverified_firsts.iter().rev() {
let mut found = false;
while let Some(&(ref last_header, ref last_verifier)) = lasts_reversed.next() {
if last_header.number() < header.number() {
if last_verifier
.check_finality_proof(&finality_proof)
.map_or(true, |hashes| !hashes.contains(&hash))
{
return Err(Error::BadEpochProof(header.number()).into());
}
found = true;
break;
}
}
if !found {
return Err(Error::WrongChunkFormat("Inconsistent chunk ordering.".into()).into());
}
}
let &(ref header, ref last_epoch) = self
.last_epochs
.last()
.expect("last_epochs known to have at least one element by the check above; qed");
if header != &target_header {
last_epoch.verify_heavy(&target_header)?;
}
Ok(())
}
}