Implement ConsensusContext

This commit is contained in:
Michael Sproul
2022-02-17 16:40:15 +11:00
parent 1db0e32bfb
commit c88fcfed2b
10 changed files with 170 additions and 26 deletions

View File

@@ -1,6 +1,7 @@
use crate::{
per_block_processing, per_epoch_processing::EpochProcessingSummary, per_slot_processing,
BlockProcessingError, BlockSignatureStrategy, SlotProcessingError, VerifyBlockRoot,
BlockProcessingError, BlockSignatureStrategy, ConsensusContext, SlotProcessingError,
VerifyBlockRoot,
};
use std::marker::PhantomData;
use types::{BeaconState, ChainSpec, EthSpec, Hash256, SignedBeaconBlock, Slot};
@@ -226,12 +227,13 @@ where
VerifyBlockRoot::False
}
});
let mut ctxt = ConsensusContext::new(block.slot());
per_block_processing(
&mut self.state,
block,
None,
self.block_sig_strategy,
verify_block_root,
&mut ctxt,
self.spec,
)
.map_err(BlockReplayError::from)?;

View File

@@ -0,0 +1,89 @@
use std::marker::PhantomData;
use tree_hash::TreeHash;
use types::{BeaconState, BeaconStateError, ChainSpec, EthSpec, Hash256, SignedBeaconBlock, Slot};
#[derive(Debug)]
pub struct ConsensusContext<T: EthSpec> {
/// Slot to act as an identifier/safeguard
slot: Slot,
/// Proposer index of the block at `slot`.
proposer_index: Option<u64>,
/// Block root of the block at `slot`.
current_block_root: Option<Hash256>,
_phantom: PhantomData<T>,
}
#[derive(Debug, PartialEq, Clone)]
pub enum ContextError {
BeaconState(BeaconStateError),
SlotMismatch { slot: Slot, expected: Slot },
}
impl From<BeaconStateError> for ContextError {
fn from(e: BeaconStateError) -> Self {
Self::BeaconState(e)
}
}
impl<T: EthSpec> ConsensusContext<T> {
pub fn new(slot: Slot) -> Self {
Self {
slot,
proposer_index: None,
current_block_root: None,
_phantom: PhantomData,
}
}
pub fn set_proposer_index(mut self, proposer_index: u64) -> Self {
self.proposer_index = Some(proposer_index);
self
}
pub fn get_proposer_index(
&mut self,
state: &BeaconState<T>,
spec: &ChainSpec,
) -> Result<u64, ContextError> {
self.check_slot(state.slot())?;
if let Some(proposer_index) = self.proposer_index {
return Ok(proposer_index);
}
let proposer_index = state.get_beacon_proposer_index(self.slot, spec)? as u64;
self.proposer_index = Some(proposer_index);
Ok(proposer_index)
}
pub fn set_current_block_root(mut self, block_root: Hash256) -> Self {
self.current_block_root = Some(block_root);
self
}
pub fn get_current_block_root(
&mut self,
block: &SignedBeaconBlock<T>,
) -> Result<Hash256, ContextError> {
self.check_slot(block.slot())?;
if let Some(current_block_root) = self.current_block_root {
return Ok(current_block_root);
}
let current_block_root = block.tree_hash_root();
self.current_block_root = Some(current_block_root);
Ok(current_block_root)
}
fn check_slot(&self, slot: Slot) -> Result<(), ContextError> {
if slot == self.slot {
Ok(())
} else {
Err(ContextError::SlotMismatch {
slot,
expected: self.slot,
})
}
}
}

View File

