formatting

This commit is contained in:
Grant Wuerker 2019-08-06 19:17:15 +02:00
parent c431bd993e
commit ce73705498
No known key found for this signature in database
GPG Key ID: F7EA56FDDA6C464F
7 changed files with 85 additions and 56 deletions

View File

@ -3,6 +3,7 @@ use crate::errors::{BeaconChainError as Error, BlockProductionError};
use crate::fork_choice::{Error as ForkChoiceError, ForkChoice}; use crate::fork_choice::{Error as ForkChoiceError, ForkChoice};
use crate::metrics::Metrics; use crate::metrics::Metrics;
use crate::persisted_beacon_chain::{PersistedBeaconChain, BEACON_CHAIN_DB_KEY}; use crate::persisted_beacon_chain::{PersistedBeaconChain, BEACON_CHAIN_DB_KEY};
use crate::BeaconChainError;
use lmd_ghost::LmdGhost; use lmd_ghost::LmdGhost;
use log::trace; use log::trace;
use operation_pool::DepositInsertStatus; use operation_pool::DepositInsertStatus;
@ -11,19 +12,18 @@ use parking_lot::{RwLock, RwLockReadGuard};
use slog::{error, info, warn, Logger}; use slog::{error, info, warn, Logger};
use slot_clock::SlotClock; use slot_clock::SlotClock;
use state_processing::per_block_processing::errors::{ use state_processing::per_block_processing::errors::{
AttesterSlashingValidationError, DepositValidationError, AttesterSlashingValidationError, DepositValidationError, ExitValidationError,
ExitValidationError, ProposerSlashingValidationError, TransferValidationError, ProposerSlashingValidationError, TransferValidationError,
}; };
use state_processing::{ use state_processing::{
per_block_processing, per_block_processing_without_verifying_block_signature, common, per_block_processing, per_block_processing_without_verifying_block_signature,
per_slot_processing, BlockProcessingError, common per_slot_processing, BlockProcessingError,
}; };
use std::sync::Arc; use std::sync::Arc;
use store::iter::{BestBlockRootsIterator, BlockIterator, BlockRootsIterator, StateRootsIterator}; use store::iter::{BestBlockRootsIterator, BlockIterator, BlockRootsIterator, StateRootsIterator};
use store::{Error as DBError, Store}; use store::{Error as DBError, Store};
use tree_hash::TreeHash; use tree_hash::TreeHash;
use types::*; use types::*;
use crate::BeaconChainError;
// Text included in blocks. // Text included in blocks.
// Must be 32-bytes or panic. // Must be 32-bytes or panic.
@ -511,17 +511,21 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
/// ///
/// If valid, the attestation is added to the `op_pool` and aggregated with another attestation /// If valid, the attestation is added to the `op_pool` and aggregated with another attestation
/// if possible. /// if possible.
pub fn process_attestation( pub fn process_attestation(&self, attestation: Attestation<T::EthSpec>) -> Result<(), Error> {
&self,
attestation: Attestation<T::EthSpec>,
) -> Result<(), Error> {
self.metrics.attestation_processing_requests.inc(); self.metrics.attestation_processing_requests.inc();
let timer = self.metrics.attestation_processing_times.start_timer(); let timer = self.metrics.attestation_processing_times.start_timer();
if let Some(state) = self.get_attestation_state(&attestation) { if let Some(state) = self.get_attestation_state(&attestation) {
if self.fork_choice.should_process_attestation(&state, &attestation)? { if self
.fork_choice
.should_process_attestation(&state, &attestation)?
{
let indexed_attestation = common::get_indexed_attestation(&state, &attestation)?; let indexed_attestation = common::get_indexed_attestation(&state, &attestation)?;
per_block_processing::is_valid_indexed_attestation(&state, &indexed_attestation, &self.spec)?; per_block_processing::is_valid_indexed_attestation(
&state,
&indexed_attestation,
&self.spec,
)?;
self.fork_choice.process_attestation(&state, &attestation)?; self.fork_choice.process_attestation(&state, &attestation)?;
} }
} }
@ -540,12 +544,20 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
} }
/// Retrieves the `BeaconState` used to create the attestation. /// Retrieves the `BeaconState` used to create the attestation.
fn get_attestation_state(&self, attestation: &Attestation<T::EthSpec>) -> Option<BeaconState<T::EthSpec>> { fn get_attestation_state(
&self,
attestation: &Attestation<T::EthSpec>,
) -> Option<BeaconState<T::EthSpec>> {
// Current state is used if the attestation targets a historic block and a slot within an // Current state is used if the attestation targets a historic block and a slot within an
// equal or adjacent epoch. // equal or adjacent epoch.
let slots_per_epoch = T::EthSpec::slots_per_epoch(); let slots_per_epoch = T::EthSpec::slots_per_epoch();
let min_slot = (self.state.read().slot.epoch(slots_per_epoch) - 1).start_slot(slots_per_epoch); let min_slot =
let blocks = BestBlockRootsIterator::owned(self.store.clone(), self.state.read().clone(), self.state.read().slot.clone()); (self.state.read().slot.epoch(slots_per_epoch) - 1).start_slot(slots_per_epoch);
let blocks = BestBlockRootsIterator::owned(
self.store.clone(),
self.state.read().clone(),
self.state.read().slot.clone(),
);
for (root, slot) in blocks { for (root, slot) in blocks {
if root == attestation.data.target.root { if root == attestation.data.target.root {
return Some(self.state.read().clone()); return Some(self.state.read().clone());
@ -554,15 +566,18 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
if slot == min_slot { if slot == min_slot {
break; break;
} }
}; }
// A different state is retrieved from the database. // A different state is retrieved from the database.
match self.store.get::<BeaconBlock<T::EthSpec>>(&attestation.data.target.root) { match self
.store
.get::<BeaconBlock<T::EthSpec>>(&attestation.data.target.root)
{
Ok(Some(block)) => match self.store.get::<BeaconState<T::EthSpec>>(&block.state_root) { Ok(Some(block)) => match self.store.get::<BeaconState<T::EthSpec>>(&block.state_root) {
Ok(state) => state, Ok(state) => state,
_ => None _ => None,
}, },
_ => None _ => None,
} }
} }
@ -1031,4 +1046,3 @@ impl From<BeaconStateError> for Error {
Error::BeaconStateError(e) Error::BeaconStateError(e)
} }
} }

