Merge current master and fix ssz-fuzzing
This commit is contained in:
@@ -10,6 +10,7 @@ boolean-bitfield = { path = "../utils/boolean-bitfield" }
|
||||
dirs = "1.0"
|
||||
ethereum-types = "0.5"
|
||||
hashing = { path = "../utils/hashing" }
|
||||
hex = "0.3"
|
||||
honey-badger-split = { path = "../utils/honey-badger-split" }
|
||||
int_to_bytes = { path = "../utils/int_to_bytes" }
|
||||
log = "0.4"
|
||||
@@ -24,6 +25,7 @@ ssz = { path = "../utils/ssz" }
|
||||
ssz_derive = { path = "../utils/ssz_derive" }
|
||||
swap_or_not_shuffle = { path = "../utils/swap_or_not_shuffle" }
|
||||
test_random_derive = { path = "../utils/test_random_derive" }
|
||||
libp2p = { git = "https://github.com/SigP/rust-libp2p", branch = "gossipsub" }
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.6.0"
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
use super::{AggregateSignature, AttestationData, Bitfield};
|
||||
use crate::test_utils::TestRandom;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// Details an attestation that can be slashable.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Encode, Decode, TreeHash, TestRandom, SignedRoot)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
Clone,
|
||||
PartialEq,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Encode,
|
||||
Decode,
|
||||
TreeHash,
|
||||
TestRandom,
|
||||
SignedRoot,
|
||||
)]
|
||||
pub struct Attestation {
|
||||
pub aggregation_bitfield: Bitfield,
|
||||
pub data: AttestationData,
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::{Crosslink, Epoch, Hash256, Slot};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// The data upon which an attestation is based.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
Clone,
|
||||
PartialEq,
|
||||
Default,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Hash,
|
||||
Encode,
|
||||
Decode,
|
||||
@@ -23,14 +24,19 @@ use test_random_derive::TestRandom;
|
||||
SignedRoot,
|
||||
)]
|
||||
pub struct AttestationData {
|
||||
// LMD GHOST vote
|
||||
pub slot: Slot,
|
||||
pub shard: u64,
|
||||
pub beacon_block_root: Hash256,
|
||||
pub epoch_boundary_root: Hash256,
|
||||
|
||||
// FFG Vote
|
||||
pub source_epoch: Epoch,
|
||||
pub source_root: Hash256,
|
||||
pub target_root: Hash256,
|
||||
|
||||
// Crosslink Vote
|
||||
pub shard: u64,
|
||||
pub previous_crosslink: Crosslink,
|
||||
pub crosslink_data_root: Hash256,
|
||||
pub latest_crosslink: Crosslink,
|
||||
pub justified_epoch: Epoch,
|
||||
pub justified_block_root: Hash256,
|
||||
}
|
||||
|
||||
impl Eq for AttestationData {}
|
||||
|
||||
@@ -6,7 +6,7 @@ use ssz_derive::{Decode, Encode, TreeHash};
|
||||
|
||||
/// Used for pairing an attestation with a proof-of-custody.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Encode, Decode, TreeHash)]
|
||||
pub struct AttestationDataAndCustodyBit {
|
||||
pub data: AttestationData,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
use crate::*;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct AttestationDuty {
|
||||
pub slot: Slot,
|
||||
pub shard: Shard,
|
||||
pub committee_index: usize,
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
use crate::{test_utils::TestRandom, SlashableAttestation};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// Two conflicting attestations.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct AttesterSlashing {
|
||||
pub slashable_attestation_1: SlashableAttestation,
|
||||
pub slashable_attestation_2: SlashableAttestation,
|
||||
|
||||
@@ -1,41 +1,50 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::{BeaconBlockBody, ChainSpec, Eth1Data, Hash256, Proposal, Slot};
|
||||
use crate::*;
|
||||
use bls::Signature;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use ssz::{SignedRoot, TreeHash};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// A block of the `BeaconChain`.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom, SignedRoot)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
PartialEq,
|
||||
Clone,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Encode,
|
||||
Decode,
|
||||
TreeHash,
|
||||
TestRandom,
|
||||
SignedRoot,
|
||||
)]
|
||||
pub struct BeaconBlock {
|
||||
pub slot: Slot,
|
||||
pub parent_root: Hash256,
|
||||
pub previous_block_root: Hash256,
|
||||
pub state_root: Hash256,
|
||||
pub randao_reveal: Signature,
|
||||
pub eth1_data: Eth1Data,
|
||||
pub body: BeaconBlockBody,
|
||||
pub signature: Signature,
|
||||
}
|
||||
|
||||
impl BeaconBlock {
|
||||
/// Produce the first block of the Beacon Chain.
|
||||
/// Returns an empty block to be used during genesis.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn genesis(state_root: Hash256, spec: &ChainSpec) -> BeaconBlock {
|
||||
/// Spec v0.5.0
|
||||
pub fn empty(spec: &ChainSpec) -> BeaconBlock {
|
||||
BeaconBlock {
|
||||
slot: spec.genesis_slot,
|
||||
parent_root: spec.zero_hash,
|
||||
state_root,
|
||||
randao_reveal: spec.empty_signature.clone(),
|
||||
eth1_data: Eth1Data {
|
||||
deposit_root: spec.zero_hash,
|
||||
block_hash: spec.zero_hash,
|
||||
},
|
||||
previous_block_root: spec.zero_hash,
|
||||
state_root: spec.zero_hash,
|
||||
body: BeaconBlockBody {
|
||||
randao_reveal: spec.empty_signature.clone(),
|
||||
eth1_data: Eth1Data {
|
||||
deposit_root: spec.zero_hash,
|
||||
block_hash: spec.zero_hash,
|
||||
},
|
||||
proposer_slashings: vec![],
|
||||
attester_slashings: vec![],
|
||||
attestations: vec![],
|
||||
@@ -49,20 +58,37 @@ impl BeaconBlock {
|
||||
|
||||
/// Returns the `hash_tree_root` of the block.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn canonical_root(&self) -> Hash256 {
|
||||
Hash256::from_slice(&self.hash_tree_root()[..])
|
||||
}
|
||||
|
||||
/// Returns an unsigned proposal for block.
|
||||
/// Returns a full `BeaconBlockHeader` of this block.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn proposal(&self, spec: &ChainSpec) -> Proposal {
|
||||
Proposal {
|
||||
/// Note: This method is used instead of an `Into` impl to avoid a `Clone` of an entire block
|
||||
/// when you want to have the block _and_ the header.
|
||||
///
|
||||
/// Note: performs a full tree-hash of `self.body`.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub fn block_header(&self) -> BeaconBlockHeader {
|
||||
BeaconBlockHeader {
|
||||
slot: self.slot,
|
||||
shard: spec.beacon_chain_shard_number,
|
||||
block_root: Hash256::from_slice(&self.signed_root()),
|
||||
previous_block_root: self.previous_block_root,
|
||||
state_root: self.state_root,
|
||||
block_body_root: Hash256::from_slice(&self.body.hash_tree_root()[..]),
|
||||
signature: self.signature.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a "temporary" header, where the `state_root` is `spec.zero_hash`.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub fn temporary_block_header(&self, spec: &ChainSpec) -> BeaconBlockHeader {
|
||||
BeaconBlockHeader {
|
||||
state_root: spec.zero_hash,
|
||||
signature: spec.empty_signature.clone(),
|
||||
..self.block_header()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
use super::{Attestation, AttesterSlashing, Deposit, ProposerSlashing, Transfer, VoluntaryExit};
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::*;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// The body of a `BeaconChain` block, containing operations.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Default, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct BeaconBlockBody {
|
||||
pub randao_reveal: Signature,
|
||||
pub eth1_data: Eth1Data,
|
||||
pub proposer_slashings: Vec<ProposerSlashing>,
|
||||
pub attester_slashings: Vec<AttesterSlashing>,
|
||||
pub attestations: Vec<Attestation>,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::*;
|
||||
use bls::Signature;
|
||||
use rand::RngCore;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// A header of a `BeaconBlock`.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
PartialEq,
|
||||
Clone,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Encode,
|
||||
Decode,
|
||||
TreeHash,
|
||||
TestRandom,
|
||||
SignedRoot,
|
||||
)]
|
||||
pub struct BeaconBlockHeader {
|
||||
pub slot: Slot,
|
||||
pub previous_block_root: Hash256,
|
||||
pub state_root: Hash256,
|
||||
pub block_body_root: Hash256,
|
||||
pub signature: Signature,
|
||||
}
|
||||
|
||||
impl BeaconBlockHeader {
|
||||
/// Returns the `hash_tree_root` of the header.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub fn canonical_root(&self) -> Hash256 {
|
||||
Hash256::from_slice(&self.hash_tree_root()[..])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
ssz_tests!(BeaconBlockHeader);
|
||||
}
|
||||
+560
-1096
File diff suppressed because it is too large
Load Diff
@@ -1,99 +0,0 @@
|
||||
use super::BeaconStateError;
|
||||
use crate::validator_registry::get_active_validator_indices;
|
||||
use crate::*;
|
||||
use rayon::prelude::*;
|
||||
use ssz::TreeHash;
|
||||
|
||||
/// Builds a `BeaconState` for use in production.
|
||||
///
|
||||
/// This struct should _not_ be modified for use in testing scenarios. Use `TestingBeaconStateBuilder` for that purpose.
|
||||
///
|
||||
/// This struct should remain safe and sensible for production usage.
|
||||
pub struct BeaconStateBuilder {
|
||||
pub state: BeaconState,
|
||||
}
|
||||
|
||||
impl BeaconStateBuilder {
|
||||
/// Create a new builder with the given number of validators.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn new(genesis_time: u64, latest_eth1_data: Eth1Data, spec: &ChainSpec) -> Self {
|
||||
Self {
|
||||
state: BeaconState::genesis(genesis_time, latest_eth1_data, spec),
|
||||
}
|
||||
}
|
||||
|
||||
/// Process deposit objects.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn process_initial_deposits(
|
||||
&mut self,
|
||||
initial_validator_deposits: &[Deposit],
|
||||
spec: &ChainSpec,
|
||||
) {
|
||||
let deposit_data = initial_validator_deposits
|
||||
.par_iter()
|
||||
.map(|deposit| &deposit.deposit_data)
|
||||
.collect();
|
||||
|
||||
self.state.process_deposits(deposit_data, spec);
|
||||
|
||||
self.activate_genesis_validators(spec);
|
||||
|
||||
self.state.deposit_index = initial_validator_deposits.len() as u64;
|
||||
}
|
||||
|
||||
fn activate_genesis_validators(&mut self, spec: &ChainSpec) {
|
||||
for validator_index in 0..self.state.validator_registry.len() {
|
||||
if self.state.get_effective_balance(validator_index, spec) >= spec.max_deposit_amount {
|
||||
self.state.activate_validator(validator_index, true, spec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiate the validator registry from a YAML file.
|
||||
///
|
||||
/// This skips a lot of signing and verification, useful if signing and verification has been
|
||||
/// completed previously.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn import_existing_validators(
|
||||
&mut self,
|
||||
validators: Vec<Validator>,
|
||||
initial_balances: Vec<u64>,
|
||||
deposit_index: u64,
|
||||
spec: &ChainSpec,
|
||||
) {
|
||||
self.state.validator_registry = validators;
|
||||
|
||||
assert_eq!(
|
||||
self.state.validator_registry.len(),
|
||||
initial_balances.len(),
|
||||
"Not enough balances for validators"
|
||||
);
|
||||
|
||||
self.state.validator_balances = initial_balances;
|
||||
|
||||
self.activate_genesis_validators(spec);
|
||||
|
||||
self.state.deposit_index = deposit_index;
|
||||
}
|
||||
|
||||
/// Updates the final state variables and returns a fully built genesis state.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn build(mut self, spec: &ChainSpec) -> Result<BeaconState, BeaconStateError> {
|
||||
let genesis_active_index_root =
|
||||
get_active_validator_indices(&self.state.validator_registry, spec.genesis_epoch)
|
||||
.hash_tree_root();
|
||||
|
||||
self.state.latest_active_index_roots = vec![
|
||||
Hash256::from_slice(&genesis_active_index_root);
|
||||
spec.latest_active_index_roots_length
|
||||
];
|
||||
|
||||
self.state.current_shuffling_seed = self.state.generate_seed(spec.genesis_epoch, spec)?;
|
||||
|
||||
Ok(self.state)
|
||||
}
|
||||
}
|
||||
@@ -1,84 +1,324 @@
|
||||
use super::{AttestationDutyMap, BeaconState, CrosslinkCommittees, Error, ShardCommitteeIndexMap};
|
||||
use crate::{ChainSpec, Epoch};
|
||||
use log::trace;
|
||||
use serde_derive::Serialize;
|
||||
use std::collections::HashMap;
|
||||
use super::BeaconState;
|
||||
use crate::*;
|
||||
use honey_badger_split::SplitExt;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use swap_or_not_shuffle::shuffle_list;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Serialize)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Error {
|
||||
UnableToShuffle,
|
||||
UnableToGenerateSeed,
|
||||
}
|
||||
|
||||
mod tests;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
|
||||
pub struct EpochCache {
|
||||
/// True if this cache has been initialized.
|
||||
pub initialized: bool,
|
||||
/// The crosslink committees for an epoch.
|
||||
pub committees: Vec<CrosslinkCommittees>,
|
||||
/// `Some(epoch)` if the cache is initialized, where `epoch` is the cache it holds.
|
||||
pub initialized_epoch: Option<Epoch>,
|
||||
/// All crosslink committees for an epoch.
|
||||
pub epoch_crosslink_committees: EpochCrosslinkCommittees,
|
||||
/// Maps validator index to a slot, shard and committee index for attestation.
|
||||
pub attestation_duty_map: AttestationDutyMap,
|
||||
pub attestation_duties: Vec<Option<AttestationDuty>>,
|
||||
/// Maps a shard to an index of `self.committees`.
|
||||
pub shard_committee_index_map: ShardCommitteeIndexMap,
|
||||
pub shard_committee_indices: Vec<Option<(Slot, usize)>>,
|
||||
/// Indices of all active validators in the epoch
|
||||
pub active_validator_indices: Vec<usize>,
|
||||
}
|
||||
|
||||
impl EpochCache {
|
||||
pub fn empty() -> EpochCache {
|
||||
EpochCache {
|
||||
initialized: false,
|
||||
committees: vec![],
|
||||
attestation_duty_map: AttestationDutyMap::new(),
|
||||
shard_committee_index_map: ShardCommitteeIndexMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a new, fully initialized cache.
|
||||
pub fn initialized(
|
||||
state: &BeaconState,
|
||||
epoch: Epoch,
|
||||
relative_epoch: RelativeEpoch,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<EpochCache, Error> {
|
||||
let mut epoch_committees: Vec<CrosslinkCommittees> =
|
||||
Vec::with_capacity(spec.slots_per_epoch as usize);
|
||||
let mut attestation_duty_map: AttestationDutyMap = HashMap::new();
|
||||
let mut shard_committee_index_map: ShardCommitteeIndexMap = HashMap::new();
|
||||
let epoch = relative_epoch.into_epoch(state.slot.epoch(spec.slots_per_epoch));
|
||||
|
||||
let shuffling =
|
||||
state.get_shuffling_for_slot(epoch.start_slot(spec.slots_per_epoch), false, spec)?;
|
||||
let active_validator_indices =
|
||||
get_active_validator_indices(&state.validator_registry, epoch);
|
||||
|
||||
for (epoch_committeess_index, slot) in epoch.slot_iter(spec.slots_per_epoch).enumerate() {
|
||||
let slot_committees = state.calculate_crosslink_committees_at_slot(
|
||||
slot,
|
||||
false,
|
||||
shuffling.clone(),
|
||||
let builder = match relative_epoch {
|
||||
RelativeEpoch::Previous => EpochCrosslinkCommitteesBuilder::for_previous_epoch(
|
||||
state,
|
||||
active_validator_indices.clone(),
|
||||
spec,
|
||||
)?;
|
||||
),
|
||||
RelativeEpoch::Current => EpochCrosslinkCommitteesBuilder::for_current_epoch(
|
||||
state,
|
||||
active_validator_indices.clone(),
|
||||
spec,
|
||||
),
|
||||
RelativeEpoch::NextWithRegistryChange => {
|
||||
EpochCrosslinkCommitteesBuilder::for_next_epoch(
|
||||
state,
|
||||
active_validator_indices.clone(),
|
||||
true,
|
||||
spec,
|
||||
)?
|
||||
}
|
||||
RelativeEpoch::NextWithoutRegistryChange => {
|
||||
EpochCrosslinkCommitteesBuilder::for_next_epoch(
|
||||
state,
|
||||
active_validator_indices.clone(),
|
||||
false,
|
||||
spec,
|
||||
)?
|
||||
}
|
||||
};
|
||||
let epoch_crosslink_committees = builder.build(spec)?;
|
||||
|
||||
for (slot_committees_index, (committee, shard)) in slot_committees.iter().enumerate() {
|
||||
// Empty committees are not permitted.
|
||||
if committee.is_empty() {
|
||||
return Err(Error::InsufficientValidators);
|
||||
}
|
||||
// Loop through all the validators in the committees and create the following maps:
|
||||
//
|
||||
// 1. `attestation_duties`: maps `ValidatorIndex` to `AttestationDuty`.
|
||||
// 2. `shard_committee_indices`: maps `Shard` into a `CrosslinkCommittee` in
|
||||
// `EpochCrosslinkCommittees`.
|
||||
let mut attestation_duties = vec![None; state.validator_registry.len()];
|
||||
let mut shard_committee_indices = vec![None; spec.shard_count as usize];
|
||||
for (i, slot_committees) in epoch_crosslink_committees
|
||||
.crosslink_committees
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let slot = epoch.start_slot(spec.slots_per_epoch) + i as u64;
|
||||
|
||||
trace!(
|
||||
"shard: {}, epoch_i: {}, slot_i: {}",
|
||||
shard,
|
||||
epoch_committeess_index,
|
||||
slot_committees_index
|
||||
);
|
||||
for (j, crosslink_committee) in slot_committees.iter().enumerate() {
|
||||
let shard = crosslink_committee.shard;
|
||||
|
||||
shard_committee_index_map
|
||||
.insert(*shard, (epoch_committeess_index, slot_committees_index));
|
||||
shard_committee_indices[shard as usize] = Some((slot, j));
|
||||
|
||||
for (committee_index, validator_index) in committee.iter().enumerate() {
|
||||
attestation_duty_map.insert(
|
||||
*validator_index as u64,
|
||||
(slot, *shard, committee_index as u64),
|
||||
);
|
||||
for (k, validator_index) in crosslink_committee.committee.iter().enumerate() {
|
||||
let attestation_duty = AttestationDuty {
|
||||
slot,
|
||||
shard,
|
||||
committee_index: k,
|
||||
};
|
||||
attestation_duties[*validator_index] = Some(attestation_duty)
|
||||
}
|
||||
}
|
||||
|
||||
epoch_committees.push(slot_committees)
|
||||
}
|
||||
|
||||
Ok(EpochCache {
|
||||
initialized: true,
|
||||
committees: epoch_committees,
|
||||
attestation_duty_map,
|
||||
shard_committee_index_map,
|
||||
initialized_epoch: Some(epoch),
|
||||
epoch_crosslink_committees,
|
||||
attestation_duties,
|
||||
shard_committee_indices,
|
||||
active_validator_indices,
|
||||
})
|
||||
}
|
||||
|
||||
/// Return a vec of `CrosslinkCommittee` for a given slot.
|
||||
pub fn get_crosslink_committees_at_slot(
|
||||
&self,
|
||||
slot: Slot,
|
||||
spec: &ChainSpec,
|
||||
) -> Option<&Vec<CrosslinkCommittee>> {
|
||||
self.epoch_crosslink_committees
|
||||
.get_crosslink_committees_at_slot(slot, spec)
|
||||
}
|
||||
|
||||
/// Return `Some(CrosslinkCommittee)` if the given shard has a committee during the given
|
||||
/// `epoch`.
|
||||
pub fn get_crosslink_committee_for_shard(
|
||||
&self,
|
||||
shard: Shard,
|
||||
spec: &ChainSpec,
|
||||
) -> Option<&CrosslinkCommittee> {
|
||||
if shard > self.shard_committee_indices.len() as u64 {
|
||||
None
|
||||
} else {
|
||||
let (slot, committee) = self.shard_committee_indices[shard as usize]?;
|
||||
let slot_committees = self.get_crosslink_committees_at_slot(slot, spec)?;
|
||||
slot_committees.get(committee)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a list of all `validator_registry` indices where the validator is active at the given
|
||||
/// `epoch`.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub fn get_active_validator_indices(validators: &[Validator], epoch: Epoch) -> Vec<usize> {
|
||||
let mut active = Vec::with_capacity(validators.len());
|
||||
|
||||
for (index, validator) in validators.iter().enumerate() {
|
||||
if validator.is_active_at(epoch) {
|
||||
active.push(index)
|
||||
}
|
||||
}
|
||||
|
||||
active.shrink_to_fit();
|
||||
|
||||
active
|
||||
}
|
||||
|
||||
/// Contains all `CrosslinkCommittees` for an epoch.
|
||||
#[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
|
||||
pub struct EpochCrosslinkCommittees {
|
||||
/// The epoch the committees are present in.
|
||||
epoch: Epoch,
|
||||
/// Each commitee for each slot of the epoch.
|
||||
pub crosslink_committees: Vec<Vec<CrosslinkCommittee>>,
|
||||
}
|
||||
|
||||
impl EpochCrosslinkCommittees {
|
||||
/// Return a new instances where all slots have zero committees.
|
||||
fn new(epoch: Epoch, spec: &ChainSpec) -> Self {
|
||||
Self {
|
||||
epoch,
|
||||
crosslink_committees: vec![vec![]; spec.slots_per_epoch as usize],
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a vec of `CrosslinkCommittee` for a given slot.
|
||||
fn get_crosslink_committees_at_slot(
|
||||
&self,
|
||||
slot: Slot,
|
||||
spec: &ChainSpec,
|
||||
) -> Option<&Vec<CrosslinkCommittee>> {
|
||||
let epoch_start_slot = self.epoch.start_slot(spec.slots_per_epoch);
|
||||
let epoch_end_slot = self.epoch.end_slot(spec.slots_per_epoch);
|
||||
|
||||
if (epoch_start_slot <= slot) && (slot <= epoch_end_slot) {
|
||||
let index = slot - epoch_start_slot;
|
||||
self.crosslink_committees.get(index.as_usize())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds an `EpochCrosslinkCommittees` object.
|
||||
pub struct EpochCrosslinkCommitteesBuilder {
|
||||
epoch: Epoch,
|
||||
shuffling_start_shard: Shard,
|
||||
shuffling_seed: Hash256,
|
||||
active_validator_indices: Vec<usize>,
|
||||
committees_per_epoch: u64,
|
||||
}
|
||||
|
||||
impl EpochCrosslinkCommitteesBuilder {
|
||||
/// Instantiates a builder that will build for the `state`'s previous epoch.
|
||||
pub fn for_previous_epoch(
|
||||
state: &BeaconState,
|
||||
active_validator_indices: Vec<usize>,
|
||||
spec: &ChainSpec,
|
||||
) -> Self {
|
||||
Self {
|
||||
epoch: state.previous_epoch(spec),
|
||||
shuffling_start_shard: state.previous_shuffling_start_shard,
|
||||
shuffling_seed: state.previous_shuffling_seed,
|
||||
committees_per_epoch: spec.get_epoch_committee_count(active_validator_indices.len()),
|
||||
active_validator_indices,
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiates a builder that will build for the `state`'s next epoch.
|
||||
pub fn for_current_epoch(
|
||||
state: &BeaconState,
|
||||
active_validator_indices: Vec<usize>,
|
||||
spec: &ChainSpec,
|
||||
) -> Self {
|
||||
Self {
|
||||
epoch: state.current_epoch(spec),
|
||||
shuffling_start_shard: state.current_shuffling_start_shard,
|
||||
shuffling_seed: state.current_shuffling_seed,
|
||||
committees_per_epoch: spec.get_epoch_committee_count(active_validator_indices.len()),
|
||||
active_validator_indices,
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiates a builder that will build for the `state`'s next epoch.
|
||||
///
|
||||
/// Note: there are two possible epoch builds for the next epoch, one where there is a registry
|
||||
/// change and one where there is not.
|
||||
pub fn for_next_epoch(
|
||||
state: &BeaconState,
|
||||
active_validator_indices: Vec<usize>,
|
||||
registry_change: bool,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<Self, Error> {
|
||||
let current_epoch = state.current_epoch(spec);
|
||||
let next_epoch = state.next_epoch(spec);
|
||||
let committees_per_epoch = spec.get_epoch_committee_count(active_validator_indices.len());
|
||||
|
||||
let epochs_since_last_registry_update =
|
||||
current_epoch - state.validator_registry_update_epoch;
|
||||
|
||||
let (seed, shuffling_start_shard) = if registry_change {
|
||||
let next_seed = state
|
||||
.generate_seed(next_epoch, spec)
|
||||
.map_err(|_| Error::UnableToGenerateSeed)?;
|
||||
(
|
||||
next_seed,
|
||||
(state.current_shuffling_start_shard + committees_per_epoch) % spec.shard_count,
|
||||
)
|
||||
} else if (epochs_since_last_registry_update > 1)
|
||||
& epochs_since_last_registry_update.is_power_of_two()
|
||||
{
|
||||
let next_seed = state
|
||||
.generate_seed(next_epoch, spec)
|
||||
.map_err(|_| Error::UnableToGenerateSeed)?;
|
||||
(next_seed, state.current_shuffling_start_shard)
|
||||
} else {
|
||||
(
|
||||
state.current_shuffling_seed,
|
||||
state.current_shuffling_start_shard,
|
||||
)
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
epoch: state.next_epoch(spec),
|
||||
shuffling_start_shard,
|
||||
shuffling_seed: seed,
|
||||
active_validator_indices,
|
||||
committees_per_epoch,
|
||||
})
|
||||
}
|
||||
|
||||
/// Consumes the builder, returning a fully-build `EpochCrosslinkCommittee`.
|
||||
pub fn build(self, spec: &ChainSpec) -> Result<EpochCrosslinkCommittees, Error> {
|
||||
// The shuffler fails on a empty list, so if there are no active validator indices, simply
|
||||
// return an empty list.
|
||||
let shuffled_active_validator_indices = if self.active_validator_indices.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
shuffle_list(
|
||||
self.active_validator_indices,
|
||||
spec.shuffle_round_count,
|
||||
&self.shuffling_seed[..],
|
||||
true,
|
||||
)
|
||||
.ok_or_else(|| Error::UnableToShuffle)?
|
||||
};
|
||||
|
||||
let mut committees: Vec<Vec<usize>> = shuffled_active_validator_indices
|
||||
.honey_badger_split(self.committees_per_epoch as usize)
|
||||
.map(|slice: &[usize]| slice.to_vec())
|
||||
.collect();
|
||||
|
||||
let mut epoch_crosslink_committees = EpochCrosslinkCommittees::new(self.epoch, spec);
|
||||
let mut shard = self.shuffling_start_shard;
|
||||
|
||||
let committees_per_slot = (self.committees_per_epoch / spec.slots_per_epoch) as usize;
|
||||
|
||||
for (i, slot) in self.epoch.slot_iter(spec.slots_per_epoch).enumerate() {
|
||||
for j in (0..committees.len())
|
||||
.skip(i * committees_per_slot)
|
||||
.take(committees_per_slot)
|
||||
{
|
||||
let crosslink_committee = CrosslinkCommittee {
|
||||
slot,
|
||||
shard,
|
||||
committee: committees[j].drain(..).collect(),
|
||||
};
|
||||
epoch_crosslink_committees.crosslink_committees[i].push(crosslink_committee);
|
||||
|
||||
shard += 1;
|
||||
shard %= spec.shard_count;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(epoch_crosslink_committees)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use crate::test_utils::*;
|
||||
use swap_or_not_shuffle::shuffle_list;
|
||||
|
||||
fn do_sane_cache_test(
|
||||
state: BeaconState,
|
||||
epoch: Epoch,
|
||||
relative_epoch: RelativeEpoch,
|
||||
validator_count: usize,
|
||||
expected_seed: Hash256,
|
||||
expected_shuffling_start: u64,
|
||||
spec: &ChainSpec,
|
||||
) {
|
||||
let active_indices: Vec<usize> = (0..validator_count).collect();
|
||||
|
||||
assert_eq!(
|
||||
&active_indices[..],
|
||||
state
|
||||
.get_cached_active_validator_indices(relative_epoch, &spec)
|
||||
.unwrap(),
|
||||
"Validator indices mismatch"
|
||||
);
|
||||
|
||||
let shuffling = shuffle_list(
|
||||
active_indices,
|
||||
spec.shuffle_round_count,
|
||||
&expected_seed[..],
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let committees_per_epoch = spec.get_epoch_committee_count(shuffling.len());
|
||||
let committees_per_slot = committees_per_epoch / spec.slots_per_epoch;
|
||||
|
||||
let mut expected_indices_iter = shuffling.iter();
|
||||
let mut shard_counter = expected_shuffling_start;
|
||||
|
||||
for (i, slot) in epoch.slot_iter(spec.slots_per_epoch).enumerate() {
|
||||
let crosslink_committees_at_slot =
|
||||
state.get_crosslink_committees_at_slot(slot, &spec).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
crosslink_committees_at_slot.len(),
|
||||
committees_per_slot as usize,
|
||||
"Bad committees per slot ({})",
|
||||
i
|
||||
);
|
||||
|
||||
for c in crosslink_committees_at_slot {
|
||||
assert_eq!(c.shard, shard_counter, "Bad shard");
|
||||
shard_counter += 1;
|
||||
shard_counter %= spec.shard_count;
|
||||
|
||||
for &i in &c.committee {
|
||||
assert_eq!(
|
||||
i,
|
||||
*expected_indices_iter.next().unwrap(),
|
||||
"Non-sequential validators."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_sane_cache_test(validator_count: usize, spec: &ChainSpec) -> BeaconState {
|
||||
let mut builder =
|
||||
TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(validator_count, spec);
|
||||
|
||||
let epoch = spec.genesis_epoch + 4;
|
||||
let slot = epoch.start_slot(spec.slots_per_epoch);
|
||||
builder.teleport_to_slot(slot, spec);
|
||||
|
||||
let (mut state, _keypairs) = builder.build();
|
||||
|
||||
state.current_shuffling_start_shard = 0;
|
||||
state.current_shuffling_seed = Hash256::from_slice(&[1; 32]);
|
||||
|
||||
state.previous_shuffling_start_shard = spec.shard_count - 1;
|
||||
state.previous_shuffling_seed = Hash256::from_slice(&[2; 32]);
|
||||
|
||||
state
|
||||
.build_epoch_cache(RelativeEpoch::Previous, spec)
|
||||
.unwrap();
|
||||
state
|
||||
.build_epoch_cache(RelativeEpoch::Current, spec)
|
||||
.unwrap();
|
||||
state
|
||||
.build_epoch_cache(RelativeEpoch::NextWithRegistryChange, spec)
|
||||
.unwrap();
|
||||
state
|
||||
.build_epoch_cache(RelativeEpoch::NextWithoutRegistryChange, spec)
|
||||
.unwrap();
|
||||
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_sane_current_epoch_cache() {
|
||||
let mut spec = ChainSpec::few_validators();
|
||||
spec.shard_count = 4;
|
||||
let validator_count = (spec.shard_count * spec.target_committee_size) + 1;
|
||||
let state = setup_sane_cache_test(validator_count as usize, &spec);
|
||||
do_sane_cache_test(
|
||||
state.clone(),
|
||||
state.current_epoch(&spec),
|
||||
RelativeEpoch::Current,
|
||||
validator_count as usize,
|
||||
state.current_shuffling_seed,
|
||||
state.current_shuffling_start_shard,
|
||||
&spec,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_sane_previous_epoch_cache() {
|
||||
let mut spec = ChainSpec::few_validators();
|
||||
spec.shard_count = 2;
|
||||
let validator_count = (spec.shard_count * spec.target_committee_size) + 1;
|
||||
let state = setup_sane_cache_test(validator_count as usize, &spec);
|
||||
do_sane_cache_test(
|
||||
state.clone(),
|
||||
state.previous_epoch(&spec),
|
||||
RelativeEpoch::Previous,
|
||||
validator_count as usize,
|
||||
state.previous_shuffling_seed,
|
||||
state.previous_shuffling_start_shard,
|
||||
&spec,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_sane_next_without_update_epoch_cache() {
|
||||
let mut spec = ChainSpec::few_validators();
|
||||
spec.shard_count = 2;
|
||||
let validator_count = (spec.shard_count * spec.target_committee_size) + 1;
|
||||
let mut state = setup_sane_cache_test(validator_count as usize, &spec);
|
||||
state.validator_registry_update_epoch = state.slot.epoch(spec.slots_per_epoch);
|
||||
do_sane_cache_test(
|
||||
state.clone(),
|
||||
state.next_epoch(&spec),
|
||||
RelativeEpoch::NextWithoutRegistryChange,
|
||||
validator_count as usize,
|
||||
state.current_shuffling_seed,
|
||||
state.current_shuffling_start_shard,
|
||||
&spec,
|
||||
);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
use crate::*;
|
||||
|
||||
/// Verify ``bitfield`` against the ``committee_size``.
|
||||
///
|
||||
/// Is title `verify_bitfield` in spec.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn verify_bitfield_length(bitfield: &Bitfield, committee_size: usize) -> bool {
|
||||
if bitfield.num_bytes() != ((committee_size + 7) / 8) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for i in committee_size..(bitfield.num_bytes() * 8) {
|
||||
if bitfield.get(i).unwrap_or(false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
@@ -1,25 +1,22 @@
|
||||
use crate::*;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
type ValidatorIndex = usize;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Default, Serialize)]
|
||||
#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct PubkeyCache {
|
||||
/// Maintain the number of keys added to the map. It is not sufficient to just use the HashMap
|
||||
/// len, as it does not increase when duplicate keys are added. Duplicate keys are used during
|
||||
/// testing.
|
||||
len: usize,
|
||||
map: HashMap<PublicKey, ValidatorIndex>,
|
||||
}
|
||||
|
||||
impl PubkeyCache {
|
||||
/// Instantiates a new, empty cache.
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
map: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of validator indices already in the map.
|
||||
/// Returns the number of validator indices added to the map so far.
|
||||
pub fn len(&self) -> ValidatorIndex {
|
||||
self.map.len()
|
||||
self.len
|
||||
}
|
||||
|
||||
/// Inserts a validator index into the map.
|
||||
@@ -27,8 +24,9 @@ impl PubkeyCache {
|
||||
/// The added index must equal the number of validators already added to the map. This ensures
|
||||
/// that an index is never skipped.
|
||||
pub fn insert(&mut self, pubkey: PublicKey, index: ValidatorIndex) -> bool {
|
||||
if index == self.map.len() {
|
||||
if index == self.len {
|
||||
self.map.insert(pubkey, index);
|
||||
self.len += 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
||||
@@ -1,53 +1,57 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use crate::test_utils::TestingBeaconStateBuilder;
|
||||
use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
|
||||
use crate::{BeaconState, ChainSpec};
|
||||
|
||||
/// Tests that `get_attestation_participants` is consistent with the result of
|
||||
/// get_crosslink_committees_at_slot` with a full bitfield.
|
||||
#[test]
|
||||
pub fn get_attestation_participants_consistency() {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
|
||||
let spec = ChainSpec::few_validators();
|
||||
let builder = TestingBeaconStateBuilder::from_deterministic_keypairs(8, &spec);
|
||||
let (mut state, _keypairs) = builder.build();
|
||||
|
||||
state
|
||||
.build_epoch_cache(RelativeEpoch::Previous, &spec)
|
||||
.unwrap();
|
||||
state
|
||||
.build_epoch_cache(RelativeEpoch::Current, &spec)
|
||||
.unwrap();
|
||||
state.build_epoch_cache(RelativeEpoch::Next, &spec).unwrap();
|
||||
|
||||
for slot in state
|
||||
.slot
|
||||
.epoch(spec.slots_per_epoch)
|
||||
.slot_iter(spec.slots_per_epoch)
|
||||
{
|
||||
let committees = state.get_crosslink_committees_at_slot(slot, &spec).unwrap();
|
||||
|
||||
for (committee, shard) in committees {
|
||||
let mut attestation_data = AttestationData::random_for_test(&mut rng);
|
||||
attestation_data.slot = slot;
|
||||
attestation_data.shard = *shard;
|
||||
|
||||
let mut bitfield = Bitfield::new();
|
||||
for (i, _) in committee.iter().enumerate() {
|
||||
bitfield.set(i, true);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
state
|
||||
.get_attestation_participants(&attestation_data, &bitfield, &spec)
|
||||
.unwrap(),
|
||||
*committee
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
use crate::test_utils::*;
|
||||
|
||||
ssz_tests!(BeaconState);
|
||||
|
||||
/// Test that
|
||||
///
|
||||
/// 1. Using the cache before it's built fails.
|
||||
/// 2. Using the cache after it's build passes.
|
||||
/// 3. Using the cache after it's dropped fails.
|
||||
fn test_cache_initialization<'a>(
|
||||
state: &'a mut BeaconState,
|
||||
relative_epoch: RelativeEpoch,
|
||||
spec: &ChainSpec,
|
||||
) {
|
||||
let slot = relative_epoch
|
||||
.into_epoch(state.slot.epoch(spec.slots_per_epoch))
|
||||
.start_slot(spec.slots_per_epoch);
|
||||
|
||||
// Assuming the cache isn't already built, assert that a call to a cache-using function fails.
|
||||
assert_eq!(
|
||||
state.get_beacon_proposer_index(slot, relative_epoch, spec),
|
||||
Err(BeaconStateError::EpochCacheUninitialized(relative_epoch))
|
||||
);
|
||||
|
||||
// Build the cache.
|
||||
state.build_epoch_cache(relative_epoch, spec).unwrap();
|
||||
|
||||
// Assert a call to a cache-using function passes.
|
||||
let _ = state
|
||||
.get_beacon_proposer_index(slot, relative_epoch, spec)
|
||||
.unwrap();
|
||||
|
||||
// Drop the cache.
|
||||
state.drop_cache(relative_epoch);
|
||||
|
||||
// Assert a call to a cache-using function fail.
|
||||
assert_eq!(
|
||||
state.get_beacon_proposer_index(slot, relative_epoch, spec),
|
||||
Err(BeaconStateError::EpochCacheUninitialized(relative_epoch))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_initialization() {
|
||||
let spec = ChainSpec::few_validators();
|
||||
let (mut state, _keypairs) =
|
||||
TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(16, &spec).build();
|
||||
|
||||
state.slot = (spec.genesis_epoch + 1).start_slot(spec.slots_per_epoch);
|
||||
|
||||
test_cache_initialization(&mut state, RelativeEpoch::Previous, &spec);
|
||||
test_cache_initialization(&mut state, RelativeEpoch::Current, &spec);
|
||||
test_cache_initialization(&mut state, RelativeEpoch::NextWithRegistryChange, &spec);
|
||||
test_cache_initialization(&mut state, RelativeEpoch::NextWithoutRegistryChange, &spec);
|
||||
}
|
||||
|
||||
+108
-35
@@ -1,21 +1,28 @@
|
||||
use crate::{Address, Epoch, Fork, Hash256, Slot};
|
||||
use crate::*;
|
||||
use bls::Signature;
|
||||
use int_to_bytes::int_to_bytes4;
|
||||
use serde_derive::Deserialize;
|
||||
use test_utils::u8_from_hex_str;
|
||||
|
||||
const GWEI: u64 = 1_000_000_000;
|
||||
|
||||
/// Each of the BLS signature domains.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub enum Domain {
|
||||
Deposit,
|
||||
Attestation,
|
||||
Proposal,
|
||||
Exit,
|
||||
BeaconBlock,
|
||||
Randao,
|
||||
Attestation,
|
||||
Deposit,
|
||||
Exit,
|
||||
Transfer,
|
||||
}
|
||||
|
||||
/// Holds all the "constants" for a BeaconChain.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(PartialEq, Debug, Clone)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(PartialEq, Debug, Clone, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ChainSpec {
|
||||
/*
|
||||
* Misc
|
||||
@@ -23,8 +30,7 @@ pub struct ChainSpec {
|
||||
pub shard_count: u64,
|
||||
pub target_committee_size: u64,
|
||||
pub max_balance_churn_quotient: u64,
|
||||
pub beacon_chain_shard_number: u64,
|
||||
pub max_indices_per_slashable_vote: u64,
|
||||
pub max_indices_per_slashable_vote: usize,
|
||||
pub max_exit_dequeues_per_epoch: u64,
|
||||
pub shuffle_round_count: u8,
|
||||
|
||||
@@ -45,13 +51,14 @@ pub struct ChainSpec {
|
||||
/*
|
||||
* Initial Values
|
||||
*/
|
||||
pub genesis_fork_version: u64,
|
||||
pub genesis_fork_version: u32,
|
||||
pub genesis_slot: Slot,
|
||||
pub genesis_epoch: Epoch,
|
||||
pub genesis_start_shard: u64,
|
||||
pub far_future_epoch: Epoch,
|
||||
pub zero_hash: Hash256,
|
||||
pub empty_signature: Signature,
|
||||
#[serde(deserialize_with = "u8_from_hex_str")]
|
||||
pub bls_withdrawal_prefix_byte: u8,
|
||||
|
||||
/*
|
||||
@@ -63,12 +70,13 @@ pub struct ChainSpec {
|
||||
pub min_seed_lookahead: Epoch,
|
||||
pub activation_exit_delay: u64,
|
||||
pub epochs_per_eth1_voting_period: u64,
|
||||
pub slots_per_historical_root: usize,
|
||||
pub min_validator_withdrawability_delay: Epoch,
|
||||
pub persistent_committee_period: u64,
|
||||
|
||||
/*
|
||||
* State list lengths
|
||||
*/
|
||||
pub latest_block_roots_length: usize,
|
||||
pub latest_randao_mixes_length: usize,
|
||||
pub latest_active_index_roots_length: usize,
|
||||
pub latest_slashed_exit_length: usize,
|
||||
@@ -100,18 +108,25 @@ pub struct ChainSpec {
|
||||
*
|
||||
* Use `ChainSpec::get_domain(..)` to access these values.
|
||||
*/
|
||||
domain_deposit: u64,
|
||||
domain_attestation: u64,
|
||||
domain_proposal: u64,
|
||||
domain_exit: u64,
|
||||
domain_randao: u64,
|
||||
domain_transfer: u64,
|
||||
domain_beacon_block: u32,
|
||||
domain_randao: u32,
|
||||
domain_attestation: u32,
|
||||
domain_deposit: u32,
|
||||
domain_exit: u32,
|
||||
domain_transfer: u32,
|
||||
|
||||
/*
|
||||
* Network specific parameters
|
||||
*
|
||||
*/
|
||||
pub boot_nodes: Vec<Multiaddr>,
|
||||
pub network_id: u8,
|
||||
}
|
||||
|
||||
impl ChainSpec {
|
||||
/// Return the number of committees in one epoch.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn get_epoch_committee_count(&self, active_validator_count: usize) -> u64 {
|
||||
std::cmp::max(
|
||||
1,
|
||||
@@ -124,24 +139,29 @@ impl ChainSpec {
|
||||
|
||||
/// Get the domain number that represents the fork meta and signature domain.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn get_domain(&self, epoch: Epoch, domain: Domain, fork: &Fork) -> u64 {
|
||||
let domain_constant = match domain {
|
||||
Domain::Deposit => self.domain_deposit,
|
||||
Domain::Attestation => self.domain_attestation,
|
||||
Domain::Proposal => self.domain_proposal,
|
||||
Domain::Exit => self.domain_exit,
|
||||
Domain::BeaconBlock => self.domain_beacon_block,
|
||||
Domain::Randao => self.domain_randao,
|
||||
Domain::Attestation => self.domain_attestation,
|
||||
Domain::Deposit => self.domain_deposit,
|
||||
Domain::Exit => self.domain_exit,
|
||||
Domain::Transfer => self.domain_transfer,
|
||||
};
|
||||
|
||||
let fork_version = fork.get_fork_version(epoch);
|
||||
fork_version * u64::pow(2, 32) + domain_constant
|
||||
let mut bytes: Vec<u8> = fork.get_fork_version(epoch).to_vec();
|
||||
bytes.append(&mut int_to_bytes4(domain_constant));
|
||||
|
||||
let mut fork_and_domain = [0; 8];
|
||||
fork_and_domain.copy_from_slice(&bytes);
|
||||
|
||||
u64::from_le_bytes(fork_and_domain)
|
||||
}
|
||||
|
||||
/// Returns a `ChainSpec` compatible with the Ethereum Foundation specification.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn foundation() -> Self {
|
||||
let genesis_slot = Slot::new(2_u64.pow(32));
|
||||
let slots_per_epoch = 64;
|
||||
@@ -154,7 +174,6 @@ impl ChainSpec {
|
||||
shard_count: 1_024,
|
||||
target_committee_size: 128,
|
||||
max_balance_churn_quotient: 32,
|
||||
beacon_chain_shard_number: u64::max_value(),
|
||||
max_indices_per_slashable_vote: 4_096,
|
||||
max_exit_dequeues_per_epoch: 4,
|
||||
shuffle_round_count: 90,
|
||||
@@ -194,12 +213,13 @@ impl ChainSpec {
|
||||
min_seed_lookahead: Epoch::new(1),
|
||||
activation_exit_delay: 4,
|
||||
epochs_per_eth1_voting_period: 16,
|
||||
slots_per_historical_root: 8_192,
|
||||
min_validator_withdrawability_delay: Epoch::new(256),
|
||||
persistent_committee_period: 2_048,
|
||||
|
||||
/*
|
||||
* State list lengths
|
||||
*/
|
||||
latest_block_roots_length: 8_192,
|
||||
latest_randao_mixes_length: 8_192,
|
||||
latest_active_index_roots_length: 8_192,
|
||||
latest_slashed_exit_length: 8_192,
|
||||
@@ -226,18 +246,40 @@ impl ChainSpec {
|
||||
/*
|
||||
* Signature domains
|
||||
*/
|
||||
domain_deposit: 0,
|
||||
domain_attestation: 1,
|
||||
domain_proposal: 2,
|
||||
domain_exit: 3,
|
||||
domain_randao: 4,
|
||||
domain_beacon_block: 0,
|
||||
domain_randao: 1,
|
||||
domain_attestation: 2,
|
||||
domain_deposit: 3,
|
||||
domain_exit: 4,
|
||||
domain_transfer: 5,
|
||||
|
||||
/*
|
||||
* Boot nodes
|
||||
*/
|
||||
boot_nodes: vec![],
|
||||
network_id: 1, // foundation network id
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `ChainSpec` compatible with the Lighthouse testnet specification.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn lighthouse_testnet() -> Self {
|
||||
/*
|
||||
* Lighthouse testnet bootnodes
|
||||
*/
|
||||
let boot_nodes = vec!["/ip4/127.0.0.1/tcp/9000"
|
||||
.parse()
|
||||
.expect("correct multiaddr")];
|
||||
|
||||
Self {
|
||||
boot_nodes,
|
||||
network_id: 2, // lighthouse testnet network id
|
||||
..ChainSpec::few_validators()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `ChainSpec` compatible with the specification suitable for 8 validators.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn few_validators() -> Self {
|
||||
let genesis_slot = Slot::new(2_u64.pow(32));
|
||||
let slots_per_epoch = 8;
|
||||
@@ -254,12 +296,43 @@ impl ChainSpec {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ChainSpec {
|
||||
fn default() -> Self {
|
||||
Self::foundation()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use int_to_bytes::int_to_bytes8;
|
||||
|
||||
#[test]
|
||||
fn test_foundation_spec_can_be_constructed() {
|
||||
let _ = ChainSpec::foundation();
|
||||
}
|
||||
|
||||
fn test_domain(domain_type: Domain, raw_domain: u32, spec: &ChainSpec) {
|
||||
let fork = Fork::genesis(&spec);
|
||||
let epoch = Epoch::new(0);
|
||||
|
||||
let domain = spec.get_domain(epoch, domain_type, &fork);
|
||||
|
||||
let mut expected = fork.get_fork_version(epoch).to_vec();
|
||||
expected.append(&mut int_to_bytes4(raw_domain));
|
||||
|
||||
assert_eq!(int_to_bytes8(domain), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_domain() {
|
||||
let spec = ChainSpec::foundation();
|
||||
|
||||
test_domain(Domain::BeaconBlock, spec.domain_beacon_block, &spec);
|
||||
test_domain(Domain::Randao, spec.domain_randao, &spec);
|
||||
test_domain(Domain::Attestation, spec.domain_attestation, &spec);
|
||||
test_domain(Domain::Deposit, spec.domain_deposit, &spec);
|
||||
test_domain(Domain::Exit, spec.domain_exit, &spec);
|
||||
test_domain(Domain::Transfer, spec.domain_transfer, &spec);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::{Epoch, Hash256};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// Specifies the block hash for a shard at an epoch.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Default, Serialize, Hash, Encode, Decode, TreeHash, TestRandom,
|
||||
Debug,
|
||||
Clone,
|
||||
PartialEq,
|
||||
Default,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Hash,
|
||||
Encode,
|
||||
Decode,
|
||||
TreeHash,
|
||||
TestRandom,
|
||||
)]
|
||||
pub struct Crosslink {
|
||||
pub epoch: Epoch,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
use crate::*;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
|
||||
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize, Decode, Encode, TreeHash)]
|
||||
pub struct CrosslinkCommittee {
|
||||
pub slot: Slot,
|
||||
pub shard: Shard,
|
||||
pub committee: Vec<usize>,
|
||||
}
|
||||
@@ -7,10 +7,10 @@ use test_random_derive::TestRandom;
|
||||
|
||||
/// A deposit to potentially become a beacon chain validator.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct Deposit {
|
||||
pub branch: Vec<Hash256>,
|
||||
pub proof: Vec<Hash256>,
|
||||
pub index: u64,
|
||||
pub deposit_data: DepositData,
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use test_random_derive::TestRandom;
|
||||
|
||||
/// Data generated by the deposit contract.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct DepositData {
|
||||
pub amount: u64,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::*;
|
||||
use bls::{Keypair, PublicKey, Signature};
|
||||
use bls::{PublicKey, Signature};
|
||||
use rand::RngCore;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::{SignedRoot, TreeHash};
|
||||
@@ -9,7 +9,7 @@ use test_random_derive::TestRandom;
|
||||
|
||||
/// The data supplied by the user to the deposit contract.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
PartialEq,
|
||||
@@ -31,25 +31,23 @@ pub struct DepositInput {
|
||||
impl DepositInput {
|
||||
/// Generate the 'proof_of_posession' signature for a given DepositInput details.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn create_proof_of_possession(
|
||||
keypair: &Keypair,
|
||||
withdrawal_credentials: &Hash256,
|
||||
domain: u64,
|
||||
&self,
|
||||
secret_key: &SecretKey,
|
||||
epoch: Epoch,
|
||||
fork: &Fork,
|
||||
spec: &ChainSpec,
|
||||
) -> Signature {
|
||||
let signable_deposit_input = DepositInput {
|
||||
pubkey: keypair.pk.clone(),
|
||||
withdrawal_credentials: withdrawal_credentials.clone(),
|
||||
proof_of_possession: Signature::empty_signature(),
|
||||
};
|
||||
let msg = signable_deposit_input.signed_root();
|
||||
let msg = self.signed_root();
|
||||
let domain = spec.get_domain(epoch, Domain::Deposit, fork);
|
||||
|
||||
Signature::new(msg.as_slice(), domain, &keypair.sk)
|
||||
Signature::new(msg.as_slice(), domain, secret_key)
|
||||
}
|
||||
|
||||
/// Verify that proof-of-possession is valid.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn validate_proof_of_possession(
|
||||
&self,
|
||||
epoch: Epoch,
|
||||
@@ -68,4 +66,23 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
ssz_tests!(DepositInput);
|
||||
|
||||
#[test]
|
||||
fn can_create_and_validate() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let fork = Fork::genesis(&spec);
|
||||
let keypair = Keypair::random();
|
||||
let epoch = Epoch::new(0);
|
||||
|
||||
let mut deposit_input = DepositInput {
|
||||
pubkey: keypair.pk.clone(),
|
||||
withdrawal_credentials: Hash256::zero(),
|
||||
proof_of_possession: Signature::empty_signature(),
|
||||
};
|
||||
|
||||
deposit_input.proof_of_possession =
|
||||
deposit_input.create_proof_of_possession(&keypair.sk, epoch, &fork, &spec);
|
||||
|
||||
assert!(deposit_input.validate_proof_of_possession(epoch, &fork, &spec));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
use super::Hash256;
|
||||
use crate::test_utils::TestRandom;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// Contains data obtained from the Eth1 chain.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Default, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug, PartialEq, Clone, Default, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom,
|
||||
)]
|
||||
pub struct Eth1Data {
|
||||
pub deposit_root: Hash256,
|
||||
pub block_hash: Hash256,
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
use super::Eth1Data;
|
||||
use crate::test_utils::TestRandom;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// A summation of votes for some `Eth1Data`.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Default, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug, PartialEq, Clone, Default, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom,
|
||||
)]
|
||||
pub struct Eth1DataVote {
|
||||
pub eth1_data: Eth1Data,
|
||||
pub vote_count: u64,
|
||||
|
||||
+75
-8
@@ -1,24 +1,46 @@
|
||||
use crate::{test_utils::TestRandom, Epoch};
|
||||
use crate::{
|
||||
test_utils::{fork_from_hex_str, TestRandom},
|
||||
ChainSpec, Epoch,
|
||||
};
|
||||
use int_to_bytes::int_to_bytes4;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// Specifies a fork of the `BeaconChain`, to prevent replay attacks.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Default, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom,
|
||||
)]
|
||||
pub struct Fork {
|
||||
pub previous_version: u64,
|
||||
pub current_version: u64,
|
||||
#[serde(deserialize_with = "fork_from_hex_str")]
|
||||
pub previous_version: [u8; 4],
|
||||
#[serde(deserialize_with = "fork_from_hex_str")]
|
||||
pub current_version: [u8; 4],
|
||||
pub epoch: Epoch,
|
||||
}
|
||||
|
||||
impl Fork {
|
||||
/// Initialize the `Fork` from the genesis parameters in the `spec`.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub fn genesis(spec: &ChainSpec) -> Self {
|
||||
let mut current_version: [u8; 4] = [0; 4];
|
||||
current_version.copy_from_slice(&int_to_bytes4(spec.genesis_fork_version));
|
||||
|
||||
Self {
|
||||
previous_version: current_version,
|
||||
current_version,
|
||||
epoch: spec.genesis_epoch,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the fork version of the given ``epoch``.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn get_fork_version(&self, epoch: Epoch) -> u64 {
|
||||
/// Spec v0.5.0
|
||||
pub fn get_fork_version(&self, epoch: Epoch) -> [u8; 4] {
|
||||
if epoch < self.epoch {
|
||||
return self.previous_version;
|
||||
}
|
||||
@@ -31,4 +53,49 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
ssz_tests!(Fork);
|
||||
|
||||
fn test_genesis(version: u32, epoch: Epoch) {
|
||||
let mut spec = ChainSpec::foundation();
|
||||
|
||||
spec.genesis_fork_version = version;
|
||||
spec.genesis_epoch = epoch;
|
||||
|
||||
let fork = Fork::genesis(&spec);
|
||||
|
||||
assert_eq!(fork.epoch, spec.genesis_epoch, "epoch incorrect");
|
||||
assert_eq!(
|
||||
fork.previous_version, fork.current_version,
|
||||
"previous and current are not identical"
|
||||
);
|
||||
assert_eq!(
|
||||
fork.current_version,
|
||||
version.to_le_bytes(),
|
||||
"current version incorrect"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genesis() {
|
||||
test_genesis(0, Epoch::new(0));
|
||||
test_genesis(9, Epoch::new(11));
|
||||
test_genesis(2_u32.pow(31), Epoch::new(2_u64.pow(63)));
|
||||
test_genesis(u32::max_value(), Epoch::max_value());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_fork_version() {
|
||||
let previous_version = [1; 4];
|
||||
let current_version = [2; 4];
|
||||
let epoch = Epoch::new(10);
|
||||
|
||||
let fork = Fork {
|
||||
previous_version,
|
||||
current_version,
|
||||
epoch,
|
||||
};
|
||||
|
||||
assert_eq!(fork.get_fork_version(epoch - 1), previous_version);
|
||||
assert_eq!(fork.get_fork_version(epoch), current_version);
|
||||
assert_eq!(fork.get_fork_version(epoch + 1), current_version);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::Hash256;
|
||||
use rand::RngCore;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// Historical block and state roots.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct HistoricalBatch {
|
||||
pub block_roots: Vec<Hash256>,
|
||||
pub state_roots: Vec<Hash256>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
ssz_tests!(HistoricalBatch);
|
||||
}
|
||||
+18
-6
@@ -6,12 +6,15 @@ pub mod test_utils;
|
||||
pub mod attestation;
|
||||
pub mod attestation_data;
|
||||
pub mod attestation_data_and_custody_bit;
|
||||
pub mod attestation_duty;
|
||||
pub mod attester_slashing;
|
||||
pub mod beacon_block;
|
||||
pub mod beacon_block_body;
|
||||
pub mod beacon_block_header;
|
||||
pub mod beacon_state;
|
||||
pub mod chain_spec;
|
||||
pub mod crosslink;
|
||||
pub mod crosslink_committee;
|
||||
pub mod deposit;
|
||||
pub mod deposit_data;
|
||||
pub mod deposit_input;
|
||||
@@ -19,20 +22,18 @@ pub mod eth1_data;
|
||||
pub mod eth1_data_vote;
|
||||
pub mod fork;
|
||||
pub mod free_attestation;
|
||||
pub mod historical_batch;
|
||||
pub mod pending_attestation;
|
||||
pub mod proposal;
|
||||
pub mod proposer_slashing;
|
||||
pub mod readers;
|
||||
pub mod shard_reassignment_record;
|
||||
pub mod slashable_attestation;
|
||||
pub mod transfer;
|
||||
pub mod voluntary_exit;
|
||||
#[macro_use]
|
||||
pub mod slot_epoch_macros;
|
||||
pub mod relative_epoch;
|
||||
pub mod slot_epoch;
|
||||
pub mod slot_height;
|
||||
pub mod validator;
|
||||
pub mod validator_registry;
|
||||
|
||||
use ethereum_types::{H160, H256, U256};
|
||||
use std::collections::HashMap;
|
||||
@@ -40,12 +41,15 @@ use std::collections::HashMap;
|
||||
pub use crate::attestation::Attestation;
|
||||
pub use crate::attestation_data::AttestationData;
|
||||
pub use crate::attestation_data_and_custody_bit::AttestationDataAndCustodyBit;
|
||||
pub use crate::attestation_duty::AttestationDuty;
|
||||
pub use crate::attester_slashing::AttesterSlashing;
|
||||
pub use crate::beacon_block::BeaconBlock;
|
||||
pub use crate::beacon_block_body::BeaconBlockBody;
|
||||
pub use crate::beacon_state::{BeaconState, Error as BeaconStateError, RelativeEpoch};
|
||||
pub use crate::beacon_block_header::BeaconBlockHeader;
|
||||
pub use crate::beacon_state::{BeaconState, Error as BeaconStateError};
|
||||
pub use crate::chain_spec::{ChainSpec, Domain};
|
||||
pub use crate::crosslink::Crosslink;
|
||||
pub use crate::crosslink_committee::CrosslinkCommittee;
|
||||
pub use crate::deposit::Deposit;
|
||||
pub use crate::deposit_data::DepositData;
|
||||
pub use crate::deposit_input::DepositInput;
|
||||
@@ -53,9 +57,10 @@ pub use crate::eth1_data::Eth1Data;
|
||||
pub use crate::eth1_data_vote::Eth1DataVote;
|
||||
pub use crate::fork::Fork;
|
||||
pub use crate::free_attestation::FreeAttestation;
|
||||
pub use crate::historical_batch::HistoricalBatch;
|
||||
pub use crate::pending_attestation::PendingAttestation;
|
||||
pub use crate::proposal::Proposal;
|
||||
pub use crate::proposer_slashing::ProposerSlashing;
|
||||
pub use crate::relative_epoch::{Error as RelativeEpochError, RelativeEpoch};
|
||||
pub use crate::slashable_attestation::SlashableAttestation;
|
||||
pub use crate::slot_epoch::{Epoch, Slot};
|
||||
pub use crate::slot_height::SlotHeight;
|
||||
@@ -63,6 +68,10 @@ pub use crate::transfer::Transfer;
|
||||
pub use crate::validator::Validator;
|
||||
pub use crate::voluntary_exit::VoluntaryExit;
|
||||
|
||||
pub type Shard = u64;
|
||||
pub type Committee = Vec<usize>;
|
||||
pub type CrosslinkCommittees = Vec<(Committee, u64)>;
|
||||
|
||||
pub type Hash256 = H256;
|
||||
pub type Address = H160;
|
||||
pub type EthBalance = U256;
|
||||
@@ -76,3 +85,6 @@ pub type AttesterMap = HashMap<(u64, u64), Vec<usize>>;
|
||||
pub type ProposerMap = HashMap<u64, usize>;
|
||||
|
||||
pub use bls::{AggregatePublicKey, AggregateSignature, Keypair, PublicKey, SecretKey, Signature};
|
||||
pub use libp2p::floodsub::{Topic, TopicBuilder};
|
||||
pub use libp2p::multiaddr;
|
||||
pub use libp2p::Multiaddr;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::{AttestationData, Bitfield, Slot};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// An attestation that has been included in the state but not yet fully processed.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct PendingAttestation {
|
||||
pub aggregation_bitfield: Bitfield,
|
||||
pub data: AttestationData,
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::{Hash256, Slot};
|
||||
use bls::Signature;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// A proposal for some shard or beacon block.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom, SignedRoot)]
|
||||
pub struct Proposal {
|
||||
pub slot: Slot,
|
||||
/// Shard number (spec.beacon_chain_shard_number for beacon chain)
|
||||
pub shard: u64,
|
||||
pub block_root: Hash256,
|
||||
pub signature: Signature,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
|
||||
use ssz::{SignedRoot, TreeHash};
|
||||
|
||||
#[derive(TreeHash)]
|
||||
struct SignedProposal {
|
||||
pub slot: Slot,
|
||||
pub shard: u64,
|
||||
pub block_root: Hash256,
|
||||
}
|
||||
|
||||
impl Into<SignedProposal> for Proposal {
|
||||
fn into(self) -> SignedProposal {
|
||||
SignedProposal {
|
||||
slot: self.slot,
|
||||
shard: self.shard,
|
||||
block_root: self.block_root,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_signed_root() {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
let original = Proposal::random_for_test(&mut rng);
|
||||
|
||||
let other: SignedProposal = original.clone().into();
|
||||
|
||||
assert_eq!(original.signed_root(), other.hash_tree_root());
|
||||
}
|
||||
|
||||
ssz_tests!(Proposal);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
use crate::test_utils::TestRandom;
|
||||
use crate::{Hash256, Slot};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Default, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct ProposalSignedData {
|
||||
pub slot: Slot,
|
||||
pub shard: u64,
|
||||
pub block_root: Hash256,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
ssz_tests!(ProposalSignedData);
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
use super::Proposal;
|
||||
use super::BeaconBlockHeader;
|
||||
use crate::test_utils::TestRandom;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// Two conflicting proposals from the same proposer (validator).
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct ProposerSlashing {
|
||||
pub proposer_index: u64,
|
||||
pub proposal_1: Proposal,
|
||||
pub proposal_2: Proposal,
|
||||
pub header_1: BeaconBlockHeader,
|
||||
pub header_2: BeaconBlockHeader,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
use crate::{BeaconBlock, Hash256, Slot};
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// The `BeaconBlockReader` provides interfaces for reading a subset of fields of a `BeaconBlock`.
|
||||
///
|
||||
/// The purpose of this trait is to allow reading from either;
|
||||
/// - a standard `BeaconBlock` struct, or
|
||||
/// - a SSZ serialized byte array.
|
||||
///
|
||||
/// Note: presently, direct SSZ reading has not been implemented so this trait is being used for
|
||||
/// "future proofing".
|
||||
pub trait BeaconBlockReader: Debug + PartialEq {
|
||||
fn slot(&self) -> Slot;
|
||||
fn parent_root(&self) -> Hash256;
|
||||
fn state_root(&self) -> Hash256;
|
||||
fn into_beacon_block(self) -> Option<BeaconBlock>;
|
||||
}
|
||||
|
||||
impl BeaconBlockReader for BeaconBlock {
|
||||
fn slot(&self) -> Slot {
|
||||
self.slot
|
||||
}
|
||||
|
||||
fn parent_root(&self) -> Hash256 {
|
||||
self.parent_root
|
||||
}
|
||||
|
||||
fn state_root(&self) -> Hash256 {
|
||||
self.state_root
|
||||
}
|
||||
|
||||
fn into_beacon_block(self) -> Option<BeaconBlock> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
mod block_reader;
|
||||
mod state_reader;
|
||||
|
||||
pub use self::block_reader::BeaconBlockReader;
|
||||
pub use self::state_reader::BeaconStateReader;
|
||||
@@ -1,25 +0,0 @@
|
||||
use crate::{BeaconState, Slot};
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// The `BeaconStateReader` provides interfaces for reading a subset of fields of a `BeaconState`.
|
||||
///
|
||||
/// The purpose of this trait is to allow reading from either;
|
||||
/// - a standard `BeaconState` struct, or
|
||||
/// - a SSZ serialized byte array.
|
||||
///
|
||||
/// Note: presently, direct SSZ reading has not been implemented so this trait is being used for
|
||||
/// "future proofing".
|
||||
pub trait BeaconStateReader: Debug + PartialEq {
|
||||
fn slot(&self) -> Slot;
|
||||
fn into_beacon_state(self) -> Option<BeaconState>;
|
||||
}
|
||||
|
||||
impl BeaconStateReader for BeaconState {
|
||||
fn slot(&self) -> Slot {
|
||||
self.slot
|
||||
}
|
||||
|
||||
fn into_beacon_state(self) -> Option<BeaconState> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
use crate::*;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Copy)]
|
||||
pub enum Error {
|
||||
EpochTooLow { base: Epoch, other: Epoch },
|
||||
EpochTooHigh { base: Epoch, other: Epoch },
|
||||
AmbiguiousNextEpoch,
|
||||
}
|
||||
|
||||
/// Defines the epochs relative to some epoch. Most useful when referring to the committees prior
|
||||
/// to and following some epoch.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, PartialEq, Clone, Copy)]
|
||||
pub enum RelativeEpoch {
|
||||
/// The prior epoch.
|
||||
Previous,
|
||||
/// The current epoch.
|
||||
Current,
|
||||
/// The next epoch if there _is_ a validator registry update.
|
||||
///
|
||||
/// If the validator registry is updated during an epoch transition, a new shuffling seed is
|
||||
/// generated, this changes the attestation and proposal roles.
|
||||
NextWithRegistryChange,
|
||||
/// The next epoch if there _is not_ a validator registry update.
|
||||
///
|
||||
/// If the validator registry _is not_ updated during an epoch transition, the shuffling stays
|
||||
/// the same.
|
||||
NextWithoutRegistryChange,
|
||||
}
|
||||
|
||||
impl RelativeEpoch {
|
||||
/// Returns the `epoch` that `self` refers to, with respect to the `base` epoch.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub fn into_epoch(self, base: Epoch) -> Epoch {
|
||||
match self {
|
||||
RelativeEpoch::Previous => base - 1,
|
||||
RelativeEpoch::Current => base,
|
||||
RelativeEpoch::NextWithoutRegistryChange => base + 1,
|
||||
RelativeEpoch::NextWithRegistryChange => base + 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the `other` epoch into a `RelativeEpoch`, with respect to `base`
|
||||
///
|
||||
/// ## Errors
|
||||
/// Returns an error when:
|
||||
/// - `EpochTooLow` when `other` is more than 1 prior to `base`.
|
||||
/// - `EpochTooHigh` when `other` is more than 1 after `base`.
|
||||
/// - `AmbiguiousNextEpoch` whenever `other` is one after `base`, because it's unknowable if
|
||||
/// there will be a registry change.
|
||||
///
|
||||
/// Spec v0.5.0
|
||||
pub fn from_epoch(base: Epoch, other: Epoch) -> Result<Self, Error> {
|
||||
if other == base - 1 {
|
||||
Ok(RelativeEpoch::Previous)
|
||||
} else if other == base {
|
||||
Ok(RelativeEpoch::Current)
|
||||
} else if other == base + 1 {
|
||||
Err(Error::AmbiguiousNextEpoch)
|
||||
} else if other < base {
|
||||
Err(Error::EpochTooLow { base, other })
|
||||
} else {
|
||||
Err(Error::EpochTooHigh { base, other })
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience function for `Self::from_epoch` where both slots are converted into epochs.
|
||||
pub fn from_slot(base: Slot, other: Slot, spec: &ChainSpec) -> Result<Self, Error> {
|
||||
Self::from_epoch(
|
||||
base.epoch(spec.slots_per_epoch),
|
||||
other.epoch(spec.slots_per_epoch),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_into_epoch() {
|
||||
let base = Epoch::new(10);
|
||||
|
||||
assert_eq!(RelativeEpoch::Current.into_epoch(base), base);
|
||||
assert_eq!(RelativeEpoch::Previous.into_epoch(base), base - 1);
|
||||
assert_eq!(
|
||||
RelativeEpoch::NextWithRegistryChange.into_epoch(base),
|
||||
base + 1
|
||||
);
|
||||
assert_eq!(
|
||||
RelativeEpoch::NextWithoutRegistryChange.into_epoch(base),
|
||||
base + 1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_epoch() {
|
||||
let base = Epoch::new(10);
|
||||
|
||||
assert_eq!(
|
||||
RelativeEpoch::from_epoch(base, base - 1),
|
||||
Ok(RelativeEpoch::Previous)
|
||||
);
|
||||
assert_eq!(
|
||||
RelativeEpoch::from_epoch(base, base),
|
||||
Ok(RelativeEpoch::Current)
|
||||
);
|
||||
assert_eq!(
|
||||
RelativeEpoch::from_epoch(base, base + 1),
|
||||
Err(RelativeEpochError::AmbiguiousNextEpoch)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_slot() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let base = Epoch::new(10).start_slot(spec.slots_per_epoch);
|
||||
|
||||
assert_eq!(
|
||||
RelativeEpoch::from_slot(base, base - 1, &spec),
|
||||
Ok(RelativeEpoch::Previous)
|
||||
);
|
||||
assert_eq!(
|
||||
RelativeEpoch::from_slot(base, base, &spec),
|
||||
Ok(RelativeEpoch::Current)
|
||||
);
|
||||
assert_eq!(
|
||||
RelativeEpoch::from_slot(base, base + spec.slots_per_epoch, &spec),
|
||||
Err(RelativeEpochError::AmbiguiousNextEpoch)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
use crate::{test_utils::TestRandom, Slot};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct ShardReassignmentRecord {
|
||||
pub validator_index: u64,
|
||||
pub shard: u64,
|
||||
pub slot: Slot,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
ssz_tests!(ShardReassignmentRecord);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{test_utils::TestRandom, AggregateSignature, AttestationData, Bitfield, ChainSpec};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
@@ -9,8 +9,19 @@ use test_random_derive::TestRandom;
|
||||
///
|
||||
/// To be included in an `AttesterSlashing`.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom, SignedRoot)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
PartialEq,
|
||||
Clone,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Encode,
|
||||
Decode,
|
||||
TreeHash,
|
||||
TestRandom,
|
||||
SignedRoot,
|
||||
)]
|
||||
pub struct SlashableAttestation {
|
||||
/// Lists validator registry indices, not committee indices.
|
||||
pub validator_indices: Vec<u64>,
|
||||
@@ -22,17 +33,17 @@ pub struct SlashableAttestation {
|
||||
impl SlashableAttestation {
|
||||
/// Check if ``attestation_data_1`` and ``attestation_data_2`` have the same target.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn is_double_vote(&self, other: &SlashableAttestation, spec: &ChainSpec) -> bool {
|
||||
self.data.slot.epoch(spec.slots_per_epoch) == other.data.slot.epoch(spec.slots_per_epoch)
|
||||
}
|
||||
|
||||
/// Check if ``attestation_data_1`` surrounds ``attestation_data_2``.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
pub fn is_surround_vote(&self, other: &SlashableAttestation, spec: &ChainSpec) -> bool {
|
||||
let source_epoch_1 = self.data.justified_epoch;
|
||||
let source_epoch_2 = other.data.justified_epoch;
|
||||
let source_epoch_1 = self.data.source_epoch;
|
||||
let source_epoch_2 = other.data.source_epoch;
|
||||
let target_epoch_1 = self.data.slot.epoch(spec.slots_per_epoch);
|
||||
let target_epoch_2 = other.data.slot.epoch(spec.slots_per_epoch);
|
||||
|
||||
@@ -123,14 +134,14 @@ mod tests {
|
||||
|
||||
fn create_slashable_attestation(
|
||||
slot_factor: u64,
|
||||
justified_epoch: u64,
|
||||
source_epoch: u64,
|
||||
spec: &ChainSpec,
|
||||
) -> SlashableAttestation {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
let mut slashable_vote = SlashableAttestation::random_for_test(&mut rng);
|
||||
|
||||
slashable_vote.data.slot = Slot::new(slot_factor * spec.slots_per_epoch);
|
||||
slashable_vote.data.justified_epoch = Epoch::new(justified_epoch);
|
||||
slashable_vote.data.source_epoch = Epoch::new(source_epoch);
|
||||
slashable_vote
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
use super::AttestationData;
|
||||
use crate::chain_spec::ChainSpec;
|
||||
use crate::test_utils::TestRandom;
|
||||
use bls::AggregateSignature;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct SlashableVoteData {
|
||||
pub custody_bit_0_indices: Vec<u32>,
|
||||
pub custody_bit_1_indices: Vec<u32>,
|
||||
pub data: AttestationData,
|
||||
pub aggregate_signature: AggregateSignature,
|
||||
}
|
||||
|
||||
impl SlashableVoteData {
|
||||
/// Check if ``attestation_data_1`` and ``attestation_data_2`` have the same target.
|
||||
///
|
||||
/// Spec v0.3.0
|
||||
pub fn is_double_vote(&self, other: &SlashableVoteData, spec: &ChainSpec) -> bool {
|
||||
self.data.slot.epoch(spec.epoch_length) == other.data.slot.epoch(spec.epoch_length)
|
||||
}
|
||||
|
||||
/// Check if ``attestation_data_1`` surrounds ``attestation_data_2``.
|
||||
///
|
||||
/// Spec v0.3.0
|
||||
pub fn is_surround_vote(&self, other: &SlashableVoteData, spec: &ChainSpec) -> bool {
|
||||
let source_epoch_1 = self.data.justified_epoch;
|
||||
let source_epoch_2 = other.data.justified_epoch;
|
||||
let target_epoch_1 = self.data.slot.epoch(spec.epoch_length);
|
||||
let target_epoch_2 = other.data.slot.epoch(spec.epoch_length);
|
||||
|
||||
(source_epoch_1 < source_epoch_2) && (target_epoch_2 < target_epoch_1)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::chain_spec::ChainSpec;
|
||||
use crate::slot_epoch::{Epoch, Slot};
|
||||
use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
|
||||
|
||||
#[test]
|
||||
pub fn test_is_double_vote_true() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let slashable_vote_first = create_slashable_vote_data(1, 1, &spec);
|
||||
let slashable_vote_second = create_slashable_vote_data(1, 1, &spec);
|
||||
|
||||
assert_eq!(
|
||||
slashable_vote_first.is_double_vote(&slashable_vote_second, &spec),
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_double_vote_false() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let slashable_vote_first = create_slashable_vote_data(1, 1, &spec);
|
||||
let slashable_vote_second = create_slashable_vote_data(2, 1, &spec);
|
||||
|
||||
assert_eq!(
|
||||
slashable_vote_first.is_double_vote(&slashable_vote_second, &spec),
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_surround_vote_true() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let slashable_vote_first = create_slashable_vote_data(2, 1, &spec);
|
||||
let slashable_vote_second = create_slashable_vote_data(1, 2, &spec);
|
||||
|
||||
assert_eq!(
|
||||
slashable_vote_first.is_surround_vote(&slashable_vote_second, &spec),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_surround_vote_true_realistic() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let slashable_vote_first = create_slashable_vote_data(4, 1, &spec);
|
||||
let slashable_vote_second = create_slashable_vote_data(3, 2, &spec);
|
||||
|
||||
assert_eq!(
|
||||
slashable_vote_first.is_surround_vote(&slashable_vote_second, &spec),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_surround_vote_false_source_epoch_fails() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let slashable_vote_first = create_slashable_vote_data(2, 2, &spec);
|
||||
let slashable_vote_second = create_slashable_vote_data(1, 1, &spec);
|
||||
|
||||
assert_eq!(
|
||||
slashable_vote_first.is_surround_vote(&slashable_vote_second, &spec),
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_surround_vote_false_target_epoch_fails() {
|
||||
let spec = ChainSpec::foundation();
|
||||
let slashable_vote_first = create_slashable_vote_data(1, 1, &spec);
|
||||
let slashable_vote_second = create_slashable_vote_data(2, 2, &spec);
|
||||
|
||||
assert_eq!(
|
||||
slashable_vote_first.is_surround_vote(&slashable_vote_second, &spec),
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
ssz_tests!(SlashableVoteData);
|
||||
|
||||
fn create_slashable_vote_data(
|
||||
slot_factor: u64,
|
||||
justified_epoch: u64,
|
||||
spec: &ChainSpec,
|
||||
) -> SlashableVoteData {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
let mut slashable_vote = SlashableVoteData::random_for_test(&mut rng);
|
||||
|
||||
slashable_vote.data.slot = Slot::new(slot_factor * spec.epoch_length);
|
||||
slashable_vote.data.justified_epoch = Epoch::new(justified_epoch);
|
||||
slashable_vote
|
||||
}
|
||||
}
|
||||
@@ -130,4 +130,15 @@ mod epoch_tests {
|
||||
assert_eq!(Slot::from(i), slots[i as usize])
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_epoch_ssz() {
|
||||
let max_epoch = Epoch::max_value();
|
||||
let mut ssz = SszStream::new();
|
||||
ssz.append(&max_epoch);
|
||||
let encoded = ssz.drain();
|
||||
assert_eq!(&encoded, &[255, 255, 255, 255, 255, 255, 255, 255]);
|
||||
let (decoded, _i): (Epoch, usize) = <_>::ssz_decode(&encoded, 0).unwrap();
|
||||
assert_eq!(max_epoch, decoded);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
mod macros;
|
||||
mod generate_deterministic_keypairs;
|
||||
mod keypairs_file;
|
||||
mod serde_utils;
|
||||
mod test_random;
|
||||
mod testing_attestation_builder;
|
||||
mod testing_attestation_data_builder;
|
||||
mod testing_attester_slashing_builder;
|
||||
mod testing_beacon_block_builder;
|
||||
mod testing_beacon_state_builder;
|
||||
mod testing_deposit_builder;
|
||||
mod testing_pending_attestation_builder;
|
||||
mod testing_proposer_slashing_builder;
|
||||
mod testing_transfer_builder;
|
||||
mod testing_voluntary_exit_builder;
|
||||
@@ -15,12 +18,15 @@ mod testing_voluntary_exit_builder;
|
||||
pub use generate_deterministic_keypairs::generate_deterministic_keypairs;
|
||||
pub use keypairs_file::KeypairsFile;
|
||||
pub use rand::{prng::XorShiftRng, SeedableRng};
|
||||
pub use serde_utils::{fork_from_hex_str, u8_from_hex_str};
|
||||
pub use test_random::TestRandom;
|
||||
pub use testing_attestation_builder::TestingAttestationBuilder;
|
||||
pub use testing_attestation_data_builder::TestingAttestationDataBuilder;
|
||||
pub use testing_attester_slashing_builder::TestingAttesterSlashingBuilder;
|
||||
pub use testing_beacon_block_builder::TestingBeaconBlockBuilder;
|
||||
pub use testing_beacon_state_builder::{keypairs_path, TestingBeaconStateBuilder};
|
||||
pub use testing_deposit_builder::TestingDepositBuilder;
|
||||
pub use testing_pending_attestation_builder::TestingPendingAttestationBuilder;
|
||||
pub use testing_proposer_slashing_builder::TestingProposerSlashingBuilder;
|
||||
pub use testing_transfer_builder::TestingTransferBuilder;
|
||||
pub use testing_voluntary_exit_builder::TestingVoluntaryExitBuilder;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
use serde::de::Error;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
pub fn u8_from_hex_str<'de, D>(deserializer: D) -> Result<u8, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s: String = Deserialize::deserialize(deserializer)?;
|
||||
|
||||
u8::from_str_radix(&s.as_str()[2..], 16).map_err(D::Error::custom)
|
||||
}
|
||||
|
||||
pub fn fork_from_hex_str<'de, D>(deserializer: D) -> Result<[u8; 4], D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s: String = Deserialize::deserialize(deserializer)?;
|
||||
let mut array = [0 as u8; 4];
|
||||
let decoded: Vec<u8> = hex::decode(&s.as_str()[2..]).map_err(D::Error::custom)?;
|
||||
|
||||
for (i, item) in array.iter_mut().enumerate() {
|
||||
if i > decoded.len() {
|
||||
break;
|
||||
}
|
||||
*item = decoded[i];
|
||||
}
|
||||
Ok(array)
|
||||
}
|
||||
@@ -51,3 +51,17 @@ where
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_test_random_for_u8_array {
|
||||
($len: expr) => {
|
||||
impl<T: RngCore> TestRandom<T> for [u8; $len] {
|
||||
fn random_for_test(rng: &mut T) -> Self {
|
||||
let mut bytes = [0; $len];
|
||||
rng.fill_bytes(&mut bytes);
|
||||
bytes
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_test_random_for_u8_array!(4);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::test_utils::TestingAttestationDataBuilder;
|
||||
use crate::*;
|
||||
use ssz::TreeHash;
|
||||
|
||||
@@ -18,31 +19,7 @@ impl TestingAttestationBuilder {
|
||||
shard: u64,
|
||||
spec: &ChainSpec,
|
||||
) -> Self {
|
||||
let current_epoch = state.current_epoch(spec);
|
||||
let previous_epoch = state.previous_epoch(spec);
|
||||
|
||||
let is_previous_epoch =
|
||||
state.slot.epoch(spec.slots_per_epoch) != slot.epoch(spec.slots_per_epoch);
|
||||
|
||||
let justified_epoch = if is_previous_epoch {
|
||||
state.previous_justified_epoch
|
||||
} else {
|
||||
state.justified_epoch
|
||||
};
|
||||
|
||||
let epoch_boundary_root = if is_previous_epoch {
|
||||
*state
|
||||
.get_block_root(previous_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap()
|
||||
} else {
|
||||
*state
|
||||
.get_block_root(current_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let justified_block_root = *state
|
||||
.get_block_root(justified_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap();
|
||||
let data_builder = TestingAttestationDataBuilder::new(state, shard, slot, spec);
|
||||
|
||||
let mut aggregation_bitfield = Bitfield::new();
|
||||
let mut custody_bitfield = Bitfield::new();
|
||||
@@ -54,16 +31,7 @@ impl TestingAttestationBuilder {
|
||||
|
||||
let attestation = Attestation {
|
||||
aggregation_bitfield,
|
||||
data: AttestationData {
|
||||
slot,
|
||||
shard,
|
||||
beacon_block_root: *state.get_block_root(slot, spec).unwrap(),
|
||||
epoch_boundary_root,
|
||||
crosslink_data_root: Hash256::zero(),
|
||||
latest_crosslink: state.latest_crosslinks[shard as usize].clone(),
|
||||
justified_epoch,
|
||||
justified_block_root,
|
||||
},
|
||||
data: data_builder.build(),
|
||||
custody_bitfield,
|
||||
aggregate_signature: AggregateSignature::new(),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
use crate::*;
|
||||
|
||||
/// Builds an `AttestationData` to be used for testing purposes.
|
||||
///
|
||||
/// This struct should **never be used for production purposes.**
|
||||
pub struct TestingAttestationDataBuilder {
|
||||
data: AttestationData,
|
||||
}
|
||||
|
||||
impl TestingAttestationDataBuilder {
|
||||
/// Configures a new `AttestationData` which attests to all of the same parameters as the
|
||||
/// state.
|
||||
pub fn new(state: &BeaconState, shard: u64, slot: Slot, spec: &ChainSpec) -> Self {
|
||||
let current_epoch = state.current_epoch(spec);
|
||||
let previous_epoch = state.previous_epoch(spec);
|
||||
|
||||
let is_previous_epoch =
|
||||
state.slot.epoch(spec.slots_per_epoch) != slot.epoch(spec.slots_per_epoch);
|
||||
|
||||
let source_epoch = if is_previous_epoch {
|
||||
state.previous_justified_epoch
|
||||
} else {
|
||||
state.current_justified_epoch
|
||||
};
|
||||
|
||||
let target_root = if is_previous_epoch {
|
||||
*state
|
||||
.get_block_root(previous_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap()
|
||||
} else {
|
||||
*state
|
||||
.get_block_root(current_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let source_root = *state
|
||||
.get_block_root(source_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap();
|
||||
|
||||
let data = AttestationData {
|
||||
// LMD GHOST vote
|
||||
slot,
|
||||
beacon_block_root: *state.get_block_root(slot, spec).unwrap(),
|
||||
|
||||
// FFG Vote
|
||||
source_epoch,
|
||||
source_root,
|
||||
target_root,
|
||||
|
||||
// Crosslink vote
|
||||
shard,
|
||||
previous_crosslink: Crosslink {
|
||||
epoch: slot.epoch(spec.slots_per_epoch),
|
||||
crosslink_data_root: spec.zero_hash,
|
||||
},
|
||||
crosslink_data_root: spec.zero_hash,
|
||||
};
|
||||
|
||||
Self { data }
|
||||
}
|
||||
|
||||
/// Returns the `AttestationData`, consuming the builder.
|
||||
pub fn build(self) -> AttestationData {
|
||||
self.data
|
||||
}
|
||||
}
|
||||
@@ -23,45 +23,39 @@ impl TestingAttesterSlashingBuilder {
|
||||
{
|
||||
let double_voted_slot = Slot::new(0);
|
||||
let shard = 0;
|
||||
let justified_epoch = Epoch::new(0);
|
||||
let epoch = Epoch::new(0);
|
||||
let hash_1 = Hash256::from_low_u64_le(1);
|
||||
let hash_2 = Hash256::from_low_u64_le(2);
|
||||
|
||||
let data_1 = AttestationData {
|
||||
slot: double_voted_slot,
|
||||
beacon_block_root: hash_1,
|
||||
source_epoch: epoch,
|
||||
source_root: hash_1,
|
||||
target_root: hash_1,
|
||||
shard,
|
||||
previous_crosslink: Crosslink {
|
||||
epoch,
|
||||
crosslink_data_root: hash_1,
|
||||
},
|
||||
crosslink_data_root: hash_1,
|
||||
};
|
||||
|
||||
let data_2 = AttestationData {
|
||||
beacon_block_root: hash_2,
|
||||
..data_1.clone()
|
||||
};
|
||||
|
||||
let mut slashable_attestation_1 = SlashableAttestation {
|
||||
validator_indices: validator_indices.to_vec(),
|
||||
data: AttestationData {
|
||||
slot: double_voted_slot,
|
||||
shard,
|
||||
beacon_block_root: hash_1,
|
||||
epoch_boundary_root: hash_1,
|
||||
crosslink_data_root: hash_1,
|
||||
latest_crosslink: Crosslink {
|
||||
epoch,
|
||||
crosslink_data_root: hash_1,
|
||||
},
|
||||
justified_epoch,
|
||||
justified_block_root: hash_1,
|
||||
},
|
||||
data: data_1,
|
||||
custody_bitfield: Bitfield::new(),
|
||||
aggregate_signature: AggregateSignature::new(),
|
||||
};
|
||||
|
||||
let mut slashable_attestation_2 = SlashableAttestation {
|
||||
validator_indices: validator_indices.to_vec(),
|
||||
data: AttestationData {
|
||||
slot: double_voted_slot,
|
||||
shard,
|
||||
beacon_block_root: hash_2,
|
||||
epoch_boundary_root: hash_2,
|
||||
crosslink_data_root: hash_2,
|
||||
latest_crosslink: Crosslink {
|
||||
epoch,
|
||||
crosslink_data_root: hash_2,
|
||||
},
|
||||
justified_epoch,
|
||||
justified_block_root: hash_2,
|
||||
},
|
||||
data: data_2,
|
||||
custody_bitfield: Bitfield::new(),
|
||||
aggregate_signature: AggregateSignature::new(),
|
||||
};
|
||||
|
||||
@@ -12,14 +12,14 @@ use ssz::{SignedRoot, TreeHash};
|
||||
///
|
||||
/// This struct should **never be used for production purposes.**
|
||||
pub struct TestingBeaconBlockBuilder {
|
||||
block: BeaconBlock,
|
||||
pub block: BeaconBlock,
|
||||
}
|
||||
|
||||
impl TestingBeaconBlockBuilder {
|
||||
/// Create a new builder from genesis.
|
||||
pub fn new(spec: &ChainSpec) -> Self {
|
||||
Self {
|
||||
block: BeaconBlock::genesis(spec.zero_hash, spec),
|
||||
block: BeaconBlock::empty(spec),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,10 +32,9 @@ impl TestingBeaconBlockBuilder {
|
||||
///
|
||||
/// Modifying the block after signing may invalidate the signature.
|
||||
pub fn sign(&mut self, sk: &SecretKey, fork: &Fork, spec: &ChainSpec) {
|
||||
let proposal = self.block.proposal(spec);
|
||||
let message = proposal.signed_root();
|
||||
let message = self.block.signed_root();
|
||||
let epoch = self.block.slot.epoch(spec.slots_per_epoch);
|
||||
let domain = spec.get_domain(epoch, Domain::Proposal, fork);
|
||||
let domain = spec.get_domain(epoch, Domain::BeaconBlock, fork);
|
||||
self.block.signature = Signature::new(&message, domain, sk);
|
||||
}
|
||||
|
||||
@@ -46,7 +45,7 @@ impl TestingBeaconBlockBuilder {
|
||||
let epoch = self.block.slot.epoch(spec.slots_per_epoch);
|
||||
let message = epoch.hash_tree_root();
|
||||
let domain = spec.get_domain(epoch, Domain::Randao, fork);
|
||||
self.block.randao_reveal = Signature::new(&message, domain, sk);
|
||||
self.block.body.randao_reveal = Signature::new(&message, domain, sk);
|
||||
}
|
||||
|
||||
/// Inserts a signed, valid `ProposerSlashing` for the validator.
|
||||
@@ -74,19 +73,20 @@ impl TestingBeaconBlockBuilder {
|
||||
self.block.body.attester_slashings.push(attester_slashing);
|
||||
}
|
||||
|
||||
/// Fills the block with `MAX_ATTESTATIONS` attestations.
|
||||
/// Fills the block with `num_attestations` attestations.
|
||||
///
|
||||
/// It will first go and get each committee that is able to include an attestation in this
|
||||
/// block. If there are enough committees, it will produce an attestation for each. If there
|
||||
/// are _not_ enough committees, it will start splitting the committees in half until it
|
||||
/// block. If there _are_ enough committees, it will produce an attestation for each. If there
|
||||
/// _are not_ enough committees, it will start splitting the committees in half until it
|
||||
/// achieves the target. It will then produce separate attestations for each split committee.
|
||||
///
|
||||
/// Note: the signed messages of the split committees will be identical -- it would be possible
|
||||
/// to aggregate these split attestations.
|
||||
pub fn fill_with_attestations(
|
||||
pub fn insert_attestations(
|
||||
&mut self,
|
||||
state: &BeaconState,
|
||||
secret_keys: &[&SecretKey],
|
||||
num_attestations: usize,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), BeaconStateError> {
|
||||
let mut slot = self.block.slot - spec.min_attestation_inclusion_delay;
|
||||
@@ -109,12 +109,17 @@ impl TestingBeaconBlockBuilder {
|
||||
break;
|
||||
}
|
||||
|
||||
for (committee, shard) in state.get_crosslink_committees_at_slot(slot, spec)? {
|
||||
if attestations_added >= spec.max_attestations {
|
||||
for crosslink_committee in state.get_crosslink_committees_at_slot(slot, spec)? {
|
||||
if attestations_added >= num_attestations {
|
||||
break;
|
||||
}
|
||||
|
||||
committees.push((slot, committee.clone(), committee.clone(), *shard));
|
||||
committees.push((
|
||||
slot,
|
||||
crosslink_committee.committee.clone(),
|
||||
crosslink_committee.committee.clone(),
|
||||
crosslink_committee.shard,
|
||||
));
|
||||
|
||||
attestations_added += 1;
|
||||
}
|
||||
@@ -125,12 +130,12 @@ impl TestingBeaconBlockBuilder {
|
||||
// Loop through all the committees, splitting each one in half until we have
|
||||
// `MAX_ATTESTATIONS` committees.
|
||||
loop {
|
||||
if committees.len() >= spec.max_attestations as usize {
|
||||
if committees.len() >= num_attestations as usize {
|
||||
break;
|
||||
}
|
||||
|
||||
for index in 0..committees.len() {
|
||||
if committees.len() >= spec.max_attestations as usize {
|
||||
if committees.len() >= num_attestations as usize {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -175,9 +180,14 @@ impl TestingBeaconBlockBuilder {
|
||||
) {
|
||||
let keypair = Keypair::random();
|
||||
|
||||
let mut builder = TestingDepositBuilder::new(amount);
|
||||
let mut builder = TestingDepositBuilder::new(keypair.pk.clone(), amount);
|
||||
builder.set_index(index);
|
||||
builder.sign(&keypair, state, spec);
|
||||
builder.sign(
|
||||
&keypair,
|
||||
state.slot.epoch(spec.slots_per_epoch),
|
||||
&state.fork,
|
||||
spec,
|
||||
);
|
||||
|
||||
self.block.body.deposits.push(builder.build())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{generate_deterministic_keypairs, KeypairsFile};
|
||||
use crate::beacon_state::BeaconStateBuilder;
|
||||
use crate::test_utils::TestingPendingAttestationBuilder;
|
||||
use crate::*;
|
||||
use bls::get_withdrawal_credentials;
|
||||
use dirs;
|
||||
@@ -109,7 +109,8 @@ impl TestingBeaconStateBuilder {
|
||||
Validator {
|
||||
pubkey: keypair.pk.clone(),
|
||||
withdrawal_credentials,
|
||||
activation_epoch: spec.far_future_epoch,
|
||||
// All validators start active.
|
||||
activation_epoch: spec.genesis_epoch,
|
||||
exit_epoch: spec.far_future_epoch,
|
||||
withdrawable_epoch: spec.far_future_epoch,
|
||||
initiated_exit: false,
|
||||
@@ -118,7 +119,7 @@ impl TestingBeaconStateBuilder {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut state_builder = BeaconStateBuilder::new(
|
||||
let mut state = BeaconState::genesis(
|
||||
0,
|
||||
Eth1Data {
|
||||
deposit_root: Hash256::zero(),
|
||||
@@ -130,16 +131,10 @@ impl TestingBeaconStateBuilder {
|
||||
let balances = vec![32_000_000_000; validator_count];
|
||||
|
||||
debug!("Importing {} existing validators...", validator_count);
|
||||
state_builder.import_existing_validators(
|
||||
validators,
|
||||
balances,
|
||||
validator_count as u64,
|
||||
spec,
|
||||
);
|
||||
state.validator_registry = validators;
|
||||
state.validator_balances = balances;
|
||||
|
||||
let state = state_builder.build(spec).unwrap();
|
||||
|
||||
debug!("BeaconState built.");
|
||||
debug!("BeaconState initialized.");
|
||||
|
||||
Self { state, keypairs }
|
||||
}
|
||||
@@ -158,7 +153,8 @@ impl TestingBeaconStateBuilder {
|
||||
|
||||
state.build_epoch_cache(RelativeEpoch::Previous, &spec)?;
|
||||
state.build_epoch_cache(RelativeEpoch::Current, &spec)?;
|
||||
state.build_epoch_cache(RelativeEpoch::Next, &spec)?;
|
||||
state.build_epoch_cache(RelativeEpoch::NextWithRegistryChange, &spec)?;
|
||||
state.build_epoch_cache(RelativeEpoch::NextWithoutRegistryChange, &spec)?;
|
||||
|
||||
state.update_pubkey_cache()?;
|
||||
|
||||
@@ -189,7 +185,7 @@ impl TestingBeaconStateBuilder {
|
||||
state.current_shuffling_seed = Hash256::from_low_u64_le(1);
|
||||
|
||||
state.previous_justified_epoch = epoch - 3;
|
||||
state.justified_epoch = epoch - 2;
|
||||
state.current_justified_epoch = epoch - 2;
|
||||
state.justification_bitfield = u64::max_value();
|
||||
|
||||
state.finalized_epoch = epoch - 3;
|
||||
@@ -218,7 +214,7 @@ impl TestingBeaconStateBuilder {
|
||||
- spec.min_attestation_inclusion_delay;
|
||||
let last_slot = std::cmp::min(state.slot.as_u64(), last_slot);
|
||||
|
||||
for slot in first_slot..last_slot + 1 {
|
||||
for slot in first_slot..=last_slot {
|
||||
let slot = Slot::from(slot);
|
||||
|
||||
let committees = state
|
||||
@@ -226,77 +222,24 @@ impl TestingBeaconStateBuilder {
|
||||
.unwrap()
|
||||
.clone();
|
||||
|
||||
for (committee, shard) in committees {
|
||||
state
|
||||
.latest_attestations
|
||||
.push(committee_to_pending_attestation(
|
||||
state, &committee, shard, slot, spec,
|
||||
))
|
||||
for crosslink_committee in committees {
|
||||
let mut builder = TestingPendingAttestationBuilder::new(
|
||||
state,
|
||||
crosslink_committee.shard,
|
||||
slot,
|
||||
spec,
|
||||
);
|
||||
// The entire committee should have signed the pending attestation.
|
||||
let signers = vec![true; crosslink_committee.committee.len()];
|
||||
builder.add_committee_participation(signers);
|
||||
let attestation = builder.build();
|
||||
|
||||
if attestation.data.slot.epoch(spec.slots_per_epoch) < state.current_epoch(spec) {
|
||||
state.previous_epoch_attestations.push(attestation)
|
||||
} else {
|
||||
state.current_epoch_attestations.push(attestation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a committee to a `PendingAttestation`.
|
||||
///
|
||||
/// The committee will be signed by all validators in the committee.
|
||||
fn committee_to_pending_attestation(
|
||||
state: &BeaconState,
|
||||
committee: &[usize],
|
||||
shard: u64,
|
||||
slot: Slot,
|
||||
spec: &ChainSpec,
|
||||
) -> PendingAttestation {
|
||||
let current_epoch = state.current_epoch(spec);
|
||||
let previous_epoch = state.previous_epoch(spec);
|
||||
|
||||
let mut aggregation_bitfield = Bitfield::new();
|
||||
let mut custody_bitfield = Bitfield::new();
|
||||
|
||||
for (i, _) in committee.iter().enumerate() {
|
||||
aggregation_bitfield.set(i, true);
|
||||
custody_bitfield.set(i, true);
|
||||
}
|
||||
|
||||
let is_previous_epoch =
|
||||
state.slot.epoch(spec.slots_per_epoch) != slot.epoch(spec.slots_per_epoch);
|
||||
|
||||
let justified_epoch = if is_previous_epoch {
|
||||
state.previous_justified_epoch
|
||||
} else {
|
||||
state.justified_epoch
|
||||
};
|
||||
|
||||
let epoch_boundary_root = if is_previous_epoch {
|
||||
*state
|
||||
.get_block_root(previous_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap()
|
||||
} else {
|
||||
*state
|
||||
.get_block_root(current_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let justified_block_root = *state
|
||||
.get_block_root(justified_epoch.start_slot(spec.slots_per_epoch), spec)
|
||||
.unwrap();
|
||||
|
||||
PendingAttestation {
|
||||
aggregation_bitfield,
|
||||
data: AttestationData {
|
||||
slot,
|
||||
shard,
|
||||
beacon_block_root: *state.get_block_root(slot, spec).unwrap(),
|
||||
epoch_boundary_root,
|
||||
crosslink_data_root: Hash256::zero(),
|
||||
latest_crosslink: Crosslink {
|
||||
epoch: slot.epoch(spec.slots_per_epoch),
|
||||
crosslink_data_root: Hash256::zero(),
|
||||
},
|
||||
justified_epoch,
|
||||
justified_block_root,
|
||||
},
|
||||
custody_bitfield,
|
||||
inclusion_slot: slot + spec.min_attestation_inclusion_delay,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,17 +10,15 @@ pub struct TestingDepositBuilder {
|
||||
|
||||
impl TestingDepositBuilder {
|
||||
/// Instantiates a new builder.
|
||||
pub fn new(amount: u64) -> Self {
|
||||
let keypair = Keypair::random();
|
||||
|
||||
pub fn new(pubkey: PublicKey, amount: u64) -> Self {
|
||||
let deposit = Deposit {
|
||||
branch: vec![],
|
||||
proof: vec![],
|
||||
index: 0,
|
||||
deposit_data: DepositData {
|
||||
amount,
|
||||
timestamp: 1,
|
||||
deposit_input: DepositInput {
|
||||
pubkey: keypair.pk,
|
||||
pubkey,
|
||||
withdrawal_credentials: Hash256::zero(),
|
||||
proof_of_possession: Signature::empty_signature(),
|
||||
},
|
||||
@@ -40,21 +38,22 @@ impl TestingDepositBuilder {
|
||||
/// - `pubkey` to the signing pubkey.
|
||||
/// - `withdrawal_credentials` to the signing pubkey.
|
||||
/// - `proof_of_possesssion`
|
||||
pub fn sign(&mut self, keypair: &Keypair, state: &BeaconState, spec: &ChainSpec) {
|
||||
pub fn sign(&mut self, keypair: &Keypair, epoch: Epoch, fork: &Fork, spec: &ChainSpec) {
|
||||
let withdrawal_credentials = Hash256::from_slice(
|
||||
&get_withdrawal_credentials(&keypair.pk, spec.bls_withdrawal_prefix_byte)[..],
|
||||
);
|
||||
|
||||
let epoch = state.current_epoch(spec);
|
||||
let domain = spec.get_domain(epoch, Domain::Deposit, &state.fork);
|
||||
|
||||
self.deposit.deposit_data.deposit_input.pubkey = keypair.pk.clone();
|
||||
self.deposit
|
||||
.deposit_data
|
||||
.deposit_input
|
||||
.withdrawal_credentials = withdrawal_credentials.clone();
|
||||
self.deposit.deposit_data.deposit_input.proof_of_possession =
|
||||
DepositInput::create_proof_of_possession(&keypair, &withdrawal_credentials, domain);
|
||||
.withdrawal_credentials = withdrawal_credentials;
|
||||
|
||||
self.deposit.deposit_data.deposit_input.proof_of_possession = self
|
||||
.deposit
|
||||
.deposit_data
|
||||
.deposit_input
|
||||
.create_proof_of_possession(&keypair.sk, epoch, fork, spec);
|
||||
}
|
||||
|
||||
/// Builds the deposit, consuming the builder.
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
use crate::test_utils::TestingAttestationDataBuilder;
|
||||
use crate::*;
|
||||
|
||||
/// Builds an `AttesterSlashing` to be used for testing purposes.
|
||||
///
|
||||
/// This struct should **never be used for production purposes.**
|
||||
pub struct TestingPendingAttestationBuilder {
|
||||
pending_attestation: PendingAttestation,
|
||||
}
|
||||
|
||||
impl TestingPendingAttestationBuilder {
|
||||
/// Create a new valid* `PendingAttestation` for the given parameters.
|
||||
///
|
||||
/// The `inclusion_slot` will be set to be the earliest possible slot the `Attestation` could
|
||||
/// have been included (`slot + MIN_ATTESTATION_INCLUSION_DELAY`).
|
||||
///
|
||||
/// * The aggregation and custody bitfields will all be empty, they need to be set with
|
||||
/// `Self::add_committee_participation`.
|
||||
pub fn new(state: &BeaconState, shard: u64, slot: Slot, spec: &ChainSpec) -> Self {
|
||||
let data_builder = TestingAttestationDataBuilder::new(state, shard, slot, spec);
|
||||
|
||||
let pending_attestation = PendingAttestation {
|
||||
aggregation_bitfield: Bitfield::new(),
|
||||
data: data_builder.build(),
|
||||
custody_bitfield: Bitfield::new(),
|
||||
inclusion_slot: slot + spec.min_attestation_inclusion_delay,
|
||||
};
|
||||
|
||||
Self {
|
||||
pending_attestation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the committee participation in the `PendingAttestation`.
|
||||
///
|
||||
/// The `PendingAttestation` will appear to be signed by each committee member who's value in
|
||||
/// `signers` is true.
|
||||
pub fn add_committee_participation(&mut self, signers: Vec<bool>) {
|
||||
let mut aggregation_bitfield = Bitfield::new();
|
||||
let mut custody_bitfield = Bitfield::new();
|
||||
|
||||
for (i, signed) in signers.iter().enumerate() {
|
||||
aggregation_bitfield.set(i, *signed);
|
||||
custody_bitfield.set(i, false); // Fixed to `false` for phase 0.
|
||||
}
|
||||
|
||||
self.pending_attestation.aggregation_bitfield = aggregation_bitfield;
|
||||
self.pending_attestation.custody_bitfield = custody_bitfield;
|
||||
}
|
||||
|
||||
/// Returns the `PendingAttestation`, consuming the builder.
|
||||
pub fn build(self) -> PendingAttestation {
|
||||
self.pending_attestation
|
||||
}
|
||||
}
|
||||
@@ -22,38 +22,38 @@ impl TestingProposerSlashingBuilder {
|
||||
F: Fn(u64, &[u8], Epoch, Domain) -> Signature,
|
||||
{
|
||||
let slot = Slot::new(0);
|
||||
let shard = 0;
|
||||
let hash_1 = Hash256::from([1; 32]);
|
||||
let hash_2 = Hash256::from([2; 32]);
|
||||
|
||||
let mut proposal_1 = Proposal {
|
||||
let mut header_1 = BeaconBlockHeader {
|
||||
slot,
|
||||
shard,
|
||||
block_root: Hash256::from_low_u64_le(1),
|
||||
previous_block_root: hash_1,
|
||||
state_root: hash_1,
|
||||
block_body_root: hash_1,
|
||||
signature: Signature::empty_signature(),
|
||||
};
|
||||
|
||||
let mut proposal_2 = Proposal {
|
||||
slot,
|
||||
shard,
|
||||
block_root: Hash256::from_low_u64_le(2),
|
||||
signature: Signature::empty_signature(),
|
||||
let mut header_2 = BeaconBlockHeader {
|
||||
previous_block_root: hash_2,
|
||||
..header_1.clone()
|
||||
};
|
||||
|
||||
proposal_1.signature = {
|
||||
let message = proposal_1.signed_root();
|
||||
header_1.signature = {
|
||||
let message = header_1.signed_root();
|
||||
let epoch = slot.epoch(spec.slots_per_epoch);
|
||||
signer(proposer_index, &message[..], epoch, Domain::Proposal)
|
||||
signer(proposer_index, &message[..], epoch, Domain::BeaconBlock)
|
||||
};
|
||||
|
||||
proposal_2.signature = {
|
||||
let message = proposal_2.signed_root();
|
||||
header_2.signature = {
|
||||
let message = header_2.signed_root();
|
||||
let epoch = slot.epoch(spec.slots_per_epoch);
|
||||
signer(proposer_index, &message[..], epoch, Domain::Proposal)
|
||||
signer(proposer_index, &message[..], epoch, Domain::BeaconBlock)
|
||||
};
|
||||
|
||||
ProposerSlashing {
|
||||
proposer_index,
|
||||
proposal_1,
|
||||
proposal_2,
|
||||
header_1,
|
||||
header_2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,12 @@ pub struct TestingTransferBuilder {
|
||||
|
||||
impl TestingTransferBuilder {
|
||||
/// Instantiates a new builder.
|
||||
pub fn new(from: u64, to: u64, amount: u64, slot: Slot) -> Self {
|
||||
pub fn new(sender: u64, recipient: u64, amount: u64, slot: Slot) -> Self {
|
||||
let keypair = Keypair::random();
|
||||
|
||||
let transfer = Transfer {
|
||||
from,
|
||||
to,
|
||||
sender,
|
||||
recipient,
|
||||
amount,
|
||||
fee: 0,
|
||||
slot,
|
||||
|
||||
@@ -2,18 +2,29 @@ use super::Slot;
|
||||
use crate::test_utils::TestRandom;
|
||||
use bls::{PublicKey, Signature};
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// The data submitted to the deposit contract.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom, SignedRoot)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
PartialEq,
|
||||
Clone,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Encode,
|
||||
Decode,
|
||||
TreeHash,
|
||||
TestRandom,
|
||||
SignedRoot,
|
||||
)]
|
||||
pub struct Transfer {
|
||||
pub from: u64,
|
||||
pub to: u64,
|
||||
pub sender: u64,
|
||||
pub recipient: u64,
|
||||
pub amount: u64,
|
||||
pub fee: u64,
|
||||
pub slot: Slot,
|
||||
|
||||
+50
-19
@@ -6,7 +6,7 @@ use test_random_derive::TestRandom;
|
||||
|
||||
/// Information about a `BeaconChain` validator.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
/// Spec v0.5.0
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode, TestRandom, TreeHash)]
|
||||
pub struct Validator {
|
||||
pub pubkey: PublicKey,
|
||||
@@ -53,29 +53,60 @@ impl Default for Validator {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
|
||||
|
||||
#[test]
|
||||
fn test_validator_can_be_active() {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
let mut validator = Validator::random_for_test(&mut rng);
|
||||
fn default() {
|
||||
let v = Validator::default();
|
||||
|
||||
let activation_epoch = u64::random_for_test(&mut rng);
|
||||
let exit_epoch = activation_epoch + 234;
|
||||
let epoch = Epoch::new(0);
|
||||
|
||||
validator.activation_epoch = Epoch::from(activation_epoch);
|
||||
validator.exit_epoch = Epoch::from(exit_epoch);
|
||||
assert_eq!(v.is_active_at(epoch), false);
|
||||
assert_eq!(v.is_exited_at(epoch), false);
|
||||
assert_eq!(v.is_withdrawable_at(epoch), false);
|
||||
assert_eq!(v.initiated_exit, false);
|
||||
assert_eq!(v.slashed, false);
|
||||
}
|
||||
|
||||
for slot in (activation_epoch - 100)..(exit_epoch + 100) {
|
||||
let slot = Epoch::from(slot);
|
||||
if slot < activation_epoch {
|
||||
assert!(!validator.is_active_at(slot));
|
||||
} else if slot >= exit_epoch {
|
||||
assert!(!validator.is_active_at(slot));
|
||||
} else {
|
||||
assert!(validator.is_active_at(slot));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn is_active_at() {
|
||||
let epoch = Epoch::new(10);
|
||||
|
||||
let v = Validator {
|
||||
activation_epoch: epoch,
|
||||
..Validator::default()
|
||||
};
|
||||
|
||||
assert_eq!(v.is_active_at(epoch - 1), false);
|
||||
assert_eq!(v.is_active_at(epoch), true);
|
||||
assert_eq!(v.is_active_at(epoch + 1), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_exited_at() {
|
||||
let epoch = Epoch::new(10);
|
||||
|
||||
let v = Validator {
|
||||
exit_epoch: epoch,
|
||||
..Validator::default()
|
||||
};
|
||||
|
||||
assert_eq!(v.is_exited_at(epoch - 1), false);
|
||||
assert_eq!(v.is_exited_at(epoch), true);
|
||||
assert_eq!(v.is_exited_at(epoch + 1), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_withdrawable_at() {
|
||||
let epoch = Epoch::new(10);
|
||||
|
||||
let v = Validator {
|
||||
withdrawable_epoch: epoch,
|
||||
..Validator::default()
|
||||
};
|
||||
|
||||
assert_eq!(v.is_withdrawable_at(epoch - 1), false);
|
||||
assert_eq!(v.is_withdrawable_at(epoch), true);
|
||||
assert_eq!(v.is_withdrawable_at(epoch + 1), true);
|
||||
}
|
||||
|
||||
ssz_tests!(Validator);
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
/// Contains logic to manipulate a `&[Validator]`.
|
||||
/// For now, we avoid defining a newtype and just have flat functions here.
|
||||
use super::validator::*;
|
||||
use crate::Epoch;
|
||||
|
||||
/// Given an indexed sequence of `validators`, return the indices corresponding to validators that are active at `epoch`.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn get_active_validator_indices(validators: &[Validator], epoch: Epoch) -> Vec<usize> {
|
||||
validators
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, validator)| {
|
||||
if validator.is_active_at(epoch) {
|
||||
Some(index)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
|
||||
|
||||
#[test]
|
||||
fn can_get_empty_active_validator_indices() {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
|
||||
let validators = vec![];
|
||||
let some_epoch = Epoch::random_for_test(&mut rng);
|
||||
let indices = get_active_validator_indices(&validators, some_epoch);
|
||||
assert_eq!(indices, vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_get_no_active_validator_indices() {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
let mut validators = vec![];
|
||||
let count_validators = 10;
|
||||
for _ in 0..count_validators {
|
||||
validators.push(Validator::default())
|
||||
}
|
||||
|
||||
let some_epoch = Epoch::random_for_test(&mut rng);
|
||||
let indices = get_active_validator_indices(&validators, some_epoch);
|
||||
assert_eq!(indices, vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_get_all_active_validator_indices() {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
let count_validators = 10;
|
||||
let some_epoch = Epoch::random_for_test(&mut rng);
|
||||
|
||||
let mut validators = (0..count_validators)
|
||||
.into_iter()
|
||||
.map(|_| {
|
||||
let mut validator = Validator::default();
|
||||
|
||||
let activation_offset = u64::random_for_test(&mut rng);
|
||||
let exit_offset = u64::random_for_test(&mut rng);
|
||||
|
||||
validator.activation_epoch = some_epoch - activation_offset;
|
||||
validator.exit_epoch = some_epoch + exit_offset;
|
||||
|
||||
validator
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// test boundary condition by ensuring that at least one validator in the list just activated
|
||||
if let Some(validator) = validators.get_mut(0) {
|
||||
validator.activation_epoch = some_epoch;
|
||||
}
|
||||
|
||||
let indices = get_active_validator_indices(&validators, some_epoch);
|
||||
assert_eq!(
|
||||
indices,
|
||||
(0..count_validators).into_iter().collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
fn set_validators_to_default_entry_exit(validators: &mut [Validator]) {
|
||||
for validator in validators.iter_mut() {
|
||||
validator.activation_epoch = Epoch::max_value();
|
||||
validator.exit_epoch = Epoch::max_value();
|
||||
}
|
||||
}
|
||||
|
||||
// sets all `validators` to be active as of some epoch prior to `epoch`. returns the activation epoch.
|
||||
fn set_validators_to_activated(validators: &mut [Validator], epoch: Epoch) -> Epoch {
|
||||
let activation_epoch = epoch - 10;
|
||||
for validator in validators.iter_mut() {
|
||||
validator.activation_epoch = activation_epoch;
|
||||
}
|
||||
activation_epoch
|
||||
}
|
||||
|
||||
// sets all `validators` to be exited as of some epoch before `epoch`.
|
||||
fn set_validators_to_exited(
|
||||
validators: &mut [Validator],
|
||||
epoch: Epoch,
|
||||
activation_epoch: Epoch,
|
||||
) {
|
||||
assert!(activation_epoch < epoch);
|
||||
let mut exit_epoch = activation_epoch + 10;
|
||||
while exit_epoch >= epoch {
|
||||
exit_epoch -= 1;
|
||||
}
|
||||
assert!(activation_epoch < exit_epoch && exit_epoch < epoch);
|
||||
|
||||
for validator in validators.iter_mut() {
|
||||
validator.exit_epoch = exit_epoch;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_get_some_active_validator_indices() {
|
||||
let mut rng = XorShiftRng::from_seed([42; 16]);
|
||||
const COUNT_PARTITIONS: usize = 3;
|
||||
const COUNT_VALIDATORS: usize = 3 * COUNT_PARTITIONS;
|
||||
let some_epoch: Epoch = Epoch::random_for_test(&mut rng);
|
||||
|
||||
let mut validators = (0..COUNT_VALIDATORS)
|
||||
.into_iter()
|
||||
.map(|_| {
|
||||
let mut validator = Validator::default();
|
||||
|
||||
let activation_offset = Epoch::random_for_test(&mut rng);
|
||||
let exit_offset = Epoch::random_for_test(&mut rng);
|
||||
|
||||
validator.activation_epoch = some_epoch - activation_offset;
|
||||
validator.exit_epoch = some_epoch + exit_offset;
|
||||
|
||||
validator
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// we partition the set into partitions based on lifecycle:
|
||||
for (i, chunk) in validators.chunks_exact_mut(COUNT_PARTITIONS).enumerate() {
|
||||
match i {
|
||||
0 => {
|
||||
// 1. not activated (Default::default())
|
||||
set_validators_to_default_entry_exit(chunk);
|
||||
}
|
||||
1 => {
|
||||
// 2. activated, but not exited
|
||||
set_validators_to_activated(chunk, some_epoch);
|
||||
// test boundary condition by ensuring that at least one validator in the list just activated
|
||||
if let Some(validator) = chunk.get_mut(0) {
|
||||
validator.activation_epoch = some_epoch;
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
// 3. exited
|
||||
let activation_epoch = set_validators_to_activated(chunk, some_epoch);
|
||||
set_validators_to_exited(chunk, some_epoch, activation_epoch);
|
||||
// test boundary condition by ensuring that at least one validator in the list just exited
|
||||
if let Some(validator) = chunk.get_mut(0) {
|
||||
validator.exit_epoch = some_epoch;
|
||||
}
|
||||
}
|
||||
_ => unreachable!(
|
||||
"constants local to this test not in sync with generation of test case"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
let indices = get_active_validator_indices(&validators, some_epoch);
|
||||
assert_eq!(indices, vec![3, 4, 5]);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
use crate::{test_utils::TestRandom, Hash256, Slot};
|
||||
use bls::PublicKey;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use ssz_derive::{Decode, Encode, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
// The information gathered from the PoW chain validator registration function.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Encode, Decode, TreeHash, TestRandom)]
|
||||
pub struct ValidatorRegistryDeltaBlock {
|
||||
pub latest_registry_delta_root: Hash256,
|
||||
pub validator_index: u32,
|
||||
pub pubkey: PublicKey,
|
||||
pub slot: Slot,
|
||||
pub flag: u64,
|
||||
}
|
||||
|
||||
impl Default for ValidatorRegistryDeltaBlock {
|
||||
/// Yields a "default" `Validator`. Primarily used for testing.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
latest_registry_delta_root: Hash256::zero(),
|
||||
validator_index: std::u32::MAX,
|
||||
pubkey: PublicKey::default(),
|
||||
slot: Slot::from(std::u64::MAX),
|
||||
flag: std::u64::MAX,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
ssz_tests!(ValidatorRegistryDeltaBlock);
|
||||
}
|
||||
@@ -1,15 +1,26 @@
|
||||
use crate::{test_utils::TestRandom, Epoch};
|
||||
use bls::Signature;
|
||||
use rand::RngCore;
|
||||
use serde_derive::Serialize;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use ssz::TreeHash;
|
||||
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
|
||||
use test_random_derive::TestRandom;
|
||||
|
||||
/// An exit voluntarily submitted a validator who wishes to withdraw.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Encode, Decode, TreeHash, TestRandom, SignedRoot)]
|
||||
/// Spec v0.5.0
|
||||
#[derive(
|
||||
Debug,
|
||||
PartialEq,
|
||||
Clone,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Encode,
|
||||
Decode,
|
||||
TreeHash,
|
||||
TestRandom,
|
||||
SignedRoot,
|
||||
)]
|
||||
pub struct VoluntaryExit {
|
||||
pub epoch: Epoch,
|
||||
pub validator_index: u64,
|
||||
|
||||
Reference in New Issue
Block a user