Skip to content

Commit

Permalink
refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
realbigsean committed May 5, 2022
1 parent 24c6273 commit 513d2b2
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 62 deletions.
8 changes: 5 additions & 3 deletions consensus/fork_choice/src/fork_choice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,7 @@ where
}

// Update unrealized justified/finalized checkpoints.
let (mini_beacon_state, _) =
let (justifiable_beacon_state, _) =
state_processing::per_epoch_processing::altair::process_justifiable(state, spec)?;

let target_slot = block
Expand Down Expand Up @@ -732,8 +732,10 @@ where
justified_checkpoint: state.current_justified_checkpoint(),
finalized_checkpoint: state.finalized_checkpoint(),
execution_status,
unrealized_justified_checkpoint: Some(mini_beacon_state.current_justified_checkpoint),
unrealized_finalized_checkpoint: Some(mini_beacon_state.finalized_checkpoint),
unrealized_justified_checkpoint: Some(
justifiable_beacon_state.current_justified_checkpoint,
),
unrealized_finalized_checkpoint: Some(justifiable_beacon_state.finalized_checkpoint),
})?;

Ok(())
Expand Down
16 changes: 8 additions & 8 deletions consensus/state_processing/src/per_epoch_processing/altair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ pub use rewards_and_penalties::process_rewards_and_penalties;
pub use sync_committee_updates::process_sync_committee_updates;
use types::beacon_state::participation_cache::CurrentEpochParticipationCache;
pub use types::beacon_state::participation_cache::ParticipationCache;
use types::{BeaconState, ChainSpec, EthSpec, MiniBeaconState, RelativeEpoch};
use types::justifiable_beacon_state::JustifiableBeaconState;
use types::{BeaconState, ChainSpec, EthSpec, RelativeEpoch};