View File

@ -1,9 +1,11 @@
use crate::fork_choice::Error as ForkChoiceError; use crate::fork_choice::Error as ForkChoiceError;
use crate::metrics::Error as MetricsError; use crate::metrics::Error as MetricsError;
use state_processing::per_block_processing::errors::{
AttestationValidationError, IndexedAttestationValidationError,
};
use state_processing::BlockProcessingError; use state_processing::BlockProcessingError;
use state_processing::SlotProcessingError; use state_processing::SlotProcessingError;
use types::*; use types::*;
use state_processing::per_block_processing::errors::{AttestationValidationError, IndexedAttestationValidationError};
macro_rules! easy_from_to { macro_rules! easy_from_to {
($from: ident, $to: ident) => { ($from: ident, $to: ident) => {
@ -33,7 +35,7 @@ pub enum BeaconChainError {
SlotProcessingError(SlotProcessingError), SlotProcessingError(SlotProcessingError),
MetricsError(String), MetricsError(String),
AttestationValidationError(AttestationValidationError), AttestationValidationError(AttestationValidationError),
IndexedAttestationValidationError(IndexedAttestationValidationError) IndexedAttestationValidationError(IndexedAttestationValidationError),
} }
easy_from_to!(SlotProcessingError, BeaconChainError); easy_from_to!(SlotProcessingError, BeaconChainError);

View File

@ -3,7 +3,9 @@ use lmd_ghost::LmdGhost;
use state_processing::common::get_attesting_indices; use state_processing::common::get_attesting_indices;
use std::sync::Arc; use std::sync::Arc;
use store::{Error as StoreError, Store}; use store::{Error as StoreError, Store};
use types::{Attestation, BeaconBlock, BeaconState, BeaconStateError, Epoch, EthSpec, Hash256, Slot}; use types::{
Attestation, BeaconBlock, BeaconState, BeaconStateError, Epoch, EthSpec, Hash256, Slot,
};
type Result<T> = std::result::Result<T, Error>; type Result<T> = std::result::Result<T, Error>;
@ -171,7 +173,11 @@ impl<T: BeaconChainTypes> ForkChoice<T> {
} }
/// Determines whether or not the given attestation contains a latest message. /// Determines whether or not the given attestation contains a latest message.
pub fn should_process_attestation(&self, state: &BeaconState<T::EthSpec>, attestation: &Attestation<T::EthSpec>) -> Result<bool> { pub fn should_process_attestation(
&self,
state: &BeaconState<T::EthSpec>,
attestation: &Attestation<T::EthSpec>,
) -> Result<bool> {
let validator_indices = let validator_indices =
get_attesting_indices(state, &attestation.data, &attestation.aggregation_bits)?; get_attesting_indices(state, &attestation.data, &attestation.aggregation_bits)?;
@ -179,12 +185,11 @@ impl<T: BeaconChainTypes> ForkChoice<T> {
Ok(validator_indices Ok(validator_indices
.iter() .iter()
.find(|&&v| { .find(|&&v| match self.backend.latest_message(v) {
match self.backend.latest_message(v) { Some((_, slot)) => block_slot > slot,
Some((_, slot)) => block_slot > slot, None => true,
None => true })
} .is_some())
}).is_some())
} }
// Returns the latest message for a given validator // Returns the latest message for a given validator
@ -224,4 +229,3 @@ impl From<String> for Error {
Error::BackendError(e) Error::BackendError(e)
} }
} }

