-
Notifications
You must be signed in to change notification settings - Fork 596
/
chain.rs
4668 lines (4281 loc) · 197 KB
/
chain.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
use crate::block_processing_utils::{
BlockPreprocessInfo, BlockProcessingArtifact, BlocksInProcessing,
};
use crate::blocks_delay_tracker::BlocksDelayTracker;
use crate::chain_update::ChainUpdate;
use crate::crypto_hash_timer::CryptoHashTimer;
use crate::lightclient::get_epoch_block_producers_view;
use crate::migrations::check_if_block_is_first_with_chunk_of_version;
use crate::missing_chunks::MissingChunksPool;
use crate::orphan::{Orphan, OrphanBlockPool};
use crate::sharding::shuffle_receipt_proofs;
use crate::state_request_tracker::StateRequestTracker;
use crate::state_snapshot_actor::SnapshotCallbacks;
use crate::store::{ChainStore, ChainStoreAccess, ChainStoreUpdate};
use crate::rayon_spawner::RayonAsyncComputationSpawner;
use crate::types::{
AcceptedBlock, ApplyChunkBlockContext, BlockEconomicsConfig, ChainConfig, RuntimeAdapter,
StorageDataSource,
};
pub use crate::update_shard::{
apply_new_chunk, apply_old_chunk, NewChunkData, NewChunkResult, OldChunkData, OldChunkResult,
ShardContext, StorageContext,
};
use crate::update_shard::{
process_shard_update, ReshardingData, ShardUpdateReason, ShardUpdateResult,
};
use crate::validate::{
validate_challenge, validate_chunk_proofs, validate_chunk_with_chunk_extra,
validate_transactions_order,
};
use crate::{
byzantine_assert, create_light_client_block_view, BlockStatus, ChainGenesis, Doomslug,
Provenance,
};
use crate::{metrics, DoomslugThresholdMode};
use borsh::BorshDeserialize;
use crossbeam_channel::{unbounded, Receiver, Sender};
use itertools::Itertools;
use lru::LruCache;
use near_async::futures::{AsyncComputationSpawner, AsyncComputationSpawnerExt};
use near_async::time::{Clock, Duration, Instant};
use near_chain_configs::{MutableConfigValue, ReshardingConfig, ReshardingHandle};
#[cfg(feature = "new_epoch_sync")]
use near_chain_primitives::error::epoch_sync::EpochSyncInfoError;
use near_chain_primitives::error::{BlockKnownError, Error, LogTransientStorageError};
use near_epoch_manager::shard_tracker::ShardTracker;
use near_epoch_manager::types::BlockHeaderInfo;
use near_epoch_manager::EpochManagerAdapter;
use near_o11y::log_assert;
use near_primitives::block::{genesis_chunks, Block, BlockValidityError, Tip};
use near_primitives::block_header::BlockHeader;
use near_primitives::challenge::{
BlockDoubleSign, Challenge, ChallengeBody, ChallengesResult, ChunkProofs, ChunkState,
MaybeEncodedShardChunk, PartialState, SlashedValidator,
};
use near_primitives::checked_feature;
#[cfg(feature = "new_epoch_sync")]
use near_primitives::epoch_manager::epoch_sync::EpochSyncInfo;
#[cfg(feature = "new_epoch_sync")]
use near_primitives::errors::epoch_sync::EpochSyncHashType;
use near_primitives::errors::EpochError;
use near_primitives::hash::{hash, CryptoHash};
use near_primitives::merkle::{
combine_hash, merklize, verify_path, Direction, MerklePath, MerklePathItem, PartialMerkleTree,
};
use near_primitives::receipt::Receipt;
use near_primitives::sandbox::state_patch::SandboxStatePatch;
use near_primitives::shard_layout::{account_id_to_shard_id, ShardLayout, ShardUId};
use near_primitives::sharding::{
ChunkHash, ChunkHashHeight, EncodedShardChunk, ReceiptList, ReceiptProof, ShardChunk,
ShardChunkHeader, ShardInfo, ShardProof, StateSyncInfo,
};
use near_primitives::state_part::PartId;
use near_primitives::state_sync::{
get_num_state_parts, BitArray, CachedParts, ReceiptProofResponse, RootProof,
ShardStateSyncResponseHeader, ShardStateSyncResponseHeaderV2, StateHeaderKey, StatePartKey,
};
use near_primitives::transaction::{ExecutionOutcomeWithIdAndProof, SignedTransaction};
use near_primitives::types::chunk_extra::ChunkExtra;
use near_primitives::types::{
AccountId, Balance, BlockExtra, BlockHeight, BlockHeightDelta, EpochId, Gas, MerkleHash,
NumBlocks, ShardId, StateRoot,
};
use near_primitives::unwrap_or_return;
#[cfg(feature = "new_epoch_sync")]
use near_primitives::utils::index_to_bytes;
use near_primitives::utils::MaybeValidated;
use near_primitives::version::{ProtocolFeature, PROTOCOL_VERSION};
use near_primitives::views::{
BlockStatusView, DroppedReason, ExecutionOutcomeWithIdView, ExecutionStatusView,
FinalExecutionOutcomeView, FinalExecutionOutcomeWithReceiptView, FinalExecutionStatus,
LightClientBlockView, SignedTransactionView,
};
use near_store::config::StateSnapshotType;
use near_store::flat::{store_helper, FlatStorageReadyStatus, FlatStorageStatus};
use near_store::get_genesis_state_roots;
use near_store::DBCol;
use once_cell::sync::OnceCell;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::{Debug, Formatter};
use std::sync::Arc;
use tracing::{debug, debug_span, error, info, warn, Span};
/// The size of the invalid_blocks in-memory pool
pub const INVALID_CHUNKS_POOL_SIZE: usize = 5000;
/// 5000 years in seconds. Big constant for sandbox to allow time traveling.
#[cfg(feature = "sandbox")]
const ACCEPTABLE_TIME_DIFFERENCE: i64 = 60 * 60 * 24 * 365 * 5000;
// Number of parent blocks traversed to check if the block can be finalized.
const NUM_PARENTS_TO_CHECK_FINALITY: usize = 20;
/// Refuse blocks more than this many block intervals in the future (as in bitcoin).
#[cfg(not(feature = "sandbox"))]
const ACCEPTABLE_TIME_DIFFERENCE: i64 = 12 * 10;
/// Private constant for 1 NEAR (copy from near/config.rs) used for reporting.
const NEAR_BASE: Balance = 1_000_000_000_000_000_000_000_000;
/// apply_chunks may be called in two code paths, through process_block or through catchup_blocks
/// When it is called through process_block, it is possible that the shard state for the next epoch
/// has not been caught up yet, thus the two modes IsCaughtUp and NotCaughtUp.
/// CatchingUp is for when apply_chunks is called through catchup_blocks, this is to catch up the
/// shard states for the next epoch
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
enum ApplyChunksMode {
IsCaughtUp,
CatchingUp,
NotCaughtUp,
}
/// `ApplyChunksDoneMessage` is a message that signals the finishing of applying chunks of a block.
/// Upon receiving this message, ClientActors know that it's time to finish processing the blocks that
/// just finished applying chunks.
#[derive(actix::Message, Debug)]
#[rtype(result = "()")]
pub struct ApplyChunksDoneMessage;
/// Contains information for missing chunks in a block
pub struct BlockMissingChunks {
/// previous block hash
pub prev_hash: CryptoHash,
pub missing_chunks: Vec<ShardChunkHeader>,
}
impl Debug for BlockMissingChunks {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BlockMissingChunks")
.field("prev_hash", &self.prev_hash)
.field("num_missing_chunks", &self.missing_chunks.len())
.finish()
}
}
/// Check if block header is known
/// Returns Err(Error) if any error occurs when checking store
/// Ok(Err(BlockKnownError)) if the block header is known
/// Ok(Ok()) otherwise
pub fn check_header_known(
chain: &Chain,
header: &BlockHeader,
) -> Result<Result<(), BlockKnownError>, Error> {
// TODO: Change the return type to Result<BlockKnownStatusEnum, Error>.
let header_head = chain.chain_store().header_head()?;
if header.hash() == &header_head.last_block_hash
|| header.hash() == &header_head.prev_block_hash
{
return Ok(Err(BlockKnownError::KnownInHeader));
}
check_known_store(chain, header.hash())
}
/// Check if this block is in the store already.
/// Returns Err(Error) if any error occurs when checking store
/// Ok(Err(BlockKnownError)) if the block is in the store
/// Ok(Ok()) otherwise
fn check_known_store(
chain: &Chain,
block_hash: &CryptoHash,
) -> Result<Result<(), BlockKnownError>, Error> {
// TODO: Change the return type to Result<BlockKnownStatusEnum, Error>.
if chain.chain_store().block_exists(block_hash)? {
Ok(Err(BlockKnownError::KnownInStore))
} else {
// Not yet processed this block, we can proceed.
Ok(Ok(()))
}
}
/// Check if block is known: head, orphan, in processing or in store.
/// Returns Err(Error) if any error occurs when checking store
/// Ok(Err(BlockKnownError)) if the block is known
/// Ok(Ok()) otherwise
pub fn check_known(
chain: &Chain,
block_hash: &CryptoHash,
) -> Result<Result<(), BlockKnownError>, Error> {
// TODO: Change the return type to Result<BlockKnownStatusEnum, Error>.
let head = chain.chain_store().head()?;
// Quick in-memory check for fast-reject any block handled recently.
if block_hash == &head.last_block_hash || block_hash == &head.prev_block_hash {
return Ok(Err(BlockKnownError::KnownInHead));
}
if chain.blocks_in_processing.contains(block_hash) {
return Ok(Err(BlockKnownError::KnownInProcessing));
}
// Check if this block is in the set of known orphans.
if chain.orphans.contains(block_hash) {
return Ok(Err(BlockKnownError::KnownInOrphan));
}
if chain.blocks_with_missing_chunks.contains(block_hash) {
return Ok(Err(BlockKnownError::KnownInMissingChunks));
}
if chain.is_block_invalid(block_hash) {
return Ok(Err(BlockKnownError::KnownAsInvalid));
}
check_known_store(chain, block_hash)
}
type BlockApplyChunksResult = (CryptoHash, Vec<(ShardId, Result<ShardUpdateResult, Error>)>);
/// Facade to the blockchain block processing and storage.
/// Provides current view on the state according to the chain state.
pub struct Chain {
pub(crate) clock: Clock,
pub chain_store: ChainStore,
pub epoch_manager: Arc<dyn EpochManagerAdapter>,
pub shard_tracker: ShardTracker,
pub runtime_adapter: Arc<dyn RuntimeAdapter>,
pub(crate) orphans: OrphanBlockPool,
pub blocks_with_missing_chunks: MissingChunksPool<Orphan>,
genesis: Block,
pub transaction_validity_period: NumBlocks,
pub epoch_length: BlockHeightDelta,
/// Block economics, relevant to changes when new block must be produced.
pub block_economics_config: BlockEconomicsConfig,
pub doomslug_threshold_mode: DoomslugThresholdMode,
pub blocks_delay_tracker: BlocksDelayTracker,
/// Processing a block is done in three stages: preprocess_block, async_apply_chunks and
/// postprocess_block. The async_apply_chunks is done asynchronously from the ClientActor thread.
/// `blocks_in_processing` keeps track of all the blocks that have been preprocessed but are
/// waiting for chunks being applied.
pub(crate) blocks_in_processing: BlocksInProcessing,
/// Used by async_apply_chunks to send apply chunks results back to chain
apply_chunks_sender: Sender<BlockApplyChunksResult>,
/// Used to receive apply chunks results
apply_chunks_receiver: Receiver<BlockApplyChunksResult>,
/// Used to spawn the apply chunks jobs.
apply_chunks_spawner: Arc<dyn AsyncComputationSpawner>,
/// Time when head was updated most recently.
last_time_head_updated: Instant,
/// Prevents re-application of known-to-be-invalid blocks, so that in case of a
/// protocol issue we can recover faster by focusing on correct blocks.
invalid_blocks: LruCache<CryptoHash, ()>,
/// Support for sandbox's patch_state requests.
///
/// Sandbox needs ability to arbitrary modify the state. Blockchains
/// naturally prevent state tampering, so we can't *just* modify data in
/// place in the database. Instead, we will include this "bonus changes" in
/// the next block we'll be processing, keeping them in this field in the
/// meantime.
///
/// Note that without `sandbox` feature enabled, `SandboxStatePatch` is
/// a ZST. All methods of the type are no-ops which behave as if the object
/// was empty and could not hold any records (which it cannot). It’s
/// impossible to have non-empty state patch on non-sandbox builds.
pending_state_patch: SandboxStatePatch,
/// Used to store state parts already requested along with elapsed time
/// to create the parts. This information is used for debugging
pub(crate) requested_state_parts: StateRequestTracker,
/// A callback to initiate state snapshot.
snapshot_callbacks: Option<SnapshotCallbacks>,
/// Configuration for resharding.
pub(crate) resharding_config: MutableConfigValue<near_chain_configs::ReshardingConfig>,
// A handle that allows the main process to interrupt resharding if needed.
// This typically happens when the main process is interrupted.
pub resharding_handle: ReshardingHandle,
}
impl Drop for Chain {
fn drop(&mut self) {
let _ = self.blocks_in_processing.wait_for_all_blocks();
}
}
/// UpdateShardJob is a closure that is responsible for updating a shard for a single block.
/// Execution context (latest blocks/chunks details) are already captured within.
type UpdateShardJob =
(ShardId, Box<dyn FnOnce(&Span) -> Result<ShardUpdateResult, Error> + Send + Sync + 'static>);
/// PreprocessBlockResult is a tuple where the first element is a vector of jobs
/// to update shards, the second element is BlockPreprocessInfo
type PreprocessBlockResult = (Vec<UpdateShardJob>, BlockPreprocessInfo);
// Used only for verify_block_hash_and_signature. See that method.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum VerifyBlockHashAndSignatureResult {
Correct,
Incorrect,
CannotVerifyBecauseBlockIsOrphan,
}
impl Chain {
pub fn make_genesis_block(
epoch_manager: &dyn EpochManagerAdapter,
runtime_adapter: &dyn RuntimeAdapter,
chain_genesis: &ChainGenesis,
) -> Result<Block, Error> {
let state_roots = get_genesis_state_roots(runtime_adapter.store())?
.expect("genesis should be initialized.");
let genesis_chunks = genesis_chunks(
state_roots,
&epoch_manager.shard_ids(&EpochId::default())?,
chain_genesis.gas_limit,
chain_genesis.height,
chain_genesis.protocol_version,
);
Ok(Block::genesis(
chain_genesis.protocol_version,
genesis_chunks.into_iter().map(|chunk| chunk.take_header()).collect(),
chain_genesis.time,
chain_genesis.height,
chain_genesis.min_gas_price,
chain_genesis.total_supply,
Chain::compute_bp_hash(
epoch_manager,
EpochId::default(),
EpochId::default(),
&CryptoHash::default(),
)?,
))
}
pub fn new_for_view_client(
clock: Clock,
epoch_manager: Arc<dyn EpochManagerAdapter>,
shard_tracker: ShardTracker,
runtime_adapter: Arc<dyn RuntimeAdapter>,
chain_genesis: &ChainGenesis,
doomslug_threshold_mode: DoomslugThresholdMode,
save_trie_changes: bool,
) -> Result<Chain, Error> {
let store = runtime_adapter.store();
let chain_store = ChainStore::new(store.clone(), chain_genesis.height, save_trie_changes);
let genesis = Self::make_genesis_block(
epoch_manager.as_ref(),
runtime_adapter.as_ref(),
chain_genesis,
)?;
let (sc, rc) = unbounded();
Ok(Chain {
clock: clock.clone(),
chain_store,
epoch_manager,
shard_tracker,
runtime_adapter,
orphans: OrphanBlockPool::new(),
blocks_with_missing_chunks: MissingChunksPool::new(),
blocks_in_processing: BlocksInProcessing::new(),
genesis,
transaction_validity_period: chain_genesis.transaction_validity_period,
epoch_length: chain_genesis.epoch_length,
block_economics_config: BlockEconomicsConfig::from(chain_genesis),
doomslug_threshold_mode,
blocks_delay_tracker: BlocksDelayTracker::new(clock.clone()),
apply_chunks_sender: sc,
apply_chunks_receiver: rc,
apply_chunks_spawner: Arc::new(RayonAsyncComputationSpawner),
last_time_head_updated: clock.now(),
invalid_blocks: LruCache::new(INVALID_CHUNKS_POOL_SIZE),
pending_state_patch: Default::default(),
requested_state_parts: StateRequestTracker::new(),
snapshot_callbacks: None,
resharding_config: MutableConfigValue::new(
ReshardingConfig::default(),
"resharding_config",
),
resharding_handle: ReshardingHandle::new(),
})
}
pub fn new(
clock: Clock,
epoch_manager: Arc<dyn EpochManagerAdapter>,
shard_tracker: ShardTracker,
runtime_adapter: Arc<dyn RuntimeAdapter>,
chain_genesis: &ChainGenesis,
doomslug_threshold_mode: DoomslugThresholdMode,
chain_config: ChainConfig,
snapshot_callbacks: Option<SnapshotCallbacks>,
apply_chunks_spawner: Arc<dyn AsyncComputationSpawner>,
validator_account_id: Option<&AccountId>,
) -> Result<Chain, Error> {
// Get runtime initial state and create genesis block out of it.
let state_roots = get_genesis_state_roots(runtime_adapter.store())?
.expect("genesis should be initialized.");
let mut chain_store = ChainStore::new(
runtime_adapter.store().clone(),
chain_genesis.height,
chain_config.save_trie_changes,
);
let genesis_chunks = genesis_chunks(
state_roots.clone(),
&epoch_manager.shard_ids(&EpochId::default())?,
chain_genesis.gas_limit,
chain_genesis.height,
chain_genesis.protocol_version,
);
let genesis = Block::genesis(
chain_genesis.protocol_version,
genesis_chunks.iter().map(|chunk| chunk.cloned_header()).collect(),
chain_genesis.time,
chain_genesis.height,
chain_genesis.min_gas_price,
chain_genesis.total_supply,
Chain::compute_bp_hash(
epoch_manager.as_ref(),
EpochId::default(),
EpochId::default(),
&CryptoHash::default(),
)?,
);
// Check if we have a head in the store, otherwise pick genesis block.
let mut store_update = chain_store.store_update();
let (block_head, header_head) = match store_update.head() {
Ok(block_head) => {
// Check that genesis in the store is the same as genesis given in the config.
let genesis_hash = store_update.get_block_hash_by_height(chain_genesis.height)?;
if &genesis_hash != genesis.hash() {
return Err(Error::Other(format!(
"Genesis mismatch between storage and config: {:?} vs {:?}",
genesis_hash,
genesis.hash()
)));
}
// Check we have the header corresponding to the header_head.
let mut header_head = store_update.header_head()?;
if store_update.get_block_header(&header_head.last_block_hash).is_err() {
// Reset header head and "sync" head to be consistent with current block head.
store_update.save_header_head_if_not_challenged(&block_head)?;
header_head = block_head.clone();
}
// TODO: perform validation that latest state in runtime matches the stored chain.
(block_head, header_head)
}
Err(Error::DBNotFoundErr(_)) => {
for chunk in genesis_chunks {
store_update.save_chunk(chunk.clone());
}
store_update.merge(epoch_manager.add_validator_proposals(BlockHeaderInfo::new(
genesis.header(),
// genesis height is considered final
chain_genesis.height,
))?);
store_update.save_block_header(genesis.header().clone())?;
store_update.save_block(genesis.clone());
store_update
.save_block_extra(genesis.hash(), BlockExtra { challenges_result: vec![] });
for (chunk_header, state_root) in genesis.chunks().iter().zip(state_roots.iter()) {
store_update.save_chunk_extra(
genesis.hash(),
&epoch_manager
.shard_id_to_uid(chunk_header.shard_id(), &EpochId::default())?,
Self::create_genesis_chunk_extra(state_root, chain_genesis.gas_limit),
);
}
let block_head = Tip::from_header(genesis.header());
let header_head = block_head.clone();
store_update.save_head(&block_head)?;
store_update.save_final_head(&header_head)?;
// Set the root block of flat state to be the genesis block. Later, when we
// init FlatStorages, we will read the from this column in storage, so it
// must be set here.
let flat_storage_manager = runtime_adapter.get_flat_storage_manager();
let genesis_epoch_id = genesis.header().epoch_id();
let mut tmp_store_update = store_update.store().store_update();
for shard_uid in epoch_manager.get_shard_layout(genesis_epoch_id)?.shard_uids() {
flat_storage_manager.set_flat_storage_for_genesis(
&mut tmp_store_update,
shard_uid,
genesis.hash(),
genesis.header().height(),
)
}
store_update.merge(tmp_store_update);
info!(target: "chain", "Init: saved genesis: #{} {} / {:?}", block_head.height, block_head.last_block_hash, state_roots);
(block_head, header_head)
}
Err(err) => return Err(err),
};
store_update.commit()?;
// We must load in-memory tries here, and not inside runtime, because
// if we were initializing from genesis, the runtime would be
// initialized when no blocks or flat storage were initialized. We
// require flat storage in order to load in-memory tries.
// TODO(#9511): The calculation of shard UIDs is not precise in the case
// of resharding. We need to revisit this.
let tip = chain_store.head()?;
let shard_uids: Vec<_> =
epoch_manager.get_shard_layout(&tip.epoch_id)?.shard_uids().collect();
let tracked_shards: Vec<_> = shard_uids
.iter()
.filter(|shard_uid| {
shard_tracker.care_about_shard(
validator_account_id,
&tip.prev_block_hash,
shard_uid.shard_id(),
true,
)
})
.cloned()
.collect();
runtime_adapter.get_tries().load_mem_tries_for_enabled_shards(&tracked_shards)?;
info!(target: "chain", "Init: header head @ #{} {}; block head @ #{} {}",
header_head.height, header_head.last_block_hash,
block_head.height, block_head.last_block_hash);
metrics::BLOCK_HEIGHT_HEAD.set(block_head.height as i64);
let block_header = chain_store.get_block_header(&block_head.last_block_hash)?;
metrics::BLOCK_ORDINAL_HEAD.set(block_header.block_ordinal() as i64);
metrics::HEADER_HEAD_HEIGHT.set(header_head.height as i64);
metrics::BOOT_TIME_SECONDS.set(clock.now_utc().unix_timestamp());
metrics::TAIL_HEIGHT.set(chain_store.tail()? as i64);
metrics::CHUNK_TAIL_HEIGHT.set(chain_store.chunk_tail()? as i64);
metrics::FORK_TAIL_HEIGHT.set(chain_store.fork_tail()? as i64);
// Even though the channel is unbounded, the channel size is practically bounded by the size
// of blocks_in_processing, which is set to 5 now.
let (sc, rc) = unbounded();
Ok(Chain {
clock: clock.clone(),
chain_store,
epoch_manager,
shard_tracker,
runtime_adapter,
orphans: OrphanBlockPool::new(),
blocks_with_missing_chunks: MissingChunksPool::new(),
blocks_in_processing: BlocksInProcessing::new(),
invalid_blocks: LruCache::new(INVALID_CHUNKS_POOL_SIZE),
genesis: genesis.clone(),
transaction_validity_period: chain_genesis.transaction_validity_period,
epoch_length: chain_genesis.epoch_length,
block_economics_config: BlockEconomicsConfig::from(chain_genesis),
doomslug_threshold_mode,
blocks_delay_tracker: BlocksDelayTracker::new(clock.clone()),
apply_chunks_sender: sc,
apply_chunks_receiver: rc,
apply_chunks_spawner,
last_time_head_updated: clock.now(),
pending_state_patch: Default::default(),
requested_state_parts: StateRequestTracker::new(),
snapshot_callbacks,
resharding_config: chain_config.resharding_config,
resharding_handle: ReshardingHandle::new(),
})
}
#[cfg(feature = "test_features")]
pub fn adv_disable_doomslug(&mut self) {
self.doomslug_threshold_mode = DoomslugThresholdMode::NoApprovals
}
pub fn compute_bp_hash(
epoch_manager: &dyn EpochManagerAdapter,
epoch_id: EpochId,
prev_epoch_id: EpochId,
last_known_hash: &CryptoHash,
) -> Result<CryptoHash, Error> {
let bps = epoch_manager.get_epoch_block_producers_ordered(&epoch_id, last_known_hash)?;
let protocol_version = epoch_manager.get_epoch_protocol_version(&prev_epoch_id)?;
if checked_feature!("stable", BlockHeaderV3, protocol_version) {
let validator_stakes = bps.into_iter().map(|(bp, _)| bp);
Ok(CryptoHash::hash_borsh_iter(validator_stakes))
} else {
let validator_stakes = bps.into_iter().map(|(bp, _)| bp.into_v1());
Ok(CryptoHash::hash_borsh_iter(validator_stakes))
}
}
pub fn get_last_time_head_updated(&self) -> Instant {
self.last_time_head_updated
}
fn create_genesis_chunk_extra(state_root: &StateRoot, gas_limit: Gas) -> ChunkExtra {
ChunkExtra::new(state_root, CryptoHash::default(), vec![], 0, gas_limit, 0)
}
pub fn genesis_chunk_extra(&self, shard_id: ShardId) -> Result<ChunkExtra, Error> {
let shard_index = shard_id as usize;
let state_root = *get_genesis_state_roots(self.chain_store.store())?
.ok_or_else(|| Error::Other("genesis state roots do not exist in the db".to_owned()))?
.get(shard_index)
.ok_or_else(|| {
Error::Other(format!("genesis state root does not exist for shard {shard_index}"))
})?;
let gas_limit = self
.genesis
.chunks()
.get(shard_index)
.ok_or_else(|| {
Error::Other(format!("genesis chunk does not exist for shard {shard_index}"))
})?
.gas_limit();
Ok(Self::create_genesis_chunk_extra(&state_root, gas_limit))
}
/// Creates a light client block for the last final block from perspective of some other block
///
/// # Arguments
/// * `header` - the last finalized block seen from `header` (not pushed back) will be used to
/// compute the light client block
pub fn create_light_client_block(
header: &BlockHeader,
epoch_manager: &dyn EpochManagerAdapter,
chain_store: &dyn ChainStoreAccess,
) -> Result<LightClientBlockView, Error> {
let final_block_header = {
let ret = chain_store.get_block_header(header.last_final_block())?;
let two_ahead = chain_store.get_block_header_by_height(ret.height() + 2)?;
if two_ahead.epoch_id() != ret.epoch_id() {
let one_ahead = chain_store.get_block_header_by_height(ret.height() + 1)?;
if one_ahead.epoch_id() != ret.epoch_id() {
let new_final_hash = *ret.last_final_block();
chain_store.get_block_header(&new_final_hash)?
} else {
let new_final_hash = *one_ahead.last_final_block();
chain_store.get_block_header(&new_final_hash)?
}
} else {
ret
}
};
let next_block_producers = get_epoch_block_producers_view(
final_block_header.next_epoch_id(),
header.prev_hash(),
epoch_manager,
)?;
create_light_client_block_view(&final_block_header, chain_store, Some(next_block_producers))
}
pub fn save_block(&mut self, block: MaybeValidated<Block>) -> Result<(), Error> {
if self.chain_store.get_block(block.hash()).is_ok() {
return Ok(());
}
let mut chain_store_update = ChainStoreUpdate::new(&mut self.chain_store);
chain_store_update.save_block(block.into_inner());
// We don't need to increase refcount for `prev_hash` at this point
// because this is the block before State Sync.
chain_store_update.commit()?;
Ok(())
}
fn save_block_height_processed(&mut self, block_height: BlockHeight) -> Result<(), Error> {
let mut chain_store_update = ChainStoreUpdate::new(&mut self.chain_store);
if !chain_store_update.is_height_processed(block_height)? {
chain_store_update.save_block_height_processed(block_height);
}
chain_store_update.commit()?;
Ok(())
}
fn maybe_mark_block_invalid(&mut self, block_hash: CryptoHash, error: &Error) {
// We only mark the block as invalid if the block has bad data (not for other errors that would
// not be the fault of the block itself), except when the block has a bad signature which means
// the block might not have been what the block producer originally produced. Either way, it's
// OK if we miss some cases here because this is just an optimization to avoid reprocessing
// known invalid blocks so the network recovers faster in case of any issues.
if error.is_bad_data() && !matches!(error, Error::InvalidSignature) {
metrics::NUM_INVALID_BLOCKS.with_label_values(&[error.prometheus_label_value()]).inc();
self.invalid_blocks.put(block_hash, ());
}
}
/// Return a StateSyncInfo that includes the information needed for syncing state for shards needed
/// in the next epoch.
fn get_state_sync_info(
&self,
me: &Option<AccountId>,
block: &Block,
) -> Result<Option<StateSyncInfo>, Error> {
let prev_hash = *block.header().prev_hash();
let shards_to_state_sync = Chain::get_shards_to_state_sync(
self.epoch_manager.as_ref(),
&self.shard_tracker,
me,
&prev_hash,
)?;
let prev_block = self.get_block(&prev_hash)?;
if prev_block.chunks().len() != block.chunks().len() && !shards_to_state_sync.is_empty() {
// Currently, the state sync algorithm assumes that the number of chunks do not change
// between the epoch being synced to and the last epoch.
// For example, if shard layout changes at the beginning of epoch T, validators
// will not be able to sync states at epoch T for epoch T+1
// Fortunately, since all validators track all shards for now, this error will not be
// triggered in live yet
// Instead of propagating the error, we simply log the error here because the error
// do not affect processing blocks for this epoch. However, when the next epoch comes,
// the validator will not have the states ready so it will halt.
error!(
"Cannot download states for epoch {:?} because sharding just changed. I'm {:?}",
block.header().epoch_id(),
me
);
debug_assert!(false);
}
if shards_to_state_sync.is_empty() {
Ok(None)
} else {
debug!(target: "chain", "Downloading state for {:?}, I'm {:?}", shards_to_state_sync, me);
let state_sync_info = StateSyncInfo {
epoch_tail_hash: *block.header().hash(),
shards: shards_to_state_sync
.iter()
.map(|shard_id| {
let chunk = &prev_block.chunks()[*shard_id as usize];
ShardInfo(*shard_id, chunk.chunk_hash())
})
.collect(),
};
Ok(Some(state_sync_info))
}
}
/// Do basic validation of a block upon receiving it. Check that block is
/// well-formed (various roots match).
pub fn validate_block(&self, block: &MaybeValidated<Block>) -> Result<(), Error> {
block
.validate_with(|block| {
Chain::validate_block_impl(self.epoch_manager.as_ref(), self.genesis_block(), block)
.map(|_| true)
})
.map(|_| ())
}
fn validate_block_impl(
epoch_manager: &dyn EpochManagerAdapter,
genesis_block: &Block,
block: &Block,
) -> Result<(), Error> {
for (shard_id, chunk_header) in block.chunks().iter().enumerate() {
if chunk_header.height_created() == genesis_block.header().height() {
// Special case: genesis chunks can be in non-genesis blocks and don't have a signature
// We must verify that content matches and signature is empty.
// TODO: this code will not work when genesis block has different number of chunks as the current block
// https://github.com/near/nearcore/issues/4908
let chunks = genesis_block.chunks();
let genesis_chunk = chunks.get(shard_id);
let genesis_chunk = genesis_chunk.ok_or(Error::InvalidChunk)?;
if genesis_chunk.chunk_hash() != chunk_header.chunk_hash()
|| genesis_chunk.signature() != chunk_header.signature()
{
return Err(Error::InvalidChunk);
}
} else if chunk_header.height_created() == block.header().height() {
if chunk_header.shard_id() != shard_id as ShardId {
return Err(Error::InvalidShardId(chunk_header.shard_id()));
}
if !epoch_manager.verify_chunk_header_signature(
&chunk_header.clone(),
block.header().epoch_id(),
block.header().prev_hash(),
)? {
byzantine_assert!(false);
return Err(Error::InvalidChunk);
}
}
}
block.check_validity().map_err(|e| <BlockValidityError as Into<Error>>::into(e))?;
Ok(())
}
/// Verify header signature when the epoch is known, but not the whole chain.
/// Same as verify_header_signature except it does not verify that block producer hasn't been slashed
fn partial_verify_orphan_header_signature(&self, header: &BlockHeader) -> Result<bool, Error> {
let block_producer =
self.epoch_manager.get_block_producer(header.epoch_id(), header.height())?;
// DEVNOTE: we pass head which is not necessarily on block's chain, but it's only used for
// slashing info which we will ignore
let head = self.head()?;
let (block_producer, _slashed) = self.epoch_manager.get_validator_by_account_id(
header.epoch_id(),
&head.last_block_hash,
&block_producer,
)?;
Ok(header.signature().verify(header.hash().as_ref(), block_producer.public_key()))
}
/// Optimization which checks if block with the given header can be reached from final head, and thus can be
/// finalized by this node.
/// If this is the case, returns Ok.
/// If we discovered that it is not the case, returns `Error::CannotBeFinalized`.
/// If too many parents were checked, returns Ok to avoid long delays.
fn check_if_finalizable(&self, header: &BlockHeader) -> Result<(), Error> {
let mut header = header.clone();
let final_head = self.final_head()?;
for _ in 0..NUM_PARENTS_TO_CHECK_FINALITY {
// If we reached final head, then block can be finalized.
if header.hash() == &final_head.last_block_hash {
return Ok(());
}
// If we went behind final head, then block cannot be finalized on top of final head.
if header.height() < final_head.height {
return Err(Error::CannotBeFinalized);
}
// Otherwise go to parent block.
header = match self.get_previous_header(&header) {
Ok(header) => header,
Err(_) => {
// We couldn't find previous header. Return Ok because it can be an orphaned block which can be
// connected to canonical chain later.
return Ok(());
}
}
}
// If we traversed too many blocks, return Ok to avoid long delays.
Ok(())
}
/// Validate header. Returns error if the header is invalid.
/// `challenges`: the function will add new challenges generated from validating this header
/// to the vector. You can pass an empty vector here, or a vector with existing
/// challenges already.
fn validate_header(
&self,
header: &BlockHeader,
provenance: &Provenance,
challenges: &mut Vec<ChallengeBody>,
) -> Result<(), Error> {
// Refuse blocks from the too distant future.
if header.timestamp() > self.clock.now_utc() + Duration::seconds(ACCEPTABLE_TIME_DIFFERENCE)
{
return Err(Error::InvalidBlockFutureTime(header.timestamp()));
}
// Check the signature.
if !self.epoch_manager.verify_header_signature(header)? {
return Err(Error::InvalidSignature);
}
// Check we don't know a block with given height already.
// If we do - send out double sign challenge and keep going as double signed blocks are valid blocks.
// Check if there is already known block of the same height that has the same epoch id
if let Some(block_hashes) =
self.chain_store.get_all_block_hashes_by_height(header.height())?.get(header.epoch_id())
{
// This should be guaranteed but it doesn't hurt to check again
if !block_hashes.contains(header.hash()) {
let other_header = self.get_block_header(block_hashes.iter().next().unwrap())?;
challenges.push(ChallengeBody::BlockDoubleSign(BlockDoubleSign {
left_block_header: borsh::to_vec(&header).expect("Failed to serialize"),
right_block_header: borsh::to_vec(&other_header).expect("Failed to serialize"),
}));
}
}
#[cfg(feature = "protocol_feature_reject_blocks_with_outdated_protocol_version")]
if let Ok(epoch_protocol_version) =
self.epoch_manager.get_epoch_protocol_version(header.epoch_id())
{
if checked_feature!(
"protocol_feature_reject_blocks_with_outdated_protocol_version",
RejectBlocksWithOutdatedProtocolVersions,
epoch_protocol_version
) {
if header.latest_protocol_version() < epoch_protocol_version {
error!(
"header protocol version {} smaller than epoch protocol version {}",
header.latest_protocol_version(),
epoch_protocol_version
);
return Err(Error::InvalidProtocolVersion);
}
}
}
let prev_header = self.get_previous_header(header)?;
// Check that epoch_id in the header does match epoch given previous header (only if previous header is present).
let epoch_id_from_prev_block =
&self.epoch_manager.get_epoch_id_from_prev_block(header.prev_hash())?;
let epoch_id_from_header = header.epoch_id();
if epoch_id_from_prev_block != epoch_id_from_header {
return Err(Error::InvalidEpochHash);
}
// Check that epoch_id in the header does match epoch given previous header (only if previous header is present).
if &self.epoch_manager.get_next_epoch_id_from_prev_block(header.prev_hash())?
!= header.next_epoch_id()
{
return Err(Error::InvalidEpochHash);
}
if header.epoch_id() == prev_header.epoch_id() {
if header.next_bp_hash() != prev_header.next_bp_hash() {
return Err(Error::InvalidNextBPHash);
}
} else {
if header.next_bp_hash()
!= &Chain::compute_bp_hash(
self.epoch_manager.as_ref(),
header.next_epoch_id().clone(),
header.epoch_id().clone(),
header.prev_hash(),
)?
{
return Err(Error::InvalidNextBPHash);
}
}
if header.chunk_mask().len() != self.epoch_manager.shard_ids(header.epoch_id())?.len() {
return Err(Error::InvalidChunkMask);
}
if !header.verify_chunks_included() {
return Err(Error::InvalidChunkMask);
}
if let Some(prev_height) = header.prev_height() {
if prev_height != prev_header.height() {
return Err(Error::Other("Invalid prev_height".to_string()));
}
}
// Prevent time warp attacks and some timestamp manipulations by forcing strict
// time progression.
if header.raw_timestamp() <= prev_header.raw_timestamp() {
return Err(Error::InvalidBlockPastTime(prev_header.timestamp(), header.timestamp()));
}
// If this is not the block we produced (hence trust in it) - validates block
// producer, confirmation signatures and finality info.
if *provenance != Provenance::PRODUCED {
// first verify aggregated signature
if !self.epoch_manager.verify_approval(
prev_header.hash(),
prev_header.height(),
header.height(),
header.approvals(),
)? {
return Err(Error::InvalidApprovals);
};
let stakes = self
.epoch_manager
.get_epoch_block_approvers_ordered(header.prev_hash())?
.iter()
.map(|(x, is_slashed)| (x.stake_this_epoch, x.stake_next_epoch, *is_slashed))
.collect::<Vec<_>>();
if !Doomslug::can_approved_block_be_produced(
self.doomslug_threshold_mode,
header.approvals(),
&stakes,
) {
return Err(Error::NotEnoughApprovals);
}
let expected_last_ds_final_block = if prev_header.height() + 1 == header.height() {
prev_header.hash()
} else {
prev_header.last_ds_final_block()
};
let expected_last_final_block = if prev_header.height() + 1 == header.height()
&& prev_header.last_ds_final_block() == prev_header.prev_hash()
{
prev_header.prev_hash()
} else {
prev_header.last_final_block()
};
if header.last_ds_final_block() != expected_last_ds_final_block
|| header.last_final_block() != expected_last_final_block