Files
lighthouse/testing/ef_tests/src/cases/rewards.rs
Paul Hauner 6e3ca48cb9 Cache participating indices for Altair epoch processing (#2416)
## Issue Addressed

NA

## Proposed Changes

This PR addresses two things:

1. Allows the `ValidatorMonitor` to work with Altair states.
1. Optimizes `altair::process_epoch` (see [code](https://github.com/paulhauner/lighthouse/blob/participation-cache/consensus/state_processing/src/per_epoch_processing/altair/participation_cache.rs) for description)

## Breaking Changes

The breaking changes in this PR revolve around one premise:

*After the Altair fork, it's not longer possible (given only a `BeaconState`) to identify if a validator had *any* attestation included during some epoch. The best we can do is see if that validator made the "timely" source/target/head flags.*

Whilst this seems annoying, it's not actually too bad. Finalization is based upon "timely target" attestations, so that's really the most important thing. Although there's *some* value in knowing if a validator had *any* attestation included, it's far more important to know about "timely target" participation, since this is what affects finality and justification.

For simplicity and consistency, I've also removed the ability to determine if *any* attestation was included from metrics and API endpoints. Now, all Altair and non-Altair states will simply report on the head/target attestations.

The following section details where we've removed fields and provides replacement values.

### Breaking Changes: Prometheus Metrics

Some participation metrics have been removed and replaced. Some were removed since they are no longer relevant to Altair (e.g., total attesting balance) and others replaced with gwei values instead of pre-computed values. This provides more flexibility at display-time (e.g., Grafana).

The following metrics were added as replacements:

- `beacon_participation_prev_epoch_head_attesting_gwei_total`
- `beacon_participation_prev_epoch_target_attesting_gwei_total`
- `beacon_participation_prev_epoch_source_attesting_gwei_total`
- `beacon_participation_prev_epoch_active_gwei_total`

The following metrics were removed:

- `beacon_participation_prev_epoch_attester`
   - instead use `beacon_participation_prev_epoch_source_attesting_gwei_total / beacon_participation_prev_epoch_active_gwei_total`.
- `beacon_participation_prev_epoch_target_attester`
   - instead use `beacon_participation_prev_epoch_target_attesting_gwei_total / beacon_participation_prev_epoch_active_gwei_total`.
- `beacon_participation_prev_epoch_head_attester`
   - instead use `beacon_participation_prev_epoch_head_attesting_gwei_total / beacon_participation_prev_epoch_active_gwei_total`.

The `beacon_participation_prev_epoch_attester` endpoint has been removed. Users should instead use the pre-existing `beacon_participation_prev_epoch_target_attester`. 

### Breaking Changes: HTTP API

The `/lighthouse/validator_inclusion/{epoch}/{validator_id}` endpoint loses the following fields:

- `current_epoch_attesting_gwei` (use `current_epoch_target_attesting_gwei` instead)
- `previous_epoch_attesting_gwei` (use `previous_epoch_target_attesting_gwei` instead)

The `/lighthouse/validator_inclusion/{epoch}/{validator_id}` endpoint lose the following fields:

- `is_current_epoch_attester` (use `is_current_epoch_target_attester` instead)
- `is_previous_epoch_attester` (use `is_previous_epoch_target_attester` instead)
- `is_active_in_current_epoch` becomes `is_active_unslashed_in_current_epoch`.
- `is_active_in_previous_epoch` becomes `is_active_unslashed_in_previous_epoch`.

## Additional Info

NA

## TODO

- [x] Deal with total balances
- [x] Update validator_inclusion API
- [ ] Ensure `beacon_participation_prev_epoch_target_attester` and `beacon_participation_prev_epoch_head_attester` work before Altair

Co-authored-by: realbigsean <seananderson33@gmail.com>
2021-07-27 07:01:01 +00:00

218 lines
7.1 KiB
Rust

use super::*;
use crate::case_result::compare_result_detailed;
use crate::decode::{ssz_decode_file, ssz_decode_state, yaml_decode_file};
use compare_fields_derive::CompareFields;
use serde_derive::Deserialize;
use ssz_derive::{Decode, Encode};
use state_processing::{
per_epoch_processing::{
altair::{self, rewards_and_penalties::get_flag_index_deltas, ParticipationCache},
base::{self, rewards_and_penalties::AttestationDelta, ValidatorStatuses},
Delta,
},
EpochProcessingError,
};
use std::path::{Path, PathBuf};
use types::{
consts::altair::{TIMELY_HEAD_FLAG_INDEX, TIMELY_SOURCE_FLAG_INDEX, TIMELY_TARGET_FLAG_INDEX},
BeaconState, EthSpec, ForkName,
};
#[derive(Debug, Clone, PartialEq, Decode, Encode, CompareFields)]
pub struct Deltas {
#[compare_fields(as_slice)]
rewards: Vec<u64>,
#[compare_fields(as_slice)]
penalties: Vec<u64>,
}
#[derive(Debug, Clone, PartialEq, Decode, Encode, CompareFields)]
pub struct AllDeltas {
source_deltas: Deltas,
target_deltas: Deltas,
head_deltas: Deltas,
inclusion_delay_deltas: Option<Deltas>,
inactivity_penalty_deltas: Deltas,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Metadata {
pub description: Option<String>,
}
#[derive(Debug, Clone)]
pub struct RewardsTest<E: EthSpec> {
pub path: PathBuf,
pub metadata: Metadata,
pub pre: BeaconState<E>,
pub deltas: AllDeltas,
}
/// Function that extracts a delta for a single component from an `AttestationDelta`.
type Accessor = fn(&AttestationDelta) -> &Delta;
fn load_optional_deltas_file(path: &Path) -> Result<Option<Deltas>, Error> {
let deltas = if path.is_file() {
Some(ssz_decode_file(&path)?)
} else {
None
};
Ok(deltas)
}
impl<E: EthSpec> LoadCase for RewardsTest<E> {
fn load_from_dir(path: &Path, fork_name: ForkName) -> Result<Self, Error> {
let spec = &testing_spec::<E>(fork_name);
let metadata_path = path.join("meta.yaml");
let metadata: Metadata = if metadata_path.is_file() {
yaml_decode_file(&metadata_path)?
} else {
Metadata::default()
};
let pre = ssz_decode_state(&path.join("pre.ssz_snappy"), spec)?;
let source_deltas = ssz_decode_file(&path.join("source_deltas.ssz_snappy"))?;
let target_deltas = ssz_decode_file(&path.join("target_deltas.ssz_snappy"))?;
let head_deltas = ssz_decode_file(&path.join("head_deltas.ssz_snappy"))?;
let inclusion_delay_deltas =
load_optional_deltas_file(&path.join("inclusion_delay_deltas.ssz_snappy"))?;
let inactivity_penalty_deltas =
ssz_decode_file(&path.join("inactivity_penalty_deltas.ssz_snappy"))?;
let deltas = AllDeltas {
source_deltas,
target_deltas,
head_deltas,
inclusion_delay_deltas,
inactivity_penalty_deltas,
};
Ok(Self {
path: path.into(),
metadata,
pre,
deltas,
})
}
}
impl<E: EthSpec> Case for RewardsTest<E> {
fn description(&self) -> String {
self.metadata
.description
.clone()
.unwrap_or_else(String::new)
}
fn result(&self, _case_index: usize, fork_name: ForkName) -> Result<(), Error> {
let mut state = self.pre.clone();
let spec = &testing_spec::<E>(fork_name);
let deltas: Result<AllDeltas, EpochProcessingError> = (|| {
// Processing requires the committee caches.
state.build_all_committee_caches(spec)?;
if let BeaconState::Base(_) = state {
let mut validator_statuses = ValidatorStatuses::new(&state, spec)?;
validator_statuses.process_attestations(&state)?;
let deltas = base::rewards_and_penalties::get_attestation_deltas(
&state,
&validator_statuses,
spec,
)?;
Ok(convert_all_base_deltas(&deltas))
} else {
let total_active_balance = state.get_total_active_balance(spec)?;
let source_deltas = compute_altair_flag_deltas(
&state,
TIMELY_SOURCE_FLAG_INDEX,
total_active_balance,
spec,
)?;
let target_deltas = compute_altair_flag_deltas(
&state,
TIMELY_TARGET_FLAG_INDEX,
total_active_balance,
spec,
)?;
let head_deltas = compute_altair_flag_deltas(
&state,
TIMELY_HEAD_FLAG_INDEX,
total_active_balance,
spec,
)?;
let inactivity_penalty_deltas = compute_altair_inactivity_deltas(&state, spec)?;
Ok(AllDeltas {
source_deltas,
target_deltas,
head_deltas,
inclusion_delay_deltas: None,
inactivity_penalty_deltas,
})
}
})();
compare_result_detailed(&deltas, &Some(self.deltas.clone()))?;
Ok(())
}
}
fn convert_all_base_deltas(ad: &[AttestationDelta]) -> AllDeltas {
AllDeltas {
source_deltas: convert_base_deltas(ad, |d| &d.source_delta),
target_deltas: convert_base_deltas(ad, |d| &d.target_delta),
head_deltas: convert_base_deltas(ad, |d| &d.head_delta),
inclusion_delay_deltas: Some(convert_base_deltas(ad, |d| &d.inclusion_delay_delta)),
inactivity_penalty_deltas: convert_base_deltas(ad, |d| &d.inactivity_penalty_delta),
}
}
fn convert_base_deltas(attestation_deltas: &[AttestationDelta], accessor: Accessor) -> Deltas {
let (rewards, penalties) = attestation_deltas
.iter()
.map(accessor)
.map(|delta| (delta.rewards, delta.penalties))
.unzip();
Deltas { rewards, penalties }
}
fn compute_altair_flag_deltas<E: EthSpec>(
state: &BeaconState<E>,
flag_index: usize,
total_active_balance: u64,
spec: &ChainSpec,
) -> Result<Deltas, EpochProcessingError> {
let mut deltas = vec![Delta::default(); state.validators().len()];
get_flag_index_deltas(
&mut deltas,
state,
flag_index,
total_active_balance,
&ParticipationCache::new(state, spec).unwrap(),
spec,
)?;
Ok(convert_altair_deltas(deltas))
}
fn compute_altair_inactivity_deltas<E: EthSpec>(
state: &BeaconState<E>,
spec: &ChainSpec,
) -> Result<Deltas, EpochProcessingError> {
let mut deltas = vec![Delta::default(); state.validators().len()];
altair::rewards_and_penalties::get_inactivity_penalty_deltas(
&mut deltas,
state,
&ParticipationCache::new(state, spec).unwrap(),
spec,
)?;
Ok(convert_altair_deltas(deltas))
}
fn convert_altair_deltas(deltas: Vec<Delta>) -> Deltas {
let (rewards, penalties) = deltas.into_iter().map(|d| (d.rewards, d.penalties)).unzip();
Deltas { rewards, penalties }
}