View File

@ -178,12 +178,7 @@ where
if let BlockProcessingOutcome::Processed { block_root } = outcome { if let BlockProcessingOutcome::Processed { block_root } = outcome {
head_block_root = Some(block_root); head_block_root = Some(block_root);
self.add_free_attestations( self.add_free_attestations(&attestation_strategy, &new_state, block_root, slot);
&attestation_strategy,
&new_state,
block_root,
slot,
);
} else { } else {
panic!("block should be successfully processed: {:?}", outcome); panic!("block should be successfully processed: {:?}", outcome);
} }

View File

@ -8,7 +8,7 @@ use lmd_ghost::ThreadSafeReducedTree;
use rand::Rng; use rand::Rng;
use store::{MemoryStore, Store}; use store::{MemoryStore, Store};
use types::test_utils::{SeedableRng, TestRandom, XorShiftRng}; use types::test_utils::{SeedableRng, TestRandom, XorShiftRng};
use types::{Deposit, EthSpec, Hash256, MinimalEthSpec, Slot, RelativeEpoch}; use types::{Deposit, EthSpec, Hash256, MinimalEthSpec, RelativeEpoch, Slot};
// Should ideally be divisible by 3. // Should ideally be divisible by 3.
pub const VALIDATOR_COUNT: usize = 24; pub const VALIDATOR_COUNT: usize = 24;
@ -270,20 +270,23 @@ fn free_attestations_added_to_fork_choice_some_none() {
let validators: Vec<usize> = (0..VALIDATOR_COUNT).collect(); let validators: Vec<usize> = (0..VALIDATOR_COUNT).collect();
let slots: Vec<Slot> = validators let slots: Vec<Slot> = validators
.iter() .iter()
.map(|&v| .map(|&v| {
state.get_attestation_duties(v, RelativeEpoch::Current) state
.get_attestation_duties(v, RelativeEpoch::Current)
.expect("should get attester duties") .expect("should get attester duties")
.unwrap() .unwrap()
.slot .slot
).collect(); })
.collect();
let validator_slots: Vec<(&usize, Slot)> = validators.iter().zip(slots).collect(); let validator_slots: Vec<(&usize, Slot)> = validators.iter().zip(slots).collect();
for (validator, slot) in validator_slots.clone() { for (validator, slot) in validator_slots.clone() {
let latest_message = fork_choice.latest_message(*validator); let latest_message = fork_choice.latest_message(*validator);
if slot <= num_blocks_produced && slot != 0{ if slot <= num_blocks_produced && slot != 0 {
assert_eq!( assert_eq!(
latest_message.unwrap().1, slot, latest_message.unwrap().1,
slot,
"Latest message slot should be equal to attester duty." "Latest message slot should be equal to attester duty."
) )
} else { } else {
@ -313,30 +316,35 @@ fn free_attestations_added_to_fork_choice_all_updated() {
let validators: Vec<usize> = (0..VALIDATOR_COUNT).collect(); let validators: Vec<usize> = (0..VALIDATOR_COUNT).collect();
let slots: Vec<Slot> = validators let slots: Vec<Slot> = validators
.iter() .iter()
.map(|&v| .map(|&v| {
state.get_attestation_duties(v, RelativeEpoch::Current) state
.get_attestation_duties(v, RelativeEpoch::Current)
.expect("should get attester duties") .expect("should get attester duties")
.unwrap() .unwrap()
.slot .slot
).collect(); })
.collect();
let validator_slots: Vec<(&usize, Slot)> = validators.iter().zip(slots).collect(); let validator_slots: Vec<(&usize, Slot)> = validators.iter().zip(slots).collect();
for (validator, slot) in validator_slots { for (validator, slot) in validator_slots {
let latest_message = fork_choice.latest_message(*validator); let latest_message = fork_choice.latest_message(*validator);
assert_eq!( assert_eq!(
latest_message.unwrap().1, slot, latest_message.unwrap().1,
slot,
"Latest message slot should be equal to attester duty." "Latest message slot should be equal to attester duty."
); );
if slot != num_blocks_produced { if slot != num_blocks_produced {
let block_root = state.get_block_root(slot) let block_root = state
.get_block_root(slot)
.expect("Should get block root at slot"); .expect("Should get block root at slot");
assert_eq!( assert_eq!(
latest_message.unwrap().0, *block_root, latest_message.unwrap().0,
*block_root,
"Latest message block root should be equal to block at slot." "Latest message block root should be equal to block at slot."
); );
} }
} }
} }

View File

@ -1,4 +1,4 @@
use beacon_chain::{BeaconChain, BeaconChainTypes, BeaconChainError}; use beacon_chain::{BeaconChain, BeaconChainError, BeaconChainTypes};
use eth2_libp2p::PubsubMessage; use eth2_libp2p::PubsubMessage;
use eth2_libp2p::TopicBuilder; use eth2_libp2p::TopicBuilder;
use eth2_libp2p::BEACON_ATTESTATION_TOPIC; use eth2_libp2p::BEACON_ATTESTATION_TOPIC;
@ -179,7 +179,11 @@ impl<T: BeaconChainTypes> AttestationService for AttestationServiceInstance<T> {
"error" => format!("{:?}", e), "error" => format!("{:?}", e),
); );
resp.set_success(false); resp.set_success(false);
resp.set_msg(format!("InvalidIndexedAttestation: {:?}", e).as_bytes().to_vec()); resp.set_msg(
format!("InvalidIndexedAttestation: {:?}", e)
.as_bytes()
.to_vec(),
);
} }
Err(e) => { Err(e) => {
// Some other error // Some other error
@ -190,7 +194,11 @@ impl<T: BeaconChainTypes> AttestationService for AttestationServiceInstance<T> {
"error" => format!("{:?}", e), "error" => format!("{:?}", e),
); );
resp.set_success(false); resp.set_success(false);
resp.set_msg(format!("There was a beacon chain error: {:?}", e).as_bytes().to_vec()); resp.set_msg(
format!("There was a beacon chain error: {:?}", e)
.as_bytes()
.to_vec(),
);
} }
}; };

View File

@ -111,9 +111,7 @@ where
} }
fn latest_message(&self, validator_index: usize) -> Option<(Hash256, Slot)> { fn latest_message(&self, validator_index: usize) -> Option<(Hash256, Slot)> {
self.core self.core.write().latest_message(validator_index)
.write()
.latest_message(validator_index)
} }
} }
@ -263,7 +261,7 @@ where
pub fn latest_message(&mut self, validator_index: usize) -> Option<(Hash256, Slot)> { pub fn latest_message(&mut self, validator_index: usize) -> Option<(Hash256, Slot)> {
match self.latest_votes.get(validator_index) { match self.latest_votes.get(validator_index) {
Some(v) => Some((v.hash.clone(), v.slot.clone())), Some(v) => Some((v.hash.clone(), v.slot.clone())),
None => None None => None,
} }
} }