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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//! Linear chain synchronizer.
//!
//! Synchronizes the linear chain when node joins the network.
//!
//! Steps are:
//! 1. Fetch blocks up to initial, trusted hash (blocks are downloaded starting from trusted hash up
//! until Genesis).
//! 2. Fetch deploys of the lowest height block.
//! 3. Execute that block.
//! 4. Repeat steps 2-3 until trusted hash is reached.
//! 5. Transition to `SyncingDescendants` state.
//! 6. Fetch child block of highest block.
//! 7. Fetch deploys of that block.
//! 8. Execute that block.
//! 9. Repeat steps 6-8 as long as there's a child in the linear chain.
//!
//! The order of "download block – download deploys – execute" block steps differ,
//! in order to increase the chances of catching up with the linear chain quicker.
//! When synchronizing linear chain up to the trusted hash we cannot execute later blocks without
//! earlier ones. When we're syncing descendants, on the other hand, we can and we want to do it
//! ASAP so that we can start participating in consensus. That's why deploy fetching and block
//! execution is interleaved. If we had downloaded the whole chain, and then deploys, and then
//! execute (as we do in the first, SynchronizeTrustedHash, phase) it would have taken more time and
//! we might miss more eras.
mod event;
use std::{convert::Infallible, fmt::Display, mem};
use datasize::DataSize;
use rand::{seq::SliceRandom, Rng};
use tracing::{error, info, trace, warn};
use super::{fetcher::FetchResult, Component};
use crate::{
effect::{
requests::{BlockExecutorRequest, BlockValidationRequest, FetcherRequest, StorageRequest},
EffectBuilder, EffectExt, EffectOptionExt, Effects,
},
types::{Block, BlockByHeight, BlockHash, BlockHeader, FinalizedBlock},
NodeRng,
};
use event::BlockByHeightResult;
pub use event::Event;
pub trait ReactorEventT<I>:
From<StorageRequest>
+ From<FetcherRequest<I, Block>>
+ From<FetcherRequest<I, BlockByHeight>>
+ From<BlockValidationRequest<BlockHeader, I>>
+ From<BlockExecutorRequest>
+ Send
{
}
impl<I, REv> ReactorEventT<I> for REv where
REv: From<StorageRequest>
+ From<FetcherRequest<I, Block>>
+ From<FetcherRequest<I, BlockByHeight>>
+ From<BlockValidationRequest<BlockHeader, I>>
+ From<BlockExecutorRequest>
+ Send
{
}
#[derive(DataSize, Debug)]
enum State {
/// No syncing of the linear chain configured.
None,
/// Synchronizing the linear chain up until trusted hash.
SyncingTrustedHash {
/// Linear chain block to start sync from.
trusted_hash: BlockHash,
/// During synchronization we might see new eras being created.
/// Track the highest height and wait until it's handled by consensus.
highest_block_seen: u64,
/// Chain of downloaded blocks from the linear chain.
/// We will `pop()` when executing blocks.
linear_chain: Vec<BlockHeader>,
/// The most recent block we started to execute. This is updated whenever we start
/// downloading deploys for the next block to be executed.
latest_block: Box<Option<BlockHeader>>,
},
/// Synchronizing the descendants of the trusted hash.
SyncingDescendants {
trusted_hash: BlockHash,
/// The most recent block we started to execute. This is updated whenever we start
/// downloading deploys for the next block to be executed.
latest_block: Box<BlockHeader>,
/// During synchronization we might see new eras being created.
/// Track the highest height and wait until it's handled by consensus.
highest_block_seen: u64,
},
/// Synchronizing done.
Done,
}
impl Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
State::None => write!(f, "None"),
State::SyncingTrustedHash { trusted_hash, .. } => {
write!(f, "SyncingTrustedHash(trusted_hash: {:?})", trusted_hash)
}
State::SyncingDescendants {
highest_block_seen, ..
} => write!(
f,
"SyncingDescendants(highest_block_seen: {})",
highest_block_seen
),
State::Done => write!(f, "Done"),
}
}
}
impl State {
fn sync_trusted_hash(trusted_hash: BlockHash) -> Self {
State::SyncingTrustedHash {
trusted_hash,
highest_block_seen: 0,
linear_chain: Vec::new(),
latest_block: Box::new(None),
}
}
fn sync_descendants(trusted_hash: BlockHash, latest_block: BlockHeader) -> Self {
State::SyncingDescendants {
trusted_hash,
latest_block: Box::new(latest_block),
highest_block_seen: 0,
}
}
fn block_downloaded(&mut self, block: &BlockHeader) {
match self {
State::None | State::Done => {}
State::SyncingTrustedHash {
highest_block_seen, ..
}
| State::SyncingDescendants {
highest_block_seen, ..
} => {
let curr_height = block.height();
if curr_height > *highest_block_seen {
*highest_block_seen = curr_height;
}
}
};
}
}
#[derive(DataSize, Debug)]
pub(crate) struct LinearChainSync<I> {
// Set of peers that we can requests block from.
peers: Vec<I>,
// Peers we have not yet requested current block from.
// NOTE: Maybe use a bitmask to decide which peers were tried?.
peers_to_try: Vec<I>,
state: State,
}
impl<I: Clone + PartialEq + 'static> LinearChainSync<I> {
pub fn new(init_hash: Option<BlockHash>) -> Self {
let state = init_hash.map_or(State::None, State::sync_trusted_hash);
LinearChainSync {
peers: Vec::new(),
peers_to_try: Vec::new(),
state,
}
}
/// Resets `peers_to_try` back to all `peers` we know of.
fn reset_peers<R: Rng + ?Sized>(&mut self, rng: &mut R) {
self.peers_to_try = self.peers.clone();
self.peers_to_try.as_mut_slice().shuffle(rng);
}
/// Returns a random peer.
fn random_peer(&mut self) -> Option<I> {
self.peers_to_try.pop()
}
// Unsafe version of `random_peer`.
// Panics if no peer is available for querying.
fn random_peer_unsafe(&mut self) -> I {
self.random_peer().expect("At least one peer available.")
}
// Peer misbehaved (returned us invalid data).
// Remove it from the set of nodes we request data from.
fn ban_peer(&mut self, peer: I) {
let index = self.peers.iter().position(|p| *p == peer);
index.map(|idx| self.peers.remove(idx));
}
/// Add new block to linear chain.
fn add_block(&mut self, block_header: BlockHeader) {
match &mut self.state {
State::None | State::Done => {}
State::SyncingTrustedHash { linear_chain, .. } => linear_chain.push(block_header),
State::SyncingDescendants { latest_block, .. } => **latest_block = block_header,
};
}
/// Returns `true` if we have finished syncing linear chain.
pub fn is_synced(&self) -> bool {
matches!(self.state, State::None | State::Done)
}
fn block_downloaded<REv>(
&mut self,
rng: &mut NodeRng,
effect_builder: EffectBuilder<REv>,
block_header: &BlockHeader,
) -> Effects<Event<I>>
where
I: Send + 'static,
REv: ReactorEventT<I>,
{
self.reset_peers(rng);
self.state.block_downloaded(block_header);
self.add_block(block_header.clone());
match &self.state {
State::None | State::Done => panic!("Downloaded block when in {} state.", self.state),
State::SyncingTrustedHash { .. } => {
if block_header.is_genesis_child() {
info!("Linear chain downloaded. Start downloading deploys.");
effect_builder
.immediately()
.event(move |_| Event::StartDownloadingDeploys)
} else {
self.fetch_next_block(effect_builder, rng, block_header)
}
}
State::SyncingDescendants { .. } => {
// When synchronizing descendants, we want to download block and execute it
// before trying to download the next block in linear chain.
self.fetch_next_block_deploys(effect_builder)
}
}
}
fn mark_done(&mut self) {
self.state = State::Done;
}
/// Handles an event indicating that a linear chain block has been executed and handled by
/// consensus component. This is a signal that we can safely continue with the next blocks,
/// without worrying about timing and/or ordering issues.
/// Returns effects that are created as a response to that event.
fn block_handled<REv>(
&mut self,
rng: &mut NodeRng,
effect_builder: EffectBuilder<REv>,
block_header: BlockHeader,
) -> Effects<Event<I>>
where
I: Send + 'static,
REv: ReactorEventT<I>,
{
let height = block_header.height();
let hash = block_header.hash();
trace!(%hash, %height, "Downloaded linear chain block.");
// Reset peers before creating new requests.
self.reset_peers(rng);
let block_height = block_header.height();
let curr_state = mem::replace(&mut self.state, State::None);
match curr_state {
State::None | State::Done => panic!("Block handled when in {:?} state.", &curr_state),
State::SyncingTrustedHash {
highest_block_seen,
trusted_hash,
ref latest_block,
..
} => {
match latest_block.as_ref() {
Some(expected) => assert_eq!(
expected, &block_header,
"Block execution result doesn't match received block."
),
None => panic!("Unexpected block execution results."),
}
if block_height == highest_block_seen {
info!(%block_height, "Finished synchronizing linear chain up until trusted hash.");
let peer = self.random_peer_unsafe();
// Kick off syncing trusted hash descendants.
self.state = State::sync_descendants(trusted_hash, block_header);
fetch_block_at_height(effect_builder, peer, block_height + 1)
} else {
self.state = curr_state;
self.fetch_next_block_deploys(effect_builder)
}
}
State::SyncingDescendants {
ref latest_block, ..
} => {
assert_eq!(
**latest_block, block_header,
"Block execution result doesn't match received block."
);
self.state = curr_state;
self.fetch_next_block(effect_builder, rng, &block_header)
}
}
}
/// Returns effects for fetching next block's deploys.
fn fetch_next_block_deploys<REv>(
&mut self,
effect_builder: EffectBuilder<REv>,
) -> Effects<Event<I>>
where
I: Send + 'static,
REv: ReactorEventT<I>,
{
let peer = self.random_peer_unsafe();
let next_block = match &mut self.state {
State::None | State::Done => {
panic!("Tried fetching next block when in {:?} state.", self.state)
}
State::SyncingTrustedHash {
linear_chain,
latest_block,
..
} => match linear_chain.pop() {
None => None,
Some(block) => {
// Update `latest_block` so that we can verify whether result of execution
// matches the expected value.
latest_block.replace(block.clone());
Some(block)
}
},
State::SyncingDescendants { latest_block, .. } => Some((**latest_block).clone()),
};
next_block.map_or_else(
|| {
warn!("Tried fetching next block deploys when there was no block.");
Effects::new()
},
|block| fetch_block_deploys(effect_builder, peer, block),
)
}
fn fetch_next_block<REv>(
&mut self,
effect_builder: EffectBuilder<REv>,
rng: &mut NodeRng,
block_header: &BlockHeader,
) -> Effects<Event<I>>
where
I: Send + 'static,
REv: ReactorEventT<I>,
{
self.reset_peers(rng);
let peer = self.random_peer_unsafe();
match self.state {
State::SyncingTrustedHash { .. } => {
let parent_hash = *block_header.parent_hash();
fetch_block_by_hash(effect_builder, peer, parent_hash)
}
State::SyncingDescendants { .. } => {
let next_height = block_header.height() + 1;
fetch_block_at_height(effect_builder, peer, next_height)
}
State::Done | State::None => {
panic!("Tried fetching block when in {:?} state", self.state)
}
}
}
fn latest_block(&self) -> Option<&BlockHeader> {
match &self.state {
State::SyncingTrustedHash { latest_block, .. } => Option::as_ref(&*latest_block),
State::SyncingDescendants { latest_block, .. } => Some(&*latest_block),
State::Done | State::None => None,
}
}
}
impl<I, REv> Component<REv> for LinearChainSync<I>
where
I: Display + Clone + Send + PartialEq + 'static,
REv: ReactorEventT<I>,
{
type Event = Event<I>;
type ConstructionError = Infallible;
fn handle_event(
&mut self,
effect_builder: EffectBuilder<REv>,
rng: &mut NodeRng,
event: Self::Event,
) -> Effects<Self::Event> {
match event {
Event::Start(init_peer) => {
match self.state {
State::None | State::Done | State::SyncingDescendants { .. } => {
// No syncing configured.
trace!("Received `Start` event when in {} state.", self.state);
Effects::new()
}
State::SyncingTrustedHash { trusted_hash, .. } => {
trace!(?trusted_hash, "Start synchronization");
// Start synchronization.
fetch_block_by_hash(effect_builder, init_peer, trusted_hash)
}
}
}
Event::GetBlockHeightResult(block_height, fetch_result) => match fetch_result {
BlockByHeightResult::Absent => match self.random_peer() {
None => {
// `block_height` not found on any of the peers.
// We have synchronized all, currently existing, descendants of trusted
// hash.
self.mark_done();
info!("Finished synchronizing descendants of the trusted hash.");
Effects::new()
}
Some(peer) => fetch_block_at_height(effect_builder, peer, block_height),
},
BlockByHeightResult::FromStorage(block) => {
// We shouldn't get invalid data from the storage.
// If we do, it's a bug.
assert_eq!(block.height(), block_height, "Block height mismatch.");
trace!(%block_height, "Linear block found in the local storage.");
// When syncing descendants of a trusted hash, we might have some of them in our
// local storage. If that's the case, just continue.
self.block_downloaded(rng, effect_builder, block.header())
}
BlockByHeightResult::FromPeer(block, peer) => {
if block.height() != block_height
|| *block.header().parent_hash() != self.latest_block().unwrap().hash()
{
warn!(
%peer,
got_height = block.height(),
expected_height = block_height,
got_parent = %block.header().parent_hash(),
expected_parent = %self.latest_block().unwrap().hash(),
"block mismatch",
);
// NOTE: Signal misbehaving validator to networking layer.
self.ban_peer(peer);
return self.handle_event(
effect_builder,
rng,
Event::GetBlockHeightResult(block_height, BlockByHeightResult::Absent),
);
}
self.block_downloaded(rng, effect_builder, block.header())
}
},
Event::GetBlockHashResult(block_hash, fetch_result) => match fetch_result {
None => match self.random_peer() {
None => {
error!(%block_hash, "Could not download linear block from any of the peers.");
panic!("Failed to download linear chain.")
}
Some(peer) => fetch_block_by_hash(effect_builder, peer, block_hash),
},
Some(FetchResult::FromStorage(block)) => {
// We shouldn't get invalid data from the storage.
// If we do, it's a bug.
assert_eq!(*block.hash(), block_hash, "Block hash mismatch.");
trace!(%block_hash, "Linear block found in the local storage.");
self.block_downloaded(rng, effect_builder, block.header())
}
Some(FetchResult::FromPeer(block, peer)) => {
if *block.hash() != block_hash {
warn!(
"Block hash mismatch. Expected {} got {} from {}.",
block_hash,
block.hash(),
peer
);
// NOTE: Signal misbehaving validator to networking layer.
// NOTE: Cannot call `self.ban_peer` with `peer` value b/c it's fixed for
// `KeyFingerprint` type and we're abstract in what peer type is.
return self.handle_event(
effect_builder,
rng,
Event::GetBlockHashResult(block_hash, None),
);
}
self.block_downloaded(rng, effect_builder, block.header())
}
},
Event::DeploysFound(block_header) => {
let block_height = block_header.height();
trace!(%block_height, "Deploys for linear chain block found.");
// Reset used peers so we can download next block with the full set.
self.reset_peers(rng);
// Execute block
let finalized_block: FinalizedBlock = (*block_header).into();
effect_builder.execute_block(finalized_block).ignore()
}
Event::DeploysNotFound(block_header) => match self.random_peer() {
None => {
let block_hash = block_header.hash();
error!(%block_hash, "Could not download deploys from linear chain block.");
panic!("Failed to download linear chain deploys.")
}
Some(peer) => fetch_block_deploys(effect_builder, peer, *block_header),
},
Event::StartDownloadingDeploys => {
// Start downloading deploys from the first block of the linear chain.
self.reset_peers(rng);
self.fetch_next_block_deploys(effect_builder)
}
Event::NewPeerConnected(peer_id) => {
trace!(%peer_id, "New peer connected");
// Add to the set of peers we can request things from.
let mut effects = Effects::new();
if self.peers.is_empty() {
// First peer connected, start downloading.
let cloned_peer_id = peer_id.clone();
effects.extend(
effect_builder
.immediately()
.event(move |_| Event::Start(cloned_peer_id)),
);
}
self.peers.push(peer_id);
effects
}
Event::BlockHandled(header) => {
let block_height = header.height();
let block_hash = header.hash();
trace!(?block_height, ?block_hash, "Block handled.");
self.block_handled(rng, effect_builder, *header)
}
}
}
}
fn fetch_block_deploys<I: Send + 'static, REv>(
effect_builder: EffectBuilder<REv>,
peer: I,
block_header: BlockHeader,
) -> Effects<Event<I>>
where
REv: ReactorEventT<I>,
{
let block_timestamp = block_header.timestamp();
effect_builder
.validate_block(peer, block_header, block_timestamp)
.event(move |(found, block_header)| {
if found {
Event::DeploysFound(Box::new(block_header))
} else {
Event::DeploysNotFound(Box::new(block_header))
}
})
}
fn fetch_block_by_hash<I: Send + 'static, REv>(
effect_builder: EffectBuilder<REv>,
peer: I,
block_hash: BlockHash,
) -> Effects<Event<I>>
where
REv: ReactorEventT<I>,
{
effect_builder.fetch_block(block_hash, peer).map_or_else(
move |value| Event::GetBlockHashResult(block_hash, Some(value)),
move || Event::GetBlockHashResult(block_hash, None),
)
}
fn fetch_block_at_height<I: Send + Clone + 'static, REv>(
effect_builder: EffectBuilder<REv>,
peer: I,
block_height: u64,
) -> Effects<Event<I>>
where
REv: ReactorEventT<I>,
{
effect_builder
.fetch_block_by_height(block_height, peer.clone())
.map_or_else(
move |fetch_result| match fetch_result {
FetchResult::FromPeer(result, _) => match *result {
BlockByHeight::Absent(ret_height) => {
warn!(
"Fetcher returned result for invalid height. Expected {}, got {}",
block_height, ret_height
);
Event::GetBlockHeightResult(block_height, BlockByHeightResult::Absent)
}
BlockByHeight::Block(block) => Event::GetBlockHeightResult(
block_height,
BlockByHeightResult::FromPeer(block, peer),
),
},
FetchResult::FromStorage(result) => match *result {
BlockByHeight::Absent(_) => {
// Fetcher should try downloading the block from a peer
// when it can't find it in the storage.
panic!("Should not return `Absent` in `FromStorage`.")
}
BlockByHeight::Block(block) => Event::GetBlockHeightResult(
block_height,
BlockByHeightResult::FromStorage(block),
),
},
},
move || Event::GetBlockHeightResult(block_height, BlockByHeightResult::Absent),
)
}