Skip to content

Commit 4380e05

Browse files
Delete the participation cache (#16)
1 parent a4427da commit 4380e05

File tree

17 files changed

+101
-565
lines changed

17 files changed

+101
-565
lines changed

beacon_node/beacon_chain/src/attestation_rewards.rs

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use crate::{BeaconChain, BeaconChainError, BeaconChainTypes};
22
use eth2::lighthouse::attestation_rewards::{IdealAttestationRewards, TotalAttestationRewards};
33
use eth2::lighthouse::StandardAttestationRewards;
4-
use participation_cache::ParticipationCache;
54
use safe_arith::SafeArith;
65
use serde_utils::quoted_u64::Quoted;
76
use slog::debug;
@@ -10,7 +9,7 @@ use state_processing::per_epoch_processing::altair::{
109
};
1110
use state_processing::{
1211
common::altair::BaseRewardPerIncrement,
13-
per_epoch_processing::altair::{participation_cache, rewards_and_penalties::get_flag_weight},
12+
per_epoch_processing::altair::rewards_and_penalties::get_flag_weight,
1413
};
1514
use std::collections::HashMap;
1615
use store::consts::altair::{
@@ -134,8 +133,6 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
134133
let spec = &self.spec;
135134

136135
// Calculate ideal_rewards
137-
let participation_cache = ParticipationCache::new(&state, spec)
138-
.map_err(|_| BeaconChainError::AttestationRewardsError)?;
139136
process_justification_and_finalization(&state)?.apply_changes_to_state(&mut state);
140137
process_inactivity_updates_slow(&mut state, spec)?;
141138

@@ -147,14 +144,14 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
147144
let weight = get_flag_weight(flag_index)
148145
.map_err(|_| BeaconChainError::AttestationRewardsError)?;
149146

150-
let unslashed_participating_balance = participation_cache
151-
.previous_epoch_flag_attesting_balance(flag_index)
152-
.map_err(|_| BeaconChainError::AttestationRewardsError)?;
147+
let unslashed_participating_balance = state
148+
.progressive_balances_cache()
149+
.previous_epoch_flag_attesting_balance(flag_index)?;
153150

154151
let unslashed_participating_increments =
155152
unslashed_participating_balance.safe_div(spec.effective_balance_increment)?;
156153

157-
let total_active_balance = participation_cache.current_epoch_total_active_balance();
154+
let total_active_balance = state.get_total_active_balance()?;
158155

159156
let active_increments =
160157
total_active_balance.safe_div(spec.effective_balance_increment)?;
@@ -190,15 +187,15 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
190187
let mut total_rewards: Vec<TotalAttestationRewards> = Vec::new();
191188

192189
let validators = if validators.is_empty() {
193-
participation_cache.eligible_validator_indices().to_vec()
190+
Self::all_eligible_validator_indices(&state, previous_epoch)?
194191
} else {
195192
Self::validators_ids_to_indices(&mut state, validators)?
196193
};
197194

198195
for &validator_index in &validators {
199196
// Return 0s for unknown/inactive validator indices. This is a bit different from stable
200197
// where we error for unknown pubkeys.
201-
let Ok(validator) = participation_cache.get_validator(validator_index) else {
198+
let Ok(validator) = state.get_validator(validator_index) else {
202199
debug!(
203200
self.log,
204201
"No rewards for inactive/unknown validator";
@@ -215,7 +212,11 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
215212
});
216213
continue;
217214
};
218-
let eligible = validator.is_eligible;
215+
let previous_epoch_participation_flags = state
216+
.previous_epoch_participation()?
217+
.get(validator_index)
218+
.ok_or(BeaconChainError::AttestationRewardsError)?;
219+
let eligible = state.is_eligible_validator(previous_epoch, validator)?;
219220
let mut head_reward = 0i64;
220221
let mut target_reward = 0i64;
221222
let mut source_reward = 0i64;
@@ -228,9 +229,8 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
228229
let (ideal_reward, penalty) = ideal_rewards_hashmap
229230
.get(&(flag_index, effective_balance))
230231
.ok_or(BeaconChainError::AttestationRewardsError)?;
231-
let voted_correctly = validator
232-
.is_unslashed_participating_index(flag_index)
233-
.map_err(|_| BeaconChainError::AttestationRewardsError)?;
232+
let voted_correctly = !validator.slashed
233+
&& previous_epoch_participation_flags.has_flag(flag_index)?;
234234
if voted_correctly {
235235
if flag_index == TIMELY_HEAD_FLAG_INDEX {
236236
head_reward += *ideal_reward as i64;
@@ -314,6 +314,24 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
314314
Ok(max_steps)
315315
}
316316

317+
fn all_eligible_validator_indices(
318+
state: &BeaconState<T::EthSpec>,
319+
previous_epoch: Epoch,
320+
) -> Result<Vec<usize>, BeaconChainError> {
321+
state
322+
.validators()
323+
.iter()
324+
.enumerate()
325+
.filter_map(|(i, validator)| {
326+
state
327+
.is_eligible_validator(previous_epoch, validator)
328+
.map(|eligible| eligible.then_some(i))
329+
.map_err(BeaconChainError::BeaconStateError)
330+
.transpose()
331+
})
332+
.collect()
333+
}
334+
317335
fn validators_ids_to_indices(
318336
state: &mut BeaconState<T::EthSpec>,
319337
validators: Vec<ValidatorId>,

beacon_node/http_api/src/attestation_performance.rs

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use eth2::lighthouse::{
33
AttestationPerformance, AttestationPerformanceQuery, AttestationPerformanceStatistics,
44
};
55
use state_processing::{
6-
per_epoch_processing::altair::participation_cache::Error as ParticipationCacheError,
76
per_epoch_processing::EpochProcessingSummary, BlockReplayError, BlockReplayer,
87
};
98
use std::sync::Arc;
@@ -18,7 +17,6 @@ const BLOCK_ROOT_CHUNK_SIZE: usize = 100;
1817
enum AttestationPerformanceError {
1918
BlockReplay(#[allow(dead_code)] BlockReplayError),
2019
BeaconState(#[allow(dead_code)] BeaconStateError),
21-
ParticipationCache(#[allow(dead_code)] ParticipationCacheError),
2220
UnableToFindValidator(#[allow(dead_code)] usize),
2321
}
2422

@@ -34,12 +32,6 @@ impl From<BeaconStateError> for AttestationPerformanceError {
3432
}
3533
}
3634

37-
impl From<ParticipationCacheError> for AttestationPerformanceError {
38-
fn from(e: ParticipationCacheError) -> Self {
39-
Self::ParticipationCache(e)
40-
}
41-
}
42-
4335
pub fn get_attestation_performance<T: BeaconChainTypes>(
4436
target: String,
4537
query: AttestationPerformanceQuery,

consensus/fork_choice/src/fork_choice.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,11 @@ where
747747
| BeaconBlockRef::Capella(_)
748748
| BeaconBlockRef::Merge(_)
749749
| BeaconBlockRef::Altair(_) => {
750-
// FIXME(sproul): initialize progressive balances
750+
// NOTE: Processing justification & finalization requires the progressive
751+
// balances cache, but we cannot initialize it here as we only have an
752+
// immutable reference. The state *should* have come straight from block
753+
// processing, which initialises the cache, but if we add other `on_block`
754+
// calls in future it could be worth passing a mutable reference.
751755
per_epoch_processing::altair::process_justification_and_finalization(state)?
752756
}
753757
BeaconBlockRef::Base(_) => {

consensus/state_processing/src/all_caches.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ impl<E: EthSpec> AllCaches for BeaconState<E> {
2424
fn build_all_caches(&mut self, spec: &ChainSpec) -> Result<(), EpochCacheError> {
2525
self.build_caches(spec)?;
2626
initialize_epoch_cache(self, spec)?;
27-
initialize_progressive_balances_cache(self, None, spec)?;
27+
initialize_progressive_balances_cache(self, spec)?;
2828
Ok(())
2929
}
3030

consensus/state_processing/src/common/update_progressive_balances_cache.rs

Lines changed: 51 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,16 @@ use crate::metrics::{
33
PARTICIPATION_CURR_EPOCH_TARGET_ATTESTING_GWEI_PROGRESSIVE_TOTAL,
44
PARTICIPATION_PREV_EPOCH_TARGET_ATTESTING_GWEI_PROGRESSIVE_TOTAL,
55
};
6-
use crate::per_epoch_processing::altair::ParticipationCache;
76
use crate::{BlockProcessingError, EpochProcessingError};
87
use lighthouse_metrics::set_gauge;
9-
use std::borrow::Cow;
108
use types::{
119
is_progressive_balances_enabled, BeaconState, BeaconStateError, ChainSpec, Epoch,
12-
EpochTotalBalances, EthSpec, ProgressiveBalancesCache,
10+
EpochTotalBalances, EthSpec, ParticipationFlags, ProgressiveBalancesCache, Validator,
1311
};
1412

15-
/// Initializes the `ProgressiveBalancesCache` cache using balance values from the
16-
/// `ParticipationCache`. If the optional `&ParticipationCache` is not supplied, it will be computed
17-
/// from the `BeaconState`.
13+
/// Initializes the `ProgressiveBalancesCache` if it is unbuilt.
1814
pub fn initialize_progressive_balances_cache<E: EthSpec>(
1915
state: &mut BeaconState<E>,
20-
maybe_participation_cache: Option<&ParticipationCache>,
2116
spec: &ChainSpec,
2217
) -> Result<(), BeaconStateError> {
2318
if !is_progressive_balances_enabled(state)
@@ -26,29 +21,37 @@ pub fn initialize_progressive_balances_cache<E: EthSpec>(
2621
return Ok(());
2722
}
2823

29-
// FIXME(sproul): simplify the participation cache
30-
let participation_cache = match maybe_participation_cache {
31-
Some(cache) => Cow::Borrowed(cache),
32-
None => {
33-
state.build_total_active_balance_cache_at(state.current_epoch(), spec)?;
34-
Cow::Owned(
35-
ParticipationCache::new(state, spec)
36-
.map_err(|e| BeaconStateError::ParticipationCacheError(format!("{e:?}")))?,
37-
)
24+
// Calculate the total flag balances for previous & current epoch in a single iteration.
25+
// This calculates `get_total_balance(unslashed_participating_indices(..))` for each flag in
26+
// the current and previous epoch.
27+
let current_epoch = state.current_epoch();
28+
let previous_epoch = state.previous_epoch();
29+
let mut previous_epoch_cache = EpochTotalBalances::new(spec);
30+
let mut current_epoch_cache = EpochTotalBalances::new(spec);
31+
for ((validator, current_epoch_flags), previous_epoch_flags) in state
32+
.validators()
33+
.iter()
34+
.zip(state.current_epoch_participation()?)
35+
.zip(state.previous_epoch_participation()?)
36+
{
37+
// Exclude slashed validators. We are calculating *unslashed* participating totals.
38+
if validator.slashed {
39+
continue;
3840
}
39-
};
4041

41-
let current_epoch = state.current_epoch();
42-
let previous_epoch_cache = EpochTotalBalances {
43-
total_flag_balances: participation_cache
44-
.previous_epoch_participation
45-
.total_flag_balances,
46-
};
47-
let current_epoch_cache = EpochTotalBalances {
48-
total_flag_balances: participation_cache
49-
.current_epoch_participation
50-
.total_flag_balances,
51-
};
42+
// Update current epoch flag balances.
43+
if validator.is_active_at(current_epoch) {
44+
update_flag_total_balances(&mut current_epoch_cache, *current_epoch_flags, validator)?;
45+
}
46+
// Update previous epoch flag balances.
47+
if validator.is_active_at(previous_epoch) {
48+
update_flag_total_balances(
49+
&mut previous_epoch_cache,
50+
*previous_epoch_flags,
51+
validator,
52+
)?;
53+
}
54+
}
5255

5356
state.progressive_balances_cache_mut().initialize(
5457
current_epoch,
@@ -61,6 +64,26 @@ pub fn initialize_progressive_balances_cache<E: EthSpec>(
6164
Ok(())
6265
}
6366

67+
/// During the initialization of the progressive balances for a single epoch, add
68+
/// `validator.effective_balance` to the flag total, for each flag present in `participation_flags`.
69+
///
70+
/// Pre-conditions:
71+
///
72+
/// - `validator` must not be slashed
73+
/// - the `participation_flags` must be for `validator` in the same epoch as the `total_balances`
74+
fn update_flag_total_balances(
75+
total_balances: &mut EpochTotalBalances,
76+
participation_flags: ParticipationFlags,
77+
validator: &Validator,
78+
) -> Result<(), BeaconStateError> {
79+
for (flag, balance) in total_balances.total_flag_balances.iter_mut().enumerate() {
80+
if participation_flags.has_flag(flag)? {
81+
balance.safe_add_assign(validator.effective_balance)?;
82+
}
83+
}
84+
Ok(())
85+
}
86+
6487
/// Updates the `ProgressiveBalancesCache` when a new target attestation has been processed.
6588
pub fn update_progressive_balances_on_attestation<T: EthSpec>(
6689
state: &mut BeaconState<T>,

consensus/state_processing/src/per_block_processing.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ pub fn per_block_processing<T: EthSpec, Payload: AbstractExecPayload<T>>(
121121

122122
// Build epoch cache if it hasn't already been built, or if it is no longer valid
123123
initialize_epoch_cache(state, spec)?;
124-
initialize_progressive_balances_cache(state, None, spec)?;
124+
initialize_progressive_balances_cache(state, spec)?;
125125
state.build_slashings_cache()?;
126126

127127
let verify_signatures = match block_signature_strategy {

consensus/state_processing/src/per_block_processing/altair/sync_committee.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,10 @@ pub fn process_sync_aggregate<T: EthSpec>(
6868
increase_balance(state, participant_index, participant_reward)?;
6969
}
7070
proposer_balance.safe_add_assign(proposer_reward)?;
71+
} else if participant_index == proposer_index {
72+
proposer_balance = proposer_balance.saturating_sub(participant_reward);
7173
} else {
72-
if participant_index == proposer_index {
73-
proposer_balance = proposer_balance.saturating_sub(participant_reward);
74-
} else {
75-
decrease_balance(state, participant_index, participant_reward)?;
76-
}
74+
decrease_balance(state, participant_index, participant_reward)?;
7775
}
7876
}
7977

consensus/state_processing/src/per_block_processing/errors.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
use super::signature_sets::Error as SignatureSetError;
2-
use crate::per_epoch_processing::altair::participation_cache;
32
use crate::{ContextError, EpochCacheError};
43
use merkle_proof::MerkleTreeError;
5-
use participation_cache::Error as ParticipationCacheError;
64
use safe_arith::ArithError;
75
use ssz::DecodeError;
86
use types::*;
@@ -90,7 +88,6 @@ pub enum BlockProcessingError {
9088
found: Hash256,
9189
},
9290
WithdrawalCredentialsInvalid,
93-
ParticipationCacheError(ParticipationCacheError),
9491
}
9592

9693
impl From<BeaconStateError> for BlockProcessingError {
@@ -154,12 +151,6 @@ impl From<BlockOperationError<HeaderInvalid>> for BlockProcessingError {
154151
}
155152
}
156153

157-
impl From<ParticipationCacheError> for BlockProcessingError {
158-
fn from(e: ParticipationCacheError) -> Self {
159-
BlockProcessingError::ParticipationCacheError(e)
160-
}
161-
}
162-
163154
/// A conversion that consumes `self` and adds an `index` variable to resulting struct.
164155
///
165156
/// Used here to allow converting an error into an upstream error that points to the object that

consensus/state_processing/src/per_epoch_processing/altair.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,13 @@ use crate::per_epoch_processing::{
1111
};
1212
pub use inactivity_updates::process_inactivity_updates_slow;
1313
pub use justification_and_finalization::process_justification_and_finalization;
14-
pub use participation_cache::ParticipationCache;
1514
pub use participation_flag_updates::process_participation_flag_updates;
1615
pub use rewards_and_penalties::process_rewards_and_penalties_slow;
1716
pub use sync_committee_updates::process_sync_committee_updates;
1817
use types::{BeaconState, ChainSpec, EthSpec, RelativeEpoch};
1918

2019
pub mod inactivity_updates;
2120
pub mod justification_and_finalization;
22-
pub mod participation_cache;
2321
pub mod participation_flag_updates;
2422
pub mod rewards_and_penalties;
2523
pub mod sync_committee_updates;
@@ -34,7 +32,7 @@ pub fn process_epoch<T: EthSpec>(
3432
state.build_committee_cache(RelativeEpoch::Next, spec)?;
3533
state.build_total_active_balance_cache_at(state.current_epoch(), spec)?;
3634
initialize_epoch_cache(state, spec)?;
37-
initialize_progressive_balances_cache::<T>(state, None, spec)?;
35+
initialize_progressive_balances_cache::<T>(state, spec)?;
3836

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

0 commit comments

Comments
 (0)