mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-15 02:42:38 +00:00
Refactor winning root logic
This commit is contained in:
@@ -17,7 +17,7 @@ impl Attesters {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GroupedAttesters {
|
||||
pub struct AttesterSets {
|
||||
pub current_epoch: Attesters,
|
||||
pub current_epoch_boundary: Attesters,
|
||||
pub previous_epoch: Attesters,
|
||||
@@ -25,7 +25,7 @@ pub struct GroupedAttesters {
|
||||
pub previous_epoch_head: Attesters,
|
||||
}
|
||||
|
||||
impl GroupedAttesters {
|
||||
impl AttesterSets {
|
||||
pub fn new(state: &BeaconState, spec: &ChainSpec) -> Result<Self, BeaconStateError> {
|
||||
let mut current_epoch = Attesters::default();
|
||||
let mut current_epoch_boundary = Attesters::default();
|
||||
@@ -1,11 +1,5 @@
|
||||
use types::*;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum WinningRootError {
|
||||
NoWinningRoot,
|
||||
BeaconStateError(BeaconStateError),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum EpochProcessingError {
|
||||
UnableToDetermineProducer,
|
||||
@@ -14,7 +8,6 @@ pub enum EpochProcessingError {
|
||||
NoRandaoSeed,
|
||||
BeaconStateError(BeaconStateError),
|
||||
InclusionError(InclusionError),
|
||||
WinningRootError(WinningRootError),
|
||||
}
|
||||
|
||||
impl From<InclusionError> for EpochProcessingError {
|
||||
@@ -29,8 +22,15 @@ impl From<BeaconStateError> for EpochProcessingError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BeaconStateError> for WinningRootError {
|
||||
fn from(e: BeaconStateError) -> WinningRootError {
|
||||
WinningRootError::BeaconStateError(e)
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum InclusionError {
|
||||
/// The validator did not participate in an attestation in this period.
|
||||
NoAttestationsForValidator,
|
||||
BeaconStateError(BeaconStateError),
|
||||
}
|
||||
|
||||
impl From<BeaconStateError> for InclusionError {
|
||||
fn from(e: BeaconStateError) -> InclusionError {
|
||||
InclusionError::BeaconStateError(e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
use super::errors::InclusionError;
|
||||
use types::*;
|
||||
|
||||
/// Returns the distance between the first included attestation for some validator and this
|
||||
/// slot.
|
||||
///
|
||||
/// Note: In the spec this is defined "inline", not as a helper function.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn inclusion_distance(
|
||||
state: &BeaconState,
|
||||
attestations: &[&PendingAttestation],
|
||||
validator_index: usize,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<u64, InclusionError> {
|
||||
let attestation = earliest_included_attestation(state, attestations, validator_index, spec)?;
|
||||
Ok((attestation.inclusion_slot - attestation.data.slot).as_u64())
|
||||
}
|
||||
|
||||
/// Returns the slot of the earliest included attestation for some validator.
|
||||
///
|
||||
/// Note: In the spec this is defined "inline", not as a helper function.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn inclusion_slot(
|
||||
state: &BeaconState,
|
||||
attestations: &[&PendingAttestation],
|
||||
validator_index: usize,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<Slot, InclusionError> {
|
||||
let attestation = earliest_included_attestation(state, attestations, validator_index, spec)?;
|
||||
Ok(attestation.inclusion_slot)
|
||||
}
|
||||
|
||||
/// Finds the earliest included attestation for some validator.
|
||||
///
|
||||
/// Note: In the spec this is defined "inline", not as a helper function.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
fn earliest_included_attestation(
|
||||
state: &BeaconState,
|
||||
attestations: &[&PendingAttestation],
|
||||
validator_index: usize,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<PendingAttestation, InclusionError> {
|
||||
let mut included_attestations = vec![];
|
||||
|
||||
for (i, a) in attestations.iter().enumerate() {
|
||||
let participants =
|
||||
state.get_attestation_participants(&a.data, &a.aggregation_bitfield, spec)?;
|
||||
if participants.iter().any(|i| *i == validator_index) {
|
||||
included_attestations.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
let earliest_attestation_index = included_attestations
|
||||
.iter()
|
||||
.min_by_key(|i| attestations[**i].inclusion_slot)
|
||||
.ok_or_else(|| InclusionError::NoAttestationsForValidator)?;
|
||||
Ok(attestations[*earliest_attestation_index].clone())
|
||||
}
|
||||
@@ -1,86 +1,118 @@
|
||||
use super::errors::WinningRootError;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::iter::FromIterator;
|
||||
use types::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WinningRoot {
|
||||
pub crosslink_data_root: Hash256,
|
||||
pub attesting_validator_indices: Vec<usize>,
|
||||
pub total_balance: u64,
|
||||
pub total_attesting_balance: u64,
|
||||
}
|
||||
|
||||
impl WinningRoot {
|
||||
/// Returns `true` if `self` is a "better" candidate than `other`.
|
||||
///
|
||||
/// A winning root is "better" than another if it has a higher `total_attesting_balance`. Ties
|
||||
/// are broken by favouring the lower `crosslink_data_root` value.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn is_better_than(&self, other: &Self) -> bool {
|
||||
if self.total_attesting_balance > other.total_attesting_balance {
|
||||
true
|
||||
} else if self.total_attesting_balance == other.total_attesting_balance {
|
||||
self.crosslink_data_root < other.crosslink_data_root
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the `crosslink_data_root` with the highest total attesting balance for the given shard.
|
||||
/// Breaks ties by favouring the smaller `crosslink_data_root` hash.
|
||||
///
|
||||
/// The `WinningRoot` object also contains additional fields that are useful in later stages of
|
||||
/// per-epoch processing.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
pub fn winning_root(
|
||||
state: &BeaconState,
|
||||
shard: u64,
|
||||
current_epoch_attestations: &[&PendingAttestation],
|
||||
previous_epoch_attestations: &[&PendingAttestation],
|
||||
spec: &ChainSpec,
|
||||
) -> Result<WinningRoot, WinningRootError> {
|
||||
let mut attestations = current_epoch_attestations.to_vec();
|
||||
attestations.append(&mut previous_epoch_attestations.to_vec());
|
||||
) -> Result<Option<WinningRoot>, BeaconStateError> {
|
||||
let mut winning_root: Option<WinningRoot> = None;
|
||||
|
||||
let mut candidates: HashMap<Hash256, WinningRoot> = HashMap::new();
|
||||
|
||||
let mut highest_seen_balance = 0;
|
||||
|
||||
for a in &attestations {
|
||||
if a.data.shard != shard {
|
||||
continue;
|
||||
}
|
||||
|
||||
let crosslink_data_root = &a.data.crosslink_data_root;
|
||||
|
||||
if candidates.contains_key(crosslink_data_root) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let attesting_validator_indices = attestations
|
||||
let crosslink_data_roots: HashSet<Hash256> = HashSet::from_iter(
|
||||
previous_epoch_attestations
|
||||
.iter()
|
||||
.try_fold::<_, _, Result<_, BeaconStateError>>(vec![], |mut acc, a| {
|
||||
if (a.data.shard == shard) && (a.data.crosslink_data_root == *crosslink_data_root) {
|
||||
acc.append(&mut state.get_attestation_participants(
|
||||
&a.data,
|
||||
&a.aggregation_bitfield,
|
||||
spec,
|
||||
)?);
|
||||
.chain(current_epoch_attestations.iter())
|
||||
.filter_map(|a| {
|
||||
if a.data.shard == shard {
|
||||
Some(a.data.crosslink_data_root)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
Ok(acc)
|
||||
})?;
|
||||
}),
|
||||
);
|
||||
|
||||
let total_balance: u64 = attesting_validator_indices
|
||||
.iter()
|
||||
.fold(0, |acc, i| acc + state.get_effective_balance(*i, spec));
|
||||
for crosslink_data_root in crosslink_data_roots {
|
||||
let attesting_validator_indices = get_attesting_validator_indices(
|
||||
state,
|
||||
shard,
|
||||
current_epoch_attestations,
|
||||
previous_epoch_attestations,
|
||||
&crosslink_data_root,
|
||||
spec,
|
||||
)?;
|
||||
|
||||
let total_attesting_balance: u64 = attesting_validator_indices
|
||||
.iter()
|
||||
.fold(0, |acc, i| acc + state.get_effective_balance(*i, spec));
|
||||
|
||||
if total_attesting_balance > highest_seen_balance {
|
||||
highest_seen_balance = total_attesting_balance;
|
||||
}
|
||||
|
||||
let candidate_root = WinningRoot {
|
||||
crosslink_data_root: *crosslink_data_root,
|
||||
let candidate = WinningRoot {
|
||||
crosslink_data_root,
|
||||
attesting_validator_indices,
|
||||
total_attesting_balance,
|
||||
total_balance,
|
||||
};
|
||||
|
||||
candidates.insert(*crosslink_data_root, candidate_root);
|
||||
if let Some(ref winner) = winning_root {
|
||||
if candidate.is_better_than(&winner) {
|
||||
winning_root = Some(candidate);
|
||||
}
|
||||
} else {
|
||||
winning_root = Some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(candidates
|
||||
.iter()
|
||||
.filter_map(|(_hash, candidate)| {
|
||||
if candidate.total_attesting_balance == highest_seen_balance {
|
||||
Some(candidate)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.min_by_key(|candidate| candidate.crosslink_data_root)
|
||||
.ok_or_else(|| WinningRootError::NoWinningRoot)?
|
||||
// TODO: avoid clone.
|
||||
.clone())
|
||||
Ok(winning_root)
|
||||
}
|
||||
|
||||
/// Returns all indices which voted for a given crosslink. May contain duplicates.
|
||||
///
|
||||
/// Spec v0.4.0
|
||||
fn get_attesting_validator_indices(
|
||||
state: &BeaconState,
|
||||
shard: u64,
|
||||
current_epoch_attestations: &[&PendingAttestation],
|
||||
previous_epoch_attestations: &[&PendingAttestation],
|
||||
crosslink_data_root: &Hash256,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<Vec<usize>, BeaconStateError> {
|
||||
let mut indices = vec![];
|
||||
|
||||
for a in current_epoch_attestations
|
||||
.iter()
|
||||
.chain(previous_epoch_attestations.iter())
|
||||
{
|
||||
if (a.data.shard == shard) && (a.data.crosslink_data_root == *crosslink_data_root) {
|
||||
indices.append(&mut state.get_attestation_participants(
|
||||
&a.data,
|
||||
&a.aggregation_bitfield,
|
||||
spec,
|
||||
)?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(indices)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user