-
Notifications
You must be signed in to change notification settings - Fork 635
/
block_header.rs
973 lines (892 loc) · 36.9 KB
/
block_header.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
use borsh::{BorshDeserialize, BorshSerialize};
use chrono::{DateTime, Utc};
use serde::Serialize;
use near_crypto::{KeyType, PublicKey, Signature};
use crate::challenge::ChallengesResult;
use crate::hash::{hash, CryptoHash};
use crate::merkle::combine_hash;
use crate::network::PeerId;
use crate::types::validator_stake::{ValidatorStake, ValidatorStakeIter, ValidatorStakeV1};
use crate::types::{AccountId, Balance, BlockHeight, EpochId, MerkleHash, NumBlocks};
use crate::utils::{from_timestamp, to_timestamp};
use crate::validator_signer::ValidatorSigner;
use crate::version::{ProtocolVersion, PROTOCOL_VERSION};
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub struct BlockHeaderInnerLite {
/// Height of this block.
pub height: BlockHeight,
/// Epoch start hash of this block's epoch.
/// Used for retrieving validator information
pub epoch_id: EpochId,
pub next_epoch_id: EpochId,
/// Root hash of the state at the previous block.
pub prev_state_root: MerkleHash,
/// Root of the outcomes of transactions and receipts.
pub outcome_root: MerkleHash,
/// Timestamp at which the block was built (number of non-leap-nanoseconds since January 1, 1970 0:00:00 UTC).
pub timestamp: u64,
/// Hash of the next epoch block producers set
pub next_bp_hash: CryptoHash,
/// Merkle root of block hashes up to the current block.
pub block_merkle_root: CryptoHash,
}
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub struct BlockHeaderInnerRest {
/// Root hash of the chunk receipts in the given block.
pub chunk_receipts_root: MerkleHash,
/// Root hash of the chunk headers in the given block.
pub chunk_headers_root: MerkleHash,
/// Root hash of the chunk transactions in the given block.
pub chunk_tx_root: MerkleHash,
/// Number of chunks included into the block.
pub chunks_included: u64,
/// Root hash of the challenges in the given block.
pub challenges_root: MerkleHash,
/// The output of the randomness beacon
pub random_value: CryptoHash,
/// Validator proposals.
pub validator_proposals: Vec<ValidatorStakeV1>,
/// Mask for new chunks included in the block
pub chunk_mask: Vec<bool>,
/// Gas price. Same for all chunks
pub gas_price: Balance,
/// Total supply of tokens in the system
pub total_supply: Balance,
/// List of challenges result from previous block.
pub challenges_result: ChallengesResult,
/// Last block that has full BFT finality
pub last_final_block: CryptoHash,
/// Last block that has doomslug finality
pub last_ds_final_block: CryptoHash,
/// All the approvals included in this block
pub approvals: Vec<Option<Signature>>,
/// Latest protocol version that this block producer has.
pub latest_protocol_version: ProtocolVersion,
}
/// Remove `chunks_included` from V1
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub struct BlockHeaderInnerRestV2 {
/// Root hash of the chunk receipts in the given block.
pub chunk_receipts_root: MerkleHash,
/// Root hash of the chunk headers in the given block.
pub chunk_headers_root: MerkleHash,
/// Root hash of the chunk transactions in the given block.
pub chunk_tx_root: MerkleHash,
/// Root hash of the challenges in the given block.
pub challenges_root: MerkleHash,
/// The output of the randomness beacon
pub random_value: CryptoHash,
/// Validator proposals.
pub validator_proposals: Vec<ValidatorStakeV1>,
/// Mask for new chunks included in the block
pub chunk_mask: Vec<bool>,
/// Gas price. Same for all chunks
pub gas_price: Balance,
/// Total supply of tokens in the system
pub total_supply: Balance,
/// List of challenges result from previous block.
pub challenges_result: ChallengesResult,
/// Last block that has full BFT finality
pub last_final_block: CryptoHash,
/// Last block that has doomslug finality
pub last_ds_final_block: CryptoHash,
/// All the approvals included in this block
pub approvals: Vec<Option<Signature>>,
/// Latest protocol version that this block producer has.
pub latest_protocol_version: ProtocolVersion,
}
/// Add `prev_height`
/// Add `block_ordinal`
/// Add `epoch_sync_data_hash`
/// Use new `ValidatorStake` struct
#[cfg(feature = "protocol_feature_block_header_v3")]
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub struct BlockHeaderInnerRestV3 {
/// Root hash of the chunk receipts in the given block.
pub chunk_receipts_root: MerkleHash,
/// Root hash of the chunk headers in the given block.
pub chunk_headers_root: MerkleHash,
/// Root hash of the chunk transactions in the given block.
pub chunk_tx_root: MerkleHash,
/// Root hash of the challenges in the given block.
pub challenges_root: MerkleHash,
/// The output of the randomness beacon
pub random_value: CryptoHash,
/// Validator proposals.
pub validator_proposals: Vec<ValidatorStake>,
/// Mask for new chunks included in the block
pub chunk_mask: Vec<bool>,
/// Gas price. Same for all chunks
pub gas_price: Balance,
/// Total supply of tokens in the system
pub total_supply: Balance,
/// List of challenges result from previous block.
pub challenges_result: ChallengesResult,
/// Last block that has full BFT finality
pub last_final_block: CryptoHash,
/// Last block that has doomslug finality
pub last_ds_final_block: CryptoHash,
/// The ordinal of the Block on the Canonical Chain
pub block_ordinal: NumBlocks,
pub prev_height: BlockHeight,
pub epoch_sync_data_hash: Option<CryptoHash>,
/// All the approvals included in this block
pub approvals: Vec<Option<Signature>>,
/// Latest protocol version that this block producer has.
pub latest_protocol_version: ProtocolVersion,
}
/// The part of the block approval that is different for endorsements and skips
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, PartialEq, Eq, Hash)]
pub enum ApprovalInner {
Endorsement(CryptoHash),
Skip(BlockHeight),
}
/// Block approval by other block producers with a signature
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct Approval {
pub inner: ApprovalInner,
pub target_height: BlockHeight,
pub signature: Signature,
pub account_id: AccountId,
}
/// The type of approvals. It is either approval from self or from a peer
#[derive(PartialEq, Eq, Debug)]
pub enum ApprovalType {
SelfApproval,
PeerApproval(PeerId),
}
/// Block approval by other block producers.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct ApprovalMessage {
pub approval: Approval,
pub target: AccountId,
}
impl ApprovalInner {
pub fn new(
parent_hash: &CryptoHash,
parent_height: BlockHeight,
target_height: BlockHeight,
) -> Self {
if target_height == parent_height + 1 {
ApprovalInner::Endorsement(parent_hash.clone())
} else {
ApprovalInner::Skip(parent_height)
}
}
}
impl Approval {
pub fn new(
parent_hash: CryptoHash,
parent_height: BlockHeight,
target_height: BlockHeight,
signer: &dyn ValidatorSigner,
) -> Self {
let inner = ApprovalInner::new(&parent_hash, parent_height, target_height);
let signature = signer.sign_approval(&inner, target_height);
Approval { inner, target_height, signature, account_id: signer.validator_id().clone() }
}
pub fn get_data_for_sig(inner: &ApprovalInner, target_height: BlockHeight) -> Vec<u8> {
[inner.try_to_vec().unwrap().as_ref(), target_height.to_le_bytes().as_ref()].concat()
}
}
impl ApprovalMessage {
pub fn new(approval: Approval, target: AccountId) -> Self {
ApprovalMessage { approval, target }
}
}
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
#[borsh_init(init)]
pub struct BlockHeaderV1 {
pub prev_hash: CryptoHash,
/// Inner part of the block header that gets hashed, split into two parts, one that is sent
/// to light clients, and the rest
pub inner_lite: BlockHeaderInnerLite,
pub inner_rest: BlockHeaderInnerRest,
/// Signature of the block producer.
pub signature: Signature,
/// Cached value of hash for this block.
#[borsh_skip]
pub hash: CryptoHash,
}
impl BlockHeaderV1 {
pub fn init(&mut self) {
self.hash = BlockHeader::compute_hash(
self.prev_hash,
&self.inner_lite.try_to_vec().expect("Failed to serialize"),
&self.inner_rest.try_to_vec().expect("Failed to serialize"),
);
}
}
/// V1 -> V2: Remove `chunks_included` from `inner_reset`
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
#[borsh_init(init)]
pub struct BlockHeaderV2 {
pub prev_hash: CryptoHash,
/// Inner part of the block header that gets hashed, split into two parts, one that is sent
/// to light clients, and the rest
pub inner_lite: BlockHeaderInnerLite,
pub inner_rest: BlockHeaderInnerRestV2,
/// Signature of the block producer.
pub signature: Signature,
/// Cached value of hash for this block.
#[borsh_skip]
pub hash: CryptoHash,
}
/// V2 -> V3: Add `prev_height` to `inner_rest` and use new `ValidatorStake`
// Add `block_ordinal` to `inner_rest`
#[cfg(feature = "protocol_feature_block_header_v3")]
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
#[borsh_init(init)]
pub struct BlockHeaderV3 {
pub prev_hash: CryptoHash,
/// Inner part of the block header that gets hashed, split into two parts, one that is sent
/// to light clients, and the rest
pub inner_lite: BlockHeaderInnerLite,
pub inner_rest: BlockHeaderInnerRestV3,
/// Signature of the block producer.
pub signature: Signature,
/// Cached value of hash for this block.
#[borsh_skip]
pub hash: CryptoHash,
}
impl BlockHeaderV2 {
pub fn init(&mut self) {
self.hash = BlockHeader::compute_hash(
self.prev_hash,
&self.inner_lite.try_to_vec().expect("Failed to serialize"),
&self.inner_rest.try_to_vec().expect("Failed to serialize"),
);
}
}
#[cfg(feature = "protocol_feature_block_header_v3")]
impl BlockHeaderV3 {
pub fn init(&mut self) {
self.hash = BlockHeader::compute_hash(
self.prev_hash,
&self.inner_lite.try_to_vec().expect("Failed to serialize"),
&self.inner_rest.try_to_vec().expect("Failed to serialize"),
);
}
}
/// Versioned BlockHeader data structure.
/// For each next version, document what are the changes between versions.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub enum BlockHeader {
BlockHeaderV1(Box<BlockHeaderV1>),
BlockHeaderV2(Box<BlockHeaderV2>),
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeaderV3(Box<BlockHeaderV3>),
}
impl BlockHeader {
pub fn compute_inner_hash(inner_lite: &[u8], inner_rest: &[u8]) -> CryptoHash {
let hash_lite = hash(inner_lite);
let hash_rest = hash(inner_rest);
combine_hash(hash_lite, hash_rest)
}
pub fn compute_hash(prev_hash: CryptoHash, inner_lite: &[u8], inner_rest: &[u8]) -> CryptoHash {
let hash_inner = BlockHeader::compute_inner_hash(inner_lite, inner_rest);
return combine_hash(hash_inner, prev_hash);
}
pub fn new(
protocol_version: ProtocolVersion,
height: BlockHeight,
prev_hash: CryptoHash,
prev_state_root: MerkleHash,
chunk_receipts_root: MerkleHash,
chunk_headers_root: MerkleHash,
chunk_tx_root: MerkleHash,
outcome_root: MerkleHash,
timestamp: u64,
challenges_root: MerkleHash,
random_value: CryptoHash,
validator_proposals: Vec<ValidatorStake>,
chunk_mask: Vec<bool>,
#[cfg(feature = "protocol_feature_block_header_v3")] block_ordinal: NumBlocks,
epoch_id: EpochId,
next_epoch_id: EpochId,
gas_price: Balance,
total_supply: Balance,
challenges_result: ChallengesResult,
signer: &dyn ValidatorSigner,
last_final_block: CryptoHash,
last_ds_final_block: CryptoHash,
#[cfg(feature = "protocol_feature_block_header_v3")] epoch_sync_data_hash: Option<
CryptoHash,
>,
approvals: Vec<Option<Signature>>,
next_bp_hash: CryptoHash,
block_merkle_root: CryptoHash,
#[cfg(feature = "protocol_feature_block_header_v3")] prev_height: BlockHeight,
) -> Self {
let inner_lite = BlockHeaderInnerLite {
height,
epoch_id,
next_epoch_id,
prev_state_root,
outcome_root,
timestamp,
next_bp_hash,
block_merkle_root,
};
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
let last_header_v2_version: Option<u32> = None;
#[cfg(feature = "protocol_feature_block_header_v3")]
let last_header_v2_version =
Some(crate::version::ProtocolFeature::BlockHeaderV3.protocol_version() - 1);
if protocol_version <= 29 {
let chunks_included = chunk_mask.iter().map(|val| *val as u64).sum::<u64>();
let inner_rest = BlockHeaderInnerRest {
chunk_receipts_root,
chunk_headers_root,
chunk_tx_root,
chunks_included,
challenges_root,
random_value,
#[cfg(feature = "protocol_feature_block_header_v3")]
validator_proposals: validator_proposals.into_iter().map(|v| v.into_v1()).collect(),
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
validator_proposals,
chunk_mask,
gas_price,
total_supply,
challenges_result,
last_final_block,
last_ds_final_block,
approvals,
latest_protocol_version: PROTOCOL_VERSION,
};
let (hash, signature) = signer.sign_block_header_parts(
prev_hash,
&inner_lite.try_to_vec().expect("Failed to serialize"),
&inner_rest.try_to_vec().expect("Failed to serialize"),
);
Self::BlockHeaderV1(Box::new(BlockHeaderV1 {
prev_hash,
inner_lite,
inner_rest,
signature,
hash,
}))
} else if last_header_v2_version.is_none()
|| protocol_version <= last_header_v2_version.unwrap()
{
let inner_rest = BlockHeaderInnerRestV2 {
chunk_receipts_root,
chunk_headers_root,
chunk_tx_root,
challenges_root,
random_value,
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
validator_proposals,
#[cfg(feature = "protocol_feature_block_header_v3")]
validator_proposals: validator_proposals.into_iter().map(|v| v.into_v1()).collect(),
chunk_mask,
gas_price,
total_supply,
challenges_result,
last_final_block,
last_ds_final_block,
approvals,
latest_protocol_version: PROTOCOL_VERSION,
};
let (hash, signature) = signer.sign_block_header_parts(
prev_hash,
&inner_lite.try_to_vec().expect("Failed to serialize"),
&inner_rest.try_to_vec().expect("Failed to serialize"),
);
Self::BlockHeaderV2(Box::new(BlockHeaderV2 {
prev_hash,
inner_lite,
inner_rest,
signature,
hash,
}))
} else {
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
unreachable!();
#[cfg(feature = "protocol_feature_block_header_v3")]
{
let inner_rest = BlockHeaderInnerRestV3 {
chunk_receipts_root,
chunk_headers_root,
chunk_tx_root,
challenges_root,
random_value,
validator_proposals,
chunk_mask,
gas_price,
block_ordinal,
total_supply,
challenges_result,
last_final_block,
last_ds_final_block,
prev_height,
epoch_sync_data_hash,
approvals,
latest_protocol_version: PROTOCOL_VERSION,
};
let (hash, signature) = signer.sign_block_header_parts(
prev_hash,
&inner_lite.try_to_vec().expect("Failed to serialize"),
&inner_rest.try_to_vec().expect("Failed to serialize"),
);
Self::BlockHeaderV3(Box::new(BlockHeaderV3 {
prev_hash,
inner_lite,
inner_rest,
signature,
hash,
}))
}
}
}
pub fn genesis(
genesis_protocol_version: ProtocolVersion,
height: BlockHeight,
state_root: MerkleHash,
chunk_receipts_root: MerkleHash,
chunk_headers_root: MerkleHash,
chunk_tx_root: MerkleHash,
num_shards: u64,
challenges_root: MerkleHash,
timestamp: DateTime<Utc>,
initial_gas_price: Balance,
initial_total_supply: Balance,
next_bp_hash: CryptoHash,
) -> Self {
let chunks_included = if height == 0 { num_shards } else { 0 };
let inner_lite = BlockHeaderInnerLite {
height,
epoch_id: EpochId::default(),
next_epoch_id: EpochId::default(),
prev_state_root: state_root,
outcome_root: CryptoHash::default(),
timestamp: to_timestamp(timestamp),
next_bp_hash,
block_merkle_root: CryptoHash::default(),
};
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
let last_header_v2_version: Option<u32> = None;
#[cfg(feature = "protocol_feature_block_header_v3")]
let last_header_v2_version =
Some(crate::version::ProtocolFeature::BlockHeaderV3.protocol_version() - 1);
if genesis_protocol_version <= 29 {
let inner_rest = BlockHeaderInnerRest {
chunk_receipts_root,
chunk_headers_root,
chunk_tx_root,
chunks_included,
challenges_root,
random_value: CryptoHash::default(),
validator_proposals: vec![],
chunk_mask: vec![],
gas_price: initial_gas_price,
total_supply: initial_total_supply,
challenges_result: vec![],
last_final_block: CryptoHash::default(),
last_ds_final_block: CryptoHash::default(),
approvals: vec![],
latest_protocol_version: genesis_protocol_version,
};
let hash = BlockHeader::compute_hash(
CryptoHash::default(),
&inner_lite.try_to_vec().expect("Failed to serialize"),
&inner_rest.try_to_vec().expect("Failed to serialize"),
);
Self::BlockHeaderV1(Box::new(BlockHeaderV1 {
prev_hash: CryptoHash::default(),
inner_lite,
inner_rest,
signature: Signature::empty(KeyType::ED25519),
hash,
}))
} else if last_header_v2_version.is_none()
|| genesis_protocol_version <= last_header_v2_version.unwrap()
{
let inner_rest = BlockHeaderInnerRestV2 {
chunk_receipts_root,
chunk_headers_root,
chunk_tx_root,
challenges_root,
random_value: CryptoHash::default(),
validator_proposals: vec![],
chunk_mask: vec![true; chunks_included as usize],
gas_price: initial_gas_price,
total_supply: initial_total_supply,
challenges_result: vec![],
last_final_block: CryptoHash::default(),
last_ds_final_block: CryptoHash::default(),
approvals: vec![],
latest_protocol_version: genesis_protocol_version,
};
let hash = BlockHeader::compute_hash(
CryptoHash::default(),
&inner_lite.try_to_vec().expect("Failed to serialize"),
&inner_rest.try_to_vec().expect("Failed to serialize"),
);
Self::BlockHeaderV2(Box::new(BlockHeaderV2 {
prev_hash: CryptoHash::default(),
inner_lite,
inner_rest,
signature: Signature::empty(KeyType::ED25519),
hash,
}))
} else {
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
unreachable!();
#[cfg(feature = "protocol_feature_block_header_v3")]
{
let inner_rest = BlockHeaderInnerRestV3 {
chunk_receipts_root,
chunk_headers_root,
chunk_tx_root,
challenges_root,
random_value: CryptoHash::default(),
validator_proposals: vec![],
chunk_mask: vec![true; chunks_included as usize],
block_ordinal: 1, // It is guaranteed that Chain has the only Block which is Genesis
gas_price: initial_gas_price,
total_supply: initial_total_supply,
challenges_result: vec![],
last_final_block: CryptoHash::default(),
last_ds_final_block: CryptoHash::default(),
prev_height: 0,
epoch_sync_data_hash: None, // Epoch Sync cannot be executed up to Genesis
approvals: vec![],
latest_protocol_version: genesis_protocol_version,
};
let hash = BlockHeader::compute_hash(
CryptoHash::default(),
&inner_lite.try_to_vec().expect("Failed to serialize"),
&inner_rest.try_to_vec().expect("Failed to serialize"),
);
Self::BlockHeaderV3(Box::new(BlockHeaderV3 {
prev_hash: CryptoHash::default(),
inner_lite,
inner_rest,
signature: Signature::empty(KeyType::ED25519),
hash,
}))
}
}
}
#[inline]
pub fn hash(&self) -> &CryptoHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.hash,
BlockHeader::BlockHeaderV2(header) => &header.hash,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.hash,
}
}
#[inline]
pub fn prev_hash(&self) -> &CryptoHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.prev_hash,
BlockHeader::BlockHeaderV2(header) => &header.prev_hash,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.prev_hash,
}
}
#[inline]
pub fn signature(&self) -> &Signature {
match self {
BlockHeader::BlockHeaderV1(header) => &header.signature,
BlockHeader::BlockHeaderV2(header) => &header.signature,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.signature,
}
}
#[inline]
pub fn height(&self) -> BlockHeight {
match self {
BlockHeader::BlockHeaderV1(header) => header.inner_lite.height,
BlockHeader::BlockHeaderV2(header) => header.inner_lite.height,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => header.inner_lite.height,
}
}
#[inline]
#[cfg(feature = "protocol_feature_block_header_v3")]
pub fn prev_height(&self) -> Option<BlockHeight> {
match self {
BlockHeader::BlockHeaderV1(_) => None,
BlockHeader::BlockHeaderV2(_) => None,
BlockHeader::BlockHeaderV3(header) => Some(header.inner_rest.prev_height),
}
}
#[inline]
pub fn epoch_id(&self) -> &EpochId {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_lite.epoch_id,
BlockHeader::BlockHeaderV2(header) => &header.inner_lite.epoch_id,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_lite.epoch_id,
}
}
#[inline]
pub fn next_epoch_id(&self) -> &EpochId {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_lite.next_epoch_id,
BlockHeader::BlockHeaderV2(header) => &header.inner_lite.next_epoch_id,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_lite.next_epoch_id,
}
}
#[inline]
pub fn prev_state_root(&self) -> &MerkleHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_lite.prev_state_root,
BlockHeader::BlockHeaderV2(header) => &header.inner_lite.prev_state_root,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_lite.prev_state_root,
}
}
#[inline]
pub fn chunk_receipts_root(&self) -> &MerkleHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.chunk_receipts_root,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.chunk_receipts_root,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.chunk_receipts_root,
}
}
#[inline]
pub fn chunk_headers_root(&self) -> &MerkleHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.chunk_headers_root,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.chunk_headers_root,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.chunk_headers_root,
}
}
#[inline]
pub fn chunk_tx_root(&self) -> &MerkleHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.chunk_tx_root,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.chunk_tx_root,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.chunk_tx_root,
}
}
pub fn chunks_included(&self) -> u64 {
match self {
BlockHeader::BlockHeaderV1(header) => header.inner_rest.chunks_included,
BlockHeader::BlockHeaderV2(header) => {
header.inner_rest.chunk_mask.iter().map(|&x| u64::from(x)).sum::<u64>()
}
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => {
header.inner_rest.chunk_mask.iter().map(|&x| u64::from(x)).sum::<u64>()
}
}
}
#[inline]
pub fn challenges_root(&self) -> &MerkleHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.challenges_root,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.challenges_root,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.challenges_root,
}
}
#[inline]
pub fn outcome_root(&self) -> &MerkleHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_lite.outcome_root,
BlockHeader::BlockHeaderV2(header) => &header.inner_lite.outcome_root,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_lite.outcome_root,
}
}
#[inline]
pub fn raw_timestamp(&self) -> u64 {
match self {
BlockHeader::BlockHeaderV1(header) => header.inner_lite.timestamp,
BlockHeader::BlockHeaderV2(header) => header.inner_lite.timestamp,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => header.inner_lite.timestamp,
}
}
#[inline]
pub fn validator_proposals(&self) -> ValidatorStakeIter {
match self {
BlockHeader::BlockHeaderV1(header) => {
ValidatorStakeIter::v1(&header.inner_rest.validator_proposals)
}
BlockHeader::BlockHeaderV2(header) => {
ValidatorStakeIter::v1(&header.inner_rest.validator_proposals)
}
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => {
ValidatorStakeIter::new(&header.inner_rest.validator_proposals)
}
}
}
#[inline]
pub fn chunk_mask(&self) -> &[bool] {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.chunk_mask,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.chunk_mask,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.chunk_mask,
}
}
#[inline]
pub fn block_ordinal(&self) -> NumBlocks {
match self {
BlockHeader::BlockHeaderV1(_) => 0, // not applicable
BlockHeader::BlockHeaderV2(_) => 0, // not applicable
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => header.inner_rest.block_ordinal,
}
}
#[inline]
pub fn gas_price(&self) -> Balance {
match self {
BlockHeader::BlockHeaderV1(header) => header.inner_rest.gas_price,
BlockHeader::BlockHeaderV2(header) => header.inner_rest.gas_price,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => header.inner_rest.gas_price,
}
}
#[inline]
pub fn total_supply(&self) -> Balance {
match self {
BlockHeader::BlockHeaderV1(header) => header.inner_rest.total_supply,
BlockHeader::BlockHeaderV2(header) => header.inner_rest.total_supply,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => header.inner_rest.total_supply,
}
}
#[inline]
pub fn random_value(&self) -> &CryptoHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.random_value,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.random_value,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.random_value,
}
}
#[inline]
pub fn last_final_block(&self) -> &CryptoHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.last_final_block,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.last_final_block,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.last_final_block,
}
}
#[inline]
pub fn last_ds_final_block(&self) -> &CryptoHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.last_ds_final_block,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.last_ds_final_block,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.last_ds_final_block,
}
}
#[inline]
pub fn challenges_result(&self) -> &ChallengesResult {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.challenges_result,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.challenges_result,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.challenges_result,
}
}
#[inline]
pub fn next_bp_hash(&self) -> &CryptoHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_lite.next_bp_hash,
BlockHeader::BlockHeaderV2(header) => &header.inner_lite.next_bp_hash,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_lite.next_bp_hash,
}
}
#[inline]
pub fn block_merkle_root(&self) -> &CryptoHash {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_lite.block_merkle_root,
BlockHeader::BlockHeaderV2(header) => &header.inner_lite.block_merkle_root,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_lite.block_merkle_root,
}
}
#[inline]
pub fn epoch_sync_data_hash(&self) -> Option<CryptoHash> {
match self {
BlockHeader::BlockHeaderV1(_) => None,
BlockHeader::BlockHeaderV2(_) => None,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => header.inner_rest.epoch_sync_data_hash,
}
}
#[inline]
pub fn approvals(&self) -> &[Option<Signature>] {
match self {
BlockHeader::BlockHeaderV1(header) => &header.inner_rest.approvals,
BlockHeader::BlockHeaderV2(header) => &header.inner_rest.approvals,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => &header.inner_rest.approvals,
}
}
/// Verifies that given public key produced the block.
pub fn verify_block_producer(&self, public_key: &PublicKey) -> bool {
self.signature().verify(self.hash().as_ref(), public_key)
}
pub fn timestamp(&self) -> DateTime<Utc> {
from_timestamp(self.raw_timestamp())
}
pub fn num_approvals(&self) -> u64 {
self.approvals().iter().filter(|x| x.is_some()).count() as u64
}
pub fn verify_chunks_included(&self) -> bool {
match self {
BlockHeader::BlockHeaderV1(header) => {
header.inner_rest.chunk_mask.iter().map(|&x| u64::from(x)).sum::<u64>()
== header.inner_rest.chunks_included
}
BlockHeader::BlockHeaderV2(_header) => true,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(_header) => true,
}
}
#[inline]
pub fn latest_protocol_version(&self) -> u32 {
match self {
BlockHeader::BlockHeaderV1(header) => header.inner_rest.latest_protocol_version,
BlockHeader::BlockHeaderV2(header) => header.inner_rest.latest_protocol_version,
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => header.inner_rest.latest_protocol_version,
}
}
pub fn inner_lite_bytes(&self) -> Vec<u8> {
match self {
BlockHeader::BlockHeaderV1(header) => {
header.inner_lite.try_to_vec().expect("Failed to serialize")
}
BlockHeader::BlockHeaderV2(header) => {
header.inner_lite.try_to_vec().expect("Failed to serialize")
}
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => {
header.inner_lite.try_to_vec().expect("Failed to serialize")
}
}
}
pub fn inner_rest_bytes(&self) -> Vec<u8> {
match self {
BlockHeader::BlockHeaderV1(header) => {
header.inner_rest.try_to_vec().expect("Failed to serialize")
}
BlockHeader::BlockHeaderV2(header) => {
header.inner_rest.try_to_vec().expect("Failed to serialize")
}
#[cfg(feature = "protocol_feature_block_header_v3")]
BlockHeader::BlockHeaderV3(header) => {
header.inner_rest.try_to_vec().expect("Failed to serialize")
}
}
}
}