Skip to content

Commit

Permalink
Merge pull request #203 from ralexstokes/cargo-fmt
Browse files Browse the repository at this point in the history
add cargo fmt config in line with other repos in this family
  • Loading branch information
ralexstokes committed Jul 16, 2023
2 parents 1728010 + 1adab3c commit 6d34a94
Show file tree
Hide file tree
Showing 132 changed files with 1,862 additions and 3,564 deletions.
34 changes: 11 additions & 23 deletions examples/serde.rs
Original file line number Diff line number Diff line change
@@ -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}");
Expand Down
10 changes: 6 additions & 4 deletions examples/sketch.rs
Original file line number Diff line number Diff line change
@@ -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();
Expand Down
11 changes: 6 additions & 5 deletions examples/state_transition_across_multiple_forks.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down
9 changes: 9 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -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
10 changes: 6 additions & 4 deletions src/altair/beacon_block.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand Down
10 changes: 6 additions & 4 deletions src/altair/beacon_state.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand Down
121 changes: 42 additions & 79 deletions src/altair/block_processing.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand All @@ -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)?;
Expand All @@ -103,7 +104,7 @@ pub fn process_attestation<
expected_length: committee.len(),
length: attestation.aggregation_bits.len(),
},
)));
)))
}

// Participation flag indices
Expand All @@ -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);
Expand All @@ -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(())
}

Expand Down Expand Up @@ -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;
Expand All @@ -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);
}
Expand Down Expand Up @@ -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::<Vec<_>>();
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::<Vec<_>>();
let previous_slot = u64::max(state.slot, 1) - 1;
let domain = get_domain(
state,
Expand All @@ -301,7 +272,7 @@ pub fn process_sync_aggregate<
signature: sync_aggregate.sync_committee_signature.clone(),
root: signing_root,
},
)));
)))
}

// Compute participant and proposer rewards
Expand All @@ -324,23 +295,15 @@ pub fn process_sync_aggregate<
.collect::<HashMap<&BlsPublicKey, usize>>();
let mut committee_indices: Vec<ValidatorIndex> = 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);
}
Expand Down
Loading

0 comments on commit 6d34a94

Please sign in to comment.