diff --git a/examples/serde.rs b/examples/serde.rs index c47a4692e..b34ef2ac3 100644 --- a/examples/serde.rs +++ b/examples/serde.rs @@ -1,40 +1,28 @@ #![cfg(feature = "serde")] -use ethereum_consensus::altair::mainnet::SyncCommittee; -use ethereum_consensus::bellatrix::mainnet::ExecutionPayloadHeader; -use ethereum_consensus::phase0::mainnet::{ - Attestation, AttesterSlashing, BeaconState, Deposit, PendingAttestation, ProposerSlashing, - SignedBeaconBlock, SignedVoluntaryExit, +use ethereum_consensus::{ + altair::mainnet::SyncCommittee, + bellatrix::mainnet::ExecutionPayloadHeader, + phase0::mainnet::{ + Attestation, AttesterSlashing, BeaconState, Deposit, PendingAttestation, ProposerSlashing, + SignedBeaconBlock, SignedVoluntaryExit, + }, }; fn main() { let mut block = SignedBeaconBlock::default(); - block - .message - .body - .proposer_slashings - .push(ProposerSlashing::default()); - block - .message - .body - .attester_slashings - .push(AttesterSlashing::default()); + block.message.body.proposer_slashings.push(ProposerSlashing::default()); + block.message.body.attester_slashings.push(AttesterSlashing::default()); block.message.body.attestations.push(Attestation::default()); block.message.body.deposits.push(Deposit::default()); - block - .message - .body - .voluntary_exits - .push(SignedVoluntaryExit::default()); + block.message.body.voluntary_exits.push(SignedVoluntaryExit::default()); let block_json = serde_json::to_string(&block).unwrap(); println!("{block_json}"); let _: SignedBeaconBlock = serde_json::from_str(&block_json).unwrap(); let mut state = BeaconState::default(); - state - .current_epoch_attestations - .push(PendingAttestation::default()); + state.current_epoch_attestations.push(PendingAttestation::default()); let state_json = serde_json::to_string(&state).unwrap(); println!("{state_json}"); diff --git a/examples/sketch.rs b/examples/sketch.rs index c8162c9ce..90ec0b276 100644 --- a/examples/sketch.rs +++ b/examples/sketch.rs @@ -1,7 +1,9 @@ -use ethereum_consensus::altair::mainnet as altair; -use ethereum_consensus::bellatrix::mainnet as bellatrix; -use ethereum_consensus::phase0::mainnet as phase0; -use ethereum_consensus::state_transition::{Context, Validation}; +use ethereum_consensus::{ + altair::mainnet as altair, + bellatrix::mainnet as bellatrix, + phase0::mainnet as phase0, + state_transition::{Context, Validation}, +}; fn main() { let context = Context::for_mainnet(); diff --git a/examples/state_transition_across_multiple_forks.rs b/examples/state_transition_across_multiple_forks.rs index 0f86a388c..946cdc089 100644 --- a/examples/state_transition_across_multiple_forks.rs +++ b/examples/state_transition_across_multiple_forks.rs @@ -1,8 +1,9 @@ -use ethereum_consensus::altair::mainnet as altair; -use ethereum_consensus::bellatrix::mainnet as bellatrix; -use ethereum_consensus::bellatrix::NoOpExecutionEngine; -use ethereum_consensus::phase0::mainnet as phase0; -use ethereum_consensus::state_transition::mainnet::{Context, Executor}; +use ethereum_consensus::{ + altair::mainnet as altair, + bellatrix::{mainnet as bellatrix, NoOpExecutionEngine}, + phase0::mainnet as phase0, + state_transition::mainnet::{Context, Executor}, +}; use ssz_rs::prelude::*; use std::error::Error; diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..e70aee8cc --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,9 @@ +reorder_imports = true +imports_granularity = "Crate" +use_small_heuristics = "Max" +comment_width = 100 +wrap_comments = true +binop_separator = "Back" +trailing_comma = "Vertical" +trailing_semicolon = false +use_field_init_shorthand = true diff --git a/src/altair/beacon_block.rs b/src/altair/beacon_block.rs index b40cf9a42..a88ac7735 100644 --- a/src/altair/beacon_block.rs +++ b/src/altair/beacon_block.rs @@ -1,8 +1,10 @@ -use crate::altair::SyncAggregate; -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + altair::SyncAggregate, + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize, PartialEq, Eq)] diff --git a/src/altair/beacon_state.rs b/src/altair/beacon_state.rs index 5eb64cde9..ec292a374 100644 --- a/src/altair/beacon_state.rs +++ b/src/altair/beacon_state.rs @@ -1,8 +1,10 @@ -use crate::altair::{ - BeaconBlockHeader, Checkpoint, Eth1Data, Fork, SyncCommittee, Validator, - JUSTIFICATION_BITS_LENGTH, +use crate::{ + altair::{ + BeaconBlockHeader, Checkpoint, Eth1Data, Fork, SyncCommittee, Validator, + JUSTIFICATION_BITS_LENGTH, + }, + primitives::{Bytes32, Gwei, ParticipationFlags, Root, Slot}, }; -use crate::primitives::{Bytes32, Gwei, ParticipationFlags, Root, Slot}; use ssz_rs::prelude::*; #[derive(Default, Debug, SimpleSerialize, Clone, PartialEq, Eq)] diff --git a/src/altair/block_processing.rs b/src/altair/block_processing.rs index 750e6b8cf..31a4264b5 100644 --- a/src/altair/block_processing.rs +++ b/src/altair/block_processing.rs @@ -1,12 +1,14 @@ use crate::altair as spec; -use crate::crypto::{eth_fast_aggregate_verify, verify_signature}; -use crate::domains::DomainType; -use crate::primitives::{BlsPublicKey, ParticipationFlags, ValidatorIndex}; -use crate::signing::compute_signing_root; -use crate::state_transition::{ - invalid_operation_error, Context, InvalidAttestation, InvalidDeposit, InvalidOperation, - InvalidSyncAggregate, Result, +use crate::{ + crypto::{eth_fast_aggregate_verify, verify_signature}, + domains::DomainType, + primitives::{BlsPublicKey, ParticipationFlags, ValidatorIndex}, + signing::compute_signing_root, + state_transition::{ + invalid_operation_error, Context, InvalidAttestation, InvalidDeposit, InvalidOperation, + InvalidSyncAggregate, Result, + }, }; use spec::{ add_flag, compute_domain, compute_epoch_at_slot, decrease_balance, @@ -20,8 +22,10 @@ use spec::{ PARTICIPATION_FLAG_WEIGHTS, PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, WEIGHT_DENOMINATOR, }; use ssz_rs::prelude::*; -use std::collections::{HashMap, HashSet}; -use std::iter::zip; +use std::{ + collections::{HashMap, HashSet}, + iter::zip, +}; pub fn process_attestation< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -58,7 +62,7 @@ pub fn process_attestation< target: data.target.epoch, current: current_epoch, }, - ))); + ))) } let attestation_epoch = compute_epoch_at_slot(data.slot, context); @@ -69,7 +73,7 @@ pub fn process_attestation< epoch: attestation_epoch, target: data.target.epoch, }, - ))); + ))) } let attestation_has_delay = data.slot + context.min_attestation_inclusion_delay <= state.slot; @@ -83,17 +87,14 @@ pub fn process_attestation< lower_bound: data.slot + context.slots_per_epoch, upper_bound: data.slot + context.min_attestation_inclusion_delay, }, - ))); + ))) } let committee_count = get_committee_count_per_slot(state, data.target.epoch, context); if data.index >= committee_count { return Err(invalid_operation_error(InvalidOperation::Attestation( - InvalidAttestation::InvalidIndex { - index: data.index, - upper_bound: committee_count, - }, - ))); + InvalidAttestation::InvalidIndex { index: data.index, upper_bound: committee_count }, + ))) } let committee = get_beacon_committee(state, data.slot, data.index, context)?; @@ -103,7 +104,7 @@ pub fn process_attestation< expected_length: committee.len(), length: attestation.aggregation_bits.len(), }, - ))); + ))) } // Participation flag indices @@ -125,15 +126,15 @@ pub fn process_attestation< for index in attesting_indices { for (flag_index, weight) in PARTICIPATION_FLAG_WEIGHTS.iter().enumerate() { if is_current { - if participation_flag_indices.contains(&flag_index) - && !has_flag(state.current_epoch_participation[index], flag_index) + if participation_flag_indices.contains(&flag_index) && + !has_flag(state.current_epoch_participation[index], flag_index) { state.current_epoch_participation[index] = add_flag(state.current_epoch_participation[index], flag_index); proposer_reward_numerator += get_base_reward(state, index, context)? * weight; } - } else if participation_flag_indices.contains(&flag_index) - && !has_flag(state.previous_epoch_participation[index], flag_index) + } else if participation_flag_indices.contains(&flag_index) && + !has_flag(state.previous_epoch_participation[index], flag_index) { state.previous_epoch_participation[index] = add_flag(state.previous_epoch_participation[index], flag_index); @@ -146,11 +147,7 @@ pub fn process_attestation< let proposer_reward_denominator = (WEIGHT_DENOMINATOR - PROPOSER_WEIGHT) * WEIGHT_DENOMINATOR / PROPOSER_WEIGHT; let proposer_reward = proposer_reward_numerator / proposer_reward_denominator; - increase_balance( - state, - get_beacon_proposer_index(state, context)?, - proposer_reward, - ); + increase_balance(state, get_beacon_proposer_index(state, context)?, proposer_reward); Ok(()) } @@ -188,14 +185,8 @@ pub fn process_deposit< let root = &state.eth1_data.deposit_root; if !is_valid_merkle_branch(&leaf, branch.iter(), depth, index, root) { return Err(invalid_operation_error(InvalidOperation::Deposit( - InvalidDeposit::InvalidProof { - leaf, - branch, - depth, - index, - root: *root, - }, - ))); + InvalidDeposit::InvalidProof { leaf, branch, depth, index, root: *root }, + ))) } state.eth1_deposit_index += 1; @@ -215,25 +206,15 @@ pub fn process_deposit< if verify_signature(public_key, signing_root.as_ref(), &deposit.data.signature).is_err() { // NOTE: explicitly return with no error and also no further mutations to `state` - return Ok(()); + return Ok(()) } - state - .validators - .push(get_validator_from_deposit(deposit, context)); + state.validators.push(get_validator_from_deposit(deposit, context)); state.balances.push(amount); - state - .previous_epoch_participation - .push(ParticipationFlags::default()); - state - .current_epoch_participation - .push(ParticipationFlags::default()); + state.previous_epoch_participation.push(ParticipationFlags::default()); + state.current_epoch_participation.push(ParticipationFlags::default()); state.inactivity_scores.push(0) } else { - let index = state - .validators - .iter() - .position(|v| &v.public_key == public_key) - .unwrap(); + let index = state.validators.iter().position(|v| &v.public_key == public_key).unwrap(); increase_balance(state, index, amount); } @@ -266,20 +247,10 @@ pub fn process_sync_aggregate< ) -> Result<()> { // Verify sync committee aggregate signature signing over the previous slot block root let committee_public_keys = &state.current_sync_committee.public_keys; - let participant_public_keys = zip( - committee_public_keys.iter(), - sync_aggregate.sync_committee_bits.iter(), - ) - .filter_map( - |(public_key, bit)| { - if *bit { - Some(public_key) - } else { - None - } - }, - ) - .collect::>(); + let participant_public_keys = + zip(committee_public_keys.iter(), sync_aggregate.sync_committee_bits.iter()) + .filter_map(|(public_key, bit)| if *bit { Some(public_key) } else { None }) + .collect::>(); let previous_slot = u64::max(state.slot, 1) - 1; let domain = get_domain( state, @@ -301,7 +272,7 @@ pub fn process_sync_aggregate< signature: sync_aggregate.sync_committee_signature.clone(), root: signing_root, }, - ))); + ))) } // Compute participant and proposer rewards @@ -324,23 +295,15 @@ pub fn process_sync_aggregate< .collect::>(); let mut committee_indices: Vec = Vec::default(); for public_key in state.current_sync_committee.public_keys.iter() { - committee_indices.push( - *all_public_keys - .get(public_key) - .expect("validator public_key should exist"), - ); + committee_indices + .push(*all_public_keys.get(public_key).expect("validator public_key should exist")); } - for (participant_index, participation_bit) in zip( - committee_indices.iter(), - sync_aggregate.sync_committee_bits.iter(), - ) { + for (participant_index, participation_bit) in + zip(committee_indices.iter(), sync_aggregate.sync_committee_bits.iter()) + { if *participation_bit { increase_balance(state, *participant_index, participant_reward); - increase_balance( - state, - get_beacon_proposer_index(state, context)?, - proposer_reward, - ); + increase_balance(state, get_beacon_proposer_index(state, context)?, proposer_reward); } else { decrease_balance(state, *participant_index, participant_reward); } diff --git a/src/altair/epoch_processing.rs b/src/altair/epoch_processing.rs index c6eaa626a..be0b9c297 100644 --- a/src/altair/epoch_processing.rs +++ b/src/altair/epoch_processing.rs @@ -1,7 +1,9 @@ use crate::altair as spec; -use crate::primitives::{Gwei, ParticipationFlags, ValidatorIndex, GENESIS_EPOCH}; -use crate::state_transition::{Context, Result}; +use crate::{ + primitives::{Gwei, ParticipationFlags, ValidatorIndex, GENESIS_EPOCH}, + state_transition::{Context, Result}, +}; use spec::{ decrease_balance, get_base_reward_per_increment, get_current_epoch, get_eligible_validator_indices, get_flag_index_deltas, get_inactivity_penalty_deltas, @@ -66,10 +68,11 @@ pub fn process_justification_and_finalization< context: &Context, ) -> Result<()> { // Initial FFG checkpoint values have a `0x00` stub for `root`. - // Skip FFG updates in the first two epochs to avoid corner cases that might result in modifying this stub. + // Skip FFG updates in the first two epochs to avoid corner cases that might result in modifying + // this stub. let current_epoch = get_current_epoch(state, context); if current_epoch <= GENESIS_EPOCH + 1 { - return Ok(()); + return Ok(()) } let previous_indices = get_unslashed_participating_indices( @@ -121,7 +124,7 @@ pub fn process_inactivity_updates< // Skip the genesis epoch as score updates are based on the previous epoch participation let current_epoch = get_current_epoch(state, context); if current_epoch == GENESIS_EPOCH { - return Ok(()); + return Ok(()) } let eligible_validator_indices = @@ -142,10 +145,8 @@ pub fn process_inactivity_updates< } // Decrease the inactivity score of all eligible validators during a leak-free epoch if not_is_leaking { - state.inactivity_scores[index] -= u64::min( - context.inactivity_score_recovery_rate, - state.inactivity_scores[index], - ); + state.inactivity_scores[index] -= + u64::min(context.inactivity_score_recovery_rate, state.inactivity_scores[index]); } } Ok(()) @@ -173,10 +174,11 @@ pub fn process_rewards_and_penalties< >, context: &Context, ) -> Result<()> { - // No rewards are applied at the end of `GENESIS_EPOCH` because rewards are for work done in the previous epoch + // No rewards are applied at the end of `GENESIS_EPOCH` because rewards are for work done in the + // previous epoch let current_epoch = get_current_epoch(state, context); if current_epoch == GENESIS_EPOCH { - return Ok(()); + return Ok(()) } let mut deltas = Vec::new(); @@ -218,9 +220,8 @@ pub fn process_participation_flag_updates< let current_participation = mem::take(&mut state.current_epoch_participation); state.previous_epoch_participation = current_participation; let rotate_participation = vec![ParticipationFlags::default(); state.validators.len()]; - state.current_epoch_participation = rotate_participation - .try_into() - .expect("should convert from Vec to List"); + state.current_epoch_participation = + rotate_participation.try_into().expect("should convert from Vec to List"); Ok(()) } @@ -254,8 +255,8 @@ pub fn process_slashings< ); for i in 0..state.validators.len() { let validator = &state.validators[i]; - if validator.slashed - && (epoch + context.epochs_per_slashings_vector / 2) == validator.withdrawable_epoch + if validator.slashed && + (epoch + context.epochs_per_slashings_vector / 2) == validator.withdrawable_epoch { let increment = context.effective_balance_increment; let penalty_numerator = diff --git a/src/altair/fork.rs b/src/altair/fork.rs index dbe0f9139..8212618cb 100644 --- a/src/altair/fork.rs +++ b/src/altair/fork.rs @@ -1,9 +1,11 @@ -use crate::altair::{ - add_flag, get_attestation_participation_flag_indices, get_attesting_indices, - get_next_sync_committee, BeaconState, Fork, +use crate::{ + altair::{ + add_flag, get_attestation_participation_flag_indices, get_attesting_indices, + get_next_sync_committee, BeaconState, Fork, + }, + phase0, + state_transition::{Context, Result}, }; -use crate::phase0; -use crate::state_transition::{Context, Result}; use ssz_rs::prelude::*; fn translate_participation< @@ -80,15 +82,12 @@ pub fn upgrade_to_altair< >, > { let epoch = phase0::get_current_epoch(state, context); - let previous_epoch_participation = vec![0u8; state.validators.len()] - .try_into() - .map_err(|(_, err)| err)?; - let current_epoch_participation = vec![0u8; state.validators.len()] - .try_into() - .map_err(|(_, err)| err)?; - let inactivity_scores = vec![0u64; state.validators.len()] - .try_into() - .map_err(|(_, err)| err)?; + let previous_epoch_participation = + vec![0u8; state.validators.len()].try_into().map_err(|(_, err)| err)?; + let current_epoch_participation = + vec![0u8; state.validators.len()].try_into().map_err(|(_, err)| err)?; + let inactivity_scores = + vec![0u64; state.validators.len()].try_into().map_err(|(_, err)| err)?; let mut post_state = BeaconState { genesis_time: state.genesis_time, genesis_validators_root: state.genesis_validators_root, diff --git a/src/altair/genesis.rs b/src/altair/genesis.rs index d2e340ec5..b76f43588 100644 --- a/src/altair/genesis.rs +++ b/src/altair/genesis.rs @@ -1,8 +1,10 @@ use crate::altair as spec; -use crate::phase0::DEPOSIT_DATA_LIST_BOUND; -use crate::primitives::{Gwei, Hash32, GENESIS_EPOCH}; -use crate::state_transition::{Context, Result}; +use crate::{ + phase0::DEPOSIT_DATA_LIST_BOUND, + primitives::{Gwei, Hash32, GENESIS_EPOCH}, + state_transition::{Context, Result}, +}; use spec::{ get_active_validator_indices, get_next_sync_committee, process_deposit, BeaconBlock, BeaconBlockBody, BeaconBlockHeader, BeaconState, Deposit, DepositData, Eth1Data, Fork, @@ -60,10 +62,7 @@ pub fn initialize_beacon_state_from_eth1< SYNC_COMMITTEE_SIZE, >::default(); let body_root = latest_block_body.hash_tree_root()?; - let latest_block_header = BeaconBlockHeader { - body_root, - ..Default::default() - }; + let latest_block_header = BeaconBlockHeader { body_root, ..Default::default() }; let randao_mixes = Vector::try_from( std::iter::repeat(eth1_block_hash) .take(context.epochs_per_historical_vector as usize) @@ -132,13 +131,13 @@ pub fn is_valid_genesis_state< context: &Context, ) -> bool { if state.genesis_time < context.min_genesis_time { - return false; + return false } - if get_active_validator_indices(state, GENESIS_EPOCH).len() - < context.min_genesis_active_validator_count + if get_active_validator_indices(state, GENESIS_EPOCH).len() < + context.min_genesis_active_validator_count { - return false; + return false } true @@ -180,8 +179,5 @@ pub fn get_genesis_block< SYNC_COMMITTEE_SIZE, >, > { - Ok(BeaconBlock { - state_root: genesis_state.hash_tree_root()?, - ..Default::default() - }) + Ok(BeaconBlock { state_root: genesis_state.hash_tree_root()?, ..Default::default() }) } diff --git a/src/altair/helpers.rs b/src/altair/helpers.rs index b6a4a2bf4..8f68cb8dd 100644 --- a/src/altair/helpers.rs +++ b/src/altair/helpers.rs @@ -1,10 +1,12 @@ use crate::altair as spec; -use crate::crypto::{eth_aggregate_public_keys, hash}; -use crate::domains::DomainType; -use crate::primitives::{BlsPublicKey, Epoch, Gwei, ParticipationFlags, ValidatorIndex}; -use crate::state_transition::{ - invalid_operation_error, Context, Error, InvalidAttestation, InvalidOperation, Result, +use crate::{ + crypto::{eth_aggregate_public_keys, hash}, + domains::DomainType, + primitives::{BlsPublicKey, Epoch, Gwei, ParticipationFlags, ValidatorIndex}, + state_transition::{ + invalid_operation_error, Context, Error, InvalidAttestation, InvalidOperation, Result, + }, }; use integer_sqrt::IntegerSquareRoot; use spec::{ @@ -108,18 +110,13 @@ pub fn get_next_sync_committee< context: &Context, ) -> Result> { let indices = get_next_sync_committee_indices(state, context)?; - let public_keys = indices - .into_iter() - .map(|i| state.validators[i].public_key.clone()) - .collect::>(); + let public_keys = + indices.into_iter().map(|i| state.validators[i].public_key.clone()).collect::>(); let public_keys = Vector::::try_from(public_keys) .map_err(|(_, err)| err)?; let aggregate_public_key = eth_aggregate_public_keys(&public_keys)?; - Ok(SyncCommittee:: { - public_keys, - aggregate_public_key, - }) + Ok(SyncCommittee:: { public_keys, aggregate_public_key }) } pub fn get_base_reward_per_increment< @@ -144,13 +141,12 @@ pub fn get_base_reward_per_increment< >, context: &Context, ) -> Result { - Ok( - context.effective_balance_increment * context.base_reward_factor - / get_total_active_balance(state, context)?.integer_sqrt(), - ) + Ok(context.effective_balance_increment * context.base_reward_factor / + get_total_active_balance(state, context)?.integer_sqrt()) } -// Return the set of validator indices that are both active and unslashed for the given ``flag_index`` and ``epoch`` +// Return the set of validator indices that are both active and unslashed for the given +// ``flag_index`` and ``epoch`` pub fn get_unslashed_participating_indices< const SLOTS_PER_HISTORICAL_ROOT: usize, const HISTORICAL_ROOTS_LIMIT: usize, @@ -183,7 +179,7 @@ pub fn get_unslashed_participating_indices< requested: epoch, previous: previous_epoch, current: current_epoch, - }); + }) } let epoch_participation = if is_current { @@ -241,12 +237,12 @@ pub fn get_attestation_participation_flag_indices< source_checkpoint: data.source.clone(), current: get_current_epoch(state, context), }, - ))); + ))) } - let is_matching_target = is_matching_source - && (data.target.root == *get_block_root(state, data.target.epoch, context)?); - let is_matching_head = is_matching_target - && (data.beacon_block_root == *get_block_root_at_slot(state, data.slot)?); + let is_matching_target = is_matching_source && + (data.target.root == *get_block_root(state, data.target.epoch, context)?); + let is_matching_head = is_matching_target && + (data.beacon_block_root == *get_block_root_at_slot(state, data.slot)?); let mut participation_flag_indices = Vec::new(); if is_matching_source && inclusion_delay <= context.slots_per_epoch.integer_sqrt() { @@ -394,8 +390,8 @@ pub fn slash_validator< decrease_balance( state, slashed_index, - state.validators[slashed_index].effective_balance - / context.min_slashing_penalty_quotient_altair, + state.validators[slashed_index].effective_balance / + context.min_slashing_penalty_quotient_altair, ); let proposer_index = get_beacon_proposer_index(state, context)?; @@ -407,10 +403,6 @@ pub fn slash_validator< let proposer_reward_scaling_factor = PROPOSER_WEIGHT / WEIGHT_DENOMINATOR; let proposer_reward = whistleblower_reward * proposer_reward_scaling_factor; increase_balance(state, proposer_index, proposer_reward); - increase_balance( - state, - whistleblower_index, - whistleblower_reward - proposer_reward, - ); + increase_balance(state, whistleblower_index, whistleblower_reward - proposer_reward); Ok(()) } diff --git a/src/altair/light_client.rs b/src/altair/light_client.rs index 8f4f41b64..13eb336bf 100644 --- a/src/altair/light_client.rs +++ b/src/altair/light_client.rs @@ -1,6 +1,8 @@ -use crate::altair::{SyncAggregate, SyncCommittee}; -use crate::phase0::BeaconBlockHeader; -use crate::primitives::{Bytes32, Version}; +use crate::{ + altair::{SyncAggregate, SyncCommittee}, + phase0::BeaconBlockHeader, + primitives::{Bytes32, Version}, +}; use ssz_rs::prelude::*; pub const NEXT_SYNC_COMMITTEE_INDEX_FLOOR_LOG_2: usize = 5; diff --git a/src/altair/mod.rs b/src/altair/mod.rs index e424e99d8..53829944b 100644 --- a/src/altair/mod.rs +++ b/src/altair/mod.rs @@ -37,8 +37,7 @@ pub use crate::phase0::{ JUSTIFICATION_BITS_LENGTH, }; -pub use presets::mainnet; -pub use presets::minimal; +pub use presets::{mainnet, minimal}; pub const TIMELY_SOURCE_FLAG_INDEX: usize = 0; pub const TIMELY_TARGET_FLAG_INDEX: usize = 1; @@ -49,8 +48,5 @@ pub const TIMELY_HEAD_WEIGHT: u64 = 14; pub const SYNC_REWARD_WEIGHT: u64 = 2; pub const PROPOSER_WEIGHT: u64 = 8; pub const WEIGHT_DENOMINATOR: u64 = 64; -pub const PARTICIPATION_FLAG_WEIGHTS: [u64; 3] = [ - TIMELY_SOURCE_WEIGHT, - TIMELY_TARGET_WEIGHT, - TIMELY_HEAD_WEIGHT, -]; +pub const PARTICIPATION_FLAG_WEIGHTS: [u64; 3] = + [TIMELY_SOURCE_WEIGHT, TIMELY_TARGET_WEIGHT, TIMELY_HEAD_WEIGHT]; diff --git a/src/altair/networking.rs b/src/altair/networking.rs index 526c1d695..7b53ee7ce 100644 --- a/src/altair/networking.rs +++ b/src/altair/networking.rs @@ -1,5 +1,4 @@ -use crate::altair::validator::SYNC_COMMITTEE_SUBNET_COUNT; -use crate::phase0::ATTESTATION_SUBNET_COUNT; +use crate::{altair::validator::SYNC_COMMITTEE_SUBNET_COUNT, phase0::ATTESTATION_SUBNET_COUNT}; use ssz_rs::prelude::Bitvector; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/src/altair/presets/mainnet.rs b/src/altair/presets/mainnet.rs index 57b811240..18e1cc44f 100644 --- a/src/altair/presets/mainnet.rs +++ b/src/altair/presets/mainnet.rs @@ -1,5 +1,3 @@ -use crate::altair; -use crate::altair::presets::Preset; pub use crate::phase0::mainnet::{ AggregateAndProof, Attestation, AttesterSlashing, HistoricalBatch, IndexedAttestation, PendingAttestation, SignedAggregateAndProof, EPOCHS_PER_HISTORICAL_VECTOR, @@ -7,7 +5,7 @@ pub use crate::phase0::mainnet::{ MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, }; -use crate::primitives::Epoch; +use crate::{altair, altair::presets::Preset, primitives::Epoch}; pub use altair::*; diff --git a/src/altair/presets/minimal.rs b/src/altair/presets/minimal.rs index 6c8b0c31b..add53ec22 100644 --- a/src/altair/presets/minimal.rs +++ b/src/altair/presets/minimal.rs @@ -1,5 +1,3 @@ -use crate::altair; -use crate::altair::presets::Preset; pub use crate::phase0::minimal::{ AggregateAndProof, Attestation, AttesterSlashing, HistoricalBatch, IndexedAttestation, PendingAttestation, SignedAggregateAndProof, EPOCHS_PER_HISTORICAL_VECTOR, @@ -7,7 +5,7 @@ pub use crate::phase0::minimal::{ MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, }; -use crate::primitives::Epoch; +use crate::{altair, altair::presets::Preset, primitives::Epoch}; pub use altair::*; diff --git a/src/altair/state_transition/block_processing.rs b/src/altair/state_transition/block_processing.rs index 705b3f371..e4daad241 100644 --- a/src/altair/state_transition/block_processing.rs +++ b/src/altair/state_transition/block_processing.rs @@ -1,18 +1,21 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::altair as spec; -pub use crate::altair::block_processing::process_attestation; -pub use crate::altair::block_processing::process_block; -pub use crate::altair::block_processing::process_deposit; -pub use crate::altair::block_processing::process_sync_aggregate; -use crate::crypto::{hash, verify_signature}; -use crate::signing::compute_signing_root; +pub use crate::altair::block_processing::{ + process_attestation, process_block, process_deposit, process_sync_aggregate, +}; +use crate::{ + altair as spec, + crypto::{hash, verify_signature}, + signing::compute_signing_root, +}; -use crate::primitives::{Bytes32, DomainType, Gwei, ValidatorIndex, FAR_FUTURE_EPOCH}; -use crate::ssz::ByteVector; -use crate::state_transition::{ - invalid_header_error, invalid_operation_error, Context, InvalidAttesterSlashing, - InvalidBeaconBlockHeader, InvalidDeposit, InvalidOperation, InvalidProposerSlashing, - InvalidVoluntaryExit, Result, +use crate::{ + primitives::{Bytes32, DomainType, Gwei, ValidatorIndex, FAR_FUTURE_EPOCH}, + ssz::ByteVector, + state_transition::{ + invalid_header_error, invalid_operation_error, Context, InvalidAttesterSlashing, + InvalidBeaconBlockHeader, InvalidDeposit, InvalidOperation, InvalidProposerSlashing, + InvalidVoluntaryExit, Result, + }, }; use spec::{ compute_epoch_at_slot, get_beacon_proposer_index, get_current_epoch, get_domain, @@ -71,17 +74,14 @@ pub fn process_attester_slashing< Box::new(attestation_1.data.clone()), Box::new(attestation_2.data.clone()), ), - ))); + ))) } is_valid_indexed_attestation(state, attestation_1, context)?; is_valid_indexed_attestation(state, attestation_2, context)?; let indices_1: HashSet = HashSet::from_iter(attestation_1.attesting_indices.iter().cloned()); let indices_2 = HashSet::from_iter(attestation_2.attesting_indices.iter().cloned()); - let mut indices = indices_1 - .intersection(&indices_2) - .cloned() - .collect::>(); + let mut indices = indices_1.intersection(&indices_2).cloned().collect::>(); indices.sort_unstable(); let mut slashed_any = false; let current_epoch = get_current_epoch(state, context); @@ -136,38 +136,30 @@ pub fn process_block_header< context: &Context, ) -> Result<()> { if block.slot != state.slot { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::StateSlotMismatch { - state_slot: state.slot, - block_slot: block.slot, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::StateSlotMismatch { + state_slot: state.slot, + block_slot: block.slot, + })) } if block.slot <= state.latest_block_header.slot { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::OlderThanLatestBlockHeader { - block_slot: block.slot, - latest_block_header_slot: state.latest_block_header.slot, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::OlderThanLatestBlockHeader { + block_slot: block.slot, + latest_block_header_slot: state.latest_block_header.slot, + })) } let proposer_index = get_beacon_proposer_index(state, context)?; if block.proposer_index != proposer_index { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ProposerIndexMismatch { - block_proposer_index: block.proposer_index, - proposer_index, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ProposerIndexMismatch { + block_proposer_index: block.proposer_index, + proposer_index, + })) } let expected_parent_root = state.latest_block_header.hash_tree_root()?; if block.parent_root != expected_parent_root { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ParentBlockRootMismatch { - expected: expected_parent_root, - provided: block.parent_root, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ParentBlockRootMismatch { + expected: expected_parent_root, + provided: block.parent_root, + })) } state.latest_block_header = BeaconBlockHeader { slot: block.slot, @@ -178,9 +170,7 @@ pub fn process_block_header< }; let proposer = &state.validators[block.proposer_index]; if proposer.slashed { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ProposerSlashed(proposer_index), - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ProposerSlashed(proposer_index))) } Ok(()) } @@ -221,11 +211,8 @@ pub fn process_eth1_data< context: &Context, ) { state.eth1_data_votes.push(body.eth1_data.clone()); - let votes_count = state - .eth1_data_votes - .iter() - .filter(|&vote| *vote == body.eth1_data) - .count() as u64; + let votes_count = + state.eth1_data_votes.iter().filter(|&vote| *vote == body.eth1_data).count() as u64; if votes_count * 2 > context.epochs_per_eth1_voting_period * context.slots_per_epoch { state.eth1_data = body.eth1_data.clone(); } @@ -276,7 +263,7 @@ pub fn process_operations< expected: expected_deposit_count, count: body.deposits.len(), }, - ))); + ))) } body.proposer_slashings .iter_mut() @@ -284,12 +271,8 @@ pub fn process_operations< body.attester_slashings .iter_mut() .try_for_each(|op| process_attester_slashing(state, op, context))?; - body.attestations - .iter() - .try_for_each(|op| process_attestation(state, op, context))?; - body.deposits - .iter_mut() - .try_for_each(|op| process_deposit(state, op, context))?; + body.attestations.iter().try_for_each(|op| process_attestation(state, op, context))?; + body.deposits.iter_mut().try_for_each(|op| process_deposit(state, op, context))?; body.voluntary_exits .iter_mut() .try_for_each(|op| process_voluntary_exit(state, op, context))?; @@ -323,7 +306,7 @@ pub fn process_proposer_slashing< if header_1.slot != header_2.slot { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::SlotMismatch(header_1.slot, header_2.slot), - ))); + ))) } if header_1.proposer_index != header_2.proposer_index { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( @@ -331,12 +314,12 @@ pub fn process_proposer_slashing< header_1.proposer_index, header_2.proposer_index, ), - ))); + ))) } if header_1 == header_2 { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::HeadersAreEqual(header_1.clone()), - ))); + ))) } let proposer_index = header_1.proposer_index; let proposer = state.validators.get(proposer_index).ok_or_else(|| { @@ -347,20 +330,19 @@ pub fn process_proposer_slashing< if !is_slashable_validator(proposer, get_current_epoch(state, context)) { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::ProposerIsNotSlashable(header_1.proposer_index), - ))); + ))) } let epoch = compute_epoch_at_slot(header_1.slot, context); let domain = get_domain(state, DomainType::BeaconProposer, Some(epoch), context)?; - for signed_header in [ - &mut proposer_slashing.signed_header_1, - &mut proposer_slashing.signed_header_2, - ] { + for signed_header in + [&mut proposer_slashing.signed_header_1, &mut proposer_slashing.signed_header_2] + { let signing_root = compute_signing_root(&mut signed_header.message, domain)?; let public_key = &proposer.public_key; if verify_signature(public_key, signing_root.as_ref(), &signed_header.signature).is_err() { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::InvalidSignature(signed_header.signature.clone()), - ))); + ))) } } slash_validator(state, proposer_index, None, context) @@ -406,21 +388,10 @@ pub fn process_randao< let proposer = &state.validators[proposer_index]; let domain = get_domain(state, DomainType::Randao, Some(epoch), context)?; let signing_root = compute_signing_root(&mut epoch, domain)?; - if verify_signature( - &proposer.public_key, - signing_root.as_ref(), - &body.randao_reveal, - ) - .is_err() - { - return Err(invalid_operation_error(InvalidOperation::Randao( - body.randao_reveal.clone(), - ))); + if verify_signature(&proposer.public_key, signing_root.as_ref(), &body.randao_reveal).is_err() { + return Err(invalid_operation_error(InvalidOperation::Randao(body.randao_reveal.clone()))) } - let mix = xor( - get_randao_mix(state, epoch), - &hash(body.randao_reveal.as_ref()), - ); + let mix = xor(get_randao_mix(state, epoch), &hash(body.randao_reveal.as_ref())); let mix_index = epoch % context.epochs_per_historical_vector; state.randao_mixes[mix_index as usize] = mix; Ok(()) @@ -449,19 +420,16 @@ pub fn process_voluntary_exit< context: &Context, ) -> Result<()> { let voluntary_exit = &mut signed_voluntary_exit.message; - let validator = state - .validators - .get(voluntary_exit.validator_index) - .ok_or_else(|| { - invalid_operation_error(InvalidOperation::VoluntaryExit( - InvalidVoluntaryExit::InvalidIndex(voluntary_exit.validator_index), - )) - })?; + let validator = state.validators.get(voluntary_exit.validator_index).ok_or_else(|| { + invalid_operation_error(InvalidOperation::VoluntaryExit( + InvalidVoluntaryExit::InvalidIndex(voluntary_exit.validator_index), + )) + })?; let current_epoch = get_current_epoch(state, context); if !is_active_validator(validator, current_epoch) { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( InvalidVoluntaryExit::InactiveValidator(current_epoch), - ))); + ))) } if validator.exit_epoch != FAR_FUTURE_EPOCH { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( @@ -469,15 +437,12 @@ pub fn process_voluntary_exit< index: voluntary_exit.validator_index, epoch: validator.exit_epoch, }, - ))); + ))) } if current_epoch < voluntary_exit.epoch { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( - InvalidVoluntaryExit::EarlyExit { - current_epoch, - exit_epoch: voluntary_exit.epoch, - }, - ))); + InvalidVoluntaryExit::EarlyExit { current_epoch, exit_epoch: voluntary_exit.epoch }, + ))) } let minimum_time_active = validator.activation_eligibility_epoch + context.shard_committee_period; @@ -487,35 +452,22 @@ pub fn process_voluntary_exit< current_epoch, minimum_time_active, }, - ))); + ))) } - let domain = get_domain( - state, - DomainType::VoluntaryExit, - Some(voluntary_exit.epoch), - context, - )?; + let domain = get_domain(state, DomainType::VoluntaryExit, Some(voluntary_exit.epoch), context)?; let signing_root = compute_signing_root(voluntary_exit, domain)?; let public_key = &validator.public_key; - if verify_signature( - public_key, - signing_root.as_ref(), - &signed_voluntary_exit.signature, - ) - .is_err() + if verify_signature(public_key, signing_root.as_ref(), &signed_voluntary_exit.signature) + .is_err() { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( InvalidVoluntaryExit::InvalidSignature(signed_voluntary_exit.signature.clone()), - ))); + ))) } initiate_validator_exit(state, voluntary_exit.validator_index, context); Ok(()) } pub fn xor(a: &Bytes32, b: &Bytes32) -> Bytes32 { - let inner = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a ^ b) - .collect::>(); + let inner = a.iter().zip(b.iter()).map(|(a, b)| a ^ b).collect::>(); ByteVector::<32>::try_from(inner.as_ref()).unwrap() } diff --git a/src/altair/state_transition/epoch_processing.rs b/src/altair/state_transition/epoch_processing.rs index 0b4e1b748..b0060354a 100644 --- a/src/altair/state_transition/epoch_processing.rs +++ b/src/altair/state_transition/epoch_processing.rs @@ -1,15 +1,14 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::altair as spec; -pub use crate::altair::epoch_processing::get_base_reward; -pub use crate::altair::epoch_processing::process_epoch; -pub use crate::altair::epoch_processing::process_inactivity_updates; -pub use crate::altair::epoch_processing::process_justification_and_finalization; -pub use crate::altair::epoch_processing::process_participation_flag_updates; -pub use crate::altair::epoch_processing::process_rewards_and_penalties; -pub use crate::altair::epoch_processing::process_slashings; -pub use crate::altair::epoch_processing::process_sync_committee_updates; -use crate::primitives::{Epoch, Gwei, ValidatorIndex}; -use crate::state_transition::{Context, Result}; +pub use crate::altair::epoch_processing::{ + get_base_reward, process_epoch, process_inactivity_updates, + process_justification_and_finalization, process_participation_flag_updates, + process_rewards_and_penalties, process_slashings, process_sync_committee_updates, +}; +use crate::{ + altair as spec, + primitives::{Epoch, Gwei, ValidatorIndex}, + state_transition::{Context, Result}, +}; use ssz_rs::prelude::*; @@ -120,8 +119,8 @@ pub fn process_effective_balance_updates< for i in 0..state.validators.len() { let validator = &mut state.validators[i]; let balance = state.balances[i]; - if balance + downward_threshold < validator.effective_balance - || validator.effective_balance + upward_threshold < balance + if balance + downward_threshold < validator.effective_balance || + validator.effective_balance + upward_threshold < balance { validator.effective_balance = Gwei::min( balance - balance % context.effective_balance_increment, @@ -186,9 +185,7 @@ pub fn process_historical_roots_update< block_summary_root: state.block_roots.hash_tree_root()?, state_summary_root: state.state_roots.hash_tree_root()?, }; - state - .historical_roots - .push(historical_batch.hash_tree_root()?) + state.historical_roots.push(historical_batch.hash_tree_root()?) } Ok(()) } @@ -247,34 +244,32 @@ pub fn process_registry_updates< if is_eligible_for_activation_queue(validator, context) { validator.activation_eligibility_epoch = current_epoch + 1; } - if is_active_validator(validator, current_epoch) - && validator.effective_balance <= context.ejection_balance + if is_active_validator(validator, current_epoch) && + validator.effective_balance <= context.ejection_balance { initiate_validator_exit(state, i, context); } } - let mut activation_queue = state - .validators - .iter() - .enumerate() - .filter_map(|(index, validator)| { - if is_eligible_for_activation(state, validator) { - Some(index) - } else { - None - } - }) - .collect::>(); + let mut activation_queue = + state + .validators + .iter() + .enumerate() + .filter_map(|(index, validator)| { + if is_eligible_for_activation(state, validator) { + Some(index) + } else { + None + } + }) + .collect::>(); activation_queue.sort_by(|&i, &j| { let a = &state.validators[i]; let b = &state.validators[j]; (a.activation_eligibility_epoch, i).cmp(&(b.activation_eligibility_epoch, j)) }); let activation_exit_epoch = compute_activation_exit_epoch(current_epoch, context); - for i in activation_queue - .into_iter() - .take(get_validator_churn_limit(state, context)) - { + for i in activation_queue.into_iter().take(get_validator_churn_limit(state, context)) { let validator = &mut state.validators[i]; validator.activation_epoch = activation_exit_epoch; } @@ -335,9 +330,7 @@ pub fn weigh_justification_and_finalization< let old_previous_justified_checkpoint = state.previous_justified_checkpoint.clone(); let old_current_justified_checkpoint = state.current_justified_checkpoint.clone(); state.previous_justified_checkpoint = state.current_justified_checkpoint.clone(); - state - .justification_bits - .copy_within(..JUSTIFICATION_BITS_LENGTH - 1, 1); + state.justification_bits.copy_within(..JUSTIFICATION_BITS_LENGTH - 1, 1); state.justification_bits.set(0, false); if previous_epoch_target_balance * 3 >= total_active_balance * 2 { state.current_justified_checkpoint = Checkpoint { diff --git a/src/altair/state_transition/helpers.rs b/src/altair/state_transition/helpers.rs index ec5f1884e..487d1ec2e 100644 --- a/src/altair/state_transition/helpers.rs +++ b/src/altair/state_transition/helpers.rs @@ -1,32 +1,29 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::altair as spec; -pub use crate::altair::helpers::add_flag; -pub use crate::altair::helpers::get_attestation_participation_flag_indices; -pub use crate::altair::helpers::get_base_reward_per_increment; -pub use crate::altair::helpers::get_flag_index_deltas; -pub use crate::altair::helpers::get_inactivity_penalty_deltas; -pub use crate::altair::helpers::get_next_sync_committee; -pub use crate::altair::helpers::get_next_sync_committee_indices; -pub use crate::altair::helpers::get_unslashed_participating_indices; -pub use crate::altair::helpers::has_flag; -pub use crate::altair::helpers::slash_validator; -use crate::crypto::{fast_aggregate_verify, hash, verify_signature}; -use crate::primitives::{ - Bytes32, CommitteeIndex, Domain, DomainType, Epoch, ForkDigest, Gwei, Root, Slot, - ValidatorIndex, Version, FAR_FUTURE_EPOCH, GENESIS_EPOCH, +pub use crate::altair::helpers::{ + add_flag, get_attestation_participation_flag_indices, get_base_reward_per_increment, + get_flag_index_deltas, get_inactivity_penalty_deltas, get_next_sync_committee, + get_next_sync_committee_indices, get_unslashed_participating_indices, has_flag, + slash_validator, }; -use crate::signing::compute_signing_root; -use crate::state_transition::{ - invalid_operation_error, Context, Error, InvalidAttestation, InvalidIndexedAttestation, - InvalidOperation, Result, +use crate::{ + altair as spec, + crypto::{fast_aggregate_verify, hash, verify_signature}, + primitives::{ + Bytes32, CommitteeIndex, Domain, DomainType, Epoch, ForkDigest, Gwei, Root, Slot, + ValidatorIndex, Version, FAR_FUTURE_EPOCH, GENESIS_EPOCH, + }, + signing::compute_signing_root, + state_transition::{ + invalid_operation_error, Context, Error, InvalidAttestation, InvalidIndexedAttestation, + InvalidOperation, Result, + }, }; use spec::{ Attestation, AttestationData, BeaconState, ForkData, IndexedAttestation, SignedBeaconBlock, Validator, }; use ssz_rs::prelude::*; -use std::cmp; -use std::collections::HashSet; +use std::{cmp, collections::HashSet}; pub fn compute_activation_exit_epoch(epoch: Epoch, context: &Context) -> Epoch { epoch + 1 + context.max_seed_lookahead } @@ -67,12 +64,9 @@ pub fn compute_fork_data_root( current_version: Version, genesis_validators_root: Root, ) -> Result { - ForkData { - current_version, - genesis_validators_root, - } - .hash_tree_root() - .map_err(Error::Merkleization) + ForkData { current_version, genesis_validators_root } + .hash_tree_root() + .map_err(Error::Merkleization) } pub fn compute_fork_digest( current_version: Version, @@ -107,7 +101,7 @@ pub fn compute_proposer_index< context: &Context, ) -> Result { if indices.is_empty() { - return Err(Error::CollectionCannotBeEmpty); + return Err(Error::CollectionCannotBeEmpty) } let max_byte = u8::MAX as u64; let mut i = 0; @@ -122,7 +116,7 @@ pub fn compute_proposer_index< let random_byte = hash(hash_input).as_ref()[i % 32] as u64; let effective_balance = state.validators[candidate_index].effective_balance; if effective_balance * max_byte >= context.max_effective_balance * random_byte { - return Ok(candidate_index); + return Ok(candidate_index) } i += 1; } @@ -134,10 +128,7 @@ pub fn compute_shuffled_index( context: &Context, ) -> Result { if index >= index_count { - return Err(Error::InvalidShufflingIndex { - index, - total: index_count, - }); + return Err(Error::InvalidShufflingIndex { index, total: index_count }) } let mut pivot_input = [0u8; 33]; pivot_input[..32].copy_from_slice(seed.as_ref()); @@ -248,11 +239,8 @@ pub fn get_attesting_indices< let committee = get_beacon_committee(state, data.slot, data.index, context)?; if bits.len() != committee.len() { return Err(invalid_operation_error(InvalidOperation::Attestation( - InvalidAttestation::Bitfield { - expected_length: committee.len(), - length: bits.len(), - }, - ))); + InvalidAttestation::Bitfield { expected_length: committee.len(), length: bits.len() }, + ))) } let mut indices = HashSet::with_capacity(bits.capacity()); for (i, validator_index) in committee.iter().enumerate() { @@ -378,7 +366,7 @@ pub fn get_block_root_at_slot< requested: slot, lower_bound: state.slot - 1, upper_bound: state.slot + SLOTS_PER_HISTORICAL_ROOT as Slot, - }); + }) } Ok(&state.block_roots[slot as usize % SLOTS_PER_HISTORICAL_ROOT]) } @@ -409,9 +397,9 @@ pub fn get_committee_count_per_slot< 1, u64::min( context.max_committees_per_slot, - get_active_validator_indices(state, epoch).len() as u64 - / context.slots_per_epoch - / context.target_committee_size, + get_active_validator_indices(state, epoch).len() as u64 / + context.slots_per_epoch / + context.target_committee_size, ), ) as usize } @@ -469,12 +457,7 @@ pub fn get_domain< } else { state.fork.current_version }; - compute_domain( - domain_type, - Some(fork_version), - Some(state.genesis_validators_root), - context, - ) + compute_domain(domain_type, Some(fork_version), Some(state.genesis_validators_root), context) } pub fn get_eligible_validator_indices< 'a, @@ -500,19 +483,15 @@ pub fn get_eligible_validator_indices< context: &Context, ) -> impl Iterator + 'a { let previous_epoch = get_previous_epoch(state, context); - state - .validators - .iter() - .enumerate() - .filter_map(move |(i, validator)| { - if is_active_validator(validator, previous_epoch) - || (validator.slashed && previous_epoch + 1 < validator.withdrawable_epoch) - { - Some(i) - } else { - None - } - }) + state.validators.iter().enumerate().filter_map(move |(i, validator)| { + if is_active_validator(validator, previous_epoch) || + (validator.slashed && previous_epoch + 1 < validator.withdrawable_epoch) + { + Some(i) + } else { + None + } + }) } pub fn get_indexed_attestation< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -685,9 +664,7 @@ pub fn get_total_balance< ) -> Result { let total_balance = indices .iter() - .try_fold(Gwei::default(), |acc, i| { - acc.checked_add(state.validators[*i].effective_balance) - }) + .try_fold(Gwei::default(), |acc, i| acc.checked_add(state.validators[*i].effective_balance)) .ok_or(Error::Overflow)?; Ok(u64::max(total_balance, context.effective_balance_increment)) } @@ -769,7 +746,7 @@ pub fn initiate_validator_exit< context: &Context, ) { if state.validators[index].exit_epoch != FAR_FUTURE_EPOCH { - return; + return } let mut exit_epochs: Vec = state .validators @@ -777,16 +754,10 @@ pub fn initiate_validator_exit< .filter(|v| v.exit_epoch != FAR_FUTURE_EPOCH) .map(|v| v.exit_epoch) .collect(); - exit_epochs.push(compute_activation_exit_epoch( - get_current_epoch(state, context), - context, - )); + exit_epochs.push(compute_activation_exit_epoch(get_current_epoch(state, context), context)); let mut exit_queue_epoch = *exit_epochs.iter().max().unwrap(); - let exit_queue_churn = state - .validators - .iter() - .filter(|v| v.exit_epoch == exit_queue_epoch) - .count(); + let exit_queue_churn = + state.validators.iter().filter(|v| v.exit_epoch == exit_queue_epoch).count(); if exit_queue_churn >= get_validator_churn_limit(state, context) { exit_queue_epoch += 1; } @@ -819,12 +790,12 @@ pub fn is_eligible_for_activation< >, validator: &Validator, ) -> bool { - validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch - && validator.activation_epoch == FAR_FUTURE_EPOCH + validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch && + validator.activation_epoch == FAR_FUTURE_EPOCH } pub fn is_eligible_for_activation_queue(validator: &Validator, context: &Context) -> bool { - validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH - && validator.effective_balance == context.max_effective_balance + validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH && + validator.effective_balance == context.max_effective_balance } pub fn is_slashable_attestation_data(data_1: &AttestationData, data_2: &AttestationData) -> bool { let double_vote = data_1 != data_2 && data_1.target.epoch == data_2.target.epoch; @@ -833,9 +804,9 @@ pub fn is_slashable_attestation_data(data_1: &AttestationData, data_2: &Attestat double_vote || surround_vote } pub fn is_slashable_validator(validator: &Validator, epoch: Epoch) -> bool { - !validator.slashed - && validator.activation_epoch <= epoch - && epoch < validator.withdrawable_epoch + !validator.slashed && + validator.activation_epoch <= epoch && + epoch < validator.withdrawable_epoch } pub fn is_valid_indexed_attestation< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -862,9 +833,9 @@ pub fn is_valid_indexed_attestation< ) -> Result<()> { let attesting_indices = &indexed_attestation.attesting_indices; if attesting_indices.is_empty() { - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation(InvalidIndexedAttestation::AttestingIndicesEmpty), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::AttestingIndicesEmpty, + ))) } let is_sorted = attesting_indices .windows(2) @@ -875,11 +846,9 @@ pub fn is_valid_indexed_attestation< }) .all(|x| x); if !is_sorted { - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation( - InvalidIndexedAttestation::AttestingIndicesNotSorted, - ), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::AttestingIndicesNotSorted, + ))) } let indices: HashSet = HashSet::from_iter(attesting_indices.iter().cloned()); if indices.len() != indexed_attestation.attesting_indices.len() { @@ -892,23 +861,17 @@ pub fn is_valid_indexed_attestation< seen.insert(i); } } - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation(InvalidIndexedAttestation::DuplicateIndices( - duplicates, - )), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::DuplicateIndices(duplicates), + ))) } let mut public_keys = vec![]; for index in indices { - let public_key = state - .validators - .get(index) - .map(|v| &v.public_key) - .ok_or_else(|| { - invalid_operation_error(InvalidOperation::IndexedAttestation( - InvalidIndexedAttestation::InvalidIndex(index), - )) - })?; + let public_key = state.validators.get(index).map(|v| &v.public_key).ok_or_else(|| { + invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::InvalidIndex(index), + )) + })?; public_keys.push(public_key); } let domain = get_domain( @@ -918,12 +881,8 @@ pub fn is_valid_indexed_attestation< context, )?; let signing_root = compute_signing_root(&mut indexed_attestation.data, domain)?; - fast_aggregate_verify( - &public_keys, - signing_root.as_ref(), - &indexed_attestation.signature, - ) - .map_err(Into::into) + fast_aggregate_verify(&public_keys, signing_root.as_ref(), &indexed_attestation.signature) + .map_err(Into::into) } pub fn verify_block_signature< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -965,10 +924,7 @@ pub fn verify_block_signature< let proposer = state .validators .get(proposer_index) - .ok_or(Error::OutOfBounds { - requested: proposer_index, - bound: state.validators.len(), - })?; + .ok_or(Error::OutOfBounds { requested: proposer_index, bound: state.validators.len() })?; let domain = get_domain(state, DomainType::BeaconProposer, None, context)?; let signing_root = compute_signing_root(&mut signed_block.message, domain)?; let public_key = &proposer.public_key; diff --git a/src/altair/state_transition/mod.rs b/src/altair/state_transition/mod.rs index e538ca0fa..14895cc05 100644 --- a/src/altair/state_transition/mod.rs +++ b/src/altair/state_transition/mod.rs @@ -3,8 +3,10 @@ pub mod block_processing; pub mod epoch_processing; pub mod helpers; pub mod slot_processing; -use crate::altair as spec; -use crate::state_transition::{Context, Error, Result, Validation}; +use crate::{ + altair as spec, + state_transition::{Context, Error, Result, Validation}, +}; use spec::{process_block, process_slots, verify_block_signature, BeaconState, SignedBeaconBlock}; use ssz_rs::prelude::*; pub fn state_transition< diff --git a/src/altair/state_transition/slot_processing.rs b/src/altair/state_transition/slot_processing.rs index 8ae0d9b7a..29ca583d9 100644 --- a/src/altair/state_transition/slot_processing.rs +++ b/src/altair/state_transition/slot_processing.rs @@ -1,7 +1,9 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::altair as spec; -use crate::primitives::{Root, Slot}; -use crate::state_transition::{Context, Error, Result}; +use crate::{ + altair as spec, + primitives::{Root, Slot}, + state_transition::{Context, Error, Result}, +}; use spec::{process_epoch, BeaconState}; use ssz_rs::prelude::*; pub fn process_slot< @@ -61,10 +63,7 @@ pub fn process_slots< context: &Context, ) -> Result<()> { if state.slot >= slot { - return Err(Error::TransitionToPreviousSlot { - requested: slot, - current: state.slot, - }); + return Err(Error::TransitionToPreviousSlot { requested: slot, current: state.slot }) } while state.slot < slot { process_slot(state, context)?; diff --git a/src/bellatrix/beacon_block.rs b/src/bellatrix/beacon_block.rs index 0258699b3..aced08513 100644 --- a/src/bellatrix/beacon_block.rs +++ b/src/bellatrix/beacon_block.rs @@ -1,9 +1,11 @@ -use crate::altair::SyncAggregate; -use crate::bellatrix::ExecutionPayload; -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + altair::SyncAggregate, + bellatrix::ExecutionPayload, + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize, PartialEq, Eq)] diff --git a/src/bellatrix/beacon_state.rs b/src/bellatrix/beacon_state.rs index d1f6c7a2b..26dd39688 100644 --- a/src/bellatrix/beacon_state.rs +++ b/src/bellatrix/beacon_state.rs @@ -1,9 +1,9 @@ -use crate::altair::SyncCommittee; -use crate::bellatrix::ExecutionPayloadHeader; -use crate::phase0::{ - BeaconBlockHeader, Checkpoint, Eth1Data, Fork, Validator, JUSTIFICATION_BITS_LENGTH, +use crate::{ + altair::SyncCommittee, + bellatrix::ExecutionPayloadHeader, + phase0::{BeaconBlockHeader, Checkpoint, Eth1Data, Fork, Validator, JUSTIFICATION_BITS_LENGTH}, + primitives::{Bytes32, Gwei, ParticipationFlags, Root, Slot}, }; -use crate::primitives::{Bytes32, Gwei, ParticipationFlags, Root, Slot}; use ssz_rs::prelude::*; #[derive(Default, Debug, SimpleSerialize, Clone, PartialEq, Eq)] diff --git a/src/bellatrix/blinded_beacon_block.rs b/src/bellatrix/blinded_beacon_block.rs index 9d3767690..cf0e5bd82 100644 --- a/src/bellatrix/blinded_beacon_block.rs +++ b/src/bellatrix/blinded_beacon_block.rs @@ -1,9 +1,11 @@ -use crate::altair::SyncAggregate; -use crate::bellatrix::ExecutionPayloadHeader; -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + altair::SyncAggregate, + bellatrix::ExecutionPayloadHeader, + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize)] diff --git a/src/bellatrix/block_processing.rs b/src/bellatrix/block_processing.rs index c98fe9f7d..aa2210044 100644 --- a/src/bellatrix/block_processing.rs +++ b/src/bellatrix/block_processing.rs @@ -61,7 +61,7 @@ pub fn process_execution_payload< expected: state.latest_execution_payload_header.block_hash.clone(), } .into(), - )); + )) } let current_epoch = get_current_epoch(state, context); @@ -73,7 +73,7 @@ pub fn process_execution_payload< expected: randao_mix.clone(), } .into(), - )); + )) } let timestamp = compute_timestamp_at_slot(state, state.slot, context)?; @@ -84,7 +84,7 @@ pub fn process_execution_payload< expected: timestamp, } .into(), - )); + )) } execution_engine.notify_new_payload(payload)?; diff --git a/src/bellatrix/epoch_processing.rs b/src/bellatrix/epoch_processing.rs index 63d3a91f7..381082dd7 100644 --- a/src/bellatrix/epoch_processing.rs +++ b/src/bellatrix/epoch_processing.rs @@ -1,7 +1,9 @@ use crate::bellatrix as spec; -use crate::primitives::Gwei; -use crate::state_transition::{Context, Result}; +use crate::{ + primitives::Gwei, + state_transition::{Context, Result}, +}; use spec::{ decrease_balance, get_current_epoch, get_total_active_balance, process_effective_balance_updates, process_eth1_data_reset, process_historical_roots_update, @@ -49,8 +51,8 @@ pub fn process_slashings< ); for i in 0..state.validators.len() { let validator = &state.validators[i]; - if validator.slashed - && (epoch + context.epochs_per_slashings_vector / 2) == validator.withdrawable_epoch + if validator.slashed && + (epoch + context.epochs_per_slashings_vector / 2) == validator.withdrawable_epoch { let increment = context.effective_balance_increment; let penalty_numerator = diff --git a/src/bellatrix/execution.rs b/src/bellatrix/execution.rs index 50d0e2533..1c914041f 100644 --- a/src/bellatrix/execution.rs +++ b/src/bellatrix/execution.rs @@ -1,6 +1,8 @@ -use crate::primitives::{Bytes32, ExecutionAddress, Hash32, Root, U256}; -use crate::ssz::{ByteList, ByteVector}; -use crate::state_transition::{self, Error}; +use crate::{ + primitives::{Bytes32, ExecutionAddress, Hash32, Root, U256}, + ssz::{ByteList, ByteVector}, + state_transition::{self, Error}, +}; use ssz_rs::prelude::*; pub type Transaction = ByteList; diff --git a/src/bellatrix/fork.rs b/src/bellatrix/fork.rs index 461cfa0e1..efb4e9d35 100644 --- a/src/bellatrix/fork.rs +++ b/src/bellatrix/fork.rs @@ -1,6 +1,8 @@ -use crate::altair; -use crate::bellatrix::{BeaconState, Fork}; -use crate::state_transition::Context; +use crate::{ + altair, + bellatrix::{BeaconState, Fork}, + state_transition::Context, +}; use ssz_rs::prelude::*; pub fn upgrade_to_bellatrix< diff --git a/src/bellatrix/genesis.rs b/src/bellatrix/genesis.rs index 6ded0e639..017dbca09 100644 --- a/src/bellatrix/genesis.rs +++ b/src/bellatrix/genesis.rs @@ -1,8 +1,10 @@ use crate::bellatrix as spec; -use crate::phase0::DEPOSIT_DATA_LIST_BOUND; -use crate::primitives::{Gwei, Hash32, GENESIS_EPOCH}; -use crate::state_transition::{Context, Result}; +use crate::{ + phase0::DEPOSIT_DATA_LIST_BOUND, + primitives::{Gwei, Hash32, GENESIS_EPOCH}, + state_transition::{Context, Result}, +}; use spec::{ get_active_validator_indices, get_next_sync_committee, process_deposit, BeaconBlock, BeaconBlockBody, BeaconBlockHeader, BeaconState, Deposit, DepositData, Eth1Data, @@ -81,10 +83,7 @@ pub fn initialize_beacon_state_from_eth1< MAX_TRANSACTIONS_PER_PAYLOAD, >::default(); let body_root = latest_block_body.hash_tree_root()?; - let latest_block_header = BeaconBlockHeader { - body_root, - ..Default::default() - }; + let latest_block_header = BeaconBlockHeader { body_root, ..Default::default() }; let randao_mixes = Vector::try_from( std::iter::repeat(eth1_block_hash) .take(context.epochs_per_historical_vector as usize) @@ -163,13 +162,13 @@ pub fn is_valid_genesis_state< context: &Context, ) -> bool { if state.genesis_time < context.min_genesis_time { - return false; + return false } - if get_active_validator_indices(state, GENESIS_EPOCH).len() - < context.min_genesis_active_validator_count + if get_active_validator_indices(state, GENESIS_EPOCH).len() < + context.min_genesis_active_validator_count { - return false; + return false } true @@ -223,8 +222,5 @@ pub fn get_genesis_block< MAX_TRANSACTIONS_PER_PAYLOAD, >, > { - Ok(BeaconBlock { - state_root: genesis_state.hash_tree_root()?, - ..Default::default() - }) + Ok(BeaconBlock { state_root: genesis_state.hash_tree_root()?, ..Default::default() }) } diff --git a/src/bellatrix/helpers.rs b/src/bellatrix/helpers.rs index 009e533a7..f09a3f622 100644 --- a/src/bellatrix/helpers.rs +++ b/src/bellatrix/helpers.rs @@ -1,7 +1,9 @@ use crate::bellatrix as spec; -use crate::primitives::{Gwei, Slot, ValidatorIndex, GENESIS_SLOT}; -use crate::state_transition::{Context, Error, Result}; +use crate::{ + primitives::{Gwei, Slot, ValidatorIndex, GENESIS_SLOT}, + state_transition::{Context, Error, Result}, +}; use spec::{ decrease_balance, get_beacon_proposer_index, get_current_epoch, get_eligible_validator_indices, get_previous_epoch, get_unslashed_participating_indices, increase_balance, @@ -105,8 +107,8 @@ pub fn slash_validator< decrease_balance( state, slashed_index, - state.validators[slashed_index].effective_balance - / context.min_slashing_penalty_quotient_bellatrix, + state.validators[slashed_index].effective_balance / + context.min_slashing_penalty_quotient_bellatrix, ); let proposer_index = get_beacon_proposer_index(state, context)?; let whistleblower_index = whistleblower_index.unwrap_or(proposer_index); @@ -115,11 +117,7 @@ pub fn slash_validator< let proposer_reward_scaling_factor = PROPOSER_WEIGHT / WEIGHT_DENOMINATOR; let proposer_reward = whistleblower_reward * proposer_reward_scaling_factor; increase_balance(state, proposer_index, proposer_reward); - increase_balance( - state, - whistleblower_index, - whistleblower_reward - proposer_reward, - ); + increase_balance(state, whistleblower_index, whistleblower_reward - proposer_reward); Ok(()) } diff --git a/src/bellatrix/mod.rs b/src/bellatrix/mod.rs index 9f8628171..c8a448674 100644 --- a/src/bellatrix/mod.rs +++ b/src/bellatrix/mod.rs @@ -30,17 +30,19 @@ pub use genesis::*; pub use networking::*; pub use presets::Preset; -pub use crate::altair::{ - SyncAggregate, SyncAggregatorSelectionData, SyncCommittee, PARTICIPATION_FLAG_WEIGHTS, - PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, - TIMELY_TARGET_FLAG_INDEX, WEIGHT_DENOMINATOR, -}; -pub use crate::phase0::{ - Attestation, AttestationData, AttesterSlashing, BeaconBlockHeader, Checkpoint, Deposit, - DepositData, DepositMessage, Eth1Block, Eth1Data, Fork, ForkData, HistoricalSummary, - IndexedAttestation, ProposerSlashing, SignedBeaconBlockHeader, SignedVoluntaryExit, - SigningData, Validator, VoluntaryExit, BASE_REWARDS_PER_EPOCH, DEPOSIT_CONTRACT_TREE_DEPTH, - JUSTIFICATION_BITS_LENGTH, +pub use crate::{ + altair::{ + SyncAggregate, SyncAggregatorSelectionData, SyncCommittee, PARTICIPATION_FLAG_WEIGHTS, + PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, + TIMELY_TARGET_FLAG_INDEX, WEIGHT_DENOMINATOR, + }, + phase0::{ + Attestation, AttestationData, AttesterSlashing, BeaconBlockHeader, Checkpoint, Deposit, + DepositData, DepositMessage, Eth1Block, Eth1Data, Fork, ForkData, HistoricalSummary, + IndexedAttestation, ProposerSlashing, SignedBeaconBlockHeader, SignedVoluntaryExit, + SigningData, Validator, VoluntaryExit, BASE_REWARDS_PER_EPOCH, DEPOSIT_CONTRACT_TREE_DEPTH, + JUSTIFICATION_BITS_LENGTH, + }, }; pub mod mainnet { diff --git a/src/bellatrix/presets/mainnet.rs b/src/bellatrix/presets/mainnet.rs index 77220fdb2..0b7c1c44d 100644 --- a/src/bellatrix/presets/mainnet.rs +++ b/src/bellatrix/presets/mainnet.rs @@ -1,18 +1,18 @@ -pub use crate::altair::mainnet::SYNC_COMMITTEE_SIZE; -pub use crate::altair::mainnet::{ - AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, - IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, - SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, - SyncCommitteeMessage, -}; -use crate::bellatrix; -use crate::bellatrix::presets::Preset; -pub use crate::phase0::mainnet::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +pub use crate::{ + altair::mainnet::{ + AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, + IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, + SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, + SyncCommitteeMessage, SYNC_COMMITTEE_SIZE, + }, + phase0::mainnet::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, }; +use crate::{bellatrix, bellatrix::presets::Preset}; pub use bellatrix::*; diff --git a/src/bellatrix/presets/minimal.rs b/src/bellatrix/presets/minimal.rs index 753f8cf2f..bc3c390e7 100644 --- a/src/bellatrix/presets/minimal.rs +++ b/src/bellatrix/presets/minimal.rs @@ -1,18 +1,18 @@ -pub use crate::altair::minimal::SYNC_COMMITTEE_SIZE; -pub use crate::altair::minimal::{ - AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, - IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, - SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, - SyncCommitteeMessage, -}; -use crate::bellatrix; -use crate::bellatrix::presets::Preset; -pub use crate::phase0::minimal::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +pub use crate::{ + altair::minimal::{ + AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, + IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, + SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, + SyncCommitteeMessage, SYNC_COMMITTEE_SIZE, + }, + phase0::minimal::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, }; +use crate::{bellatrix, bellatrix::presets::Preset}; pub use bellatrix::*; diff --git a/src/bellatrix/state_transition/block_processing.rs b/src/bellatrix/state_transition/block_processing.rs index 6473bd349..fcd4c19b1 100644 --- a/src/bellatrix/state_transition/block_processing.rs +++ b/src/bellatrix/state_transition/block_processing.rs @@ -1,17 +1,19 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::bellatrix as spec; -pub use crate::bellatrix::block_processing::process_block; -pub use crate::bellatrix::block_processing::process_execution_payload; -use crate::crypto::{eth_fast_aggregate_verify, hash, verify_signature}; -use crate::primitives::{ - BlsPublicKey, Bytes32, DomainType, Gwei, ParticipationFlags, ValidatorIndex, FAR_FUTURE_EPOCH, -}; -use crate::signing::compute_signing_root; -use crate::ssz::ByteVector; -use crate::state_transition::{ - invalid_header_error, invalid_operation_error, Context, InvalidAttestation, - InvalidAttesterSlashing, InvalidBeaconBlockHeader, InvalidDeposit, InvalidOperation, - InvalidProposerSlashing, InvalidSyncAggregate, InvalidVoluntaryExit, Result, +pub use crate::bellatrix::block_processing::{process_block, process_execution_payload}; +use crate::{ + bellatrix as spec, + crypto::{eth_fast_aggregate_verify, hash, verify_signature}, + primitives::{ + BlsPublicKey, Bytes32, DomainType, Gwei, ParticipationFlags, ValidatorIndex, + FAR_FUTURE_EPOCH, + }, + signing::compute_signing_root, + ssz::ByteVector, + state_transition::{ + invalid_header_error, invalid_operation_error, Context, InvalidAttestation, + InvalidAttesterSlashing, InvalidBeaconBlockHeader, InvalidDeposit, InvalidOperation, + InvalidProposerSlashing, InvalidSyncAggregate, InvalidVoluntaryExit, Result, + }, }; use spec::{ add_flag, compute_domain, compute_epoch_at_slot, decrease_balance, @@ -27,8 +29,10 @@ use spec::{ PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, WEIGHT_DENOMINATOR, }; use ssz_rs::prelude::*; -use std::collections::{HashMap, HashSet}; -use std::iter::zip; +use std::{ + collections::{HashMap, HashSet}, + iter::zip, +}; pub fn get_validator_from_deposit(deposit: &Deposit, context: &Context) -> Validator { let amount = deposit.data.amount; let effective_balance = Gwei::min( @@ -88,7 +92,7 @@ pub fn process_attestation< target: data.target.epoch, current: current_epoch, }, - ))); + ))) } let attestation_epoch = compute_epoch_at_slot(data.slot, context); if data.target.epoch != attestation_epoch { @@ -98,7 +102,7 @@ pub fn process_attestation< epoch: attestation_epoch, target: data.target.epoch, }, - ))); + ))) } let attestation_has_delay = data.slot + context.min_attestation_inclusion_delay <= state.slot; let attestation_is_recent = state.slot <= data.slot + context.slots_per_epoch; @@ -111,16 +115,13 @@ pub fn process_attestation< lower_bound: data.slot + context.slots_per_epoch, upper_bound: data.slot + context.min_attestation_inclusion_delay, }, - ))); + ))) } let committee_count = get_committee_count_per_slot(state, data.target.epoch, context); if data.index >= committee_count { return Err(invalid_operation_error(InvalidOperation::Attestation( - InvalidAttestation::InvalidIndex { - index: data.index, - upper_bound: committee_count, - }, - ))); + InvalidAttestation::InvalidIndex { index: data.index, upper_bound: committee_count }, + ))) } let committee = get_beacon_committee(state, data.slot, data.index, context)?; if attestation.aggregation_bits.len() != committee.len() { @@ -129,7 +130,7 @@ pub fn process_attestation< expected_length: committee.len(), length: attestation.aggregation_bits.len(), }, - ))); + ))) } let inclusion_delay = state.slot - data.slot; let participation_flag_indices = @@ -145,15 +146,15 @@ pub fn process_attestation< for index in attesting_indices { for (flag_index, weight) in PARTICIPATION_FLAG_WEIGHTS.iter().enumerate() { if is_current { - if participation_flag_indices.contains(&flag_index) - && !has_flag(state.current_epoch_participation[index], flag_index) + if participation_flag_indices.contains(&flag_index) && + !has_flag(state.current_epoch_participation[index], flag_index) { state.current_epoch_participation[index] = add_flag(state.current_epoch_participation[index], flag_index); proposer_reward_numerator += get_base_reward(state, index, context)? * weight; } - } else if participation_flag_indices.contains(&flag_index) - && !has_flag(state.previous_epoch_participation[index], flag_index) + } else if participation_flag_indices.contains(&flag_index) && + !has_flag(state.previous_epoch_participation[index], flag_index) { state.previous_epoch_participation[index] = add_flag(state.previous_epoch_participation[index], flag_index); @@ -164,11 +165,7 @@ pub fn process_attestation< let proposer_reward_denominator = (WEIGHT_DENOMINATOR - PROPOSER_WEIGHT) * WEIGHT_DENOMINATOR / PROPOSER_WEIGHT; let proposer_reward = proposer_reward_numerator / proposer_reward_denominator; - increase_balance( - state, - get_beacon_proposer_index(state, context)?, - proposer_reward, - ); + increase_balance(state, get_beacon_proposer_index(state, context)?, proposer_reward); Ok(()) } pub fn process_attester_slashing< @@ -210,17 +207,14 @@ pub fn process_attester_slashing< Box::new(attestation_1.data.clone()), Box::new(attestation_2.data.clone()), ), - ))); + ))) } is_valid_indexed_attestation(state, attestation_1, context)?; is_valid_indexed_attestation(state, attestation_2, context)?; let indices_1: HashSet = HashSet::from_iter(attestation_1.attesting_indices.iter().cloned()); let indices_2 = HashSet::from_iter(attestation_2.attesting_indices.iter().cloned()); - let mut indices = indices_1 - .intersection(&indices_2) - .cloned() - .collect::>(); + let mut indices = indices_1.intersection(&indices_2).cloned().collect::>(); indices.sort_unstable(); let mut slashed_any = false; let current_epoch = get_current_epoch(state, context); @@ -287,38 +281,30 @@ pub fn process_block_header< context: &Context, ) -> Result<()> { if block.slot != state.slot { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::StateSlotMismatch { - state_slot: state.slot, - block_slot: block.slot, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::StateSlotMismatch { + state_slot: state.slot, + block_slot: block.slot, + })) } if block.slot <= state.latest_block_header.slot { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::OlderThanLatestBlockHeader { - block_slot: block.slot, - latest_block_header_slot: state.latest_block_header.slot, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::OlderThanLatestBlockHeader { + block_slot: block.slot, + latest_block_header_slot: state.latest_block_header.slot, + })) } let proposer_index = get_beacon_proposer_index(state, context)?; if block.proposer_index != proposer_index { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ProposerIndexMismatch { - block_proposer_index: block.proposer_index, - proposer_index, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ProposerIndexMismatch { + block_proposer_index: block.proposer_index, + proposer_index, + })) } let expected_parent_root = state.latest_block_header.hash_tree_root()?; if block.parent_root != expected_parent_root { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ParentBlockRootMismatch { - expected: expected_parent_root, - provided: block.parent_root, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ParentBlockRootMismatch { + expected: expected_parent_root, + provided: block.parent_root, + })) } state.latest_block_header = BeaconBlockHeader { slot: block.slot, @@ -329,9 +315,7 @@ pub fn process_block_header< }; let proposer = &state.validators[block.proposer_index]; if proposer.slashed { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ProposerSlashed(proposer_index), - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ProposerSlashed(proposer_index))) } Ok(()) } @@ -377,14 +361,8 @@ pub fn process_deposit< let root = &state.eth1_data.deposit_root; if !is_valid_merkle_branch(&leaf, branch.iter(), depth, index, root) { return Err(invalid_operation_error(InvalidOperation::Deposit( - InvalidDeposit::InvalidProof { - leaf, - branch, - depth, - index, - root: *root, - }, - ))); + InvalidDeposit::InvalidProof { leaf, branch, depth, index, root: *root }, + ))) } state.eth1_deposit_index += 1; let public_key = &deposit.data.public_key; @@ -400,25 +378,15 @@ pub fn process_deposit< let domain = compute_domain(DomainType::Deposit, None, None, context)?; let signing_root = compute_signing_root(&mut deposit_message, domain)?; if verify_signature(public_key, signing_root.as_ref(), &deposit.data.signature).is_err() { - return Ok(()); + return Ok(()) } - state - .validators - .push(get_validator_from_deposit(deposit, context)); + state.validators.push(get_validator_from_deposit(deposit, context)); state.balances.push(amount); - state - .previous_epoch_participation - .push(ParticipationFlags::default()); - state - .current_epoch_participation - .push(ParticipationFlags::default()); + state.previous_epoch_participation.push(ParticipationFlags::default()); + state.current_epoch_participation.push(ParticipationFlags::default()); state.inactivity_scores.push(0) } else { - let index = state - .validators - .iter() - .position(|v| &v.public_key == public_key) - .unwrap(); + let index = state.validators.iter().position(|v| &v.public_key == public_key).unwrap(); increase_balance(state, index, amount); } Ok(()) @@ -472,11 +440,8 @@ pub fn process_eth1_data< context: &Context, ) { state.eth1_data_votes.push(body.eth1_data.clone()); - let votes_count = state - .eth1_data_votes - .iter() - .filter(|&vote| *vote == body.eth1_data) - .count() as u64; + let votes_count = + state.eth1_data_votes.iter().filter(|&vote| *vote == body.eth1_data).count() as u64; if votes_count * 2 > context.epochs_per_eth1_voting_period * context.slots_per_epoch { state.eth1_data = body.eth1_data.clone(); } @@ -539,7 +504,7 @@ pub fn process_operations< expected: expected_deposit_count, count: body.deposits.len(), }, - ))); + ))) } body.proposer_slashings .iter_mut() @@ -547,12 +512,8 @@ pub fn process_operations< body.attester_slashings .iter_mut() .try_for_each(|op| process_attester_slashing(state, op, context))?; - body.attestations - .iter() - .try_for_each(|op| process_attestation(state, op, context))?; - body.deposits - .iter_mut() - .try_for_each(|op| process_deposit(state, op, context))?; + body.attestations.iter().try_for_each(|op| process_attestation(state, op, context))?; + body.deposits.iter_mut().try_for_each(|op| process_deposit(state, op, context))?; body.voluntary_exits .iter_mut() .try_for_each(|op| process_voluntary_exit(state, op, context))?; @@ -594,7 +555,7 @@ pub fn process_proposer_slashing< if header_1.slot != header_2.slot { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::SlotMismatch(header_1.slot, header_2.slot), - ))); + ))) } if header_1.proposer_index != header_2.proposer_index { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( @@ -602,12 +563,12 @@ pub fn process_proposer_slashing< header_1.proposer_index, header_2.proposer_index, ), - ))); + ))) } if header_1 == header_2 { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::HeadersAreEqual(header_1.clone()), - ))); + ))) } let proposer_index = header_1.proposer_index; let proposer = state.validators.get(proposer_index).ok_or_else(|| { @@ -618,20 +579,19 @@ pub fn process_proposer_slashing< if !is_slashable_validator(proposer, get_current_epoch(state, context)) { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::ProposerIsNotSlashable(header_1.proposer_index), - ))); + ))) } let epoch = compute_epoch_at_slot(header_1.slot, context); let domain = get_domain(state, DomainType::BeaconProposer, Some(epoch), context)?; - for signed_header in [ - &mut proposer_slashing.signed_header_1, - &mut proposer_slashing.signed_header_2, - ] { + for signed_header in + [&mut proposer_slashing.signed_header_1, &mut proposer_slashing.signed_header_2] + { let signing_root = compute_signing_root(&mut signed_header.message, domain)?; let public_key = &proposer.public_key; if verify_signature(public_key, signing_root.as_ref(), &signed_header.signature).is_err() { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::InvalidSignature(signed_header.signature.clone()), - ))); + ))) } } slash_validator(state, proposer_index, None, context) @@ -689,21 +649,10 @@ pub fn process_randao< let proposer = &state.validators[proposer_index]; let domain = get_domain(state, DomainType::Randao, Some(epoch), context)?; let signing_root = compute_signing_root(&mut epoch, domain)?; - if verify_signature( - &proposer.public_key, - signing_root.as_ref(), - &body.randao_reveal, - ) - .is_err() - { - return Err(invalid_operation_error(InvalidOperation::Randao( - body.randao_reveal.clone(), - ))); + if verify_signature(&proposer.public_key, signing_root.as_ref(), &body.randao_reveal).is_err() { + return Err(invalid_operation_error(InvalidOperation::Randao(body.randao_reveal.clone()))) } - let mix = xor( - get_randao_mix(state, epoch), - &hash(body.randao_reveal.as_ref()), - ); + let mix = xor(get_randao_mix(state, epoch), &hash(body.randao_reveal.as_ref())); let mix_index = epoch % context.epochs_per_historical_vector; state.randao_mixes[mix_index as usize] = mix; Ok(()) @@ -740,20 +689,10 @@ pub fn process_sync_aggregate< context: &Context, ) -> Result<()> { let committee_public_keys = &state.current_sync_committee.public_keys; - let participant_public_keys = zip( - committee_public_keys.iter(), - sync_aggregate.sync_committee_bits.iter(), - ) - .filter_map( - |(public_key, bit)| { - if *bit { - Some(public_key) - } else { - None - } - }, - ) - .collect::>(); + let participant_public_keys = + zip(committee_public_keys.iter(), sync_aggregate.sync_committee_bits.iter()) + .filter_map(|(public_key, bit)| if *bit { Some(public_key) } else { None }) + .collect::>(); let previous_slot = u64::max(state.slot, 1) - 1; let domain = get_domain( state, @@ -775,7 +714,7 @@ pub fn process_sync_aggregate< signature: sync_aggregate.sync_committee_signature.clone(), root: signing_root, }, - ))); + ))) } let total_active_increments = get_total_active_balance(state, context)? / context.effective_balance_increment; @@ -794,23 +733,15 @@ pub fn process_sync_aggregate< .collect::>(); let mut committee_indices: Vec = Vec::default(); for public_key in state.current_sync_committee.public_keys.iter() { - committee_indices.push( - *all_public_keys - .get(public_key) - .expect("validator public_key should exist"), - ); - } - for (participant_index, participation_bit) in zip( - committee_indices.iter(), - sync_aggregate.sync_committee_bits.iter(), - ) { + committee_indices + .push(*all_public_keys.get(public_key).expect("validator public_key should exist")); + } + for (participant_index, participation_bit) in + zip(committee_indices.iter(), sync_aggregate.sync_committee_bits.iter()) + { if *participation_bit { increase_balance(state, *participant_index, participant_reward); - increase_balance( - state, - get_beacon_proposer_index(state, context)?, - proposer_reward, - ); + increase_balance(state, get_beacon_proposer_index(state, context)?, proposer_reward); } else { decrease_balance(state, *participant_index, participant_reward); } @@ -849,19 +780,16 @@ pub fn process_voluntary_exit< context: &Context, ) -> Result<()> { let voluntary_exit = &mut signed_voluntary_exit.message; - let validator = state - .validators - .get(voluntary_exit.validator_index) - .ok_or_else(|| { - invalid_operation_error(InvalidOperation::VoluntaryExit( - InvalidVoluntaryExit::InvalidIndex(voluntary_exit.validator_index), - )) - })?; + let validator = state.validators.get(voluntary_exit.validator_index).ok_or_else(|| { + invalid_operation_error(InvalidOperation::VoluntaryExit( + InvalidVoluntaryExit::InvalidIndex(voluntary_exit.validator_index), + )) + })?; let current_epoch = get_current_epoch(state, context); if !is_active_validator(validator, current_epoch) { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( InvalidVoluntaryExit::InactiveValidator(current_epoch), - ))); + ))) } if validator.exit_epoch != FAR_FUTURE_EPOCH { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( @@ -869,15 +797,12 @@ pub fn process_voluntary_exit< index: voluntary_exit.validator_index, epoch: validator.exit_epoch, }, - ))); + ))) } if current_epoch < voluntary_exit.epoch { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( - InvalidVoluntaryExit::EarlyExit { - current_epoch, - exit_epoch: voluntary_exit.epoch, - }, - ))); + InvalidVoluntaryExit::EarlyExit { current_epoch, exit_epoch: voluntary_exit.epoch }, + ))) } let minimum_time_active = validator.activation_eligibility_epoch + context.shard_committee_period; @@ -887,35 +812,22 @@ pub fn process_voluntary_exit< current_epoch, minimum_time_active, }, - ))); + ))) } - let domain = get_domain( - state, - DomainType::VoluntaryExit, - Some(voluntary_exit.epoch), - context, - )?; + let domain = get_domain(state, DomainType::VoluntaryExit, Some(voluntary_exit.epoch), context)?; let signing_root = compute_signing_root(voluntary_exit, domain)?; let public_key = &validator.public_key; - if verify_signature( - public_key, - signing_root.as_ref(), - &signed_voluntary_exit.signature, - ) - .is_err() + if verify_signature(public_key, signing_root.as_ref(), &signed_voluntary_exit.signature) + .is_err() { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( InvalidVoluntaryExit::InvalidSignature(signed_voluntary_exit.signature.clone()), - ))); + ))) } initiate_validator_exit(state, voluntary_exit.validator_index, context); Ok(()) } pub fn xor(a: &Bytes32, b: &Bytes32) -> Bytes32 { - let inner = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a ^ b) - .collect::>(); + let inner = a.iter().zip(b.iter()).map(|(a, b)| a ^ b).collect::>(); ByteVector::<32>::try_from(inner.as_ref()).unwrap() } diff --git a/src/bellatrix/state_transition/epoch_processing.rs b/src/bellatrix/state_transition/epoch_processing.rs index e63551ad8..d57738627 100644 --- a/src/bellatrix/state_transition/epoch_processing.rs +++ b/src/bellatrix/state_transition/epoch_processing.rs @@ -1,18 +1,19 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::bellatrix as spec; -pub use crate::bellatrix::epoch_processing::process_epoch; -pub use crate::bellatrix::epoch_processing::process_slashings; -use crate::primitives::{Epoch, Gwei, ParticipationFlags, ValidatorIndex, GENESIS_EPOCH}; -use crate::state_transition::{Context, Result}; -use spec::get_inactivity_penalty_deltas; +pub use crate::bellatrix::epoch_processing::{process_epoch, process_slashings}; +use crate::{ + bellatrix as spec, + primitives::{Epoch, Gwei, ParticipationFlags, ValidatorIndex, GENESIS_EPOCH}, + state_transition::{Context, Result}, +}; use spec::{ compute_activation_exit_epoch, decrease_balance, get_base_reward_per_increment, get_block_root, get_current_epoch, get_eligible_validator_indices, get_flag_index_deltas, - get_next_sync_committee, get_previous_epoch, get_randao_mix, get_total_active_balance, - get_total_balance, get_unslashed_participating_indices, get_validator_churn_limit, - increase_balance, initiate_validator_exit, is_active_validator, is_eligible_for_activation, - is_eligible_for_activation_queue, BeaconState, Checkpoint, HistoricalSummary, - JUSTIFICATION_BITS_LENGTH, PARTICIPATION_FLAG_WEIGHTS, TIMELY_TARGET_FLAG_INDEX, + get_inactivity_penalty_deltas, get_next_sync_committee, get_previous_epoch, get_randao_mix, + get_total_active_balance, get_total_balance, get_unslashed_participating_indices, + get_validator_churn_limit, increase_balance, initiate_validator_exit, is_active_validator, + is_eligible_for_activation, is_eligible_for_activation_queue, BeaconState, Checkpoint, + HistoricalSummary, JUSTIFICATION_BITS_LENGTH, PARTICIPATION_FLAG_WEIGHTS, + TIMELY_TARGET_FLAG_INDEX, }; use ssz_rs::prelude::*; use std::mem; @@ -184,8 +185,8 @@ pub fn process_effective_balance_updates< for i in 0..state.validators.len() { let validator = &mut state.validators[i]; let balance = state.balances[i]; - if balance + downward_threshold < validator.effective_balance - || validator.effective_balance + upward_threshold < balance + if balance + downward_threshold < validator.effective_balance || + validator.effective_balance + upward_threshold < balance { validator.effective_balance = Gwei::min( balance - balance % context.effective_balance_increment, @@ -266,9 +267,7 @@ pub fn process_historical_roots_update< block_summary_root: state.block_roots.hash_tree_root()?, state_summary_root: state.state_roots.hash_tree_root()?, }; - state - .historical_roots - .push(historical_batch.hash_tree_root()?) + state.historical_roots.push(historical_batch.hash_tree_root()?) } Ok(()) } @@ -304,7 +303,7 @@ pub fn process_inactivity_updates< ) -> Result<()> { let current_epoch = get_current_epoch(state, context); if current_epoch == GENESIS_EPOCH { - return Ok(()); + return Ok(()) } let eligible_validator_indices = get_eligible_validator_indices(state, context).collect::>(); @@ -322,10 +321,8 @@ pub fn process_inactivity_updates< state.inactivity_scores[index] += context.inactivity_score_bias; } if not_is_leaking { - state.inactivity_scores[index] -= u64::min( - context.inactivity_score_recovery_rate, - state.inactivity_scores[index], - ); + state.inactivity_scores[index] -= + u64::min(context.inactivity_score_recovery_rate, state.inactivity_scores[index]); } } Ok(()) @@ -362,7 +359,7 @@ pub fn process_justification_and_finalization< ) -> Result<()> { let current_epoch = get_current_epoch(state, context); if current_epoch <= GENESIS_EPOCH + 1 { - return Ok(()); + return Ok(()) } let previous_indices = get_unslashed_participating_indices( state, @@ -419,9 +416,8 @@ pub fn process_participation_flag_updates< let current_participation = mem::take(&mut state.current_epoch_participation); state.previous_epoch_participation = current_participation; let rotate_participation = vec![ParticipationFlags::default(); state.validators.len()]; - state.current_epoch_participation = rotate_participation - .try_into() - .expect("should convert from Vec to List"); + state.current_epoch_participation = + rotate_participation.try_into().expect("should convert from Vec to List"); Ok(()) } pub fn process_randao_mixes_reset< @@ -495,34 +491,32 @@ pub fn process_registry_updates< if is_eligible_for_activation_queue(validator, context) { validator.activation_eligibility_epoch = current_epoch + 1; } - if is_active_validator(validator, current_epoch) - && validator.effective_balance <= context.ejection_balance + if is_active_validator(validator, current_epoch) && + validator.effective_balance <= context.ejection_balance { initiate_validator_exit(state, i, context); } } - let mut activation_queue = state - .validators - .iter() - .enumerate() - .filter_map(|(index, validator)| { - if is_eligible_for_activation(state, validator) { - Some(index) - } else { - None - } - }) - .collect::>(); + let mut activation_queue = + state + .validators + .iter() + .enumerate() + .filter_map(|(index, validator)| { + if is_eligible_for_activation(state, validator) { + Some(index) + } else { + None + } + }) + .collect::>(); activation_queue.sort_by(|&i, &j| { let a = &state.validators[i]; let b = &state.validators[j]; (a.activation_eligibility_epoch, i).cmp(&(b.activation_eligibility_epoch, j)) }); let activation_exit_epoch = compute_activation_exit_epoch(current_epoch, context); - for i in activation_queue - .into_iter() - .take(get_validator_churn_limit(state, context)) - { + for i in activation_queue.into_iter().take(get_validator_churn_limit(state, context)) { let validator = &mut state.validators[i]; validator.activation_epoch = activation_exit_epoch; } @@ -559,7 +553,7 @@ pub fn process_rewards_and_penalties< ) -> Result<()> { let current_epoch = get_current_epoch(state, context); if current_epoch == GENESIS_EPOCH { - return Ok(()); + return Ok(()) } let mut deltas = Vec::new(); for flag_index in 0..PARTICIPATION_FLAG_WEIGHTS.len() { @@ -686,9 +680,7 @@ pub fn weigh_justification_and_finalization< let old_previous_justified_checkpoint = state.previous_justified_checkpoint.clone(); let old_current_justified_checkpoint = state.current_justified_checkpoint.clone(); state.previous_justified_checkpoint = state.current_justified_checkpoint.clone(); - state - .justification_bits - .copy_within(..JUSTIFICATION_BITS_LENGTH - 1, 1); + state.justification_bits.copy_within(..JUSTIFICATION_BITS_LENGTH - 1, 1); state.justification_bits.set(0, false); if previous_epoch_target_balance * 3 >= total_active_balance * 2 { state.current_justified_checkpoint = Checkpoint { diff --git a/src/bellatrix/state_transition/helpers.rs b/src/bellatrix/state_transition/helpers.rs index 908219234..abf95acfb 100644 --- a/src/bellatrix/state_transition/helpers.rs +++ b/src/bellatrix/state_transition/helpers.rs @@ -1,20 +1,20 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::bellatrix as spec; -pub use crate::bellatrix::helpers::compute_timestamp_at_slot; -pub use crate::bellatrix::helpers::get_inactivity_penalty_deltas; -pub use crate::bellatrix::helpers::is_execution_enabled; -pub use crate::bellatrix::helpers::is_merge_transition_block; -pub use crate::bellatrix::helpers::is_merge_transition_complete; -pub use crate::bellatrix::helpers::slash_validator; -use crate::crypto::{eth_aggregate_public_keys, fast_aggregate_verify, hash, verify_signature}; -use crate::primitives::{ - BlsPublicKey, Bytes32, CommitteeIndex, Domain, DomainType, Epoch, ForkDigest, Gwei, - ParticipationFlags, Root, Slot, ValidatorIndex, Version, FAR_FUTURE_EPOCH, GENESIS_EPOCH, +pub use crate::bellatrix::helpers::{ + compute_timestamp_at_slot, get_inactivity_penalty_deltas, is_execution_enabled, + is_merge_transition_block, is_merge_transition_complete, slash_validator, }; -use crate::signing::compute_signing_root; -use crate::state_transition::{ - invalid_operation_error, Context, Error, InvalidAttestation, InvalidIndexedAttestation, - InvalidOperation, Result, +use crate::{ + bellatrix as spec, + crypto::{eth_aggregate_public_keys, fast_aggregate_verify, hash, verify_signature}, + primitives::{ + BlsPublicKey, Bytes32, CommitteeIndex, Domain, DomainType, Epoch, ForkDigest, Gwei, + ParticipationFlags, Root, Slot, ValidatorIndex, Version, FAR_FUTURE_EPOCH, GENESIS_EPOCH, + }, + signing::compute_signing_root, + state_transition::{ + invalid_operation_error, Context, Error, InvalidAttestation, InvalidIndexedAttestation, + InvalidOperation, Result, + }, }; use integer_sqrt::IntegerSquareRoot; use spec::{ @@ -23,8 +23,7 @@ use spec::{ TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, TIMELY_TARGET_FLAG_INDEX, WEIGHT_DENOMINATOR, }; use ssz_rs::prelude::*; -use std::cmp; -use std::collections::HashSet; +use std::{cmp, collections::HashSet}; pub fn add_flag(flags: ParticipationFlags, flag_index: usize) -> ParticipationFlags { let flag = 2u8.pow(flag_index as u32); flags | flag @@ -69,12 +68,9 @@ pub fn compute_fork_data_root( current_version: Version, genesis_validators_root: Root, ) -> Result { - ForkData { - current_version, - genesis_validators_root, - } - .hash_tree_root() - .map_err(Error::Merkleization) + ForkData { current_version, genesis_validators_root } + .hash_tree_root() + .map_err(Error::Merkleization) } pub fn compute_fork_digest( current_version: Version, @@ -117,7 +113,7 @@ pub fn compute_proposer_index< context: &Context, ) -> Result { if indices.is_empty() { - return Err(Error::CollectionCannotBeEmpty); + return Err(Error::CollectionCannotBeEmpty) } let max_byte = u8::MAX as u64; let mut i = 0; @@ -132,7 +128,7 @@ pub fn compute_proposer_index< let random_byte = hash(hash_input).as_ref()[i % 32] as u64; let effective_balance = state.validators[candidate_index].effective_balance; if effective_balance * max_byte >= context.max_effective_balance * random_byte { - return Ok(candidate_index); + return Ok(candidate_index) } i += 1; } @@ -144,10 +140,7 @@ pub fn compute_shuffled_index( context: &Context, ) -> Result { if index >= index_count { - return Err(Error::InvalidShufflingIndex { - index, - total: index_count, - }); + return Err(Error::InvalidShufflingIndex { index, total: index_count }) } let mut pivot_input = [0u8; 33]; pivot_input[..32].copy_from_slice(seed.as_ref()); @@ -292,12 +285,12 @@ pub fn get_attestation_participation_flag_indices< source_checkpoint: data.source.clone(), current: get_current_epoch(state, context), }, - ))); + ))) } - let is_matching_target = is_matching_source - && (data.target.root == *get_block_root(state, data.target.epoch, context)?); - let is_matching_head = is_matching_target - && (data.beacon_block_root == *get_block_root_at_slot(state, data.slot)?); + let is_matching_target = is_matching_source && + (data.target.root == *get_block_root(state, data.target.epoch, context)?); + let is_matching_head = is_matching_target && + (data.beacon_block_root == *get_block_root_at_slot(state, data.slot)?); let mut participation_flag_indices = Vec::new(); if is_matching_source && inclusion_delay <= context.slots_per_epoch.integer_sqrt() { participation_flag_indices.push(TIMELY_SOURCE_FLAG_INDEX); @@ -345,11 +338,8 @@ pub fn get_attesting_indices< let committee = get_beacon_committee(state, data.slot, data.index, context)?; if bits.len() != committee.len() { return Err(invalid_operation_error(InvalidOperation::Attestation( - InvalidAttestation::Bitfield { - expected_length: committee.len(), - length: bits.len(), - }, - ))); + InvalidAttestation::Bitfield { expected_length: committee.len(), length: bits.len() }, + ))) } let mut indices = HashSet::with_capacity(bits.capacity()); for (i, validator_index) in committee.iter().enumerate() { @@ -389,10 +379,8 @@ pub fn get_base_reward_per_increment< >, context: &Context, ) -> Result { - Ok( - context.effective_balance_increment * context.base_reward_factor - / get_total_active_balance(state, context)?.integer_sqrt(), - ) + Ok(context.effective_balance_increment * context.base_reward_factor / + get_total_active_balance(state, context)?.integer_sqrt()) } pub fn get_beacon_committee< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -542,7 +530,7 @@ pub fn get_block_root_at_slot< requested: slot, lower_bound: state.slot - 1, upper_bound: state.slot + SLOTS_PER_HISTORICAL_ROOT as Slot, - }); + }) } Ok(&state.block_roots[slot as usize % SLOTS_PER_HISTORICAL_ROOT]) } @@ -581,9 +569,9 @@ pub fn get_committee_count_per_slot< 1, u64::min( context.max_committees_per_slot, - get_active_validator_indices(state, epoch).len() as u64 - / context.slots_per_epoch - / context.target_committee_size, + get_active_validator_indices(state, epoch).len() as u64 / + context.slots_per_epoch / + context.target_committee_size, ), ) as usize } @@ -657,12 +645,7 @@ pub fn get_domain< } else { state.fork.current_version }; - compute_domain( - domain_type, - Some(fork_version), - Some(state.genesis_validators_root), - context, - ) + compute_domain(domain_type, Some(fork_version), Some(state.genesis_validators_root), context) } pub fn get_eligible_validator_indices< 'a, @@ -696,19 +679,15 @@ pub fn get_eligible_validator_indices< context: &Context, ) -> impl Iterator + 'a { let previous_epoch = get_previous_epoch(state, context); - state - .validators - .iter() - .enumerate() - .filter_map(move |(i, validator)| { - if is_active_validator(validator, previous_epoch) - || (validator.slashed && previous_epoch + 1 < validator.withdrawable_epoch) - { - Some(i) - } else { - None - } - }) + state.validators.iter().enumerate().filter_map(move |(i, validator)| { + if is_active_validator(validator, previous_epoch) || + (validator.slashed && previous_epoch + 1 < validator.withdrawable_epoch) + { + Some(i) + } else { + None + } + }) } pub fn get_flag_index_deltas< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -842,17 +821,12 @@ pub fn get_next_sync_committee< context: &Context, ) -> Result> { let indices = get_next_sync_committee_indices(state, context)?; - let public_keys = indices - .into_iter() - .map(|i| state.validators[i].public_key.clone()) - .collect::>(); + let public_keys = + indices.into_iter().map(|i| state.validators[i].public_key.clone()).collect::>(); let public_keys = Vector::::try_from(public_keys) .map_err(|(_, err)| err)?; let aggregate_public_key = eth_aggregate_public_keys(&public_keys)?; - Ok(SyncCommittee:: { - public_keys, - aggregate_public_key, - }) + Ok(SyncCommittee:: { public_keys, aggregate_public_key }) } pub fn get_next_sync_committee_indices< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -1088,9 +1062,7 @@ pub fn get_total_balance< ) -> Result { let total_balance = indices .iter() - .try_fold(Gwei::default(), |acc, i| { - acc.checked_add(state.validators[*i].effective_balance) - }) + .try_fold(Gwei::default(), |acc, i| acc.checked_add(state.validators[*i].effective_balance)) .ok_or(Error::Overflow)?; Ok(u64::max(total_balance, context.effective_balance_increment)) } @@ -1134,7 +1106,7 @@ pub fn get_unslashed_participating_indices< requested: epoch, previous: previous_epoch, current: current_epoch, - }); + }) } let epoch_participation = if is_current { &state.current_epoch_participation @@ -1256,7 +1228,7 @@ pub fn initiate_validator_exit< context: &Context, ) { if state.validators[index].exit_epoch != FAR_FUTURE_EPOCH { - return; + return } let mut exit_epochs: Vec = state .validators @@ -1264,16 +1236,10 @@ pub fn initiate_validator_exit< .filter(|v| v.exit_epoch != FAR_FUTURE_EPOCH) .map(|v| v.exit_epoch) .collect(); - exit_epochs.push(compute_activation_exit_epoch( - get_current_epoch(state, context), - context, - )); + exit_epochs.push(compute_activation_exit_epoch(get_current_epoch(state, context), context)); let mut exit_queue_epoch = *exit_epochs.iter().max().unwrap(); - let exit_queue_churn = state - .validators - .iter() - .filter(|v| v.exit_epoch == exit_queue_epoch) - .count(); + let exit_queue_churn = + state.validators.iter().filter(|v| v.exit_epoch == exit_queue_epoch).count(); if exit_queue_churn >= get_validator_churn_limit(state, context) { exit_queue_epoch += 1; } @@ -1314,12 +1280,12 @@ pub fn is_eligible_for_activation< >, validator: &Validator, ) -> bool { - validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch - && validator.activation_epoch == FAR_FUTURE_EPOCH + validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch && + validator.activation_epoch == FAR_FUTURE_EPOCH } pub fn is_eligible_for_activation_queue(validator: &Validator, context: &Context) -> bool { - validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH - && validator.effective_balance == context.max_effective_balance + validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH && + validator.effective_balance == context.max_effective_balance } pub fn is_slashable_attestation_data(data_1: &AttestationData, data_2: &AttestationData) -> bool { let double_vote = data_1 != data_2 && data_1.target.epoch == data_2.target.epoch; @@ -1328,9 +1294,9 @@ pub fn is_slashable_attestation_data(data_1: &AttestationData, data_2: &Attestat double_vote || surround_vote } pub fn is_slashable_validator(validator: &Validator, epoch: Epoch) -> bool { - !validator.slashed - && validator.activation_epoch <= epoch - && epoch < validator.withdrawable_epoch + !validator.slashed && + validator.activation_epoch <= epoch && + epoch < validator.withdrawable_epoch } pub fn is_valid_indexed_attestation< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -1365,9 +1331,9 @@ pub fn is_valid_indexed_attestation< ) -> Result<()> { let attesting_indices = &indexed_attestation.attesting_indices; if attesting_indices.is_empty() { - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation(InvalidIndexedAttestation::AttestingIndicesEmpty), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::AttestingIndicesEmpty, + ))) } let is_sorted = attesting_indices .windows(2) @@ -1378,11 +1344,9 @@ pub fn is_valid_indexed_attestation< }) .all(|x| x); if !is_sorted { - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation( - InvalidIndexedAttestation::AttestingIndicesNotSorted, - ), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::AttestingIndicesNotSorted, + ))) } let indices: HashSet = HashSet::from_iter(attesting_indices.iter().cloned()); if indices.len() != indexed_attestation.attesting_indices.len() { @@ -1395,23 +1359,17 @@ pub fn is_valid_indexed_attestation< seen.insert(i); } } - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation(InvalidIndexedAttestation::DuplicateIndices( - duplicates, - )), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::DuplicateIndices(duplicates), + ))) } let mut public_keys = vec![]; for index in indices { - let public_key = state - .validators - .get(index) - .map(|v| &v.public_key) - .ok_or_else(|| { - invalid_operation_error(InvalidOperation::IndexedAttestation( - InvalidIndexedAttestation::InvalidIndex(index), - )) - })?; + let public_key = state.validators.get(index).map(|v| &v.public_key).ok_or_else(|| { + invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::InvalidIndex(index), + )) + })?; public_keys.push(public_key); } let domain = get_domain( @@ -1421,12 +1379,8 @@ pub fn is_valid_indexed_attestation< context, )?; let signing_root = compute_signing_root(&mut indexed_attestation.data, domain)?; - fast_aggregate_verify( - &public_keys, - signing_root.as_ref(), - &indexed_attestation.signature, - ) - .map_err(Into::into) + fast_aggregate_verify(&public_keys, signing_root.as_ref(), &indexed_attestation.signature) + .map_err(Into::into) } pub fn verify_block_signature< const SLOTS_PER_HISTORICAL_ROOT: usize, @@ -1480,10 +1434,7 @@ pub fn verify_block_signature< let proposer = state .validators .get(proposer_index) - .ok_or(Error::OutOfBounds { - requested: proposer_index, - bound: state.validators.len(), - })?; + .ok_or(Error::OutOfBounds { requested: proposer_index, bound: state.validators.len() })?; let domain = get_domain(state, DomainType::BeaconProposer, None, context)?; let signing_root = compute_signing_root(&mut signed_block.message, domain)?; let public_key = &proposer.public_key; diff --git a/src/bellatrix/state_transition/mod.rs b/src/bellatrix/state_transition/mod.rs index 4085b5147..ab8383253 100644 --- a/src/bellatrix/state_transition/mod.rs +++ b/src/bellatrix/state_transition/mod.rs @@ -4,7 +4,8 @@ pub mod epoch_processing; pub mod helpers; pub mod slot_processing; -pub use crate::bellatrix::state_transition_bellatrix::state_transition; -pub use crate::bellatrix::state_transition_bellatrix::state_transition_block_in_slot; +pub use crate::bellatrix::state_transition_bellatrix::{ + state_transition, state_transition_block_in_slot, +}; use ssz_rs::prelude::*; diff --git a/src/bellatrix/state_transition/slot_processing.rs b/src/bellatrix/state_transition/slot_processing.rs index 2c45b2435..e0cc369c2 100644 --- a/src/bellatrix/state_transition/slot_processing.rs +++ b/src/bellatrix/state_transition/slot_processing.rs @@ -1,7 +1,9 @@ //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. -use crate::bellatrix as spec; -use crate::primitives::{Root, Slot}; -use crate::state_transition::{Context, Error, Result}; +use crate::{ + bellatrix as spec, + primitives::{Root, Slot}, + state_transition::{Context, Error, Result}, +}; use spec::{process_epoch, BeaconState}; use ssz_rs::prelude::*; pub fn process_slot< @@ -77,10 +79,7 @@ pub fn process_slots< context: &Context, ) -> Result<()> { if state.slot >= slot { - return Err(Error::TransitionToPreviousSlot { - requested: slot, - current: state.slot, - }); + return Err(Error::TransitionToPreviousSlot { requested: slot, current: state.slot }) } while state.slot < slot { process_slot(state, context)?; diff --git a/src/bellatrix/state_transition_bellatrix.rs b/src/bellatrix/state_transition_bellatrix.rs index f030f49f8..fd0e01e54 100644 --- a/src/bellatrix/state_transition_bellatrix.rs +++ b/src/bellatrix/state_transition_bellatrix.rs @@ -1,5 +1,7 @@ -use crate::bellatrix as spec; -use crate::state_transition::{Context, Error, Result, Validation}; +use crate::{ + bellatrix as spec, + state_transition::{Context, Error, Result, Validation}, +}; use spec::{ process_block, process_slots, verify_block_signature, BeaconState, ExecutionEngine, SignedBeaconBlock, diff --git a/src/bin/gen_spec.rs b/src/bin/gen_spec.rs index e6fa6c089..3c97ab057 100644 --- a/src/bin/gen_spec.rs +++ b/src/bin/gen_spec.rs @@ -1,18 +1,19 @@ use quote::{format_ident, ToTokens}; -use std::collections::HashMap; -use std::collections::HashSet; -use std::fmt; -use std::fs::{self}; +use std::{ + collections::{HashMap, HashSet}, + fmt, + fs::{self}, +}; -use std::mem; -use std::path::{Path, PathBuf}; +use std::{ + mem, + path::{Path, PathBuf}, +}; -use syn::visit::Visit; -use syn::visit_mut::VisitMut; use syn::{ - parse_quote, punctuated::Punctuated, token::Comma, ConstParam, FnArg, GenericArgument, - GenericParam, Ident, Item, ItemConst, ItemFn, ItemMod, ItemUse, PathArguments, PathSegment, - Signature, Type, UseTree, + parse_quote, punctuated::Punctuated, token::Comma, visit::Visit, visit_mut::VisitMut, + ConstParam, FnArg, GenericArgument, GenericParam, Ident, Item, ItemConst, ItemFn, ItemMod, + ItemUse, PathArguments, PathSegment, Signature, Type, UseTree, }; const ATTESTATION_BOUND_IDENT: &str = "PENDING_ATTESTATIONS_BOUND"; @@ -50,20 +51,13 @@ struct ImportEditor { impl ImportEditor { fn new(imports_to_filter: HashSet) -> Self { - Self { - all_imports: Default::default(), - imports_to_filter, - } + Self { all_imports: Default::default(), imports_to_filter } } fn into_items(self) -> Vec { let mut items = vec![]; for (path, tree) in self.all_imports { - let prefix = path - .iter() - .map(|node| node.to_string()) - .collect::>() - .join("::"); + let prefix = path.iter().map(|node| node.to_string()).collect::>().join("::"); let names = tree .iter() .map(|node| node.to_token_stream().to_string()) @@ -115,8 +109,8 @@ impl VisitMut for GenericsEditor { if let Type::Path(ty) = node { if ty.path.segments.len() == 1 { let segment = &mut ty.path.segments[0]; - if segment.ident == "BeaconState" - || segment.ident.to_string().contains("BeaconBlock") + if segment.ident == "BeaconState" || + segment.ident.to_string().contains("BeaconBlock") { if let PathArguments::AngleBracketed(arguments) = &mut segment.arguments { for bound in BELLATRIX_BEACON_STATE_BOUNDS { @@ -140,17 +134,17 @@ impl VisitMut for GenericsEditor { if let Type::Path(ty) = &*ty.elem { ty } else { - return false; + return false } } _ => return false, }; if ty.path.segments.len() == 1 { let segment = &ty.path.segments[0]; - if segment.ident == "BeaconState" - || segment.ident.to_string().contains("BeaconBlock") + if segment.ident == "BeaconState" || + segment.ident.to_string().contains("BeaconBlock") { - return true; + return true } } } @@ -241,19 +235,15 @@ impl Module { } fn parse_if_exists(mut self, module_dir: &Path) -> Option { - let path = if matches!(self.spec, Specs::Bellatrix) - && matches!(self.module, Modules::StateTransition) + let path = if matches!(self.spec, Specs::Bellatrix) && + matches!(self.module, Modules::StateTransition) { - module_dir - .join("state_transition_bellatrix") - .with_extension("rs") + module_dir.join("state_transition_bellatrix").with_extension("rs") } else { - module_dir - .join(self.module.to_string()) - .with_extension("rs") + module_dir.join(self.module.to_string()).with_extension("rs") }; if !path.exists() { - return None; + return None } let source = fs::read_to_string(path).unwrap(); @@ -290,23 +280,12 @@ impl Module { fn unify_uses(&mut self) { let uses = mem::take(&mut self.uses); - let items = uses - .into_iter() - .map(|decl| Item::Use(decl.node)) - .collect::>(); - let file = syn::File { - shebang: None, - attrs: vec![], - items, - }; + let items = uses.into_iter().map(|decl| Item::Use(decl.node)).collect::>(); + let file = syn::File { shebang: None, attrs: vec![], items }; let imports_to_filter = self.get_imports_to_filter(); let mut editor = ImportEditor::new(imports_to_filter); editor.visit_file(&file); - self.uses = editor - .into_items() - .into_iter() - .map(|node| UseDecl { node }) - .collect(); + self.uses = editor.into_items().into_iter().map(|node| UseDecl { node }).collect(); } fn merge(&mut self, previous: &Self) { @@ -323,7 +302,7 @@ impl Module { self.consts = self.consts.union(&previous.consts).cloned().collect(); for (fn_name, fn_decl) in &previous.fns { if self.fns.contains_key(fn_name) { - continue; + continue } self.fns.insert(fn_name.clone(), fn_decl.clone()); } @@ -356,17 +335,14 @@ impl Module { let spec_import: ItemUse = syn::parse_str(&spec_item).unwrap(); items.push(Item::Use(spec_import)); for fn_to_import in &self.fns_to_import { - let module = if matches!(self.spec, Specs::Bellatrix) - && matches!(self.module, Modules::StateTransition) + let module = if matches!(self.spec, Specs::Bellatrix) && + matches!(self.module, Modules::StateTransition) { "state_transition_bellatrix".to_string() } else { self.module.to_string() }; - let use_repr = format!( - "pub use crate::{}::{}::{};", - self.spec, module, fn_to_import - ); + let use_repr = format!("pub use crate::{}::{}::{};", self.spec, module, fn_to_import); let use_item: ItemUse = syn::parse_str(&use_repr).unwrap(); items.push(Item::Use(use_item)); } @@ -382,7 +358,7 @@ impl Module { fn_names.sort(); for fn_name in fn_names { if self.fns_to_import.contains(fn_name) { - continue; + continue } let fn_item = self.fns.get(fn_name).unwrap(); items.push(Item::Fn(fn_item.node.clone())); @@ -402,20 +378,14 @@ impl<'ast> Visit<'ast> for Module { fn visit_item_fn(&mut self, node: &'ast ItemFn) { let fn_name = node.sig.ident.to_string(); - let fn_decl = FnDecl { - node: node.clone(), - item_index: self.item_index, - }; + let fn_decl = FnDecl { node: node.clone(), item_index: self.item_index }; self.item_index += 1; self.fns.insert(fn_name, fn_decl); syn::visit::visit_item_fn(self, node) } fn visit_item_const(&mut self, node: &'ast ItemConst) { - let const_decl = ConstDecl { - node: node.clone(), - item_index: self.item_index, - }; + let const_decl = ConstDecl { node: node.clone(), item_index: self.item_index }; self.item_index += 1; self.consts.insert(const_decl); syn::visit::visit_item_const(self, node) @@ -487,10 +457,8 @@ impl Spec { fn merge(&mut self, previous_spec: Self) { for module_name in ALL_MODULES { let previous_module = previous_spec.modules.get(module_name).unwrap(); - let module = self - .modules - .entry(*module_name) - .or_insert_with_key(|m| Module::new(*m, self.spec)); + let module = + self.modules.entry(*module_name).or_insert_with_key(|m| Module::new(*m, self.spec)); module.merge(previous_module); } } @@ -531,7 +499,7 @@ impl Spec { if let GenericParam::Const(param) = param { let ident = param.ident.to_string(); if ident == ATTESTATION_BOUND_IDENT { - return false; + return false } } true @@ -673,28 +641,15 @@ impl Spec { fn patch_bellatrix_types(&mut self) { for (_, module) in self.modules.iter_mut() { let fns = mem::take(&mut module.fns); - let items = fns - .into_values() - .map(|decl| Item::Fn(decl.node)) - .collect::>(); - let mut file = syn::File { - shebang: None, - attrs: vec![], - items, - }; + let items = fns.into_values().map(|decl| Item::Fn(decl.node)).collect::>(); + let mut file = syn::File { shebang: None, attrs: vec![], items }; let mut generics_editor = GenericsEditor::new(); generics_editor.visit_file_mut(&mut file); module.fns = file .items .into_iter() .map(|item| match item { - Item::Fn(node) => ( - node.sig.ident.to_string(), - FnDecl { - node, - item_index: 0, - }, - ), + Item::Fn(node) => (node.sig.ident.to_string(), FnDecl { node, item_index: 0 }), _ => unreachable!(), }) .collect(); @@ -722,11 +677,7 @@ impl Spec { let warning = parse_quote! { //! WARNING: This file was derived by the `gen-spec` utility. DO NOT EDIT MANUALLY. }; - let target_file = syn::File { - shebang: None, - attrs: vec![warning], - items, - }; + let target_file = syn::File { shebang: None, attrs: vec![warning], items }; let output = prettyplease::unparse(&target_file); let mut module_name = module_name.to_string(); if module_name == "state_transition" { @@ -764,8 +715,6 @@ impl Generator { fn main() { // NOTE: must run specs from beginning, in chronological order let specs = vec![Specs::Phase0, Specs::Altair, Specs::Bellatrix]; - let generator = Generator { - specs_to_generate: specs, - }; + let generator = Generator { specs_to_generate: specs }; generator.run(); } diff --git a/src/bin/gen_tests.rs b/src/bin/gen_tests.rs index ce8cc8f24..fc6b2ef4e 100644 --- a/src/bin/gen_tests.rs +++ b/src/bin/gen_tests.rs @@ -1,8 +1,10 @@ use convert_case::{Case, Casing}; -use std::collections::HashMap; -use std::fmt::Write; -use std::fs; -use std::path::{Component, Path, PathBuf}; +use std::{ + collections::HashMap, + fmt::Write, + fs, + path::{Component, Path, PathBuf}, +}; use walkdir::{DirEntry, Error, WalkDir}; type TestIndex = HashMap< @@ -28,7 +30,7 @@ fn insert_test(tests: &mut TestIndex, path: &Path) -> bool { // NOTE: these tests are handled elsewhere outside this repo. if runner == "ssz_generic" { - return false; + return false } let tests = tests.entry(runner).or_default(); @@ -69,11 +71,7 @@ fn generate_module_decl_src<'a>(modules: impl Iterator) -> St let mut src = String::new(); for module in modules { let module = prefix_if_starts_with_reserved(module); - let module = if module == "phase_0" { - "phase0".to_string() - } else { - module - }; + let module = if module == "phase_0" { "phase0".to_string() } else { module }; writeln!(src, "mod {module};").unwrap(); } src @@ -95,10 +93,7 @@ fn is_leaf(entry: &DirEntry) -> bool { } fn leaf_dirs(path: &PathBuf) -> impl Iterator { - WalkDir::new(path) - .into_iter() - .filter(|e| is_leaf(e.as_ref().unwrap())) - .map(|e| e.unwrap()) + WalkDir::new(path).into_iter().filter(|e| is_leaf(e.as_ref().unwrap())).map(|e| e.unwrap()) } fn generate_suite_src( @@ -116,11 +111,7 @@ fn generate_suite_src( "# .to_string(); - writeln!( - src, - "use crate::spec_test_runners::{runner}::{test_case_type};", - ) - .unwrap(); + writeln!(src, "use crate::spec_test_runners::{runner}::{test_case_type};",).unwrap(); let needs_trait_import = matches!(runner, "bls"); @@ -194,16 +185,9 @@ fn generate_suite_src( Spec::Bellatrix => "altair", _ => unimplemented!("support other forks"), }; - writeln!( - src, - "use ethereum_consensus::{pre_fork}::{config} as pre_spec;", - ) - .unwrap(); - writeln!( - src, - "use ethereum_consensus::bellatrix::{config}::NoOpExecutionEngine;", - ) - .unwrap(); + writeln!(src, "use ethereum_consensus::{pre_fork}::{config} as pre_spec;",).unwrap(); + writeln!(src, "use ethereum_consensus::bellatrix::{config}::NoOpExecutionEngine;",) + .unwrap(); } if matches!(runner, "fork") { match spec { diff --git a/src/builder/mod.rs b/src/builder/mod.rs index 1690b289d..3f8b82ee4 100644 --- a/src/builder/mod.rs +++ b/src/builder/mod.rs @@ -1,6 +1,8 @@ -use crate::phase0::compute_domain; -use crate::primitives::{BlsPublicKey, BlsSignature, Domain, DomainType, ExecutionAddress}; -use crate::state_transition::{Context, Error}; +use crate::{ + phase0::compute_domain, + primitives::{BlsPublicKey, BlsSignature, Domain, DomainType, ExecutionAddress}, + state_transition::{Context, Error}, +}; use ssz_rs::prelude::*; #[derive(Debug, Clone, Default, SimpleSerialize)] diff --git a/src/capella/beacon_block.rs b/src/capella/beacon_block.rs index 6cde9d09a..e9d3120f0 100644 --- a/src/capella/beacon_block.rs +++ b/src/capella/beacon_block.rs @@ -1,9 +1,11 @@ -use crate::altair::SyncAggregate; -use crate::capella::{ExecutionPayload, SignedBlsToExecutionChange}; -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + altair::SyncAggregate, + capella::{ExecutionPayload, SignedBlsToExecutionChange}, + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize, PartialEq, Eq)] diff --git a/src/capella/beacon_state.rs b/src/capella/beacon_state.rs index f72f0b33a..9dddfe737 100644 --- a/src/capella/beacon_state.rs +++ b/src/capella/beacon_state.rs @@ -1,10 +1,8 @@ -use crate::altair::SyncCommittee; -use crate::capella::{ExecutionPayloadHeader, HistoricalSummary}; -use crate::phase0::{ - BeaconBlockHeader, Checkpoint, Eth1Data, Fork, Validator, JUSTIFICATION_BITS_LENGTH, -}; -use crate::primitives::{ - Bytes32, Gwei, ParticipationFlags, Root, Slot, ValidatorIndex, WithdrawalIndex, +use crate::{ + altair::SyncCommittee, + capella::{ExecutionPayloadHeader, HistoricalSummary}, + phase0::{BeaconBlockHeader, Checkpoint, Eth1Data, Fork, Validator, JUSTIFICATION_BITS_LENGTH}, + primitives::{Bytes32, Gwei, ParticipationFlags, Root, Slot, ValidatorIndex, WithdrawalIndex}, }; use ssz_rs::prelude::*; diff --git a/src/capella/blinded_beacon_block.rs b/src/capella/blinded_beacon_block.rs index 6bf86afb0..9ddc8d4dc 100644 --- a/src/capella/blinded_beacon_block.rs +++ b/src/capella/blinded_beacon_block.rs @@ -1,9 +1,11 @@ -use crate::altair::SyncAggregate; -use crate::capella::{ExecutionPayloadHeader, SignedBlsToExecutionChange}; -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + altair::SyncAggregate, + capella::{ExecutionPayloadHeader, SignedBlsToExecutionChange}, + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize)] diff --git a/src/capella/execution.rs b/src/capella/execution.rs index c17355c05..1ddad395e 100644 --- a/src/capella/execution.rs +++ b/src/capella/execution.rs @@ -1,8 +1,10 @@ -use crate::bellatrix::Transaction; -use crate::capella::withdrawal::Withdrawal; -use crate::primitives::{Bytes32, ExecutionAddress, Hash32, Root, U256}; -use crate::ssz::{ByteList, ByteVector}; -use crate::state_transition::{self, Error}; +use crate::{ + bellatrix::Transaction, + capella::withdrawal::Withdrawal, + primitives::{Bytes32, ExecutionAddress, Hash32, Root, U256}, + ssz::{ByteList, ByteVector}, + state_transition::{self, Error}, +}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize, PartialEq, Eq)] diff --git a/src/capella/mod.rs b/src/capella/mod.rs index 2f865a304..1ce2a5789 100644 --- a/src/capella/mod.rs +++ b/src/capella/mod.rs @@ -17,18 +17,20 @@ pub use execution::*; pub use presets::Preset; pub use withdrawal::*; -pub use crate::altair::{ - SyncAggregate, SyncAggregatorSelectionData, SyncCommittee, PARTICIPATION_FLAG_WEIGHTS, - PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, - TIMELY_TARGET_FLAG_INDEX, WEIGHT_DENOMINATOR, -}; -pub use crate::bellatrix::Transaction; -pub use crate::phase0::{ - Attestation, AttestationData, AttesterSlashing, BeaconBlockHeader, Checkpoint, Deposit, - DepositData, DepositMessage, Eth1Block, Eth1Data, Fork, ForkData, HistoricalSummary, - IndexedAttestation, ProposerSlashing, SignedBeaconBlockHeader, SignedVoluntaryExit, - SigningData, Validator, VoluntaryExit, BASE_REWARDS_PER_EPOCH, DEPOSIT_CONTRACT_TREE_DEPTH, - JUSTIFICATION_BITS_LENGTH, +pub use crate::{ + altair::{ + SyncAggregate, SyncAggregatorSelectionData, SyncCommittee, PARTICIPATION_FLAG_WEIGHTS, + PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, + TIMELY_TARGET_FLAG_INDEX, WEIGHT_DENOMINATOR, + }, + bellatrix::Transaction, + phase0::{ + Attestation, AttestationData, AttesterSlashing, BeaconBlockHeader, Checkpoint, Deposit, + DepositData, DepositMessage, Eth1Block, Eth1Data, Fork, ForkData, HistoricalSummary, + IndexedAttestation, ProposerSlashing, SignedBeaconBlockHeader, SignedVoluntaryExit, + SigningData, Validator, VoluntaryExit, BASE_REWARDS_PER_EPOCH, DEPOSIT_CONTRACT_TREE_DEPTH, + JUSTIFICATION_BITS_LENGTH, + }, }; pub mod mainnet { diff --git a/src/capella/presets/mainnet.rs b/src/capella/presets/mainnet.rs index 094768cc3..fdc48255c 100644 --- a/src/capella/presets/mainnet.rs +++ b/src/capella/presets/mainnet.rs @@ -1,23 +1,22 @@ -pub use crate::altair::mainnet::SYNC_COMMITTEE_SIZE; -pub use crate::altair::mainnet::{ - AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, - IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, - SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, - SyncCommitteeMessage, -}; -pub use crate::bellatrix::mainnet::Transaction; -pub use crate::bellatrix::mainnet::{ - BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, - MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, -}; -use crate::capella; -use crate::capella::presets::Preset; -pub use crate::phase0::mainnet::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +pub use crate::{ + altair::mainnet::{ + AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, + IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, + SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, + SyncCommitteeMessage, SYNC_COMMITTEE_SIZE, + }, + bellatrix::mainnet::{ + Transaction, BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, + MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, + }, + phase0::mainnet::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, }; +use crate::{capella, capella::presets::Preset}; pub use capella::*; diff --git a/src/capella/presets/minimal.rs b/src/capella/presets/minimal.rs index 401df4d31..f9f08e67e 100644 --- a/src/capella/presets/minimal.rs +++ b/src/capella/presets/minimal.rs @@ -1,23 +1,22 @@ -pub use crate::altair::minimal::SYNC_COMMITTEE_SIZE; -pub use crate::altair::minimal::{ - AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, - IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, - SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, - SyncCommitteeMessage, -}; -pub use crate::bellatrix::minimal::Transaction; -pub use crate::bellatrix::minimal::{ - BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, - MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, -}; -use crate::capella; -use crate::capella::presets::Preset; -pub use crate::phase0::minimal::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +pub use crate::{ + altair::minimal::{ + AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, + IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, + SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, + SyncCommitteeMessage, SYNC_COMMITTEE_SIZE, + }, + bellatrix::minimal::{ + Transaction, BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, + MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, + }, + phase0::minimal::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, }; +use crate::{capella, capella::presets::Preset}; pub use capella::*; diff --git a/src/clock.rs b/src/clock.rs index 24709d077..0fa9015a3 100644 --- a/src/clock.rs +++ b/src/clock.rs @@ -1,10 +1,13 @@ //! A consensus clock -use crate::configs; -use crate::phase0 as presets; -use crate::primitives::{Epoch, Slot}; -use std::ops::Deref; -use std::sync::Arc; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use crate::{ + configs, phase0 as presets, + primitives::{Epoch, Slot}, +}; +use std::{ + ops::Deref, + sync::Arc, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; pub const MAINNET_GENESIS_TIME: u64 = 1606824023; pub const SEPOLIA_GENESIS_TIME: u64 = 1655733600; @@ -20,10 +23,7 @@ pub fn convert_timestamp_to_slot( } pub fn get_current_unix_time_in_secs() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs() + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() } pub trait TimeProvider { @@ -63,12 +63,7 @@ pub fn from_system_time( slots_per_epoch: Slot, ) -> Clock { let time_provider = SystemTimeProvider; - Clock::new( - genesis_time, - seconds_per_slot, - slots_per_epoch, - time_provider, - ) + Clock::new(genesis_time, seconds_per_slot, slots_per_epoch, time_provider) } pub fn for_mainnet() -> Clock { @@ -99,12 +94,7 @@ impl Clock { slots_per_epoch: Slot, time_provider: T, ) -> Self { - let inner = Inner { - genesis_time, - seconds_per_slot, - slots_per_epoch, - time_provider, - }; + let inner = Inner { genesis_time, seconds_per_slot, slots_per_epoch, time_provider }; Self(Arc::new(inner)) } @@ -200,10 +190,7 @@ mod tests { } fn new_ticker(seconds_per_slot: u64) -> Arc { - Arc::new(Ticker { - tick: Mutex::new(0), - seconds_per_slot, - }) + Arc::new(Ticker { tick: Mutex::new(0), seconds_per_slot }) } #[test] @@ -253,7 +240,7 @@ mod tests { time_provider.tick_slot(); iter += 1; if iter > 1 { - break; + break } } } diff --git a/src/configs/goerli.rs b/src/configs/goerli.rs index f6d9033ca..ca19e1966 100644 --- a/src/configs/goerli.rs +++ b/src/configs/goerli.rs @@ -1,5 +1,7 @@ -use crate::configs::Config; -use crate::primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}; +use crate::{ + configs::Config, + primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}, +}; pub const MIN_GENESIS_ACTIVE_VALIDATOR_COUNT: usize = 16384; pub const MIN_GENESIS_TIME: u64 = 1614588812; diff --git a/src/configs/mainnet.rs b/src/configs/mainnet.rs index a2f46b64c..f6301b5bd 100644 --- a/src/configs/mainnet.rs +++ b/src/configs/mainnet.rs @@ -1,5 +1,7 @@ -use crate::configs::Config; -use crate::primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}; +use crate::{ + configs::Config, + primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}, +}; pub const MIN_GENESIS_ACTIVE_VALIDATOR_COUNT: usize = 16384; pub const MIN_GENESIS_TIME: u64 = 1606824000; diff --git a/src/configs/minimal.rs b/src/configs/minimal.rs index aa6e3e96f..b5d957ea8 100644 --- a/src/configs/minimal.rs +++ b/src/configs/minimal.rs @@ -1,5 +1,7 @@ -use crate::configs::Config; -use crate::primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}; +use crate::{ + configs::Config, + primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}, +}; pub const TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH: Epoch = FAR_FUTURE_EPOCH; pub const MIN_GENESIS_ACTIVE_VALIDATOR_COUNT: usize = 64; diff --git a/src/configs/sepolia.rs b/src/configs/sepolia.rs index 2e3a8ff62..905a44445 100644 --- a/src/configs/sepolia.rs +++ b/src/configs/sepolia.rs @@ -1,5 +1,7 @@ -use crate::configs::Config; -use crate::primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}; +use crate::{ + configs::Config, + primitives::{Epoch, ExecutionAddress, Gwei, Version, FAR_FUTURE_EPOCH, U256}, +}; pub const MIN_GENESIS_ACTIVE_VALIDATOR_COUNT: usize = 1300; pub const MIN_GENESIS_TIME: u64 = 1655647200; diff --git a/src/crypto.rs b/src/crypto.rs index 5b4e33858..dcc24b330 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -1,12 +1,13 @@ -use crate::primitives::Bytes32; #[cfg(feature = "serde")] use crate::serde::{try_bytes_from_hex_str, HexError}; -use crate::ssz::ByteVector; +use crate::{primitives::Bytes32, ssz::ByteVector}; use blst::{min_pk as bls_impl, BLST_ERROR}; use sha2::{digest::FixedOutput, Digest, Sha256}; use ssz_rs::prelude::*; -use std::fmt; -use std::ops::{Deref, DerefMut}; +use std::{ + fmt, + ops::{Deref, DerefMut}, +}; use thiserror::Error; pub fn hash>(data: D) -> Bytes32 { @@ -76,7 +77,7 @@ pub fn verify_signature( pub fn aggregate(signatures: &[Signature]) -> Result { if signatures.is_empty() { - return Err(Error::EmptyAggregate); + return Err(Error::EmptyAggregate) } let signatures = signatures @@ -132,7 +133,7 @@ pub fn fast_aggregate_verify( // Return the aggregate public key for the public keys in `pks` pub fn eth_aggregate_public_keys(public_keys: &[PublicKey]) -> Result { if public_keys.is_empty() { - return Err(Error::EmptyAggregate); + return Err(Error::EmptyAggregate) } let public_keys = public_keys .iter() @@ -468,19 +469,12 @@ mod tests { fn test_aggregate_verify() { let n = 20; let mut rng = thread_rng(); - let sks: Vec<_> = (0..n) - .map(|_| SecretKey::random(&mut rng).unwrap()) - .collect(); + let sks: Vec<_> = (0..n).map(|_| SecretKey::random(&mut rng).unwrap()).collect(); let pks: Vec<_> = sks.iter().map(|sk| sk.public_key()).collect(); - let msgs: Vec> = (0..n) - .map(|_| (0..64).map(|_| rand::thread_rng().gen()).collect()) - .collect(); + let msgs: Vec> = + (0..n).map(|_| (0..64).map(|_| rand::thread_rng().gen()).collect()).collect(); - let signatures: Vec<_> = msgs - .iter() - .zip(&sks) - .map(|(msg, sk)| sk.sign(msg)) - .collect(); + let signatures: Vec<_> = msgs.iter().zip(&sks).map(|(msg, sk)| sk.sign(msg)).collect(); let msgs = msgs.iter().map(|r| &r[..]).collect::>(); @@ -494,9 +488,7 @@ mod tests { fn test_fast_aggregated_verify() { let n = 20; let mut rng = thread_rng(); - let sks: Vec<_> = (0..n) - .map(|_| SecretKey::random(&mut rng).unwrap()) - .collect(); + let sks: Vec<_> = (0..n).map(|_| SecretKey::random(&mut rng).unwrap()).collect(); let pks: Vec<_> = sks.iter().map(|sk| sk.public_key()).collect(); let msg = "message".as_bytes(); diff --git a/src/deneb/beacon_block.rs b/src/deneb/beacon_block.rs index c71fa505d..f018859af 100644 --- a/src/deneb/beacon_block.rs +++ b/src/deneb/beacon_block.rs @@ -1,11 +1,13 @@ -use crate::altair::SyncAggregate; -use crate::capella::SignedBlsToExecutionChange; -use crate::deneb::ExecutionPayload; -use crate::kzg::KzgCommitment; -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + altair::SyncAggregate, + capella::SignedBlsToExecutionChange, + deneb::ExecutionPayload, + kzg::KzgCommitment, + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize, PartialEq, Eq)] diff --git a/src/deneb/beacon_state.rs b/src/deneb/beacon_state.rs index 059ce612d..80b909786 100644 --- a/src/deneb/beacon_state.rs +++ b/src/deneb/beacon_state.rs @@ -1,11 +1,9 @@ -use crate::altair::SyncCommittee; -use crate::capella::HistoricalSummary; -use crate::deneb::ExecutionPayloadHeader; -use crate::phase0::{ - BeaconBlockHeader, Checkpoint, Eth1Data, Fork, Validator, JUSTIFICATION_BITS_LENGTH, -}; -use crate::primitives::{ - Bytes32, Gwei, ParticipationFlags, Root, Slot, ValidatorIndex, WithdrawalIndex, +use crate::{ + altair::SyncCommittee, + capella::HistoricalSummary, + deneb::ExecutionPayloadHeader, + phase0::{BeaconBlockHeader, Checkpoint, Eth1Data, Fork, Validator, JUSTIFICATION_BITS_LENGTH}, + primitives::{Bytes32, Gwei, ParticipationFlags, Root, Slot, ValidatorIndex, WithdrawalIndex}, }; use ssz_rs::prelude::*; diff --git a/src/deneb/blinded_beacon_block.rs b/src/deneb/blinded_beacon_block.rs index 3537f38c7..d1968ad85 100644 --- a/src/deneb/blinded_beacon_block.rs +++ b/src/deneb/blinded_beacon_block.rs @@ -1,11 +1,13 @@ -use crate::altair::SyncAggregate; -use crate::capella::SignedBlsToExecutionChange; -use crate::deneb::ExecutionPayloadHeader; -use crate::kzg::KzgCommitment; -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + altair::SyncAggregate, + capella::SignedBlsToExecutionChange, + deneb::ExecutionPayloadHeader, + kzg::KzgCommitment, + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize)] diff --git a/src/deneb/blinded_blob_sidecar.rs b/src/deneb/blinded_blob_sidecar.rs index 8e53672ef..0ddf5755a 100644 --- a/src/deneb/blinded_blob_sidecar.rs +++ b/src/deneb/blinded_blob_sidecar.rs @@ -1,5 +1,7 @@ -use crate::kzg::{KzgCommitment, KzgProof}; -use crate::primitives::{BlobIndex, BlsSignature, Root, Slot, ValidatorIndex}; +use crate::{ + kzg::{KzgCommitment, KzgProof}, + primitives::{BlobIndex, BlsSignature, Root, Slot, ValidatorIndex}, +}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize, PartialEq, Eq)] diff --git a/src/deneb/blob_sidecar.rs b/src/deneb/blob_sidecar.rs index 53ca0cda4..29766f886 100644 --- a/src/deneb/blob_sidecar.rs +++ b/src/deneb/blob_sidecar.rs @@ -1,6 +1,8 @@ -use crate::kzg::{KzgCommitment, KzgProof}; -use crate::primitives::{BlobIndex, BlsSignature, Root, Slot, ValidatorIndex}; -use crate::ssz::ByteVector; +use crate::{ + kzg::{KzgCommitment, KzgProof}, + primitives::{BlobIndex, BlsSignature, Root, Slot, ValidatorIndex}, + ssz::ByteVector, +}; use ssz_rs::prelude::*; pub type Blob = ByteVector; diff --git a/src/deneb/execution.rs b/src/deneb/execution.rs index b9924e2dd..b15c791f3 100644 --- a/src/deneb/execution.rs +++ b/src/deneb/execution.rs @@ -1,8 +1,10 @@ -use crate::bellatrix::Transaction; -use crate::capella::Withdrawal; -use crate::primitives::{Bytes32, ExecutionAddress, Hash32, Root, U256}; -use crate::ssz::{ByteList, ByteVector}; -use crate::state_transition::{self, Error}; +use crate::{ + bellatrix::Transaction, + capella::Withdrawal, + primitives::{Bytes32, ExecutionAddress, Hash32, Root, U256}, + ssz::{ByteList, ByteVector}, + state_transition::{self, Error}, +}; use ssz_rs::prelude::*; #[derive(Default, Debug, Clone, SimpleSerialize, PartialEq, Eq)] diff --git a/src/deneb/mod.rs b/src/deneb/mod.rs index d5f6ed444..12299eb9a 100644 --- a/src/deneb/mod.rs +++ b/src/deneb/mod.rs @@ -19,19 +19,21 @@ pub use execution::*; pub use networking::*; pub use presets::Preset; -pub use crate::altair::{ - SyncAggregate, SyncAggregatorSelectionData, SyncCommittee, PARTICIPATION_FLAG_WEIGHTS, - PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, - TIMELY_TARGET_FLAG_INDEX, WEIGHT_DENOMINATOR, -}; -pub use crate::bellatrix::Transaction; -pub use crate::capella::{BlsToExecutionChange, SignedBlsToExecutionChange, Withdrawal}; -pub use crate::phase0::{ - Attestation, AttestationData, AttesterSlashing, BeaconBlockHeader, Checkpoint, Deposit, - DepositData, DepositMessage, Eth1Block, Eth1Data, Fork, ForkData, HistoricalSummary, - IndexedAttestation, ProposerSlashing, SignedBeaconBlockHeader, SignedVoluntaryExit, - SigningData, Validator, VoluntaryExit, BASE_REWARDS_PER_EPOCH, DEPOSIT_CONTRACT_TREE_DEPTH, - JUSTIFICATION_BITS_LENGTH, +pub use crate::{ + altair::{ + SyncAggregate, SyncAggregatorSelectionData, SyncCommittee, PARTICIPATION_FLAG_WEIGHTS, + PROPOSER_WEIGHT, SYNC_REWARD_WEIGHT, TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, + TIMELY_TARGET_FLAG_INDEX, WEIGHT_DENOMINATOR, + }, + bellatrix::Transaction, + capella::{BlsToExecutionChange, SignedBlsToExecutionChange, Withdrawal}, + phase0::{ + Attestation, AttestationData, AttesterSlashing, BeaconBlockHeader, Checkpoint, Deposit, + DepositData, DepositMessage, Eth1Block, Eth1Data, Fork, ForkData, HistoricalSummary, + IndexedAttestation, ProposerSlashing, SignedBeaconBlockHeader, SignedVoluntaryExit, + SigningData, Validator, VoluntaryExit, BASE_REWARDS_PER_EPOCH, DEPOSIT_CONTRACT_TREE_DEPTH, + JUSTIFICATION_BITS_LENGTH, + }, }; pub mod mainnet { diff --git a/src/deneb/presets/mainnet.rs b/src/deneb/presets/mainnet.rs index 372fda904..5bc64c3d4 100644 --- a/src/deneb/presets/mainnet.rs +++ b/src/deneb/presets/mainnet.rs @@ -1,24 +1,23 @@ -pub use crate::altair::mainnet::SYNC_COMMITTEE_SIZE; -pub use crate::altair::mainnet::{ - AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, - IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, - SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, - SyncCommitteeMessage, -}; -pub use crate::bellatrix::mainnet::Transaction; -pub use crate::bellatrix::mainnet::{ - BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, - MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, -}; -pub use crate::capella::mainnet::{MAX_BLS_TO_EXECUTION_CHANGES, MAX_WITHDRAWALS_PER_PAYLOAD}; -use crate::deneb; -use crate::deneb::presets::Preset; -pub use crate::phase0::mainnet::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +pub use crate::{ + altair::mainnet::{ + AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, + IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, + SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, + SyncCommitteeMessage, SYNC_COMMITTEE_SIZE, + }, + bellatrix::mainnet::{ + Transaction, BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, + MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, + }, + capella::mainnet::{MAX_BLS_TO_EXECUTION_CHANGES, MAX_WITHDRAWALS_PER_PAYLOAD}, + phase0::mainnet::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, }; +use crate::{deneb, deneb::presets::Preset}; pub use deneb::*; diff --git a/src/deneb/presets/minimal.rs b/src/deneb/presets/minimal.rs index 956c2308f..9108a2d23 100644 --- a/src/deneb/presets/minimal.rs +++ b/src/deneb/presets/minimal.rs @@ -1,24 +1,23 @@ -pub use crate::altair::minimal::SYNC_COMMITTEE_SIZE; -pub use crate::altair::minimal::{ - AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, - IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, - SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, - SyncCommitteeMessage, -}; -pub use crate::bellatrix::minimal::Transaction; -pub use crate::bellatrix::minimal::{ - BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, - MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, -}; -pub use crate::capella::minimal::{MAX_BLS_TO_EXECUTION_CHANGES, MAX_WITHDRAWALS_PER_PAYLOAD}; -use crate::deneb; -use crate::deneb::presets::Preset; -pub use crate::phase0::minimal::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +pub use crate::{ + altair::minimal::{ + AggregateAndProof, Attestation, AttesterSlashing, ContributionAndProof, HistoricalBatch, + IndexedAttestation, LightClientUpdate, PendingAttestation, SignedAggregateAndProof, + SignedContributionAndProof, SyncAggregate, SyncCommittee, SyncCommitteeContribution, + SyncCommitteeMessage, SYNC_COMMITTEE_SIZE, + }, + bellatrix::minimal::{ + Transaction, BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, + MAX_TRANSACTIONS_PER_PAYLOAD, PROPORTIONAL_SLASHING_MULTIPLIER_BELLATRIX, + }, + capella::minimal::{MAX_BLS_TO_EXECUTION_CHANGES, MAX_WITHDRAWALS_PER_PAYLOAD}, + phase0::minimal::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, }; +use crate::{deneb, deneb::presets::Preset}; pub use deneb::*; diff --git a/src/kzg.rs b/src/kzg.rs index b87d4c537..2718124c1 100644 --- a/src/kzg.rs +++ b/src/kzg.rs @@ -1,5 +1,4 @@ -use crate::primitives::Bytes32; -use crate::ssz::ByteVector; +use crate::{primitives::Bytes32, ssz::ByteVector}; use ssz_rs::prelude::*; pub const KZG_COMMITMENT_BYTES_LEN: usize = 48; diff --git a/src/networking.rs b/src/networking.rs index 828f1b841..df2e8fab9 100644 --- a/src/networking.rs +++ b/src/networking.rs @@ -3,8 +3,7 @@ pub use multiaddr::Multiaddr; use multihash::{Code, Error, Multihash}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -use std::fmt; -use std::{convert::TryFrom, str::FromStr}; +use std::{convert::TryFrom, fmt, str::FromStr}; use thiserror::Error; pub const MAX_INLINE_KEY_LENGTH: usize = 42; @@ -142,9 +141,6 @@ mod tests { fn test_id_str_format() { let id_repr = "QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N"; let id: PeerId = PeerId::from_str(id_repr).unwrap(); - assert_eq!( - format!("{id}"), - "QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N" - ) + assert_eq!(format!("{id}"), "QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N") } } diff --git a/src/phase0/beacon_block.rs b/src/phase0/beacon_block.rs index 5b6e32221..e7cc6eacf 100644 --- a/src/phase0/beacon_block.rs +++ b/src/phase0/beacon_block.rs @@ -1,7 +1,9 @@ -use crate::phase0::{ - Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, +use crate::{ + phase0::{ + Attestation, AttesterSlashing, Deposit, Eth1Data, ProposerSlashing, SignedVoluntaryExit, + }, + primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}, }; -use crate::primitives::{BlsSignature, Bytes32, Root, Slot, ValidatorIndex}; use ssz_rs::prelude::*; #[derive(Default, Debug, SimpleSerialize, Clone, PartialEq, Eq)] diff --git a/src/phase0/beacon_state.rs b/src/phase0/beacon_state.rs index 2c40b6580..24bd21216 100644 --- a/src/phase0/beacon_state.rs +++ b/src/phase0/beacon_state.rs @@ -1,8 +1,10 @@ -use crate::phase0::{ - BeaconBlockHeader, Checkpoint, Eth1Data, Fork, PendingAttestation, Validator, - JUSTIFICATION_BITS_LENGTH, +use crate::{ + phase0::{ + BeaconBlockHeader, Checkpoint, Eth1Data, Fork, PendingAttestation, Validator, + JUSTIFICATION_BITS_LENGTH, + }, + primitives::{Bytes32, Epoch, Gwei, Root, Slot}, }; -use crate::primitives::{Bytes32, Epoch, Gwei, Root, Slot}; use ssz_rs::prelude::*; pub(super) const fn get_eth1_data_votes_bound( @@ -26,17 +28,18 @@ pub struct HistoricalBatch { pub state_roots: Vector, } -/// `HistoricalBatch` is to be used as a "summary" Merkleized container and is simply a wrapper around -/// `block_roots` & `state_roots` (and their respective Merkle roots). Instead of the `_roots` -/// being of type `Vector`, a single `Root` is pulled out to allow Merkleization of each root to be -/// performed manually (using the `ssz_rs` crate). +/// `HistoricalBatch` is to be used as a "summary" Merkleized container and is simply a wrapper +/// around `block_roots` & `state_roots` (and their respective Merkle roots). Instead of the +/// `_roots` being of type `Vector`, a single `Root` is pulled out to allow Merkleization +/// of each root to be performed manually (using the `ssz_rs` crate). /// -/// Instead of requiring a full copy of the roots, the container is summarized as `HistoricalSummary` -/// with `block_summary_root` & `state_summary_root`. +/// Instead of requiring a full copy of the roots, the container is summarized as +/// `HistoricalSummary` with `block_summary_root` & `state_summary_root`. /// /// This design decision was chosen for memory optimization purposes, for example, in the /// `state_transition` crate's `process_historical_roots_update` function. Also note that the -/// `HistoricalBatch` container has no need for serialization, otherwise, this design would pose an issue. +/// `HistoricalBatch` container has no need for serialization, otherwise, this design would pose an +/// issue. /// /// For more information, see the comment here: #[derive(Default, Debug, SimpleSerialize, Clone, PartialEq, Eq)] diff --git a/src/phase0/block_processing.rs b/src/phase0/block_processing.rs index f97bf9658..24d623079 100644 --- a/src/phase0/block_processing.rs +++ b/src/phase0/block_processing.rs @@ -1,15 +1,15 @@ use crate::phase0 as spec; -use crate::crypto::{hash, verify_signature}; -use crate::primitives::{ - BlsPublicKey, Bytes32, DomainType, Gwei, ValidatorIndex, FAR_FUTURE_EPOCH, -}; -use crate::signing::compute_signing_root; -use crate::ssz::ByteVector; -use crate::state_transition::{ - invalid_header_error, invalid_operation_error, Context, InvalidAttestation, - InvalidAttesterSlashing, InvalidBeaconBlockHeader, InvalidDeposit, InvalidOperation, - InvalidProposerSlashing, InvalidVoluntaryExit, Result, +use crate::{ + crypto::{hash, verify_signature}, + primitives::{BlsPublicKey, Bytes32, DomainType, Gwei, ValidatorIndex, FAR_FUTURE_EPOCH}, + signing::compute_signing_root, + ssz::ByteVector, + state_transition::{ + invalid_header_error, invalid_operation_error, Context, InvalidAttestation, + InvalidAttesterSlashing, InvalidBeaconBlockHeader, InvalidDeposit, InvalidOperation, + InvalidProposerSlashing, InvalidVoluntaryExit, Result, + }, }; use spec::{ compute_domain, compute_epoch_at_slot, get_beacon_committee, get_beacon_proposer_index, @@ -52,7 +52,7 @@ pub fn process_proposer_slashing< if header_1.slot != header_2.slot { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::SlotMismatch(header_1.slot, header_2.slot), - ))); + ))) } if header_1.proposer_index != header_2.proposer_index { @@ -61,13 +61,13 @@ pub fn process_proposer_slashing< header_1.proposer_index, header_2.proposer_index, ), - ))); + ))) } if header_1 == header_2 { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::HeadersAreEqual(header_1.clone()), - ))); + ))) } let proposer_index = header_1.proposer_index; @@ -79,21 +79,20 @@ pub fn process_proposer_slashing< if !is_slashable_validator(proposer, get_current_epoch(state, context)) { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::ProposerIsNotSlashable(header_1.proposer_index), - ))); + ))) } let epoch = compute_epoch_at_slot(header_1.slot, context); let domain = get_domain(state, DomainType::BeaconProposer, Some(epoch), context)?; - for signed_header in [ - &mut proposer_slashing.signed_header_1, - &mut proposer_slashing.signed_header_2, - ] { + for signed_header in + [&mut proposer_slashing.signed_header_1, &mut proposer_slashing.signed_header_2] + { let signing_root = compute_signing_root(&mut signed_header.message, domain)?; let public_key = &proposer.public_key; if verify_signature(public_key, signing_root.as_ref(), &signed_header.signature).is_err() { return Err(invalid_operation_error(InvalidOperation::ProposerSlashing( InvalidProposerSlashing::InvalidSignature(signed_header.signature.clone()), - ))); + ))) } } @@ -132,7 +131,7 @@ pub fn process_attester_slashing< Box::new(attestation_1.data.clone()), Box::new(attestation_2.data.clone()), ), - ))); + ))) } is_valid_indexed_attestation(state, attestation_1, context)?; @@ -142,10 +141,7 @@ pub fn process_attester_slashing< let indices_1: HashSet = HashSet::from_iter(attestation_1.attesting_indices.iter().cloned()); let indices_2 = HashSet::from_iter(attestation_2.attesting_indices.iter().cloned()); - let mut indices = indices_1 - .intersection(&indices_2) - .cloned() - .collect::>(); + let mut indices = indices_1.intersection(&indices_2).cloned().collect::>(); indices.sort_unstable(); let mut slashed_any = false; @@ -201,7 +197,7 @@ pub fn process_attestation< target: data.target.epoch, current: current_epoch, }, - ))); + ))) } let attestation_epoch = compute_epoch_at_slot(data.slot, context); @@ -212,7 +208,7 @@ pub fn process_attestation< epoch: attestation_epoch, target: data.target.epoch, }, - ))); + ))) } let attestation_has_delay = data.slot + context.min_attestation_inclusion_delay <= state.slot; @@ -226,17 +222,14 @@ pub fn process_attestation< lower_bound: data.slot + context.slots_per_epoch, upper_bound: data.slot + context.min_attestation_inclusion_delay, }, - ))); + ))) } let committee_count = get_committee_count_per_slot(state, data.target.epoch, context); if data.index >= committee_count { return Err(invalid_operation_error(InvalidOperation::Attestation( - InvalidAttestation::InvalidIndex { - index: data.index, - upper_bound: committee_count, - }, - ))); + InvalidAttestation::InvalidIndex { index: data.index, upper_bound: committee_count }, + ))) } let committee = get_beacon_committee(state, data.slot, data.index, context)?; @@ -247,7 +240,7 @@ pub fn process_attestation< expected_length: committee.len(), length: attestation.aggregation_bits.len(), }, - ))); + ))) } // NOTE: swap order of these wrt the spec to avoid mutation @@ -272,7 +265,7 @@ pub fn process_attestation< source_checkpoint: data.source.clone(), current: current_epoch, }, - ))); + ))) } state.current_epoch_attestations.push(pending_attestation); } else { @@ -283,7 +276,7 @@ pub fn process_attestation< source_checkpoint: data.source.clone(), current: current_epoch, }, - ))); + ))) } state.previous_epoch_attestations.push(pending_attestation); } @@ -344,14 +337,8 @@ pub fn process_deposit< let root = &state.eth1_data.deposit_root; if !is_valid_merkle_branch(&leaf, branch.iter(), depth, index, root) { return Err(invalid_operation_error(InvalidOperation::Deposit( - InvalidDeposit::InvalidProof { - leaf, - branch, - depth, - index, - root: *root, - }, - ))); + InvalidDeposit::InvalidProof { leaf, branch, depth, index, root: *root }, + ))) } state.eth1_deposit_index += 1; @@ -371,19 +358,13 @@ pub fn process_deposit< if verify_signature(public_key, signing_root.as_ref(), &deposit.data.signature).is_err() { // NOTE: explicitly return with no error and also no further mutations to `state` - return Ok(()); + return Ok(()) } - state - .validators - .push(get_validator_from_deposit(deposit, context)); + state.validators.push(get_validator_from_deposit(deposit, context)); state.balances.push(amount); } else { - let index = state - .validators - .iter() - .position(|v| &v.public_key == public_key) - .unwrap(); + let index = state.validators.iter().position(|v| &v.public_key == public_key).unwrap(); increase_balance(state, index, amount); } @@ -415,20 +396,17 @@ pub fn process_voluntary_exit< context: &Context, ) -> Result<()> { let voluntary_exit = &mut signed_voluntary_exit.message; - let validator = state - .validators - .get(voluntary_exit.validator_index) - .ok_or_else(|| { - invalid_operation_error(InvalidOperation::VoluntaryExit( - InvalidVoluntaryExit::InvalidIndex(voluntary_exit.validator_index), - )) - })?; + let validator = state.validators.get(voluntary_exit.validator_index).ok_or_else(|| { + invalid_operation_error(InvalidOperation::VoluntaryExit( + InvalidVoluntaryExit::InvalidIndex(voluntary_exit.validator_index), + )) + })?; let current_epoch = get_current_epoch(state, context); if !is_active_validator(validator, current_epoch) { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( InvalidVoluntaryExit::InactiveValidator(current_epoch), - ))); + ))) } if validator.exit_epoch != FAR_FUTURE_EPOCH { @@ -437,16 +415,13 @@ pub fn process_voluntary_exit< index: voluntary_exit.validator_index, epoch: validator.exit_epoch, }, - ))); + ))) } if current_epoch < voluntary_exit.epoch { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( - InvalidVoluntaryExit::EarlyExit { - current_epoch, - exit_epoch: voluntary_exit.epoch, - }, - ))); + InvalidVoluntaryExit::EarlyExit { current_epoch, exit_epoch: voluntary_exit.epoch }, + ))) } let minimum_time_active = @@ -457,28 +432,19 @@ pub fn process_voluntary_exit< current_epoch, minimum_time_active, }, - ))); + ))) } - let domain = get_domain( - state, - DomainType::VoluntaryExit, - Some(voluntary_exit.epoch), - context, - )?; + let domain = get_domain(state, DomainType::VoluntaryExit, Some(voluntary_exit.epoch), context)?; let signing_root = compute_signing_root(voluntary_exit, domain)?; let public_key = &validator.public_key; - if verify_signature( - public_key, - signing_root.as_ref(), - &signed_voluntary_exit.signature, - ) - .is_err() + if verify_signature(public_key, signing_root.as_ref(), &signed_voluntary_exit.signature) + .is_err() { return Err(invalid_operation_error(InvalidOperation::VoluntaryExit( InvalidVoluntaryExit::InvalidSignature(signed_voluntary_exit.signature.clone()), - ))); + ))) } initiate_validator_exit(state, voluntary_exit.validator_index, context); @@ -522,41 +488,33 @@ pub fn process_block_header< context: &Context, ) -> Result<()> { if block.slot != state.slot { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::StateSlotMismatch { - state_slot: state.slot, - block_slot: block.slot, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::StateSlotMismatch { + state_slot: state.slot, + block_slot: block.slot, + })) } if block.slot <= state.latest_block_header.slot { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::OlderThanLatestBlockHeader { - block_slot: block.slot, - latest_block_header_slot: state.latest_block_header.slot, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::OlderThanLatestBlockHeader { + block_slot: block.slot, + latest_block_header_slot: state.latest_block_header.slot, + })) } let proposer_index = get_beacon_proposer_index(state, context)?; if block.proposer_index != proposer_index { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ProposerIndexMismatch { - block_proposer_index: block.proposer_index, - proposer_index, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ProposerIndexMismatch { + block_proposer_index: block.proposer_index, + proposer_index, + })) } let expected_parent_root = state.latest_block_header.hash_tree_root()?; if block.parent_root != expected_parent_root { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ParentBlockRootMismatch { - expected: expected_parent_root, - provided: block.parent_root, - }, - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ParentBlockRootMismatch { + expected: expected_parent_root, + provided: block.parent_root, + })) } state.latest_block_header = BeaconBlockHeader { @@ -569,20 +527,14 @@ pub fn process_block_header< let proposer = &state.validators[block.proposer_index]; if proposer.slashed { - return Err(invalid_header_error( - InvalidBeaconBlockHeader::ProposerSlashed(proposer_index), - )); + return Err(invalid_header_error(InvalidBeaconBlockHeader::ProposerSlashed(proposer_index))) } Ok(()) } pub fn xor(a: &Bytes32, b: &Bytes32) -> Bytes32 { - let inner = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a ^ b) - .collect::>(); + let inner = a.iter().zip(b.iter()).map(|(a, b)| a ^ b).collect::>(); ByteVector::<32>::try_from(inner.as_ref()).unwrap() } @@ -629,22 +581,11 @@ pub fn process_randao< let domain = get_domain(state, DomainType::Randao, Some(epoch), context)?; let signing_root = compute_signing_root(&mut epoch, domain)?; - if verify_signature( - &proposer.public_key, - signing_root.as_ref(), - &body.randao_reveal, - ) - .is_err() - { - return Err(invalid_operation_error(InvalidOperation::Randao( - body.randao_reveal.clone(), - ))); + if verify_signature(&proposer.public_key, signing_root.as_ref(), &body.randao_reveal).is_err() { + return Err(invalid_operation_error(InvalidOperation::Randao(body.randao_reveal.clone()))) } - let mix = xor( - get_randao_mix(state, epoch), - &hash(body.randao_reveal.as_ref()), - ); + let mix = xor(get_randao_mix(state, epoch), &hash(body.randao_reveal.as_ref())); let mix_index = epoch % context.epochs_per_historical_vector; state.randao_mixes[mix_index as usize] = mix; Ok(()) @@ -687,11 +628,8 @@ pub fn process_eth1_data< ) { state.eth1_data_votes.push(body.eth1_data.clone()); - let votes_count = state - .eth1_data_votes - .iter() - .filter(|&vote| *vote == body.eth1_data) - .count() as u64; + let votes_count = + state.eth1_data_votes.iter().filter(|&vote| *vote == body.eth1_data).count() as u64; if votes_count * 2 > context.epochs_per_eth1_voting_period * context.slots_per_epoch { state.eth1_data = body.eth1_data.clone(); @@ -744,7 +682,7 @@ pub fn process_operations< expected: expected_deposit_count, count: body.deposits.len(), }, - ))); + ))) } body.proposer_slashings @@ -753,12 +691,8 @@ pub fn process_operations< body.attester_slashings .iter_mut() .try_for_each(|op| process_attester_slashing(state, op, context))?; - body.attestations - .iter() - .try_for_each(|op| process_attestation(state, op, context))?; - body.deposits - .iter_mut() - .try_for_each(|op| process_deposit(state, op, context))?; + body.attestations.iter().try_for_each(|op| process_attestation(state, op, context))?; + body.deposits.iter_mut().try_for_each(|op| process_deposit(state, op, context))?; body.voluntary_exits .iter_mut() .try_for_each(|op| process_voluntary_exit(state, op, context))?; diff --git a/src/phase0/epoch_processing.rs b/src/phase0/epoch_processing.rs index 5e4dd0959..d0dc4141b 100644 --- a/src/phase0/epoch_processing.rs +++ b/src/phase0/epoch_processing.rs @@ -1,7 +1,9 @@ use crate::phase0 as spec; -use crate::primitives::{Epoch, Gwei, ValidatorIndex, GENESIS_EPOCH}; -use crate::state_transition::{Context, Error, Result}; +use crate::{ + primitives::{Epoch, Gwei, ValidatorIndex, GENESIS_EPOCH}, + state_transition::{Context, Error, Result}, +}; use integer_sqrt::IntegerSquareRoot; use spec::{ compute_activation_exit_epoch, decrease_balance, get_attesting_indices, get_block_root, @@ -12,8 +14,7 @@ use spec::{ PendingAttestation, BASE_REWARDS_PER_EPOCH, JUSTIFICATION_BITS_LENGTH, }; use ssz_rs::prelude::*; -use std::collections::HashSet; -use std::mem; +use std::{collections::HashSet, mem}; pub fn get_matching_source_attestations< 'a, @@ -48,7 +49,7 @@ pub fn get_matching_source_attestations< requested: epoch, previous: previous_epoch, current: current_epoch, - }); + }) } if epoch == current_epoch { @@ -85,7 +86,7 @@ pub fn get_matching_target_attestations< let source_attestations = get_matching_source_attestations(state, epoch, context)?; let mut result = vec![]; if source_attestations.is_empty() { - return Ok(result); + return Ok(result) } let block_root = get_block_root(state, epoch, context)?; @@ -189,9 +190,10 @@ pub fn process_justification_and_finalization< context: &Context, ) -> Result<()> { // Initial FFG checkpoint values have a `0x00` stub for `root`. - // Skip FFG updates in the first two epochs to avoid corner cases that might result in modifying this stub. + // Skip FFG updates in the first two epochs to avoid corner cases that might result in modifying + // this stub. if get_current_epoch(state, context) <= GENESIS_EPOCH + 1 { - return Ok(()); + return Ok(()) } let previous_attestations = get_matching_target_attestations(state, get_previous_epoch(state, context), context)?; @@ -231,7 +233,8 @@ pub fn process_rewards_and_penalties< >, context: &Context, ) -> Result<()> { - // No rewards are applied at the end of `GENESIS_EPOCH` because rewards are for work done in the previous epoch + // No rewards are applied at the end of `GENESIS_EPOCH` because rewards are for work done in the + // previous epoch let current_epoch = get_current_epoch(state, context); if current_epoch != GENESIS_EPOCH { let (rewards, penalties) = get_attestation_deltas(state, context)?; @@ -275,26 +278,27 @@ pub fn process_registry_updates< validator.activation_eligibility_epoch = current_epoch + 1; } - if is_active_validator(validator, current_epoch) - && validator.effective_balance <= context.ejection_balance + if is_active_validator(validator, current_epoch) && + validator.effective_balance <= context.ejection_balance { initiate_validator_exit(state, i, context); } } // Queue validators eligible for activation and not yet dequeued for activation - let mut activation_queue = state - .validators - .iter() - .enumerate() - .filter_map(|(index, validator)| { - if is_eligible_for_activation(state, validator) { - Some(index) - } else { - None - } - }) - .collect::>(); + let mut activation_queue = + state + .validators + .iter() + .enumerate() + .filter_map(|(index, validator)| { + if is_eligible_for_activation(state, validator) { + Some(index) + } else { + None + } + }) + .collect::>(); // Order by the sequence of activation_eligibility_epoch setting and then index activation_queue.sort_by(|&i, &j| { let a = &state.validators[i]; @@ -304,10 +308,7 @@ pub fn process_registry_updates< // Dequeued validators for activation up to churn limit let activation_exit_epoch = compute_activation_exit_epoch(current_epoch, context); - for i in activation_queue - .into_iter() - .take(get_validator_churn_limit(state, context)) - { + for i in activation_queue.into_iter().take(get_validator_churn_limit(state, context)) { let validator = &mut state.validators[i]; validator.activation_epoch = activation_exit_epoch; } @@ -344,8 +345,8 @@ pub fn process_slashings< for i in 0..state.validators.len() { let validator = &state.validators[i]; - if validator.slashed - && (epoch + context.epochs_per_slashings_vector / 2) == validator.withdrawable_epoch + if validator.slashed && + (epoch + context.epochs_per_slashings_vector / 2) == validator.withdrawable_epoch { let increment = context.effective_balance_increment; let penalty_numerator = @@ -416,8 +417,8 @@ pub fn process_effective_balance_updates< for i in 0..state.validators.len() { let validator = &mut state.validators[i]; let balance = state.balances[i]; - if balance + downward_threshold < validator.effective_balance - || validator.effective_balance + upward_threshold < balance + if balance + downward_threshold < validator.effective_balance || + validator.effective_balance + upward_threshold < balance { validator.effective_balance = Gwei::min( balance - balance % context.effective_balance_increment, @@ -512,9 +513,7 @@ pub fn process_historical_roots_update< block_summary_root: state.block_roots.hash_tree_root()?, state_summary_root: state.state_roots.hash_tree_root()?, }; - state - .historical_roots - .push(historical_batch.hash_tree_root()?) + state.historical_roots.push(historical_batch.hash_tree_root()?) } Ok(()) } @@ -611,9 +610,7 @@ pub fn weigh_justification_and_finalization< // Process justifications state.previous_justified_checkpoint = state.current_justified_checkpoint.clone(); - state - .justification_bits - .copy_within(..JUSTIFICATION_BITS_LENGTH - 1, 1); + state.justification_bits.copy_within(..JUSTIFICATION_BITS_LENGTH - 1, 1); state.justification_bits.set(0, false); if previous_epoch_target_balance * 3 >= total_active_balance * 2 { state.current_justified_checkpoint = Checkpoint { @@ -677,9 +674,9 @@ pub fn get_base_reward< ) -> Result { let total_balance = get_total_active_balance(state, context)?; let effective_balance = state.validators[index].effective_balance; - Ok(effective_balance * context.base_reward_factor - / total_balance.integer_sqrt() - / BASE_REWARDS_PER_EPOCH) + Ok(effective_balance * context.base_reward_factor / + total_balance.integer_sqrt() / + BASE_REWARDS_PER_EPOCH) } pub fn get_proposer_reward< @@ -981,8 +978,8 @@ pub fn get_inactivity_penalty_deltas< BASE_REWARDS_PER_EPOCH * base_reward - get_proposer_reward(state, i, context)?; if !matching_target_attesting_indices.contains(&i) { let effective_balance = state.validators[i].effective_balance; - penalties[i] += effective_balance * get_finality_delay(state, context) - / context.inactivity_penalty_quotient; + penalties[i] += effective_balance * get_finality_delay(state, context) / + context.inactivity_penalty_quotient; } } } diff --git a/src/phase0/genesis.rs b/src/phase0/genesis.rs index 37ef1ffc9..16b94bd6b 100644 --- a/src/phase0/genesis.rs +++ b/src/phase0/genesis.rs @@ -1,7 +1,9 @@ use crate::phase0 as spec; -use crate::primitives::{Gwei, Hash32, GENESIS_EPOCH}; -use crate::state_transition::{Context, Result}; +use crate::{ + primitives::{Gwei, Hash32, GENESIS_EPOCH}, + state_transition::{Context, Result}, +}; use spec::{ get_active_validator_indices, process_deposit, BeaconBlock, BeaconBlockBody, BeaconBlockHeader, BeaconState, Deposit, DepositData, Eth1Data, Fork, DEPOSIT_DATA_LIST_BOUND, @@ -58,10 +60,7 @@ pub fn initialize_beacon_state_from_eth1< MAX_VOLUNTARY_EXITS, >::default(); let body_root = latest_block_body.hash_tree_root()?; - let latest_block_header = BeaconBlockHeader { - body_root, - ..Default::default() - }; + let latest_block_header = BeaconBlockHeader { body_root, ..Default::default() }; let randao_mixes = Vector::try_from( std::iter::repeat(eth1_block_hash) .take(context.epochs_per_historical_vector as usize) @@ -126,13 +125,13 @@ pub fn is_valid_genesis_state< context: &Context, ) -> bool { if state.genesis_time < context.min_genesis_time { - return false; + return false } - if get_active_validator_indices(state, GENESIS_EPOCH).len() - < context.min_genesis_active_validator_count + if get_active_validator_indices(state, GENESIS_EPOCH).len() < + context.min_genesis_active_validator_count { - return false; + return false } true @@ -173,8 +172,5 @@ pub fn get_genesis_block< MAX_VOLUNTARY_EXITS, >, > { - Ok(BeaconBlock { - state_root: genesis_state.hash_tree_root()?, - ..Default::default() - }) + Ok(BeaconBlock { state_root: genesis_state.hash_tree_root()?, ..Default::default() }) } diff --git a/src/phase0/helpers.rs b/src/phase0/helpers.rs index 36864a18f..d791bd89c 100644 --- a/src/phase0/helpers.rs +++ b/src/phase0/helpers.rs @@ -1,30 +1,31 @@ use crate::phase0 as spec; -use crate::crypto::{fast_aggregate_verify, hash, verify_signature}; -use crate::primitives::{ - Bytes32, CommitteeIndex, Domain, DomainType, Epoch, ForkDigest, Gwei, Root, Slot, - ValidatorIndex, Version, FAR_FUTURE_EPOCH, GENESIS_EPOCH, -}; -use crate::signing::compute_signing_root; -use crate::state_transition::{ - invalid_operation_error, Context, Error, InvalidAttestation, InvalidIndexedAttestation, - InvalidOperation, Result, +use crate::{ + crypto::{fast_aggregate_verify, hash, verify_signature}, + primitives::{ + Bytes32, CommitteeIndex, Domain, DomainType, Epoch, ForkDigest, Gwei, Root, Slot, + ValidatorIndex, Version, FAR_FUTURE_EPOCH, GENESIS_EPOCH, + }, + signing::compute_signing_root, + state_transition::{ + invalid_operation_error, Context, Error, InvalidAttestation, InvalidIndexedAttestation, + InvalidOperation, Result, + }, }; use spec::{ Attestation, AttestationData, BeaconState, ForkData, IndexedAttestation, SignedBeaconBlock, Validator, }; use ssz_rs::prelude::*; -use std::cmp; -use std::collections::HashSet; +use std::{cmp, collections::HashSet}; pub fn is_active_validator(validator: &Validator, epoch: Epoch) -> bool { validator.activation_epoch <= epoch && epoch < validator.exit_epoch } pub fn is_eligible_for_activation_queue(validator: &Validator, context: &Context) -> bool { - validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH - && validator.effective_balance == context.max_effective_balance + validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH && + validator.effective_balance == context.max_effective_balance } pub fn is_eligible_for_activation< @@ -49,14 +50,14 @@ pub fn is_eligible_for_activation< >, validator: &Validator, ) -> bool { - validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch - && validator.activation_epoch == FAR_FUTURE_EPOCH + validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch && + validator.activation_epoch == FAR_FUTURE_EPOCH } pub fn is_slashable_validator(validator: &Validator, epoch: Epoch) -> bool { - !validator.slashed - && validator.activation_epoch <= epoch - && epoch < validator.withdrawable_epoch + !validator.slashed && + validator.activation_epoch <= epoch && + epoch < validator.withdrawable_epoch } pub fn is_slashable_attestation_data(data_1: &AttestationData, data_2: &AttestationData) -> bool { @@ -92,9 +93,9 @@ pub fn is_valid_indexed_attestation< let attesting_indices = &indexed_attestation.attesting_indices; if attesting_indices.is_empty() { - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation(InvalidIndexedAttestation::AttestingIndicesEmpty), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::AttestingIndicesEmpty, + ))) } // List of indices is non-empty given check above. Begin iteration from the second element @@ -103,11 +104,9 @@ pub fn is_valid_indexed_attestation< let mut duplicates = HashSet::new(); for &index in &attesting_indices[1..] { if index < prev { - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation( - InvalidIndexedAttestation::AttestingIndicesNotSorted, - ), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::AttestingIndicesNotSorted, + ))) } if index == prev { duplicates.insert(index); @@ -115,24 +114,18 @@ pub fn is_valid_indexed_attestation< prev = index; } if !duplicates.is_empty() { - return Err(invalid_operation_error( - InvalidOperation::IndexedAttestation(InvalidIndexedAttestation::DuplicateIndices( - Vec::from_iter(duplicates), - )), - )); + return Err(invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::DuplicateIndices(Vec::from_iter(duplicates)), + ))) } let mut public_keys = vec![]; for &index in &attesting_indices[..] { - let public_key = state - .validators - .get(index) - .map(|v| &v.public_key) - .ok_or_else(|| { - invalid_operation_error(InvalidOperation::IndexedAttestation( - InvalidIndexedAttestation::InvalidIndex(index), - )) - })?; + let public_key = state.validators.get(index).map(|v| &v.public_key).ok_or_else(|| { + invalid_operation_error(InvalidOperation::IndexedAttestation( + InvalidIndexedAttestation::InvalidIndex(index), + )) + })?; public_keys.push(public_key); } @@ -143,12 +136,8 @@ pub fn is_valid_indexed_attestation< context, )?; let signing_root = compute_signing_root(&mut indexed_attestation.data, domain)?; - fast_aggregate_verify( - &public_keys, - signing_root.as_ref(), - &indexed_attestation.signature, - ) - .map_err(Into::into) + fast_aggregate_verify(&public_keys, signing_root.as_ref(), &indexed_attestation.signature) + .map_err(Into::into) } pub fn verify_block_signature< @@ -190,10 +179,7 @@ pub fn verify_block_signature< let proposer = state .validators .get(proposer_index) - .ok_or(Error::OutOfBounds { - requested: proposer_index, - bound: state.validators.len(), - })?; + .ok_or(Error::OutOfBounds { requested: proposer_index, bound: state.validators.len() })?; let domain = get_domain(state, DomainType::BeaconProposer, None, context)?; let signing_root = compute_signing_root(&mut signed_block.message, domain)?; @@ -232,12 +218,7 @@ pub fn get_domain< state.fork.current_version }; - compute_domain( - domain_type, - Some(fork_version), - Some(state.genesis_validators_root), - context, - ) + compute_domain(domain_type, Some(fork_version), Some(state.genesis_validators_root), context) } pub fn get_current_epoch< @@ -272,10 +253,7 @@ pub fn compute_shuffled_index( context: &Context, ) -> Result { if index >= index_count { - return Err(Error::InvalidShufflingIndex { - index, - total: index_count, - }); + return Err(Error::InvalidShufflingIndex { index, total: index_count }) } let mut pivot_input = [0u8; 33]; @@ -329,7 +307,7 @@ pub fn compute_proposer_index< context: &Context, ) -> Result { if indices.is_empty() { - return Err(Error::CollectionCannotBeEmpty); + return Err(Error::CollectionCannotBeEmpty) } let max_byte = u8::MAX as u64; let mut i = 0; @@ -347,7 +325,7 @@ pub fn compute_proposer_index< let effective_balance = state.validators[candidate_index].effective_balance; if effective_balance * max_byte >= context.max_effective_balance * random_byte { - return Ok(candidate_index); + return Ok(candidate_index) } i += 1 } @@ -411,12 +389,9 @@ pub fn compute_fork_data_root( current_version: Version, genesis_validators_root: Root, ) -> Result { - ForkData { - current_version, - genesis_validators_root, - } - .hash_tree_root() - .map_err(Error::Merkleization) + ForkData { current_version, genesis_validators_root } + .hash_tree_root() + .map_err(Error::Merkleization) } pub fn get_previous_epoch< @@ -503,7 +478,7 @@ pub fn get_block_root_at_slot< requested: slot, lower_bound: state.slot - 1, upper_bound: state.slot + SLOTS_PER_HISTORICAL_ROOT as Slot, - }); + }) } Ok(&state.block_roots[slot as usize % SLOTS_PER_HISTORICAL_ROOT]) } @@ -656,9 +631,9 @@ pub fn get_committee_count_per_slot< 1, u64::min( context.max_committees_per_slot, - get_active_validator_indices(state, epoch).len() as u64 - / context.slots_per_epoch - / context.target_committee_size, + get_active_validator_indices(state, epoch).len() as u64 / + context.slots_per_epoch / + context.target_committee_size, ), ) as usize } @@ -753,9 +728,7 @@ pub fn get_total_balance< ) -> Result { let total_balance = indices .iter() - .try_fold(Gwei::default(), |acc, i| { - acc.checked_add(state.validators[*i].effective_balance) - }) + .try_fold(Gwei::default(), |acc, i| acc.checked_add(state.validators[*i].effective_balance)) .ok_or(Error::Overflow)?; Ok(u64::max(total_balance, context.effective_balance_increment)) } @@ -854,11 +827,8 @@ pub fn get_attesting_indices< if bits.len() != committee.len() { return Err(invalid_operation_error(InvalidOperation::Attestation( - InvalidAttestation::Bitfield { - expected_length: committee.len(), - length: bits.len(), - }, - ))); + InvalidAttestation::Bitfield { expected_length: committee.len(), length: bits.len() }, + ))) } let mut indices = HashSet::with_capacity(bits.capacity()); @@ -952,7 +922,7 @@ pub fn initiate_validator_exit< context: &Context, ) { if state.validators[index].exit_epoch != FAR_FUTURE_EPOCH { - return; + return } let mut exit_epochs: Vec = state @@ -962,18 +932,12 @@ pub fn initiate_validator_exit< .map(|v| v.exit_epoch) .collect(); - exit_epochs.push(compute_activation_exit_epoch( - get_current_epoch(state, context), - context, - )); + exit_epochs.push(compute_activation_exit_epoch(get_current_epoch(state, context), context)); let mut exit_queue_epoch = *exit_epochs.iter().max().unwrap(); - let exit_queue_churn = state - .validators - .iter() - .filter(|v| v.exit_epoch == exit_queue_epoch) - .count(); + let exit_queue_churn = + state.validators.iter().filter(|v| v.exit_epoch == exit_queue_epoch).count(); if exit_queue_churn >= get_validator_churn_limit(state, context) { exit_queue_epoch += 1 @@ -1031,11 +995,7 @@ pub fn slash_validator< state.validators[slashed_index].effective_balance / context.whistleblower_reward_quotient; let proposer_reward = whistleblower_reward / context.proposer_reward_quotient; increase_balance(state, proposer_index, proposer_reward); - increase_balance( - state, - whistleblower_index, - whistleblower_reward - proposer_reward, - ); + increase_balance(state, whistleblower_index, whistleblower_reward - proposer_reward); Ok(()) } @@ -1063,17 +1023,13 @@ pub fn get_eligible_validator_indices< context: &Context, ) -> impl Iterator + 'a { let previous_epoch = get_previous_epoch(state, context); - state - .validators - .iter() - .enumerate() - .filter_map(move |(i, validator)| { - if is_active_validator(validator, previous_epoch) - || (validator.slashed && previous_epoch + 1 < validator.withdrawable_epoch) - { - Some(i) - } else { - None - } - }) + state.validators.iter().enumerate().filter_map(move |(i, validator)| { + if is_active_validator(validator, previous_epoch) || + (validator.slashed && previous_epoch + 1 < validator.withdrawable_epoch) + { + Some(i) + } else { + None + } + }) } diff --git a/src/phase0/mod.rs b/src/phase0/mod.rs index 834de1bc1..5d149899d 100644 --- a/src/phase0/mod.rs +++ b/src/phase0/mod.rs @@ -35,5 +35,4 @@ pub const DEPOSIT_CONTRACT_TREE_DEPTH: usize = 2usize.pow(5); pub const JUSTIFICATION_BITS_LENGTH: usize = 4; pub const DEPOSIT_DATA_LIST_BOUND: usize = 2usize.pow(DEPOSIT_CONTRACT_TREE_DEPTH as u32); -pub use presets::mainnet; -pub use presets::minimal; +pub use presets::{mainnet, minimal}; diff --git a/src/phase0/operations.rs b/src/phase0/operations.rs index 1f6c6ba37..9cb01e9ad 100644 --- a/src/phase0/operations.rs +++ b/src/phase0/operations.rs @@ -1,7 +1,9 @@ -use crate::phase0::{SignedBeaconBlockHeader, DEPOSIT_CONTRACT_TREE_DEPTH}; -use crate::primitives::{ - BlsPublicKey, BlsSignature, Bytes32, CommitteeIndex, Epoch, Gwei, Hash32, Root, Slot, - ValidatorIndex, +use crate::{ + phase0::{SignedBeaconBlockHeader, DEPOSIT_CONTRACT_TREE_DEPTH}, + primitives::{ + BlsPublicKey, BlsSignature, Bytes32, CommitteeIndex, Epoch, Gwei, Hash32, Root, Slot, + ValidatorIndex, + }, }; use ssz_rs::prelude::*; diff --git a/src/phase0/presets/mainnet.rs b/src/phase0/presets/mainnet.rs index 20fb32b98..106b87d63 100644 --- a/src/phase0/presets/mainnet.rs +++ b/src/phase0/presets/mainnet.rs @@ -1,6 +1,8 @@ -use crate::phase0; -use crate::phase0::presets::Preset; -use crate::primitives::{Epoch, Gwei, Slot}; +use crate::{ + phase0, + phase0::presets::Preset, + primitives::{Epoch, Gwei, Slot}, +}; pub use phase0::*; diff --git a/src/phase0/presets/minimal.rs b/src/phase0/presets/minimal.rs index c9d87540b..747587f32 100644 --- a/src/phase0/presets/minimal.rs +++ b/src/phase0/presets/minimal.rs @@ -1,6 +1,8 @@ -use crate::phase0; -use crate::phase0::presets::Preset; -use crate::primitives::{Epoch, Gwei, Slot}; +use crate::{ + phase0, + phase0::presets::Preset, + primitives::{Epoch, Gwei, Slot}, +}; pub use phase0::*; diff --git a/src/phase0/slot_processing.rs b/src/phase0/slot_processing.rs index 6a61d9fa8..ee0fcfc4d 100644 --- a/src/phase0/slot_processing.rs +++ b/src/phase0/slot_processing.rs @@ -1,7 +1,9 @@ use crate::phase0 as spec; -use crate::primitives::{Root, Slot}; -use crate::state_transition::{Context, Error, Result}; +use crate::{ + primitives::{Root, Slot}, + state_transition::{Context, Error, Result}, +}; use spec::{process_epoch, BeaconState}; use ssz_rs::prelude::*; @@ -29,10 +31,7 @@ pub fn process_slots< context: &Context, ) -> Result<()> { if state.slot >= slot { - return Err(Error::TransitionToPreviousSlot { - requested: slot, - current: state.slot, - }); + return Err(Error::TransitionToPreviousSlot { requested: slot, current: state.slot }) } while state.slot < slot { process_slot(state, context)?; diff --git a/src/phase0/validator.rs b/src/phase0/validator.rs index c832e223f..94fbbd857 100644 --- a/src/phase0/validator.rs +++ b/src/phase0/validator.rs @@ -1,5 +1,7 @@ -use crate::phase0::Attestation; -use crate::primitives::{BlsPublicKey, BlsSignature, Bytes32, Epoch, Gwei, Root, ValidatorIndex}; +use crate::{ + phase0::Attestation, + primitives::{BlsPublicKey, BlsSignature, Bytes32, Epoch, Gwei, Root, ValidatorIndex}, +}; use ssz_rs::prelude::*; #[derive(Default, Debug, SimpleSerialize, Clone, PartialEq, Eq)] diff --git a/src/primitives.rs b/src/primitives.rs index 74bfabec8..1294c04fb 100644 --- a/src/primitives.rs +++ b/src/primitives.rs @@ -1,6 +1,8 @@ -pub use crate::crypto::{PublicKey as BlsPublicKey, Signature as BlsSignature}; -pub use crate::domains::DomainType; use crate::ssz::ByteVector; +pub use crate::{ + crypto::{PublicKey as BlsPublicKey, Signature as BlsSignature}, + domains::DomainType, +}; use ssz_rs::prelude::*; pub use ssz_rs::prelude::U256; @@ -56,10 +58,7 @@ mod tests { fn test_serde() { let bytes = Bytes32::default(); let json = serde_json::to_string(&bytes).unwrap(); - assert_eq!( - json, - "\"0x0000000000000000000000000000000000000000000000000000000000000000\"" - ); + assert_eq!(json, "\"0x0000000000000000000000000000000000000000000000000000000000000000\""); let bytes_roundtrip: Bytes32 = serde_json::from_str(&json).unwrap(); assert_eq!(bytes, bytes_roundtrip); } diff --git a/src/serde.rs b/src/serde.rs index f3c939ba2..d83311777 100644 --- a/src/serde.rs +++ b/src/serde.rs @@ -12,9 +12,7 @@ pub enum HexError { } pub fn try_bytes_from_hex_str(s: &str) -> Result, HexError> { - let target = s - .strip_prefix(HEX_ENCODING_PREFIX) - .ok_or(HexError::MissingPrefix)?; + let target = s.strip_prefix(HEX_ENCODING_PREFIX).ok_or(HexError::MissingPrefix)?; let data = hex::decode(target)?; Ok(data) } @@ -49,8 +47,7 @@ pub mod as_hex { pub mod as_string { use serde::de::Deserialize; - use std::fmt; - use std::str::FromStr; + use std::{fmt, str::FromStr}; pub fn serialize(data: T, serializer: S) -> Result where @@ -75,11 +72,11 @@ pub mod as_string { } pub mod collection_over_string { - use serde::de::{Deserializer, Error}; - use serde::ser::SerializeSeq; - use std::fmt; - use std::marker::PhantomData; - use std::str::FromStr; + use serde::{ + de::{Deserializer, Error}, + ser::SerializeSeq, + }; + use std::{fmt, marker::PhantomData, str::FromStr}; pub fn serialize(data: T, serializer: S) -> Result where diff --git a/src/signing.rs b/src/signing.rs index d9909d6ee..9fd4bc7e3 100644 --- a/src/signing.rs +++ b/src/signing.rs @@ -1,6 +1,8 @@ -use crate::crypto::{verify_signature, SecretKey}; -use crate::primitives::{BlsPublicKey, BlsSignature, Domain, Root}; -use crate::state_transition::Error; +use crate::{ + crypto::{verify_signature, SecretKey}, + primitives::{BlsPublicKey, BlsSignature, Domain, Root}, + state_transition::Error, +}; use ssz_rs::prelude::*; #[derive(Default, Debug, SimpleSerialize)] @@ -15,10 +17,7 @@ pub fn compute_signing_root( ) -> Result { let object_root = ssz_object.hash_tree_root()?; - let mut s = SigningData { - object_root, - domain, - }; + let mut s = SigningData { object_root, domain }; s.hash_tree_root().map_err(Error::Merkleization) } diff --git a/src/ssz/byte_list.rs b/src/ssz/byte_list.rs index 3f15cf9aa..ee55f5598 100644 --- a/src/ssz/byte_list.rs +++ b/src/ssz/byte_list.rs @@ -1,8 +1,10 @@ use super::write_bytes_to_lower_hex; use ssz_rs::prelude::*; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::ops::{Deref, DerefMut}; +use std::{ + fmt, + hash::{Hash, Hasher}, + ops::{Deref, DerefMut}, +}; #[derive(Default, Clone, Eq, SimpleSerialize)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/src/ssz/byte_vector.rs b/src/ssz/byte_vector.rs index 8fecb1959..5e7a97d5b 100644 --- a/src/ssz/byte_vector.rs +++ b/src/ssz/byte_vector.rs @@ -1,8 +1,10 @@ use super::write_bytes_to_lower_hex; use ssz_rs::prelude::*; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::ops::{Deref, DerefMut}; +use std::{ + fmt, + hash::{Hash, Hasher}, + ops::{Deref, DerefMut}, +}; #[derive(Default, Clone, Eq, SimpleSerialize)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/src/state_transition/beacon_block.rs b/src/state_transition/beacon_block.rs index 112d7ffb3..da84d2388 100644 --- a/src/state_transition/beacon_block.rs +++ b/src/state_transition/beacon_block.rs @@ -1,8 +1,7 @@ /// This module contains "wrapper" types for beacon blocks so that /// the state transition machinery can be polymorphic with respect to forks. use crate::altair; -use crate::bellatrix; -use crate::phase0; +use crate::{bellatrix, phase0}; #[derive(Debug)] pub enum SignedBeaconBlock< diff --git a/src/state_transition/beacon_state.rs b/src/state_transition/beacon_state.rs index fbdfa07d1..05852a864 100644 --- a/src/state_transition/beacon_state.rs +++ b/src/state_transition/beacon_state.rs @@ -1,8 +1,7 @@ /// This module contains "wrapper" types for beacon states so that /// the state transition machinery can be polymorphic with respect to forks. use crate::altair; -use crate::bellatrix; -use crate::phase0; +use crate::{bellatrix, phase0}; #[derive(Debug)] pub enum BeaconState< diff --git a/src/state_transition/context.rs b/src/state_transition/context.rs index 042f7f5e8..c228adf08 100644 --- a/src/state_transition/context.rs +++ b/src/state_transition/context.rs @@ -1,10 +1,11 @@ -use crate::altair; -use crate::bellatrix; -use crate::clock::{self, Clock, SystemTimeProvider}; -use crate::configs::{self, Config}; -use crate::phase0; -use crate::primitives::{Epoch, ExecutionAddress, Gwei, Hash32, Slot, Version, U256}; -use crate::state_transition::Error; +use crate::{ + altair, bellatrix, + clock::{self, Clock, SystemTimeProvider}, + configs::{self, Config}, + phase0, + primitives::{Epoch, ExecutionAddress, Gwei, Hash32, Slot, Version, U256}, + state_transition::Error, +}; #[derive(Debug)] pub enum Forks { diff --git a/src/state_transition/error.rs b/src/state_transition/error.rs index 173f6bd46..eea6ed636 100644 --- a/src/state_transition/error.rs +++ b/src/state_transition/error.rs @@ -1,7 +1,9 @@ -use crate::crypto::Error as CryptoError; -use crate::phase0::{AttestationData, BeaconBlockHeader, Checkpoint}; -use crate::primitives::{BlsSignature, Bytes32, Epoch, Hash32, Root, Slot, ValidatorIndex}; -use crate::state_transition::Forks; +use crate::{ + crypto::Error as CryptoError, + phase0::{AttestationData, BeaconBlockHeader, Checkpoint}, + primitives::{BlsSignature, Bytes32, Epoch, Hash32, Root, Slot, ValidatorIndex}, + state_transition::Forks, +}; use ssz_rs::prelude::*; use thiserror::Error; @@ -28,11 +30,7 @@ pub enum Error { #[error("given index {index} is greater than the total amount of indices {total}")] InvalidShufflingIndex { index: usize, total: usize }, #[error("slot {requested} is outside of allowed range ({lower_bound}, {upper_bound})")] - SlotOutOfRange { - requested: Slot, - lower_bound: Slot, - upper_bound: Slot, - }, + SlotOutOfRange { requested: Slot, lower_bound: Slot, upper_bound: Slot }, #[error("overflow")] Overflow, #[error("underflow")] @@ -46,18 +44,11 @@ pub enum Error { #[error( "the requested epoch {requested} is not in the required current epoch {current} or previous epoch {previous}" )] - InvalidEpoch { - requested: Epoch, - previous: Epoch, - current: Epoch, - }, + InvalidEpoch { requested: Epoch, previous: Epoch, current: Epoch }, #[error( "transition requested from a later fork {destination_fork:?} to an earlier fork {source_fork:?}" )] - IncompatibleForks { - source_fork: Forks, - destination_fork: Forks, - }, + IncompatibleForks { source_fork: Forks, destination_fork: Forks }, #[error("genesis time unknown for network {0}")] UnknownGenesisTime(String), #[cfg(feature = "serde")] @@ -104,47 +95,25 @@ pub enum InvalidBeaconBlockHeader { #[error("proposer with index {0} is slashed")] ProposerSlashed(ValidatorIndex), #[error("block slot {block_slot} is older than the latest block header slot {latest_block_header_slot}")] - OlderThanLatestBlockHeader { - block_slot: Slot, - latest_block_header_slot: Slot, - }, + OlderThanLatestBlockHeader { block_slot: Slot, latest_block_header_slot: Slot }, #[error("mismatch between the block proposer index {block_proposer_index} and the state proposer index {proposer_index}")] - ProposerIndexMismatch { - block_proposer_index: ValidatorIndex, - proposer_index: ValidatorIndex, - }, + ProposerIndexMismatch { block_proposer_index: ValidatorIndex, proposer_index: ValidatorIndex }, } #[derive(Debug, Error)] pub enum InvalidAttestation { #[error("expected length of {expected_length} in bitfield but had length {length}")] - Bitfield { - expected_length: usize, - length: usize, - }, + Bitfield { expected_length: usize, length: usize }, #[error("invalid target epoch {target}, not current ({current}) or previous epochs")] InvalidTargetEpoch { target: Epoch, current: Epoch }, #[error("invalid slot {slot} (in epoch {epoch}) based on target epoch {target}")] - InvalidSlot { - slot: Slot, - epoch: Epoch, - target: Epoch, - }, + InvalidSlot { slot: Slot, epoch: Epoch, target: Epoch }, #[error("attestation at slot {attestation_slot} is not timely for state slot {state_slot}, outside of range [{lower_bound}, {upper_bound}]")] - NotTimely { - state_slot: Slot, - attestation_slot: Slot, - lower_bound: Slot, - upper_bound: Slot, - }, + NotTimely { state_slot: Slot, attestation_slot: Slot, lower_bound: Slot, upper_bound: Slot }, #[error("attestation's index {index} exceeds the current committee count {upper_bound}")] InvalidIndex { index: usize, upper_bound: usize }, #[error("attestation's source checkpoint {source_checkpoint:?} does not match the expected checkpoint {expected:?} (in epoch {current})")] - InvalidSource { - expected: Checkpoint, - source_checkpoint: Checkpoint, - current: Epoch, - }, + InvalidSource { expected: Checkpoint, source_checkpoint: Checkpoint, current: Epoch }, } #[derive(Debug, Error)] @@ -164,13 +133,7 @@ pub enum InvalidDeposit { #[error("expected {expected} deposits but only had {count} deposits")] IncorrectCount { expected: usize, count: usize }, #[error("merkle validation failed for tree with depth {depth} and root {root:?} at index {index} for leaf {leaf:?} and branch {branch:?}")] - InvalidProof { - leaf: Node, - branch: Vec, - depth: usize, - index: usize, - root: Root, - }, + InvalidProof { leaf: Node, branch: Vec, depth: usize, index: usize, root: Root }, #[error("invalid signature for deposit: {0:?}")] InvalidSignature(BlsSignature), } @@ -208,15 +171,9 @@ pub enum InvalidVoluntaryExit { #[error("validator {index} already exited in {epoch}")] ValidatorAlreadyExited { index: ValidatorIndex, epoch: Epoch }, #[error("exit in epoch {exit_epoch} is not eligible for processing in current epoch {current_epoch}")] - EarlyExit { - current_epoch: Epoch, - exit_epoch: Epoch, - }, + EarlyExit { current_epoch: Epoch, exit_epoch: Epoch }, #[error("validator needs to be active for a minimum period of time (from epoch {minimum_time_active}, currently in {current_epoch})")] - ValidatorIsNotActiveForLongEnough { - current_epoch: Epoch, - minimum_time_active: Epoch, - }, + ValidatorIsNotActiveForLongEnough { current_epoch: Epoch, minimum_time_active: Epoch }, #[error("voluntary exit has invalid signature: {0:?}")] InvalidSignature(BlsSignature), } @@ -232,10 +189,7 @@ pub enum InvalidExecutionPayload { #[error("expected parent hash {expected} but block has parent hash {provided}")] InvalidParentHash { provided: Hash32, expected: Hash32 }, #[error("expected randao value {expected} but block has randao value {provided}")] - InvalidPrevRandao { - provided: Bytes32, - expected: Bytes32, - }, + InvalidPrevRandao { provided: Bytes32, expected: Bytes32 }, #[error("expected timestamp {expected} but block has timestamp {provided}")] InvalidTimestamp { provided: u64, expected: u64 }, } diff --git a/src/state_transition/executor.rs b/src/state_transition/executor.rs index e22bdf5d1..8f13b49e8 100644 --- a/src/state_transition/executor.rs +++ b/src/state_transition/executor.rs @@ -1,8 +1,6 @@ -use crate::altair; -use crate::bellatrix; -use crate::phase0; -use crate::state_transition::{ - BeaconState, Context, Error, Forks, Result, SignedBeaconBlock, Validation, +use crate::{ + altair, bellatrix, phase0, + state_transition::{BeaconState, Context, Error, Forks, Result, SignedBeaconBlock, Validation}, }; #[derive(Debug)] @@ -118,11 +116,7 @@ impl< execution_engine: E, context: Context, ) -> Self { - Self { - state, - execution_engine, - context, - } + Self { state, execution_engine, context } } pub fn apply_block( diff --git a/src/state_transition/presets/mainnet.rs b/src/state_transition/presets/mainnet.rs index bef56e226..5cc232bae 100644 --- a/src/state_transition/presets/mainnet.rs +++ b/src/state_transition/presets/mainnet.rs @@ -1,15 +1,17 @@ -use crate::altair::mainnet::SYNC_COMMITTEE_SIZE; -use crate::bellatrix::mainnet::{ - BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, - MAX_TRANSACTIONS_PER_PAYLOAD, -}; -use crate::phase0::mainnet::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - PENDING_ATTESTATIONS_BOUND, SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +use crate::{ + altair::mainnet::SYNC_COMMITTEE_SIZE, + bellatrix::mainnet::{ + BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, + MAX_TRANSACTIONS_PER_PAYLOAD, + }, + phase0::mainnet::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + PENDING_ATTESTATIONS_BOUND, SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, + state_transition, }; -use crate::state_transition; pub use state_transition::{BeaconState, Context, Error, SignedBeaconBlock, Validation}; diff --git a/src/state_transition/presets/minimal.rs b/src/state_transition/presets/minimal.rs index e3e475b9d..94f87e28e 100644 --- a/src/state_transition/presets/minimal.rs +++ b/src/state_transition/presets/minimal.rs @@ -1,15 +1,17 @@ -use crate::altair::minimal::SYNC_COMMITTEE_SIZE; -use crate::bellatrix::minimal::{ - BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, - MAX_TRANSACTIONS_PER_PAYLOAD, -}; -use crate::phase0::minimal::{ - EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, - HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, - MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, - PENDING_ATTESTATIONS_BOUND, SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, +use crate::{ + altair::minimal::SYNC_COMMITTEE_SIZE, + bellatrix::minimal::{ + BYTES_PER_LOGS_BLOOM, MAX_BYTES_PER_TRANSACTION, MAX_EXTRA_DATA_BYTES, + MAX_TRANSACTIONS_PER_PAYLOAD, + }, + phase0::minimal::{ + EPOCHS_PER_HISTORICAL_VECTOR, EPOCHS_PER_SLASHINGS_VECTOR, ETH1_DATA_VOTES_BOUND, + HISTORICAL_ROOTS_LIMIT, MAX_ATTESTATIONS, MAX_ATTESTER_SLASHINGS, MAX_DEPOSITS, + MAX_PROPOSER_SLASHINGS, MAX_VALIDATORS_PER_COMMITTEE, MAX_VOLUNTARY_EXITS, + PENDING_ATTESTATIONS_BOUND, SLOTS_PER_HISTORICAL_ROOT, VALIDATOR_REGISTRY_LIMIT, + }, + state_transition, }; -use crate::state_transition; pub use state_transition::{BeaconState, Context, Error, SignedBeaconBlock, Validation}; diff --git a/tests/consensus_spec_tests/general/altair/bls/eth_aggregate_pubkeys/small/mod.rs b/tests/consensus_spec_tests/general/altair/bls/eth_aggregate_pubkeys/small/mod.rs index a1bf48052..9979983a4 100644 --- a/tests/consensus_spec_tests/general/altair/bls/eth_aggregate_pubkeys/small/mod.rs +++ b/tests/consensus_spec_tests/general/altair/bls/eth_aggregate_pubkeys/small/mod.rs @@ -1,8 +1,7 @@ // WARNING! // This file was generated with `gen-tests`. Do NOT edit manually. -use crate::spec_test_runners::bls::EthAggregatePubkeysTestCase; -use crate::test_utils::TestCase; +use crate::{spec_test_runners::bls::EthAggregatePubkeysTestCase, test_utils::TestCase}; #[test] fn test_eth_aggregate_pubkeys_empty_list() { diff --git a/tests/consensus_spec_tests/general/altair/bls/eth_fast_aggregate_verify/small/mod.rs b/tests/consensus_spec_tests/general/altair/bls/eth_fast_aggregate_verify/small/mod.rs index f365d8432..2b0188fa0 100644 --- a/tests/consensus_spec_tests/general/altair/bls/eth_fast_aggregate_verify/small/mod.rs +++ b/tests/consensus_spec_tests/general/altair/bls/eth_fast_aggregate_verify/small/mod.rs @@ -1,8 +1,7 @@ // WARNING! // This file was generated with `gen-tests`. Do NOT edit manually. -use crate::spec_test_runners::bls::EthFastAggregateVerifyTestCase; -use crate::test_utils::TestCase; +use crate::{spec_test_runners::bls::EthFastAggregateVerifyTestCase, test_utils::TestCase}; #[test] fn test_eth_fast_aggregate_verify_extra_pubkey_4_f_079_f_946446_fabf() { diff --git a/tests/consensus_spec_tests/general/phase0/bls/aggregate/small/mod.rs b/tests/consensus_spec_tests/general/phase0/bls/aggregate/small/mod.rs index b11c76bd7..366b292a6 100644 --- a/tests/consensus_spec_tests/general/phase0/bls/aggregate/small/mod.rs +++ b/tests/consensus_spec_tests/general/phase0/bls/aggregate/small/mod.rs @@ -1,8 +1,7 @@ // WARNING! // This file was generated with `gen-tests`. Do NOT edit manually. -use crate::spec_test_runners::bls::AggregateTestCase; -use crate::test_utils::TestCase; +use crate::{spec_test_runners::bls::AggregateTestCase, test_utils::TestCase}; #[test] fn test_aggregate_0_x_0000000000000000000000000000000000000000000000000000000000000000() { diff --git a/tests/consensus_spec_tests/general/phase0/bls/aggregate_verify/small/mod.rs b/tests/consensus_spec_tests/general/phase0/bls/aggregate_verify/small/mod.rs index 8be547caa..c0f7d38a1 100644 --- a/tests/consensus_spec_tests/general/phase0/bls/aggregate_verify/small/mod.rs +++ b/tests/consensus_spec_tests/general/phase0/bls/aggregate_verify/small/mod.rs @@ -1,8 +1,7 @@ // WARNING! // This file was generated with `gen-tests`. Do NOT edit manually. -use crate::spec_test_runners::bls::AggregateVerifyTestCase; -use crate::test_utils::TestCase; +use crate::{spec_test_runners::bls::AggregateVerifyTestCase, test_utils::TestCase}; #[test] fn test_aggregate_verify_infinity_pubkey() { diff --git a/tests/consensus_spec_tests/general/phase0/bls/fast_aggregate_verify/small/mod.rs b/tests/consensus_spec_tests/general/phase0/bls/fast_aggregate_verify/small/mod.rs index 24e608eee..40958a20c 100644 --- a/tests/consensus_spec_tests/general/phase0/bls/fast_aggregate_verify/small/mod.rs +++ b/tests/consensus_spec_tests/general/phase0/bls/fast_aggregate_verify/small/mod.rs @@ -1,8 +1,7 @@ // WARNING! // This file was generated with `gen-tests`. Do NOT edit manually. -use crate::spec_test_runners::bls::FastAggregateVerifyTestCase; -use crate::test_utils::TestCase; +use crate::{spec_test_runners::bls::FastAggregateVerifyTestCase, test_utils::TestCase}; #[test] fn test_fast_aggregate_verify_extra_pubkey_4_f_079_f_946446_fabf() { diff --git a/tests/consensus_spec_tests/general/phase0/bls/sign/small/mod.rs b/tests/consensus_spec_tests/general/phase0/bls/sign/small/mod.rs index dfa09fcf6..3d7c40594 100644 --- a/tests/consensus_spec_tests/general/phase0/bls/sign/small/mod.rs +++ b/tests/consensus_spec_tests/general/phase0/bls/sign/small/mod.rs @@ -1,8 +1,7 @@ // WARNING! // This file was generated with `gen-tests`. Do NOT edit manually. -use crate::spec_test_runners::bls::SignTestCase; -use crate::test_utils::TestCase; +use crate::{spec_test_runners::bls::SignTestCase, test_utils::TestCase}; #[test] fn test_sign_case_11_b_8_c_7_cad_5238946() { diff --git a/tests/consensus_spec_tests/general/phase0/bls/verify/small/mod.rs b/tests/consensus_spec_tests/general/phase0/bls/verify/small/mod.rs index 5e0d76492..c80b96c71 100644 --- a/tests/consensus_spec_tests/general/phase0/bls/verify/small/mod.rs +++ b/tests/consensus_spec_tests/general/phase0/bls/verify/small/mod.rs @@ -1,8 +1,7 @@ // WARNING! // This file was generated with `gen-tests`. Do NOT edit manually. -use crate::spec_test_runners::bls::VerifyTestCase; -use crate::test_utils::TestCase; +use crate::{spec_test_runners::bls::VerifyTestCase, test_utils::TestCase}; #[test] fn test_verify_infinity_pubkey_and_infinity_signature() { diff --git a/tests/consensus_spec_tests/mainnet/altair/fork/fork/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/altair/fork/fork/pyspec_tests/mod.rs index ffdcbe302..fe10009c1 100644 --- a/tests/consensus_spec_tests/mainnet/altair/fork/fork/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/altair/fork/fork/pyspec_tests/mod.rs @@ -2,8 +2,7 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::fork::ForkTestCase; -use ethereum_consensus::altair::mainnet as spec; -use ethereum_consensus::phase0::mainnet as phase0; +use ethereum_consensus::{altair::mainnet as spec, phase0::mainnet as phase0}; use ssz_rs::prelude::*; #[test] @@ -12,11 +11,9 @@ fn test_altair_fork_random_0() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_0", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -25,11 +22,9 @@ fn test_altair_fork_random_1() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_1", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -38,11 +33,9 @@ fn test_altair_fork_random_2() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_2", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -51,55 +44,45 @@ fn test_altair_fork_random_3() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_3", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_duplicate_attestations() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_duplicate_attestations"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_low_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_low_balances"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_misc_balances"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_mismatched_attestations() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/altair_fork_random_mismatched_attestations"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -108,11 +91,9 @@ fn test_fork_base_state() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/fork_base_state", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -121,11 +102,9 @@ fn test_fork_many_next_epoch() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/fork_many_next_epoch", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -134,22 +113,18 @@ fn test_fork_next_epoch() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/fork_next_epoch", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_fork_next_epoch_with_block() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/fork_next_epoch_with_block"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -158,20 +133,16 @@ fn test_fork_random_low_balances() { "consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/fork_random_low_balances", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/altair/fork/fork/pyspec_tests/fork_random_misc_balances"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } diff --git a/tests/consensus_spec_tests/mainnet/altair/rewards/basic/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/altair/rewards/basic/pyspec_tests/mod.rs index a44e66156..118b7e377 100644 --- a/tests/consensus_spec_tests/mainnet/altair/rewards/basic/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/altair/rewards/basic/pyspec_tests/mod.rs @@ -18,13 +18,7 @@ fn test_all_balances_too_low_for_reward() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_empty() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_all_correct() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -91,13 +73,7 @@ fn test_full_but_partial_participation() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_half_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -141,13 +111,7 @@ fn test_quarter_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_some_very_low_effective_balances_that_attested() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -187,13 +145,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -210,13 +162,7 @@ fn test_with_exited_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -233,13 +179,7 @@ fn test_with_not_yet_activated_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -256,12 +196,6 @@ fn test_with_slashed_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/mainnet/altair/rewards/leak/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/altair/rewards/leak/pyspec_tests/mod.rs index b9c5a2fcf..c208e853f 100644 --- a/tests/consensus_spec_tests/mainnet/altair/rewards/leak/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/altair/rewards/leak/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_empty_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_full_but_partial_participation_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -93,13 +75,7 @@ fn test_full_random_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_full_random_seven_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -139,13 +109,7 @@ fn test_full_random_ten_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_half_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_quarter_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_some_very_low_effective_balances_that_attested_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,13 +181,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -258,13 +198,7 @@ fn test_with_exited_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -281,13 +215,7 @@ fn test_with_not_yet_activated_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -304,12 +232,6 @@ fn test_with_slashed_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/mainnet/altair/rewards/random/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/altair/rewards/random/pyspec_tests/mod.rs index e5f8cc484..b399e2f9a 100644 --- a/tests/consensus_spec_tests/mainnet/altair/rewards/random/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/altair/rewards/random/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_full_random_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -45,13 +39,7 @@ fn test_full_random_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -70,13 +58,7 @@ fn test_full_random_2() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -95,13 +77,7 @@ fn test_full_random_3() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -120,13 +96,7 @@ fn test_full_random_4() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -143,13 +113,7 @@ fn test_full_random_low_balances_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -166,13 +130,7 @@ fn test_full_random_low_balances_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_full_random_misc_balances() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_full_random_without_leak_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,12 +181,6 @@ fn test_full_random_without_leak_and_current_exit_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/mainnet/altair/transition/core/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/altair/transition/core/pyspec_tests/mod.rs index 13f867b95..5325b8bf1 100644 --- a/tests/consensus_spec_tests/mainnet/altair/transition/core/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/altair/transition/core/pyspec_tests/mod.rs @@ -2,10 +2,12 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::transition::CoreTestCase; -use ethereum_consensus::altair::mainnet as spec; -use ethereum_consensus::bellatrix::mainnet::NoOpExecutionEngine; -use ethereum_consensus::phase0::mainnet as pre_spec; -use ethereum_consensus::state_transition::mainnet::{BeaconState, Executor}; +use ethereum_consensus::{ + altair::mainnet as spec, + bellatrix::mainnet::NoOpExecutionEngine, + phase0::mainnet as pre_spec, + state_transition::mainnet::{BeaconState, Executor}, +}; use ssz_rs::prelude::*; #[test] diff --git a/tests/consensus_spec_tests/mainnet/bellatrix/fork/fork/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/bellatrix/fork/fork/pyspec_tests/mod.rs index 2d5b59db0..052654d71 100644 --- a/tests/consensus_spec_tests/mainnet/bellatrix/fork/fork/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/bellatrix/fork/fork/pyspec_tests/mod.rs @@ -2,74 +2,61 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::fork::ForkTestCase; -use ethereum_consensus::altair::mainnet as altair; -use ethereum_consensus::bellatrix::mainnet as spec; +use ethereum_consensus::{altair::mainnet as altair, bellatrix::mainnet as spec}; use ssz_rs::prelude::*; #[test] fn test_bellatrix_fork_random_0() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_0"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_1() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_1"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_2() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_2"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_3() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_3"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_low_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_low_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_misc_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] @@ -78,11 +65,9 @@ fn test_fork_base_state() { "consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/fork_base_state", ); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] @@ -91,11 +76,9 @@ fn test_fork_many_next_epoch() { "consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/fork_many_next_epoch", ); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] @@ -104,42 +87,34 @@ fn test_fork_next_epoch() { "consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/fork_next_epoch", ); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_fork_next_epoch_with_block() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/fork_next_epoch_with_block"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_fork_random_low_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/fork_random_low_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/mainnet/bellatrix/fork/fork/pyspec_tests/fork_random_misc_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } diff --git a/tests/consensus_spec_tests/mainnet/bellatrix/operations/execution_payload/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/bellatrix/operations/execution_payload/pyspec_tests/mod.rs index 6c7cc80d6..30ea57b44 100644 --- a/tests/consensus_spec_tests/mainnet/bellatrix/operations/execution_payload/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/bellatrix/operations/execution_payload/pyspec_tests/mod.rs @@ -18,14 +18,12 @@ fn test_bad_everything_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -45,14 +43,12 @@ fn test_bad_execution_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -72,14 +68,12 @@ fn test_bad_execution_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -99,14 +93,12 @@ fn test_bad_parent_hash_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -126,14 +118,12 @@ fn test_bad_random_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -153,14 +143,12 @@ fn test_bad_random_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -180,14 +168,12 @@ fn test_bad_timestamp_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -207,14 +193,12 @@ fn test_bad_timestamp_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -234,14 +218,12 @@ fn test_non_empty_extra_data_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -261,14 +243,12 @@ fn test_non_empty_extra_data_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -288,14 +268,12 @@ fn test_success_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -315,14 +293,12 @@ fn test_success_first_payload_with_gap_slot() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -342,14 +318,12 @@ fn test_success_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -369,14 +343,12 @@ fn test_success_regular_payload_with_gap_slot() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) diff --git a/tests/consensus_spec_tests/mainnet/bellatrix/rewards/basic/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/bellatrix/rewards/basic/pyspec_tests/mod.rs index c41133125..bfaba94a0 100644 --- a/tests/consensus_spec_tests/mainnet/bellatrix/rewards/basic/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/bellatrix/rewards/basic/pyspec_tests/mod.rs @@ -18,13 +18,7 @@ fn test_all_balances_too_low_for_reward() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_empty() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_all_correct() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -91,13 +73,7 @@ fn test_full_but_partial_participation() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_half_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -141,13 +111,7 @@ fn test_quarter_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_some_very_low_effective_balances_that_attested() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -187,13 +145,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -210,13 +162,7 @@ fn test_with_exited_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -233,13 +179,7 @@ fn test_with_not_yet_activated_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -256,12 +196,6 @@ fn test_with_slashed_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/mainnet/bellatrix/rewards/leak/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/bellatrix/rewards/leak/pyspec_tests/mod.rs index 596c16a6f..ac769bfa8 100644 --- a/tests/consensus_spec_tests/mainnet/bellatrix/rewards/leak/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/bellatrix/rewards/leak/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_empty_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_full_but_partial_participation_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -93,13 +75,7 @@ fn test_full_random_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_full_random_seven_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -139,13 +109,7 @@ fn test_full_random_ten_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_half_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_quarter_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_some_very_low_effective_balances_that_attested_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,13 +181,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -258,13 +198,7 @@ fn test_with_exited_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -281,13 +215,7 @@ fn test_with_not_yet_activated_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -304,12 +232,6 @@ fn test_with_slashed_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/mainnet/bellatrix/rewards/random/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/bellatrix/rewards/random/pyspec_tests/mod.rs index a15dd9926..e01939fdc 100644 --- a/tests/consensus_spec_tests/mainnet/bellatrix/rewards/random/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/bellatrix/rewards/random/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_full_random_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -45,13 +39,7 @@ fn test_full_random_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -70,13 +58,7 @@ fn test_full_random_2() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -95,13 +77,7 @@ fn test_full_random_3() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -120,13 +96,7 @@ fn test_full_random_4() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -143,13 +113,7 @@ fn test_full_random_low_balances_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -166,13 +130,7 @@ fn test_full_random_low_balances_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_full_random_misc_balances() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_full_random_without_leak_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,12 +181,6 @@ fn test_full_random_without_leak_and_current_exit_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/mainnet/bellatrix/transition/core/pyspec_tests/mod.rs b/tests/consensus_spec_tests/mainnet/bellatrix/transition/core/pyspec_tests/mod.rs index 0f3ee5af6..22e400f61 100644 --- a/tests/consensus_spec_tests/mainnet/bellatrix/transition/core/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/mainnet/bellatrix/transition/core/pyspec_tests/mod.rs @@ -2,10 +2,11 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::transition::CoreTestCase; -use ethereum_consensus::altair::mainnet as pre_spec; -use ethereum_consensus::bellatrix::mainnet as spec; -use ethereum_consensus::bellatrix::mainnet::NoOpExecutionEngine; -use ethereum_consensus::state_transition::mainnet::{BeaconState, Executor}; +use ethereum_consensus::{ + altair::mainnet as pre_spec, + bellatrix::{mainnet as spec, mainnet::NoOpExecutionEngine}, + state_transition::mainnet::{BeaconState, Executor}, +}; use ssz_rs::prelude::*; #[test] diff --git a/tests/consensus_spec_tests/minimal/altair/fork/fork/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/altair/fork/fork/pyspec_tests/mod.rs index 6daf0b689..6315d9bb2 100644 --- a/tests/consensus_spec_tests/minimal/altair/fork/fork/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/altair/fork/fork/pyspec_tests/mod.rs @@ -2,8 +2,7 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::fork::ForkTestCase; -use ethereum_consensus::altair::minimal as spec; -use ethereum_consensus::phase0::minimal as phase0; +use ethereum_consensus::{altair::minimal as spec, phase0::minimal as phase0}; use ssz_rs::prelude::*; #[test] @@ -12,11 +11,9 @@ fn test_altair_fork_random_0() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_0", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -25,11 +22,9 @@ fn test_altair_fork_random_1() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_1", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -38,11 +33,9 @@ fn test_altair_fork_random_2() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_2", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -51,66 +44,54 @@ fn test_altair_fork_random_3() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_3", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_duplicate_attestations() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_duplicate_attestations"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_large_validator_set() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_large_validator_set"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_low_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_low_balances"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_misc_balances"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_altair_fork_random_mismatched_attestations() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/altair_fork_random_mismatched_attestations"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -119,11 +100,9 @@ fn test_fork_base_state() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/fork_base_state", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -132,11 +111,9 @@ fn test_fork_many_next_epoch() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/fork_many_next_epoch", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -145,33 +122,27 @@ fn test_fork_next_epoch() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/fork_next_epoch", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_fork_next_epoch_with_block() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/fork_next_epoch_with_block"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_fork_random_large_validator_set() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/fork_random_large_validator_set"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] @@ -180,20 +151,16 @@ fn test_fork_random_low_balances() { "consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/fork_random_low_balances", ); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } #[test] fn test_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/altair/fork/fork/pyspec_tests/fork_random_misc_balances"); - test_case.execute( - |state: &phase0::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_altair(state, context).unwrap() - }, - ); + test_case.execute(|state: &phase0::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_altair(state, context).unwrap() + }); } diff --git a/tests/consensus_spec_tests/minimal/altair/rewards/basic/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/altair/rewards/basic/pyspec_tests/mod.rs index 780126537..7c3487f65 100644 --- a/tests/consensus_spec_tests/minimal/altair/rewards/basic/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/altair/rewards/basic/pyspec_tests/mod.rs @@ -18,13 +18,7 @@ fn test_all_balances_too_low_for_reward() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_empty() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_all_correct() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -91,13 +73,7 @@ fn test_full_but_partial_participation() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_half_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -141,13 +111,7 @@ fn test_quarter_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_some_very_low_effective_balances_that_attested() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -187,13 +145,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -210,13 +162,7 @@ fn test_with_exited_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -233,13 +179,7 @@ fn test_with_not_yet_activated_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -256,12 +196,6 @@ fn test_with_slashed_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/minimal/altair/rewards/leak/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/altair/rewards/leak/pyspec_tests/mod.rs index 9ca4938dd..f2f551e88 100644 --- a/tests/consensus_spec_tests/minimal/altair/rewards/leak/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/altair/rewards/leak/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_empty_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_full_but_partial_participation_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -93,13 +75,7 @@ fn test_full_random_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_full_random_seven_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -139,13 +109,7 @@ fn test_full_random_ten_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_half_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_quarter_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_some_very_low_effective_balances_that_attested_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,13 +181,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -258,13 +198,7 @@ fn test_with_exited_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -281,13 +215,7 @@ fn test_with_not_yet_activated_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -304,12 +232,6 @@ fn test_with_slashed_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/minimal/altair/rewards/random/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/altair/rewards/random/pyspec_tests/mod.rs index a38acec87..b2aba4534 100644 --- a/tests/consensus_spec_tests/minimal/altair/rewards/random/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/altair/rewards/random/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_full_random_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -45,13 +39,7 @@ fn test_full_random_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -70,13 +58,7 @@ fn test_full_random_2() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -95,13 +77,7 @@ fn test_full_random_3() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -120,13 +96,7 @@ fn test_full_random_4() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -143,13 +113,7 @@ fn test_full_random_low_balances_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -166,13 +130,7 @@ fn test_full_random_low_balances_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_full_random_misc_balances() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_full_random_without_leak_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,12 +181,6 @@ fn test_full_random_without_leak_and_current_exit_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/minimal/altair/transition/core/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/altair/transition/core/pyspec_tests/mod.rs index 090f8e063..1a74a6093 100644 --- a/tests/consensus_spec_tests/minimal/altair/transition/core/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/altair/transition/core/pyspec_tests/mod.rs @@ -2,10 +2,12 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::transition::CoreTestCase; -use ethereum_consensus::altair::minimal as spec; -use ethereum_consensus::bellatrix::minimal::NoOpExecutionEngine; -use ethereum_consensus::phase0::minimal as pre_spec; -use ethereum_consensus::state_transition::minimal::{BeaconState, Executor}; +use ethereum_consensus::{ + altair::minimal as spec, + bellatrix::minimal::NoOpExecutionEngine, + phase0::minimal as pre_spec, + state_transition::minimal::{BeaconState, Executor}, +}; use ssz_rs::prelude::*; #[test] diff --git a/tests/consensus_spec_tests/minimal/bellatrix/fork/fork/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/bellatrix/fork/fork/pyspec_tests/mod.rs index 135e86e2d..727cfed13 100644 --- a/tests/consensus_spec_tests/minimal/bellatrix/fork/fork/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/bellatrix/fork/fork/pyspec_tests/mod.rs @@ -2,85 +2,70 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::fork::ForkTestCase; -use ethereum_consensus::altair::minimal as altair; -use ethereum_consensus::bellatrix::minimal as spec; +use ethereum_consensus::{altair::minimal as altair, bellatrix::minimal as spec}; use ssz_rs::prelude::*; #[test] fn test_bellatrix_fork_random_0() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_0"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_1() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_1"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_2() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_2"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_3() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_3"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_large_validator_set() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_large_validator_set"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_low_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_low_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_bellatrix_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/bellatrix_fork_random_misc_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] @@ -89,11 +74,9 @@ fn test_fork_base_state() { "consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/fork_base_state", ); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] @@ -102,11 +85,9 @@ fn test_fork_many_next_epoch() { "consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/fork_many_next_epoch", ); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] @@ -115,53 +96,43 @@ fn test_fork_next_epoch() { "consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/fork_next_epoch", ); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_fork_next_epoch_with_block() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/fork_next_epoch_with_block"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_fork_random_large_validator_set() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/fork_random_large_validator_set"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_fork_random_low_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/fork_random_low_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } #[test] fn test_fork_random_misc_balances() { let test_case = ForkTestCase::<>::from("consensus-spec-tests/tests/minimal/bellatrix/fork/fork/pyspec_tests/fork_random_misc_balances"); - test_case.execute( - |state: &altair::BeaconState, context| -> spec::BeaconState { - spec::upgrade_to_bellatrix(state, context) - }, - ); + test_case.execute(|state: &altair::BeaconState, context| -> spec::BeaconState { + spec::upgrade_to_bellatrix(state, context) + }); } diff --git a/tests/consensus_spec_tests/minimal/bellatrix/genesis/initialization/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/bellatrix/genesis/initialization/pyspec_tests/mod.rs index 932106bfa..76aba002f 100644 --- a/tests/consensus_spec_tests/minimal/bellatrix/genesis/initialization/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/bellatrix/genesis/initialization/pyspec_tests/mod.rs @@ -30,11 +30,7 @@ fn test_initialize_beacon_state_from_eth_1() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); @@ -65,11 +61,7 @@ fn test_initialize_beacon_state_one_topup_activation() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); @@ -100,11 +92,7 @@ fn test_initialize_beacon_state_random_invalid_genesis() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); @@ -135,11 +123,7 @@ fn test_initialize_beacon_state_random_valid_genesis() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); @@ -170,11 +154,7 @@ fn test_initialize_beacon_state_some_small_balances() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); @@ -205,11 +185,7 @@ fn test_initialize_post_transition() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); @@ -240,11 +216,7 @@ fn test_initialize_pre_transition_empty_payload() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); @@ -275,11 +247,7 @@ fn test_initialize_pre_transition_no_param() { { spec::MAX_BYTES_PER_TRANSACTION }, { spec::MAX_TRANSACTIONS_PER_PAYLOAD }, >( - eth1_block_hash, - eth1_timestamp, - deposits, - execution_payload_header, - context, + eth1_block_hash, eth1_timestamp, deposits, execution_payload_header, context ) }, ); diff --git a/tests/consensus_spec_tests/minimal/bellatrix/operations/execution_payload/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/bellatrix/operations/execution_payload/pyspec_tests/mod.rs index fb9deb376..657fcbc51 100644 --- a/tests/consensus_spec_tests/minimal/bellatrix/operations/execution_payload/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/bellatrix/operations/execution_payload/pyspec_tests/mod.rs @@ -18,14 +18,12 @@ fn test_bad_everything_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -45,14 +43,12 @@ fn test_bad_execution_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -72,14 +68,12 @@ fn test_bad_execution_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -99,14 +93,12 @@ fn test_bad_parent_hash_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -126,14 +118,12 @@ fn test_bad_random_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -153,14 +143,12 @@ fn test_bad_random_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -180,14 +168,12 @@ fn test_bad_timestamp_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -207,14 +193,12 @@ fn test_bad_timestamp_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -234,14 +218,12 @@ fn test_non_empty_extra_data_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -261,14 +243,12 @@ fn test_non_empty_extra_data_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -288,14 +268,12 @@ fn test_success_first_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -315,14 +293,12 @@ fn test_success_first_payload_with_gap_slot() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -342,14 +318,12 @@ fn test_success_regular_payload() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) @@ -369,14 +343,12 @@ fn test_success_regular_payload_with_gap_slot() { Ok(()) } else { // NOTE: exact error is not specified for this test - Err(Error::InvalidBlock(Box::new( - InvalidBlock::InvalidOperation(InvalidOperation::ExecutionPayload( - InvalidExecutionPayload::InvalidTimestamp { - provided: 0, - expected: 0, - }, - )), - ))) + Err(Error::InvalidBlock(Box::new(InvalidBlock::InvalidOperation( + InvalidOperation::ExecutionPayload(InvalidExecutionPayload::InvalidTimestamp { + provided: 0, + expected: 0, + }), + )))) } }); spec::process_execution_payload(state, operation, execution_engine, context) diff --git a/tests/consensus_spec_tests/minimal/bellatrix/rewards/basic/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/bellatrix/rewards/basic/pyspec_tests/mod.rs index 30b1fc5f9..b04ff8acf 100644 --- a/tests/consensus_spec_tests/minimal/bellatrix/rewards/basic/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/bellatrix/rewards/basic/pyspec_tests/mod.rs @@ -18,13 +18,7 @@ fn test_all_balances_too_low_for_reward() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_empty() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_all_correct() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -91,13 +73,7 @@ fn test_full_but_partial_participation() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_half_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -141,13 +111,7 @@ fn test_quarter_full() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_some_very_low_effective_balances_that_attested() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -187,13 +145,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -210,13 +162,7 @@ fn test_with_exited_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -233,13 +179,7 @@ fn test_with_not_yet_activated_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -256,12 +196,6 @@ fn test_with_slashed_validators() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/minimal/bellatrix/rewards/leak/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/bellatrix/rewards/leak/pyspec_tests/mod.rs index f59db4783..6cc62d65b 100644 --- a/tests/consensus_spec_tests/minimal/bellatrix/rewards/leak/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/bellatrix/rewards/leak/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_empty_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -43,13 +37,7 @@ fn test_full_but_partial_participation_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -68,13 +56,7 @@ fn test_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -93,13 +75,7 @@ fn test_full_random_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -116,13 +92,7 @@ fn test_full_random_seven_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -139,13 +109,7 @@ fn test_full_random_ten_epoch_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -164,13 +128,7 @@ fn test_half_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_quarter_full_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_some_very_low_effective_balances_that_attested_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,13 +181,7 @@ fn test_some_very_low_effective_balances_that_did_not_attest_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -258,13 +198,7 @@ fn test_with_exited_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -281,13 +215,7 @@ fn test_with_not_yet_activated_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -304,12 +232,6 @@ fn test_with_slashed_validators_leak() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/minimal/bellatrix/rewards/random/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/bellatrix/rewards/random/pyspec_tests/mod.rs index eb9661cd2..f0d8c7062 100644 --- a/tests/consensus_spec_tests/minimal/bellatrix/rewards/random/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/bellatrix/rewards/random/pyspec_tests/mod.rs @@ -20,13 +20,7 @@ fn test_full_random_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -45,13 +39,7 @@ fn test_full_random_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -70,13 +58,7 @@ fn test_full_random_2() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -95,13 +77,7 @@ fn test_full_random_3() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -120,13 +96,7 @@ fn test_full_random_4() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -143,13 +113,7 @@ fn test_full_random_low_balances_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -166,13 +130,7 @@ fn test_full_random_low_balances_1() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -189,13 +147,7 @@ fn test_full_random_misc_balances() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -212,13 +164,7 @@ fn test_full_random_without_leak_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } @@ -235,12 +181,6 @@ fn test_full_random_without_leak_and_current_exit_0() { let head_deltas = spec::get_flag_index_deltas(state, flag_index, context).unwrap(); let inactivity_penalty_deltas = spec::get_inactivity_penalty_deltas(state, context).unwrap(); - ( - source_deltas, - target_deltas, - head_deltas, - None, - inactivity_penalty_deltas, - ) + (source_deltas, target_deltas, head_deltas, None, inactivity_penalty_deltas) }); } diff --git a/tests/consensus_spec_tests/minimal/bellatrix/transition/core/pyspec_tests/mod.rs b/tests/consensus_spec_tests/minimal/bellatrix/transition/core/pyspec_tests/mod.rs index 32927bcf6..893240041 100644 --- a/tests/consensus_spec_tests/minimal/bellatrix/transition/core/pyspec_tests/mod.rs +++ b/tests/consensus_spec_tests/minimal/bellatrix/transition/core/pyspec_tests/mod.rs @@ -2,10 +2,11 @@ // This file was generated with `gen-tests`. Do NOT edit manually. use crate::spec_test_runners::transition::CoreTestCase; -use ethereum_consensus::altair::minimal as pre_spec; -use ethereum_consensus::bellatrix::minimal as spec; -use ethereum_consensus::bellatrix::minimal::NoOpExecutionEngine; -use ethereum_consensus::state_transition::minimal::{BeaconState, Executor}; +use ethereum_consensus::{ + altair::minimal as pre_spec, + bellatrix::{minimal as spec, minimal::NoOpExecutionEngine}, + state_transition::minimal::{BeaconState, Executor}, +}; use ssz_rs::prelude::*; #[test] diff --git a/tests/spec_test_runners/bls/mod.rs b/tests/spec_test_runners/bls/mod.rs index 153a13692..0a9207ed4 100644 --- a/tests/spec_test_runners/bls/mod.rs +++ b/tests/spec_test_runners/bls/mod.rs @@ -1,10 +1,12 @@ use crate::test_utils::{load_yaml, TestCase}; -use ethereum_consensus::crypto::{ - aggregate, aggregate_verify, eth_aggregate_public_keys, eth_fast_aggregate_verify, - fast_aggregate_verify, verify_signature, PublicKey, SecretKey, Signature, +use ethereum_consensus::{ + crypto::{ + aggregate, aggregate_verify, eth_aggregate_public_keys, eth_fast_aggregate_verify, + fast_aggregate_verify, verify_signature, PublicKey, SecretKey, Signature, + }, + primitives::Bytes32, + serde as eth_serde, }; -use ethereum_consensus::primitives::Bytes32; -use ethereum_consensus::serde as eth_serde; use serde::Deserialize; use serde_with::{serde_as, DefaultOnError}; @@ -60,19 +62,8 @@ impl AggregateVerifyTestCase { } pub fn run(&self) -> bool { - let public_keys = self - .input - .pubkeys - .iter() - .flatten() - .cloned() - .collect::>(); - let messages = self - .input - .messages - .iter() - .map(|m| m.as_ref()) - .collect::>(); + let public_keys = self.input.pubkeys.iter().flatten().cloned().collect::>(); + let messages = self.input.messages.iter().map(|m| m.as_ref()).collect::>(); let signature = self.input.signature.as_ref().unwrap(); aggregate_verify(&public_keys, &messages, signature).is_ok() } @@ -89,7 +80,7 @@ impl TestCase for AggregateVerifyTestCase { fn verify_failure(&self) -> bool { if self.input.signature.is_none() { - return true; + return true } !self.run() } @@ -144,13 +135,13 @@ impl TestCase for FastAggregateVerifyTestCase { fn verify_failure(&self) -> bool { if self.input.signature.is_none() { - return true; + return true } if self.input.pubkeys.iter().any(|key| { let input: Result = serde_yaml::from_str(key); input.is_err() }) { - return true; + return true } !self.run() @@ -185,12 +176,7 @@ impl TestCase for SignTestCase { } fn verify_success(&self) -> bool { - let signature = self - .input - .privkey - .as_ref() - .unwrap() - .sign(self.input.message.as_ref()); + let signature = self.input.privkey.as_ref().unwrap().sign(self.input.message.as_ref()); &signature == self.output.as_ref().unwrap() } @@ -242,10 +228,10 @@ impl TestCase for VerifyTestCase { fn verify_failure(&self) -> bool { if self.input.signature.is_none() { - return true; + return true } if self.input.pubkey.is_none() { - return true; + return true } !self.run() } @@ -334,14 +320,14 @@ impl TestCase for EthFastAggregateVerifyTestCase { fn verify_failure(&self) -> bool { if self.input.signature.is_none() { - return true; + return true } if self.input.public_keys.iter().any(|key| { let input: Result = serde_yaml::from_str(key); input.is_err() }) { - return true; + return true } !self.run() diff --git a/tests/spec_test_runners/epoch_processing/mod.rs b/tests/spec_test_runners/epoch_processing/mod.rs index f34994a7e..ce43eed0e 100644 --- a/tests/spec_test_runners/epoch_processing/mod.rs +++ b/tests/spec_test_runners/epoch_processing/mod.rs @@ -9,11 +9,7 @@ fn load_epoch_test(test_case_path: &str) -> (S, Option = load_snappy_ssz(&path); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; (pre, post, config) } diff --git a/tests/spec_test_runners/finality/mod.rs b/tests/spec_test_runners/finality/mod.rs index f06126fca..61eb55495 100644 --- a/tests/spec_test_runners/finality/mod.rs +++ b/tests/spec_test_runners/finality/mod.rs @@ -39,18 +39,10 @@ where blocks.push(block); } - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - blocks, - config, - } + Self { pre, post, blocks, config } } pub fn execute(&mut self, f: F) @@ -61,12 +53,7 @@ where Config::Minimal => Context::for_minimal(), Config::Mainnet => Context::for_mainnet(), }; - let result = f( - &mut self.pre, - &mut self.blocks, - Validation::Enabled, - &context, - ); + let result = f(&mut self.pre, &mut self.blocks, Validation::Enabled, &context); if let Some(post) = self.post.as_ref() { assert_eq!(&self.pre, post); } else { diff --git a/tests/spec_test_runners/fork/mod.rs b/tests/spec_test_runners/fork/mod.rs index 9fb2791c6..5eefddc54 100644 --- a/tests/spec_test_runners/fork/mod.rs +++ b/tests/spec_test_runners/fork/mod.rs @@ -20,11 +20,8 @@ where let path = test_case_path.to_string() + "/post.ssz_snappy"; let post: T = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; Self { pre, post, config } } diff --git a/tests/spec_test_runners/genesis/mod.rs b/tests/spec_test_runners/genesis/mod.rs index 203f0afac..192b5fb65 100644 --- a/tests/spec_test_runners/genesis/mod.rs +++ b/tests/spec_test_runners/genesis/mod.rs @@ -1,6 +1,8 @@ use crate::test_utils::{load_snappy_ssz, load_yaml, Config}; -use ethereum_consensus::primitives::{Bytes32, Hash32}; -use ethereum_consensus::state_transition::{Context, Result}; +use ethereum_consensus::{ + primitives::{Bytes32, Hash32}, + state_transition::{Context, Result}, +}; use serde::Deserialize; use std::fmt; @@ -55,19 +57,10 @@ where let path = test_case_path.to_string() + "/state.ssz_snappy"; let state: S = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - eth1, - deposits, - execution_payload_header, - state, - config, - } + Self { eth1, deposits, execution_payload_header, state, config } } pub fn execute(&mut self, f: F) @@ -113,11 +106,7 @@ where todo!("support preset"); }; - Self { - state, - is_valid, - config, - } + Self { state, is_valid, config } } pub fn execute(&mut self, f: F) diff --git a/tests/spec_test_runners/operations/mod.rs b/tests/spec_test_runners/operations/mod.rs index 7114f66ed..7b661d046 100644 --- a/tests/spec_test_runners/operations/mod.rs +++ b/tests/spec_test_runners/operations/mod.rs @@ -25,18 +25,10 @@ where let path = test_case_path.to_string() + "/attestation.ssz_snappy"; let operation: T = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - config, - } + Self { pre, post, operation, config } } pub fn execute(&mut self, f: F) @@ -80,18 +72,10 @@ where let path = test_case_path.to_string() + "/attester_slashing.ssz_snappy"; let operation: T = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - config, - } + Self { pre, post, operation, config } } pub fn execute(&mut self, f: F) @@ -135,18 +119,10 @@ where let path = test_case_path.to_string() + "/block.ssz_snappy"; let operation: T = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - config, - } + Self { pre, post, operation, config } } pub fn execute(&mut self, f: F) @@ -190,18 +166,10 @@ where let path = test_case_path.to_string() + "/deposit.ssz_snappy"; let operation = load_snappy_ssz::(&path); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - config, - } + Self { pre, post, operation, config } } pub fn execute(&mut self, f: F) @@ -249,18 +217,10 @@ where let path = test_case_path.to_string() + "/proposer_slashing.ssz_snappy"; let operation = load_snappy_ssz::(&path); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - config, - } + Self { pre, post, operation, config } } pub fn execute(&mut self, f: F) @@ -308,18 +268,10 @@ where let path = test_case_path.to_string() + "/voluntary_exit.ssz_snappy"; let operation: T = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - config, - } + Self { pre, post, operation, config } } pub fn execute(&mut self, f: F) @@ -363,18 +315,10 @@ where let path = test_case_path.to_string() + "/sync_aggregate.ssz_snappy"; let operation: T = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - config, - } + Self { pre, post, operation, config } } pub fn execute(&mut self, f: F) @@ -427,19 +371,10 @@ where let path = test_case_path.to_string() + "/execution.yaml"; let execution_validity: ExecutionValidity = load_yaml(&path); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - operation, - execution_validity, - config, - } + Self { pre, post, operation, execution_validity, config } } pub fn execute(&mut self, f: F) diff --git a/tests/spec_test_runners/random/mod.rs b/tests/spec_test_runners/random/mod.rs index fe8bc8835..50ea21afa 100644 --- a/tests/spec_test_runners/random/mod.rs +++ b/tests/spec_test_runners/random/mod.rs @@ -39,18 +39,10 @@ where blocks.push(block); } - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - blocks, - config, - } + Self { pre, post, blocks, config } } pub fn execute(&mut self, f: F) @@ -61,12 +53,7 @@ where Config::Minimal => Context::for_minimal(), Config::Mainnet => Context::for_mainnet(), }; - let result = f( - &mut self.pre, - &mut self.blocks, - Validation::Enabled, - &context, - ); + let result = f(&mut self.pre, &mut self.blocks, Validation::Enabled, &context); if let Some(post) = self.post.as_ref() { assert_eq!(&self.pre, post); } else { diff --git a/tests/spec_test_runners/rewards/mod.rs b/tests/spec_test_runners/rewards/mod.rs index 9c3f12b05..0d95f978f 100644 --- a/tests/spec_test_runners/rewards/mod.rs +++ b/tests/spec_test_runners/rewards/mod.rs @@ -1,6 +1,5 @@ use crate::test_utils::{load_snappy_ssz, Config}; -use ethereum_consensus::primitives::Gwei; -use ethereum_consensus::state_transition::Context; +use ethereum_consensus::{primitives::Gwei, state_transition::Context}; use ssz_rs::prelude::*; use std::fmt; // NOTE: constant across presets @@ -55,11 +54,8 @@ where let path = test_case_path.to_string() + "/inactivity_penalty_deltas.ssz_snappy"; let inactivity_penalty_deltas: Deltas = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; Self { pre, @@ -133,11 +129,8 @@ where let path = test_case_path.to_string() + "/inactivity_penalty_deltas.ssz_snappy"; let inactivity_penalty_deltas: Deltas = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; Self { pre, @@ -211,11 +204,8 @@ where let path = test_case_path.to_string() + "/inactivity_penalty_deltas.ssz_snappy"; let inactivity_penalty_deltas: Deltas = load_snappy_ssz(&path).unwrap(); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; Self { pre, diff --git a/tests/spec_test_runners/sanity/mod.rs b/tests/spec_test_runners/sanity/mod.rs index 5975fbc19..62e53e5ed 100644 --- a/tests/spec_test_runners/sanity/mod.rs +++ b/tests/spec_test_runners/sanity/mod.rs @@ -1,6 +1,8 @@ use crate::test_utils::{load_snappy_ssz, load_yaml, Config}; -use ethereum_consensus::primitives::Slot; -use ethereum_consensus::state_transition::{Context, Result, Validation}; +use ethereum_consensus::{ + primitives::Slot, + state_transition::{Context, Result, Validation}, +}; use serde::Deserialize; use std::fmt; @@ -40,18 +42,10 @@ where blocks.push(block); } - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - blocks, - config, - } + Self { pre, post, blocks, config } } pub fn execute(&mut self, f: F) @@ -62,12 +56,7 @@ where Config::Minimal => Context::for_minimal(), Config::Mainnet => Context::for_mainnet(), }; - let result = f( - &mut self.pre, - &mut self.blocks, - Validation::Enabled, - &context, - ); + let result = f(&mut self.pre, &mut self.blocks, Validation::Enabled, &context); if let Some(post) = self.post.as_ref() { assert_eq!(&self.pre, post); } else { @@ -97,18 +86,10 @@ where let path = test_case_path.to_string() + "/slots.yaml"; let slots: Slot = load_yaml(&path); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - pre, - post, - slots, - config, - } + Self { pre, post, slots, config } } pub fn execute(&mut self, f: F) diff --git a/tests/spec_test_runners/shuffling/mod.rs b/tests/spec_test_runners/shuffling/mod.rs index c00128dca..fc088d05f 100644 --- a/tests/spec_test_runners/shuffling/mod.rs +++ b/tests/spec_test_runners/shuffling/mod.rs @@ -1,7 +1,7 @@ use crate::test_utils::{load_yaml, Config}; -use ethereum_consensus::phase0::compute_shuffled_index; -use ethereum_consensus::primitives::Bytes32; -use ethereum_consensus::state_transition::Context; +use ethereum_consensus::{ + phase0::compute_shuffled_index, primitives::Bytes32, state_transition::Context, +}; use serde::Deserialize; #[derive(Debug, Deserialize)] @@ -23,11 +23,8 @@ impl CoreTestCase { let data: ShufflingTestData = load_yaml(&path); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; Self { data, config } } diff --git a/tests/spec_test_runners/transition/mod.rs b/tests/spec_test_runners/transition/mod.rs index df9db8d65..b02482d22 100644 --- a/tests/spec_test_runners/transition/mod.rs +++ b/tests/spec_test_runners/transition/mod.rs @@ -1,6 +1,8 @@ use crate::test_utils::{load_snappy_ssz, load_yaml, Config}; -use ethereum_consensus::primitives::Epoch; -use ethereum_consensus::state_transition::{Context, Result}; +use ethereum_consensus::{ + primitives::Epoch, + state_transition::{Context, Result}, +}; use serde::Deserialize; use std::fmt; @@ -30,18 +32,10 @@ where let path = test_case_path.to_string() + "/meta.yaml"; let meta: Meta = load_yaml(&path); - let config = if test_case_path.contains("minimal") { - Config::Minimal - } else { - Config::Mainnet - }; + let config = + if test_case_path.contains("minimal") { Config::Minimal } else { Config::Mainnet }; - Self { - test_case_path: test_case_path.to_string(), - post, - meta, - config, - } + Self { test_case_path: test_case_path.to_string(), post, meta, config } } pub fn execute(&mut self, f: F) diff --git a/tests/test_utils.rs b/tests/test_utils.rs index 8cd3a741a..594df1159 100644 --- a/tests/test_utils.rs +++ b/tests/test_utils.rs @@ -1,10 +1,7 @@ #![cfg(feature = "spec-tests")] use serde::Deserialize; -use std::fmt; -use std::fs::File; -use std::io::Read; -use std::path::Path; +use std::{fmt, fs::File, io::Read, path::Path}; #[derive(Debug)] pub enum Config { @@ -20,11 +17,8 @@ pub trait TestCase: fmt::Debug { fn verify_failure(&self) -> bool; fn execute(&self) { - let result = if self.should_succeed() { - self.verify_success() - } else { - self.verify_failure() - }; + let result = + if self.should_succeed() { self.verify_success() } else { self.verify_failure() }; assert!(result, "{self:#?}") } } @@ -53,7 +47,7 @@ pub fn load_snappy_ssz_bytes(path: &Path) -> Vec { pub fn load_snappy_ssz(path: &str) -> Option { let path = Path::new(path); if !path.exists() { - return None; + return None } let buffer = load_snappy_ssz_bytes(path);