-
Notifications
You must be signed in to change notification settings - Fork 232
/
mod.rs
852 lines (799 loc) · 32.3 KB
/
mod.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
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! CKB node has initial block download phase (IBD mode) like Bitcoin:
//! <https://btcinformation.org/en/glossary/initial-block-download>
//!
//! When CKB node is in IBD mode, it will respond `packed::InIBD` to `GetHeaders` and `GetBlocks` requests
//!
//! And CKB has a headers-first synchronization style like Bitcoin:
//! <https://btcinformation.org/en/glossary/headers-first-sync>
//!
mod block_fetcher;
mod block_process;
mod get_blocks_process;
mod get_headers_process;
mod headers_process;
mod in_ibd_process;
pub(crate) use self::block_fetcher::BlockFetcher;
pub(crate) use self::block_process::BlockProcess;
pub(crate) use self::get_blocks_process::GetBlocksProcess;
pub(crate) use self::get_headers_process::GetHeadersProcess;
pub(crate) use self::headers_process::HeadersProcess;
pub(crate) use self::in_ibd_process::InIBDProcess;
use crate::block_status::BlockStatus;
use crate::types::{HeaderIndexView, HeadersSyncController, IBDState, Peers, SyncShared};
use crate::utils::{metric_ckb_message_bytes, send_message_to, MetricDirection};
use crate::{Status, StatusCode};
use ckb_chain::chain::ChainController;
use ckb_channel as channel;
use ckb_channel::{select, Receiver};
use ckb_constant::sync::{
BAD_MESSAGE_BAN_TIME, CHAIN_SYNC_TIMEOUT, EVICTION_HEADERS_RESPONSE_TIME,
INIT_BLOCKS_IN_TRANSIT_PER_PEER, MAX_TIP_AGE,
};
use ckb_error::Error as CKBError;
use ckb_logger::{debug, error, info, trace, warn};
use ckb_network::{
async_trait, bytes::Bytes, tokio, CKBProtocolContext, CKBProtocolHandler, PeerIndex,
ServiceControl, SupportProtocols,
};
use ckb_stop_handler::{new_crossbeam_exit_rx, register_thread};
use ckb_systemtime::unix_time_as_millis;
use ckb_types::{
core::{self, BlockNumber},
packed::{self, Byte32},
prelude::*,
};
use std::{
collections::HashSet,
sync::{atomic::Ordering, Arc},
time::{Duration, Instant},
};
pub const SEND_GET_HEADERS_TOKEN: u64 = 0;
pub const IBD_BLOCK_FETCH_TOKEN: u64 = 1;
pub const NOT_IBD_BLOCK_FETCH_TOKEN: u64 = 2;
pub const TIMEOUT_EVICTION_TOKEN: u64 = 3;
pub const NO_PEER_CHECK_TOKEN: u64 = 255;
const SYNC_NOTIFY_INTERVAL: Duration = Duration::from_secs(1);
const IBD_BLOCK_FETCH_INTERVAL: Duration = Duration::from_millis(40);
const NOT_IBD_BLOCK_FETCH_INTERVAL: Duration = Duration::from_millis(200);
#[derive(Copy, Clone)]
enum CanStart {
Ready,
MinWorkNotReach,
AssumeValidNotFound,
}
// TODO: Consider converting this enum to a struct since it only has one item
//
// struct FetchCMD {
// peers: Vec<PeerIndex>,
// ibd_state: IBDState,
// }
//
enum FetchCMD {
Fetch((Vec<PeerIndex>, IBDState)),
}
struct BlockFetchCMD {
sync: Synchronizer,
p2p_control: ServiceControl,
recv: channel::Receiver<FetchCMD>,
can_start: CanStart,
number: BlockNumber,
}
impl BlockFetchCMD {
fn process_fetch_cmd(&mut self, cmd: FetchCMD) {
match cmd {
FetchCMD::Fetch((peers, state)) => match self.can_start() {
CanStart::Ready => {
for peer in peers {
if let Some(fetch) = BlockFetcher::new(&self.sync, peer, state).fetch() {
for item in fetch {
BlockFetchCMD::send_getblocks(item, &self.p2p_control, peer);
}
}
}
}
CanStart::MinWorkNotReach => {
let best_known = self.sync.shared.state().shared_best_header_ref();
let number = best_known.number();
if number != self.number && (number - self.number) % 10000 == 0 {
self.number = number;
info!(
"best known header number: {}, total difficulty: {:#x}, \
require min header number on 500_000, min total difficulty: {:#x}, \
then start to download block",
number,
best_known.total_difficulty(),
self.sync.shared.state().min_chain_work()
);
}
}
CanStart::AssumeValidNotFound => {
let state = self.sync.shared.state();
let best_known = state.shared_best_header_ref();
let number = best_known.number();
let assume_valid_target: Byte32 = state
.assume_valid_target()
.as_ref()
.map(Pack::pack)
.expect("assume valid target must exist");
if number != self.number && (number - self.number) % 10000 == 0 {
self.number = number;
info!(
"best known header number: {}, hash: {:#?}, \
can't find assume valid target temporarily, hash: {:#?} \
please wait",
number,
best_known.hash(),
assume_valid_target
);
}
}
},
}
}
fn run(&mut self, stop_signal: Receiver<()>) {
loop {
select! {
recv(self.recv) -> msg => {
if let Ok(cmd) = msg {
self.process_fetch_cmd(cmd)
}
}
recv(stop_signal) -> _ => {
debug!("thread BlockDownload received exit signal, exit now");
return;
}
}
}
}
fn can_start(&mut self) -> CanStart {
if let CanStart::Ready = self.can_start {
return self.can_start;
}
let state = self.sync.shared.state();
let min_work_reach = |flag: &mut CanStart| {
if state.min_chain_work_ready() {
*flag = CanStart::AssumeValidNotFound;
}
};
let assume_valid_target_find = |flag: &mut CanStart| {
let mut assume_valid_target = state.assume_valid_target();
if let Some(ref target) = *assume_valid_target {
match state.header_map().get(&target.pack()) {
Some(header) => {
*flag = CanStart::Ready;
// Blocks that are no longer in the scope of ibd must be forced to verify
if unix_time_as_millis().saturating_sub(header.timestamp()) < MAX_TIP_AGE {
assume_valid_target.take();
}
}
None => {
// Best known already not in the scope of ibd, it means target is invalid
if unix_time_as_millis()
.saturating_sub(state.shared_best_header_ref().timestamp())
< MAX_TIP_AGE
{
*flag = CanStart::Ready;
assume_valid_target.take();
}
}
}
} else {
*flag = CanStart::Ready;
}
};
match self.can_start {
CanStart::Ready => self.can_start,
CanStart::MinWorkNotReach => {
min_work_reach(&mut self.can_start);
if let CanStart::AssumeValidNotFound = self.can_start {
assume_valid_target_find(&mut self.can_start);
}
self.can_start
}
CanStart::AssumeValidNotFound => {
assume_valid_target_find(&mut self.can_start);
self.can_start
}
}
}
fn send_getblocks(v_fetch: Vec<packed::Byte32>, nc: &ServiceControl, peer: PeerIndex) {
let content = packed::GetBlocks::new_builder()
.block_hashes(v_fetch.clone().pack())
.build();
let message = packed::SyncMessage::new_builder().set(content).build();
debug!("send_getblocks len={:?} to peer={}", v_fetch.len(), peer);
if let Err(err) = nc.send_message_to(
peer,
SupportProtocols::Sync.protocol_id(),
message.as_bytes(),
) {
debug!("synchronizer send GetBlocks error: {:?}", err);
}
}
}
/// Sync protocol handle
#[derive(Clone)]
pub struct Synchronizer {
pub(crate) chain: ChainController,
/// Sync shared state
pub shared: Arc<SyncShared>,
fetch_channel: Option<channel::Sender<FetchCMD>>,
}
impl Synchronizer {
/// Init sync protocol handle
///
/// This is a runtime sync protocol shared state, and any Sync protocol messages will be processed and forwarded by it
pub fn new(chain: ChainController, shared: Arc<SyncShared>) -> Synchronizer {
Synchronizer {
chain,
shared,
fetch_channel: None,
}
}
/// Get shared state
pub fn shared(&self) -> &Arc<SyncShared> {
&self.shared
}
fn try_process(
&self,
nc: &dyn CKBProtocolContext,
peer: PeerIndex,
message: packed::SyncMessageUnionReader<'_>,
) -> Status {
match message {
packed::SyncMessageUnionReader::GetHeaders(reader) => {
GetHeadersProcess::new(reader, self, peer, nc).execute()
}
packed::SyncMessageUnionReader::SendHeaders(reader) => {
HeadersProcess::new(reader, self, peer, nc).execute()
}
packed::SyncMessageUnionReader::GetBlocks(reader) => {
GetBlocksProcess::new(reader, self, peer, nc).execute()
}
packed::SyncMessageUnionReader::SendBlock(reader) => {
if reader.check_data() {
BlockProcess::new(reader, self, peer).execute()
} else {
StatusCode::ProtocolMessageIsMalformed.with_context("SendBlock is invalid")
}
}
packed::SyncMessageUnionReader::InIBD(_) => InIBDProcess::new(self, peer, nc).execute(),
_ => StatusCode::ProtocolMessageIsMalformed.with_context("unexpected sync message"),
}
}
fn process(
&self,
nc: &dyn CKBProtocolContext,
peer: PeerIndex,
message: packed::SyncMessageUnionReader<'_>,
) {
let item_name = message.item_name();
let item_bytes = message.as_slice().len() as u64;
let status = self.try_process(nc, peer, message);
metric_ckb_message_bytes(
MetricDirection::In,
&SupportProtocols::Sync.name(),
item_name,
Some(status.code()),
item_bytes,
);
if let Some(ban_time) = status.should_ban() {
error!(
"receive {} from {}, ban {:?} for {}",
item_name, peer, ban_time, status
);
nc.ban_peer(peer, ban_time, status.to_string());
} else if status.should_warn() {
warn!("receive {} from {}, {}", item_name, peer, status);
} else if !status.is_ok() {
debug!("receive {} from {}, {}", item_name, peer, status);
}
}
/// Get peers info
pub fn peers(&self) -> &Peers {
self.shared().state().peers()
}
fn better_tip_header(&self) -> HeaderIndexView {
let (header, total_difficulty) = {
let active_chain = self.shared.active_chain();
(
active_chain.tip_header(),
active_chain.total_difficulty().to_owned(),
)
};
let best_known = self.shared.state().shared_best_header();
// is_better_chain
if total_difficulty > *best_known.total_difficulty() {
(header, total_difficulty).into()
} else {
best_known
}
}
/// Process a new block sync from other peer
//TODO: process block which we don't request
pub fn process_new_block(&self, block: core::BlockView) -> Result<bool, CKBError> {
let block_hash = block.hash();
let status = self.shared.active_chain().get_block_status(&block_hash);
// NOTE: Filtering `BLOCK_STORED` but not `BLOCK_RECEIVED`, is for avoiding
// stopping synchronization even when orphan_pool maintains dirty items by bugs.
if status.contains(BlockStatus::BLOCK_STORED) {
debug!("block {} already stored", block_hash);
Ok(false)
} else if status.contains(BlockStatus::HEADER_VALID) {
self.shared.insert_new_block(&self.chain, Arc::new(block))
} else {
debug!(
"Synchronizer process_new_block unexpected status {:?} {}",
status, block_hash,
);
// TODO which error should we return?
Ok(false)
}
}
/// Get blocks to fetch
pub fn get_blocks_to_fetch(
&self,
peer: PeerIndex,
ibd: IBDState,
) -> Option<Vec<Vec<packed::Byte32>>> {
BlockFetcher::new(self, peer, ibd).fetch()
}
pub(crate) fn on_connected(&self, nc: &dyn CKBProtocolContext, peer: PeerIndex) {
let pid = SupportProtocols::Sync.protocol_id();
let (is_outbound, is_whitelist, is_2023edition) = nc
.get_peer(peer)
.map(|peer| {
(
peer.is_outbound(),
peer.is_whitelist,
peer.protocols.get(&pid).map(|v| v == "3").unwrap_or(false),
)
})
.unwrap_or((false, false, false));
self.peers()
.sync_connected(peer, is_outbound, is_whitelist, is_2023edition);
}
/// Regularly check and eject some nodes that do not respond in time
// - If at timeout their best known block now has more work than our tip
// when the timeout was set, then either reset the timeout or clear it
// (after comparing against our current tip's work)
// - If at timeout their best known block still has less work than our
// tip did when the timeout was set, then send a getheaders message,
// and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
// If their best known block is still behind when that new timeout is
// reached, disconnect.
pub fn eviction(&self, nc: &dyn CKBProtocolContext) {
let active_chain = self.shared.active_chain();
let mut eviction = Vec::new();
let better_tip_header = self.better_tip_header();
for mut kv_pair in self.peers().state.iter_mut() {
let (peer, state) = kv_pair.pair_mut();
let now = unix_time_as_millis();
if let Some(ref mut controller) = state.headers_sync_controller {
let better_tip_ts = better_tip_header.timestamp();
if let Some(is_timeout) = controller.is_timeout(better_tip_ts, now) {
if is_timeout {
eviction.push(*peer);
continue;
}
} else {
active_chain.send_getheaders_to_peer(
nc,
*peer,
better_tip_header.number_and_hash(),
);
}
}
// On ibd, node should only have one peer to sync headers, and it's state can control by
// headers_sync_controller.
//
// The header sync of other nodes does not matter in the ibd phase, and parallel synchronization
// can be enabled by unknown list, so there is no need to repeatedly download headers with
// multiple nodes at the same time.
if active_chain.is_initial_block_download() {
continue;
}
if state.peer_flags.is_outbound {
let best_known_header = state.best_known_header.as_ref();
let (tip_header, local_total_difficulty) = {
(
active_chain.tip_header().to_owned(),
active_chain.total_difficulty().to_owned(),
)
};
if best_known_header
.map(|header_index| header_index.total_difficulty().clone())
.unwrap_or_default()
>= local_total_difficulty
{
if state.chain_sync.timeout != 0 {
state.chain_sync.timeout = 0;
state.chain_sync.work_header = None;
state.chain_sync.total_difficulty = None;
state.chain_sync.sent_getheaders = false;
}
} else if state.chain_sync.timeout == 0
|| (best_known_header.is_some()
&& best_known_header
.map(|header_index| header_index.total_difficulty().clone())
>= state.chain_sync.total_difficulty)
{
// Our best block known by this peer is behind our tip, and we're either noticing
// that for the first time, OR this peer was able to catch up to some earlier point
// where we checked against our tip.
// Either way, set a new timeout based on current tip.
state.chain_sync.timeout = now + CHAIN_SYNC_TIMEOUT;
state.chain_sync.work_header = Some(tip_header);
state.chain_sync.total_difficulty = Some(local_total_difficulty);
state.chain_sync.sent_getheaders = false;
} else if state.chain_sync.timeout > 0 && now > state.chain_sync.timeout {
// No evidence yet that our peer has synced to a chain with work equal to that
// of our tip, when we first detected it was behind. Send a single getheaders
// message to give the peer a chance to update us.
if state.chain_sync.sent_getheaders {
if state.peer_flags.is_protect || state.peer_flags.is_whitelist {
if state.sync_started() {
self.shared().state().suspend_sync(state);
}
} else {
eviction.push(*peer);
}
} else {
state.chain_sync.sent_getheaders = true;
state.chain_sync.timeout = now + EVICTION_HEADERS_RESPONSE_TIME;
active_chain.send_getheaders_to_peer(
nc,
*peer,
state
.chain_sync
.work_header
.as_ref()
.expect("work_header be assigned")
.into(),
);
}
}
}
}
for peer in eviction {
info!("timeout eviction peer={}", peer);
if let Err(err) = nc.disconnect(peer, "sync timeout eviction") {
debug!("synchronizer disconnect error: {:?}", err);
}
}
}
fn start_sync_headers(&self, nc: &dyn CKBProtocolContext) {
let now = unix_time_as_millis();
let active_chain = self.shared.active_chain();
let ibd = active_chain.is_initial_block_download();
let peers: Vec<PeerIndex> = self
.peers()
.state
.iter()
.filter(|kv_pair| kv_pair.value().can_start_sync(now, ibd))
.map(|kv_pair| *kv_pair.key())
.collect();
if peers.is_empty() {
return;
}
let tip = self.better_tip_header();
for peer in peers {
// Only sync with 1 peer if we're in IBD
if self
.shared()
.state()
.n_sync_started()
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| {
if ibd && x != 0 {
None
} else {
Some(x + 1)
}
})
.is_err()
{
break;
}
{
if let Some(mut peer_state) = self.peers().state.get_mut(&peer) {
peer_state.start_sync(HeadersSyncController::from_header(&tip));
}
}
debug!("start sync peer={}", peer);
active_chain.send_getheaders_to_peer(nc, peer, tip.number_and_hash());
}
}
fn get_peers_to_fetch(
&self,
ibd: IBDState,
disconnect_list: &HashSet<PeerIndex>,
) -> Vec<PeerIndex> {
trace!("poll find_blocks_to_fetch select peers");
let state = &self
.shared
.state()
.read_inflight_blocks()
.download_schedulers;
let mut peers: Vec<PeerIndex> = self
.peers()
.state
.iter()
.filter(|kv_pair| {
let (id, state) = kv_pair.pair();
if disconnect_list.contains(id) {
return false;
};
match ibd {
IBDState::In => {
state.peer_flags.is_outbound
|| state.peer_flags.is_whitelist
|| state.peer_flags.is_protect
}
IBDState::Out => state.started_or_tip_synced(),
}
})
.map(|kv_pair| *kv_pair.key())
.collect();
peers.sort_by_key(|id| {
::std::cmp::Reverse(
state
.get(id)
.map_or(INIT_BLOCKS_IN_TRANSIT_PER_PEER, |d| d.task_count()),
)
});
peers
}
fn find_blocks_to_fetch(&mut self, nc: &dyn CKBProtocolContext, ibd: IBDState) {
let tip = self.shared.active_chain().tip_number();
let disconnect_list = {
let mut list = self.shared().state().write_inflight_blocks().prune(tip);
if let IBDState::In = ibd {
// best known < tip and in IBD state, and unknown list is empty,
// these node can be disconnect
list.extend(
self.shared
.state()
.peers()
.get_best_known_less_than_tip_and_unknown_empty(tip),
)
};
list
};
for peer in disconnect_list.iter() {
// It is not forbidden to evict protected nodes:
// - First of all, this node is not designated by the user for protection,
// but is connected randomly. It does not represent the will of the user
// - Secondly, in the synchronization phase, the nodes with zero download tasks are
// retained, apart from reducing the download efficiency, there is no benefit.
if self
.peers()
.get_flag(*peer)
.map(|flag| flag.is_whitelist)
.unwrap_or(false)
{
continue;
}
if let Err(err) = nc.disconnect(*peer, "sync disconnect") {
debug!("synchronizer disconnect error: {:?}", err);
}
}
// fetch use a lot of cpu time, especially in ibd state
// so, the fetch function use another thread
match nc.p2p_control() {
Some(raw) => match self.fetch_channel {
Some(ref sender) => {
if !sender.is_full() {
let peers = self.get_peers_to_fetch(ibd, &disconnect_list);
let _ignore = sender.try_send(FetchCMD::Fetch((peers, ibd)));
}
}
None => {
let p2p_control = raw.clone();
let sync = self.clone();
let (sender, recv) = channel::bounded(2);
let peers = self.get_peers_to_fetch(ibd, &disconnect_list);
sender.send(FetchCMD::Fetch((peers, ibd))).unwrap();
self.fetch_channel = Some(sender);
let thread = ::std::thread::Builder::new();
let number = self.shared.state().shared_best_header_ref().number();
const THREAD_NAME: &str = "BlockDownload";
let blockdownload_jh = thread
.name(THREAD_NAME.into())
.spawn(move || {
let stop_signal = new_crossbeam_exit_rx();
BlockFetchCMD {
sync,
p2p_control,
recv,
number,
can_start: CanStart::MinWorkNotReach,
}
.run(stop_signal);
})
.expect("download thread can't start");
register_thread(THREAD_NAME, blockdownload_jh);
}
},
None => {
for peer in self.get_peers_to_fetch(ibd, &disconnect_list) {
if let Some(fetch) = self.get_blocks_to_fetch(peer, ibd) {
for item in fetch {
self.send_getblocks(item, nc, peer);
}
}
}
}
}
}
fn send_getblocks(
&self,
v_fetch: Vec<packed::Byte32>,
nc: &dyn CKBProtocolContext,
peer: PeerIndex,
) {
let content = packed::GetBlocks::new_builder()
.block_hashes(v_fetch.clone().pack())
.build();
let message = packed::SyncMessage::new_builder().set(content).build();
debug!("send_getblocks len={:?} to peer={}", v_fetch.len(), peer);
let _status = send_message_to(nc, peer, &message);
}
}
#[async_trait]
impl CKBProtocolHandler for Synchronizer {
async fn init(&mut self, nc: Arc<dyn CKBProtocolContext + Sync>) {
// NOTE: 100ms is what bitcoin use.
nc.set_notify(SYNC_NOTIFY_INTERVAL, SEND_GET_HEADERS_TOKEN)
.await
.expect("set_notify at init is ok");
nc.set_notify(SYNC_NOTIFY_INTERVAL, TIMEOUT_EVICTION_TOKEN)
.await
.expect("set_notify at init is ok");
nc.set_notify(IBD_BLOCK_FETCH_INTERVAL, IBD_BLOCK_FETCH_TOKEN)
.await
.expect("set_notify at init is ok");
nc.set_notify(NOT_IBD_BLOCK_FETCH_INTERVAL, NOT_IBD_BLOCK_FETCH_TOKEN)
.await
.expect("set_notify at init is ok");
nc.set_notify(Duration::from_secs(2), NO_PEER_CHECK_TOKEN)
.await
.expect("set_notify at init is ok");
}
async fn received(
&mut self,
nc: Arc<dyn CKBProtocolContext + Sync>,
peer_index: PeerIndex,
data: Bytes,
) {
let msg = match packed::SyncMessageReader::from_compatible_slice(&data) {
Ok(msg) => {
let item = msg.to_enum();
if let packed::SyncMessageUnionReader::SendBlock(ref reader) = item {
if reader.count_extra_fields() > 1 {
info!(
"Peer {} sends us a malformed message: \
too many fields in SendBlock",
peer_index
);
nc.ban_peer(
peer_index,
BAD_MESSAGE_BAN_TIME,
String::from(
"send us a malformed message: \
too many fields in SendBlock",
),
);
return;
} else {
item
}
} else {
match packed::SyncMessageReader::from_slice(&data) {
Ok(msg) => msg.to_enum(),
_ => {
info!(
"Peer {} sends us a malformed message: \
too many fields",
peer_index
);
nc.ban_peer(
peer_index,
BAD_MESSAGE_BAN_TIME,
String::from(
"send us a malformed message: \
too many fields",
),
);
return;
}
}
}
}
_ => {
info!("Peer {} sends us a malformed message", peer_index);
nc.ban_peer(
peer_index,
BAD_MESSAGE_BAN_TIME,
String::from("send us a malformed message"),
);
return;
}
};
debug!("received msg {} from {}", msg.item_name(), peer_index);
#[cfg(feature = "with_sentry")]
{
let sentry_hub = sentry::Hub::current();
let _scope_guard = sentry_hub.push_scope();
sentry_hub.configure_scope(|scope| {
scope.set_tag("p2p.protocol", "synchronizer");
scope.set_tag("p2p.message", msg.item_name());
});
}
let start_time = Instant::now();
tokio::task::block_in_place(|| self.process(nc.as_ref(), peer_index, msg));
debug!(
"process message={}, peer={}, cost={:?}",
msg.item_name(),
peer_index,
Instant::now().saturating_duration_since(start_time),
);
}
async fn connected(
&mut self,
nc: Arc<dyn CKBProtocolContext + Sync>,
peer_index: PeerIndex,
_version: &str,
) {
info!("SyncProtocol.connected peer={}", peer_index);
self.on_connected(nc.as_ref(), peer_index);
}
async fn disconnected(
&mut self,
_nc: Arc<dyn CKBProtocolContext + Sync>,
peer_index: PeerIndex,
) {
let sync_state = self.shared().state();
sync_state.disconnected(peer_index);
}
async fn notify(&mut self, nc: Arc<dyn CKBProtocolContext + Sync>, token: u64) {
if !self.peers().state.is_empty() {
let start_time = Instant::now();
trace!("start notify token={}", token);
match token {
SEND_GET_HEADERS_TOKEN => {
self.start_sync_headers(nc.as_ref());
}
IBD_BLOCK_FETCH_TOKEN => {
if self.shared.active_chain().is_initial_block_download() {
self.find_blocks_to_fetch(nc.as_ref(), IBDState::In);
} else {
{
self.shared.state().write_inflight_blocks().adjustment = false;
}
self.shared.state().peers().clear_unknown_list();
if nc.remove_notify(IBD_BLOCK_FETCH_TOKEN).await.is_err() {
trace!("remove ibd block fetch fail");
}
}
}
NOT_IBD_BLOCK_FETCH_TOKEN => {
if !self.shared.active_chain().is_initial_block_download() {
self.find_blocks_to_fetch(nc.as_ref(), IBDState::Out);
}
}
TIMEOUT_EVICTION_TOKEN => {
self.eviction(nc.as_ref());
}
// Here is just for NO_PEER_CHECK_TOKEN token, only handle it when there is no peer.
_ => {}
}
trace!(
"finished notify token={} cost={:?}",
token,
Instant::now().saturating_duration_since(start_time)
);
} else if token == NO_PEER_CHECK_TOKEN {
debug!("no peers connected");
}
}
}