Add progress on state_processing fixed-len update

This commit is contained in:
Paul Hauner 2019-05-08 15:36:02 +10:00
parent 7a67d34293
commit 8cefd20e9d
No known key found for this signature in database
GPG Key ID: D362883A9218FCC6
29 changed files with 275 additions and 268 deletions

View File

@ -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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
validator_index: usize,
spec: &ChainSpec,
) -> Result<(), Error> {

View File

@ -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<T: BeaconStateTypes>(
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(())
}

View File

@ -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<T: BeaconStateTypes>(
genesis_validator_deposits: &[Deposit],
genesis_time: u64,
genesis_eth1_data: Eth1Data,
spec: &ChainSpec,
) -> Result<BeaconState, BlockProcessingError> {
) -> Result<BeaconState<T>, 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)?;

View File

@ -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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
mut state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
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
@ -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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
transfers: &[Transfer],
spec: &ChainSpec,
) -> Result<(), Error> {

View File

@ -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<T: BeaconStateTypes>(
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: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
attestation: &Attestation,
state: &BeaconState,
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
committee: &[usize],
a: &Attestation,
spec: &ChainSpec,

View File

@ -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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
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: BeaconStateTypes>(
state: &BeaconState<T>,
attester_slashing: &AttesterSlashing,
is_slashed: F,
spec: &ChainSpec,

View File

@ -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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
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: BeaconStateTypes>(
state: &BeaconState<T>,
deposit: &Deposit,
) -> Result<Option<u64>, 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<T: BeaconStateTypes>(
state: &BeaconState<T>,
deposit: &Deposit,
spec: &ChainSpec,
) -> bool {
let leaf = hash(&get_serialized_deposit_data(deposit));
verify_merkle_proof(
Hash256::from_slice(&leaf),

View File

@ -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<T: BeaconStateTypes>(
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: BeaconStateTypes>(
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: BeaconStateTypes>(
state: &BeaconState<T>,
exit: &VoluntaryExit,
spec: &ChainSpec,
time_independent_only: bool,

View File

@ -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<T: BeaconStateTypes>(
proposer_slashing: &ProposerSlashing,
state: &BeaconState,
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<(), Error> {
let proposer = state

View File

@ -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<T: BeaconStateTypes>(
state: &BeaconState<T>,
slashable_attestation: &SlashableAttestation,
spec: &ChainSpec,
) -> Result<(), Error> {

View File

@ -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<T: BeaconStateTypes>(
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: BeaconStateTypes>(
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: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
transfer: &Transfer,
spec: &ChainSpec,
) -> Result<(), Error> {

View File

@ -33,7 +33,10 @@ pub type WinningRootHashSet = HashMap<u64, WinningRoot>;
/// 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<T: BeaconStateTypes>(
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)?;
@ -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<T: BeaconStateTypes>(state: &mut BeaconState<T>, 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<T: BeaconStateTypes>(
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(())
@ -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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
spec: &ChainSpec,
) -> Result<WinningRootHashSet, Error> {
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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()[..]));

View File

@ -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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
deltas: &mut Vec<Delta>,
state: &mut BeaconState,
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
deltas: &mut Vec<Delta>,
state: &BeaconState,
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
deltas: &mut Vec<Delta>,
state: &BeaconState,
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(state: &BeaconState<T>, spec: &ChainSpec) -> Epoch {
state.current_epoch(spec) + 1 - state.finalized_epoch
}

View File

@ -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<T: BeaconStateTypes>(
state: &BeaconState<T>,
attestation_data: &AttestationData,
bitfield: &Bitfield,
spec: &ChainSpec,

View File

@ -6,8 +6,8 @@ use types::*;
/// slot.
///
/// Spec v0.5.1
pub fn inclusion_distance(
state: &BeaconState,
pub fn inclusion_distance<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
attestations: &[&PendingAttestation],
validator_index: usize,
spec: &ChainSpec,

View File

@ -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<T: BeaconStateTypes>(
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

View File

@ -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<T: BeaconStateTypes>(state: &mut BeaconState<T>, 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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
validator_index: usize,
spec: &ChainSpec,
) {

View File

@ -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<T: BeaconStateTypes>(
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)?;

View File

@ -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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<bool, BeaconStateError> {
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
validator_index: usize,
is_genesis: bool,
spec: &ChainSpec,

View File

@ -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<Self, BeaconStateError> {
pub fn new<T: BeaconStateTypes>(
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<Self, BeaconStateError> {
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<T: BeaconStateTypes>(
&mut self,
state: &BeaconState,
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
&mut self,
state: &BeaconState,
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
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)
}
@ -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<T: BeaconStateTypes>(
a: &PendingAttestation,
state: &BeaconState,
state: &BeaconState<T>,
spec: &ChainSpec,
) -> 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)
}

View File

@ -35,8 +35,8 @@ impl WinningRoot {
/// per-epoch processing.
///
/// Spec v0.5.1
pub fn winning_root(
state: &BeaconState,
pub fn winning_root<T: BeaconStateTypes>(
state: &BeaconState<T>,
shard: u64,
spec: &ChainSpec,
) -> Result<Option<WinningRoot>, 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<T: BeaconStateTypes>(
state: &BeaconState<T>,
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<T: BeaconStateTypes>(
state: &BeaconState<T>,
shard: u64,
crosslink_data_root: &Hash256,
spec: &ChainSpec,

View File

@ -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<T: BeaconStateTypes>(
state: &mut BeaconState<T>,
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<T: BeaconStateTypes>(
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`
@ -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;

View File

@ -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<Hash256, T::NumLatestRandaoMixes>,
pub latest_randao_mixes: FixedLenVec<Hash256, T::LatestRandaoMixesLength>,
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<Crosslink>,
pub latest_block_roots: TreeHashVector<Hash256>,
latest_state_roots: TreeHashVector<Hash256>,
latest_active_index_roots: TreeHashVector<Hash256>,
latest_slashed_balances: TreeHashVector<u64>,
pub latest_crosslinks: FixedLenVec<Crosslink, T::ShardCount>,
pub latest_block_roots: FixedLenVec<Hash256, T::SlotsPerHistoricalRoot>,
latest_state_roots: FixedLenVec<Hash256, T::SlotsPerHistoricalRoot>,
latest_active_index_roots: FixedLenVec<Hash256, T::LatestActiveIndexRootsLength>,
latest_slashed_balances: FixedLenVec<u64, T::LatestSlashedExitLength>,
pub latest_block_header: BeaconBlockHeader,
pub historical_roots: Vec<Hash256>,
@ -169,8 +169,10 @@ impl<T: BeaconStateTypes> BeaconState<T> {
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<T: BeaconStateTypes> BeaconState<T> {
// 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<T: BeaconStateTypes> BeaconState<T> {
Hash256::from_slice(&self.tree_hash_root()[..])
}
pub fn historical_batch(&self) -> HistoricalBatch {
pub fn historical_batch(&self) -> HistoricalBatch<T> {
HistoricalBatch {
block_roots: self.latest_block_roots.clone(),
state_roots: self.latest_state_roots.clone(),
@ -386,14 +398,9 @@ impl<T: BeaconStateTypes> BeaconState<T> {
/// 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<usize, Error> {
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<usize, Error> {
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<T: BeaconStateTypes> BeaconState<T> {
/// 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<T: BeaconStateTypes> BeaconState<T> {
&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<T: BeaconStateTypes> BeaconState<T> {
/// Spec v0.5.1
fn get_randao_mix_index(&self, epoch: Epoch, spec: &ChainSpec) -> Result<usize, Error> {
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<T: BeaconStateTypes> BeaconState<T> {
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<T: BeaconStateTypes> BeaconState<T> {
fn get_active_index_root_index(&self, epoch: Epoch, spec: &ChainSpec) -> Result<usize, Error> {
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<T: BeaconStateTypes> BeaconState<T> {
/// 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<usize, Error> {
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<usize, Error> {
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<T: BeaconStateTypes> BeaconState<T> {
/// 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<T: BeaconStateTypes> BeaconState<T> {
/// 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<usize, Error> {
let i = epoch.as_usize() % spec.latest_slashed_exit_length;
fn get_slashed_balance_index(&self, epoch: Epoch) -> Result<usize, Error> {
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<T: BeaconStateTypes> BeaconState<T> {
/// Gets the total slashed balances for some epoch.
///
/// Spec v0.5.1
pub fn get_slashed_balance(&self, epoch: Epoch, spec: &ChainSpec) -> Result<u64, Error> {
let i = self.get_slashed_balance_index(epoch, spec)?;
pub fn get_slashed_balance(&self, epoch: Epoch) -> Result<u64, Error> {
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(())
}

View File

@ -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<FoundationStateParams>;
@ -18,7 +26,11 @@ pub type FoundationBeaconState = BeaconState<FoundationStateParams>;
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<FewValidatorsStateParams>;

View File

@ -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
*/

View File

@ -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<Hash256>,
pub state_roots: TreeHashVector<Hash256>,
pub struct HistoricalBatch<T: BeaconStateTypes> {
pub block_roots: FixedLenVec<Hash256, T::SlotsPerHistoricalRoot>,
pub state_roots: FixedLenVec<Hash256, T::SlotsPerHistoricalRoot>,
}
#[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<FoundationStateParams>;
ssz_tests!(FoundationHistoricalBatch);
cached_tree_hash_tests!(FoundationHistoricalBatch);
}

View File

@ -87,7 +87,7 @@ pub type AttesterMap = HashMap<(u64, u64), Vec<usize>>;
pub type ProposerMap = HashMap<u64, usize>;
pub use bls::{AggregatePublicKey, AggregateSignature, Keypair, PublicKey, SecretKey, Signature};
pub use 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;

View File

@ -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,

View File

@ -17,6 +17,16 @@ where
_phantom: PhantomData<N>,
}
impl<T, N: Unsigned> FixedLenVec<T, N> {
pub fn len(&self) -> usize {
self.vec.len()
}
pub fn capacity() -> usize {
N::to_usize()
}
}
impl<T: Default, N: Unsigned> From<Vec<T>> for FixedLenVec<T, N> {
fn from(mut vec: Vec<T>) -> Self {
dbg!(Self::capacity());
@ -44,12 +54,6 @@ impl<T, N: Unsigned> Default for FixedLenVec<T, N> {
}
}
impl<T, N: Unsigned> FixedLenVec<T, N> {
pub fn capacity() -> usize {
N::to_usize()
}
}
impl<T, N: Unsigned, I: SliceIndex<[T]>> Index<I> for FixedLenVec<T, N> {
type Output = I::Output;