merged master

This commit is contained in:
Darren Langley
2019-05-16 22:45:32 +10:00
240 changed files with 7991 additions and 20470 deletions
+2 -1
View File
@@ -14,7 +14,6 @@ env_logger = "0.6.0"
serde = "1.0"
serde_derive = "1.0"
serde_yaml = "0.8"
yaml-utils = { path = "yaml_utils" }
[dependencies]
bls = { path = "../utils/bls" }
@@ -26,5 +25,7 @@ log = "0.4"
merkle_proof = { path = "../utils/merkle_proof" }
ssz = { path = "../utils/ssz" }
ssz_derive = { path = "../utils/ssz_derive" }
tree_hash = { path = "../utils/tree_hash" }
tree_hash_derive = { path = "../utils/tree_hash_derive" }
types = { path = "../types" }
rayon = "1.0"
@@ -1,6 +1,5 @@
use criterion::Criterion;
use criterion::{black_box, Benchmark};
use ssz::TreeHash;
use state_processing::{
per_block_processing,
per_block_processing::{
@@ -9,6 +8,7 @@ use state_processing::{
verify_block_signature,
},
};
use tree_hash::TreeHash;
use types::*;
/// Run the detailed benchmarking suite on the given `BeaconState`.
@@ -263,7 +263,7 @@ pub fn bench_block_processing(
c.bench(
&format!("{}/block_processing", desc),
Benchmark::new("tree_hash_block", move |b| {
b.iter(|| black_box(block.hash_tree_root()))
b.iter(|| black_box(block.tree_hash_root()))
})
.sample_size(10),
);
@@ -1,6 +1,5 @@
use criterion::Criterion;
use criterion::{black_box, Benchmark};
use ssz::TreeHash;
use state_processing::{
per_epoch_processing,
per_epoch_processing::{
@@ -9,6 +8,7 @@ use state_processing::{
update_active_tree_index_roots, update_latest_slashed_balances,
},
};
use tree_hash::TreeHash;
use types::test_utils::TestingBeaconStateBuilder;
use types::*;
@@ -256,7 +256,7 @@ fn bench_epoch_processing(c: &mut Criterion, state: &BeaconState, spec: &ChainSp
c.bench(
&format!("{}/epoch_processing", desc),
Benchmark::new("tree_hash_state", move |b| {
b.iter(|| black_box(state_clone.hash_tree_root()))
b.iter(|| black_box(state_clone.tree_hash_root()))
})
.sample_size(SMALL_BENCHING_SAMPLE_SIZE),
);
@@ -2,9 +2,9 @@ use types::{BeaconStateError as Error, *};
/// Exit the validator of the given `index`.
///
/// Spec v0.5.0
pub fn exit_validator(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn exit_validator<T: EthSpec>(
state: &mut BeaconState<T>,
validator_index: usize,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -3,9 +3,9 @@ use types::{BeaconStateError as Error, *};
/// Slash the validator with index ``index``.
///
/// Spec v0.5.0
pub fn slash_validator(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn slash_validator<T: EthSpec>(
state: &mut BeaconState<T>,
validator_index: usize,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -36,8 +36,7 @@ pub fn slash_validator(
state.set_slashed_balance(
current_epoch,
state.get_slashed_balance(current_epoch, spec)? + effective_balance,
spec,
state.get_slashed_balance(current_epoch)? + effective_balance,
)?;
let whistleblower_index =
@@ -56,7 +55,7 @@ pub fn slash_validator(
state.validator_registry[validator_index].slashed = true;
state.validator_registry[validator_index].withdrawable_epoch =
current_epoch + Epoch::from(spec.latest_slashed_exit_length);
current_epoch + Epoch::from(T::LatestSlashedExitLength::to_usize());
Ok(())
}
@@ -4,7 +4,7 @@ use types::*;
///
/// Is title `verify_bitfield` in spec.
///
/// Spec v0.5.0
/// Spec v0.5.1
pub fn verify_bitfield_length(bitfield: &Bitfield, committee_size: usize) -> bool {
if bitfield.num_bytes() != ((committee_size + 7) / 8) {
return false;
@@ -18,3 +18,62 @@ pub fn verify_bitfield_length(bitfield: &Bitfield, committee_size: usize) -> boo
true
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn bitfield_length() {
assert_eq!(
verify_bitfield_length(&Bitfield::from_bytes(&[0b0000_0001]), 4),
true
);
assert_eq!(
verify_bitfield_length(&Bitfield::from_bytes(&[0b0001_0001]), 4),
false
);
assert_eq!(
verify_bitfield_length(&Bitfield::from_bytes(&[0b0000_0000]), 4),
true
);
assert_eq!(
verify_bitfield_length(&Bitfield::from_bytes(&[0b1000_0000]), 8),
true
);
assert_eq!(
verify_bitfield_length(&Bitfield::from_bytes(&[0b1000_0000, 0b0000_0000]), 16),
true
);
assert_eq!(
verify_bitfield_length(&Bitfield::from_bytes(&[0b1000_0000, 0b0000_0000]), 15),
false
);
assert_eq!(
verify_bitfield_length(&Bitfield::from_bytes(&[0b0000_0000, 0b0000_0000]), 8),
false
);
assert_eq!(
verify_bitfield_length(
&Bitfield::from_bytes(&[0b0000_0000, 0b0000_0000, 0b0000_0000]),
8
),
false
);
assert_eq!(
verify_bitfield_length(
&Bitfield::from_bytes(&[0b0000_0000, 0b0000_0000, 0b0000_0000]),
24
),
true
);
}
}
@@ -1,5 +1,5 @@
use super::per_block_processing::{errors::BlockProcessingError, process_deposits};
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::*;
pub enum GenesisError {
@@ -9,13 +9,13 @@ pub enum GenesisError {
/// Returns the genesis `BeaconState`
///
/// Spec v0.5.0
pub fn get_genesis_state(
/// Spec v0.5.1
pub fn get_genesis_state<T: EthSpec>(
genesis_validator_deposits: &[Deposit],
genesis_time: u64,
genesis_eth1_data: Eth1Data,
spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
) -> Result<BeaconState<T>, BlockProcessingError> {
// Get the genesis `BeaconState`
let mut state = BeaconState::genesis(genesis_time, genesis_eth1_data, spec);
@@ -36,13 +36,13 @@ pub fn get_genesis_state(
let active_validator_indices = state
.get_cached_active_validator_indices(RelativeEpoch::Current, spec)?
.to_vec();
let genesis_active_index_root = Hash256::from_slice(&active_validator_indices.hash_tree_root());
state.fill_active_index_roots_with(genesis_active_index_root, spec);
let genesis_active_index_root = Hash256::from_slice(&active_validator_indices.tree_hash_root());
state.fill_active_index_roots_with(genesis_active_index_root);
// Generate the current shuffling seed.
state.current_shuffling_seed = state.generate_seed(spec.genesis_epoch, spec)?;
Ok(())
Ok(state)
}
impl From<BlockProcessingError> for GenesisError {
@@ -1,7 +1,7 @@
use crate::common::slash_validator;
use errors::{BlockInvalid as Invalid, BlockProcessingError as Error, IntoWithIndex};
use rayon::prelude::*;
use ssz::{SignedRoot, TreeHash};
use tree_hash::{SignedRoot, TreeHash};
use types::*;
pub use self::verify_attester_slashing::{
@@ -41,9 +41,9 @@ const VERIFY_DEPOSIT_MERKLE_PROOFS: bool = false;
/// Returns `Ok(())` if the block is valid and the state was successfully updated. Otherwise
/// returns an error describing why the block was invalid or how the function failed to execute.
///
/// Spec v0.5.0
pub fn per_block_processing(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn per_block_processing<T: EthSpec>(
state: &mut BeaconState<T>,
block: &BeaconBlock,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -56,9 +56,9 @@ pub fn per_block_processing(
/// Returns `Ok(())` if the block is valid and the state was successfully updated. Otherwise
/// returns an error describing why the block was invalid or how the function failed to execute.
///
/// Spec v0.5.0
pub fn per_block_processing_without_verifying_block_signature(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn per_block_processing_without_verifying_block_signature<T: EthSpec>(
state: &mut BeaconState<T>,
block: &BeaconBlock,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -71,9 +71,9 @@ pub fn per_block_processing_without_verifying_block_signature(
/// Returns `Ok(())` if the block is valid and the state was successfully updated. Otherwise
/// returns an error describing why the block was invalid or how the function failed to execute.
///
/// Spec v0.5.0
fn per_block_processing_signature_optional(
mut state: &mut BeaconState,
/// Spec v0.5.1
fn per_block_processing_signature_optional<T: EthSpec>(
mut state: &mut BeaconState<T>,
block: &BeaconBlock,
should_verify_block_signature: bool,
spec: &ChainSpec,
@@ -101,20 +101,22 @@ fn per_block_processing_signature_optional(
/// Processes the block header.
///
/// Spec v0.5.0
pub fn process_block_header(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_block_header<T: EthSpec>(
state: &mut BeaconState<T>,
block: &BeaconBlock,
spec: &ChainSpec,
) -> Result<(), Error> {
verify!(block.slot == state.slot, Invalid::StateSlotMismatch);
// NOTE: this is not to spec. I think spec is broken. See:
//
// https://github.com/ethereum/eth2.0-specs/issues/797
let expected_previous_block_root =
Hash256::from_slice(&state.latest_block_header.signed_root());
verify!(
block.previous_block_root == *state.get_block_root(state.slot - 1, spec)?,
Invalid::ParentBlockRootMismatch
block.previous_block_root == expected_previous_block_root,
Invalid::ParentBlockRootMismatch {
state: expected_previous_block_root,
block: block.previous_block_root,
}
);
state.latest_block_header = block.temporary_block_header(spec);
@@ -124,9 +126,9 @@ pub fn process_block_header(
/// Verifies the signature of a block.
///
/// Spec v0.5.0
pub fn verify_block_signature(
state: &BeaconState,
/// Spec v0.5.1
pub fn verify_block_signature<T: EthSpec>(
state: &BeaconState<T>,
block: &BeaconBlock,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -152,9 +154,9 @@ pub fn verify_block_signature(
/// Verifies the `randao_reveal` against the block's proposer pubkey and updates
/// `state.latest_randao_mixes`.
///
/// Spec v0.5.0
pub fn process_randao(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_randao<T: EthSpec>(
state: &mut BeaconState<T>,
block: &BeaconBlock,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -164,7 +166,7 @@ pub fn process_randao(
// Verify the RANDAO is a valid signature of the proposer.
verify!(
block.body.randao_reveal.verify(
&state.current_epoch(spec).hash_tree_root()[..],
&state.current_epoch(spec).tree_hash_root()[..],
spec.get_domain(
block.slot.epoch(spec.slots_per_epoch),
Domain::Randao,
@@ -183,8 +185,11 @@ pub fn process_randao(
/// Update the `state.eth1_data_votes` based upon the `eth1_data` provided.
///
/// Spec v0.5.0
pub fn process_eth1_data(state: &mut BeaconState, eth1_data: &Eth1Data) -> Result<(), Error> {
/// Spec v0.5.1
pub fn process_eth1_data<T: EthSpec>(
state: &mut BeaconState<T>,
eth1_data: &Eth1Data,
) -> Result<(), Error> {
// Attempt to find a `Eth1DataVote` with matching `Eth1Data`.
let matching_eth1_vote_index = state
.eth1_data_votes
@@ -209,9 +214,9 @@ pub fn process_eth1_data(state: &mut BeaconState, eth1_data: &Eth1Data) -> Resul
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
///
/// Spec v0.5.0
pub fn process_proposer_slashings(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_proposer_slashings<T: EthSpec>(
state: &mut BeaconState<T>,
proposer_slashings: &[ProposerSlashing],
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -242,9 +247,9 @@ pub fn process_proposer_slashings(
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
///
/// Spec v0.5.0
pub fn process_attester_slashings(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_attester_slashings<T: EthSpec>(
state: &mut BeaconState<T>,
attester_slashings: &[AttesterSlashing],
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -300,9 +305,9 @@ pub fn process_attester_slashings(
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
///
/// Spec v0.5.0
pub fn process_attestations(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_attestations<T: EthSpec>(
state: &mut BeaconState<T>,
attestations: &[Attestation],
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -342,9 +347,9 @@ pub fn process_attestations(
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
///
/// Spec v0.5.0
pub fn process_deposits(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_deposits<T: EthSpec>(
state: &mut BeaconState<T>,
deposits: &[Deposit],
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -412,9 +417,9 @@ pub fn process_deposits(
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
///
/// Spec v0.5.0
pub fn process_exits(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_exits<T: EthSpec>(
state: &mut BeaconState<T>,
voluntary_exits: &[VoluntaryExit],
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -444,9 +449,9 @@ pub fn process_exits(
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
///
/// Spec v0.5.0
pub fn process_transfers(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_transfers<T: EthSpec>(
state: &mut BeaconState<T>,
transfers: &[Transfer],
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -67,7 +67,10 @@ impl_from_beacon_state_error!(BlockProcessingError);
#[derive(Debug, PartialEq)]
pub enum BlockInvalid {
StateSlotMismatch,
ParentBlockRootMismatch,
ParentBlockRootMismatch {
state: Hash256,
block: Hash256,
},
BadSignature,
BadRandaoSignature,
MaxAttestationsExceeded,
@@ -271,10 +274,10 @@ pub enum ProposerSlashingValidationError {
pub enum ProposerSlashingInvalid {
/// The proposer index is not a known validator.
ProposerUnknown(u64),
/// The two proposal have different slots.
/// The two proposal have different epochs.
///
/// (proposal_1_slot, proposal_2_slot)
ProposalSlotMismatch(Slot, Slot),
ProposalEpochMismatch(Slot, Slot),
/// The proposals are identical and therefore not slashable.
ProposalsIdentical,
/// The specified proposer has already been slashed.
@@ -1,6 +1,6 @@
use super::errors::{AttestationInvalid as Invalid, AttestationValidationError as Error};
use crate::common::verify_bitfield_length;
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::*;
/// Indicates if an `Attestation` is valid to be included in a block in the current epoch of the
@@ -8,9 +8,9 @@ use types::*;
///
/// Returns `Ok(())` if the `Attestation` is valid, otherwise indicates the reason for invalidity.
///
/// Spec v0.5.0
pub fn validate_attestation(
state: &BeaconState,
/// Spec v0.5.1
pub fn validate_attestation<T: EthSpec>(
state: &BeaconState<T>,
attestation: &Attestation,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -18,8 +18,8 @@ pub fn validate_attestation(
}
/// Like `validate_attestation` but doesn't run checks which may become true in future states.
pub fn validate_attestation_time_independent_only(
state: &BeaconState,
pub fn validate_attestation_time_independent_only<T: EthSpec>(
state: &BeaconState<T>,
attestation: &Attestation,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -31,9 +31,9 @@ pub fn validate_attestation_time_independent_only(
///
/// Returns `Ok(())` if the `Attestation` is valid, otherwise indicates the reason for invalidity.
///
/// Spec v0.5.0
pub fn validate_attestation_without_signature(
state: &BeaconState,
/// Spec v0.5.1
pub fn validate_attestation_without_signature<T: EthSpec>(
state: &BeaconState<T>,
attestation: &Attestation,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -44,9 +44,9 @@ pub fn validate_attestation_without_signature(
/// given state, optionally validating the aggregate signature.
///
///
/// Spec v0.5.0
fn validate_attestation_parametric(
state: &BeaconState,
/// Spec v0.5.1
fn validate_attestation_parametric<T: EthSpec>(
state: &BeaconState<T>,
attestation: &Attestation,
spec: &ChainSpec,
verify_signature: bool,
@@ -167,10 +167,10 @@ fn validate_attestation_parametric(
/// Verify that the `source_epoch` and `source_root` of an `Attestation` correctly
/// match the current (or previous) justified epoch and root from the state.
///
/// Spec v0.5.0
fn verify_justified_epoch_and_root(
/// Spec v0.5.1
fn verify_justified_epoch_and_root<T: EthSpec>(
attestation: &Attestation,
state: &BeaconState,
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), Error> {
let state_epoch = state.slot.epoch(spec.slots_per_epoch);
@@ -222,9 +222,9 @@ fn verify_justified_epoch_and_root(
/// - `custody_bitfield` does not have a bit for each index of `committee`.
/// - A `validator_index` in `committee` is not in `state.validator_registry`.
///
/// Spec v0.5.0
fn verify_attestation_signature(
state: &BeaconState,
/// Spec v0.5.1
fn verify_attestation_signature<T: EthSpec>(
state: &BeaconState<T>,
committee: &[usize],
a: &Attestation,
spec: &ChainSpec,
@@ -270,14 +270,14 @@ fn verify_attestation_signature(
data: a.data.clone(),
custody_bit: false,
}
.hash_tree_root();
.tree_hash_root();
// Message when custody bitfield is `true`
let message_1 = AttestationDataAndCustodyBit {
data: a.data.clone(),
custody_bit: true,
}
.hash_tree_root();
.tree_hash_root();
let mut messages = vec![];
let mut keys = vec![];
@@ -7,9 +7,9 @@ use types::*;
///
/// Returns `Ok(())` if the `AttesterSlashing` is valid, otherwise indicates the reason for invalidity.
///
/// Spec v0.5.0
pub fn verify_attester_slashing(
state: &BeaconState,
/// Spec v0.5.1
pub fn verify_attester_slashing<T: EthSpec>(
state: &BeaconState<T>,
attester_slashing: &AttesterSlashing,
should_verify_slashable_attestations: bool,
spec: &ChainSpec,
@@ -41,9 +41,9 @@ pub fn verify_attester_slashing(
///
/// Returns Ok(indices) if `indices.len() > 0`.
///
/// Spec v0.5.0
pub fn gather_attester_slashing_indices(
state: &BeaconState,
/// Spec v0.5.1
pub fn gather_attester_slashing_indices<T: EthSpec>(
state: &BeaconState<T>,
attester_slashing: &AttesterSlashing,
spec: &ChainSpec,
) -> Result<Vec<u64>, Error> {
@@ -57,8 +57,8 @@ pub fn gather_attester_slashing_indices(
/// Same as `gather_attester_slashing_indices` but allows the caller to specify the criteria
/// for determining whether a given validator should be considered slashed.
pub fn gather_attester_slashing_indices_modular<F>(
state: &BeaconState,
pub fn gather_attester_slashing_indices_modular<F, T: EthSpec>(
state: &BeaconState<T>,
attester_slashing: &AttesterSlashing,
is_slashed: F,
spec: &ChainSpec,
@@ -15,9 +15,9 @@ use types::*;
///
/// Note: this function is incomplete.
///
/// Spec v0.5.0
pub fn verify_deposit(
state: &BeaconState,
/// Spec v0.5.1
pub fn verify_deposit<T: EthSpec>(
state: &BeaconState<T>,
deposit: &Deposit,
verify_merkle_branch: bool,
spec: &ChainSpec,
@@ -46,8 +46,11 @@ pub fn verify_deposit(
/// Verify that the `Deposit` index is correct.
///
/// Spec v0.5.0
pub fn verify_deposit_index(state: &BeaconState, deposit: &Deposit) -> Result<(), Error> {
/// Spec v0.5.1
pub fn verify_deposit_index<T: EthSpec>(
state: &BeaconState<T>,
deposit: &Deposit,
) -> Result<(), Error> {
verify!(
deposit.index == state.deposit_index,
Invalid::BadIndex {
@@ -65,8 +68,8 @@ pub fn verify_deposit_index(state: &BeaconState, deposit: &Deposit) -> Result<()
/// ## Errors
///
/// Errors if the state's `pubkey_cache` is not current.
pub fn get_existing_validator_index(
state: &BeaconState,
pub fn get_existing_validator_index<T: EthSpec>(
state: &BeaconState<T>,
deposit: &Deposit,
) -> Result<Option<u64>, Error> {
let deposit_input = &deposit.deposit_data.deposit_input;
@@ -88,12 +91,16 @@ pub fn get_existing_validator_index(
/// Verify that a deposit is included in the state's eth1 deposit root.
///
/// Spec v0.5.0
fn verify_deposit_merkle_proof(state: &BeaconState, deposit: &Deposit, spec: &ChainSpec) -> bool {
/// Spec v0.5.1
fn verify_deposit_merkle_proof<T: EthSpec>(
state: &BeaconState<T>,
deposit: &Deposit,
spec: &ChainSpec,
) -> bool {
let leaf = hash(&get_serialized_deposit_data(deposit));
verify_merkle_proof(
Hash256::from_slice(&leaf),
&deposit.proof,
&deposit.proof[..],
spec.deposit_contract_tree_depth as usize,
deposit.index as usize,
state.latest_eth1_data.deposit_root,
@@ -102,7 +109,7 @@ fn verify_deposit_merkle_proof(state: &BeaconState, deposit: &Deposit, spec: &Ch
/// Helper struct for easily getting the serialized data generated by the deposit contract.
///
/// Spec v0.5.0
/// Spec v0.5.1
#[derive(Encode)]
struct SerializedDepositData {
amount: u64,
@@ -113,7 +120,7 @@ struct SerializedDepositData {
/// Return the serialized data generated by the deposit contract that is used to generate the
/// merkle proof.
///
/// Spec v0.5.0
/// Spec v0.5.1
fn get_serialized_deposit_data(deposit: &Deposit) -> Vec<u8> {
let serialized_deposit_data = SerializedDepositData {
amount: deposit.deposit_data.amount,
@@ -1,5 +1,5 @@
use super::errors::{ExitInvalid as Invalid, ExitValidationError as Error};
use ssz::SignedRoot;
use tree_hash::SignedRoot;
use types::*;
/// Indicates if an `Exit` is valid to be included in a block in the current epoch of the given
@@ -7,9 +7,9 @@ use types::*;
///
/// Returns `Ok(())` if the `Exit` is valid, otherwise indicates the reason for invalidity.
///
/// Spec v0.5.0
pub fn verify_exit(
state: &BeaconState,
/// Spec v0.5.1
pub fn verify_exit<T: EthSpec>(
state: &BeaconState<T>,
exit: &VoluntaryExit,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -17,8 +17,8 @@ pub fn verify_exit(
}
/// Like `verify_exit` but doesn't run checks which may become true in future states.
pub fn verify_exit_time_independent_only(
state: &BeaconState,
pub fn verify_exit_time_independent_only<T: EthSpec>(
state: &BeaconState<T>,
exit: &VoluntaryExit,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -26,8 +26,8 @@ pub fn verify_exit_time_independent_only(
}
/// Parametric version of `verify_exit` that skips some checks if `time_independent_only` is true.
fn verify_exit_parametric(
state: &BeaconState,
fn verify_exit_parametric<T: EthSpec>(
state: &BeaconState<T>,
exit: &VoluntaryExit,
spec: &ChainSpec,
time_independent_only: bool,
@@ -1,5 +1,5 @@
use super::errors::{ProposerSlashingInvalid as Invalid, ProposerSlashingValidationError as Error};
use ssz::SignedRoot;
use tree_hash::SignedRoot;
use types::*;
/// Indicates if a `ProposerSlashing` is valid to be included in a block in the current epoch of the given
@@ -7,10 +7,10 @@ use types::*;
///
/// Returns `Ok(())` if the `ProposerSlashing` is valid, otherwise indicates the reason for invalidity.
///
/// Spec v0.5.0
pub fn verify_proposer_slashing(
/// Spec v0.5.1
pub fn verify_proposer_slashing<T: EthSpec>(
proposer_slashing: &ProposerSlashing,
state: &BeaconState,
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), Error> {
let proposer = state
@@ -21,8 +21,9 @@ pub fn verify_proposer_slashing(
})?;
verify!(
proposer_slashing.header_1.slot == proposer_slashing.header_2.slot,
Invalid::ProposalSlotMismatch(
proposer_slashing.header_1.slot.epoch(spec.slots_per_epoch)
== proposer_slashing.header_2.slot.epoch(spec.slots_per_epoch),
Invalid::ProposalEpochMismatch(
proposer_slashing.header_1.slot,
proposer_slashing.header_2.slot
)
@@ -66,7 +67,7 @@ pub fn verify_proposer_slashing(
///
/// Returns `true` if the signature is valid.
///
/// Spec v0.5.0
/// Spec v0.5.1
fn verify_header_signature(
header: &BeaconBlockHeader,
pubkey: &PublicKey,
@@ -2,7 +2,7 @@ use super::errors::{
SlashableAttestationInvalid as Invalid, SlashableAttestationValidationError as Error,
};
use crate::common::verify_bitfield_length;
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::*;
/// Indicates if a `SlashableAttestation` is valid to be included in a block in the current epoch of the given
@@ -10,9 +10,9 @@ use types::*;
///
/// Returns `Ok(())` if the `SlashableAttestation` is valid, otherwise indicates the reason for invalidity.
///
/// Spec v0.5.0
pub fn verify_slashable_attestation(
state: &BeaconState,
/// Spec v0.5.1
pub fn verify_slashable_attestation<T: EthSpec>(
state: &BeaconState<T>,
slashable_attestation: &SlashableAttestation,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -77,12 +77,12 @@ pub fn verify_slashable_attestation(
data: slashable_attestation.data.clone(),
custody_bit: false,
}
.hash_tree_root();
.tree_hash_root();
let message_1 = AttestationDataAndCustodyBit {
data: slashable_attestation.data.clone(),
custody_bit: true,
}
.hash_tree_root();
.tree_hash_root();
let mut messages = vec![];
let mut keys = vec![];
@@ -1,6 +1,6 @@
use super::errors::{TransferInvalid as Invalid, TransferValidationError as Error};
use bls::get_withdrawal_credentials;
use ssz::SignedRoot;
use tree_hash::SignedRoot;
use types::*;
/// Indicates if a `Transfer` is valid to be included in a block in the current epoch of the given
@@ -10,9 +10,9 @@ use types::*;
///
/// Note: this function is incomplete.
///
/// Spec v0.5.0
pub fn verify_transfer(
state: &BeaconState,
/// Spec v0.5.1
pub fn verify_transfer<T: EthSpec>(
state: &BeaconState<T>,
transfer: &Transfer,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -20,8 +20,8 @@ pub fn verify_transfer(
}
/// Like `verify_transfer` but doesn't run checks which may become true in future states.
pub fn verify_transfer_time_independent_only(
state: &BeaconState,
pub fn verify_transfer_time_independent_only<T: EthSpec>(
state: &BeaconState<T>,
transfer: &Transfer,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -29,8 +29,8 @@ pub fn verify_transfer_time_independent_only(
}
/// Parametric version of `verify_transfer` that allows some checks to be skipped.
fn verify_transfer_parametric(
state: &BeaconState,
fn verify_transfer_parametric<T: EthSpec>(
state: &BeaconState<T>,
transfer: &Transfer,
spec: &ChainSpec,
time_independent_only: bool,
@@ -122,9 +122,9 @@ fn verify_transfer_parametric(
///
/// Does not check that the transfer is valid, however checks for overflow in all actions.
///
/// Spec v0.5.0
pub fn execute_transfer(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn execute_transfer<T: EthSpec>(
state: &mut BeaconState<T>,
transfer: &Transfer,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -3,8 +3,8 @@ use errors::EpochProcessingError as Error;
use process_ejections::process_ejections;
use process_exit_queue::process_exit_queue;
use process_slashings::process_slashings;
use ssz::TreeHash;
use std::collections::HashMap;
use tree_hash::TreeHash;
use types::*;
use update_registry_and_shuffling_data::update_registry_and_shuffling_data;
use validator_statuses::{TotalBalances, ValidatorStatuses};
@@ -32,8 +32,11 @@ pub type WinningRootHashSet = HashMap<u64, WinningRoot>;
/// Mutates the given `BeaconState`, returning early if an error is encountered. If an error is
/// returned, a state might be "half-processed" and therefore in an invalid state.
///
/// Spec v0.5.0
pub fn per_epoch_processing(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> {
/// Spec v0.5.1
pub fn per_epoch_processing<T: EthSpec>(
state: &mut BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), Error> {
// Ensure the previous and next epoch caches are built.
state.build_epoch_cache(RelativeEpoch::Previous, spec)?;
state.build_epoch_cache(RelativeEpoch::Current, spec)?;
@@ -86,8 +89,8 @@ pub fn per_epoch_processing(state: &mut BeaconState, spec: &ChainSpec) -> Result
/// Maybe resets the eth1 period.
///
/// Spec v0.5.0
pub fn maybe_reset_eth1_period(state: &mut BeaconState, spec: &ChainSpec) {
/// Spec v0.5.1
pub fn maybe_reset_eth1_period<T: EthSpec>(state: &mut BeaconState<T>, spec: &ChainSpec) {
let next_epoch = state.next_epoch(spec);
let voting_period = spec.epochs_per_eth1_voting_period;
@@ -108,9 +111,9 @@ pub fn maybe_reset_eth1_period(state: &mut BeaconState, spec: &ChainSpec) {
/// - `justified_epoch`
/// - `previous_justified_epoch`
///
/// Spec v0.5.0
pub fn update_justification_and_finalization(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn update_justification_and_finalization<T: EthSpec>(
state: &mut BeaconState<T>,
total_balances: &TotalBalances,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -160,13 +163,13 @@ pub fn update_justification_and_finalization(
if new_justified_epoch != state.current_justified_epoch {
state.current_justified_epoch = new_justified_epoch;
state.current_justified_root =
*state.get_block_root(new_justified_epoch.start_slot(spec.slots_per_epoch), spec)?;
*state.get_block_root(new_justified_epoch.start_slot(spec.slots_per_epoch))?;
}
if new_finalized_epoch != state.finalized_epoch {
state.finalized_epoch = new_finalized_epoch;
state.finalized_root =
*state.get_block_root(new_finalized_epoch.start_slot(spec.slots_per_epoch), spec)?;
*state.get_block_root(new_finalized_epoch.start_slot(spec.slots_per_epoch))?;
}
Ok(())
@@ -178,9 +181,9 @@ pub fn update_justification_and_finalization(
///
/// Also returns a `WinningRootHashSet` for later use during epoch processing.
///
/// Spec v0.5.0
pub fn process_crosslinks(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_crosslinks<T: EthSpec>(
state: &mut BeaconState<T>,
spec: &ChainSpec,
) -> Result<WinningRootHashSet, Error> {
let mut winning_root_for_shards: WinningRootHashSet = HashMap::new();
@@ -221,8 +224,11 @@ pub fn process_crosslinks(
/// Finish up an epoch update.
///
/// Spec v0.5.0
pub fn finish_epoch_update(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> {
/// Spec v0.5.1
pub fn finish_epoch_update<T: EthSpec>(
state: &mut BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), Error> {
let current_epoch = state.current_epoch(spec);
let next_epoch = state.next_epoch(spec);
@@ -236,16 +242,12 @@ pub fn finish_epoch_update(state: &mut BeaconState, spec: &ChainSpec) -> Result<
let active_index_root = Hash256::from_slice(
&state
.get_active_validator_indices(next_epoch + spec.activation_exit_delay)
.hash_tree_root()[..],
.tree_hash_root()[..],
);
state.set_active_index_root(next_epoch, active_index_root, spec)?;
// Set total slashed balances
state.set_slashed_balance(
next_epoch,
state.get_slashed_balance(current_epoch, spec)?,
spec,
)?;
state.set_slashed_balance(next_epoch, state.get_slashed_balance(current_epoch)?)?;
// Set randao mix
state.set_randao_mix(
@@ -257,11 +259,11 @@ pub fn finish_epoch_update(state: &mut BeaconState, spec: &ChainSpec) -> Result<
state.slot -= 1;
}
if next_epoch.as_u64() % (spec.slots_per_historical_root as u64 / spec.slots_per_epoch) == 0 {
let historical_batch: HistoricalBatch = state.historical_batch();
if next_epoch.as_u64() % (T::SlotsPerHistoricalRoot::to_u64() / spec.slots_per_epoch) == 0 {
let historical_batch = state.historical_batch();
state
.historical_roots
.push(Hash256::from_slice(&historical_batch.hash_tree_root()[..]));
.push(Hash256::from_slice(&historical_batch.tree_hash_root()[..]));
}
state.previous_epoch_attestations = state.current_epoch_attestations.clone();
@@ -32,9 +32,9 @@ impl std::ops::AddAssign for Delta {
/// Apply attester and proposer rewards.
///
/// Spec v0.5.0
pub fn apply_rewards(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn apply_rewards<T: EthSpec>(
state: &mut BeaconState<T>,
validator_statuses: &mut ValidatorStatuses,
winning_root_for_shards: &WinningRootHashSet,
spec: &ChainSpec,
@@ -79,10 +79,10 @@ pub fn apply_rewards(
/// Applies the attestation inclusion reward to each proposer for every validator who included an
/// attestation in the previous epoch.
///
/// Spec v0.5.0
fn get_proposer_deltas(
/// Spec v0.5.1
fn get_proposer_deltas<T: EthSpec>(
deltas: &mut Vec<Delta>,
state: &mut BeaconState,
state: &mut BeaconState<T>,
validator_statuses: &mut ValidatorStatuses,
winning_root_for_shards: &WinningRootHashSet,
spec: &ChainSpec,
@@ -120,10 +120,10 @@ fn get_proposer_deltas(
/// Apply rewards for participation in attestations during the previous epoch.
///
/// Spec v0.5.0
fn get_justification_and_finalization_deltas(
/// Spec v0.5.1
fn get_justification_and_finalization_deltas<T: EthSpec>(
deltas: &mut Vec<Delta>,
state: &BeaconState,
state: &BeaconState<T>,
validator_statuses: &ValidatorStatuses,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -163,7 +163,7 @@ fn get_justification_and_finalization_deltas(
/// Determine the delta for a single validator, if the chain is finalizing normally.
///
/// Spec v0.5.0
/// Spec v0.5.1
fn compute_normal_justification_and_finalization_delta(
validator: &ValidatorStatus,
total_balances: &TotalBalances,
@@ -215,7 +215,7 @@ fn compute_normal_justification_and_finalization_delta(
/// Determine the delta for a single delta, assuming the chain is _not_ finalizing normally.
///
/// Spec v0.5.0
/// Spec v0.5.1
fn compute_inactivity_leak_delta(
validator: &ValidatorStatus,
base_reward: u64,
@@ -261,10 +261,10 @@ fn compute_inactivity_leak_delta(
/// Calculate the deltas based upon the winning roots for attestations during the previous epoch.
///
/// Spec v0.5.0
fn get_crosslink_deltas(
/// Spec v0.5.1
fn get_crosslink_deltas<T: EthSpec>(
deltas: &mut Vec<Delta>,
state: &BeaconState,
state: &BeaconState<T>,
validator_statuses: &ValidatorStatuses,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -295,9 +295,9 @@ fn get_crosslink_deltas(
/// Returns the base reward for some validator.
///
/// Spec v0.5.0
fn get_base_reward(
state: &BeaconState,
/// Spec v0.5.1
fn get_base_reward<T: EthSpec>(
state: &BeaconState<T>,
index: usize,
previous_total_balance: u64,
spec: &ChainSpec,
@@ -312,9 +312,9 @@ fn get_base_reward(
/// Returns the inactivity penalty for some validator.
///
/// Spec v0.5.0
fn get_inactivity_penalty(
state: &BeaconState,
/// Spec v0.5.1
fn get_inactivity_penalty<T: EthSpec>(
state: &BeaconState<T>,
index: usize,
epochs_since_finality: u64,
previous_total_balance: u64,
@@ -328,7 +328,7 @@ fn get_inactivity_penalty(
/// Returns the epochs since the last finalized epoch.
///
/// Spec v0.5.0
fn epochs_since_finality(state: &BeaconState, spec: &ChainSpec) -> Epoch {
/// Spec v0.5.1
fn epochs_since_finality<T: EthSpec>(state: &BeaconState<T>, spec: &ChainSpec) -> Epoch {
state.current_epoch(spec) + 1 - state.finalized_epoch
}
@@ -3,9 +3,9 @@ use types::*;
/// Returns validator indices which participated in the attestation.
///
/// Spec v0.5.0
pub fn get_attestation_participants(
state: &BeaconState,
/// Spec v0.5.1
pub fn get_attestation_participants<T: EthSpec>(
state: &BeaconState<T>,
attestation_data: &AttestationData,
bitfield: &Bitfield,
spec: &ChainSpec,
@@ -5,9 +5,9 @@ use types::*;
/// Returns the distance between the first included attestation for some validator and this
/// slot.
///
/// Spec v0.5.0
pub fn inclusion_distance(
state: &BeaconState,
/// Spec v0.5.1
pub fn inclusion_distance<T: EthSpec>(
state: &BeaconState<T>,
attestations: &[&PendingAttestation],
validator_index: usize,
spec: &ChainSpec,
@@ -18,9 +18,9 @@ pub fn inclusion_distance(
/// Returns the slot of the earliest included attestation for some validator.
///
/// Spec v0.5.0
pub fn inclusion_slot(
state: &BeaconState,
/// Spec v0.5.1
pub fn inclusion_slot<T: EthSpec>(
state: &BeaconState<T>,
attestations: &[&PendingAttestation],
validator_index: usize,
spec: &ChainSpec,
@@ -31,9 +31,9 @@ pub fn inclusion_slot(
/// Finds the earliest included attestation for some validator.
///
/// Spec v0.5.0
fn earliest_included_attestation(
state: &BeaconState,
/// Spec v0.5.1
fn earliest_included_attestation<T: EthSpec>(
state: &BeaconState<T>,
attestations: &[&PendingAttestation],
validator_index: usize,
spec: &ChainSpec,
@@ -4,8 +4,11 @@ use types::{BeaconStateError as Error, *};
/// Iterate through the validator registry and eject active validators with balance below
/// ``EJECTION_BALANCE``.
///
/// Spec v0.5.0
pub fn process_ejections(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> {
/// Spec v0.5.1
pub fn process_ejections<T: EthSpec>(
state: &mut BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), Error> {
// There is an awkward double (triple?) loop here because we can't loop across the borrowed
// active validator indices and mutate state in the one loop.
let exitable: Vec<usize> = state
@@ -2,8 +2,8 @@ use types::*;
/// Process the exit queue.
///
/// Spec v0.5.0
pub fn process_exit_queue(state: &mut BeaconState, spec: &ChainSpec) {
/// Spec v0.5.1
pub fn process_exit_queue<T: EthSpec>(state: &mut BeaconState<T>, spec: &ChainSpec) {
let current_epoch = state.current_epoch(spec);
let eligible = |index: usize| {
@@ -31,9 +31,9 @@ pub fn process_exit_queue(state: &mut BeaconState, spec: &ChainSpec) {
/// Initiate an exit for the validator of the given `index`.
///
/// Spec v0.5.0
fn prepare_validator_for_withdrawal(
state: &mut BeaconState,
/// Spec v0.5.1
fn prepare_validator_for_withdrawal<T: EthSpec>(
state: &mut BeaconState<T>,
validator_index: usize,
spec: &ChainSpec,
) {
@@ -2,21 +2,21 @@ use types::{BeaconStateError as Error, *};
/// Process slashings.
///
/// Spec v0.5.0
pub fn process_slashings(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn process_slashings<T: EthSpec>(
state: &mut BeaconState<T>,
current_total_balance: u64,
spec: &ChainSpec,
) -> Result<(), Error> {
let current_epoch = state.current_epoch(spec);
let total_at_start = state.get_slashed_balance(current_epoch + 1, spec)?;
let total_at_end = state.get_slashed_balance(current_epoch, spec)?;
let total_at_start = state.get_slashed_balance(current_epoch + 1)?;
let total_at_end = state.get_slashed_balance(current_epoch)?;
let total_penalities = total_at_end - total_at_start;
for (index, validator) in state.validator_registry.iter().enumerate() {
let should_penalize = current_epoch.as_usize()
== validator.withdrawable_epoch.as_usize() - spec.latest_slashed_exit_length / 2;
== validator.withdrawable_epoch.as_usize() - T::LatestSlashedExitLength::to_usize() / 2;
if validator.slashed && should_penalize {
let effective_balance = state.get_effective_balance(index, spec)?;
@@ -8,9 +8,10 @@ use types::*;
fn runs_without_error() {
Builder::from_env(Env::default().default_filter_or("error")).init();
let spec = ChainSpec::few_validators();
let spec = FewValidatorsEthSpec::spec();
let mut builder = TestingBeaconStateBuilder::from_deterministic_keypairs(8, &spec);
let mut builder: TestingBeaconStateBuilder<FewValidatorsEthSpec> =
TestingBeaconStateBuilder::from_deterministic_keypairs(8, &spec);
let target_slot = (spec.genesis_epoch + 4).end_slot(spec.slots_per_epoch);
builder.teleport_to_slot(target_slot, &spec);
@@ -4,9 +4,9 @@ use types::*;
/// Peforms a validator registry update, if required.
///
/// Spec v0.5.0
pub fn update_registry_and_shuffling_data(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn update_registry_and_shuffling_data<T: EthSpec>(
state: &mut BeaconState<T>,
current_total_balance: u64,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -49,9 +49,9 @@ pub fn update_registry_and_shuffling_data(
/// Returns `true` if the validator registry should be updated during an epoch processing.
///
/// Spec v0.5.0
pub fn should_update_validator_registry(
state: &BeaconState,
/// Spec v0.5.1
pub fn should_update_validator_registry<T: EthSpec>(
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<bool, BeaconStateError> {
if state.finalized_epoch <= state.validator_registry_update_epoch {
@@ -78,9 +78,9 @@ pub fn should_update_validator_registry(
///
/// Note: Utilizes the cache and will fail if the appropriate cache is not initialized.
///
/// Spec v0.5.0
pub fn update_validator_registry(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn update_validator_registry<T: EthSpec>(
state: &mut BeaconState<T>,
current_total_balance: u64,
spec: &ChainSpec,
) -> Result<(), Error> {
@@ -133,9 +133,9 @@ pub fn update_validator_registry(
/// Activate the validator of the given ``index``.
///
/// Spec v0.5.0
pub fn activate_validator(
state: &mut BeaconState,
/// Spec v0.5.1
pub fn activate_validator<T: EthSpec>(
state: &mut BeaconState<T>,
validator_index: usize,
is_genesis: bool,
spec: &ChainSpec,
@@ -160,8 +160,11 @@ impl ValidatorStatuses {
/// - Active validators
/// - Total balances for the current and previous epochs.
///
/// Spec v0.5.0
pub fn new(state: &BeaconState, spec: &ChainSpec) -> Result<Self, BeaconStateError> {
/// Spec v0.5.1
pub fn new<T: EthSpec>(
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<Self, BeaconStateError> {
let mut statuses = Vec::with_capacity(state.validator_registry.len());
let mut total_balances = TotalBalances::default();
@@ -195,10 +198,10 @@ impl ValidatorStatuses {
/// Process some attestations from the given `state` updating the `statuses` and
/// `total_balances` fields.
///
/// Spec v0.5.0
pub fn process_attestations(
/// Spec v0.5.1
pub fn process_attestations<T: EthSpec>(
&mut self,
state: &BeaconState,
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), BeaconStateError> {
for a in state
@@ -243,7 +246,7 @@ impl ValidatorStatuses {
status.is_previous_epoch_boundary_attester = true;
}
if has_common_beacon_block_root(a, state, spec)? {
if has_common_beacon_block_root(a, state)? {
self.total_balances.previous_epoch_head_attesters += attesting_balance;
status.is_previous_epoch_head_attester = true;
}
@@ -261,10 +264,10 @@ impl ValidatorStatuses {
/// Update the `statuses` for each validator based upon whether or not they attested to the
/// "winning" shard block root for the previous epoch.
///
/// Spec v0.5.0
pub fn process_winning_roots(
/// Spec v0.5.1
pub fn process_winning_roots<T: EthSpec>(
&mut self,
state: &BeaconState,
state: &BeaconState<T>,
winning_roots: &WinningRootHashSet,
spec: &ChainSpec,
) -> Result<(), BeaconStateError> {
@@ -297,14 +300,14 @@ impl ValidatorStatuses {
/// Returns the distance between when the attestation was created and when it was included in a
/// block.
///
/// Spec v0.5.0
/// Spec v0.5.1
fn inclusion_distance(a: &PendingAttestation) -> Slot {
a.inclusion_slot - a.data.slot
}
/// Returns `true` if some `PendingAttestation` is from the supplied `epoch`.
///
/// Spec v0.5.0
/// Spec v0.5.1
fn is_from_epoch(a: &PendingAttestation, epoch: Epoch, spec: &ChainSpec) -> bool {
a.data.slot.epoch(spec.slots_per_epoch) == epoch
}
@@ -312,15 +315,15 @@ fn is_from_epoch(a: &PendingAttestation, epoch: Epoch, spec: &ChainSpec) -> bool
/// Returns `true` if a `PendingAttestation` and `BeaconState` share the same beacon block hash for
/// the first slot of the given epoch.
///
/// Spec v0.5.0
fn has_common_epoch_boundary_root(
/// Spec v0.5.1
fn has_common_epoch_boundary_root<T: EthSpec>(
a: &PendingAttestation,
state: &BeaconState,
state: &BeaconState<T>,
epoch: Epoch,
spec: &ChainSpec,
) -> Result<bool, BeaconStateError> {
let slot = epoch.start_slot(spec.slots_per_epoch);
let state_boundary_root = *state.get_block_root(slot, spec)?;
let state_boundary_root = *state.get_block_root(slot)?;
Ok(a.data.target_root == state_boundary_root)
}
@@ -328,13 +331,12 @@ fn has_common_epoch_boundary_root(
/// Returns `true` if a `PendingAttestation` and `BeaconState` share the same beacon block hash for
/// the current slot of the `PendingAttestation`.
///
/// Spec v0.5.0
fn has_common_beacon_block_root(
/// Spec v0.5.1
fn has_common_beacon_block_root<T: EthSpec>(
a: &PendingAttestation,
state: &BeaconState,
spec: &ChainSpec,
state: &BeaconState<T>,
) -> Result<bool, BeaconStateError> {
let state_block_root = *state.get_block_root(a.data.slot, spec)?;
let state_block_root = *state.get_block_root(a.data.slot)?;
Ok(a.data.beacon_block_root == state_block_root)
}
@@ -16,7 +16,7 @@ impl WinningRoot {
/// A winning root is "better" than another if it has a higher `total_attesting_balance`. Ties
/// are broken by favouring the higher `crosslink_data_root` value.
///
/// Spec v0.5.0
/// Spec v0.5.1
pub fn is_better_than(&self, other: &Self) -> bool {
if self.total_attesting_balance > other.total_attesting_balance {
true
@@ -34,9 +34,9 @@ impl WinningRoot {
/// The `WinningRoot` object also contains additional fields that are useful in later stages of
/// per-epoch processing.
///
/// Spec v0.5.0
pub fn winning_root(
state: &BeaconState,
/// Spec v0.5.1
pub fn winning_root<T: EthSpec>(
state: &BeaconState<T>,
shard: u64,
spec: &ChainSpec,
) -> Result<Option<WinningRoot>, BeaconStateError> {
@@ -89,8 +89,12 @@ pub fn winning_root(
/// Returns `true` if pending attestation `a` is eligible to become a winning root.
///
/// Spec v0.5.0
fn is_eligible_for_winning_root(state: &BeaconState, a: &PendingAttestation, shard: Shard) -> bool {
/// Spec v0.5.1
fn is_eligible_for_winning_root<T: EthSpec>(
state: &BeaconState<T>,
a: &PendingAttestation,
shard: Shard,
) -> bool {
if shard >= state.latest_crosslinks.len() as u64 {
return false;
}
@@ -100,9 +104,9 @@ fn is_eligible_for_winning_root(state: &BeaconState, a: &PendingAttestation, sha
/// Returns all indices which voted for a given crosslink. Does not contain duplicates.
///
/// Spec v0.5.0
fn get_attesting_validator_indices(
state: &BeaconState,
/// Spec v0.5.1
fn get_attesting_validator_indices<T: EthSpec>(
state: &BeaconState<T>,
shard: u64,
crosslink_data_root: &Hash256,
spec: &ChainSpec,
@@ -1,5 +1,5 @@
use crate::*;
use ssz::TreeHash;
use tree_hash::SignedRoot;
use types::*;
#[derive(Debug, PartialEq)]
@@ -10,13 +10,12 @@ pub enum Error {
/// Advances a state forward by one slot, performing per-epoch processing if required.
///
/// Spec v0.5.0
pub fn per_slot_processing(
state: &mut BeaconState,
latest_block_header: &BeaconBlockHeader,
/// Spec v0.5.1
pub fn per_slot_processing<T: EthSpec>(
state: &mut BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), Error> {
cache_state(state, latest_block_header, spec)?;
cache_state(state, spec)?;
if (state.slot + 1) % spec.slots_per_epoch == 0 {
per_epoch_processing(state, spec)?;
@@ -27,12 +26,8 @@ pub fn per_slot_processing(
Ok(())
}
fn cache_state(
state: &mut BeaconState,
latest_block_header: &BeaconBlockHeader,
spec: &ChainSpec,
) -> Result<(), Error> {
let previous_slot_state_root = Hash256::from_slice(&state.hash_tree_root()[..]);
fn cache_state<T: EthSpec>(state: &mut BeaconState<T>, spec: &ChainSpec) -> Result<(), Error> {
let previous_slot_state_root = state.update_tree_hash_cache()?;
// Note: increment the state slot here to allow use of our `state_root` and `block_root`
// getter/setter functions.
@@ -46,8 +41,11 @@ fn cache_state(
state.latest_block_header.state_root = previous_slot_state_root
}
let latest_block_root = Hash256::from_slice(&latest_block_header.hash_tree_root()[..]);
state.set_block_root(previous_slot, latest_block_root, spec)?;
// Store the previous slot's post state transition root.
state.set_state_root(previous_slot, previous_slot_state_root)?;
let latest_block_root = Hash256::from_slice(&state.latest_block_header.signed_root()[..]);
state.set_block_root(previous_slot, latest_block_root)?;
// Set the state slot back to what it should be.
state.slot -= 1;
-108
View File
@@ -1,108 +0,0 @@
#![cfg(not(debug_assertions))]
use serde_derive::Deserialize;
use serde_yaml;
use state_processing::{
per_block_processing, per_block_processing_without_verifying_block_signature,
per_slot_processing,
};
use std::{fs::File, io::prelude::*, path::PathBuf};
use types::*;
#[allow(unused_imports)]
use yaml_utils;
#[derive(Debug, Deserialize)]
pub struct TestCase {
pub name: String,
pub config: ChainSpec,
pub verify_signatures: bool,
pub initial_state: BeaconState,
pub blocks: Vec<BeaconBlock>,
}
#[derive(Debug, Deserialize)]
pub struct TestDoc {
pub title: String,
pub summary: String,
pub fork: String,
pub test_cases: Vec<TestCase>,
}
#[test]
fn test_read_yaml() {
// Test sanity-check_small-config_32-vals.yaml
let mut file = {
let mut file_path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
file_path_buf.push("yaml_utils/specs/sanity-check_small-config_32-vals.yaml");
File::open(file_path_buf).unwrap()
};
let mut yaml_str = String::new();
file.read_to_string(&mut yaml_str).unwrap();
yaml_str = yaml_str.to_lowercase();
let _doc: TestDoc = serde_yaml::from_str(&yaml_str.as_str()).unwrap();
// Test sanity-check_default-config_100-vals.yaml
file = {
let mut file_path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
file_path_buf.push("yaml_utils/specs/sanity-check_default-config_100-vals.yaml");
File::open(file_path_buf).unwrap()
};
yaml_str = String::new();
file.read_to_string(&mut yaml_str).unwrap();
yaml_str = yaml_str.to_lowercase();
let _doc: TestDoc = serde_yaml::from_str(&yaml_str.as_str()).unwrap();
}
#[test]
fn run_state_transition_tests_small() {
// Test sanity-check_small-config_32-vals.yaml
let mut file = {
let mut file_path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
file_path_buf.push("yaml_utils/specs/sanity-check_small-config_32-vals.yaml");
File::open(file_path_buf).unwrap()
};
let mut yaml_str = String::new();
file.read_to_string(&mut yaml_str).unwrap();
yaml_str = yaml_str.to_lowercase();
let doc: TestDoc = serde_yaml::from_str(&yaml_str.as_str()).unwrap();
// Run Tests
for (i, test_case) in doc.test_cases.iter().enumerate() {
let mut state = test_case.initial_state.clone();
for block in test_case.blocks.iter() {
while block.slot > state.slot {
let latest_block_header = state.latest_block_header.clone();
per_slot_processing(&mut state, &latest_block_header, &test_case.config).unwrap();
}
if test_case.verify_signatures {
let res = per_block_processing(&mut state, &block, &test_case.config);
if res.is_err() {
println!("{:?}", i);
println!("{:?}", res);
};
} else {
let res = per_block_processing_without_verifying_block_signature(
&mut state,
&block,
&test_case.config,
);
if res.is_err() {
println!("{:?}", i);
println!("{:?}", res);
}
}
}
}
}
@@ -1,15 +0,0 @@
[package]
name = "yaml-utils"
version = "0.1.0"
authors = ["Kirk Baird <baird.k@outlook.com>"]
edition = "2018"
[build-dependencies]
reqwest = "0.9"
tempdir = "0.3"
[dependencies]
[lib]
name = "yaml_utils"
path = "src/lib.rs"
-28
View File
@@ -1,28 +0,0 @@
extern crate reqwest;
extern crate tempdir;
use std::fs::File;
use std::io::copy;
fn main() {
// These test files are not to be stored in the lighthouse repo as they are quite large (32MB).
// They will be downloaded at build time by yaml-utils crate (in build.rs)
let git_path = "https://raw.githubusercontent.com/ethereum/eth2.0-tests/master/state/";
let test_names = vec![
"sanity-check_default-config_100-vals.yaml",
"sanity-check_small-config_32-vals.yaml",
];
for test in test_names {
let mut target = String::from(git_path);
target.push_str(test);
let mut response = reqwest::get(target.as_str()).unwrap();
let mut dest = {
let mut file_name = String::from("specs/");
file_name.push_str(test);
File::create(file_name).unwrap()
};
copy(&mut response, &mut dest).unwrap();
}
}
@@ -1 +0,0 @@
*.yaml
@@ -1 +0,0 @@
// This is a place holder such that yaml-utils is now a crate hence build.rs will be run when 'cargo test' is called