/
client_actor.rs
1358 lines (1253 loc) · 58.9 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 std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
use actix::{Actor, Addr, Arbiter, AsyncContext, Context, Handler};
use chrono::Duration as OldDuration;
use chrono::{DateTime, Utc};
use log::{debug, error, info, trace, warn};
#[cfg(feature = "delay_detector")]
use delay_detector::DelayDetector;
use near_chain::test_utils::format_hash;
use near_chain::types::AcceptedBlock;
#[cfg(feature = "adversarial")]
use near_chain::StoreValidator;
use near_chain::{
byzantine_assert, Block, BlockHeader, ChainGenesis, ChainStoreAccess, Provenance,
RuntimeAdapter,
};
use near_chain_configs::ClientConfig;
#[cfg(feature = "adversarial")]
use near_chain_configs::GenesisConfig;
use near_crypto::Signature;
#[cfg(feature = "metric_recorder")]
use near_network::recorder::MetricRecorder;
#[cfg(feature = "adversarial")]
use near_network::types::NetworkAdversarialMessage;
use near_network::types::{NetworkInfo, ReasonForBan, StateResponseInfo};
use near_network::{
NetworkAdapter, NetworkClientMessages, NetworkClientResponses, NetworkRequests,
};
use near_primitives::hash::CryptoHash;
use near_primitives::network::{AnnounceAccount, PeerId};
use near_primitives::types::{BlockHeight, EpochId};
use near_primitives::unwrap_or_return;
use near_primitives::utils::from_timestamp;
use near_primitives::validator_signer::ValidatorSigner;
use near_primitives::version::PROTOCOL_VERSION;
use near_primitives::views::ValidatorInfo;
#[cfg(feature = "adversarial")]
use near_store::ColBlock;
use near_telemetry::TelemetryActor;
use crate::client::Client;
use crate::info::{InfoHelper, ValidatorInfoHelper};
use crate::sync::{highest_height_peer, StateSync, StateSyncResult};
use crate::types::{
Error, GetNetworkInfo, NetworkInfoResponse, ShardSyncDownload, ShardSyncStatus, Status,
StatusSyncInfo, SyncStatus,
};
#[cfg(feature = "adversarial")]
use crate::AdversarialControls;
use crate::StatusResponse;
/// 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
#[cfg(feature = "adversarial")]
pub adv: Arc<RwLock<AdversarialControls>>,
client: Client,
network_adapter: Arc<dyn NetworkAdapter>,
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>,
block_production_started: bool,
doomslug_timer_next_attempt: DateTime<Utc>,
chunk_request_retry_next_attempt: DateTime<Utc>,
sync_started: bool,
}
/// 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(Utc::now());
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(
config: ClientConfig,
chain_genesis: ChainGenesis,
runtime_adapter: Arc<dyn RuntimeAdapter>,
node_id: PeerId,
network_adapter: Arc<dyn NetworkAdapter>,
validator_signer: Option<Arc<dyn ValidatorSigner>>,
telemetry_actor: Addr<TelemetryActor>,
enable_doomslug: bool,
#[cfg(feature = "adversarial")] adv: Arc<RwLock<AdversarialControls>>,
) -> Result<Self, Error> {
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(telemetry_actor, &config, validator_signer.clone());
let client = Client::new(
config,
chain_genesis,
runtime_adapter,
network_adapter.clone(),
validator_signer,
enable_doomslug,
)?;
let now = Utc::now();
Ok(ClientActor {
#[cfg(feature = "adversarial")]
adv,
client,
network_adapter,
node_id,
network_info: NetworkInfo {
active_peers: vec![],
num_active_peers: 0,
peer_max_count: 0,
highest_height_peers: vec![],
received_bytes_per_sec: 0,
sent_bytes_per_sec: 0,
known_producers: vec![],
#[cfg(feature = "metric_recorder")]
metric_recorder: MetricRecorder::default(),
},
last_validator_announce_time: None,
info_helper,
block_production_next_attempt: now,
block_production_started: false,
doomslug_timer_next_attempt: now,
chunk_request_retry_next_attempt: now,
sync_started: false,
})
}
}
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);
// Start periodic logging of current state of the client.
self.log_summary(ctx);
}
}
impl Handler<NetworkClientMessages> for ClientActor {
type Result = NetworkClientResponses;
fn handle(&mut self, msg: NetworkClientMessages, ctx: &mut Context<Self>) -> Self::Result {
#[cfg(feature = "delay_detector")]
let _d = DelayDetector::new(format!("NetworkClientMessage {}", msg.as_ref()).into());
self.check_triggers(ctx);
match msg {
#[cfg(feature = "adversarial")]
NetworkClientMessages::Adversarial(adversarial_msg) => {
return match adversarial_msg {
NetworkAdversarialMessage::AdvDisableDoomslug => {
info!(target: "adversary", "Turning Doomslug off");
self.adv.write().unwrap().adv_disable_doomslug = true;
self.client.doomslug.adv_disable();
self.client.chain.adv_disable_doomslug();
NetworkClientResponses::NoResponse
}
NetworkAdversarialMessage::AdvDisableHeaderSync => {
info!(target: "adversary", "Blocking header sync");
self.adv.write().unwrap().adv_disable_header_sync = true;
NetworkClientResponses::NoResponse
}
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(NetworkRequests::Block { block: block.clone() });
let (accepted_blocks, _) =
self.client.process_block(block, Provenance::PRODUCED);
for accepted_block in accepted_blocks {
self.client.on_block_accepted(
accepted_block.hash,
accepted_block.status,
accepted_block.provenance,
);
}
blocks_produced += 1;
if blocks_produced == num_blocks {
break;
}
}
NetworkClientResponses::NoResponse
}
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
}
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(ColBlock) {
num_blocks += 1;
}
NetworkClientResponses::AdvResult(num_blocks)
}
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 = GenesisConfig::default();
genesis.genesis_height = self.client.chain.store().get_genesis_height();
let mut 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().owned_store(),
);
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())
}
}
_ => panic!("invalid adversary message"),
};
}
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
.mut_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(_) = self.client.chain.save_block(&block) {
error!(target: "client", "Failed to save a block during state sync");
}
return NetworkClientResponses::NoResponse;
} else if block.hash() == sync_hash {
self.client.chain.save_orphan(&block);
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, _) => {
self.client.collect_block_approval(&approval, false);
NetworkClientResponses::NoResponse
}
NetworkClientMessages::StateResponse(StateResponseInfo {
shard_id,
sync_hash: hash,
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.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.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, 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::PartialEncodedChunkRequest(part_request_msg, route_back) => {
let _ = self.client.shards_mgr.process_partial_encoded_chunk_request(
part_request_msg,
route_back,
self.client.chain.mut_store(),
);
NetworkClientResponses::NoResponse
}
NetworkClientMessages::PartialEncodedChunkResponse(response) => {
if let Ok(accepted_blocks) =
self.client.process_partial_encoded_chunk_response(response)
{
self.process_accepted_blocks(accepted_blocks);
}
NetworkClientResponses::NoResponse
}
NetworkClientMessages::PartialEncodedChunk(partial_encoded_chunk) => {
if let Ok(accepted_blocks) =
self.client.process_partial_encoded_chunk(partial_encoded_chunk)
{
self.process_accepted_blocks(accepted_blocks);
}
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
}
}
}
}
impl Handler<Status> for ClientActor {
type Result = Result<StatusResponse, String>;
fn handle(&mut self, msg: Status, ctx: &mut Context<Self>) -> Self::Result {
#[cfg(feature = "delay_detector")]
let _d = DelayDetector::new("client status".to_string().into());
self.check_triggers(ctx);
let head = self.client.chain.head().map_err(|err| err.to_string())?;
let header = self
.client
.chain
.get_block_header(&head.last_block_hash)
.map_err(|err| err.to_string())?;
let latest_block_time = header.raw_timestamp().clone();
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(format!("No blocks for {:?}.", elapsed));
}
}
}
let validators = self
.client
.runtime_adapter
.get_epoch_block_producers_ordered(&head.epoch_id, &head.last_block_hash)
.map_err(|err| err.to_string())?
.into_iter()
.map(|(validator_stake, is_slashed)| ValidatorInfo {
account_id: validator_stake.account_id,
is_slashed,
})
.collect();
let protocol_version = self
.client
.runtime_adapter
.get_epoch_protocol_version(&head.epoch_id)
.map_err(|err| err.to_string())?;
let validator_account_id =
self.client.validator_signer.as_ref().map(|vs| vs.validator_id()).cloned();
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.into(),
latest_block_height: head.height,
latest_state_root: header.prev_state_root().clone().into(),
latest_block_time: from_timestamp(latest_block_time),
syncing: self.client.sync_status.is_syncing(),
},
validator_account_id,
})
}
}
impl Handler<GetNetworkInfo> for ClientActor {
type Result = Result<NetworkInfoResponse, String>;
fn handle(&mut self, _: GetNetworkInfo, ctx: &mut Context<Self>) -> Self::Result {
#[cfg(feature = "delay_detector")]
let _d = DelayDetector::new("client get network info".into());
self.check_triggers(ctx);
Ok(NetworkInfoResponse {
active_peers: self
.network_info
.active_peers
.clone()
.into_iter()
.map(|a| a.peer_info)
.collect::<Vec<_>>(),
num_active_peers: self.network_info.num_active_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.clone(),
#[cfg(feature = "metric_recorder")]
metric_recorder: self.network_info.metric_recorder.clone(),
})
}
}
impl ClientActor {
fn sign_announce_account(&self, epoch_id: &EpochId) -> Result<Signature, ()> {
if let Some(validator_signer) = self.client.validator_signer.as_ref() {
Ok(validator_signer.sign_account_announce(
&validator_signer.validator_id(),
&self.node_id,
epoch_id,
))
} else {
Err(())
}
}
/// 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_active_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 = Instant::now();
// 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 let Ok((validator_stake, is_slashed)) =
self.client.runtime_adapter.get_validator_by_account_id(
&next_epoch_id,
&prev_block_hash,
validator_signer.validator_id(),
)
{
if !is_slashed && validator_stake.public_key == validator_signer.public_key() {
debug!(target: "client", "Sending announce account for {}", validator_signer.validator_id());
self.last_validator_announce_time = Some(now);
let signature = self.sign_announce_account(&next_epoch_id).unwrap();
self.network_adapter.do_send(NetworkRequests::AnnounceAccount(AnnounceAccount {
account_id: validator_signer.validator_id().clone(),
peer_id: self.node_id.clone(),
epoch_id: next_epoch_id,
signature,
}));
}
}
}
/// 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> {
// If syncing, don't try to produce blocks.
if self.client.sync_status.is_syncing() {
return Ok(());
}
let _ = self.client.check_and_update_doomslug_tip();
let head = self.client.chain.head()?;
let latest_known = self.client.chain.mut_store().get_latest_known()?;
assert!(
head.height <= latest_known.height,
format!("Latest known height is invalid {} vs {}", head.height, latest_known.height)
);
let epoch_id =
self.client.runtime_adapter.get_epoch_id_from_prev_block(&head.last_block_hash)?;
for height in
latest_known.height + 1..=self.client.doomslug.get_largest_height_crossing_threshold()
{
let next_block_producer_account =
self.client.runtime_adapter.get_block_producer(&epoch_id, height)?;
if self.client.validator_signer.as_ref().map(|bp| bp.validator_id())
== Some(&next_block_producer_account)
{
let num_chunks = self.client.shards_mgr.num_chunks_for_block(&head.last_block_hash);
let have_all_chunks =
head.height == 0 || num_chunks == self.client.runtime_adapter.num_shards();
if self.client.doomslug.ready_to_produce_block(
Instant::now(),
height,
have_all_chunks,
) {
if let Err(err) = self.produce_block(height) {
// If there is an error, report it and let it retry on the next loop step.
error!(target: "client", "Block production failed: {}", err);
}
}
}
}
Ok(())
}
fn schedule_triggers(&mut self, ctx: &mut Context<Self>) {
let wait = self.check_triggers(ctx);
ctx.run_later(wait, move |act, ctx| {
act.schedule_triggers(ctx);
});
}
fn check_triggers(&mut self, ctx: &mut Context<ClientActor>) -> Duration {
// There is a bug in Actix library. While there are messages in mailbox, Actix
// will prioritize processing messages until mailbox is empty. Execution of any other task
// scheduled with run_later will be delayed.
#[cfg(feature = "delay_detector")]
let _d = DelayDetector::new("client triggers".into());
let mut delay = Duration::from_secs(1);
let now = Utc::now();
if self.sync_started {
self.doomslug_timer_next_attempt = self.run_timer(
self.client.config.doosmslug_step_period,
self.doomslug_timer_next_attempt,
ctx,
|act, ctx| act.try_doomslug_timer(ctx),
);
delay = core::cmp::min(
delay,
self.doomslug_timer_next_attempt.signed_duration_since(now).to_std().unwrap_or(delay),
)
}
if self.block_production_started {
self.block_production_next_attempt = self.run_timer(
self.client.config.block_production_tracking_delay,
self.block_production_next_attempt,
ctx,
|act, _ctx| act.try_handle_block_production(),
);
let _ = self.client.check_head_progress_stalled(
self.client.config.max_block_production_delay * HEAD_STALL_MULTIPLIER,
);
delay = core::cmp::min(
delay,
self.block_production_next_attempt.signed_duration_since(now).to_std().unwrap_or(delay),
)
}
self.chunk_request_retry_next_attempt = self.run_timer(
self.client.config.chunk_request_retry_period,
self.chunk_request_retry_next_attempt,
ctx,
|act, _ctx| act.client.shards_mgr.resend_chunk_requests(),
);
core::cmp::min(
delay,
self.chunk_request_retry_next_attempt.signed_duration_since(now).to_std().unwrap_or(delay),
)
}
fn try_handle_block_production(&mut self) {
match self.handle_block_production() {
Ok(()) => {}
Err(err) => {
error!(target: "client", "Handle block production failed: {:?}", err);
}
}
}
fn try_doomslug_timer(&mut self, _: &mut Context<ClientActor>) {
let _ = self.client.check_and_update_doomslug_tip();
let approvals = self.client.doomslug.process_timer(Instant::now());
// Important to save the largest approval target height before sending approvals, so
// that if the node crashes in the meantime, we cannot get slashed on recovery
let mut chain_store_update = self.client.chain.mut_store().store_update();
chain_store_update
.save_largest_target_height(self.client.doomslug.get_largest_target_height());
match chain_store_update.commit() {
Ok(_) => {
for approval in approvals {
if let Err(e) =
self.client.send_approval(&self.client.doomslug.get_tip().0, approval)
{
error!("Error while sending an approval {:?}", e);
}
}
}
Err(e) => error!("Error while committing largest skipped height {:?}", e),
};
}
/// Produce block if we are block producer for given `next_height` height.
/// Can return error, should be called with `produce_block` to handle errors and reschedule.
fn produce_block(&mut self, next_height: BlockHeight) -> Result<(), Error> {
match self.client.produce_block(next_height) {
Ok(Some(block)) => {
let block_hash = *block.hash();
let peer_id = self.node_id.clone();
let res = self.process_block(block, Provenance::PRODUCED, &peer_id);
match &res {
Ok(_) => Ok(()),
Err(e) => match e.kind() {
near_chain::ErrorKind::ChunksMissing(missing_chunks) => {
debug!(
"Chunks were missing for newly produced block {}, I'm {:?}, requesting. Missing: {:?}, ({:?})",
block_hash,
self.client.validator_signer.as_ref().map(|vs| vs.validator_id()),
missing_chunks,
missing_chunks.iter().map(|header| header.chunk_hash()).collect::<Vec<_>>()
);
self.client.shards_mgr.request_chunks(missing_chunks);
Ok(())
}
_ => {
error!(target: "client", "Failed to process freshly produced block: {:?}", res);
byzantine_assert!(false);
res.map_err(|err| err.into())
}
},
}
}
Ok(None) => Ok(()),
Err(err) => Err(err),
}
}
/// Process all blocks that were accepted by calling other relevant services.
fn process_accepted_blocks(&mut self, accepted_blocks: Vec<AcceptedBlock>) {
for accepted_block in accepted_blocks {
self.client.on_block_accepted(
accepted_block.hash,
accepted_block.status,
accepted_block.provenance,
);
let block = self.client.chain.get_block(&accepted_block.hash).unwrap();
let gas_used = Block::compute_gas_used(&block.chunks(), block.header().height());
let last_final_hash = *block.header().last_final_block();
self.info_helper.block_processed(gas_used);
self.check_send_announce_account(last_final_hash);
}
}
/// Process block and execute callbacks.
fn process_block(
&mut self,
block: Block,
provenance: Provenance,
peer_id: &PeerId,
) -> Result<(), near_chain::Error> {
// If we produced the block, send it out before we apply the block.
// If we didn't produce the block and didn't request it, do basic validation
// before sending it out.
if provenance == Provenance::PRODUCED {
self.network_adapter.do_send(NetworkRequests::Block { block: block.clone() });
} else {
match self.client.chain.validate_block(&block) {
Ok(_) => {
let head = self.client.chain.head()?;
// do not broadcast blocks that are too far back.
if (head.height < block.header().height()
|| &head.epoch_id == block.header().epoch_id())
&& provenance == Provenance::NONE
{
self.client.rebroadcast_block(block.clone());
}
}
Err(e) => {
if e.is_bad_data() {
self.network_adapter.do_send(NetworkRequests::BanPeer {
peer_id: peer_id.clone(),
ban_reason: ReasonForBan::BadBlockHeader,
});
return Err(e);
}
}
}
}
let (accepted_blocks, result) = self.client.process_block(block, provenance);
self.process_accepted_blocks(accepted_blocks);
result.map(|_| ())
}
/// Processes received block. Ban peer if the block header is invalid or the block is ill-formed.
fn receive_block(&mut self, block: Block, peer_id: PeerId, was_requested: bool) {
let hash = *block.hash();
debug!(target: "client", "{:?} Received block {} <- {} at {} from {}, requested: {}", self.client.validator_signer.as_ref().map(|vs| vs.validator_id()), hash, block.header().prev_hash(), block.header().height(), peer_id, was_requested);
let head = unwrap_or_return!(self.client.chain.head());
let is_syncing = self.client.sync_status.is_syncing();
if block.header().height() >= head.height + BLOCK_HORIZON && is_syncing && !was_requested {
debug!(target: "client", "dropping block {} that is too far ahead. Block height {} current head height {}", block.hash(), block.header().height(), head.height);
return;
}
let prev_hash = *block.header().prev_hash();
let provenance =
if was_requested { near_chain::Provenance::SYNC } else { near_chain::Provenance::NONE };
match self.process_block(block, provenance, &peer_id) {
Ok(_) => {}
Err(ref err) if err.is_bad_data() => {
warn!(target: "client", "receive bad block: {}", err);
}
Err(ref err) if err.is_error() => {
if self.client.sync_status.is_syncing() {
// While syncing, we may receive blocks that are older or from next epochs.
// This leads to Old Block or EpochOutOfBounds errors.
debug!(target: "client", "Error on receival of block: {}", err);
} else {
error!(target: "client", "Error on receival of block: {}", err);
}
}
Err(e) => match e.kind() {
near_chain::ErrorKind::Orphan => {
if !self.client.chain.is_orphan(&prev_hash) {
self.request_block_by_hash(prev_hash, peer_id)
}
}
near_chain::ErrorKind::ChunksMissing(missing_chunks) => {
debug!(
target: "client",
"Chunks were missing for block {}, I'm {:?}, requesting. Missing: {:?}, ({:?})",
hash.clone(),
self.client.validator_signer.as_ref().map(|vs| vs.validator_id()),
missing_chunks,
missing_chunks.iter().map(|header| header.chunk_hash()).collect::<Vec<_>>()
);
self.client.shards_mgr.request_chunks(missing_chunks);
}
_ => {
debug!(target: "client", "Process block: block {} refused by chain: {}", hash, e.kind());
}
},
}
}
fn receive_headers(&mut self, headers: Vec<BlockHeader>, peer_id: PeerId) -> bool {
info!(target: "client", "Received {} block headers from {}", headers.len(), peer_id);
if headers.len() == 0 {
return true;
}
match self.client.sync_block_headers(headers) {
Ok(_) => true,
Err(err) => {
if err.is_bad_data() {
error!(target: "client", "Error processing sync blocks: {}", err);
false
} else {
debug!(target: "client", "Block headers refused by chain: {}", err);
true
}
}
}
}
fn request_block_by_hash(&mut self, hash: CryptoHash, peer_id: PeerId) {
match self.client.chain.block_exists(&hash) {
Ok(false) => {
self.network_adapter.do_send(NetworkRequests::BlockRequest { hash, peer_id });
}
Ok(true) => {
debug!(target: "client", "send_block_request_to_peer: block {} already known", hash)
}
Err(e) => {
error!(target: "client", "send_block_request_to_peer: failed to check block exists: {:?}", e)
}
}
}
/// Check whether need to (continue) sync.
/// Also return higher height with known peers at that height.
fn syncing_info(&self) -> Result<(bool, u64), near_chain::Error> {
let head = self.client.chain.head()?;
let mut is_syncing = self.client.sync_status.is_syncing();
let full_peer_info = if let Some(full_peer_info) =
highest_height_peer(&self.network_info.highest_height_peers)
{
full_peer_info
} else {