Make BeaconState.balances a tree list!

This commit is contained in:
Michael Sproul
2021-12-01 14:14:47 +11:00
parent 4b808d3c72
commit fca92c37ad
11 changed files with 76 additions and 31 deletions

View File

@@ -16,7 +16,7 @@ pub use initiate_validator_exit::initiate_validator_exit;
pub use slash_validator::slash_validator;
use safe_arith::SafeArith;
use types::{BeaconState, BeaconStateError, EthSpec};
use types::{BeaconState, BeaconStateError, EthSpec, GetBalanceMut};
/// Increase the balance of a validator, erroring upon overflow, as per the spec.
pub fn increase_balance<E: EthSpec>(
@@ -24,7 +24,10 @@ pub fn increase_balance<E: EthSpec>(
index: usize,
delta: u64,
) -> Result<(), BeaconStateError> {
state.get_balance_mut(index)?.safe_add_assign(delta)?;
state
.balances_mut()
.get_balance_mut(index)?
.safe_add_assign(delta)?;
Ok(())
}
@@ -34,7 +37,8 @@ pub fn decrease_balance<E: EthSpec>(
index: usize,
delta: u64,
) -> Result<(), BeaconStateError> {
let balance = state.get_balance_mut(index)?;
let mut balances = state.balances_mut();
let balance = balances.get_balance_mut(index)?;
*balance = balance.saturating_sub(delta);
Ok(())
}

View File

@@ -1,6 +1,6 @@
use crate::per_epoch_processing::Error;
use safe_arith::{SafeArith, SafeArithIter};
use types::{BeaconState, BeaconStateError, ChainSpec, EthSpec, GetValidatorMut, Unsigned};
use types::{BeaconState, ChainSpec, EthSpec, GetBalanceMut, GetValidatorMut, Unsigned};
/// Process slashings.
pub fn process_slashings<T: EthSpec>(
@@ -15,7 +15,7 @@ pub fn process_slashings<T: EthSpec>(
let adjusted_total_slashing_balance =
std::cmp::min(sum_slashings.safe_mul(slashing_multiplier)?, total_balance);
let (validators, balances) = state.validators_and_balances_mut();
let (validators, mut balances) = state.validators_and_balances_mut();
for index in 0..validators.len() {
let validator = validators.get_validator(index)?;
if validator.slashed
@@ -32,9 +32,7 @@ pub fn process_slashings<T: EthSpec>(
.safe_mul(increment)?;
// Equivalent to `decrease_balance(state, index, penalty)`, but avoids borrowing `state`.
let balance = balances
.get_mut(index)
.ok_or(BeaconStateError::BalancesOutOfBounds(index))?;
let balance = balances.get_balance_mut(index)?;
*balance = balance.saturating_sub(penalty);
}
}