/
client_actor.rs
2066 lines (1902 loc) · 88.4 KB
/
client_actor.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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Client actor orchestrates Client and facilitates network connection.
use crate::client::{Client, EPOCH_START_INFO_BLOCKS};
use crate::info::{
display_sync_status, get_validator_epoch_stats, InfoHelper, ValidatorInfoHelper,
};
use crate::metrics::PARTIAL_ENCODED_CHUNK_RESPONSE_DELAY;
use crate::sync::{StateSync, StateSyncResult};
use crate::{metrics, StatusResponse};
use actix::dev::SendError;
use actix::{Actor, Addr, Arbiter, AsyncContext, Context, Handler, Message};
use actix_rt::ArbiterHandle;
use borsh::BorshSerialize;
use chrono::DateTime;
use near_chain::chain::{
do_apply_chunks, ApplyStatePartsRequest, ApplyStatePartsResponse, BlockCatchUpRequest,
BlockCatchUpResponse, StateSplitRequest, StateSplitResponse,
};
use near_chain::test_utils::format_hash;
#[cfg(feature = "test_features")]
use near_chain::ChainStoreAccess;
use near_chain::{
byzantine_assert, near_chain_primitives, Block, BlockHeader, BlockProcessingArtifact,
ChainGenesis, DoneApplyChunkCallback, Provenance, RuntimeAdapter,
};
use near_chain_configs::ClientConfig;
use near_chunks::client::ShardsManagerResponse;
use near_chunks::logic::cares_about_shard_this_or_next_epoch;
use near_client_primitives::types::{
Error, GetNetworkInfo, NetworkInfoResponse, ShardSyncDownload, ShardSyncStatus, Status,
StatusError, StatusSyncInfo, SyncStatus,
};
use near_network::types::ReasonForBan;
use near_network::types::{
NetworkClientMessages, NetworkClientResponses, NetworkInfo, NetworkRequests,
PeerManagerAdapter, PeerManagerMessageRequest,
};
use near_o11y::{OpenTelemetrySpanExt, WithSpanContext};
use near_performance_metrics;
use near_performance_metrics_macros::perf;
use near_primitives::block_header::ApprovalType;
use near_primitives::epoch_manager::RngSeed;
use near_primitives::hash::CryptoHash;
use near_primitives::network::{AnnounceAccount, PeerId};
use near_primitives::state_part::PartId;
use near_primitives::syncing::StatePartKey;
use near_primitives::time::{Clock, Utc};
use near_primitives::types::{BlockHeight, ValidatorInfoIdentifier};
use near_primitives::unwrap_or_return;
use near_primitives::utils::{from_timestamp, MaybeValidated};
use near_primitives::validator_signer::ValidatorSigner;
use near_primitives::version::PROTOCOL_VERSION;
use near_primitives::views::{DetailedDebugStatus, ValidatorInfo};
use near_store::DBCol;
use near_telemetry::TelemetryActor;
use rand::seq::SliceRandom;
use rand::{thread_rng, Rng};
use std::collections::HashMap;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use tokio::sync::oneshot;
use tracing::{debug, error, info, trace, warn};
/// Multiplier on `max_block_time` to wait until deciding that chain stalled.
const STATUS_WAIT_TIME_MULTIPLIER: u64 = 10;
/// Drop blocks whose height are beyond head + horizon if it is not in the current epoch.
const BLOCK_HORIZON: u64 = 500;
/// `max_block_production_time` times this multiplier is how long we wait before rebroadcasting
/// the current `head`
const HEAD_STALL_MULTIPLIER: u32 = 4;
pub struct ClientActor {
/// Adversarial controls
pub adv: crate::adversarial::Controls,
// Address of this ClientActor. Can be used to send messages to self.
my_address: Addr<ClientActor>,
pub(crate) client: Client,
network_adapter: Arc<dyn PeerManagerAdapter>,
network_info: NetworkInfo,
/// Identity that represents this Client at the network level.
/// It is used as part of the messages that identify this client.
node_id: PeerId,
/// Last time we announced our accounts as validators.
last_validator_announce_time: Option<Instant>,
/// Info helper.
info_helper: InfoHelper,
/// Last time handle_block_production method was called
block_production_next_attempt: DateTime<Utc>,
// Last time when log_summary method was called.
log_summary_timer_next_attempt: DateTime<Utc>,
block_production_started: bool,
doomslug_timer_next_attempt: DateTime<Utc>,
chunk_request_retry_next_attempt: DateTime<Utc>,
sync_started: bool,
state_parts_task_scheduler: Box<dyn Fn(ApplyStatePartsRequest)>,
block_catch_up_scheduler: Box<dyn Fn(BlockCatchUpRequest)>,
state_split_scheduler: Box<dyn Fn(StateSplitRequest)>,
state_parts_client_arbiter: Arbiter,
#[cfg(feature = "sandbox")]
fastforward_delta: near_primitives::types::BlockHeightDelta,
/// Synchronization measure to allow graceful shutdown.
/// Informs the system when a ClientActor gets dropped.
_shutdown_signal: Option<oneshot::Sender<()>>,
}
/// Blocks the program until given genesis time arrives.
fn wait_until_genesis(genesis_time: &DateTime<Utc>) {
loop {
// Get chrono::Duration::num_seconds() by deducting genesis_time from now.
let duration = genesis_time.signed_duration_since(Clock::utc());
let chrono_seconds = duration.num_seconds();
// Check if number of seconds in chrono::Duration larger than zero.
if chrono_seconds <= 0 {
break;
}
info!(target: "near", "Waiting until genesis: {}d {}h {}m {}s", duration.num_days(),
(duration.num_hours() % 24),
(duration.num_minutes() % 60),
(duration.num_seconds() % 60));
let wait =
std::cmp::min(Duration::from_secs(10), Duration::from_secs(chrono_seconds as u64));
thread::sleep(wait);
}
}
impl ClientActor {
pub fn new(
address: Addr<ClientActor>,
config: ClientConfig,
chain_genesis: ChainGenesis,
runtime_adapter: Arc<dyn RuntimeAdapter>,
node_id: PeerId,
network_adapter: Arc<dyn PeerManagerAdapter>,
validator_signer: Option<Arc<dyn ValidatorSigner>>,
telemetry_actor: Addr<TelemetryActor>,
enable_doomslug: bool,
rng_seed: RngSeed,
ctx: &Context<ClientActor>,
shutdown_signal: Option<oneshot::Sender<()>>,
adv: crate::adversarial::Controls,
) -> Result<Self, Error> {
let state_parts_arbiter = Arbiter::new();
let self_addr = ctx.address();
let self_addr_clone = self_addr.clone();
let sync_jobs_actor_addr = SyncJobsActor::start_in_arbiter(
&state_parts_arbiter.handle(),
move |ctx: &mut Context<SyncJobsActor>| -> SyncJobsActor {
ctx.set_mailbox_capacity(SyncJobsActor::MAILBOX_CAPACITY);
SyncJobsActor { client_addr: self_addr_clone }
},
);
wait_until_genesis(&chain_genesis.time);
if let Some(vs) = &validator_signer {
info!(target: "client", "Starting validator node: {}", vs.validator_id());
}
let info_helper = InfoHelper::new(Some(telemetry_actor), &config, validator_signer.clone());
let client = Client::new(
config,
chain_genesis,
runtime_adapter,
network_adapter.clone(),
Arc::new(self_addr.clone()),
validator_signer,
enable_doomslug,
rng_seed,
)?;
let now = Utc::now();
Ok(ClientActor {
adv,
my_address: address,
client,
network_adapter,
node_id,
network_info: NetworkInfo {
connected_peers: vec![],
num_connected_peers: 0,
peer_max_count: 0,
highest_height_peers: vec![],
received_bytes_per_sec: 0,
sent_bytes_per_sec: 0,
known_producers: vec![],
tier1_accounts: vec![],
},
last_validator_announce_time: None,
info_helper,
block_production_next_attempt: now,
log_summary_timer_next_attempt: now,
block_production_started: false,
doomslug_timer_next_attempt: now,
chunk_request_retry_next_attempt: now,
sync_started: false,
state_parts_task_scheduler: create_sync_job_scheduler::<ApplyStatePartsRequest>(
sync_jobs_actor_addr.clone(),
),
block_catch_up_scheduler: create_sync_job_scheduler::<BlockCatchUpRequest>(
sync_jobs_actor_addr.clone(),
),
state_split_scheduler: create_sync_job_scheduler::<StateSplitRequest>(
sync_jobs_actor_addr,
),
state_parts_client_arbiter: state_parts_arbiter,
#[cfg(feature = "sandbox")]
fastforward_delta: 0,
_shutdown_signal: shutdown_signal,
})
}
}
fn create_sync_job_scheduler<M>(address: Addr<SyncJobsActor>) -> Box<dyn Fn(M)>
where
M: Message + Send + 'static,
M::Result: Send,
SyncJobsActor: Handler<M>,
{
Box::new(move |msg: M| {
if let Err(err) = address.try_send(msg) {
match err {
SendError::Full(request) => {
address.do_send(request);
}
SendError::Closed(_) => {
error!("Can't send message to SyncJobsActor, mailbox is closed");
}
}
}
})
}
impl Actor for ClientActor {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
// Start syncing job.
self.start_sync(ctx);
// Start block production tracking if have block producer info.
if self.client.validator_signer.is_some() {
self.block_production_started = true;
}
// Start triggers
self.schedule_triggers(ctx);
// Start catchup job.
self.catchup(ctx);
self.client.send_network_chain_info().unwrap();
}
}
impl Handler<WithSpanContext<NetworkClientMessages>> for ClientActor {
type Result = NetworkClientResponses;
#[perf]
fn handle(
&mut self,
msg: WithSpanContext<NetworkClientMessages>,
ctx: &mut Context<Self>,
) -> Self::Result {
let msg_type: &str = (&msg.msg).into();
let span = tracing::debug_span!(
target: "client",
"handle",
handler = "NetworkClientMessages",
actor = "ClientActor",
msg_type)
.entered();
span.set_parent(msg.context);
let msg = msg.msg;
self.check_triggers(ctx);
let _d = delay_detector::DelayDetector::new(|| {
format!("NetworkClientMessage {}", msg.as_ref()).into()
});
metrics::CLIENT_MESSAGES_COUNT.with_label_values(&[msg.as_ref()]).inc();
let timer = metrics::CLIENT_MESSAGES_PROCESSING_TIME
.with_label_values(&[msg.as_ref()])
.start_timer();
let res = self.handle_client_messages(msg);
timer.observe_duration();
res
}
}
impl ClientActor {
fn handle_client_messages(&mut self, msg: NetworkClientMessages) -> NetworkClientResponses {
match msg {
#[cfg(feature = "test_features")]
NetworkClientMessages::Adversarial(adversarial_msg) => {
return match adversarial_msg {
near_network::types::NetworkAdversarialMessage::AdvDisableDoomslug => {
info!(target: "adversary", "Turning Doomslug off");
self.adv.set_disable_doomslug(true);
self.client.doomslug.adv_disable();
self.client.chain.adv_disable_doomslug();
NetworkClientResponses::NoResponse
}
near_network::types::NetworkAdversarialMessage::AdvDisableHeaderSync => {
info!(target: "adversary", "Blocking header sync");
self.adv.set_disable_header_sync(true);
NetworkClientResponses::NoResponse
}
near_network::types::NetworkAdversarialMessage::AdvProduceBlocks(
num_blocks,
only_valid,
) => {
info!(target: "adversary", "Producing {} blocks", num_blocks);
self.client.adv_produce_blocks = true;
self.client.adv_produce_blocks_only_valid = only_valid;
let start_height =
self.client.chain.mut_store().get_latest_known().unwrap().height + 1;
let mut blocks_produced = 0;
for height in start_height.. {
let block = self
.client
.produce_block(height)
.expect("block should be produced");
if only_valid && block == None {
continue;
}
let block = block.expect("block should exist after produced");
info!(target: "adversary", "Producing {} block out of {}, height = {}", blocks_produced, num_blocks, height);
self.network_adapter.do_send(
PeerManagerMessageRequest::NetworkRequests(
NetworkRequests::Block { block: block.clone() },
),
);
let _ = self.client.start_process_block(
block.into(),
Provenance::PRODUCED,
self.get_apply_chunks_done_callback(),
);
blocks_produced += 1;
if blocks_produced == num_blocks {
break;
}
}
NetworkClientResponses::NoResponse
}
near_network::types::NetworkAdversarialMessage::AdvSwitchToHeight(height) => {
info!(target: "adversary", "Switching to height {:?}", height);
let mut chain_store_update = self.client.chain.mut_store().store_update();
chain_store_update.save_largest_target_height(height);
chain_store_update
.adv_save_latest_known(height)
.expect("adv method should not fail");
chain_store_update.commit().expect("adv method should not fail");
NetworkClientResponses::NoResponse
}
near_network::types::NetworkAdversarialMessage::AdvSetSyncInfo(height) => {
info!(target: "adversary", %height, "AdvSetSyncInfo");
self.client.adv_sync_height = Some(height);
self.client.send_network_chain_info().expect("adv method should not fail");
NetworkClientResponses::NoResponse
}
near_network::types::NetworkAdversarialMessage::AdvGetSavedBlocks => {
info!(target: "adversary", "Requested number of saved blocks");
let store = self.client.chain.store().store();
let mut num_blocks = 0;
for _ in store.iter(DBCol::Block) {
num_blocks += 1;
}
NetworkClientResponses::AdvResult(num_blocks)
}
near_network::types::NetworkAdversarialMessage::AdvCheckStorageConsistency => {
// timeout is set to 1.5 seconds to give some room as we wait in Nightly for 2 seconds
let timeout = 1500;
info!(target: "adversary", "Check Storage Consistency, timeout set to {:?} milliseconds", timeout);
let mut genesis = near_chain_configs::GenesisConfig::default();
genesis.genesis_height = self.client.chain.store().get_genesis_height();
let mut store_validator = near_chain::store_validator::StoreValidator::new(
self.client.validator_signer.as_ref().map(|x| x.validator_id().clone()),
genesis,
self.client.runtime_adapter.clone(),
self.client.chain.store().store().clone(),
self.adv.is_archival(),
);
store_validator.set_timeout(timeout);
store_validator.validate();
if store_validator.is_failed() {
error!(target: "client", "Storage Validation failed, {:?}", store_validator.errors);
NetworkClientResponses::AdvResult(0)
} else {
NetworkClientResponses::AdvResult(store_validator.tests_done())
}
}
};
}
NetworkClientMessages::Transaction { transaction, is_forwarded, check_only } => {
self.client.process_tx(transaction, is_forwarded, check_only)
}
NetworkClientMessages::Block(block, peer_id, was_requested) => {
let blocks_at_height = self
.client
.chain
.store()
.get_all_block_hashes_by_height(block.header().height());
if was_requested || !blocks_at_height.is_ok() {
if let SyncStatus::StateSync(sync_hash, _) = &mut self.client.sync_status {
if let Ok(header) = self.client.chain.get_block_header(sync_hash) {
if block.hash() == header.prev_hash() {
if let Err(e) = self.client.chain.save_block(block.into()) {
error!(target: "client", "Failed to save a block during state sync: {}", e);
}
} else if block.hash() == sync_hash {
// This is the immediate block after a state sync
// We can afford to delay requesting missing chunks for this one block
if let Err(e) = self.client.chain.save_orphan(block.into(), false) {
error!(target: "client", "Received an invalid block during state sync: {}", e);
}
}
return NetworkClientResponses::NoResponse;
}
}
self.receive_block(block, peer_id, was_requested);
NetworkClientResponses::NoResponse
} else {
match self
.client
.runtime_adapter
.get_epoch_id_from_prev_block(block.header().prev_hash())
{
Ok(epoch_id) => {
if let Some(hashes) = blocks_at_height.unwrap().get(&epoch_id) {
if !hashes.contains(block.header().hash()) {
warn!(target: "client", "Rejecting unrequested block {}, height {}", block.header().hash(), block.header().height());
}
}
}
_ => {}
}
NetworkClientResponses::NoResponse
}
}
NetworkClientMessages::BlockHeaders(headers, peer_id) => {
if self.receive_headers(headers, peer_id) {
NetworkClientResponses::NoResponse
} else {
warn!(target: "client", "Banning node for sending invalid block headers");
NetworkClientResponses::Ban { ban_reason: ReasonForBan::BadBlockHeader }
}
}
NetworkClientMessages::BlockApproval(approval, peer_id) => {
debug!(target: "client", "Receive approval {:?} from peer {:?}", approval, peer_id);
self.client.collect_block_approval(&approval, ApprovalType::PeerApproval(peer_id));
NetworkClientResponses::NoResponse
}
NetworkClientMessages::StateResponse(state_response_info) => {
let shard_id = state_response_info.shard_id();
let hash = state_response_info.sync_hash();
let state_response = state_response_info.take_state_response();
trace!(target: "sync", "Received state response shard_id: {} sync_hash: {:?} part(id/size): {:?}",
shard_id,
hash,
state_response.part().as_ref().map(|(part_id, data)| (part_id, data.len()))
);
// Get the download that matches the shard_id and hash
let download = {
let mut download: Option<&mut ShardSyncDownload> = None;
// ... It could be that the state was requested by the state sync
if let SyncStatus::StateSync(sync_hash, shards_to_download) =
&mut self.client.sync_status
{
if hash == *sync_hash {
if let Some(part_id) = state_response.part_id() {
self.client
.state_sync
.received_requested_part(part_id, shard_id, hash);
}
if let Some(shard_download) = shards_to_download.get_mut(&shard_id) {
assert!(
download.is_none(),
"Internal downloads set has duplicates"
);
download = Some(shard_download);
} else {
// This may happen because of sending too many StateRequests to different peers.
// For example, we received StateResponse after StateSync completion.
}
}
}
// ... Or one of the catchups
if let Some((_, shards_to_download, _)) =
self.client.catchup_state_syncs.get_mut(&hash)
{
if let Some(part_id) = state_response.part_id() {
self.client.state_sync.received_requested_part(part_id, shard_id, hash);
}
if let Some(shard_download) = shards_to_download.get_mut(&shard_id) {
assert!(download.is_none(), "Internal downloads set has duplicates");
download = Some(shard_download);
} else {
// This may happen because of sending too many StateRequests to different peers.
// For example, we received StateResponse after StateSync completion.
}
}
// We should not be requesting the same state twice.
download
};
if let Some(shard_sync_download) = download {
match shard_sync_download.status {
ShardSyncStatus::StateDownloadHeader => {
if let Some(header) = state_response.take_header() {
if !shard_sync_download.downloads[0].done {
match self.client.chain.set_state_header(shard_id, hash, header)
{
Ok(()) => {
shard_sync_download.downloads[0].done = true;
}
Err(err) => {
error!(target: "sync", "State sync set_state_header error, shard = {}, hash = {}: {:?}", shard_id, hash, err);
shard_sync_download.downloads[0].error = true;
}
}
}
} else {
// No header found.
// It may happen because requested node couldn't build state response.
if !shard_sync_download.downloads[0].done {
info!(target: "sync", "state_response doesn't have header, should be re-requested, shard = {}, hash = {}", shard_id, hash);
shard_sync_download.downloads[0].error = true;
}
}
}
ShardSyncStatus::StateDownloadParts => {
if let Some(part) = state_response.take_part() {
let num_parts = shard_sync_download.downloads.len() as u64;
let (part_id, data) = part;
if part_id >= num_parts {
error!(target: "sync", "State sync received incorrect part_id # {:?} for hash {:?}, potential malicious peer", part_id, hash);
return NetworkClientResponses::NoResponse;
}
if !shard_sync_download.downloads[part_id as usize].done {
match self.client.chain.set_state_part(
shard_id,
hash,
PartId::new(part_id, num_parts),
&data,
) {
Ok(()) => {
shard_sync_download.downloads[part_id as usize].done =
true;
}
Err(err) => {
error!(target: "sync", "State sync set_state_part error, shard = {}, part = {}, hash = {}: {:?}", shard_id, part_id, hash, err);
shard_sync_download.downloads[part_id as usize].error =
true;
}
}
}
}
}
_ => {}
}
} else {
error!(target: "sync", "State sync received hash {} that we're not expecting, potential malicious peer", hash);
}
NetworkClientResponses::NoResponse
}
NetworkClientMessages::EpochSyncResponse(_peer_id, _response) => {
// TODO #3488
NetworkClientResponses::NoResponse
}
NetworkClientMessages::EpochSyncFinalizationResponse(_peer_id, _response) => {
// TODO #3488
NetworkClientResponses::NoResponse
}
NetworkClientMessages::PartialEncodedChunkRequest(part_request_msg, route_back) => {
let _ = self
.client
.shards_mgr
.process_partial_encoded_chunk_request(part_request_msg, route_back);
NetworkClientResponses::NoResponse
}
NetworkClientMessages::PartialEncodedChunkResponse(response, time) => {
PARTIAL_ENCODED_CHUNK_RESPONSE_DELAY.observe(time.elapsed().as_secs_f64());
let _ = self.client.shards_mgr.process_partial_encoded_chunk_response(response);
NetworkClientResponses::NoResponse
}
NetworkClientMessages::PartialEncodedChunk(partial_encoded_chunk) => {
self.client.block_production_info.record_chunk_collected(
partial_encoded_chunk.height_created(),
partial_encoded_chunk.shard_id(),
);
let _ = self
.client
.shards_mgr
.process_partial_encoded_chunk(partial_encoded_chunk.into());
NetworkClientResponses::NoResponse
}
NetworkClientMessages::PartialEncodedChunkForward(forward) => {
match self.client.shards_mgr.process_partial_encoded_chunk_forward(forward) {
Ok(_) => {}
// Unknown chunk is normal if we get parts before the header
Err(near_chunks::Error::UnknownChunk) => (),
Err(err) => {
error!(target: "client", "Error processing forwarded chunk: {}", err)
}
}
NetworkClientResponses::NoResponse
}
NetworkClientMessages::Challenge(challenge) => {
match self.client.process_challenge(challenge) {
Ok(_) => {}
Err(err) => {
error!(target: "client", "Error processing challenge: {}", err);
}
}
NetworkClientResponses::NoResponse
}
NetworkClientMessages::NetworkInfo(network_info) => {
self.network_info = network_info;
NetworkClientResponses::NoResponse
}
}
}
}
#[cfg(feature = "sandbox")]
impl Handler<near_client_primitives::types::SandboxMessage> for ClientActor {
type Result = near_client_primitives::types::SandboxResponse;
fn handle(
&mut self,
msg: near_client_primitives::types::SandboxMessage,
_ctx: &mut Context<Self>,
) -> near_client_primitives::types::SandboxResponse {
match msg {
near_client_primitives::types::SandboxMessage::SandboxPatchState(state) => {
self.client.chain.patch_state(
near_primitives::sandbox::state_patch::SandboxStatePatch::new(state),
);
near_client_primitives::types::SandboxResponse::SandboxNoResponse
}
near_client_primitives::types::SandboxMessage::SandboxPatchStateStatus => {
near_client_primitives::types::SandboxResponse::SandboxPatchStateFinished(
!self.client.chain.patch_state_in_progress(),
)
}
near_client_primitives::types::SandboxMessage::SandboxFastForward(delta_height) => {
if self.fastforward_delta > 0 {
return near_client_primitives::types::SandboxResponse::SandboxFastForwardFailed(
"Consecutive fast_forward requests cannot be made while a current one is going on.".to_string());
}
self.fastforward_delta = delta_height;
near_client_primitives::types::SandboxResponse::SandboxNoResponse
}
near_client_primitives::types::SandboxMessage::SandboxFastForwardStatus => {
near_client_primitives::types::SandboxResponse::SandboxFastForwardFinished(
self.fastforward_delta == 0,
)
}
}
}
}
impl Handler<Status> for ClientActor {
type Result = Result<StatusResponse, StatusError>;
#[perf]
fn handle(&mut self, msg: Status, ctx: &mut Context<Self>) -> Self::Result {
let _span = tracing::debug_span!(target: "client", "handle", handler = "Status").entered();
let _d = delay_detector::DelayDetector::new(|| "client status".into());
self.check_triggers(ctx);
let head = self.client.chain.head()?;
let head_header = self.client.chain.get_block_header(&head.last_block_hash)?;
let latest_block_time = head_header.raw_timestamp();
let latest_state_root = *head_header.prev_state_root();
if msg.is_health_check {
let now = Utc::now();
let block_timestamp = from_timestamp(latest_block_time);
if now > block_timestamp {
let elapsed = (now - block_timestamp).to_std().unwrap();
if elapsed
> Duration::from_millis(
self.client.config.max_block_production_delay.as_millis() as u64
* STATUS_WAIT_TIME_MULTIPLIER,
)
{
return Err(StatusError::NoNewBlocks { elapsed });
}
}
if self.client.sync_status.is_syncing() {
return Err(StatusError::NodeIsSyncing);
}
}
let validators: Vec<ValidatorInfo> = self
.client
.runtime_adapter
.get_epoch_block_producers_ordered(&head.epoch_id, &head.last_block_hash)?
.into_iter()
.map(|(validator_stake, is_slashed)| ValidatorInfo {
account_id: validator_stake.take_account_id(),
is_slashed,
})
.collect();
let epoch_start_height =
self.client.runtime_adapter.get_epoch_start_height(&head.last_block_hash).ok();
let protocol_version =
self.client.runtime_adapter.get_epoch_protocol_version(&head.epoch_id)?;
let validator_and_key =
self.client.validator_signer.as_ref().map(|vs| (vs.validator_id(), vs.public_key()));
let mut earliest_block_hash = None;
let mut earliest_block_height = None;
let mut earliest_block_time = None;
if let Some(earliest_block_hash_value) = self.client.chain.get_earliest_block_hash()? {
earliest_block_hash = Some(earliest_block_hash_value);
if let Ok(earliest_block) =
self.client.chain.get_block_header(&earliest_block_hash_value)
{
earliest_block_height = Some(earliest_block.height());
earliest_block_time = Some(earliest_block.timestamp());
}
}
// Provide more detailed information about the current state of chain.
// For now - provide info about last 50 blocks.
let detailed_debug_status = if msg.detailed {
Some(DetailedDebugStatus {
network_info: self.network_info.clone().into(),
sync_status: format!(
"{} ({})",
self.client.sync_status.as_variant_name().to_string(),
display_sync_status(&self.client.sync_status, &self.client.chain.head()?,),
),
catchup_status: self.client.get_catchup_status()?,
current_head_status: head.clone().into(),
current_header_head_status: self.client.chain.header_head()?.into(),
block_production_delay_millis: self
.client
.config
.min_block_production_delay
.as_millis() as u64,
chain_processing_info: self.client.chain.get_chain_processing_info(),
})
} else {
None
};
let uptime_sec = Clock::utc().timestamp() - self.info_helper.boot_time_seconds;
Ok(StatusResponse {
version: self.client.config.version.clone(),
protocol_version,
latest_protocol_version: PROTOCOL_VERSION,
chain_id: self.client.config.chain_id.clone(),
rpc_addr: self.client.config.rpc_addr.clone(),
validators,
sync_info: StatusSyncInfo {
latest_block_hash: head.last_block_hash,
latest_block_height: head.height,
latest_state_root,
latest_block_time: from_timestamp(latest_block_time),
syncing: self.client.sync_status.is_syncing(),
earliest_block_hash,
earliest_block_height,
earliest_block_time,
epoch_id: Some(head.epoch_id),
epoch_start_height,
},
validator_account_id: validator_and_key.as_ref().map(|v| v.0.clone()),
node_key: validator_and_key.as_ref().map(|v| v.1.clone()),
uptime_sec,
detailed_debug_status,
})
}
}
/// Private to public API conversion.
fn make_peer_info(from: near_network::types::PeerInfo) -> near_client_primitives::types::PeerInfo {
near_client_primitives::types::PeerInfo {
id: from.id,
addr: from.addr,
account_id: from.account_id,
}
}
/// Private to public API conversion.
fn make_known_producer(
from: near_network::types::KnownProducer,
) -> near_client_primitives::types::KnownProducer {
near_client_primitives::types::KnownProducer {
peer_id: from.peer_id,
account_id: from.account_id,
addr: from.addr,
next_hops: from.next_hops,
}
}
impl Handler<GetNetworkInfo> for ClientActor {
type Result = Result<NetworkInfoResponse, String>;
#[perf]
fn handle(&mut self, _msg: GetNetworkInfo, ctx: &mut Context<Self>) -> Self::Result {
let _span = tracing::debug_span!(
target: "client",
"handle",
handler="GetNetworkInfo")
.entered();
let _d = delay_detector::DelayDetector::new(|| "client get network info".into());
self.check_triggers(ctx);
Ok(NetworkInfoResponse {
connected_peers: (self.network_info.connected_peers.iter())
.map(|fpi| make_peer_info(fpi.full_peer_info.peer_info.clone()))
.collect(),
num_connected_peers: self.network_info.num_connected_peers,
peer_max_count: self.network_info.peer_max_count,
sent_bytes_per_sec: self.network_info.sent_bytes_per_sec,
received_bytes_per_sec: self.network_info.received_bytes_per_sec,
known_producers: self
.network_info
.known_producers
.iter()
.map(|p| make_known_producer(p.clone()))
.collect(),
})
}
}
/// `ApplyChunksDoneMessage` is a message that signals the finishing of applying chunks of a block.
/// Upon receiving this message, ClientActors knows that it's time to finish processing the blocks that
/// just finished applying chunks.
#[derive(Message)]
#[rtype(result = "()")]
pub struct ApplyChunksDoneMessage;
impl Handler<ApplyChunksDoneMessage> for ClientActor {
type Result = ();
fn handle(&mut self, _msg: ApplyChunksDoneMessage, _ctx: &mut Self::Context) -> Self::Result {
self.try_process_unfinished_blocks();
}
}
impl ClientActor {
/// Check if client Account Id should be sent and send it.
/// Account Id is sent when is not current a validator but are becoming a validator soon.
fn check_send_announce_account(&mut self, prev_block_hash: CryptoHash) {
// If no peers, there is no one to announce to.
if self.network_info.num_connected_peers == 0 {
debug!(target: "client", "No peers: skip account announce");
return;
}
// First check that we currently have an AccountId
let validator_signer = match self.client.validator_signer.as_ref() {
None => return,
Some(signer) => signer,
};
let now = Clock::instant();
// Check that we haven't announced it too recently
if let Some(last_validator_announce_time) = self.last_validator_announce_time {
// Don't make announcement if have passed less than half of the time in which other peers
// should remove our Account Id from their Routing Tables.
if 2 * (now - last_validator_announce_time) < self.client.config.ttl_account_id_router {
return;
}
}
debug!(target: "client", "Check announce account for {}, last announce time {:?}", validator_signer.validator_id(), self.last_validator_announce_time);
// Announce AccountId if client is becoming a validator soon.
let next_epoch_id = unwrap_or_return!(self
.client
.runtime_adapter
.get_next_epoch_id_from_prev_block(&prev_block_hash));
// Check client is part of the futures validators
if self.client.is_validator(&next_epoch_id, &prev_block_hash) {
debug!(target: "client", "Sending announce account for {}", validator_signer.validator_id());
self.last_validator_announce_time = Some(now);
let signature = validator_signer.sign_account_announce(
validator_signer.validator_id(),
&self.node_id,
&next_epoch_id,
);
self.network_adapter.do_send(PeerManagerMessageRequest::NetworkRequests(
NetworkRequests::AnnounceAccount(AnnounceAccount {
account_id: validator_signer.validator_id().clone(),
peer_id: self.node_id.clone(),
epoch_id: next_epoch_id,
signature,
}),
));
}
}
/// Process the sandbox fast forward request. If the change in block height is past an epoch,
/// we fast forward to just right before the epoch, produce some blocks to get past and into
/// a new epoch, then we continue on with the residual amount to fast forward.
#[cfg(feature = "sandbox")]
fn sandbox_process_fast_forward(
&mut self,
block_height: BlockHeight,
) -> Result<Option<near_chain::types::LatestKnown>, Error> {
let mut delta_height = std::mem::replace(&mut self.fastforward_delta, 0);
if delta_height == 0 {
return Ok(None);
}
let epoch_length = self.client.config.epoch_length;
if epoch_length <= 3 {
return Err(Error::Other(
"Unsupported: fast_forward with an epoch length of 3 or less".to_string(),
));
}
// Check if we are at epoch boundary. If we are, do not fast forward until new
// epoch is here. Decrement the fast_forward count by 1 when a block is produced
// during this period of waiting
let block_height_wrt_epoch = block_height % epoch_length;
if epoch_length - block_height_wrt_epoch <= 3 || block_height_wrt_epoch == 0 {
// wait for doomslug to call into produce block
self.fastforward_delta = delta_height;
return Ok(None);
}
let delta_height = if block_height_wrt_epoch + delta_height >= epoch_length {
// fast forward to just right before epoch boundary to have epoch_manager
// handle the epoch_height updates as normal. `- 3` since this is being
// done 3 blocks before the epoch ends.
let right_before_epoch_update = epoch_length - block_height_wrt_epoch - 3;
delta_height -= right_before_epoch_update;
self.fastforward_delta = delta_height;
right_before_epoch_update
} else {
delta_height
};
self.client.accrued_fastforward_delta += delta_height;
let delta_time = self.client.sandbox_delta_time();
let new_latest_known = near_chain::types::LatestKnown {
height: block_height + delta_height,
seen: near_primitives::utils::to_timestamp(Clock::utc() + delta_time),
};
Ok(Some(new_latest_known))
}
fn pre_block_production(&mut self) -> Result<(), Error> {
#[cfg(feature = "sandbox")]
{
let latest_known = self.client.chain.mut_store().get_latest_known()?;
if let Some(new_latest_known) =
self.sandbox_process_fast_forward(latest_known.height)?
{
self.client.chain.mut_store().save_latest_known(new_latest_known.clone())?;
self.client.sandbox_update_tip(new_latest_known.height)?;
}
}
Ok(())
}
fn post_block_production(&mut self) {
#[cfg(feature = "sandbox")]
if self.fastforward_delta > 0 {
// Decrease the delta_height by 1 since we've produced a single block. This
// ensures that we advanced the right amount of blocks when fast forwarding
// and fast forwarding triggers regular block production in the case of
// stepping between epoch boundaries.
self.fastforward_delta -= 1;
}
}
/// Retrieves latest height, and checks if must produce next block.
/// Otherwise wait for block arrival or suggest to skip after timeout.
fn handle_block_production(&mut self) -> Result<(), Error> {
let _span = tracing::debug_span!(target: "client", "handle_block_production").entered();
// If syncing, don't try to produce blocks.
if self.client.sync_status.is_syncing() {
debug!(target:"client", "Syncing - block production disabled");
return Ok(());
}
let _ = self.client.check_and_update_doomslug_tip();