forked from sigp/lighthouse
/
beacon_state.rs
1697 lines (1517 loc) · 61.5 KB
/
beacon_state.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 self::committee_cache::get_active_validator_indices;
use self::exit_cache::ExitCache;
use crate::test_utils::TestRandom;
use crate::*;
use compare_fields::CompareFields;
use compare_fields_derive::CompareFields;
use derivative::Derivative;
use eth2_hashing::hash;
use int_to_bytes::{int_to_bytes4, int_to_bytes8};
use pubkey_cache::PubkeyCache;
use safe_arith::{ArithError, SafeArith};
use serde_derive::{Deserialize, Serialize};
use ssz::{ssz_encode, Decode, DecodeError, Encode};
use ssz_derive::{Decode, Encode};
use ssz_types::{typenum::Unsigned, BitVector, FixedVector};
use std::convert::TryInto;
use std::{fmt, mem, sync::Arc};
use superstruct::superstruct;
use swap_or_not_shuffle::compute_shuffled_index;
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::TreeHash;
pub use self::committee_cache::{
compute_committee_index_in_epoch, compute_committee_range_in_epoch, epoch_committee_count,
CommitteeCache,
};
pub use clone_config::CloneConfig;
pub use eth_spec::*;
pub use iter::BlockRootsIter;
pub use tree_hash_cache::BeaconTreeHashCache;
#[macro_use]
mod committee_cache;
mod clone_config;
mod exit_cache;
mod iter;
mod pubkey_cache;
mod tests;
mod tree_hash_cache;
pub const CACHED_EPOCHS: usize = 3;
const MAX_RANDOM_BYTE: u64 = (1 << 8) - 1;
#[derive(Debug, PartialEq, Clone)]
pub enum Error {
/// A state for a different hard-fork was required -- a severe logic error.
IncorrectStateVariant,
EpochOutOfBounds,
SlotOutOfBounds,
UnknownValidator(usize),
UnableToDetermineProducer,
InvalidBitfield,
ValidatorIsWithdrawable,
ValidatorIsInactive {
val_index: usize,
},
UnableToShuffle,
ShuffleIndexOutOfBounds(usize),
IsAggregatorOutOfBounds,
BlockRootsOutOfBounds(usize),
StateRootsOutOfBounds(usize),
SlashingsOutOfBounds(usize),
BalancesOutOfBounds(usize),
RandaoMixesOutOfBounds(usize),
CommitteeCachesOutOfBounds(usize),
ParticipationOutOfBounds(usize),
InactivityScoresOutOfBounds(usize),
TooManyValidators,
InsufficientValidators,
InsufficientRandaoMixes,
InsufficientBlockRoots,
InsufficientIndexRoots,
InsufficientAttestations,
InsufficientCommittees,
InsufficientStateRoots,
NoCommittee {
slot: Slot,
index: CommitteeIndex,
},
ZeroSlotsPerEpoch,
PubkeyCacheInconsistent,
PubkeyCacheIncomplete {
cache_len: usize,
registry_len: usize,
},
PreviousCommitteeCacheUninitialized,
CurrentCommitteeCacheUninitialized,
TotalActiveBalanceCacheUninitialized,
TotalActiveBalanceCacheInconsistent {
initialized_epoch: Epoch,
current_epoch: Epoch,
},
RelativeEpochError(RelativeEpochError),
ExitCacheUninitialized,
CommitteeCacheUninitialized(Option<RelativeEpoch>),
SyncCommitteeCacheUninitialized,
BlsError(bls::Error),
SszTypesError(ssz_types::Error),
TreeHashCacheNotInitialized,
NonLinearTreeHashCacheHistory,
TreeHashCacheSkippedSlot {
cache: Slot,
state: Slot,
},
TreeHashError(tree_hash::Error),
CachedTreeHashError(cached_tree_hash::Error),
InvalidValidatorPubkey(ssz::DecodeError),
ValidatorRegistryShrunk,
TreeHashCacheInconsistent,
InvalidDepositState {
deposit_count: u64,
deposit_index: u64,
},
/// Attestation slipped through block processing with a non-matching source.
IncorrectAttestationSource,
/// An arithmetic operation occurred which would have overflowed or divided by 0.
///
/// This represents a serious bug in either the spec or Lighthouse!
ArithError(ArithError),
MissingBeaconBlock(SignedBeaconBlockHash),
MissingBeaconState(BeaconStateHash),
SyncCommitteeNotKnown {
current_epoch: Epoch,
epoch: Epoch,
},
}
/// Control whether an epoch-indexed field can be indexed at the next epoch or not.
#[derive(Debug, PartialEq, Clone, Copy)]
enum AllowNextEpoch {
True,
False,
}
impl AllowNextEpoch {
fn upper_bound_of(self, current_epoch: Epoch) -> Result<Epoch, Error> {
match self {
AllowNextEpoch::True => Ok(current_epoch.safe_add(1)?),
AllowNextEpoch::False => Ok(current_epoch),
}
}
}
#[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))]
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct BeaconStateHash(Hash256);
impl fmt::Debug for BeaconStateHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BeaconStateHash({:?})", self.0)
}
}
impl fmt::Display for BeaconStateHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<Hash256> for BeaconStateHash {
fn from(hash: Hash256) -> BeaconStateHash {
BeaconStateHash(hash)
}
}
impl From<BeaconStateHash> for Hash256 {
fn from(beacon_state_hash: BeaconStateHash) -> Hash256 {
beacon_state_hash.0
}
}
/// The state of the `BeaconChain` at some slot.
#[superstruct(
variants(Base, Altair, Merge),
variant_attributes(
derive(
Derivative,
Debug,
PartialEq,
Serialize,
Deserialize,
Encode,
Decode,
TreeHash,
TestRandom,
CompareFields,
),
serde(bound = "T: EthSpec", deny_unknown_fields),
derivative(Clone),
cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))
),
cast_error(ty = "Error", expr = "Error::IncorrectStateVariant"),
partial_getter_error(ty = "Error", expr = "Error::IncorrectStateVariant")
)]
#[derive(Debug, PartialEq, Serialize, Deserialize, Encode, TreeHash)]
#[serde(untagged)]
#[serde(bound = "T: EthSpec")]
#[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))]
#[tree_hash(enum_behaviour = "transparent")]
#[ssz(enum_behaviour = "transparent")]
pub struct BeaconState<T>
where
T: EthSpec,
{
// Versioning
#[superstruct(getter(copy))]
#[serde(with = "eth2_serde_utils::quoted_u64")]
pub genesis_time: u64,
#[superstruct(getter(copy))]
pub genesis_validators_root: Hash256,
#[superstruct(getter(copy))]
pub slot: Slot,
#[superstruct(getter(copy))]
pub fork: Fork,
// History
pub latest_block_header: BeaconBlockHeader,
#[compare_fields(as_slice)]
pub block_roots: FixedVector<Hash256, T::SlotsPerHistoricalRoot>,
#[compare_fields(as_slice)]
pub state_roots: FixedVector<Hash256, T::SlotsPerHistoricalRoot>,
pub historical_roots: VariableList<Hash256, T::HistoricalRootsLimit>,
// Ethereum 1.0 chain data
pub eth1_data: Eth1Data,
pub eth1_data_votes: VariableList<Eth1Data, T::SlotsPerEth1VotingPeriod>,
#[superstruct(getter(copy))]
#[serde(with = "eth2_serde_utils::quoted_u64")]
pub eth1_deposit_index: u64,
// Registry
#[compare_fields(as_slice)]
pub validators: VariableList<Validator, T::ValidatorRegistryLimit>,
#[compare_fields(as_slice)]
#[serde(with = "ssz_types::serde_utils::quoted_u64_var_list")]
pub balances: VariableList<u64, T::ValidatorRegistryLimit>,
// Randomness
pub randao_mixes: FixedVector<Hash256, T::EpochsPerHistoricalVector>,
// Slashings
#[serde(with = "ssz_types::serde_utils::quoted_u64_fixed_vec")]
pub slashings: FixedVector<u64, T::EpochsPerSlashingsVector>,
// Attestations (genesis fork only)
#[superstruct(only(Base))]
pub previous_epoch_attestations: VariableList<PendingAttestation<T>, T::MaxPendingAttestations>,
#[superstruct(only(Base))]
pub current_epoch_attestations: VariableList<PendingAttestation<T>, T::MaxPendingAttestations>,
// Participation (Altair and later)
#[superstruct(only(Altair, Merge))]
pub previous_epoch_participation: VariableList<ParticipationFlags, T::ValidatorRegistryLimit>,
#[superstruct(only(Altair, Merge))]
pub current_epoch_participation: VariableList<ParticipationFlags, T::ValidatorRegistryLimit>,
// Finality
#[test_random(default)]
pub justification_bits: BitVector<T::JustificationBitsLength>,
#[superstruct(getter(copy))]
pub previous_justified_checkpoint: Checkpoint,
#[superstruct(getter(copy))]
pub current_justified_checkpoint: Checkpoint,
#[superstruct(getter(copy))]
pub finalized_checkpoint: Checkpoint,
// Inactivity
#[serde(with = "ssz_types::serde_utils::quoted_u64_var_list")]
#[superstruct(only(Altair, Merge))]
pub inactivity_scores: VariableList<u64, T::ValidatorRegistryLimit>,
// Light-client sync committees
#[superstruct(only(Altair, Merge))]
pub current_sync_committee: Arc<SyncCommittee<T>>,
#[superstruct(only(Altair, Merge))]
pub next_sync_committee: Arc<SyncCommittee<T>>,
// Execution
#[superstruct(only(Merge))]
pub latest_execution_payload_header: ExecutionPayloadHeader<T>,
// Caching (not in the spec)
#[serde(skip_serializing, skip_deserializing)]
#[ssz(skip_serializing, skip_deserializing)]
#[tree_hash(skip_hashing)]
#[test_random(default)]
#[derivative(Clone(clone_with = "clone_default"))]
pub total_active_balance: Option<(Epoch, u64)>,
#[serde(skip_serializing, skip_deserializing)]
#[ssz(skip_serializing, skip_deserializing)]
#[tree_hash(skip_hashing)]
#[test_random(default)]
#[derivative(Clone(clone_with = "clone_default"))]
pub committee_caches: [CommitteeCache; CACHED_EPOCHS],
#[serde(skip_serializing, skip_deserializing)]
#[ssz(skip_serializing, skip_deserializing)]
#[tree_hash(skip_hashing)]
#[test_random(default)]
#[derivative(Clone(clone_with = "clone_default"))]
pub pubkey_cache: PubkeyCache,
#[serde(skip_serializing, skip_deserializing)]
#[ssz(skip_serializing, skip_deserializing)]
#[tree_hash(skip_hashing)]
#[test_random(default)]
#[derivative(Clone(clone_with = "clone_default"))]
pub exit_cache: ExitCache,
#[serde(skip_serializing, skip_deserializing)]
#[ssz(skip_serializing, skip_deserializing)]
#[tree_hash(skip_hashing)]
#[test_random(default)]
#[derivative(Clone(clone_with = "clone_default"))]
pub tree_hash_cache: BeaconTreeHashCache<T>,
}
impl<T: EthSpec> Clone for BeaconState<T> {
fn clone(&self) -> Self {
self.clone_with(CloneConfig::all())
}
}
impl<T: EthSpec> BeaconState<T> {
/// Create a new BeaconState suitable for genesis.
///
/// Not a complete genesis state, see `initialize_beacon_state_from_eth1`.
pub fn new(genesis_time: u64, eth1_data: Eth1Data, spec: &ChainSpec) -> Self {
BeaconState::Base(BeaconStateBase {
// Versioning
genesis_time,
genesis_validators_root: Hash256::zero(), // Set later.
slot: spec.genesis_slot,
fork: Fork {
previous_version: spec.genesis_fork_version,
current_version: spec.genesis_fork_version,
epoch: T::genesis_epoch(),
},
// History
latest_block_header: BeaconBlock::<T>::empty(spec).temporary_block_header(),
block_roots: FixedVector::from_elem(Hash256::zero()),
state_roots: FixedVector::from_elem(Hash256::zero()),
historical_roots: VariableList::empty(),
// Eth1
eth1_data,
eth1_data_votes: VariableList::empty(),
eth1_deposit_index: 0,
// Validator registry
validators: VariableList::empty(), // Set later.
balances: VariableList::empty(), // Set later.
// Randomness
randao_mixes: FixedVector::from_elem(Hash256::zero()),
// Slashings
slashings: FixedVector::from_elem(0),
// Attestations
previous_epoch_attestations: VariableList::empty(),
current_epoch_attestations: VariableList::empty(),
// Finality
justification_bits: BitVector::new(),
previous_justified_checkpoint: Checkpoint::default(),
current_justified_checkpoint: Checkpoint::default(),
finalized_checkpoint: Checkpoint::default(),
// Caching (not in spec)
total_active_balance: None,
committee_caches: [
CommitteeCache::default(),
CommitteeCache::default(),
CommitteeCache::default(),
],
pubkey_cache: PubkeyCache::default(),
exit_cache: ExitCache::default(),
tree_hash_cache: <_>::default(),
})
}
/// Returns the name of the fork pertaining to `self`.
///
/// Will return an `Err` if `self` has been instantiated to a variant conflicting with the fork
/// dictated by `self.slot()`.
pub fn fork_name(&self, spec: &ChainSpec) -> Result<ForkName, InconsistentFork> {
let fork_at_slot = spec.fork_name_at_epoch(self.current_epoch());
let object_fork = match self {
BeaconState::Base { .. } => ForkName::Base,
BeaconState::Altair { .. } => ForkName::Altair,
BeaconState::Merge { .. } => ForkName::Merge,
};
if fork_at_slot == object_fork {
Ok(object_fork)
} else {
Err(InconsistentFork {
fork_at_slot,
object_fork,
})
}
}
/// Specialised deserialisation method that uses the `ChainSpec` as context.
#[allow(clippy::integer_arithmetic)]
pub fn from_ssz_bytes(bytes: &[u8], spec: &ChainSpec) -> Result<Self, ssz::DecodeError> {
// Slot is after genesis_time (u64) and genesis_validators_root (Hash256).
let slot_start = <u64 as Decode>::ssz_fixed_len() + <Hash256 as Decode>::ssz_fixed_len();
let slot_end = slot_start + <Slot as Decode>::ssz_fixed_len();
let slot_bytes = bytes
.get(slot_start..slot_end)
.ok_or(DecodeError::InvalidByteLength {
len: bytes.len(),
expected: slot_end,
})?;
let slot = Slot::from_ssz_bytes(slot_bytes)?;
let fork_at_slot = spec.fork_name_at_slot::<T>(slot);
Ok(map_fork_name!(
fork_at_slot,
Self,
<_>::from_ssz_bytes(bytes)?
))
}
/// Returns the `tree_hash_root` of the state.
///
/// Spec v0.12.1
pub fn canonical_root(&self) -> Hash256 {
Hash256::from_slice(&self.tree_hash_root()[..])
}
pub fn historical_batch(&self) -> HistoricalBatch<T> {
HistoricalBatch {
block_roots: self.block_roots().clone(),
state_roots: self.state_roots().clone(),
}
}
/// This method ensures the state's pubkey cache is fully up-to-date before checking if the validator
/// exists in the registry. If a validator pubkey exists in the validator registry, returns `Some(i)`,
/// otherwise returns `None`.
pub fn get_validator_index(&mut self, pubkey: &PublicKeyBytes) -> Result<Option<usize>, Error> {
self.update_pubkey_cache()?;
Ok(self.pubkey_cache().get(pubkey))
}
/// The epoch corresponding to `self.slot()`.
pub fn current_epoch(&self) -> Epoch {
self.slot().epoch(T::slots_per_epoch())
}
/// The epoch prior to `self.current_epoch()`.
///
/// If the current epoch is the genesis epoch, the genesis_epoch is returned.
pub fn previous_epoch(&self) -> Epoch {
let current_epoch = self.current_epoch();
if current_epoch > T::genesis_epoch() {
current_epoch
.safe_sub(1)
.expect("current epoch greater than genesis implies greater than 0")
} else {
current_epoch
}
}
/// The epoch following `self.current_epoch()`.
///
/// Spec v0.12.1
pub fn next_epoch(&self) -> Result<Epoch, Error> {
Ok(self.current_epoch().safe_add(1)?)
}
/// Compute the number of committees at `slot`.
///
/// Makes use of the committee cache and will fail if no cache exists for the slot's epoch.
///
/// Spec v0.12.1
pub fn get_committee_count_at_slot(&self, slot: Slot) -> Result<u64, Error> {
let cache = self.committee_cache_at_slot(slot)?;
Ok(cache.committees_per_slot() as u64)
}
/// Compute the number of committees in an entire epoch.
///
/// Spec v0.12.1
pub fn get_epoch_committee_count(&self, relative_epoch: RelativeEpoch) -> Result<u64, Error> {
let cache = self.committee_cache(relative_epoch)?;
Ok(cache.epoch_committee_count() as u64)
}
/// Return the cached active validator indices at some epoch.
///
/// Note: the indices are shuffled (i.e., not in ascending order).
///
/// Returns an error if that epoch is not cached, or the cache is not initialized.
pub fn get_cached_active_validator_indices(
&self,
relative_epoch: RelativeEpoch,
) -> Result<&[usize], Error> {
let cache = self.committee_cache(relative_epoch)?;
Ok(cache.active_validator_indices())
}
/// Returns the active validator indices for the given epoch.
///
/// Does not utilize the cache, performs a full iteration over the validator registry.
pub fn get_active_validator_indices(
&self,
epoch: Epoch,
spec: &ChainSpec,
) -> Result<Vec<usize>, Error> {
if epoch >= self.compute_activation_exit_epoch(self.current_epoch(), spec)? {
Err(BeaconStateError::EpochOutOfBounds)
} else {
Ok(get_active_validator_indices(self.validators(), epoch))
}
}
/// Return the cached active validator indices at some epoch.
///
/// Note: the indices are shuffled (i.e., not in ascending order).
///
/// Returns an error if that epoch is not cached, or the cache is not initialized.
pub fn get_shuffling(&self, relative_epoch: RelativeEpoch) -> Result<&[usize], Error> {
let cache = self.committee_cache(relative_epoch)?;
Ok(cache.shuffling())
}
/// Get the Beacon committee at the given slot and index.
///
/// Utilises the committee cache.
///
/// Spec v0.12.1
pub fn get_beacon_committee(
&self,
slot: Slot,
index: CommitteeIndex,
) -> Result<BeaconCommittee, Error> {
let epoch = slot.epoch(T::slots_per_epoch());
let relative_epoch = RelativeEpoch::from_epoch(self.current_epoch(), epoch)?;
let cache = self.committee_cache(relative_epoch)?;
cache
.get_beacon_committee(slot, index)
.ok_or(Error::NoCommittee { slot, index })
}
/// Get all of the Beacon committees at a given slot.
///
/// Utilises the committee cache.
///
/// Spec v0.12.1
pub fn get_beacon_committees_at_slot(&self, slot: Slot) -> Result<Vec<BeaconCommittee>, Error> {
let cache = self.committee_cache_at_slot(slot)?;
cache.get_beacon_committees_at_slot(slot)
}
/// Get all of the Beacon committees at a given relative epoch.
///
/// Utilises the committee cache.
///
/// Spec v0.12.1
pub fn get_beacon_committees_at_epoch(
&self,
relative_epoch: RelativeEpoch,
) -> Result<Vec<BeaconCommittee>, Error> {
let cache = self.committee_cache(relative_epoch)?;
cache.get_all_beacon_committees()
}
/// Returns the block root which decided the proposer shuffling for the current epoch. This root
/// can be used to key this proposer shuffling.
///
/// ## Notes
///
/// The `block_root` covers the one-off scenario where the genesis block decides its own
/// shuffling. It should be set to the latest block applied to `self` or the genesis block root.
pub fn proposer_shuffling_decision_root(&self, block_root: Hash256) -> Result<Hash256, Error> {
let decision_slot = self.proposer_shuffling_decision_slot();
if self.slot() == decision_slot {
Ok(block_root)
} else {
self.get_block_root(decision_slot).map(|root| *root)
}
}
/// Returns the slot at which the proposer shuffling was decided. The block root at this slot
/// can be used to key the proposer shuffling for the current epoch.
fn proposer_shuffling_decision_slot(&self) -> Slot {
self.current_epoch()
.start_slot(T::slots_per_epoch())
.saturating_sub(1_u64)
}
/// Returns the block root which decided the attester shuffling for the given `relative_epoch`.
/// This root can be used to key that attester shuffling.
///
/// ## Notes
///
/// The `block_root` covers the one-off scenario where the genesis block decides its own
/// shuffling. It should be set to the latest block applied to `self` or the genesis block root.
pub fn attester_shuffling_decision_root(
&self,
block_root: Hash256,
relative_epoch: RelativeEpoch,
) -> Result<Hash256, Error> {
let decision_slot = self.attester_shuffling_decision_slot(relative_epoch);
if self.slot() == decision_slot {
Ok(block_root)
} else {
self.get_block_root(decision_slot).map(|root| *root)
}
}
/// Returns the slot at which the proposer shuffling was decided. The block root at this slot
/// can be used to key the proposer shuffling for the current epoch.
fn attester_shuffling_decision_slot(&self, relative_epoch: RelativeEpoch) -> Slot {
match relative_epoch {
RelativeEpoch::Next => self.current_epoch(),
RelativeEpoch::Current => self.previous_epoch(),
RelativeEpoch::Previous => self.previous_epoch().saturating_sub(1_u64),
}
.start_slot(T::slots_per_epoch())
.saturating_sub(1_u64)
}
/// Compute the proposer (not necessarily for the Beacon chain) from a list of indices.
pub fn compute_proposer_index(
&self,
indices: &[usize],
seed: &[u8],
spec: &ChainSpec,
) -> Result<usize, Error> {
if indices.is_empty() {
return Err(Error::InsufficientValidators);
}
let mut i = 0;
loop {
let shuffled_index = compute_shuffled_index(
i.safe_rem(indices.len())?,
indices.len(),
seed,
spec.shuffle_round_count,
)
.ok_or(Error::UnableToShuffle)?;
let candidate_index = *indices
.get(shuffled_index)
.ok_or(Error::ShuffleIndexOutOfBounds(shuffled_index))?;
let random_byte = Self::shuffling_random_byte(i, seed)?;
let effective_balance = self.get_effective_balance(candidate_index)?;
if effective_balance.safe_mul(MAX_RANDOM_BYTE)?
>= spec
.max_effective_balance
.safe_mul(u64::from(random_byte))?
{
return Ok(candidate_index);
}
i.safe_add_assign(1)?;
}
}
/// Get a random byte from the given `seed`.
///
/// Used by the proposer & sync committee selection functions.
fn shuffling_random_byte(i: usize, seed: &[u8]) -> Result<u8, Error> {
let mut preimage = seed.to_vec();
preimage.append(&mut int_to_bytes8(i.safe_div(32)? as u64));
let index = i.safe_rem(32)?;
hash(&preimage)
.get(index)
.copied()
.ok_or(Error::ShuffleIndexOutOfBounds(index))
}
/// Return `true` if the validator who produced `slot_signature` is eligible to aggregate.
///
/// Spec v0.12.1
pub fn is_aggregator(
&self,
slot: Slot,
index: CommitteeIndex,
slot_signature: &Signature,
spec: &ChainSpec,
) -> Result<bool, Error> {
let committee = self.get_beacon_committee(slot, index)?;
let modulo = std::cmp::max(
1,
(committee.committee.len() as u64).safe_div(spec.target_aggregators_per_committee)?,
);
let signature_hash = hash(&slot_signature.as_ssz_bytes());
let signature_hash_int = u64::from_le_bytes(
signature_hash
.get(0..8)
.and_then(|bytes| bytes.try_into().ok())
.ok_or(Error::IsAggregatorOutOfBounds)?,
);
Ok(signature_hash_int.safe_rem(modulo)? == 0)
}
/// Returns the beacon proposer index for the `slot` in the given `relative_epoch`.
///
/// Spec v0.12.1
pub fn get_beacon_proposer_index(&self, slot: Slot, spec: &ChainSpec) -> Result<usize, Error> {
// Proposer indices are only known for the current epoch, due to the dependence on the
// effective balances of validators, which change at every epoch transition.
let epoch = slot.epoch(T::slots_per_epoch());
if epoch != self.current_epoch() {
return Err(Error::SlotOutOfBounds);
}
let seed = self.get_beacon_proposer_seed(slot, spec)?;
let indices = self.get_active_validator_indices(epoch, spec)?;
self.compute_proposer_index(&indices, &seed, spec)
}
/// Returns the beacon proposer index for each `slot` in `self.current_epoch()`.
///
/// The returned `Vec` contains one proposer index for each slot. For example, if
/// `state.current_epoch() == 1`, then `vec[0]` refers to slot `32` and `vec[1]` refers to slot
/// `33`. It will always be the case that `vec.len() == SLOTS_PER_EPOCH`.
pub fn get_beacon_proposer_indices(&self, spec: &ChainSpec) -> Result<Vec<usize>, Error> {
// Not using the cached validator indices since they are shuffled.
let indices = self.get_active_validator_indices(self.current_epoch(), spec)?;
self.current_epoch()
.slot_iter(T::slots_per_epoch())
.map(|slot| {
let seed = self.get_beacon_proposer_seed(slot, spec)?;
self.compute_proposer_index(&indices, &seed, spec)
})
.collect()
}
/// Compute the seed to use for the beacon proposer selection at the given `slot`.
///
/// Spec v0.12.1
pub fn get_beacon_proposer_seed(&self, slot: Slot, spec: &ChainSpec) -> Result<Vec<u8>, Error> {
let epoch = slot.epoch(T::slots_per_epoch());
let mut preimage = self
.get_seed(epoch, Domain::BeaconProposer, spec)?
.as_bytes()
.to_vec();
preimage.append(&mut int_to_bytes8(slot.as_u64()));
Ok(hash(&preimage))
}
/// Get the already-built current or next sync committee from the state.
pub fn get_built_sync_committee(
&self,
epoch: Epoch,
spec: &ChainSpec,
) -> Result<&Arc<SyncCommittee<T>>, Error> {
let sync_committee_period = epoch.sync_committee_period(spec)?;
let current_sync_committee_period = self.current_epoch().sync_committee_period(spec)?;
let next_sync_committee_period = current_sync_committee_period.safe_add(1)?;
if sync_committee_period == current_sync_committee_period {
self.current_sync_committee()
} else if sync_committee_period == next_sync_committee_period {
self.next_sync_committee()
} else {
Err(Error::SyncCommitteeNotKnown {
current_epoch: self.current_epoch(),
epoch,
})
}
}
/// Get the validator indices of all validators from `sync_committee`.
pub fn get_sync_committee_indices(
&mut self,
sync_committee: &SyncCommittee<T>,
) -> Result<Vec<usize>, Error> {
sync_committee
.pubkeys
.iter()
.map(|pubkey| {
self.get_validator_index(pubkey)?
.ok_or(Error::PubkeyCacheInconsistent)
})
.collect()
}
/// Compute the sync committee indices for the next sync committee.
fn get_next_sync_committee_indices(&self, spec: &ChainSpec) -> Result<Vec<usize>, Error> {
let epoch = self.current_epoch().safe_add(1)?;
let active_validator_indices = self.get_active_validator_indices(epoch, spec)?;
let active_validator_count = active_validator_indices.len();
let seed = self.get_seed(epoch, Domain::SyncCommittee, spec)?;
let mut i = 0;
let mut sync_committee_indices = Vec::with_capacity(T::SyncCommitteeSize::to_usize());
while sync_committee_indices.len() < T::SyncCommitteeSize::to_usize() {
let shuffled_index = compute_shuffled_index(
i.safe_rem(active_validator_count)?,
active_validator_count,
seed.as_bytes(),
spec.shuffle_round_count,
)
.ok_or(Error::UnableToShuffle)?;
let candidate_index = *active_validator_indices
.get(shuffled_index)
.ok_or(Error::ShuffleIndexOutOfBounds(shuffled_index))?;
let random_byte = Self::shuffling_random_byte(i, seed.as_bytes())?;
let effective_balance = self.get_validator(candidate_index)?.effective_balance;
if effective_balance.safe_mul(MAX_RANDOM_BYTE)?
>= spec
.max_effective_balance
.safe_mul(u64::from(random_byte))?
{
sync_committee_indices.push(candidate_index);
}
i.safe_add_assign(1)?;
}
Ok(sync_committee_indices)
}
/// Compute the next sync committee.
pub fn get_next_sync_committee(&self, spec: &ChainSpec) -> Result<SyncCommittee<T>, Error> {
let sync_committee_indices = self.get_next_sync_committee_indices(spec)?;
let pubkeys = sync_committee_indices
.iter()
.map(|&index| {
self.validators()
.get(index)
.map(|v| v.pubkey)
.ok_or(Error::UnknownValidator(index))
})
.collect::<Result<Vec<_>, _>>()?;
let decompressed_pubkeys = pubkeys
.iter()
.map(|pk| pk.decompress())
.collect::<Result<Vec<_>, _>>()?;
let aggregate_pubkey = AggregatePublicKey::aggregate(&decompressed_pubkeys)?;
Ok(SyncCommittee {
pubkeys: FixedVector::new(pubkeys)?,
aggregate_pubkey: aggregate_pubkey.to_public_key().compress(),
})
}
/// Get the sync committee duties for a list of validator indices.
///
/// Will return a `SyncCommitteeNotKnown` error if the `epoch` is out of bounds with respect
/// to the current or next sync committee periods.
pub fn get_sync_committee_duties(
&self,
epoch: Epoch,
validator_indices: &[u64],
spec: &ChainSpec,
) -> Result<Vec<Option<SyncDuty>>, Error> {
let sync_committee = self.get_built_sync_committee(epoch, spec)?;
validator_indices
.iter()
.map(|&validator_index| {
let pubkey = self.get_validator(validator_index as usize)?.pubkey;
Ok(SyncDuty::from_sync_committee(
validator_index,
pubkey,
sync_committee,
))
})
.collect()
}
/// Get the canonical root of the `latest_block_header`, filling in its state root if necessary.
///
/// It needs filling in on all slots where there isn't a skip.
///
/// Spec v0.12.1
pub fn get_latest_block_root(&self, current_state_root: Hash256) -> Hash256 {
if self.latest_block_header().state_root.is_zero() {
let mut latest_block_header = self.latest_block_header().clone();
latest_block_header.state_root = current_state_root;
latest_block_header.canonical_root()
} else {
self.latest_block_header().canonical_root()
}
}
/// Safely obtains the index for latest block roots, given some `slot`.
///
/// Spec v0.12.1
fn get_latest_block_roots_index(&self, slot: Slot) -> Result<usize, Error> {
if slot < self.slot() && self.slot() <= slot.safe_add(self.block_roots().len() as u64)? {
Ok(slot.as_usize().safe_rem(self.block_roots().len())?)
} else {
Err(BeaconStateError::SlotOutOfBounds)
}
}
/// Returns an iterator across the past block roots of `state` in descending slot-order.
///
/// See the docs for `BlockRootsIter` for more detail.
pub fn rev_iter_block_roots<'a>(&'a self, spec: &ChainSpec) -> BlockRootsIter<'a, T> {
BlockRootsIter::new(self, spec.genesis_slot)
}
/// Return the block root at a recent `slot`.
pub fn get_block_root(&self, slot: Slot) -> Result<&Hash256, BeaconStateError> {
let i = self.get_latest_block_roots_index(slot)?;
self.block_roots()
.get(i)
.ok_or(Error::BlockRootsOutOfBounds(i))
}
/// Return the block root at a recent `epoch`.
///
/// Note that the spec calls this `get_block_root`.
pub fn get_block_root_at_epoch(&self, epoch: Epoch) -> Result<&Hash256, BeaconStateError> {
self.get_block_root(epoch.start_slot(T::slots_per_epoch()))
}
/// Sets the block root for some given slot.
pub fn set_block_root(
&mut self,
slot: Slot,
block_root: Hash256,
) -> Result<(), BeaconStateError> {
let i = self.get_latest_block_roots_index(slot)?;
*self
.block_roots_mut()
.get_mut(i)
.ok_or(Error::BlockRootsOutOfBounds(i))? = block_root;
Ok(())
}
/// Fill `randao_mixes` with
pub fn fill_randao_mixes_with(&mut self, index_root: Hash256) {
*self.randao_mixes_mut() = FixedVector::from_elem(index_root);
}
/// Safely obtains the index for `randao_mixes`
///
/// Spec v0.12.1
fn get_randao_mix_index(
&self,
epoch: Epoch,
allow_next_epoch: AllowNextEpoch,
) -> Result<usize, Error> {
let current_epoch = self.current_epoch();
let len = T::EpochsPerHistoricalVector::to_u64();
if current_epoch < epoch.safe_add(len)?
&& epoch <= allow_next_epoch.upper_bound_of(current_epoch)?
{
Ok(epoch.as_usize().safe_rem(len as usize)?)
} else {
Err(Error::EpochOutOfBounds)
}
}
/// XOR-assigns the existing `epoch` randao mix with the hash of the `signature`.
///
/// # Errors:
///
/// See `Self::get_randao_mix`.
pub fn update_randao_mix(&mut self, epoch: Epoch, signature: &Signature) -> Result<(), Error> {
let i = epoch
.as_usize()
.safe_rem(T::EpochsPerHistoricalVector::to_usize())?;
let signature_hash = Hash256::from_slice(&hash(&ssz_encode(signature)));
*self
.randao_mixes_mut()
.get_mut(i)
.ok_or(Error::RandaoMixesOutOfBounds(i))? =
*self.get_randao_mix(epoch)? ^ signature_hash;
Ok(())
}
/// Return the randao mix at a recent ``epoch``.
pub fn get_randao_mix(&self, epoch: Epoch) -> Result<&Hash256, Error> {
let i = self.get_randao_mix_index(epoch, AllowNextEpoch::False)?;
self.randao_mixes()
.get(i)
.ok_or(Error::RandaoMixesOutOfBounds(i))
}
/// Set the randao mix at a recent ``epoch``.
///
/// Spec v0.12.1
pub fn set_randao_mix(&mut self, epoch: Epoch, mix: Hash256) -> Result<(), Error> {
let i = self.get_randao_mix_index(epoch, AllowNextEpoch::True)?;
*self