Files
lighthouse/consensus/proto_array/src/justified_balances.rs
Mac L 969d12dc6f Use E for EthSpec globally (#5264)
* Use `E` for `EthSpec` globally

* Fix tests

* Merge branch 'unstable' into e-ethspec

* Merge branch 'unstable' into e-ethspec

# Conflicts:
#	beacon_node/execution_layer/src/engine_api.rs
#	beacon_node/execution_layer/src/engine_api/http.rs
#	beacon_node/execution_layer/src/engine_api/json_structures.rs
#	beacon_node/execution_layer/src/test_utils/handle_rpc.rs
#	beacon_node/store/src/partial_beacon_state.rs
#	consensus/types/src/beacon_block.rs
#	consensus/types/src/beacon_block_body.rs
#	consensus/types/src/beacon_state.rs
#	consensus/types/src/config_and_preset.rs
#	consensus/types/src/execution_payload.rs
#	consensus/types/src/execution_payload_header.rs
#	consensus/types/src/light_client_optimistic_update.rs
#	consensus/types/src/payload.rs
#	lcli/src/parse_ssz.rs
2024-04-02 15:12:25 +00:00

63 lines
2.0 KiB
Rust

use safe_arith::{ArithError, SafeArith};
use types::{BeaconState, EthSpec};
#[derive(Debug, PartialEq, Clone, Default)]
pub struct JustifiedBalances {
/// The effective balances for every validator in a given justified state.
///
/// Any validator who is not active in the epoch of the justified state is assigned a balance of
/// zero.
pub effective_balances: Vec<u64>,
/// The sum of `self.effective_balances`.
pub total_effective_balance: u64,
/// The number of active validators included in `self.effective_balances`.
pub num_active_validators: u64,
}
impl JustifiedBalances {
pub fn from_justified_state<E: EthSpec>(state: &BeaconState<E>) -> Result<Self, ArithError> {
let current_epoch = state.current_epoch();
let mut total_effective_balance = 0u64;
let mut num_active_validators = 0u64;
let effective_balances = state
.validators()
.iter()
.map(|validator| {
if !validator.slashed && validator.is_active_at(current_epoch) {
total_effective_balance.safe_add_assign(validator.effective_balance)?;
num_active_validators.safe_add_assign(1)?;
Ok(validator.effective_balance)
} else {
Ok(0)
}
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
effective_balances,
total_effective_balance,
num_active_validators,
})
}
pub fn from_effective_balances(effective_balances: Vec<u64>) -> Result<Self, ArithError> {
let mut total_effective_balance = 0;
let mut num_active_validators = 0;
for &balance in &effective_balances {
if balance != 0 {
total_effective_balance.safe_add_assign(balance)?;
num_active_validators.safe_add_assign(1)?;
}
}
Ok(Self {
effective_balances,
total_effective_balance,
num_active_validators,
})
}
}