@@ -18,6 +18,7 @@ mod metrics;
pub mod block_replayer;
pub mod common;
pub mod consensus_context;
pub mod genesis;
pub mod per_block_processing;
pub mod per_epoch_processing;
@@ -27,6 +28,7 @@ pub mod upgrade;
pub mod verify_operation;
pub use block_replayer::{BlockReplayError, BlockReplayer};
pub use consensus_context::{ConsensusContext, ContextError};
pub use genesis::{
eth2_genesis_time, initialize_beacon_state_from_eth1, is_valid_genesis_state,
process_activations,

View File

@@ -1,3 +1,4 @@
use crate::consensus_context::ConsensusContext;
use errors::{BlockOperationError, BlockProcessingError, HeaderInvalid};
use rayon::prelude::*;
use safe_arith::{ArithError, SafeArith};
@@ -90,9 +91,9 @@ pub enum VerifyBlockRoot {
pub fn per_block_processing<T: EthSpec>(
state: &mut BeaconState<T>,
signed_block: &SignedBeaconBlock<T>,
block_root: Option<Hash256>,
block_signature_strategy: BlockSignatureStrategy,
verify_block_root: VerifyBlockRoot,
ctxt: &mut ConsensusContext<T>,
spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
let block = signed_block.message();
@@ -110,6 +111,7 @@ pub fn per_block_processing<T: EthSpec>(
let verify_signatures = match block_signature_strategy {
BlockSignatureStrategy::VerifyBulk => {
// Verify all signatures in the block at once.
let block_root = Some(ctxt.get_current_block_root(signed_block)?);
block_verify!(
BlockSignatureVerifier::verify_entire_block(
state,
@@ -129,10 +131,10 @@ pub fn per_block_processing<T: EthSpec>(
BlockSignatureStrategy::VerifyRandao => VerifySignatures::False,
};
let proposer_index = process_block_header(state, block, verify_block_root, spec)?;
let proposer_index = process_block_header(state, block, verify_block_root, ctxt, spec)?;
if verify_signatures.is_true() {
verify_block_signature(state, signed_block, block_root, spec)?;
verify_block_signature(state, signed_block, ctxt, spec)?;
}
let verify_randao = if let BlockSignatureStrategy::VerifyRandao = block_signature_strategy {
@@ -174,6 +176,7 @@ pub fn process_block_header<T: EthSpec>(
state: &mut BeaconState<T>,
block: BeaconBlockRef<'_, T>,
verify_block_root: VerifyBlockRoot,
ctxt: &mut ConsensusContext<T>,
spec: &ChainSpec,
) -> Result<u64, BlockOperationError<HeaderInvalid>> {
// Verify that the slots match
@@ -192,8 +195,8 @@ pub fn process_block_header<T: EthSpec>(
);
// Verify that proposer index is the correct index
let proposer_index = block.proposer_index() as usize;
let state_proposer_index = state.get_beacon_proposer_index(block.slot(), spec)?;
let proposer_index = block.proposer_index();
let state_proposer_index = ctxt.get_proposer_index(state, spec)?;
verify!(
proposer_index == state_proposer_index,
HeaderInvalid::ProposerIndexMismatch {
@@ -217,11 +220,11 @@ pub fn process_block_header<T: EthSpec>(
// Verify proposer is not slashed
verify!(
!state.get_validator(proposer_index)?.slashed,
!state.get_validator(proposer_index as usize)?.slashed,
HeaderInvalid::ProposerSlashed(proposer_index)
);
Ok(block.proposer_index())
Ok(proposer_index)
}
/// Verifies the signature of a block.
@@ -230,9 +233,10 @@ pub fn process_block_header<T: EthSpec>(
pub fn verify_block_signature<T: EthSpec>(
state: &BeaconState<T>,
block: &SignedBeaconBlock<T>,
block_root: Option<Hash256>,
ctxt: &mut ConsensusContext<T>,
spec: &ChainSpec,
) -> Result<(), BlockOperationError<HeaderInvalid>> {
let block_root = Some(ctxt.get_current_block_root(block)?);
verify!(
block_proposal_signature_set(
state,

View File

@@ -1,4 +1,5 @@
use super::signature_sets::Error as SignatureSetError;
use crate::ContextError;
use merkle_proof::MerkleTreeError;
use safe_arith::ArithError;
use types::*;
@@ -70,6 +71,7 @@ pub enum BlockProcessingError {
found: u64,
},
ExecutionInvalid,
ConsensusContext(ContextError),
#[cfg(feature = "milhouse")]
MilhouseError(milhouse::Error),
}
@@ -104,6 +106,12 @@ impl From<SyncAggregateInvalid> for BlockProcessingError {
}
}
impl From<ContextError> for BlockProcessingError {
fn from(e: ContextError) -> Self {
BlockProcessingError::ConsensusContext(e)
}
}
#[cfg(feature = "milhouse")]
impl From<milhouse::Error> for BlockProcessingError {
fn from(e: milhouse::Error) -> Self {
@@ -118,6 +126,7 @@ impl From<BlockOperationError<HeaderInvalid>> for BlockProcessingError {
BlockOperationError::BeaconStateError(e) => BlockProcessingError::BeaconStateError(e),
BlockOperationError::SignatureSetError(e) => BlockProcessingError::SignatureSetError(e),
BlockOperationError::SszTypesError(e) => BlockProcessingError::SszTypesError(e),
BlockOperationError::ConsensusContext(e) => BlockProcessingError::ConsensusContext(e),
BlockOperationError::ArithError(e) => BlockProcessingError::ArithError(e),
}
}
@@ -145,6 +154,7 @@ macro_rules! impl_into_block_processing_error_with_index {
BlockOperationError::BeaconStateError(e) => BlockProcessingError::BeaconStateError(e),
BlockOperationError::SignatureSetError(e) => BlockProcessingError::SignatureSetError(e),
BlockOperationError::SszTypesError(e) => BlockProcessingError::SszTypesError(e),
BlockOperationError::ConsensusContext(e) => BlockProcessingError::ConsensusContext(e),
BlockOperationError::ArithError(e) => BlockProcessingError::ArithError(e),
}
}
@@ -176,6 +186,7 @@ pub enum BlockOperationError<T> {
BeaconStateError(BeaconStateError),
SignatureSetError(SignatureSetError),
SszTypesError(ssz_types::Error),
ConsensusContext(ContextError),
ArithError(ArithError),
}
@@ -208,6 +219,12 @@ impl<T> From<ArithError> for BlockOperationError<T> {
}
}
impl<T> From<ContextError> for BlockOperationError<T> {
fn from(e: ContextError) -> Self {
BlockOperationError::ConsensusContext(e)
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum HeaderInvalid {
ProposalSignatureInvalid,
@@ -217,14 +234,14 @@ pub enum HeaderInvalid {
block_slot: Slot,
},
ProposerIndexMismatch {
block_proposer_index: usize,
state_proposer_index: usize,
block_proposer_index: u64,
state_proposer_index: u64,
},
ParentBlockRootMismatch {
state: Hash256,
block: Hash256,
},
ProposerSlashed(usize),
ProposerSlashed(u64),
}
#[derive(Debug, PartialEq, Clone)]
@@ -319,6 +336,7 @@ impl From<BlockOperationError<IndexedAttestationInvalid>>
BlockOperationError::BeaconStateError(e) => BlockOperationError::BeaconStateError(e),
BlockOperationError::SignatureSetError(e) => BlockOperationError::SignatureSetError(e),
BlockOperationError::SszTypesError(e) => BlockOperationError::SszTypesError(e),
BlockOperationError::ConsensusContext(e) => BlockOperationError::ConsensusContext(e),
BlockOperationError::ArithError(e) => BlockOperationError::ArithError(e),
}
}