diff --git a/eth2/state_processing/src/common/exit_validator.rs b/eth2/state_processing/src/common/exit_validator.rs index a6cfb395e..e71a31b65 100644 --- a/eth2/state_processing/src/common/exit_validator.rs +++ b/eth2/state_processing/src/common/exit_validator.rs @@ -3,8 +3,8 @@ use types::{BeaconStateError as Error, *}; /// Exit the validator of the given `index`. /// /// Spec v0.5.1 -pub fn exit_validator( - state: &mut BeaconState, +pub fn exit_validator( + state: &mut BeaconState, validator_index: usize, spec: &ChainSpec, ) -> Result<(), Error> { diff --git a/eth2/state_processing/src/common/slash_validator.rs b/eth2/state_processing/src/common/slash_validator.rs index c1aad7da1..bb77e914c 100644 --- a/eth2/state_processing/src/common/slash_validator.rs +++ b/eth2/state_processing/src/common/slash_validator.rs @@ -4,8 +4,8 @@ use types::{BeaconStateError as Error, *}; /// Slash the validator with index ``index``. /// /// Spec v0.5.1 -pub fn slash_validator( - state: &mut BeaconState, +pub fn slash_validator( + state: &mut BeaconState, 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(()) } diff --git a/eth2/state_processing/src/get_genesis_state.rs b/eth2/state_processing/src/get_genesis_state.rs index 4e9fb6caf..0960187df 100644 --- a/eth2/state_processing/src/get_genesis_state.rs +++ b/eth2/state_processing/src/get_genesis_state.rs @@ -10,12 +10,12 @@ pub enum GenesisError { /// Returns the genesis `BeaconState` /// /// Spec v0.5.1 -pub fn get_genesis_state( +pub fn get_genesis_state( genesis_validator_deposits: &[Deposit], genesis_time: u64, genesis_eth1_data: Eth1Data, spec: &ChainSpec, -) -> Result { +) -> Result, BlockProcessingError> { // Get the genesis `BeaconState` let mut state = BeaconState::genesis(genesis_time, genesis_eth1_data, spec); @@ -37,7 +37,7 @@ pub fn get_genesis_state( .get_cached_active_validator_indices(RelativeEpoch::Current, spec)? .to_vec(); let genesis_active_index_root = Hash256::from_slice(&active_validator_indices.tree_hash_root()); - state.fill_active_index_roots_with(genesis_active_index_root, spec); + 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)?; diff --git a/eth2/state_processing/src/per_block_processing.rs b/eth2/state_processing/src/per_block_processing.rs index 58b948f62..e8cf7d957 100644 --- a/eth2/state_processing/src/per_block_processing.rs +++ b/eth2/state_processing/src/per_block_processing.rs @@ -40,8 +40,8 @@ const VERIFY_DEPOSIT_MERKLE_PROOFS: bool = false; /// returns an error describing why the block was invalid or how the function failed to execute. /// /// Spec v0.5.1 -pub fn per_block_processing( - state: &mut BeaconState, +pub fn per_block_processing( + state: &mut BeaconState, block: &BeaconBlock, spec: &ChainSpec, ) -> Result<(), Error> { @@ -55,8 +55,8 @@ pub fn per_block_processing( /// returns an error describing why the block was invalid or how the function failed to execute. /// /// Spec v0.5.1 -pub fn per_block_processing_without_verifying_block_signature( - state: &mut BeaconState, +pub fn per_block_processing_without_verifying_block_signature( + state: &mut BeaconState, block: &BeaconBlock, spec: &ChainSpec, ) -> Result<(), Error> { @@ -70,8 +70,8 @@ pub fn per_block_processing_without_verifying_block_signature( /// returns an error describing why the block was invalid or how the function failed to execute. /// /// Spec v0.5.1 -fn per_block_processing_signature_optional( - mut state: &mut BeaconState, +fn per_block_processing_signature_optional( + mut state: &mut BeaconState, block: &BeaconBlock, should_verify_block_signature: bool, spec: &ChainSpec, @@ -100,8 +100,8 @@ fn per_block_processing_signature_optional( /// Processes the block header. /// /// Spec v0.5.1 -pub fn process_block_header( - state: &mut BeaconState, +pub fn process_block_header( + state: &mut BeaconState, block: &BeaconBlock, spec: &ChainSpec, ) -> Result<(), Error> { @@ -125,8 +125,8 @@ pub fn process_block_header( /// Verifies the signature of a block. /// /// Spec v0.5.1 -pub fn verify_block_signature( - state: &BeaconState, +pub fn verify_block_signature( + state: &BeaconState, block: &BeaconBlock, spec: &ChainSpec, ) -> Result<(), Error> { @@ -153,8 +153,8 @@ pub fn verify_block_signature( /// `state.latest_randao_mixes`. /// /// Spec v0.5.1 -pub fn process_randao( - state: &mut BeaconState, +pub fn process_randao( + state: &mut BeaconState, block: &BeaconBlock, spec: &ChainSpec, ) -> Result<(), Error> { @@ -184,7 +184,10 @@ pub fn process_randao( /// Update the `state.eth1_data_votes` based upon the `eth1_data` provided. /// /// Spec v0.5.1 -pub fn process_eth1_data(state: &mut BeaconState, eth1_data: &Eth1Data) -> Result<(), Error> { +pub fn process_eth1_data( + state: &mut BeaconState, + eth1_data: &Eth1Data, +) -> Result<(), Error> { // Attempt to find a `Eth1DataVote` with matching `Eth1Data`. let matching_eth1_vote_index = state .eth1_data_votes @@ -210,8 +213,8 @@ pub fn process_eth1_data(state: &mut BeaconState, eth1_data: &Eth1Data) -> Resul /// an `Err` describing the invalid object or cause of failure. /// /// Spec v0.5.1 -pub fn process_proposer_slashings( - state: &mut BeaconState, +pub fn process_proposer_slashings( + state: &mut BeaconState, proposer_slashings: &[ProposerSlashing], spec: &ChainSpec, ) -> Result<(), Error> { @@ -243,8 +246,8 @@ pub fn process_proposer_slashings( /// an `Err` describing the invalid object or cause of failure. /// /// Spec v0.5.1 -pub fn process_attester_slashings( - state: &mut BeaconState, +pub fn process_attester_slashings( + state: &mut BeaconState, attester_slashings: &[AttesterSlashing], spec: &ChainSpec, ) -> Result<(), Error> { @@ -301,8 +304,8 @@ pub fn process_attester_slashings( /// an `Err` describing the invalid object or cause of failure. /// /// Spec v0.5.1 -pub fn process_attestations( - state: &mut BeaconState, +pub fn process_attestations( + state: &mut BeaconState, attestations: &[Attestation], spec: &ChainSpec, ) -> Result<(), Error> { @@ -343,8 +346,8 @@ pub fn process_attestations( /// an `Err` describing the invalid object or cause of failure. /// /// Spec v0.5.1 -pub fn process_deposits( - state: &mut BeaconState, +pub fn process_deposits( + state: &mut BeaconState, deposits: &[Deposit], spec: &ChainSpec, ) -> Result<(), Error> { @@ -413,8 +416,8 @@ pub fn process_deposits( /// an `Err` describing the invalid object or cause of failure. /// /// Spec v0.5.1 -pub fn process_exits( - state: &mut BeaconState, +pub fn process_exits( + state: &mut BeaconState, voluntary_exits: &[VoluntaryExit], spec: &ChainSpec, ) -> Result<(), Error> { @@ -445,8 +448,8 @@ pub fn process_exits( /// an `Err` describing the invalid object or cause of failure. /// /// Spec v0.5.1 -pub fn process_transfers( - state: &mut BeaconState, +pub fn process_transfers( + state: &mut BeaconState, transfers: &[Transfer], spec: &ChainSpec, ) -> Result<(), Error> { diff --git a/eth2/state_processing/src/per_block_processing/validate_attestation.rs b/eth2/state_processing/src/per_block_processing/validate_attestation.rs index 438a75c94..f0ec1b861 100644 --- a/eth2/state_processing/src/per_block_processing/validate_attestation.rs +++ b/eth2/state_processing/src/per_block_processing/validate_attestation.rs @@ -9,8 +9,8 @@ use types::*; /// Returns `Ok(())` if the `Attestation` is valid, otherwise indicates the reason for invalidity. /// /// Spec v0.5.1 -pub fn validate_attestation( - state: &BeaconState, +pub fn validate_attestation( + state: &BeaconState, 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( + state: &BeaconState, attestation: &Attestation, spec: &ChainSpec, ) -> Result<(), Error> { @@ -32,8 +32,8 @@ pub fn validate_attestation_time_independent_only( /// Returns `Ok(())` if the `Attestation` is valid, otherwise indicates the reason for invalidity. /// /// Spec v0.5.1 -pub fn validate_attestation_without_signature( - state: &BeaconState, +pub fn validate_attestation_without_signature( + state: &BeaconState, attestation: &Attestation, spec: &ChainSpec, ) -> Result<(), Error> { @@ -45,8 +45,8 @@ pub fn validate_attestation_without_signature( /// /// /// Spec v0.5.1 -fn validate_attestation_parametric( - state: &BeaconState, +fn validate_attestation_parametric( + state: &BeaconState, attestation: &Attestation, spec: &ChainSpec, verify_signature: bool, @@ -168,9 +168,9 @@ fn validate_attestation_parametric( /// match the current (or previous) justified epoch and root from the state. /// /// Spec v0.5.1 -fn verify_justified_epoch_and_root( +fn verify_justified_epoch_and_root( attestation: &Attestation, - state: &BeaconState, + state: &BeaconState, spec: &ChainSpec, ) -> Result<(), Error> { let state_epoch = state.slot.epoch(spec.slots_per_epoch); @@ -223,8 +223,8 @@ fn verify_justified_epoch_and_root( /// - A `validator_index` in `committee` is not in `state.validator_registry`. /// /// Spec v0.5.1 -fn verify_attestation_signature( - state: &BeaconState, +fn verify_attestation_signature( + state: &BeaconState, committee: &[usize], a: &Attestation, spec: &ChainSpec, diff --git a/eth2/state_processing/src/per_block_processing/verify_attester_slashing.rs b/eth2/state_processing/src/per_block_processing/verify_attester_slashing.rs index 3527b62e3..804ebd517 100644 --- a/eth2/state_processing/src/per_block_processing/verify_attester_slashing.rs +++ b/eth2/state_processing/src/per_block_processing/verify_attester_slashing.rs @@ -8,8 +8,8 @@ use types::*; /// Returns `Ok(())` if the `AttesterSlashing` is valid, otherwise indicates the reason for invalidity. /// /// Spec v0.5.1 -pub fn verify_attester_slashing( - state: &BeaconState, +pub fn verify_attester_slashing( + state: &BeaconState, attester_slashing: &AttesterSlashing, should_verify_slashable_attestations: bool, spec: &ChainSpec, @@ -42,8 +42,8 @@ pub fn verify_attester_slashing( /// Returns Ok(indices) if `indices.len() > 0`. /// /// Spec v0.5.1 -pub fn gather_attester_slashing_indices( - state: &BeaconState, +pub fn gather_attester_slashing_indices( + state: &BeaconState, attester_slashing: &AttesterSlashing, spec: &ChainSpec, ) -> Result, 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( - state: &BeaconState, +pub fn gather_attester_slashing_indices_modular( + state: &BeaconState, attester_slashing: &AttesterSlashing, is_slashed: F, spec: &ChainSpec, diff --git a/eth2/state_processing/src/per_block_processing/verify_deposit.rs b/eth2/state_processing/src/per_block_processing/verify_deposit.rs index 22a62a321..6f810ba84 100644 --- a/eth2/state_processing/src/per_block_processing/verify_deposit.rs +++ b/eth2/state_processing/src/per_block_processing/verify_deposit.rs @@ -16,8 +16,8 @@ use types::*; /// Note: this function is incomplete. /// /// Spec v0.5.1 -pub fn verify_deposit( - state: &BeaconState, +pub fn verify_deposit( + state: &BeaconState, deposit: &Deposit, verify_merkle_branch: bool, spec: &ChainSpec, @@ -47,7 +47,10 @@ pub fn verify_deposit( /// Verify that the `Deposit` index is correct. /// /// Spec v0.5.1 -pub fn verify_deposit_index(state: &BeaconState, deposit: &Deposit) -> Result<(), Error> { +pub fn verify_deposit_index( + state: &BeaconState, + 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( + state: &BeaconState, deposit: &Deposit, ) -> Result, Error> { let deposit_input = &deposit.deposit_data.deposit_input; @@ -89,7 +92,11 @@ pub fn get_existing_validator_index( /// Verify that a deposit is included in the state's eth1 deposit root. /// /// Spec v0.5.1 -fn verify_deposit_merkle_proof(state: &BeaconState, deposit: &Deposit, spec: &ChainSpec) -> bool { +fn verify_deposit_merkle_proof( + state: &BeaconState, + deposit: &Deposit, + spec: &ChainSpec, +) -> bool { let leaf = hash(&get_serialized_deposit_data(deposit)); verify_merkle_proof( Hash256::from_slice(&leaf), diff --git a/eth2/state_processing/src/per_block_processing/verify_exit.rs b/eth2/state_processing/src/per_block_processing/verify_exit.rs index 697188ee9..deaf9379a 100644 --- a/eth2/state_processing/src/per_block_processing/verify_exit.rs +++ b/eth2/state_processing/src/per_block_processing/verify_exit.rs @@ -8,8 +8,8 @@ use types::*; /// Returns `Ok(())` if the `Exit` is valid, otherwise indicates the reason for invalidity. /// /// Spec v0.5.1 -pub fn verify_exit( - state: &BeaconState, +pub fn verify_exit( + state: &BeaconState, 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( + state: &BeaconState, 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( + state: &BeaconState, exit: &VoluntaryExit, spec: &ChainSpec, time_independent_only: bool, diff --git a/eth2/state_processing/src/per_block_processing/verify_proposer_slashing.rs b/eth2/state_processing/src/per_block_processing/verify_proposer_slashing.rs index bbc03dd62..73fffcd64 100644 --- a/eth2/state_processing/src/per_block_processing/verify_proposer_slashing.rs +++ b/eth2/state_processing/src/per_block_processing/verify_proposer_slashing.rs @@ -8,9 +8,9 @@ use types::*; /// Returns `Ok(())` if the `ProposerSlashing` is valid, otherwise indicates the reason for invalidity. /// /// Spec v0.5.1 -pub fn verify_proposer_slashing( +pub fn verify_proposer_slashing( proposer_slashing: &ProposerSlashing, - state: &BeaconState, + state: &BeaconState, spec: &ChainSpec, ) -> Result<(), Error> { let proposer = state diff --git a/eth2/state_processing/src/per_block_processing/verify_slashable_attestation.rs b/eth2/state_processing/src/per_block_processing/verify_slashable_attestation.rs index 89cb93ce5..1e52c6a41 100644 --- a/eth2/state_processing/src/per_block_processing/verify_slashable_attestation.rs +++ b/eth2/state_processing/src/per_block_processing/verify_slashable_attestation.rs @@ -11,8 +11,8 @@ use types::*; /// Returns `Ok(())` if the `SlashableAttestation` is valid, otherwise indicates the reason for invalidity. /// /// Spec v0.5.1 -pub fn verify_slashable_attestation( - state: &BeaconState, +pub fn verify_slashable_attestation( + state: &BeaconState, slashable_attestation: &SlashableAttestation, spec: &ChainSpec, ) -> Result<(), Error> { diff --git a/eth2/state_processing/src/per_block_processing/verify_transfer.rs b/eth2/state_processing/src/per_block_processing/verify_transfer.rs index 8b0415508..771d350a5 100644 --- a/eth2/state_processing/src/per_block_processing/verify_transfer.rs +++ b/eth2/state_processing/src/per_block_processing/verify_transfer.rs @@ -11,8 +11,8 @@ use types::*; /// Note: this function is incomplete. /// /// Spec v0.5.1 -pub fn verify_transfer( - state: &BeaconState, +pub fn verify_transfer( + state: &BeaconState, 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( + state: &BeaconState, 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( + state: &BeaconState, transfer: &Transfer, spec: &ChainSpec, time_independent_only: bool, @@ -123,8 +123,8 @@ fn verify_transfer_parametric( /// Does not check that the transfer is valid, however checks for overflow in all actions. /// /// Spec v0.5.1 -pub fn execute_transfer( - state: &mut BeaconState, +pub fn execute_transfer( + state: &mut BeaconState, transfer: &Transfer, spec: &ChainSpec, ) -> Result<(), Error> { diff --git a/eth2/state_processing/src/per_epoch_processing.rs b/eth2/state_processing/src/per_epoch_processing.rs index 87c9b9398..e2ecd47d6 100644 --- a/eth2/state_processing/src/per_epoch_processing.rs +++ b/eth2/state_processing/src/per_epoch_processing.rs @@ -33,7 +33,10 @@ pub type WinningRootHashSet = HashMap; /// returned, a state might be "half-processed" and therefore in an invalid state. /// /// Spec v0.5.1 -pub fn per_epoch_processing(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> { +pub fn per_epoch_processing( + state: &mut BeaconState, + 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)?; @@ -87,7 +90,7 @@ pub fn per_epoch_processing(state: &mut BeaconState, spec: &ChainSpec) -> Result /// Maybe resets the eth1 period. /// /// Spec v0.5.1 -pub fn maybe_reset_eth1_period(state: &mut BeaconState, spec: &ChainSpec) { +pub fn maybe_reset_eth1_period(state: &mut BeaconState, spec: &ChainSpec) { let next_epoch = state.next_epoch(spec); let voting_period = spec.epochs_per_eth1_voting_period; @@ -109,8 +112,8 @@ pub fn maybe_reset_eth1_period(state: &mut BeaconState, spec: &ChainSpec) { /// - `previous_justified_epoch` /// /// Spec v0.5.1 -pub fn update_justification_and_finalization( - state: &mut BeaconState, +pub fn update_justification_and_finalization( + state: &mut BeaconState, 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(()) @@ -179,8 +182,8 @@ pub fn update_justification_and_finalization( /// Also returns a `WinningRootHashSet` for later use during epoch processing. /// /// Spec v0.5.1 -pub fn process_crosslinks( - state: &mut BeaconState, +pub fn process_crosslinks( + state: &mut BeaconState, spec: &ChainSpec, ) -> Result { let mut winning_root_for_shards: WinningRootHashSet = HashMap::new(); @@ -222,7 +225,10 @@ pub fn process_crosslinks( /// Finish up an epoch update. /// /// Spec v0.5.1 -pub fn finish_epoch_update(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> { +pub fn finish_epoch_update( + state: &mut BeaconState, + spec: &ChainSpec, +) -> Result<(), Error> { let current_epoch = state.current_epoch(spec); let next_epoch = state.next_epoch(spec); @@ -241,11 +247,7 @@ pub fn finish_epoch_update(state: &mut BeaconState, spec: &ChainSpec) -> Result< 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,8 +259,8 @@ 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.tree_hash_root()[..])); diff --git a/eth2/state_processing/src/per_epoch_processing/apply_rewards.rs b/eth2/state_processing/src/per_epoch_processing/apply_rewards.rs index 9af1ee8c3..fe31ef244 100644 --- a/eth2/state_processing/src/per_epoch_processing/apply_rewards.rs +++ b/eth2/state_processing/src/per_epoch_processing/apply_rewards.rs @@ -33,8 +33,8 @@ impl std::ops::AddAssign for Delta { /// Apply attester and proposer rewards. /// /// Spec v0.5.1 -pub fn apply_rewards( - state: &mut BeaconState, +pub fn apply_rewards( + state: &mut BeaconState, validator_statuses: &mut ValidatorStatuses, winning_root_for_shards: &WinningRootHashSet, spec: &ChainSpec, @@ -80,9 +80,9 @@ pub fn apply_rewards( /// attestation in the previous epoch. /// /// Spec v0.5.1 -fn get_proposer_deltas( +fn get_proposer_deltas( deltas: &mut Vec, - state: &mut BeaconState, + state: &mut BeaconState, validator_statuses: &mut ValidatorStatuses, winning_root_for_shards: &WinningRootHashSet, spec: &ChainSpec, @@ -121,9 +121,9 @@ fn get_proposer_deltas( /// Apply rewards for participation in attestations during the previous epoch. /// /// Spec v0.5.1 -fn get_justification_and_finalization_deltas( +fn get_justification_and_finalization_deltas( deltas: &mut Vec, - state: &BeaconState, + state: &BeaconState, validator_statuses: &ValidatorStatuses, spec: &ChainSpec, ) -> Result<(), Error> { @@ -262,9 +262,9 @@ fn compute_inactivity_leak_delta( /// Calculate the deltas based upon the winning roots for attestations during the previous epoch. /// /// Spec v0.5.1 -fn get_crosslink_deltas( +fn get_crosslink_deltas( deltas: &mut Vec, - state: &BeaconState, + state: &BeaconState, validator_statuses: &ValidatorStatuses, spec: &ChainSpec, ) -> Result<(), Error> { @@ -296,8 +296,8 @@ fn get_crosslink_deltas( /// Returns the base reward for some validator. /// /// Spec v0.5.1 -fn get_base_reward( - state: &BeaconState, +fn get_base_reward( + state: &BeaconState, index: usize, previous_total_balance: u64, spec: &ChainSpec, @@ -313,8 +313,8 @@ fn get_base_reward( /// Returns the inactivity penalty for some validator. /// /// Spec v0.5.1 -fn get_inactivity_penalty( - state: &BeaconState, +fn get_inactivity_penalty( + state: &BeaconState, index: usize, epochs_since_finality: u64, previous_total_balance: u64, @@ -329,6 +329,6 @@ fn get_inactivity_penalty( /// Returns the epochs since the last finalized epoch. /// /// Spec v0.5.1 -fn epochs_since_finality(state: &BeaconState, spec: &ChainSpec) -> Epoch { +fn epochs_since_finality(state: &BeaconState, spec: &ChainSpec) -> Epoch { state.current_epoch(spec) + 1 - state.finalized_epoch } diff --git a/eth2/state_processing/src/per_epoch_processing/get_attestation_participants.rs b/eth2/state_processing/src/per_epoch_processing/get_attestation_participants.rs index bea772204..ddf0d680f 100644 --- a/eth2/state_processing/src/per_epoch_processing/get_attestation_participants.rs +++ b/eth2/state_processing/src/per_epoch_processing/get_attestation_participants.rs @@ -4,8 +4,8 @@ use types::*; /// Returns validator indices which participated in the attestation. /// /// Spec v0.5.1 -pub fn get_attestation_participants( - state: &BeaconState, +pub fn get_attestation_participants( + state: &BeaconState, attestation_data: &AttestationData, bitfield: &Bitfield, spec: &ChainSpec, diff --git a/eth2/state_processing/src/per_epoch_processing/inclusion_distance.rs b/eth2/state_processing/src/per_epoch_processing/inclusion_distance.rs index 6b221f513..9d4b36876 100644 --- a/eth2/state_processing/src/per_epoch_processing/inclusion_distance.rs +++ b/eth2/state_processing/src/per_epoch_processing/inclusion_distance.rs @@ -6,8 +6,8 @@ use types::*; /// slot. /// /// Spec v0.5.1 -pub fn inclusion_distance( - state: &BeaconState, +pub fn inclusion_distance( + state: &BeaconState, attestations: &[&PendingAttestation], validator_index: usize, spec: &ChainSpec, @@ -19,8 +19,8 @@ pub fn inclusion_distance( /// Returns the slot of the earliest included attestation for some validator. /// /// Spec v0.5.1 -pub fn inclusion_slot( - state: &BeaconState, +pub fn inclusion_slot( + state: &BeaconState, attestations: &[&PendingAttestation], validator_index: usize, spec: &ChainSpec, @@ -32,8 +32,8 @@ pub fn inclusion_slot( /// Finds the earliest included attestation for some validator. /// /// Spec v0.5.1 -fn earliest_included_attestation( - state: &BeaconState, +fn earliest_included_attestation( + state: &BeaconState, attestations: &[&PendingAttestation], validator_index: usize, spec: &ChainSpec, diff --git a/eth2/state_processing/src/per_epoch_processing/process_ejections.rs b/eth2/state_processing/src/per_epoch_processing/process_ejections.rs index 6f64c46f7..5a18d77be 100644 --- a/eth2/state_processing/src/per_epoch_processing/process_ejections.rs +++ b/eth2/state_processing/src/per_epoch_processing/process_ejections.rs @@ -5,7 +5,10 @@ use types::{BeaconStateError as Error, *}; /// ``EJECTION_BALANCE``. /// /// Spec v0.5.1 -pub fn process_ejections(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> { +pub fn process_ejections( + state: &mut BeaconState, + 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 = state diff --git a/eth2/state_processing/src/per_epoch_processing/process_exit_queue.rs b/eth2/state_processing/src/per_epoch_processing/process_exit_queue.rs index a6362188d..082a64775 100644 --- a/eth2/state_processing/src/per_epoch_processing/process_exit_queue.rs +++ b/eth2/state_processing/src/per_epoch_processing/process_exit_queue.rs @@ -3,7 +3,7 @@ use types::*; /// Process the exit queue. /// /// Spec v0.5.1 -pub fn process_exit_queue(state: &mut BeaconState, spec: &ChainSpec) { +pub fn process_exit_queue(state: &mut BeaconState, spec: &ChainSpec) { let current_epoch = state.current_epoch(spec); let eligible = |index: usize| { @@ -32,8 +32,8 @@ pub fn process_exit_queue(state: &mut BeaconState, spec: &ChainSpec) { /// Initiate an exit for the validator of the given `index`. /// /// Spec v0.5.1 -fn prepare_validator_for_withdrawal( - state: &mut BeaconState, +fn prepare_validator_for_withdrawal( + state: &mut BeaconState, validator_index: usize, spec: &ChainSpec, ) { diff --git a/eth2/state_processing/src/per_epoch_processing/process_slashings.rs b/eth2/state_processing/src/per_epoch_processing/process_slashings.rs index 89a7dd484..e3a038bd7 100644 --- a/eth2/state_processing/src/per_epoch_processing/process_slashings.rs +++ b/eth2/state_processing/src/per_epoch_processing/process_slashings.rs @@ -3,20 +3,20 @@ use types::{BeaconStateError as Error, *}; /// Process slashings. /// /// Spec v0.5.1 -pub fn process_slashings( - state: &mut BeaconState, +pub fn process_slashings( + state: &mut BeaconState, 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)?; diff --git a/eth2/state_processing/src/per_epoch_processing/update_registry_and_shuffling_data.rs b/eth2/state_processing/src/per_epoch_processing/update_registry_and_shuffling_data.rs index d290d2987..b1e326225 100644 --- a/eth2/state_processing/src/per_epoch_processing/update_registry_and_shuffling_data.rs +++ b/eth2/state_processing/src/per_epoch_processing/update_registry_and_shuffling_data.rs @@ -5,8 +5,8 @@ use types::*; /// Peforms a validator registry update, if required. /// /// Spec v0.5.1 -pub fn update_registry_and_shuffling_data( - state: &mut BeaconState, +pub fn update_registry_and_shuffling_data( + state: &mut BeaconState, current_total_balance: u64, spec: &ChainSpec, ) -> Result<(), Error> { @@ -50,8 +50,8 @@ pub fn update_registry_and_shuffling_data( /// Returns `true` if the validator registry should be updated during an epoch processing. /// /// Spec v0.5.1 -pub fn should_update_validator_registry( - state: &BeaconState, +pub fn should_update_validator_registry( + state: &BeaconState, spec: &ChainSpec, ) -> Result { if state.finalized_epoch <= state.validator_registry_update_epoch { @@ -79,8 +79,8 @@ pub fn should_update_validator_registry( /// Note: Utilizes the cache and will fail if the appropriate cache is not initialized. /// /// Spec v0.5.1 -pub fn update_validator_registry( - state: &mut BeaconState, +pub fn update_validator_registry( + state: &mut BeaconState, current_total_balance: u64, spec: &ChainSpec, ) -> Result<(), Error> { @@ -134,8 +134,8 @@ pub fn update_validator_registry( /// Activate the validator of the given ``index``. /// /// Spec v0.5.1 -pub fn activate_validator( - state: &mut BeaconState, +pub fn activate_validator( + state: &mut BeaconState, validator_index: usize, is_genesis: bool, spec: &ChainSpec, diff --git a/eth2/state_processing/src/per_epoch_processing/validator_statuses.rs b/eth2/state_processing/src/per_epoch_processing/validator_statuses.rs index afa78c9c0..b5fba4be1 100644 --- a/eth2/state_processing/src/per_epoch_processing/validator_statuses.rs +++ b/eth2/state_processing/src/per_epoch_processing/validator_statuses.rs @@ -161,7 +161,10 @@ impl ValidatorStatuses { /// - Total balances for the current and previous epochs. /// /// Spec v0.5.1 - pub fn new(state: &BeaconState, spec: &ChainSpec) -> Result { + pub fn new( + state: &BeaconState, + spec: &ChainSpec, + ) -> Result { let mut statuses = Vec::with_capacity(state.validator_registry.len()); let mut total_balances = TotalBalances::default(); @@ -196,9 +199,9 @@ impl ValidatorStatuses { /// `total_balances` fields. /// /// Spec v0.5.1 - pub fn process_attestations( + pub fn process_attestations( &mut self, - state: &BeaconState, + state: &BeaconState, spec: &ChainSpec, ) -> Result<(), BeaconStateError> { for a in state @@ -262,9 +265,9 @@ impl ValidatorStatuses { /// "winning" shard block root for the previous epoch. /// /// Spec v0.5.1 - pub fn process_winning_roots( + pub fn process_winning_roots( &mut self, - state: &BeaconState, + state: &BeaconState, winning_roots: &WinningRootHashSet, spec: &ChainSpec, ) -> Result<(), BeaconStateError> { @@ -313,14 +316,14 @@ fn is_from_epoch(a: &PendingAttestation, epoch: Epoch, spec: &ChainSpec) -> bool /// the first slot of the given epoch. /// /// Spec v0.5.1 -fn has_common_epoch_boundary_root( +fn has_common_epoch_boundary_root( a: &PendingAttestation, - state: &BeaconState, + state: &BeaconState, epoch: Epoch, spec: &ChainSpec, ) -> Result { 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) } @@ -329,12 +332,12 @@ fn has_common_epoch_boundary_root( /// the current slot of the `PendingAttestation`. /// /// Spec v0.5.1 -fn has_common_beacon_block_root( +fn has_common_beacon_block_root( a: &PendingAttestation, - state: &BeaconState, + state: &BeaconState, spec: &ChainSpec, ) -> Result { - 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) } diff --git a/eth2/state_processing/src/per_epoch_processing/winning_root.rs b/eth2/state_processing/src/per_epoch_processing/winning_root.rs index 5d31dff31..246043b05 100644 --- a/eth2/state_processing/src/per_epoch_processing/winning_root.rs +++ b/eth2/state_processing/src/per_epoch_processing/winning_root.rs @@ -35,8 +35,8 @@ impl WinningRoot { /// per-epoch processing. /// /// Spec v0.5.1 -pub fn winning_root( - state: &BeaconState, +pub fn winning_root( + state: &BeaconState, shard: u64, spec: &ChainSpec, ) -> Result, BeaconStateError> { @@ -90,7 +90,11 @@ pub fn winning_root( /// Returns `true` if pending attestation `a` is eligible to become a winning root. /// /// Spec v0.5.1 -fn is_eligible_for_winning_root(state: &BeaconState, a: &PendingAttestation, shard: Shard) -> bool { +fn is_eligible_for_winning_root( + state: &BeaconState, + a: &PendingAttestation, + shard: Shard, +) -> bool { if shard >= state.latest_crosslinks.len() as u64 { return false; } @@ -101,8 +105,8 @@ 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.1 -fn get_attesting_validator_indices( - state: &BeaconState, +fn get_attesting_validator_indices( + state: &BeaconState, shard: u64, crosslink_data_root: &Hash256, spec: &ChainSpec, diff --git a/eth2/state_processing/src/per_slot_processing.rs b/eth2/state_processing/src/per_slot_processing.rs index 8f9606723..08875cf4d 100644 --- a/eth2/state_processing/src/per_slot_processing.rs +++ b/eth2/state_processing/src/per_slot_processing.rs @@ -11,7 +11,10 @@ pub enum Error { /// Advances a state forward by one slot, performing per-epoch processing if required. /// /// Spec v0.5.1 -pub fn per_slot_processing(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> { +pub fn per_slot_processing( + state: &mut BeaconState, + spec: &ChainSpec, +) -> Result<(), Error> { cache_state(state, spec)?; if (state.slot + 1) % spec.slots_per_epoch == 0 { @@ -23,7 +26,10 @@ pub fn per_slot_processing(state: &mut BeaconState, spec: &ChainSpec) -> Result< Ok(()) } -fn cache_state(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> { +fn cache_state( + state: &mut BeaconState, + 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` @@ -39,10 +45,10 @@ fn cache_state(state: &mut BeaconState, spec: &ChainSpec) -> Result<(), Error> { } // Store the previous slot's post state transition root. - state.set_state_root(previous_slot, previous_slot_state_root, spec)?; + 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, spec)?; + state.set_block_root(previous_slot, latest_block_root)?; // Set the state slot back to what it should be. state.slot -= 1; diff --git a/eth2/types/src/beacon_state.rs b/eth2/types/src/beacon_state.rs index 02210443f..1fc29f8e4 100644 --- a/eth2/types/src/beacon_state.rs +++ b/eth2/types/src/beacon_state.rs @@ -5,7 +5,7 @@ use cached_tree_hash::{Error as TreeHashCacheError, TreeHashCache}; use int_to_bytes::int_to_bytes32; use pubkey_cache::PubkeyCache; -use fixed_len_vec::FixedLenVec; +use fixed_len_vec::{typenum::Unsigned, FixedLenVec}; use serde_derive::{Deserialize, Serialize}; use ssz::{hash, ssz_encode}; use ssz_derive::{Decode, Encode}; @@ -15,7 +15,7 @@ use tree_hash_derive::{CachedTreeHash, TreeHash}; pub use beacon_state_types::{BeaconStateTypes, FewValidatorsBeaconState, FoundationBeaconState}; -mod beacon_state_types; +pub mod beacon_state_types; mod epoch_cache; mod pubkey_cache; mod tests; @@ -80,7 +80,7 @@ where pub validator_registry_update_epoch: Epoch, // Randomness and committees - pub latest_randao_mixes: FixedLenVec, + pub latest_randao_mixes: FixedLenVec, pub previous_shuffling_start_shard: u64, pub current_shuffling_start_shard: u64, pub previous_shuffling_epoch: Epoch, @@ -100,11 +100,11 @@ where pub finalized_root: Hash256, // Recent state - pub latest_crosslinks: TreeHashVector, - pub latest_block_roots: TreeHashVector, - latest_state_roots: TreeHashVector, - latest_active_index_roots: TreeHashVector, - latest_slashed_balances: TreeHashVector, + pub latest_crosslinks: FixedLenVec, + pub latest_block_roots: FixedLenVec, + latest_state_roots: FixedLenVec, + latest_active_index_roots: FixedLenVec, + latest_slashed_balances: FixedLenVec, pub latest_block_header: BeaconBlockHeader, pub historical_roots: Vec, @@ -169,8 +169,10 @@ impl BeaconState { validator_registry_update_epoch: spec.genesis_epoch, // Randomness and committees - latest_randao_mixes: vec![spec.zero_hash; spec.latest_randao_mixes_length as usize] - .into(), + latest_randao_mixes: FixedLenVec::from(vec![ + spec.zero_hash; + T::LatestRandaoMixesLength::to_usize() + ]), previous_shuffling_start_shard: spec.genesis_start_shard, current_shuffling_start_shard: spec.genesis_start_shard, previous_shuffling_epoch: spec.genesis_epoch, @@ -191,11 +193,21 @@ impl BeaconState { // Recent state latest_crosslinks: vec![initial_crosslink; spec.shard_count as usize].into(), - latest_block_roots: vec![spec.zero_hash; spec.slots_per_historical_root].into(), - latest_state_roots: vec![spec.zero_hash; spec.slots_per_historical_root].into(), - latest_active_index_roots: vec![spec.zero_hash; spec.latest_active_index_roots_length] - .into(), - latest_slashed_balances: vec![0; spec.latest_slashed_exit_length].into(), + latest_block_roots: FixedLenVec::from(vec![ + spec.zero_hash; + T::SlotsPerHistoricalRoot::to_usize() + ]), + latest_state_roots: FixedLenVec::from(vec![ + spec.zero_hash; + T::SlotsPerHistoricalRoot::to_usize() + ]), + latest_active_index_roots: FixedLenVec::from( + vec![spec.zero_hash; T::LatestActiveIndexRootsLength::to_usize()], + ), + latest_slashed_balances: FixedLenVec::from(vec![ + 0; + T::LatestSlashedExitLength::to_usize() + ]), latest_block_header: BeaconBlock::empty(spec).temporary_block_header(spec), historical_roots: vec![], @@ -228,7 +240,7 @@ impl BeaconState { Hash256::from_slice(&self.tree_hash_root()[..]) } - pub fn historical_batch(&self) -> HistoricalBatch { + pub fn historical_batch(&self) -> HistoricalBatch { HistoricalBatch { block_roots: self.latest_block_roots.clone(), state_roots: self.latest_state_roots.clone(), @@ -386,14 +398,9 @@ impl BeaconState { /// Safely obtains the index for latest block roots, given some `slot`. /// /// Spec v0.5.1 - fn get_latest_block_roots_index(&self, slot: Slot, spec: &ChainSpec) -> Result { - if (slot < self.slot) && (self.slot <= slot + spec.slots_per_historical_root as u64) { - let i = slot.as_usize() % spec.slots_per_historical_root; - if i >= self.latest_block_roots.len() { - Err(Error::InsufficientStateRoots) - } else { - Ok(i) - } + fn get_latest_block_roots_index(&self, slot: Slot) -> Result { + if (slot < self.slot) && (self.slot <= slot + self.latest_block_roots.len() as u64) { + Ok(slot.as_usize() % self.latest_block_roots.len()) } else { Err(BeaconStateError::SlotOutOfBounds) } @@ -402,12 +409,8 @@ impl BeaconState { /// Return the block root at a recent `slot`. /// /// Spec v0.5.1 - pub fn get_block_root( - &self, - slot: Slot, - spec: &ChainSpec, - ) -> Result<&Hash256, BeaconStateError> { - let i = self.get_latest_block_roots_index(slot, spec)?; + pub fn get_block_root(&self, slot: Slot) -> Result<&Hash256, BeaconStateError> { + let i = self.get_latest_block_roots_index(slot)?; Ok(&self.latest_block_roots[i]) } @@ -418,9 +421,8 @@ impl BeaconState { &mut self, slot: Slot, block_root: Hash256, - spec: &ChainSpec, ) -> Result<(), BeaconStateError> { - let i = self.get_latest_block_roots_index(slot, spec)?; + let i = self.get_latest_block_roots_index(slot)?; self.latest_block_roots[i] = block_root; Ok(()) } @@ -430,17 +432,10 @@ impl BeaconState { /// Spec v0.5.1 fn get_randao_mix_index(&self, epoch: Epoch, spec: &ChainSpec) -> Result { let current_epoch = self.current_epoch(spec); + let len = T::LatestRandaoMixesLength::to_u64(); - if (current_epoch - (spec.latest_randao_mixes_length as u64) < epoch) - & (epoch <= current_epoch) - { - let i = epoch.as_usize() % spec.latest_randao_mixes_length; - - if i < (&self.latest_randao_mixes[..]).len() { - Ok(i) - } else { - Err(Error::InsufficientRandaoMixes) - } + if (current_epoch - len < epoch) & (epoch <= current_epoch) { + Ok(epoch.as_usize() % len as usize) } else { Err(Error::EpochOutOfBounds) } @@ -459,7 +454,7 @@ impl BeaconState { signature: &Signature, spec: &ChainSpec, ) -> Result<(), Error> { - let i = epoch.as_usize() % spec.latest_randao_mixes_length; + let i = epoch.as_usize() % T::LatestRandaoMixesLength::to_usize(); let signature_hash = Hash256::from_slice(&hash(&ssz_encode(signature))); @@ -496,17 +491,12 @@ impl BeaconState { fn get_active_index_root_index(&self, epoch: Epoch, spec: &ChainSpec) -> Result { let current_epoch = self.current_epoch(spec); - if (current_epoch - spec.latest_active_index_roots_length as u64 + if (current_epoch - self.latest_active_index_roots.len() as u64 + spec.activation_exit_delay < epoch) & (epoch <= current_epoch + spec.activation_exit_delay) { - let i = epoch.as_usize() % spec.latest_active_index_roots_length; - if i < self.latest_active_index_roots.len() { - Ok(i) - } else { - Err(Error::InsufficientIndexRoots) - } + Ok(epoch.as_usize() % self.latest_active_index_roots.len()) } else { Err(Error::EpochOutOfBounds) } @@ -537,22 +527,17 @@ impl BeaconState { /// Replace `active_index_roots` with clones of `index_root`. /// /// Spec v0.5.1 - pub fn fill_active_index_roots_with(&mut self, index_root: Hash256, spec: &ChainSpec) { + pub fn fill_active_index_roots_with(&mut self, index_root: Hash256) { self.latest_active_index_roots = - vec![index_root; spec.latest_active_index_roots_length as usize].into() + vec![index_root; self.latest_active_index_roots.len() as usize].into() } /// Safely obtains the index for latest state roots, given some `slot`. /// /// Spec v0.5.1 - fn get_latest_state_roots_index(&self, slot: Slot, spec: &ChainSpec) -> Result { - if (slot < self.slot) && (self.slot <= slot + spec.slots_per_historical_root as u64) { - let i = slot.as_usize() % spec.slots_per_historical_root; - if i >= self.latest_state_roots.len() { - Err(Error::InsufficientStateRoots) - } else { - Ok(i) - } + fn get_latest_state_roots_index(&self, slot: Slot) -> Result { + if (slot < self.slot) && (self.slot <= slot + self.latest_state_roots.len() as u64) { + Ok(slot.as_usize() % self.latest_state_roots.len()) } else { Err(BeaconStateError::SlotOutOfBounds) } @@ -561,21 +546,16 @@ impl BeaconState { /// Gets the state root for some slot. /// /// Spec v0.5.1 - pub fn get_state_root(&mut self, slot: Slot, spec: &ChainSpec) -> Result<&Hash256, Error> { - let i = self.get_latest_state_roots_index(slot, spec)?; + pub fn get_state_root(&mut self, slot: Slot) -> Result<&Hash256, Error> { + let i = self.get_latest_state_roots_index(slot)?; Ok(&self.latest_state_roots[i]) } /// Sets the latest state root for slot. /// /// Spec v0.5.1 - pub fn set_state_root( - &mut self, - slot: Slot, - state_root: Hash256, - spec: &ChainSpec, - ) -> Result<(), Error> { - let i = self.get_latest_state_roots_index(slot, spec)?; + pub fn set_state_root(&mut self, slot: Slot, state_root: Hash256) -> Result<(), Error> { + let i = self.get_latest_state_roots_index(slot)?; self.latest_state_roots[i] = state_root; Ok(()) } @@ -583,8 +563,8 @@ impl BeaconState { /// Safely obtains the index for `latest_slashed_balances`, given some `epoch`. /// /// Spec v0.5.1 - fn get_slashed_balance_index(&self, epoch: Epoch, spec: &ChainSpec) -> Result { - let i = epoch.as_usize() % spec.latest_slashed_exit_length; + fn get_slashed_balance_index(&self, epoch: Epoch) -> Result { + let i = epoch.as_usize() % self.latest_slashed_balances.len(); // NOTE: the validity of the epoch is not checked. It is not in the spec but it's probably // useful to have. @@ -598,21 +578,16 @@ impl BeaconState { /// Gets the total slashed balances for some epoch. /// /// Spec v0.5.1 - pub fn get_slashed_balance(&self, epoch: Epoch, spec: &ChainSpec) -> Result { - let i = self.get_slashed_balance_index(epoch, spec)?; + pub fn get_slashed_balance(&self, epoch: Epoch) -> Result { + let i = self.get_slashed_balance_index(epoch)?; Ok(self.latest_slashed_balances[i]) } /// Sets the total slashed balances for some epoch. /// /// Spec v0.5.1 - pub fn set_slashed_balance( - &mut self, - epoch: Epoch, - balance: u64, - spec: &ChainSpec, - ) -> Result<(), Error> { - let i = self.get_slashed_balance_index(epoch, spec)?; + pub fn set_slashed_balance(&mut self, epoch: Epoch, balance: u64) -> Result<(), Error> { + let i = self.get_slashed_balance_index(epoch)?; self.latest_slashed_balances[i] = balance; Ok(()) } diff --git a/eth2/types/src/beacon_state/beacon_state_types.rs b/eth2/types/src/beacon_state/beacon_state_types.rs index 887e10c84..41f9f44c8 100644 --- a/eth2/types/src/beacon_state/beacon_state_types.rs +++ b/eth2/types/src/beacon_state/beacon_state_types.rs @@ -1,15 +1,23 @@ use crate::*; -use fixed_len_vec::typenum::{Unsigned, U8192}; +use fixed_len_vec::typenum::{Unsigned, U1024, U8, U8192}; pub trait BeaconStateTypes { - type NumLatestRandaoMixes: Unsigned + Clone + Sync + Send; + type ShardCount: Unsigned + Clone + Sync + Send; + type SlotsPerHistoricalRoot: Unsigned + Clone + Sync + Send; + type LatestRandaoMixesLength: Unsigned + Clone + Sync + Send; + type LatestActiveIndexRootsLength: Unsigned + Clone + Sync + Send; + type LatestSlashedExitLength: Unsigned + Clone + Sync + Send; } #[derive(Clone, PartialEq, Debug)] pub struct FoundationStateParams; impl BeaconStateTypes for FoundationStateParams { - type NumLatestRandaoMixes = U8192; + type ShardCount = U1024; + type SlotsPerHistoricalRoot = U8192; + type LatestRandaoMixesLength = U8192; + type LatestActiveIndexRootsLength = U8192; + type LatestSlashedExitLength = U8192; } pub type FoundationBeaconState = BeaconState; @@ -18,7 +26,11 @@ pub type FoundationBeaconState = BeaconState; pub struct FewValidatorsStateParams; impl BeaconStateTypes for FewValidatorsStateParams { - type NumLatestRandaoMixes = U8192; + type ShardCount = U8; + type SlotsPerHistoricalRoot = U8192; + type LatestRandaoMixesLength = U8192; + type LatestActiveIndexRootsLength = U8192; + type LatestSlashedExitLength = U8192; } pub type FewValidatorsBeaconState = BeaconState; diff --git a/eth2/types/src/chain_spec.rs b/eth2/types/src/chain_spec.rs index f3c92b42c..32f36a64d 100644 --- a/eth2/types/src/chain_spec.rs +++ b/eth2/types/src/chain_spec.rs @@ -70,17 +70,9 @@ 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_randao_mixes_length: usize, - pub latest_active_index_roots_length: usize, - pub latest_slashed_exit_length: usize, - /* * Reward and penalty quotients */ @@ -213,17 +205,9 @@ 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_randao_mixes_length: 8_192, - latest_active_index_roots_length: 8_192, - latest_slashed_exit_length: 8_192, - /* * Reward and penalty quotients */ diff --git a/eth2/types/src/historical_batch.rs b/eth2/types/src/historical_batch.rs index 3f8baabbc..fef6e2715 100644 --- a/eth2/types/src/historical_batch.rs +++ b/eth2/types/src/historical_batch.rs @@ -1,6 +1,8 @@ use crate::test_utils::TestRandom; -use crate::{Hash256, TreeHashVector}; +use crate::Hash256; +use crate::beacon_state::BeaconStateTypes; +use fixed_len_vec::FixedLenVec; use serde_derive::{Deserialize, Serialize}; use ssz_derive::{Decode, Encode}; use test_random_derive::TestRandom; @@ -21,15 +23,18 @@ use tree_hash_derive::{CachedTreeHash, TreeHash}; CachedTreeHash, TestRandom, )] -pub struct HistoricalBatch { - pub block_roots: TreeHashVector, - pub state_roots: TreeHashVector, +pub struct HistoricalBatch { + pub block_roots: FixedLenVec, + pub state_roots: FixedLenVec, } #[cfg(test)] mod tests { use super::*; + use crate::beacon_state::beacon_state_types::FoundationStateParams; - ssz_tests!(HistoricalBatch); - cached_tree_hash_tests!(HistoricalBatch); + pub type FoundationHistoricalBatch = HistoricalBatch; + + ssz_tests!(FoundationHistoricalBatch); + cached_tree_hash_tests!(FoundationHistoricalBatch); } diff --git a/eth2/types/src/lib.rs b/eth2/types/src/lib.rs index 1b8ca7453..03682439c 100644 --- a/eth2/types/src/lib.rs +++ b/eth2/types/src/lib.rs @@ -87,7 +87,7 @@ pub type AttesterMap = HashMap<(u64, u64), Vec>; pub type ProposerMap = HashMap; pub use bls::{AggregatePublicKey, AggregateSignature, Keypair, PublicKey, SecretKey, Signature}; -pub use fixed_len_vec::FixedLenVec; +pub use fixed_len_vec::{typenum::Unsigned, FixedLenVec}; pub use libp2p::floodsub::{Topic, TopicBuilder, TopicHash}; pub use libp2p::multiaddr; pub use libp2p::Multiaddr; diff --git a/eth2/types/src/test_utils/testing_attestation_data_builder.rs b/eth2/types/src/test_utils/testing_attestation_data_builder.rs index 4cb83a6b8..9d6bc5ec6 100644 --- a/eth2/types/src/test_utils/testing_attestation_data_builder.rs +++ b/eth2/types/src/test_utils/testing_attestation_data_builder.rs @@ -30,22 +30,22 @@ impl TestingAttestationDataBuilder { let target_root = if is_previous_epoch { *state - .get_block_root(previous_epoch.start_slot(spec.slots_per_epoch), spec) + .get_block_root(previous_epoch.start_slot(spec.slots_per_epoch)) .unwrap() } else { *state - .get_block_root(current_epoch.start_slot(spec.slots_per_epoch), spec) + .get_block_root(current_epoch.start_slot(spec.slots_per_epoch)) .unwrap() }; let source_root = *state - .get_block_root(source_epoch.start_slot(spec.slots_per_epoch), spec) + .get_block_root(source_epoch.start_slot(spec.slots_per_epoch)) .unwrap(); let data = AttestationData { // LMD GHOST vote slot, - beacon_block_root: *state.get_block_root(slot, spec).unwrap(), + beacon_block_root: *state.get_block_root(slot).unwrap(), // FFG Vote source_epoch, diff --git a/eth2/utils/fixed_len_vec/src/lib.rs b/eth2/utils/fixed_len_vec/src/lib.rs index a2e73a338..d2d4ec57c 100644 --- a/eth2/utils/fixed_len_vec/src/lib.rs +++ b/eth2/utils/fixed_len_vec/src/lib.rs @@ -17,6 +17,16 @@ where _phantom: PhantomData, } +impl FixedLenVec { + pub fn len(&self) -> usize { + self.vec.len() + } + + pub fn capacity() -> usize { + N::to_usize() + } +} + impl From> for FixedLenVec { fn from(mut vec: Vec) -> Self { dbg!(Self::capacity()); @@ -44,12 +54,6 @@ impl Default for FixedLenVec { } } -impl FixedLenVec { - pub fn capacity() -> usize { - N::to_usize() - } -} - impl> Index for FixedLenVec { type Output = I::Output;