-
Notifications
You must be signed in to change notification settings - Fork 629
/
chain.rs
5989 lines (5507 loc) · 252 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, DoneApplyChunkCallback,
};
use crate::blocks_delay_tracker::BlocksDelayTracker;
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::{BlockLike, MissingChunksPool};
use crate::state_request_tracker::StateRequestTracker;
use crate::state_snapshot_actor::MakeSnapshotCallback;
use crate::store::{ChainStore, ChainStoreAccess, ChainStoreUpdate, GCMode};
use crate::types::{
AcceptedBlock, ApplySplitStateResult, ApplySplitStateResultOrStateChanges,
ApplyTransactionResult, Block, BlockEconomicsConfig, BlockHeader, BlockStatus, ChainConfig,
ChainGenesis, Provenance, RuntimeAdapter,
};
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, Doomslug};
use crate::{metrics, DoomslugThresholdMode};
use borsh::BorshSerialize;
use chrono::Duration;
use crossbeam_channel::{unbounded, Receiver, Sender};
use delay_detector::DelayDetector;
use itertools::Itertools;
use lru::LruCache;
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, BlockValidityError, Tip};
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::{
block_info::BlockInfo,
epoch_sync::{BlockHeaderPair, EpochSyncInfo},
};
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, account_id_to_shard_uid, 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::static_clock::StaticClock;
use near_primitives::syncing::{
get_num_state_parts, ReceiptProofResponse, RootProof, ShardStateSyncResponseHeader,
ShardStateSyncResponseHeaderV1, 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, NumShards, ShardId, StateChangesForSplitStates, StateRoot,
};
use near_primitives::unwrap_or_return;
use near_primitives::utils::MaybeValidated;
use near_primitives::version::PROTOCOL_VERSION;
use near_primitives::views::{
BlockStatusView, DroppedReason, ExecutionOutcomeWithIdView, ExecutionStatusView,
FinalExecutionOutcomeView, FinalExecutionOutcomeWithReceiptView, FinalExecutionStatus,
LightClientBlockView, SignedTransactionView,
};
use near_store::flat::{store_helper, FlatStorageReadyStatus, FlatStorageStatus};
use near_store::get_genesis_state_roots;
use near_store::{DBCol, ShardTries};
use once_cell::sync::OnceCell;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter};
use std::sync::Arc;
use std::time::{Duration as TimeDuration, Instant};
use tracing::{debug, error, info, warn, Span};
/// Maximum number of orphans chain can store.
pub const MAX_ORPHAN_SIZE: usize = 1024;
/// Maximum age of orphan to store in the chain.
const MAX_ORPHAN_AGE_SECS: u64 = 300;
// Number of orphan ancestors should be checked to request chunks
// Orphans for which we will request for missing chunks must satisfy,
// its NUM_ORPHAN_ANCESTORS_CHECK'th ancestor has been accepted
pub const NUM_ORPHAN_ANCESTORS_CHECK: u64 = 3;
/// The size of the invalid_blocks in-memory pool
pub const INVALID_CHUNKS_POOL_SIZE: usize = 5000;
// Maximum number of orphans that we can request missing chunks
// Note that if there are no forks, the maximum number of orphans we would
// request missing chunks will not exceed NUM_ORPHAN_ANCESTORS_CHECK,
// this number only adds another restriction when there are multiple forks.
// It should almost never be hit
const MAX_ORPHAN_MISSING_CHUNKS: usize = 5;
/// 10000 years in seconds. Big constant for sandbox to allow time traveling.
#[cfg(feature = "sandbox")]
const ACCEPTABLE_TIME_DIFFERENCE: i64 = 60 * 60 * 24 * 365 * 10000;
// 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;
/// Over this block height delta in advance if we are not chunk producer - route tx to upcoming validators.
pub const TX_ROUTING_HEIGHT_HORIZON: BlockHeightDelta = 4;
/// 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,
}
/// Orphan is a block whose previous block is not accepted (in store) yet.
/// Therefore, they are not ready to be processed yet.
/// We save these blocks in an in-memory orphan pool to be processed later
/// after their previous block is accepted.
pub struct Orphan {
block: MaybeValidated<Block>,
provenance: Provenance,
added: Instant,
}
impl BlockLike for Orphan {
fn hash(&self) -> CryptoHash {
*self.block.hash()
}
fn height(&self) -> u64 {
self.block.header().height()
}
}
impl Orphan {
fn prev_hash(&self) -> &CryptoHash {
self.block.header().prev_hash()
}
}
/// OrphanBlockPool stores information of all orphans that are waiting to be processed
/// A block is added to the orphan pool when process_block failed because the block is an orphan
/// A block is removed from the pool if
/// 1) it is ready to be processed
/// or
/// 2) size of the pool exceeds MAX_ORPHAN_SIZE and the orphan was added a long time ago
/// or the height is high
pub struct OrphanBlockPool {
/// A map from block hash to a orphan block
orphans: HashMap<CryptoHash, Orphan>,
/// A set that contains all orphans for which we have requested missing chunks for them
/// An orphan can be added to this set when it was first added to the pool, or later
/// when certain requirements are satisfied (see check_orphans)
/// It can only be removed from this set when the orphan is removed from the pool
orphans_requested_missing_chunks: HashSet<CryptoHash>,
/// A map from block heights to orphan blocks at the height
/// It's used to evict orphans when the pool is saturated
height_idx: HashMap<BlockHeight, Vec<CryptoHash>>,
/// A map from block hashes to orphan blocks whose prev block is the block
/// It's used to check which orphan blocks are ready to be processed when a block is accepted
prev_hash_idx: HashMap<CryptoHash, Vec<CryptoHash>>,
/// number of orphans that were evicted
evicted: usize,
}
impl OrphanBlockPool {
pub fn new() -> OrphanBlockPool {
OrphanBlockPool {
orphans: HashMap::default(),
orphans_requested_missing_chunks: HashSet::default(),
height_idx: HashMap::default(),
prev_hash_idx: HashMap::default(),
evicted: 0,
}
}
pub fn len(&self) -> usize {
self.orphans.len()
}
fn len_evicted(&self) -> usize {
self.evicted
}
/// Add a block to the orphan pool
/// `requested_missing_chunks`: whether missing chunks has been requested for the orphan
fn add(&mut self, orphan: Orphan, requested_missing_chunks: bool) {
let block_hash = *orphan.block.hash();
let height_hashes = self.height_idx.entry(orphan.block.header().height()).or_default();
height_hashes.push(*orphan.block.hash());
let prev_hash_entries =
self.prev_hash_idx.entry(*orphan.block.header().prev_hash()).or_default();
prev_hash_entries.push(block_hash);
self.orphans.insert(block_hash, orphan);
if requested_missing_chunks {
self.orphans_requested_missing_chunks.insert(block_hash);
}
if self.orphans.len() > MAX_ORPHAN_SIZE {
let old_len = self.orphans.len();
let mut removed_hashes: HashSet<CryptoHash> = HashSet::default();
self.orphans.retain(|_, ref mut x| {
let keep = x.added.elapsed() < TimeDuration::from_secs(MAX_ORPHAN_AGE_SECS);
if !keep {
removed_hashes.insert(*x.block.hash());
}
keep
});
let mut heights = self.height_idx.keys().cloned().collect::<Vec<u64>>();
heights.sort_unstable();
for h in heights.iter().rev() {
if let Some(hash) = self.height_idx.remove(h) {
for h in hash {
let _ = self.orphans.remove(&h);
removed_hashes.insert(h);
}
}
if self.orphans.len() < MAX_ORPHAN_SIZE {
break;
}
}
self.height_idx.retain(|_, ref mut xs| xs.iter().any(|x| !removed_hashes.contains(x)));
self.prev_hash_idx
.retain(|_, ref mut xs| xs.iter().any(|x| !removed_hashes.contains(x)));
self.orphans_requested_missing_chunks.retain(|x| !removed_hashes.contains(x));
self.evicted += old_len - self.orphans.len();
}
metrics::NUM_ORPHANS.set(self.orphans.len() as i64);
}
pub fn contains(&self, hash: &CryptoHash) -> bool {
self.orphans.contains_key(hash)
}
pub fn get(&self, hash: &CryptoHash) -> Option<&Orphan> {
self.orphans.get(hash)
}
// Iterates over existing orphans.
pub fn map(&self, orphan_fn: &mut dyn FnMut(&CryptoHash, &Block, &Instant)) {
self.orphans
.iter()
.map(|it| orphan_fn(it.0, it.1.block.get_inner(), &it.1.added))
.collect_vec();
}
/// Remove all orphans in the pool that can be "adopted" by block `prev_hash`, i.e., children
/// of `prev_hash` and return the list.
/// This function is called when `prev_hash` is accepted, thus its children can be removed
/// from the orphan pool and be processed.
pub fn remove_by_prev_hash(&mut self, prev_hash: CryptoHash) -> Option<Vec<Orphan>> {
let mut removed_hashes: HashSet<CryptoHash> = HashSet::default();
let ret = self.prev_hash_idx.remove(&prev_hash).map(|hs| {
hs.iter()
.filter_map(|h| {
removed_hashes.insert(*h);
self.orphans_requested_missing_chunks.remove(h);
self.orphans.remove(h)
})
.collect()
});
self.height_idx.retain(|_, ref mut xs| xs.iter().any(|x| !removed_hashes.contains(x)));
metrics::NUM_ORPHANS.set(self.orphans.len() as i64);
ret
}
/// Return a list of orphans that are among the `target_depth` immediate descendants of
/// the block `parent_hash`
pub fn get_orphans_within_depth(
&self,
parent_hash: CryptoHash,
target_depth: u64,
) -> Vec<CryptoHash> {
let mut _visited = HashSet::new();
let mut res = vec![];
let mut queue = vec![(parent_hash, 0)];
while let Some((prev_hash, depth)) = queue.pop() {
if depth == target_depth {
break;
}
if let Some(block_hashes) = self.prev_hash_idx.get(&prev_hash) {
for hash in block_hashes {
queue.push((*hash, depth + 1));
res.push(*hash);
// there should be no loop
debug_assert!(_visited.insert(*hash));
}
}
// probably something serious went wrong here because there shouldn't be so many forks
assert!(
res.len() <= 100 * target_depth as usize,
"found too many orphans {:?}, probably something is wrong with the chain",
res
);
}
res
}
/// Returns true if the block has not been requested yet and the number of orphans
/// for which we have requested missing chunks have not exceeded MAX_ORPHAN_MISSING_CHUNKS
fn can_request_missing_chunks_for_orphan(&self, block_hash: &CryptoHash) -> bool {
self.orphans_requested_missing_chunks.len() < MAX_ORPHAN_MISSING_CHUNKS
&& !self.orphans_requested_missing_chunks.contains(block_hash)
}
fn mark_missing_chunks_requested_for_orphan(&mut self, block_hash: CryptoHash) {
self.orphans_requested_missing_chunks.insert(block_hash);
}
}
/// Contains information for missing chunks in a block
pub struct BlockMissingChunks {
/// previous block hash
pub prev_hash: CryptoHash,
pub missing_chunks: Vec<ShardChunkHeader>,
}
/// Contains information needed to request chunks for orphans
/// Fields will be used as arguments for `request_chunks_for_orphan`
pub struct OrphanMissingChunks {
pub missing_chunks: Vec<ShardChunkHeader>,
/// epoch id for the block that has missing chunks
pub epoch_id: EpochId,
/// hash of an ancestor block of the block that has missing chunks
/// this is used as an argument for `request_chunks_for_orphan`
/// see comments in `request_chunks_for_orphan` for what `ancestor_hash` is used for
pub ancestor_hash: CryptoHash,
}
/// 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> {
let header_head = 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> {
if 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> {
let head = 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<Result<ApplyChunkResult, Error>>);
/// Facade to the blockchain block processing and storage.
/// Provides current view on the state according to the chain state.
pub struct Chain {
store: ChainStore,
pub epoch_manager: Arc<dyn EpochManagerAdapter>,
pub shard_tracker: ShardTracker,
pub runtime_adapter: Arc<dyn RuntimeAdapter>,
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>,
/// 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,
/// Lets trigger new state snapshots.
state_snapshot_helper: Option<StateSnapshotHelper>,
}
/// Lets trigger new state snapshots.
struct StateSnapshotHelper {
/// A callback to initiate state snapshot.
make_snapshot_callback: MakeSnapshotCallback,
/// Test-only. Artificially triggers state snapshots every N blocks.
/// The value is (countdown, N).
test_snapshot_countdown_and_frequency: Option<(u64, u64)>,
}
impl Drop for Chain {
fn drop(&mut self) {
let _ = self.blocks_in_processing.wait_for_all_blocks();
}
}
/// ApplyChunkJob is a closure that is responsible for applying of a single chunk.
/// All of the chunk details and other arguments are already captured within.
type ApplyChunkJob = Box<dyn FnOnce(&Span) -> Result<ApplyChunkResult, Error> + Send + 'static>;
/// PreprocessBlockResult is a tuple where the first element is a vector of jobs
/// to apply chunks the second element is BlockPreprocessInfo
type PreprocessBlockResult = (Vec<ApplyChunkJob>, 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.num_shards(&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(
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 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 {
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::default(),
apply_chunks_sender: sc,
apply_chunks_receiver: rc,
last_time_head_updated: StaticClock::instant(),
invalid_blocks: LruCache::new(INVALID_CHUNKS_POOL_SIZE),
pending_state_patch: Default::default(),
requested_state_parts: StateRequestTracker::new(),
state_snapshot_helper: None,
})
}
pub fn new(
epoch_manager: Arc<dyn EpochManagerAdapter>,
shard_tracker: ShardTracker,
runtime_adapter: Arc<dyn RuntimeAdapter>,
chain_genesis: &ChainGenesis,
doomslug_threshold_mode: DoomslugThresholdMode,
chain_config: ChainConfig,
make_snapshot_callback: Option<MakeSnapshotCallback>,
) -> 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 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.num_shards(&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 = 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())?,
ChunkExtra::new(
state_root,
CryptoHash::default(),
vec![],
0,
chain_genesis.gas_limit,
0,
),
);
}
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)?.get_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()?;
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 = 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(StaticClock::utc().timestamp());
metrics::TAIL_HEIGHT.set(store.tail()? as i64);
metrics::CHUNK_TAIL_HEIGHT.set(store.chunk_tail()? as i64);
metrics::FORK_TAIL_HEIGHT.set(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 {
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::default(),
apply_chunks_sender: sc,
apply_chunks_receiver: rc,
last_time_head_updated: StaticClock::instant(),
pending_state_patch: Default::default(),
requested_state_parts: StateRequestTracker::new(),
state_snapshot_helper: make_snapshot_callback.map(|callback| StateSnapshotHelper {
make_snapshot_callback: callback,
test_snapshot_countdown_and_frequency: chain_config
.state_snapshot_every_n_blocks
.map(|n| (0, n)),
}),
})
}
#[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
}
/// 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.store.get_block(block.hash()).is_ok() {
return Ok(());
}
if let Err(e) = self.validate_block(&block) {
byzantine_assert!(false);
return Err(e);
}
let mut chain_store_update = ChainStoreUpdate::new(&mut self.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(())
}
pub fn save_orphan(
&mut self,
block: MaybeValidated<Block>,
requested_missing_chunks: bool,
) -> Result<(), Error> {
if self.orphans.contains(block.hash()) {
return Ok(());
}
if let Err(e) = self.validate_block(&block) {
byzantine_assert!(false);
return Err(e);
}
self.orphans.add(
Orphan { block, provenance: Provenance::NONE, added: StaticClock::instant() },
requested_missing_chunks,
);
Ok(())
}
fn save_block_height_processed(&mut self, block_height: BlockHeight) -> Result<(), Error> {
let mut chain_store_update = ChainStoreUpdate::new(&mut self.store);
if !chain_store_update.is_height_processed(block_height)? {
chain_store_update.save_block_height_processed(block_height);
}
chain_store_update.commit()?;
Ok(())
}
// GC CONTRACT
// ===
//
// Prerequisites, guaranteed by the System:
// 1. Genesis block is available and should not be removed by GC.
// 2. No block in storage except Genesis has height lower or equal to `genesis_height`.
// 3. There is known lowest block height (Tail) came from Genesis or State Sync.
// a. Tail is always on the Canonical Chain.
// b. Only one Tail exists.
// c. Tail's height is higher than or equal to `genesis_height`,
// 4. There is a known highest block height (Head).
// a. Head is always on the Canonical Chain.
// 5. All blocks in the storage have heights in range [Tail; Head].
// a. All forks end up on height of Head or lower.
// 6. If block A is ancestor of block B, height of A is strictly less then height of B.
// 7. (Property 1). A block with the lowest height among all the blocks at which the fork has started,
// i.e. all the blocks with the outgoing degree 2 or more,
// has the least height among all blocks on the fork.
// 8. (Property 2). The oldest block where the fork happened is never affected
// by Canonical Chain Switching and always stays on Canonical Chain.
//
// Overall:
// 1. GC procedure is handled by `clear_data()` function.
// 2. `clear_data()` runs GC process for all blocks from the Tail to GC Stop Height provided by Epoch Manager.
// 3. `clear_data()` executes separately:
// a. Forks Clearing runs for each height from Tail up to GC Stop Height.
// b. Canonical Chain Clearing from (Tail + 1) up to GC Stop Height.
// 4. Before actual clearing is started, Block Reference Map should be built.
// 5. `clear_data()` executes every time when block at new height is added.
// 6. In case of State Sync, State Sync Clearing happens.
//
// Forks Clearing:
// 1. Any fork which ends up on height `height` INCLUSIVELY and earlier will be completely deleted
// from the Store with all its ancestors up to the ancestor block where fork is happened
// EXCLUDING the ancestor block where fork is happened.
// 2. The oldest ancestor block always remains on the Canonical Chain by property 2.
// 3. All forks which end up on height `height + 1` and further are protected from deletion and
// no their ancestor will be deleted (even with lowest heights).
// 4. `clear_forks_data()` handles forks clearing for fixed height `height`.
//
// Canonical Chain Clearing:
// 1. Blocks on the Canonical Chain with the only descendant (if no forks started from them)
// are unlocked for Canonical Chain Clearing.
// 2. If Forks Clearing ended up on the Canonical Chain, the block may be unlocked
// for the Canonical Chain Clearing. There is no other reason to unlock the block exists.
// 3. All the unlocked blocks will be completely deleted
// from the Tail up to GC Stop Height EXCLUSIVELY.
// 4. (Property 3, GC invariant). Tail can be shifted safely to the height of the
// earliest existing block. There is always only one Tail (based on property 1)
// and it's always on the Canonical Chain (based on property 2).
//
// Example:
//
// height: 101 102 103 104
// --------[A]---[B]---[C]---[D]
// \ \
// \ \---[E]
// \
// \-[F]---[G]
//
// 1. Let's define clearing height = 102. It this case fork A-F-G is protected from deletion
// because of G which is on height 103. Nothing will be deleted.
// 2. Let's define clearing height = 103. It this case Fork Clearing will be executed for A
// to delete blocks G and F, then Fork Clearing will be executed for B to delete block E.
// Then Canonical Chain Clearing will delete blocks A and B as unlocked.
// Block C is the only block of height 103 remains on the Canonical Chain (invariant).
//
// State Sync Clearing:
// 1. Executing State Sync means that no data in the storage is useful for block processing
// and should be removed completely.
// 2. The Tail should be set to the block preceding Sync Block.
// 3. All the data preceding new Tail is deleted in State Sync Clearing
// and the Trie is updated with having only Genesis data.
// 4. State Sync Clearing happens in `reset_data_pre_state_sync()`.
//
pub fn clear_data(
&mut self,
tries: ShardTries,
gc_config: &near_chain_configs::GCConfig,
) -> Result<(), Error> {
let _d = DelayDetector::new(|| "GC".into());
let head = self.store.head()?;
let tail = self.store.tail()?;
let gc_stop_height = self.runtime_adapter.get_gc_stop_height(&head.last_block_hash);
if gc_stop_height > head.height {
return Err(Error::GCError("gc_stop_height cannot be larger than head.height".into()));
}
let prev_epoch_id = self.get_block_header(&head.prev_block_hash)?.epoch_id().clone();
let epoch_change = prev_epoch_id != head.epoch_id;
let mut fork_tail = self.store.fork_tail()?;
metrics::TAIL_HEIGHT.set(tail as i64);
metrics::FORK_TAIL_HEIGHT.set(fork_tail as i64);
metrics::CHUNK_TAIL_HEIGHT.set(self.store.chunk_tail()? as i64);
metrics::GC_STOP_HEIGHT.set(gc_stop_height as i64);
if epoch_change && fork_tail < gc_stop_height {
// if head doesn't change on the epoch boundary, we may update fork tail several times
// but that is fine since it doesn't affect correctness and also we limit the number of
// heights that fork cleaning goes through so it doesn't slow down client either.
let mut chain_store_update = self.store.store_update();
chain_store_update.update_fork_tail(gc_stop_height);
chain_store_update.commit()?;
fork_tail = gc_stop_height;
}
let mut gc_blocks_remaining = gc_config.gc_blocks_limit;
// Forks Cleaning
let gc_fork_clean_step = gc_config.gc_fork_clean_step;
let stop_height = tail.max(fork_tail.saturating_sub(gc_fork_clean_step));
for height in (stop_height..fork_tail).rev() {
self.clear_forks_data(tries.clone(), height, &mut gc_blocks_remaining)?;
if gc_blocks_remaining == 0 {
return Ok(());
}
let mut chain_store_update = self.store.store_update();
chain_store_update.update_fork_tail(height);
chain_store_update.commit()?;
}
// Canonical Chain Clearing
for height in tail + 1..gc_stop_height {
if gc_blocks_remaining == 0 {
return Ok(());
}
let blocks_current_height = self
.store
.get_all_block_hashes_by_height(height)?
.values()
.flatten()
.cloned()
.collect::<Vec<_>>();
let mut chain_store_update = self.store.store_update();
if let Some(block_hash) = blocks_current_height.first() {
let prev_hash = *chain_store_update.get_block_header(block_hash)?.prev_hash();
let prev_block_refcount = chain_store_update.get_block_refcount(&prev_hash)?;
if prev_block_refcount > 1 {
// Block of `prev_hash` starts a Fork, stopping
break;