pub mod inactivity_updates;
pub mod justification_and_finalization;
Expand All @@ -25,8 +26,8 @@ pub fn process_epoch<T: EthSpec>(
) -> Result<EpochProcessingSummary<T>, Error> {
state.build_committee_cache(RelativeEpoch::Next, spec)?;

let (mini_beacon_state, participation_cache) = process_justifiable(state, spec)?;
state.update_justifiable(mini_beacon_state);
let (justifiable_beacon_state, participation_cache) = process_justifiable(state, spec)?;
state.update_justifiable(justifiable_beacon_state);

let sync_committee = state.current_sync_committee()?.clone();

Expand Down Expand Up @@ -77,21 +78,20 @@ pub fn process_epoch<T: EthSpec>(
pub fn process_justifiable<T: EthSpec>(
state: &mut BeaconState<T>,
spec: &ChainSpec,
) -> Result<(MiniBeaconState<T>, ParticipationCache), Error> {
) -> Result<(JustifiableBeaconState<T>, ParticipationCache), Error> {
// Ensure the committee caches are built.
state.build_committee_cache(RelativeEpoch::Previous, spec)?;
state.build_committee_cache(RelativeEpoch::Current, spec)?;

// Pre-compute participating indices and total balances.
let prev_participation_cache = state.get_previous_epoch_participation_cache(spec)?;

let current_participation_cache = CurrentEpochParticipationCache::new(state, spec)?;

let participation_cache =
ParticipationCache::new(prev_participation_cache, current_participation_cache);

// Justification and finalization.
let mini_beacon_state = process_justification_and_finalization(state, &participation_cache)?;
let justifiable_beacon_state =
process_justification_and_finalization(state, &participation_cache)?;

Ok((mini_beacon_state, participation_cache))
Ok((justifiable_beacon_state, participation_cache))
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ use crate::per_epoch_processing::weigh_justification_and_finalization;
use crate::per_epoch_processing::Error;
use safe_arith::SafeArith;
use types::consts::altair::TIMELY_TARGET_FLAG_INDEX;
use types::{BeaconState, EthSpec, MiniBeaconState};
use types::justifiable_beacon_state::JustifiableBeaconState;
use types::{BeaconState, EthSpec};

/// Update the justified and finalized checkpoints for matching target attestations.
pub fn process_justification_and_finalization<T: EthSpec>(
state: &BeaconState<T>,
participation_cache: &ParticipationCache,
) -> Result<MiniBeaconState<T>, Error> {
) -> Result<JustifiableBeaconState<T>, Error> {
if state.current_epoch() <= T::genesis_epoch().safe_add(1)? {
return Ok(MiniBeaconState {
return Ok(JustifiableBeaconState {
current_justified_checkpoint: state.current_justified_checkpoint(),
previous_justified_checkpoint: state.previous_justified_checkpoint(),
justification_bits: state.justification_bits().clone(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ pub fn process_justification_and_finalization<T: EthSpec>(
return Ok(());
}

let mini_beacon_state = weigh_justification_and_finalization(
let justifiable_beacon_state = weigh_justification_and_finalization(
state,
total_balances.current_epoch(),
total_balances.previous_epoch_target_attesters(),
total_balances.current_epoch_target_attesters(),
)?;
state.update_justifiable(mini_beacon_state);
state.update_justifiable(justifiable_beacon_state);

Ok(())
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::per_epoch_processing::Error;
use safe_arith::SafeArith;
use std::ops::Range;
use types::{BeaconState, Checkpoint, EthSpec, MiniBeaconState};
use types::justifiable_beacon_state::JustifiableBeaconState;
use types::{BeaconState, Checkpoint, EthSpec};

/// Update the justified and finalized checkpoints for matching target attestations.
#[allow(clippy::if_same_then_else)] // For readability and consistency with spec.
Expand All @@ -10,42 +11,42 @@ pub fn weigh_justification_and_finalization<T: EthSpec>(
total_active_balance: u64,
previous_target_balance: u64,
current_target_balance: u64,
) -> Result<MiniBeaconState<T>, Error> {
) -> Result<JustifiableBeaconState<T>, Error> {
let previous_epoch = state.previous_epoch();
let current_epoch = state.current_epoch();

let old_previous_justified_checkpoint = state.previous_justified_checkpoint();
let old_current_justified_checkpoint = state.current_justified_checkpoint();

let mut mini_beacon_state = MiniBeaconState {
let mut justifiable_beacon_state = JustifiableBeaconState {
current_justified_checkpoint: state.current_justified_checkpoint(),
previous_justified_checkpoint: state.previous_justified_checkpoint(),
justification_bits: state.justification_bits().clone(),
finalized_checkpoint: state.finalized_checkpoint(),
};

// Process justifications
mini_beacon_state.previous_justified_checkpoint =
mini_beacon_state.current_justified_checkpoint;
mini_beacon_state.justification_bits.shift_up(1)?;
justifiable_beacon_state.previous_justified_checkpoint =
justifiable_beacon_state.current_justified_checkpoint;
justifiable_beacon_state.justification_bits.shift_up(1)?;

if previous_target_balance.safe_mul(3)? >= total_active_balance.safe_mul(2)? {
mini_beacon_state.current_justified_checkpoint = Checkpoint {
justifiable_beacon_state.current_justified_checkpoint = Checkpoint {
epoch: previous_epoch,
root: *state.get_block_root_at_epoch(previous_epoch)?,
};
mini_beacon_state.justification_bits.set(1, true)?;
justifiable_beacon_state.justification_bits.set(1, true)?;
}
// If the current epoch gets justified, fill the last bit.
if current_target_balance.safe_mul(3)? >= total_active_balance.safe_mul(2)? {
mini_beacon_state.current_justified_checkpoint = Checkpoint {
justifiable_beacon_state.current_justified_checkpoint = Checkpoint {
epoch: current_epoch,
root: *state.get_block_root_at_epoch(current_epoch)?,
};
mini_beacon_state.justification_bits.set(0, true)?;
justifiable_beacon_state.justification_bits.set(0, true)?;
}

let bits = mini_beacon_state.justification_bits.clone();
let bits = justifiable_beacon_state.justification_bits.clone();
let all_bits_set = |range: Range<usize>| -> Result<bool, Error> {
for i in range {
if !bits.get(i).map_err(Error::InvalidJustificationBit)? {
Expand All @@ -58,21 +59,21 @@ pub fn weigh_justification_and_finalization<T: EthSpec>(
// The 2nd/3rd/4th most recent epochs are all justified, the 2nd using the 4th as source.
if all_bits_set(1..4)? && old_previous_justified_checkpoint.epoch.safe_add(3)? == current_epoch
{
mini_beacon_state.finalized_checkpoint = old_previous_justified_checkpoint;
justifiable_beacon_state.finalized_checkpoint = old_previous_justified_checkpoint;
}
// The 2nd/3rd most recent epochs are both justified, the 2nd using the 3rd as source.
if all_bits_set(1..3)? && old_previous_justified_checkpoint.epoch.safe_add(2)? == current_epoch
{
mini_beacon_state.finalized_checkpoint = old_previous_justified_checkpoint;
justifiable_beacon_state.finalized_checkpoint = old_previous_justified_checkpoint;
}
// The 1st/2nd/3rd most recent epochs are all justified, the 1st using the 3nd as source.
if all_bits_set(0..3)? && old_current_justified_checkpoint.epoch.safe_add(2)? == current_epoch {
mini_beacon_state.finalized_checkpoint = old_current_justified_checkpoint;
justifiable_beacon_state.finalized_checkpoint = old_current_justified_checkpoint;
}
// The 1st/2nd most recent epochs are both justified, the 1st using the 2nd as source.
if all_bits_set(0..2)? && old_current_justified_checkpoint.epoch.safe_add(1)? == current_epoch {
mini_beacon_state.finalized_checkpoint = old_current_justified_checkpoint;
justifiable_beacon_state.finalized_checkpoint = old_current_justified_checkpoint;
}

Ok(mini_beacon_state)
Ok(justifiable_beacon_state)
}
30 changes: 15 additions & 15 deletions consensus/types/src/beacon_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub use self::committee_cache::{
compute_committee_index_in_epoch, compute_committee_range_in_epoch, epoch_committee_count,
CommitteeCache,
};
use crate::justifiable_beacon_state::JustifiableBeaconState;
pub use clone_config::CloneConfig;
pub use eth_spec::*;
pub use iter::BlockRootsIter;
Expand Down Expand Up @@ -1367,20 +1368,17 @@ impl<T: EthSpec> BeaconState<T> {
&mut self,
spec: &ChainSpec,
) -> Result<PreviousParticipationCache, BeaconStateError> {
// Check cache if it was initialized in the states current epoch.
if let Some(cache) = self.previous_epoch_participation_cache() {
if cache.initialized_epoch() == self.current_epoch() {
Ok(cache.clone())
} else {
// rebuild cache
let cache = PreviousParticipationCache::new(self, spec)?;
*self.previous_epoch_participation_cache_mut() = Some(cache.clone());
Ok(cache)
return Ok(cache.clone());
}
} else {
let cache = PreviousParticipationCache::new(self, spec)?;
*self.previous_epoch_participation_cache_mut() = Some(cache.clone());
Ok(cache)
}

// Rebuild the cache.
let cache = PreviousParticipationCache::new(self, spec)?;
*self.previous_epoch_participation_cache_mut() = Some(cache.clone());
Ok(cache)
}

/// Returns `true` if the committee cache for `relative_epoch` is built and ready to use.
Expand Down Expand Up @@ -1667,11 +1665,13 @@ impl<T: EthSpec> BeaconState<T> {
Ok(sync_committee)
}

pub fn update_justifiable(&mut self, mini_beacon_state: MiniBeaconState<T>) {
*self.current_justified_checkpoint_mut() = mini_beacon_state.current_justified_checkpoint;
*self.previous_justified_checkpoint_mut() = mini_beacon_state.previous_justified_checkpoint;
*self.finalized_checkpoint_mut() = mini_beacon_state.finalized_checkpoint;
*self.justification_bits_mut() = mini_beacon_state.justification_bits;
pub fn update_justifiable(&mut self, justifiable_beacon_state: JustifiableBeaconState<T>) {
*self.current_justified_checkpoint_mut() =
justifiable_beacon_state.current_justified_checkpoint;
*self.previous_justified_checkpoint_mut() =
justifiable_beacon_state.previous_justified_checkpoint;
*self.finalized_checkpoint_mut() = justifiable_beacon_state.finalized_checkpoint;
*self.justification_bits_mut() = justifiable_beacon_state.justification_bits;
}
}

Expand Down
13 changes: 7 additions & 6 deletions consensus/types/src/beacon_state/participation_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::{
};
use safe_arith::{ArithError, SafeArith};
use std::collections::HashMap;
use std::sync::Arc;

#[derive(Debug, PartialEq)]
pub enum Error {
Expand Down Expand Up @@ -170,9 +171,9 @@ pub struct PreviousParticipationCache {
initialized_epoch: Epoch,
previous_epoch: Epoch,
/// Caches information about active validators pertaining to `self.previous_epoch`.
previous_epoch_participation: SingleEpochParticipationCache,
previous_epoch_participation: Arc<SingleEpochParticipationCache>,
/// Caches the result of the `get_eligible_validator_indices` function.
eligible_indices: Vec<usize>,
eligible_indices: Arc<Vec<usize>>,
}

impl PreviousParticipationCache {
Expand Down Expand Up @@ -230,8 +231,8 @@ impl PreviousParticipationCache {
Ok(Self {
initialized_epoch: state.current_epoch(),
previous_epoch,
previous_epoch_participation,
eligible_indices,
previous_epoch_participation: Arc::new(previous_epoch_participation),
eligible_indices: Arc::new(eligible_indices),
})
}

Expand Down Expand Up @@ -324,9 +325,9 @@ pub struct ParticipationCache {
current_epoch_participation: SingleEpochParticipationCache,
previous_epoch: Epoch,
/// Caches information about active validators pertaining to `self.previous_epoch`.
previous_epoch_participation: SingleEpochParticipationCache,
previous_epoch_participation: Arc<SingleEpochParticipationCache>,
/// Caches the result of the `get_eligible_validator_indices` function.
eligible_indices: Vec<usize>,
eligible_indices: Arc<Vec<usize>>,
}

impl ParticipationCache {
Expand Down
9 changes: 9 additions & 0 deletions consensus/types/src/justifiable_beacon_state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use crate::{Checkpoint, EthSpec};
use ssz_types::BitVector;

pub struct JustifiableBeaconState<T: EthSpec> {
pub current_justified_checkpoint: Checkpoint,
pub previous_justified_checkpoint: Checkpoint,
pub justification_bits: BitVector<T::JustificationBitsLength>,
pub finalized_checkpoint: Checkpoint,
}
8 changes: 1 addition & 7 deletions consensus/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub mod free_attestation;
pub mod graffiti;
pub mod historical_batch;
pub mod indexed_attestation;
pub mod justifiable_beacon_state;
pub mod pending_attestation;
pub mod proposer_preparation_data;
pub mod proposer_slashing;
Expand Down Expand Up @@ -172,10 +173,3 @@ pub use bls::{
};
pub use ssz_types::{typenum, typenum::Unsigned, BitList, BitVector, FixedVector, VariableList};
pub use superstruct::superstruct;

pub struct MiniBeaconState<T: EthSpec> {
pub current_justified_checkpoint: Checkpoint,
pub previous_justified_checkpoint: Checkpoint,
pub justification_bits: BitVector<T::JustificationBitsLength>,
pub finalized_checkpoint: Checkpoint,
}
4 changes: 2 additions & 2 deletions testing/ef_tests/src/cases/epoch_processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ impl<E: EthSpec> EpochTransition<E> for JustificationAndFinalization {
let prev_participation_cache =
state.get_previous_epoch_participation_cache(spec)?;
let current_participation_cache = CurrentEpochParticipationCache::new(state, spec)?;
let mini_beacon_state = altair::process_justification_and_finalization(
let justifiable_beacon_state = altair::process_justification_and_finalization(
state,
&altair::ParticipationCache::new(
prev_participation_cache,
current_participation_cache,
),
)?;
state.update_justifiable(mini_beacon_state);
state.update_justifiable(justifiable_beacon_state);
Ok(())
}
}
Expand Down

0 comments on commit 513d2b2

Please sign in to comment.