/
chain.rs
2304 lines (2048 loc) · 89.5 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 std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration as TimeDuration, Instant};
use borsh::BorshSerialize;
use chrono::prelude::{DateTime, Utc};
use chrono::Duration;
use log::{debug, info};
use near_primitives::block::genesis_chunks;
use near_primitives::hash::{hash, CryptoHash};
use near_primitives::merkle::{merklize, verify_path};
use near_primitives::receipt::Receipt;
use near_primitives::sharding::{
ChunkHash, ChunkHashHeight, ReceiptProof, ShardChunk, ShardChunkHeader, ShardProof,
};
use near_primitives::transaction::ExecutionOutcome;
use near_primitives::types::{AccountId, Balance, BlockIndex, ChunkExtra, Gas, ShardId};
use near_store::{Store, COL_STATE_HEADERS};
use crate::byzantine_assert;
use crate::error::{Error, ErrorKind};
use crate::metrics;
use crate::store::{ChainStore, ChainStoreAccess, ChainStoreUpdate, ShardInfo, StateSyncInfo};
use crate::types::{
validate_chunk_proofs, AcceptedBlock, Block, BlockHeader, BlockStatus, Provenance, ReceiptList,
ReceiptProofResponse, ReceiptResponse, RootProof, RuntimeAdapter, ShardStateSyncResponseHeader,
ShardStateSyncResponsePart, StateHeaderKey, Tip, ValidatorSignatureVerificationResult,
};
/// Maximum number of orphans chain can store.
pub const MAX_ORPHAN_SIZE: usize = 1024;
/// Maximum age of orhpan to store in the chain.
const MAX_ORPHAN_AGE_SECS: u64 = 300;
/// Refuse blocks more than this many block intervals in the future (as in bitcoin).
const ACCEPTABLE_TIME_DIFFERENCE: i64 = 12 * 10;
enum ApplyChunksMode {
ThisEpoch,
NextEpoch,
}
pub struct Orphan {
block: Block,
provenance: Provenance,
added: Instant,
}
pub struct OrphanBlockPool {
orphans: HashMap<CryptoHash, Orphan>,
height_idx: HashMap<BlockIndex, Vec<CryptoHash>>,
prev_hash_idx: HashMap<CryptoHash, Vec<CryptoHash>>,
evicted: usize,
}
impl OrphanBlockPool {
fn new() -> OrphanBlockPool {
OrphanBlockPool {
orphans: HashMap::default(),
height_idx: HashMap::default(),
prev_hash_idx: HashMap::default(),
evicted: 0,
}
}
fn len(&self) -> usize {
self.orphans.len()
}
fn len_evicted(&self) -> usize {
self.evicted
}
fn add(&mut self, orphan: Orphan) {
let height_hashes =
self.height_idx.entry(orphan.block.header.inner.height).or_insert_with(|| vec![]);
height_hashes.push(orphan.block.hash());
let prev_hash_entries =
self.prev_hash_idx.entry(orphan.block.header.inner.prev_hash).or_insert_with(|| vec![]);
prev_hash_entries.push(orphan.block.hash());
self.orphans.insert(orphan.block.hash(), orphan);
if self.orphans.len() > MAX_ORPHAN_SIZE {
let old_len = self.orphans.len();
self.orphans.retain(|_, ref mut x| {
x.added.elapsed() < TimeDuration::from_secs(MAX_ORPHAN_AGE_SECS)
});
let mut heights = self.height_idx.keys().cloned().collect::<Vec<u64>>();
heights.sort_unstable();
let mut removed_hashes: HashSet<CryptoHash> = HashSet::default();
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.evicted += old_len - self.orphans.len();
}
}
pub fn contains(&self, hash: &CryptoHash) -> bool {
self.orphans.contains_key(hash)
}
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.clone());
self.orphans.remove(h)
})
.collect()
});
self.height_idx.retain(|_, ref mut xs| xs.iter().any(|x| !removed_hashes.contains(&x)));
ret
}
}
/// Chain genesis configuration.
#[derive(Clone)]
pub struct ChainGenesis {
pub time: DateTime<Utc>,
pub gas_limit: Gas,
pub gas_price: Balance,
pub total_supply: Balance,
pub max_inflation_rate: u8,
pub gas_price_adjustment_rate: u8,
pub transaction_validity_period: BlockIndex,
}
impl ChainGenesis {
pub fn new(
time: DateTime<Utc>,
gas_limit: Gas,
gas_price: Balance,
total_supply: Balance,
max_inflation_rate: u8,
gas_price_adjustment_rate: u8,
transaction_validity_period: BlockIndex,
) -> Self {
Self {
time,
gas_limit,
gas_price,
total_supply,
max_inflation_rate,
gas_price_adjustment_rate,
transaction_validity_period,
}
}
}
/// Facade to the blockchain block processing and storage.
/// Provides current view on the state according to the chain state.
pub struct Chain {
store: ChainStore,
runtime_adapter: Arc<dyn RuntimeAdapter>,
orphans: OrphanBlockPool,
blocks_with_missing_chunks: OrphanBlockPool,
genesis: BlockHeader,
pub transaction_validity_period: BlockIndex,
}
impl Chain {
pub fn new(
store: Arc<Store>,
runtime_adapter: Arc<dyn RuntimeAdapter>,
chain_genesis: &ChainGenesis,
) -> Result<Chain, Error> {
let mut store = ChainStore::new(store);
// Get runtime initial state and create genesis block out of it.
let (state_store_update, state_roots) = runtime_adapter.genesis_state();
let genesis_chunks = genesis_chunks(
state_roots.clone(),
runtime_adapter.num_shards(),
chain_genesis.gas_limit,
);
let genesis = Block::genesis(
genesis_chunks.iter().map(|chunk| chunk.header.clone()).collect(),
chain_genesis.time,
chain_genesis.gas_limit,
chain_genesis.gas_price,
chain_genesis.total_supply,
);
// Check if we have a head in the store, otherwise pick genesis block.
let mut store_update = store.store_update();
let head_res = store_update.head();
let head: Tip;
match head_res {
Ok(h) => {
head = h;
// 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(0)?;
if genesis_hash != genesis.hash() {
return Err(ErrorKind::Other(format!(
"Genesis mismatch between storage and config: {:?} vs {:?}",
genesis_hash,
genesis.hash()
))
.into());
}
// Check we have the header corresponding to the header_head.
let 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(&head)?;
store_update.save_sync_head(&head);
} else {
// Reset sync head to be consistent with current header head.
store_update.save_sync_head(&header_head);
}
// TODO: perform validation that latest state in runtime matches the stored chain.
}
Err(err) => match err.kind() {
ErrorKind::DBNotFoundErr(_) => {
for chunk in genesis_chunks {
store_update.save_chunk(&chunk.chunk_hash, chunk.clone());
}
runtime_adapter.add_validator_proposals(
CryptoHash::default(),
genesis.hash(),
genesis.header.inner.height,
vec![],
vec![],
vec![],
0,
0,
0,
chain_genesis.total_supply,
)?;
store_update.save_block_header(genesis.header.clone());
store_update.save_block(genesis.clone());
for (chunk_header, state_root) in genesis.chunks.iter().zip(state_roots.iter())
{
store_update.save_chunk_extra(
&genesis.hash(),
chunk_header.inner.shard_id,
ChunkExtra::new(
state_root,
vec![],
0,
chain_genesis.gas_limit,
0,
0,
0,
),
);
}
head = Tip::from_header(&genesis.header);
store_update.save_head(&head)?;
store_update.save_sync_head(&head);
store_update.merge(state_store_update);
info!(target: "chain", "Init: saved genesis: {:?} / {:?}", genesis.hash(), state_roots);
}
e => return Err(e.into()),
},
}
store_update.commit()?;
info!(target: "chain", "Init: head: {} @ {} [{}]", head.total_weight.to_num(), head.height, head.last_block_hash);
Ok(Chain {
store,
runtime_adapter,
orphans: OrphanBlockPool::new(),
blocks_with_missing_chunks: OrphanBlockPool::new(),
genesis: genesis.header,
transaction_validity_period: chain_genesis.transaction_validity_period,
})
}
/// Reset "sync" head to current header head.
/// Do this when first transition to header syncing.
pub fn reset_sync_head(&mut self) -> Result<Tip, Error> {
let mut chain_store_update = self.store.store_update();
let header_head = chain_store_update.header_head()?;
chain_store_update.save_sync_head(&header_head);
chain_store_update.commit()?;
Ok(header_head)
}
pub fn save_block(&mut self, block: &Block) -> Result<(), Error> {
let mut chain_store_update = ChainStoreUpdate::new(&mut self.store);
if !block.check_validity() {
byzantine_assert!(false);
return Err(ErrorKind::Other("Invalid block".into()).into());
}
chain_store_update.save_block(block.clone());
chain_store_update.commit()?;
Ok(())
}
/// Process a block header received during "header first" propagation.
pub fn process_block_header(&mut self, header: &BlockHeader) -> Result<(), Error> {
// We create new chain update, but it's not going to be committed so it's read only.
let mut chain_update = ChainUpdate::new(
&mut self.store,
self.runtime_adapter.clone(),
&self.orphans,
&self.blocks_with_missing_chunks,
self.transaction_validity_period,
);
chain_update.process_block_header(header)?;
Ok(())
}
pub fn mark_block_as_challenged(
&mut self,
block_hash: &CryptoHash,
challenger_hash: &CryptoHash,
) -> Result<(), Error> {
let mut chain_update = ChainUpdate::new(
&mut self.store,
self.runtime_adapter.clone(),
&self.orphans,
&self.blocks_with_missing_chunks,
self.transaction_validity_period,
);
chain_update.mark_block_as_challenged(block_hash, challenger_hash)?;
chain_update.commit()?;
Ok(())
}
/// Process a received or produced block, and unroll any orphans that may depend on it.
/// Changes current state, and calls `block_accepted` callback in case block was successfully applied.
pub fn process_block<F, F2>(
&mut self,
me: &Option<AccountId>,
block: Block,
provenance: Provenance,
block_accepted: F,
block_misses_chunks: F2,
) -> Result<Option<Tip>, Error>
where
F: Copy + FnMut(AcceptedBlock) -> (),
F2: Copy + FnMut(Vec<ShardChunkHeader>) -> (),
{
let block_hash = block.hash();
let timer = near_metrics::start_timer(&metrics::BLOCK_PROCESSING_TIME);
let res =
self.process_block_single(me, block, provenance, block_accepted, block_misses_chunks);
near_metrics::stop_timer(timer);
if res.is_ok() {
near_metrics::inc_counter(&metrics::BLOCK_PROCESSED_SUCCESSFULLY_TOTAL);
if let Some(new_res) =
self.check_orphans(me, block_hash, block_accepted, block_misses_chunks)
{
return Ok(Some(new_res));
}
}
res
}
/// Processes headers and adds them to store for syncing.
pub fn sync_block_headers(&mut self, mut headers: Vec<BlockHeader>) -> Result<(), Error> {
// Sort headers by heights if they are out of order.
headers.sort_by(|left, right| left.inner.height.cmp(&right.inner.height));
let _first_header = if let Some(header) = headers.first() {
debug!(target: "chain", "Sync block headers: {} headers from {} at {}", headers.len(), header.hash(), header.inner.height);
header
} else {
return Ok(());
};
let all_known = if let Some(last_header) = headers.last() {
self.store.get_block_header(&last_header.hash()).is_ok()
} else {
false
};
if !all_known {
// Validate header and then add to the chain.
for header in headers.iter() {
let mut chain_update = ChainUpdate::new(
&mut self.store,
self.runtime_adapter.clone(),
&self.orphans,
&self.blocks_with_missing_chunks,
self.transaction_validity_period,
);
chain_update.validate_header(header, &Provenance::SYNC)?;
chain_update.chain_store_update.save_block_header(header.clone());
chain_update.commit()?;
// Add validator proposals for given header.
self.runtime_adapter.add_validator_proposals(
header.inner.prev_hash,
header.hash(),
header.inner.height,
header.inner.validator_proposals.clone(),
vec![],
header.inner.chunk_mask.clone(),
header.inner.rent_paid,
header.inner.validator_reward,
header.inner.balance_burnt,
header.inner.total_supply,
)?;
}
}
let mut chain_update = ChainUpdate::new(
&mut self.store,
self.runtime_adapter.clone(),
&self.orphans,
&self.blocks_with_missing_chunks,
self.transaction_validity_period,
);
if let Some(header) = headers.last() {
// Update sync_head regardless of the total weight.
chain_update.update_sync_head(header)?;
// Update header_head if total weight changed.
chain_update.update_header_head_if_not_challenged(header)?;
}
chain_update.commit()
}
/// Check if state download is required, otherwise return hashes of blocks to fetch.
pub fn check_state_needed(
&mut self,
block_fetch_horizon: BlockIndex,
) -> Result<(bool, Vec<CryptoHash>), Error> {
let block_head = self.head()?;
let header_head = self.header_head()?;
let mut hashes = vec![];
if block_head.total_weight >= header_head.total_weight {
return Ok((false, hashes));
}
// Find common block between header chain and block chain.
let mut oldest_height = 0;
let mut current = self.get_block_header(&header_head.last_block_hash).map(|h| h.clone());
while let Ok(header) = current {
if header.inner.height <= block_head.height {
if self.is_on_current_chain(&header).is_ok() {
break;
}
}
oldest_height = header.inner.height;
hashes.push(header.hash());
current = self.get_previous_header(&header).map(|h| h.clone());
}
let sync_head = self.sync_head()?;
if oldest_height < sync_head.height.saturating_sub(block_fetch_horizon) {
return Ok((true, vec![]));
}
Ok((false, hashes))
}
/// Returns if given block header on the current chain.
fn is_on_current_chain(&mut self, header: &BlockHeader) -> Result<(), Error> {
let chain_header = self.get_header_by_height(header.inner.height)?;
if chain_header.hash() == header.hash() {
Ok(())
} else {
Err(ErrorKind::Other(format!("{} not on current chain", header.hash())).into())
}
}
/// Finds first of the given hashes that is known on the main chain.
pub fn find_common_header(&mut self, hashes: &Vec<CryptoHash>) -> Option<BlockHeader> {
for hash in hashes {
if let Ok(header) = self.get_block_header(&hash).map(|h| h.clone()) {
if let Ok(header_at_height) = self.get_header_by_height(header.inner.height) {
if header.hash() == header_at_height.hash() {
return Some(header);
}
}
}
}
None
}
fn determine_status(&self, head: Option<Tip>, prev_head: Tip) -> BlockStatus {
let has_head = head.is_some();
let mut is_next_block = false;
let old_hash = if let Some(head) = head {
if head.prev_block_hash == prev_head.last_block_hash {
is_next_block = true;
None
} else {
Some(prev_head.last_block_hash)
}
} else {
None
};
match (has_head, is_next_block) {
(true, true) => BlockStatus::Next,
(true, false) => BlockStatus::Reorg(old_hash.unwrap()),
(false, _) => BlockStatus::Fork,
}
}
pub fn reset_heads_post_state_sync<F, F2>(
&mut self,
me: &Option<AccountId>,
sync_hash: CryptoHash,
block_accepted: F,
block_misses_chunks: F2,
) -> Result<(), Error>
where
F: Copy + FnMut(AcceptedBlock) -> (),
F2: Copy + FnMut(Vec<ShardChunkHeader>) -> (),
{
// Get header we were syncing into.
let header = self.get_block_header(&sync_hash)?;
let hash = header.inner.prev_hash;
let prev_header = self.get_block_header(&hash)?;
let tip = Tip::from_header(prev_header);
// Update related heads now.
let mut chain_store_update = self.mut_store().store_update();
chain_store_update.save_body_head(&tip)?;
chain_store_update.save_body_tail(&tip);
chain_store_update.commit()?;
// Check if there are any orphans unlocked by this state sync.
// We can't fail beyond this point because the caller will not process accepted blocks
// and the blocks with missing chunks if this method fails
self.check_orphans(me, hash, block_accepted, block_misses_chunks);
Ok(())
}
fn start_downloading_state(
&mut self,
me: &Option<AccountId>,
block: &Block,
) -> Result<(), Error> {
let prev_hash = block.header.inner.prev_hash;
let shards_to_dl = self.get_shards_to_dl_state(me, &prev_hash);
let prev_block = self.get_block(&prev_hash)?;
debug!(target: "chain", "Downloading state for {:?}, I'm {:?}", shards_to_dl, me);
let state_dl_info = StateSyncInfo {
epoch_tail_hash: block.header.hash(),
shards: shards_to_dl
.iter()
.map(|shard_id| {
let chunk = &prev_block.chunks[*shard_id as usize];
ShardInfo(*shard_id, chunk.chunk_hash())
})
.collect(),
};
let mut chain_store_update = ChainStoreUpdate::new(&mut self.store);
chain_store_update.add_state_dl_info(state_dl_info);
chain_store_update.commit()?;
Ok(())
}
fn process_block_single<F, F2>(
&mut self,
me: &Option<AccountId>,
block: Block,
provenance: Provenance,
mut block_accepted: F,
mut block_misses_chunks: F2,
) -> Result<Option<Tip>, Error>
where
F: FnMut(AcceptedBlock) -> (),
F2: Copy + FnMut(Vec<ShardChunkHeader>) -> (),
{
near_metrics::inc_counter(&metrics::BLOCK_PROCESSED_TOTAL);
if block.chunks.len() != self.runtime_adapter.num_shards() as usize {
return Err(ErrorKind::IncorrectNumberOfChunkHeaders.into());
}
let prev_head = self.store.head()?;
let mut chain_update = ChainUpdate::new(
&mut self.store,
self.runtime_adapter.clone(),
&self.orphans,
&self.blocks_with_missing_chunks,
self.transaction_validity_period,
);
let maybe_new_head = chain_update.process_block(me, &block, &provenance);
match maybe_new_head {
Ok((head, needs_to_start_fetching_state)) => {
chain_update.commit()?;
if needs_to_start_fetching_state {
debug!("Downloading state for block {}", block.hash());
self.start_downloading_state(me, &block)?;
}
match &head {
Some(tip) => {
near_metrics::set_gauge(
&metrics::VALIDATOR_ACTIVE_TOTAL,
match self
.runtime_adapter
.get_epoch_block_producers(&tip.epoch_id, &tip.last_block_hash)
{
Ok(value) => value
.iter()
.map(|(_, is_slashed)| if *is_slashed { 0 } else { 1 })
.sum(),
Err(_) => 0,
},
);
}
None => {}
}
// Sum validator balances in full NEARs (divided by 10**18)
let sum = block
.header
.inner
.validator_proposals
.iter()
.map(|validator_stake| {
(validator_stake.amount / 1_000_000_000_000_000_000) as i64
})
.sum::<i64>();
near_metrics::set_gauge(&metrics::VALIDATOR_AMOUNT_STAKED, sum);
let status = self.determine_status(head.clone(), prev_head);
// Notify other parts of the system of the update.
block_accepted(AcceptedBlock {
hash: block.hash(),
status,
provenance,
gas_used: block.header.inner.gas_used,
gas_limit: block.header.inner.gas_limit,
});
Ok(head)
}
Err(e) => match e.kind() {
ErrorKind::Orphan => {
let block_hash = block.hash();
let orphan = Orphan { block, provenance, added: Instant::now() };
self.orphans.add(orphan);
debug!(
target: "chain",
"Process block: orphan: {:?}, # orphans {}{}",
block_hash,
self.orphans.len(),
if self.orphans.len_evicted() > 0 {
format!(", # evicted {}", self.orphans.len_evicted())
} else {
String::new()
},
);
Err(ErrorKind::Orphan.into())
}
ErrorKind::ChunksMissing(missing_chunks) => {
let block_hash = block.hash();
block_misses_chunks(missing_chunks.clone());
let orphan = Orphan { block, provenance, added: Instant::now() };
self.blocks_with_missing_chunks.add(orphan);
debug!(
target: "chain",
"Process block: missing chunks. Block hash: {:?}. Missing chunks: {:?}",
block_hash, missing_chunks,
);
Err(ErrorKind::ChunksMissing(missing_chunks).into())
}
ErrorKind::EpochOutOfBounds => {
// Possibly block arrived before we finished processing all of the blocks for epoch before last.
debug!(target: "chain", "Received block {}/{} ignored, as epoch is unknown", block.header.inner.height, block.hash());
Ok(Some(prev_head))
}
ErrorKind::Unfit(ref msg) => {
debug!(
target: "chain",
"Block {} at {} is unfit at this time: {}",
block.hash(),
block.header.inner.height,
msg
);
Err(ErrorKind::Unfit(msg.clone()).into())
}
e => Err(e.into()),
},
}
}
pub fn prev_block_is_caught_up(
&self,
prev_prev_hash: &CryptoHash,
prev_hash: &CryptoHash,
) -> Result<bool, Error> {
// This method is identical to `ChainUpdate::prev_block_is_caught_up`, see important
// disclaimers in there on some dangers of using it
Ok(!self.store.get_blocks_to_catchup(prev_prev_hash)?.contains(&prev_hash))
}
fn get_shards_to_dl_state(
&self,
me: &Option<AccountId>,
parent_hash: &CryptoHash,
) -> Vec<ShardId> {
(0..self.runtime_adapter.num_shards())
.filter(|shard_id| {
self.runtime_adapter.will_care_about_shard(
me.as_ref(),
parent_hash,
*shard_id,
true,
) && !self.runtime_adapter.cares_about_shard(
me.as_ref(),
parent_hash,
*shard_id,
true,
)
})
.collect()
}
/// Check if any block with missing chunk is ready to be processed
pub fn check_blocks_with_missing_chunks<F, F2>(
&mut self,
me: &Option<AccountId>,
prev_hash: CryptoHash,
block_accepted: F,
block_misses_chunks: F2,
) where
F: Copy + FnMut(AcceptedBlock) -> (),
F2: Copy + FnMut(Vec<ShardChunkHeader>) -> (),
{
let mut new_blocks_accepted = vec![];
if let Some(orphans) = self.blocks_with_missing_chunks.remove_by_prev_hash(prev_hash) {
for orphan in orphans.into_iter() {
let block_hash = orphan.block.header.hash();
let res = self.process_block_single(
me,
orphan.block,
orphan.provenance,
block_accepted,
block_misses_chunks,
);
match res {
Ok(_) => {
debug!(target: "chain", "Block with missing chunks is accepted; me: {:?}", me);
new_blocks_accepted.push(block_hash);
}
Err(_) => {
debug!(target: "chain", "Block with missing chunks is declined; me: {:?}", me);
}
}
}
};
for accepted_block in new_blocks_accepted {
self.check_orphans(me, accepted_block, block_accepted, block_misses_chunks);
}
}
/// Check for orphans, once a block is successfully added.
pub fn check_orphans<F, F2>(
&mut self,
me: &Option<AccountId>,
prev_hash: CryptoHash,
block_accepted: F,
block_misses_chunks: F2,
) -> Option<Tip>
where
F: Copy + FnMut(AcceptedBlock) -> (),
F2: Copy + FnMut(Vec<ShardChunkHeader>) -> (),
{
let mut queue = vec![prev_hash];
let mut queue_idx = 0;
let mut maybe_new_head = None;
// Check if there are orphans we can process.
debug!(target: "chain", "Check orphans: from {}, # orphans {}", prev_hash, self.orphans.len());
while queue_idx < queue.len() {
if let Some(orphans) = self.orphans.remove_by_prev_hash(queue[queue_idx]) {
debug!(target: "chain", "Check orphans: found {} orphans", orphans.len());
for orphan in orphans.into_iter() {
let block_hash = orphan.block.hash();
let timer = near_metrics::start_timer(&metrics::BLOCK_PROCESSING_TIME);
let res = self.process_block_single(
me,
orphan.block,
orphan.provenance,
block_accepted,
block_misses_chunks,
);
near_metrics::stop_timer(timer);
match res {
Ok(maybe_tip) => {
near_metrics::inc_counter(&metrics::BLOCK_PROCESSED_SUCCESSFULLY_TOTAL);
maybe_new_head = maybe_tip;
queue.push(block_hash);
}
Err(_) => {
debug!(target: "chain", "Orphan declined");
}
}
}
}
queue_idx += 1;
}
if queue.len() > 1 {
debug!(
target: "chain",
"Check orphans: {} blocks accepted, remaining # orphans {}",
queue.len() - 1,
self.orphans.len(),
);
}
maybe_new_head
}
pub fn get_outgoing_receipts_for_shard(
&mut self,
prev_block_hash: CryptoHash,
shard_id: ShardId,
last_height_included: BlockIndex,
) -> Result<ReceiptResponse, Error> {
self.store.get_outgoing_receipts_for_shard(prev_block_hash, shard_id, last_height_included)
}
pub fn get_state_response_header(
&mut self,
shard_id: ShardId,
sync_hash: CryptoHash,
) -> Result<ShardStateSyncResponseHeader, Error> {
// Consistency rules:
// 1. Everything prefixed with `sync_` indicates new epoch, for which we are syncing.
// 1a. `sync_prev` means the last of the prev epoch.
// 2. Empty prefix means the height where chunk was applied last time in the prev epoch.
// Let's call it `current`.
// 2a. `prev_` means we're working with height before current.
// 3. In inner loops we use all prefixes with no relation to the context described above.
let sync_block = self.get_block(&sync_hash)?;
let sync_block_header = sync_block.header.clone();
if shard_id as usize >= sync_block.chunks.len() {
return Err(ErrorKind::Other("Invalid request: ShardId out of bounds".into()).into());
}
// The chunk was applied at height `chunk_header.height_included`.
// Getting the `current` state.
let sync_prev_block = self.get_block(&sync_block_header.inner.prev_hash)?;
if shard_id as usize >= sync_prev_block.chunks.len() {
return Err(ErrorKind::Other("Invalid request: ShardId out of bounds".into()).into());
}
// Chunk header here is the same chunk header as at the `current` height.
let chunk_header = sync_prev_block.chunks[shard_id as usize].clone();
let (chunk_headers_root, chunk_proofs) = merklize(
&sync_prev_block
.chunks
.iter()
.map(|shard_chunk| {
ChunkHashHeight(shard_chunk.hash.clone(), shard_chunk.height_included)
})
.collect::<Vec<ChunkHashHeight>>(),
);
assert_eq!(chunk_headers_root, sync_prev_block.header.inner.chunk_headers_root);
let chunk = self.get_chunk_clone_from_header(&chunk_header)?;
let chunk_proof = chunk_proofs[shard_id as usize].clone();
let block_header =
self.get_header_on_chain_by_height(&sync_hash, chunk_header.height_included)?.clone();
// Collecting the `prev` state.
let prev_block = self.get_block(&block_header.inner.prev_hash)?;
if shard_id as usize >= prev_block.chunks.len() {
return Err(ErrorKind::Other("Invalid request: ShardId out of bounds".into()).into());
}
let prev_chunk_header = prev_block.chunks[shard_id as usize].clone();
let (prev_chunk_headers_root, prev_chunk_proofs) = merklize(
&prev_block
.chunks
.iter()
.map(|shard_chunk| {
ChunkHashHeight(shard_chunk.hash.clone(), shard_chunk.height_included)
})
.collect::<Vec<ChunkHashHeight>>(),
);
assert_eq!(prev_chunk_headers_root, prev_block.header.inner.chunk_headers_root);
let prev_chunk_proof = prev_chunk_proofs[shard_id as usize].clone();
let prev_chunk_height_included = prev_chunk_header.height_included;
// Getting all existing incoming_receipts from prev_chunk height to the new epoch.
let incoming_receipts_proofs = ChainStoreUpdate::new(&mut self.store)
.get_incoming_receipts_for_shard(shard_id, sync_hash, prev_chunk_height_included)?
.clone();
// Collecting proofs for incoming receipts.
let mut root_proofs = vec![];
for receipt_response in incoming_receipts_proofs.iter() {
let ReceiptProofResponse(block_hash, receipt_proofs) = receipt_response;
let block_header = self.get_block_header(&block_hash)?.clone();
let block = self.get_block(&block_hash)?;
let (block_receipts_root, block_receipts_proofs) = merklize(
&block
.chunks
.iter()
.map(|chunk| chunk.inner.outgoing_receipts_root)
.collect::<Vec<CryptoHash>>(),
);
let mut root_proofs_cur = vec![];
assert_eq!(receipt_proofs.len(), block_header.inner.chunks_included as usize);
for receipt_proof in receipt_proofs {
let ReceiptProof(receipts, shard_proof) = receipt_proof;
let ShardProof { from_shard_id, to_shard_id: _, proof } = shard_proof;
let receipts_hash = hash(&ReceiptList(shard_id, receipts.to_vec()).try_to_vec()?);
let from_shard_id = *from_shard_id as usize;
let root_proof = block.chunks[from_shard_id].inner.outgoing_receipts_root;
root_proofs_cur
.push(RootProof(root_proof, block_receipts_proofs[from_shard_id].clone()));
// Make sure we send something reasonable.
assert_eq!(block_header.inner.chunk_receipts_root, block_receipts_root);
assert!(verify_path(root_proof, &proof, &receipts_hash));
assert!(verify_path(
block_receipts_root,
&block_receipts_proofs[from_shard_id],
&root_proof,
));
}
root_proofs.push(root_proofs_cur);
}
Ok(ShardStateSyncResponseHeader {
chunk,
chunk_proof,
prev_chunk_header,
prev_chunk_proof,
incoming_receipts_proofs,
root_proofs,
})
}
pub fn get_state_response_part(
&mut self,
shard_id: ShardId,
part_id: u64,
sync_hash: CryptoHash,
) -> Result<ShardStateSyncResponsePart, Error> {
let sync_block = self.get_block(&sync_hash)?;
let sync_block_header = sync_block.header.clone();
if shard_id as usize >= sync_block.chunks.len() {
return Err(ErrorKind::Other(
"get_syncing_state_root fail: shard_id out of bounds".into(),
)
.into());
}
let sync_prev_block = self.get_block(&sync_block_header.inner.prev_hash)?;
if shard_id as usize >= sync_prev_block.chunks.len() {
return Err(ErrorKind::Other(
"get_syncing_state_root fail: shard_id out of bounds".into(),
)
.into());
}
let state_root = sync_prev_block.chunks[shard_id as usize].inner.prev_state_root.clone();