mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-10 20:22:02 +00:00
Bulk signature verification (#507)
* Add basic block processing benches * Start reviving state processing benches * Fix old block builders * Add optimization for faster pubkey add * Tidy benches, add another * Add extra block processing bench * Start working on faster BLS scheme * Add partially complete sig verify optimization * Add .gitignore to state processing * Add progress on faster signature verification * Fix SignatureSet for fake_crypto * Tidy attester slashings sig set * Tidy bulk signature verifier * Refactor signature sets to be cleaner * Start threading SignatureStrategy through code * Add (empty) test dir * Move BenchingBlockBuilder * Add initial block signature verification tests * Add tests for bulk signature verification * Start threading SignatureStrategy in block proc. * Refactor per_block_processing errors * Use sig set tuples instead of lists of two * Remove dead code * Thread VerifySignatures through per_block_processing * Add bulk signature verification * Introduce parallel bulk signature verification * Expand state processing benches * Fix additional compile errors * Fix issue where par iter chunks is 0 * Update milagro_bls dep * Remove debugs, code fragment in beacon chain * Tidy, add comments to block sig verifier * Fix various PR comments * Add block_root option to per_block_processing * Fix comment in block signature verifier * Fix comments from PR review * Remove old comment * Fix comment
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
use super::signature_sets::{Error as SignatureSetError, Result as SignatureSetResult, *};
|
||||
use crate::common::get_indexed_attestation;
|
||||
use crate::per_block_processing::errors::{AttestationInvalid, BlockOperationError};
|
||||
use bls::{verify_signature_sets, SignatureSet};
|
||||
use rayon::prelude::*;
|
||||
use types::{
|
||||
BeaconBlock, BeaconState, BeaconStateError, ChainSpec, EthSpec, Hash256, IndexedAttestation,
|
||||
};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Error {
|
||||
/// All public keys were found but signature verification failed. The block is invalid.
|
||||
SignatureInvalid,
|
||||
/// An attestation in the block was invalid. The block is invalid.
|
||||
AttestationValidationError(BlockOperationError<AttestationInvalid>),
|
||||
/// There was an error attempting to read from a `BeaconState`. Block
|
||||
/// validity was not determined.
|
||||
BeaconStateError(BeaconStateError),
|
||||
/// Failed to load a signature set. The block may be invalid or we failed to process it.
|
||||
SignatureSetError(SignatureSetError),
|
||||
}
|
||||
|
||||
impl From<BeaconStateError> for Error {
|
||||
fn from(e: BeaconStateError) -> Error {
|
||||
Error::BeaconStateError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SignatureSetError> for Error {
|
||||
fn from(e: SignatureSetError) -> Error {
|
||||
Error::SignatureSetError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BlockOperationError<AttestationInvalid>> for Error {
|
||||
fn from(e: BlockOperationError<AttestationInvalid>) -> Error {
|
||||
Error::AttestationValidationError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the BLS signatures and keys from a `BeaconBlock`, storing them as a `Vec<SignatureSet>`.
|
||||
///
|
||||
/// This allows for optimizations related to batch BLS operations (see the
|
||||
/// `Self::verify_entire_block(..)` function).
|
||||
pub struct BlockSignatureVerifier<'a, T: EthSpec> {
|
||||
block: &'a BeaconBlock<T>,
|
||||
state: &'a BeaconState<T>,
|
||||
spec: &'a ChainSpec,
|
||||
sets: Vec<SignatureSet<'a>>,
|
||||
}
|
||||
|
||||
impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
|
||||
/// Create a new verifier without any included signatures. See the `include...` functions to
|
||||
/// add signatures, and the `verify`
|
||||
pub fn new(state: &'a BeaconState<T>, block: &'a BeaconBlock<T>, spec: &'a ChainSpec) -> Self {
|
||||
Self {
|
||||
block,
|
||||
state,
|
||||
spec,
|
||||
sets: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify all* the signatures in the given `BeaconBlock`, returning `Ok(())` if the signatures
|
||||
/// are valid.
|
||||
///
|
||||
/// * : _Does not verify any signatures in `block.body.deposits`. A block is still valid if it
|
||||
/// contains invalid signatures on deposits._
|
||||
///
|
||||
/// See `Self::verify` for more detail.
|
||||
pub fn verify_entire_block(
|
||||
state: &'a BeaconState<T>,
|
||||
block: &'a BeaconBlock<T>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<()> {
|
||||
let mut verifier = Self::new(state, block, spec);
|
||||
|
||||
verifier.include_block_proposal(None)?;
|
||||
verifier.include_randao_reveal()?;
|
||||
verifier.include_proposer_slashings()?;
|
||||
verifier.include_attester_slashings()?;
|
||||
verifier.include_attestations()?;
|
||||
/*
|
||||
* Deposits are not included because they can legally have invalid signatures.
|
||||
*/
|
||||
verifier.include_exits()?;
|
||||
verifier.include_transfers()?;
|
||||
|
||||
verifier.verify()
|
||||
}
|
||||
|
||||
/// Verify all* the signatures that have been included in `self`, returning `Ok(())` if the
|
||||
/// signatures are all valid.
|
||||
///
|
||||
/// ## Notes
|
||||
///
|
||||
/// Signature validation will take place in accordance to the [Faster verification of multiple
|
||||
/// BLS signatures](https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407)
|
||||
/// optimization proposed by Vitalik Buterin.
|
||||
///
|
||||
/// It is not possible to know exactly _which_ signature is invalid here, just that
|
||||
/// _at least one_ was invalid.
|
||||
///
|
||||
/// Uses `rayon` to do a map-reduce of Vitalik's method across multiple cores.
|
||||
pub fn verify(self) -> Result<()> {
|
||||
let num_sets = self.sets.len();
|
||||
let num_chunks = std::cmp::max(1, num_sets / rayon::current_num_threads());
|
||||
let result: bool = self
|
||||
.sets
|
||||
.into_par_iter()
|
||||
.chunks(num_chunks)
|
||||
.map(|chunk| verify_signature_sets(chunk.into_iter()))
|
||||
.reduce(|| true, |current, this| current && this);
|
||||
|
||||
if result {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::SignatureInvalid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Includes the block signature for `self.block` for verification.
|
||||
fn include_block_proposal(&mut self, block_root: Option<Hash256>) -> Result<()> {
|
||||
let set = block_proposal_signature_set(self.state, self.block, block_root, self.spec)?;
|
||||
self.sets.push(set);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes the randao signature for `self.block` for verification.
|
||||
fn include_randao_reveal(&mut self) -> Result<()> {
|
||||
let set = randao_signature_set(self.state, self.block, self.spec)?;
|
||||
self.sets.push(set);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes all signatures in `self.block.body.proposer_slashings` for verification.
|
||||
fn include_proposer_slashings(&mut self) -> Result<()> {
|
||||
let mut sets: Vec<SignatureSet> = self
|
||||
.block
|
||||
.body
|
||||
.proposer_slashings
|
||||
.iter()
|
||||
.map(|proposer_slashing| {
|
||||
let (set_1, set_2) =
|
||||
proposer_slashing_signature_set(self.state, proposer_slashing, self.spec)?;
|
||||
Ok(vec![set_1, set_2])
|
||||
})
|
||||
.collect::<SignatureSetResult<Vec<Vec<SignatureSet>>>>()?
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
|
||||
self.sets.append(&mut sets);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes all signatures in `self.block.body.attester_slashings` for verification.
|
||||
fn include_attester_slashings(&mut self) -> Result<()> {
|
||||
self.block
|
||||
.body
|
||||
.attester_slashings
|
||||
.iter()
|
||||
.try_for_each(|attester_slashing| {
|
||||
let (set_1, set_2) =
|
||||
attester_slashing_signature_sets(&self.state, attester_slashing, &self.spec)?;
|
||||
|
||||
self.sets.push(set_1);
|
||||
self.sets.push(set_2);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Includes all signatures in `self.block.body.attestations` for verification.
|
||||
fn include_attestations(&mut self) -> Result<Vec<IndexedAttestation<T>>> {
|
||||
self.block
|
||||
.body
|
||||
.attestations
|
||||
.iter()
|
||||
.map(|attestation| {
|
||||
let indexed_attestation = get_indexed_attestation(self.state, attestation)?;
|
||||
|
||||
self.sets.push(indexed_attestation_signature_set(
|
||||
&self.state,
|
||||
&attestation.signature,
|
||||
&indexed_attestation,
|
||||
&self.spec,
|
||||
)?);
|
||||
|
||||
Ok(indexed_attestation)
|
||||
})
|
||||
.collect::<Result<_>>()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Includes all signatures in `self.block.body.voluntary_exits` for verification.
|
||||
fn include_exits(&mut self) -> Result<()> {
|
||||
let mut sets = self
|
||||
.block
|
||||
.body
|
||||
.voluntary_exits
|
||||
.iter()
|
||||
.map(|exit| exit_signature_set(&self.state, exit, &self.spec))
|
||||
.collect::<SignatureSetResult<_>>()?;
|
||||
|
||||
self.sets.append(&mut sets);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes all signatures in `self.block.body.transfers` for verification.
|
||||
fn include_transfers(&mut self) -> Result<()> {
|
||||
let mut sets = self
|
||||
.block
|
||||
.body
|
||||
.transfers
|
||||
.iter()
|
||||
.map(|transfer| transfer_signature_set(&self.state, transfer, &self.spec))
|
||||
.collect::<SignatureSetResult<_>>()?;
|
||||
|
||||
self.sets.append(&mut sets);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,87 @@
|
||||
use super::signature_sets::Error as SignatureSetError;
|
||||
use types::*;
|
||||
|
||||
macro_rules! impl_from_beacon_state_error {
|
||||
($type: ident) => {
|
||||
impl From<BeaconStateError> for $type {
|
||||
fn from(e: BeaconStateError) -> $type {
|
||||
$type::BeaconStateError(e)
|
||||
}
|
||||
}
|
||||
};
|
||||
/// The error returned from the `per_block_processing` function. Indicates that a block is either
|
||||
/// invalid, or we were unable to determine it's validity (we encountered an unexpected error).
|
||||
///
|
||||
/// Any of the `...Error` variants indicate that at some point during block (and block operation)
|
||||
/// verification, there was an error. There is no indication as to _where_ that error happened
|
||||
/// (e.g., when processing attestations instead of when processing deposits).
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum BlockProcessingError {
|
||||
RandaoSignatureInvalid,
|
||||
BulkSignatureVerificationFailed,
|
||||
StateRootMismatch,
|
||||
DepositCountInvalid {
|
||||
expected: usize,
|
||||
found: usize,
|
||||
},
|
||||
DuplicateTransfers {
|
||||
duplicates: usize,
|
||||
},
|
||||
HeaderInvalid {
|
||||
reason: HeaderInvalid,
|
||||
},
|
||||
ProposerSlashingInvalid {
|
||||
index: usize,
|
||||
reason: ProposerSlashingInvalid,
|
||||
},
|
||||
AttesterSlashingInvalid {
|
||||
index: usize,
|
||||
reason: AttesterSlashingInvalid,
|
||||
},
|
||||
IndexedAttestationInvalid {
|
||||
index: usize,
|
||||
reason: IndexedAttestationInvalid,
|
||||
},
|
||||
AttestationInvalid {
|
||||
index: usize,
|
||||
reason: AttestationInvalid,
|
||||
},
|
||||
DepositInvalid {
|
||||
index: usize,
|
||||
reason: DepositInvalid,
|
||||
},
|
||||
ExitInvalid {
|
||||
index: usize,
|
||||
reason: ExitInvalid,
|
||||
},
|
||||
TransferInvalid {
|
||||
index: usize,
|
||||
reason: TransferInvalid,
|
||||
},
|
||||
BeaconStateError(BeaconStateError),
|
||||
SignatureSetError(SignatureSetError),
|
||||
SszTypesError(ssz_types::Error),
|
||||
}
|
||||
|
||||
macro_rules! impl_into_with_index_with_beacon_error {
|
||||
($error_type: ident, $invalid_type: ident) => {
|
||||
impl IntoWithIndex<BlockProcessingError> for $error_type {
|
||||
fn into_with_index(self, i: usize) -> BlockProcessingError {
|
||||
match self {
|
||||
$error_type::Invalid(e) => {
|
||||
BlockProcessingError::Invalid(BlockInvalid::$invalid_type(i, e))
|
||||
}
|
||||
$error_type::BeaconStateError(e) => BlockProcessingError::BeaconStateError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
impl From<BeaconStateError> for BlockProcessingError {
|
||||
fn from(e: BeaconStateError) -> Self {
|
||||
BlockProcessingError::BeaconStateError(e)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_into_with_index_without_beacon_error {
|
||||
($error_type: ident, $invalid_type: ident) => {
|
||||
impl IntoWithIndex<BlockProcessingError> for $error_type {
|
||||
fn into_with_index(self, i: usize) -> BlockProcessingError {
|
||||
match self {
|
||||
$error_type::Invalid(e) => {
|
||||
BlockProcessingError::Invalid(BlockInvalid::$invalid_type(i, e))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<SignatureSetError> for BlockProcessingError {
|
||||
fn from(e: SignatureSetError) -> Self {
|
||||
BlockProcessingError::SignatureSetError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ssz_types::Error> for BlockProcessingError {
|
||||
fn from(error: ssz_types::Error) -> Self {
|
||||
BlockProcessingError::SszTypesError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BlockOperationError<HeaderInvalid>> for BlockProcessingError {
|
||||
fn from(e: BlockOperationError<HeaderInvalid>) -> BlockProcessingError {
|
||||
match e {
|
||||
BlockOperationError::Invalid(reason) => BlockProcessingError::HeaderInvalid { reason },
|
||||
BlockOperationError::BeaconStateError(e) => BlockProcessingError::BeaconStateError(e),
|
||||
BlockOperationError::SignatureSetError(e) => BlockProcessingError::SignatureSetError(e),
|
||||
BlockOperationError::SszTypesError(e) => BlockProcessingError::SszTypesError(e),
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// A conversion that consumes `self` and adds an `index` variable to resulting struct.
|
||||
@@ -48,81 +93,117 @@ pub trait IntoWithIndex<T>: Sized {
|
||||
fn into_with_index(self, index: usize) -> T;
|
||||
}
|
||||
|
||||
/*
|
||||
* Block Validation
|
||||
*/
|
||||
macro_rules! impl_into_block_processing_error_with_index {
|
||||
($($type: ident),*) => {
|
||||
$(
|
||||
impl IntoWithIndex<BlockProcessingError> for BlockOperationError<$type> {
|
||||
fn into_with_index(self, index: usize) -> BlockProcessingError {
|
||||
match self {
|
||||
BlockOperationError::Invalid(reason) => BlockProcessingError::$type {
|
||||
index,
|
||||
reason
|
||||
},
|
||||
BlockOperationError::BeaconStateError(e) => BlockProcessingError::BeaconStateError(e),
|
||||
BlockOperationError::SignatureSetError(e) => BlockProcessingError::SignatureSetError(e),
|
||||
BlockOperationError::SszTypesError(e) => BlockProcessingError::SszTypesError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_into_block_processing_error_with_index!(
|
||||
ProposerSlashingInvalid,
|
||||
AttesterSlashingInvalid,
|
||||
IndexedAttestationInvalid,
|
||||
AttestationInvalid,
|
||||
DepositInvalid,
|
||||
ExitInvalid,
|
||||
TransferInvalid
|
||||
);
|
||||
|
||||
pub type HeaderValidationError = BlockOperationError<HeaderInvalid>;
|
||||
pub type AttesterSlashingValidationError = BlockOperationError<AttesterSlashingInvalid>;
|
||||
pub type ProposerSlashingValidationError = BlockOperationError<ProposerSlashingInvalid>;
|
||||
pub type AttestationValidationError = BlockOperationError<AttestationInvalid>;
|
||||
pub type DepositValidationError = BlockOperationError<DepositInvalid>;
|
||||
pub type ExitValidationError = BlockOperationError<ExitInvalid>;
|
||||
pub type TransferValidationError = BlockOperationError<TransferInvalid>;
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum BlockProcessingError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(BlockInvalid),
|
||||
/// Encountered a `BeaconStateError` whilst attempting to determine validity.
|
||||
pub enum BlockOperationError<T> {
|
||||
Invalid(T),
|
||||
BeaconStateError(BeaconStateError),
|
||||
/// Encountered an `ssz_types::Error` whilst attempting to determine validity.
|
||||
SignatureSetError(SignatureSetError),
|
||||
SszTypesError(ssz_types::Error),
|
||||
}
|
||||
|
||||
impl_from_beacon_state_error!(BlockProcessingError);
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum BlockInvalid {
|
||||
StateSlotMismatch,
|
||||
ParentBlockRootMismatch {
|
||||
state: Hash256,
|
||||
block: Hash256,
|
||||
},
|
||||
ProposerSlashed(usize),
|
||||
BadSignature,
|
||||
BadRandaoSignature,
|
||||
MaxAttestationsExceeded,
|
||||
MaxAttesterSlashingsExceed,
|
||||
MaxProposerSlashingsExceeded,
|
||||
DepositCountInvalid,
|
||||
DuplicateTransfers,
|
||||
MaxExitsExceeded,
|
||||
MaxTransfersExceed,
|
||||
AttestationInvalid(usize, AttestationInvalid),
|
||||
/// A `IndexedAttestation` inside an `AttesterSlashing` was invalid.
|
||||
///
|
||||
/// To determine the offending `AttesterSlashing` index, divide the error message `usize` by two.
|
||||
IndexedAttestationInvalid(usize, IndexedAttestationInvalid),
|
||||
AttesterSlashingInvalid(usize, AttesterSlashingInvalid),
|
||||
ProposerSlashingInvalid(usize, ProposerSlashingInvalid),
|
||||
DepositInvalid(usize, DepositInvalid),
|
||||
// TODO: merge this into the `DepositInvalid` error.
|
||||
DepositProcessingFailed(usize),
|
||||
ExitInvalid(usize, ExitInvalid),
|
||||
TransferInvalid(usize, TransferInvalid),
|
||||
// NOTE: this is only used in tests, normally a state root mismatch is handled
|
||||
// in the beacon_chain rather than in state_processing
|
||||
StateRootMismatch,
|
||||
impl<T> BlockOperationError<T> {
|
||||
pub fn invalid(reason: T) -> BlockOperationError<T> {
|
||||
BlockOperationError::Invalid(reason)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ssz_types::Error> for BlockProcessingError {
|
||||
impl<T> From<BeaconStateError> for BlockOperationError<T> {
|
||||
fn from(e: BeaconStateError) -> Self {
|
||||
BlockOperationError::BeaconStateError(e)
|
||||
}
|
||||
}
|
||||
impl<T> From<SignatureSetError> for BlockOperationError<T> {
|
||||
fn from(e: SignatureSetError) -> Self {
|
||||
BlockOperationError::SignatureSetError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<ssz_types::Error> for BlockOperationError<T> {
|
||||
fn from(error: ssz_types::Error) -> Self {
|
||||
BlockProcessingError::SszTypesError(error)
|
||||
BlockOperationError::SszTypesError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<BlockProcessingError> for BlockInvalid {
|
||||
fn into(self) -> BlockProcessingError {
|
||||
BlockProcessingError::Invalid(self)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Attestation Validation
|
||||
*/
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum AttestationValidationError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(AttestationInvalid),
|
||||
/// Encountered a `BeaconStateError` whilst attempting to determine validity.
|
||||
BeaconStateError(BeaconStateError),
|
||||
pub enum HeaderInvalid {
|
||||
ProposalSignatureInvalid,
|
||||
StateSlotMismatch,
|
||||
ParentBlockRootMismatch { state: Hash256, block: Hash256 },
|
||||
ProposerSlashed(usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum ProposerSlashingInvalid {
|
||||
/// The proposer index is not a known validator.
|
||||
ProposerUnknown(u64),
|
||||
/// The two proposal have different epochs.
|
||||
///
|
||||
/// (proposal_1_slot, proposal_2_slot)
|
||||
ProposalEpochMismatch(Slot, Slot),
|
||||
/// The proposals are identical and therefore not slashable.
|
||||
ProposalsIdentical,
|
||||
/// The specified proposer cannot be slashed because they are already slashed, or not active.
|
||||
ProposerNotSlashable(u64),
|
||||
/// The first proposal signature was invalid.
|
||||
BadProposal1Signature,
|
||||
/// The second proposal signature was invalid.
|
||||
BadProposal2Signature,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum AttesterSlashingInvalid {
|
||||
/// The attestation data is identical, an attestation cannot conflict with itself.
|
||||
AttestationDataIdentical,
|
||||
/// The attestations were not in conflict.
|
||||
NotSlashable,
|
||||
/// The first `IndexedAttestation` was invalid.
|
||||
IndexedAttestation1Invalid(BlockOperationError<IndexedAttestationInvalid>),
|
||||
/// The second `IndexedAttestation` was invalid.
|
||||
IndexedAttestation2Invalid(BlockOperationError<IndexedAttestationInvalid>),
|
||||
/// The validator index is unknown. One cannot slash one who does not exist.
|
||||
UnknownValidator(u64),
|
||||
/// The specified validator has already been withdrawn.
|
||||
ValidatorAlreadyWithdrawn(u64),
|
||||
/// There were no indices able to be slashed.
|
||||
NoSlashableIndices,
|
||||
}
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
@@ -186,69 +267,21 @@ pub enum AttestationInvalid {
|
||||
BadIndexedAttestation(IndexedAttestationInvalid),
|
||||
}
|
||||
|
||||
impl_from_beacon_state_error!(AttestationValidationError);
|
||||
impl_into_with_index_with_beacon_error!(AttestationValidationError, AttestationInvalid);
|
||||
|
||||
impl From<IndexedAttestationValidationError> for AttestationValidationError {
|
||||
fn from(err: IndexedAttestationValidationError) -> Self {
|
||||
let IndexedAttestationValidationError::Invalid(e) = err;
|
||||
AttestationValidationError::Invalid(AttestationInvalid::BadIndexedAttestation(e))
|
||||
impl From<BlockOperationError<IndexedAttestationInvalid>>
|
||||
for BlockOperationError<AttestationInvalid>
|
||||
{
|
||||
fn from(e: BlockOperationError<IndexedAttestationInvalid>) -> Self {
|
||||
match e {
|
||||
BlockOperationError::Invalid(e) => {
|
||||
BlockOperationError::invalid(AttestationInvalid::BadIndexedAttestation(e))
|
||||
}
|
||||
BlockOperationError::BeaconStateError(e) => BlockOperationError::BeaconStateError(e),
|
||||
BlockOperationError::SignatureSetError(e) => BlockOperationError::SignatureSetError(e),
|
||||
BlockOperationError::SszTypesError(e) => BlockOperationError::SszTypesError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ssz_types::Error> for AttestationValidationError {
|
||||
fn from(error: ssz_types::Error) -> Self {
|
||||
Self::from(IndexedAttestationValidationError::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* `AttesterSlashing` Validation
|
||||
*/
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum AttesterSlashingValidationError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(AttesterSlashingInvalid),
|
||||
/// Encountered a `BeaconStateError` whilst attempting to determine validity.
|
||||
BeaconStateError(BeaconStateError),
|
||||
}
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum AttesterSlashingInvalid {
|
||||
/// The attestation data is identical, an attestation cannot conflict with itself.
|
||||
AttestationDataIdentical,
|
||||
/// The attestations were not in conflict.
|
||||
NotSlashable,
|
||||
/// The first `IndexedAttestation` was invalid.
|
||||
IndexedAttestation1Invalid(IndexedAttestationInvalid),
|
||||
/// The second `IndexedAttestation` was invalid.
|
||||
IndexedAttestation2Invalid(IndexedAttestationInvalid),
|
||||
/// The validator index is unknown. One cannot slash one who does not exist.
|
||||
UnknownValidator(u64),
|
||||
/// The specified validator has already been withdrawn.
|
||||
ValidatorAlreadyWithdrawn(u64),
|
||||
/// There were no indices able to be slashed.
|
||||
NoSlashableIndices,
|
||||
}
|
||||
|
||||
impl_from_beacon_state_error!(AttesterSlashingValidationError);
|
||||
impl_into_with_index_with_beacon_error!(AttesterSlashingValidationError, AttesterSlashingInvalid);
|
||||
|
||||
/*
|
||||
* `IndexedAttestation` Validation
|
||||
*/
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum IndexedAttestationValidationError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(IndexedAttestationInvalid),
|
||||
}
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum IndexedAttestationInvalid {
|
||||
/// The custody bit 0 validators intersect with the bit 1 validators.
|
||||
@@ -271,106 +304,24 @@ pub enum IndexedAttestationInvalid {
|
||||
UnknownValidator(u64),
|
||||
/// The indexed attestation aggregate signature was not valid.
|
||||
BadSignature,
|
||||
/// There was an error whilst attempting to get a set of signatures. The signatures may have
|
||||
/// been invalid or an internal error occurred.
|
||||
SignatureSetError(SignatureSetError),
|
||||
}
|
||||
|
||||
impl Into<IndexedAttestationInvalid> for IndexedAttestationValidationError {
|
||||
fn into(self) -> IndexedAttestationInvalid {
|
||||
match self {
|
||||
IndexedAttestationValidationError::Invalid(e) => e,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ssz_types::Error> for IndexedAttestationValidationError {
|
||||
fn from(error: ssz_types::Error) -> Self {
|
||||
IndexedAttestationValidationError::Invalid(
|
||||
IndexedAttestationInvalid::CustodyBitfieldBoundsError(error),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl_into_with_index_without_beacon_error!(
|
||||
IndexedAttestationValidationError,
|
||||
IndexedAttestationInvalid
|
||||
);
|
||||
|
||||
/*
|
||||
* `ProposerSlashing` Validation
|
||||
*/
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum ProposerSlashingValidationError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(ProposerSlashingInvalid),
|
||||
}
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum ProposerSlashingInvalid {
|
||||
/// The proposer index is not a known validator.
|
||||
ProposerUnknown(u64),
|
||||
/// The two proposal have different epochs.
|
||||
///
|
||||
/// (proposal_1_slot, proposal_2_slot)
|
||||
ProposalEpochMismatch(Slot, Slot),
|
||||
/// The proposals are identical and therefore not slashable.
|
||||
ProposalsIdentical,
|
||||
/// The specified proposer cannot be slashed because they are already slashed, or not active.
|
||||
ProposerNotSlashable(u64),
|
||||
/// The first proposal signature was invalid.
|
||||
BadProposal1Signature,
|
||||
/// The second proposal signature was invalid.
|
||||
BadProposal2Signature,
|
||||
}
|
||||
|
||||
impl_into_with_index_without_beacon_error!(
|
||||
ProposerSlashingValidationError,
|
||||
ProposerSlashingInvalid
|
||||
);
|
||||
|
||||
/*
|
||||
* `Deposit` Validation
|
||||
*/
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum DepositValidationError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(DepositInvalid),
|
||||
/// Encountered a `BeaconStateError` whilst attempting to determine validity.
|
||||
BeaconStateError(BeaconStateError),
|
||||
}
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum DepositInvalid {
|
||||
/// The deposit index does not match the state index.
|
||||
BadIndex { state: u64, deposit: u64 },
|
||||
/// The signature (proof-of-possession) does not match the given pubkey.
|
||||
BadSignature,
|
||||
/// The signature does not represent a valid BLS signature.
|
||||
BadSignatureBytes,
|
||||
/// The signature or pubkey does not represent a valid BLS point.
|
||||
BadBlsBytes,
|
||||
/// The specified `branch` and `index` did not form a valid proof that the deposit is included
|
||||
/// in the eth1 deposit root.
|
||||
BadMerkleProof,
|
||||
}
|
||||
|
||||
impl_from_beacon_state_error!(DepositValidationError);
|
||||
impl_into_with_index_with_beacon_error!(DepositValidationError, DepositInvalid);
|
||||
|
||||
/*
|
||||
* `Exit` Validation
|
||||
*/
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum ExitValidationError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(ExitInvalid),
|
||||
}
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum ExitInvalid {
|
||||
/// The specified validator is not active.
|
||||
@@ -390,24 +341,11 @@ pub enum ExitInvalid {
|
||||
},
|
||||
/// The exit signature was not signed by the validator.
|
||||
BadSignature,
|
||||
/// There was an error whilst attempting to get a set of signatures. The signatures may have
|
||||
/// been invalid or an internal error occurred.
|
||||
SignatureSetError(SignatureSetError),
|
||||
}
|
||||
|
||||
impl_into_with_index_without_beacon_error!(ExitValidationError, ExitInvalid);
|
||||
|
||||
/*
|
||||
* `Transfer` Validation
|
||||
*/
|
||||
|
||||
/// The object is invalid or validation failed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum TransferValidationError {
|
||||
/// Validation completed successfully and the object is invalid.
|
||||
Invalid(TransferInvalid),
|
||||
/// Encountered a `BeaconStateError` whilst attempting to determine validity.
|
||||
BeaconStateError(BeaconStateError),
|
||||
}
|
||||
|
||||
/// Describes why an object is invalid.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum TransferInvalid {
|
||||
/// The validator indicated by `transfer.from` is unknown.
|
||||
@@ -460,6 +398,3 @@ pub enum TransferInvalid {
|
||||
/// (proposer_balance, transfer_fee)
|
||||
ProposerBalanceOverflow(u64, u64),
|
||||
}
|
||||
|
||||
impl_from_beacon_state_error!(TransferValidationError);
|
||||
impl_into_with_index_with_beacon_error!(TransferValidationError, TransferInvalid);
|
||||
|
||||
@@ -1,42 +1,25 @@
|
||||
use super::errors::{
|
||||
IndexedAttestationInvalid as Invalid, IndexedAttestationValidationError as Error,
|
||||
};
|
||||
use super::errors::{BlockOperationError, IndexedAttestationInvalid as Invalid};
|
||||
use super::signature_sets::indexed_attestation_signature_set;
|
||||
use crate::VerifySignatures;
|
||||
use std::collections::HashSet;
|
||||
use std::iter::FromIterator;
|
||||
use tree_hash::TreeHash;
|
||||
use types::*;
|
||||
|
||||
type Result<T> = std::result::Result<T, BlockOperationError<Invalid>>;
|
||||
|
||||
fn error(reason: Invalid) -> BlockOperationError<Invalid> {
|
||||
BlockOperationError::invalid(reason)
|
||||
}
|
||||
|
||||
/// Verify an `IndexedAttestation`.
|
||||
///
|
||||
/// Spec v0.8.0
|
||||
pub fn is_valid_indexed_attestation<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
indexed_attestation: &IndexedAttestation<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
is_valid_indexed_attestation_parametric(state, indexed_attestation, spec, true)
|
||||
}
|
||||
|
||||
/// Verify but don't check the signature.
|
||||
///
|
||||
/// Spec v0.8.0
|
||||
pub fn is_valid_indexed_attestation_without_signature<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
indexed_attestation: &IndexedAttestation<T>,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
is_valid_indexed_attestation_parametric(state, indexed_attestation, spec, false)
|
||||
}
|
||||
|
||||
/// Optionally check the signature.
|
||||
///
|
||||
/// Spec v0.8.0
|
||||
fn is_valid_indexed_attestation_parametric<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
indexed_attestation: &IndexedAttestation<T>,
|
||||
spec: &ChainSpec,
|
||||
verify_signature: bool,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let bit_0_indices = &indexed_attestation.custody_bit_0_indices;
|
||||
let bit_1_indices = &indexed_attestation.custody_bit_1_indices;
|
||||
|
||||
@@ -59,10 +42,10 @@ fn is_valid_indexed_attestation_parametric<T: EthSpec>(
|
||||
);
|
||||
|
||||
// Check that both vectors of indices are sorted
|
||||
let check_sorted = |list: &[u64]| -> Result<(), Error> {
|
||||
let check_sorted = |list: &[u64]| -> Result<()> {
|
||||
list.windows(2).enumerate().try_for_each(|(i, pair)| {
|
||||
if pair[0] >= pair[1] {
|
||||
invalid!(Invalid::BadValidatorIndicesOrdering(i));
|
||||
return Err(error(Invalid::BadValidatorIndicesOrdering(i)));
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -72,74 +55,18 @@ fn is_valid_indexed_attestation_parametric<T: EthSpec>(
|
||||
check_sorted(&bit_0_indices)?;
|
||||
check_sorted(&bit_1_indices)?;
|
||||
|
||||
if verify_signature {
|
||||
is_valid_indexed_attestation_signature(state, indexed_attestation, spec)?;
|
||||
if verify_signatures.is_true() {
|
||||
verify!(
|
||||
indexed_attestation_signature_set(
|
||||
state,
|
||||
&indexed_attestation.signature,
|
||||
&indexed_attestation,
|
||||
spec
|
||||
)?
|
||||
.is_valid(),
|
||||
Invalid::BadSignature
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create an aggregate public key for a list of validators, failing if any key can't be found.
|
||||
fn create_aggregate_pubkey<'a, T, I>(
|
||||
state: &BeaconState<T>,
|
||||
validator_indices: I,
|
||||
) -> Result<AggregatePublicKey, Error>
|
||||
where
|
||||
I: IntoIterator<Item = &'a u64>,
|
||||
T: EthSpec,
|
||||
{
|
||||
validator_indices.into_iter().try_fold(
|
||||
AggregatePublicKey::new(),
|
||||
|mut aggregate_pubkey, &validator_idx| {
|
||||
state
|
||||
.validators
|
||||
.get(validator_idx as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::UnknownValidator(validator_idx)))
|
||||
.map(|validator| {
|
||||
aggregate_pubkey.add(&validator.pubkey);
|
||||
aggregate_pubkey
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Verify the signature of an IndexedAttestation.
|
||||
///
|
||||
/// Spec v0.8.0
|
||||
fn is_valid_indexed_attestation_signature<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
indexed_attestation: &IndexedAttestation<T>,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
let bit_0_pubkey = create_aggregate_pubkey(state, &indexed_attestation.custody_bit_0_indices)?;
|
||||
let bit_1_pubkey = create_aggregate_pubkey(state, &indexed_attestation.custody_bit_1_indices)?;
|
||||
|
||||
let message_0 = AttestationDataAndCustodyBit {
|
||||
data: indexed_attestation.data.clone(),
|
||||
custody_bit: false,
|
||||
}
|
||||
.tree_hash_root();
|
||||
let message_1 = AttestationDataAndCustodyBit {
|
||||
data: indexed_attestation.data.clone(),
|
||||
custody_bit: true,
|
||||
}
|
||||
.tree_hash_root();
|
||||
|
||||
let messages = vec![&message_0[..], &message_1[..]];
|
||||
let keys = vec![&bit_0_pubkey, &bit_1_pubkey];
|
||||
|
||||
let domain = spec.get_domain(
|
||||
indexed_attestation.data.target.epoch,
|
||||
Domain::Attestation,
|
||||
&state.fork,
|
||||
);
|
||||
|
||||
verify!(
|
||||
indexed_attestation
|
||||
.signature
|
||||
.verify_multiple(&messages[..], domain, &keys[..]),
|
||||
Invalid::BadSignature
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
282
eth2/state_processing/src/per_block_processing/signature_sets.rs
Normal file
282
eth2/state_processing/src/per_block_processing/signature_sets.rs
Normal file
@@ -0,0 +1,282 @@
|
||||
//! A `SignatureSet` is an abstraction over the components of a signature. A `SignatureSet` may be
|
||||
//! validated individually, or alongside in others in a potentially cheaper bulk operation.
|
||||
//!
|
||||
//! This module exposes one function to extract each type of `SignatureSet` from a `BeaconBlock`.
|
||||
use bls::SignatureSet;
|
||||
use std::convert::TryInto;
|
||||
use tree_hash::{SignedRoot, TreeHash};
|
||||
use types::{
|
||||
AggregateSignature, AttestationDataAndCustodyBit, AttesterSlashing, BeaconBlock,
|
||||
BeaconBlockHeader, BeaconState, BeaconStateError, ChainSpec, Deposit, Domain, EthSpec, Fork,
|
||||
Hash256, IndexedAttestation, ProposerSlashing, PublicKey, RelativeEpoch, Signature, Transfer,
|
||||
VoluntaryExit,
|
||||
};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Error {
|
||||
/// Signature verification failed. The block is invalid.
|
||||
SignatureInvalid,
|
||||
/// There was an error attempting to read from a `BeaconState`. Block
|
||||
/// validity was not determined.
|
||||
BeaconStateError(BeaconStateError),
|
||||
/// Attempted to find the public key of a validator that does not exist. You cannot distinguish
|
||||
/// between an error and an invalid block in this case.
|
||||
ValidatorUnknown(u64),
|
||||
/// The public keys supplied do not match the number of objects requiring keys. Block validity
|
||||
/// was not determined.
|
||||
MismatchedPublicKeyLen { pubkey_len: usize, other_len: usize },
|
||||
}
|
||||
|
||||
impl From<BeaconStateError> for Error {
|
||||
fn from(e: BeaconStateError) -> Error {
|
||||
Error::BeaconStateError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// A signature set that is valid if a block was signed by the expected block producer.
|
||||
pub fn block_proposal_signature_set<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
block: &'a BeaconBlock<T>,
|
||||
block_signed_root: Option<Hash256>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet<'a>> {
|
||||
let block_proposer = &state.validators
|
||||
[state.get_beacon_proposer_index(block.slot, RelativeEpoch::Current, spec)?];
|
||||
|
||||
let domain = spec.get_domain(
|
||||
block.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::BeaconProposer,
|
||||
&state.fork,
|
||||
);
|
||||
|
||||
let message = if let Some(root) = block_signed_root {
|
||||
root.as_bytes().to_vec()
|
||||
} else {
|
||||
block.signed_root()
|
||||
};
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&block.signature,
|
||||
&block_proposer.pubkey,
|
||||
message,
|
||||
domain,
|
||||
))
|
||||
}
|
||||
|
||||
/// A signature set that is valid if the block proposers randao reveal signature is correct.
|
||||
pub fn randao_signature_set<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
block: &'a BeaconBlock<T>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet<'a>> {
|
||||
let block_proposer = &state.validators
|
||||
[state.get_beacon_proposer_index(block.slot, RelativeEpoch::Current, spec)?];
|
||||
|
||||
let domain = spec.get_domain(
|
||||
block.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::Randao,
|
||||
&state.fork,
|
||||
);
|
||||
|
||||
let message = state.current_epoch().tree_hash_root();
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&block.body.randao_reveal,
|
||||
&block_proposer.pubkey,
|
||||
message,
|
||||
domain,
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns two signature sets, one for each `BlockHeader` included in the `ProposerSlashing`.
|
||||
pub fn proposer_slashing_signature_set<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
proposer_slashing: &'a ProposerSlashing,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<(SignatureSet<'a>, SignatureSet<'a>)> {
|
||||
let proposer = state
|
||||
.validators
|
||||
.get(proposer_slashing.proposer_index as usize)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(proposer_slashing.proposer_index))?;
|
||||
|
||||
Ok((
|
||||
block_header_signature_set(state, &proposer_slashing.header_1, &proposer.pubkey, spec)?,
|
||||
block_header_signature_set(state, &proposer_slashing.header_2, &proposer.pubkey, spec)?,
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns a signature set that is valid if the given `pubkey` signed the `header`.
|
||||
fn block_header_signature_set<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
header: &'a BeaconBlockHeader,
|
||||
pubkey: &'a PublicKey,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet<'a>> {
|
||||
let domain = spec.get_domain(
|
||||
header.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::BeaconProposer,
|
||||
&state.fork,
|
||||
);
|
||||
|
||||
let message = header.signed_root();
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&header.signature,
|
||||
pubkey,
|
||||
message,
|
||||
domain,
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns the signature set for the given `indexed_attestation`.
|
||||
pub fn indexed_attestation_signature_set<'a, 'b, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
signature: &'a AggregateSignature,
|
||||
indexed_attestation: &'b IndexedAttestation<T>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet<'a>> {
|
||||
let message_0 = AttestationDataAndCustodyBit {
|
||||
data: indexed_attestation.data.clone(),
|
||||
custody_bit: false,
|
||||
}
|
||||
.tree_hash_root();
|
||||
let message_1 = AttestationDataAndCustodyBit {
|
||||
data: indexed_attestation.data.clone(),
|
||||
custody_bit: true,
|
||||
}
|
||||
.tree_hash_root();
|
||||
|
||||
let domain = spec.get_domain(
|
||||
indexed_attestation.data.target.epoch,
|
||||
Domain::Attestation,
|
||||
&state.fork,
|
||||
);
|
||||
|
||||
Ok(SignatureSet::dual(
|
||||
signature,
|
||||
message_0,
|
||||
get_pubkeys(state, &indexed_attestation.custody_bit_0_indices)?,
|
||||
message_1,
|
||||
get_pubkeys(state, &indexed_attestation.custody_bit_1_indices)?,
|
||||
domain,
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns the signature set for the given `attester_slashing` and corresponding `pubkeys`.
|
||||
pub fn attester_slashing_signature_sets<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
attester_slashing: &'a AttesterSlashing<T>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<(SignatureSet<'a>, SignatureSet<'a>)> {
|
||||
Ok((
|
||||
indexed_attestation_signature_set(
|
||||
state,
|
||||
&attester_slashing.attestation_1.signature,
|
||||
&attester_slashing.attestation_1,
|
||||
spec,
|
||||
)?,
|
||||
indexed_attestation_signature_set(
|
||||
state,
|
||||
&attester_slashing.attestation_2.signature,
|
||||
&attester_slashing.attestation_2,
|
||||
spec,
|
||||
)?,
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns the BLS values in a `Deposit`, if they're all valid. Otherwise, returns `None`.
|
||||
///
|
||||
/// This method is separate to `deposit_signature_set` to satisfy lifetime requirements.
|
||||
pub fn deposit_pubkey_signature_message(
|
||||
deposit: &Deposit,
|
||||
) -> Option<(PublicKey, Signature, Vec<u8>)> {
|
||||
let pubkey = (&deposit.data.pubkey).try_into().ok()?;
|
||||
let signature = (&deposit.data.signature).try_into().ok()?;
|
||||
let message = deposit.data.signed_root();
|
||||
Some((pubkey, signature, message))
|
||||
}
|
||||
|
||||
/// Returns the signature set for some set of deposit signatures, made with
|
||||
/// `deposit_pubkey_signature_message`.
|
||||
pub fn deposit_signature_set<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
pubkey_signature_message: &'a (PublicKey, Signature, Vec<u8>),
|
||||
spec: &'a ChainSpec,
|
||||
) -> SignatureSet<'a> {
|
||||
let (pubkey, signature, message) = pubkey_signature_message;
|
||||
|
||||
// Note: Deposits are valid across forks, thus the deposit domain is computed
|
||||
// with the fork zeroed.
|
||||
let domain = spec.get_domain(state.current_epoch(), Domain::Deposit, &Fork::default());
|
||||
|
||||
SignatureSet::single(signature, pubkey, message.clone(), domain)
|
||||
}
|
||||
|
||||
/// Returns a signature set that is valid if the `VoluntaryExit` was signed by the indicated
|
||||
/// validator.
|
||||
pub fn exit_signature_set<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
exit: &'a VoluntaryExit,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet<'a>> {
|
||||
let validator = state
|
||||
.validators
|
||||
.get(exit.validator_index as usize)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(exit.validator_index))?;
|
||||
|
||||
let domain = spec.get_domain(exit.epoch, Domain::VoluntaryExit, &state.fork);
|
||||
|
||||
let message = exit.signed_root();
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&exit.signature,
|
||||
&validator.pubkey,
|
||||
message,
|
||||
domain,
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns a signature set that is valid if the `Transfer` was signed by `transfer.pubkey`.
|
||||
pub fn transfer_signature_set<'a, T: EthSpec>(
|
||||
state: &'a BeaconState<T>,
|
||||
transfer: &'a Transfer,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet<'a>> {
|
||||
let domain = spec.get_domain(
|
||||
transfer.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::Transfer,
|
||||
&state.fork,
|
||||
);
|
||||
|
||||
let message = transfer.signed_root();
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&transfer.signature,
|
||||
&transfer.pubkey,
|
||||
message,
|
||||
domain,
|
||||
))
|
||||
}
|
||||
|
||||
/// Maps validator indices to public keys.
|
||||
fn get_pubkeys<'a, 'b, T, I>(
|
||||
state: &'a BeaconState<T>,
|
||||
validator_indices: I,
|
||||
) -> Result<Vec<&'a PublicKey>>
|
||||
where
|
||||
I: IntoIterator<Item = &'b u64>,
|
||||
T: EthSpec,
|
||||
{
|
||||
validator_indices
|
||||
.into_iter()
|
||||
.map(|&validator_idx| {
|
||||
state
|
||||
.validators
|
||||
.get(validator_idx as usize)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(validator_idx))
|
||||
.map(|validator| &validator.pubkey)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#![cfg(all(test, not(feature = "fake_crypto")))]
|
||||
use super::block_processing_builder::BlockProcessingBuilder;
|
||||
use super::errors::*;
|
||||
use crate::per_block_processing;
|
||||
use crate::{per_block_processing, BlockSignatureStrategy};
|
||||
use tree_hash::SignedRoot;
|
||||
use types::*;
|
||||
|
||||
@@ -13,7 +13,13 @@ fn valid_block_ok() {
|
||||
let builder = get_builder(&spec);
|
||||
let (block, mut state) = builder.build(None, None, &spec);
|
||||
|
||||
let result = per_block_processing(&mut state, &block, &spec);
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
@@ -27,13 +33,19 @@ fn invalid_block_header_state_slot() {
|
||||
state.slot = Slot::new(133713);
|
||||
block.slot = Slot::new(424242);
|
||||
|
||||
let result = per_block_processing(&mut state, &block, &spec);
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::Invalid(
|
||||
BlockInvalid::StateSlotMismatch
|
||||
))
|
||||
Err(BlockProcessingError::HeaderInvalid {
|
||||
reason: HeaderInvalid::StateSlotMismatch
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,16 +56,22 @@ fn invalid_parent_block_root() {
|
||||
let invalid_parent_root = Hash256::from([0xAA; 32]);
|
||||
let (block, mut state) = builder.build(None, Some(invalid_parent_root), &spec);
|
||||
|
||||
let result = per_block_processing(&mut state, &block, &spec);
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::Invalid(
|
||||
BlockInvalid::ParentBlockRootMismatch {
|
||||
Err(BlockProcessingError::HeaderInvalid {
|
||||
reason: HeaderInvalid::ParentBlockRootMismatch {
|
||||
state: Hash256::from_slice(&state.latest_block_header.signed_root()),
|
||||
block: block.parent_root
|
||||
}
|
||||
))
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -71,12 +89,20 @@ fn invalid_block_signature() {
|
||||
block.signature = Signature::new(&message, domain, &keypair.sk);
|
||||
|
||||
// process block with invalid block signature
|
||||
let result = per_block_processing(&mut state, &block, &spec);
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// should get a BadSignature error
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::Invalid(BlockInvalid::BadSignature))
|
||||
Err(BlockProcessingError::HeaderInvalid {
|
||||
reason: HeaderInvalid::ProposalSignatureInvalid
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -89,15 +115,16 @@ fn invalid_randao_reveal_signature() {
|
||||
let keypair = Keypair::random();
|
||||
let (block, mut state) = builder.build(Some(keypair.sk), None, &spec);
|
||||
|
||||
let result = per_block_processing(&mut state, &block, &spec);
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// should get a BadRandaoSignature error
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::Invalid(
|
||||
BlockInvalid::BadRandaoSignature
|
||||
))
|
||||
);
|
||||
assert_eq!(result, Err(BlockProcessingError::RandaoSignatureInvalid));
|
||||
}
|
||||
|
||||
fn get_builder(spec: &ChainSpec) -> (BlockProcessingBuilder<MainnetEthSpec>) {
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
use super::errors::{AttestationInvalid as Invalid, AttestationValidationError as Error};
|
||||
use super::errors::{AttestationInvalid as Invalid, BlockOperationError};
|
||||
use super::VerifySignatures;
|
||||
use crate::common::get_indexed_attestation;
|
||||
use crate::per_block_processing::{
|
||||
is_valid_indexed_attestation, is_valid_indexed_attestation_without_signature,
|
||||
};
|
||||
use crate::per_block_processing::is_valid_indexed_attestation;
|
||||
use tree_hash::TreeHash;
|
||||
use types::*;
|
||||
|
||||
type Result<T> = std::result::Result<T, BlockOperationError<Invalid>>;
|
||||
|
||||
fn error(reason: Invalid) -> BlockOperationError<Invalid> {
|
||||
BlockOperationError::invalid(reason)
|
||||
}
|
||||
|
||||
/// Returns `Ok(())` if the given `attestation` is valid to be included in a block that is applied
|
||||
/// to `state`. Otherwise, returns a descriptive `Err`.
|
||||
///
|
||||
@@ -16,9 +20,9 @@ use types::*;
|
||||
pub fn verify_attestation_for_block_inclusion<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attestation: &Attestation<T>,
|
||||
spec: &ChainSpec,
|
||||
verify_signatures: VerifySignatures,
|
||||
) -> Result<(), Error> {
|
||||
spec: &ChainSpec,
|
||||
) -> Result<()> {
|
||||
let data = &attestation.data;
|
||||
|
||||
// Check attestation slot.
|
||||
@@ -40,7 +44,7 @@ pub fn verify_attestation_for_block_inclusion<T: EthSpec>(
|
||||
}
|
||||
);
|
||||
|
||||
verify_attestation_for_state(state, attestation, spec, verify_signatures)
|
||||
verify_attestation_for_state(state, attestation, verify_signatures, spec)
|
||||
}
|
||||
|
||||
/// Returns `Ok(())` if `attestation` is a valid attestation to the chain that precedes the given
|
||||
@@ -53,9 +57,9 @@ pub fn verify_attestation_for_block_inclusion<T: EthSpec>(
|
||||
pub fn verify_attestation_for_state<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attestation: &Attestation<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
verify_signature: VerifySignatures,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let data = &attestation.data;
|
||||
verify!(
|
||||
data.crosslink.shard < T::ShardCount::to_u64(),
|
||||
@@ -90,11 +94,7 @@ pub fn verify_attestation_for_state<T: EthSpec>(
|
||||
|
||||
// Check signature and bitfields
|
||||
let indexed_attestation = get_indexed_attestation(state, attestation)?;
|
||||
if verify_signature == VerifySignatures::True {
|
||||
is_valid_indexed_attestation(state, &indexed_attestation, spec)?;
|
||||
} else {
|
||||
is_valid_indexed_attestation_without_signature(state, &indexed_attestation, spec)?;
|
||||
}
|
||||
is_valid_indexed_attestation(state, &indexed_attestation, verify_signatures, spec)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -107,7 +107,7 @@ pub fn verify_attestation_for_state<T: EthSpec>(
|
||||
fn verify_casper_ffg_vote<'a, T: EthSpec>(
|
||||
attestation: &Attestation<T>,
|
||||
state: &'a BeaconState<T>,
|
||||
) -> Result<&'a Crosslink, Error> {
|
||||
) -> Result<&'a Crosslink> {
|
||||
let data = &attestation.data;
|
||||
if data.target.epoch == state.current_epoch() {
|
||||
verify!(
|
||||
@@ -130,6 +130,6 @@ fn verify_casper_ffg_vote<'a, T: EthSpec>(
|
||||
);
|
||||
Ok(state.get_previous_crosslink(data.crosslink.shard)?)
|
||||
} else {
|
||||
invalid!(Invalid::BadTargetEpoch)
|
||||
return Err(error(Invalid::BadTargetEpoch));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
use super::errors::{AttesterSlashingInvalid as Invalid, AttesterSlashingValidationError as Error};
|
||||
use super::errors::{AttesterSlashingInvalid as Invalid, BlockOperationError};
|
||||
use super::is_valid_indexed_attestation::is_valid_indexed_attestation;
|
||||
use crate::per_block_processing::VerifySignatures;
|
||||
use std::collections::BTreeSet;
|
||||
use types::*;
|
||||
|
||||
type Result<T> = std::result::Result<T, BlockOperationError<Invalid>>;
|
||||
|
||||
fn error(reason: Invalid) -> BlockOperationError<Invalid> {
|
||||
BlockOperationError::invalid(reason)
|
||||
}
|
||||
|
||||
/// Indicates if an `AttesterSlashing` is valid to be included in a block in the current epoch of the given
|
||||
/// state.
|
||||
///
|
||||
@@ -13,8 +20,9 @@ pub fn verify_attester_slashing<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attester_slashing: &AttesterSlashing<T>,
|
||||
should_verify_indexed_attestations: bool,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let attestation_1 = &attester_slashing.attestation_1;
|
||||
let attestation_2 = &attester_slashing.attestation_2;
|
||||
|
||||
@@ -26,10 +34,10 @@ pub fn verify_attester_slashing<T: EthSpec>(
|
||||
);
|
||||
|
||||
if should_verify_indexed_attestations {
|
||||
is_valid_indexed_attestation(state, &attestation_1, spec)
|
||||
.map_err(|e| Error::Invalid(Invalid::IndexedAttestation1Invalid(e.into())))?;
|
||||
is_valid_indexed_attestation(state, &attestation_2, spec)
|
||||
.map_err(|e| Error::Invalid(Invalid::IndexedAttestation2Invalid(e.into())))?;
|
||||
is_valid_indexed_attestation(state, &attestation_1, verify_signatures, spec)
|
||||
.map_err(|e| error(Invalid::IndexedAttestation1Invalid(e)))?;
|
||||
is_valid_indexed_attestation(state, &attestation_2, verify_signatures, spec)
|
||||
.map_err(|e| error(Invalid::IndexedAttestation2Invalid(e)))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -43,7 +51,7 @@ pub fn verify_attester_slashing<T: EthSpec>(
|
||||
pub fn get_slashable_indices<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attester_slashing: &AttesterSlashing<T>,
|
||||
) -> Result<Vec<u64>, Error> {
|
||||
) -> Result<Vec<u64>> {
|
||||
get_slashable_indices_modular(state, attester_slashing, |_, validator| {
|
||||
validator.is_slashable_at(state.current_epoch())
|
||||
})
|
||||
@@ -55,7 +63,7 @@ pub fn get_slashable_indices_modular<F, T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attester_slashing: &AttesterSlashing<T>,
|
||||
is_slashable: F,
|
||||
) -> Result<Vec<u64>, Error>
|
||||
) -> Result<Vec<u64>>
|
||||
where
|
||||
F: Fn(u64, &Validator) -> bool,
|
||||
{
|
||||
@@ -81,7 +89,7 @@ where
|
||||
let validator = state
|
||||
.validators
|
||||
.get(index as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::UnknownValidator(index)))?;
|
||||
.ok_or_else(|| error(Invalid::UnknownValidator(index)))?;
|
||||
|
||||
if is_slashable(index, validator) {
|
||||
slashable_indices.push(index);
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
use super::errors::{DepositInvalid as Invalid, DepositValidationError as Error};
|
||||
use super::errors::{BlockOperationError, DepositInvalid};
|
||||
use crate::per_block_processing::signature_sets::{
|
||||
deposit_pubkey_signature_message, deposit_signature_set,
|
||||
};
|
||||
use merkle_proof::verify_merkle_proof;
|
||||
use std::convert::TryInto;
|
||||
use tree_hash::{SignedRoot, TreeHash};
|
||||
use tree_hash::TreeHash;
|
||||
use types::*;
|
||||
|
||||
type Result<T> = std::result::Result<T, BlockOperationError<DepositInvalid>>;
|
||||
|
||||
fn error(reason: DepositInvalid) -> BlockOperationError<DepositInvalid> {
|
||||
BlockOperationError::invalid(reason)
|
||||
}
|
||||
|
||||
/// Verify `Deposit.pubkey` signed `Deposit.signature`.
|
||||
///
|
||||
/// Spec v0.8.0
|
||||
@@ -11,18 +19,13 @@ pub fn verify_deposit_signature<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
deposit: &Deposit,
|
||||
spec: &ChainSpec,
|
||||
pubkey: &PublicKey,
|
||||
) -> Result<(), Error> {
|
||||
// Note: Deposits are valid across forks, thus the deposit domain is computed
|
||||
// with the fork zeroed.
|
||||
let domain = spec.get_domain(state.current_epoch(), Domain::Deposit, &Fork::default());
|
||||
let signature: Signature = (&deposit.data.signature)
|
||||
.try_into()
|
||||
.map_err(|_| Error::Invalid(Invalid::BadSignatureBytes))?;
|
||||
) -> Result<()> {
|
||||
let deposit_signature_message = deposit_pubkey_signature_message(deposit)
|
||||
.ok_or_else(|| error(DepositInvalid::BadBlsBytes))?;
|
||||
|
||||
verify!(
|
||||
signature.verify(&deposit.data.signed_root(), domain, pubkey),
|
||||
Invalid::BadSignature
|
||||
deposit_signature_set(state, &deposit_signature_message, spec).is_valid(),
|
||||
DepositInvalid::BadSignature
|
||||
);
|
||||
|
||||
Ok(())
|
||||
@@ -37,7 +40,7 @@ pub fn verify_deposit_signature<T: EthSpec>(
|
||||
pub fn get_existing_validator_index<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
pub_key: &PublicKey,
|
||||
) -> Result<Option<u64>, Error> {
|
||||
) -> Result<Option<u64>> {
|
||||
let validator_index = state.get_validator_index(pub_key)?;
|
||||
Ok(validator_index.map(|idx| idx as u64))
|
||||
}
|
||||
@@ -53,7 +56,7 @@ pub fn verify_deposit_merkle_proof<T: EthSpec>(
|
||||
deposit: &Deposit,
|
||||
deposit_index: u64,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let leaf = deposit.data.tree_hash_root();
|
||||
|
||||
verify!(
|
||||
@@ -64,7 +67,7 @@ pub fn verify_deposit_merkle_proof<T: EthSpec>(
|
||||
deposit_index as usize,
|
||||
state.eth1_data.deposit_root,
|
||||
),
|
||||
Invalid::BadMerkleProof
|
||||
DepositInvalid::BadMerkleProof
|
||||
);
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
use super::errors::{ExitInvalid as Invalid, ExitValidationError as Error};
|
||||
use tree_hash::SignedRoot;
|
||||
use super::errors::{BlockOperationError, ExitInvalid};
|
||||
use crate::per_block_processing::{signature_sets::exit_signature_set, VerifySignatures};
|
||||
use types::*;
|
||||
|
||||
type Result<T> = std::result::Result<T, BlockOperationError<ExitInvalid>>;
|
||||
|
||||
fn error(reason: ExitInvalid) -> BlockOperationError<ExitInvalid> {
|
||||
BlockOperationError::invalid(reason)
|
||||
}
|
||||
|
||||
/// Indicates if an `Exit` is valid to be included in a block in the current epoch of the given
|
||||
/// state.
|
||||
///
|
||||
@@ -11,9 +17,10 @@ use types::*;
|
||||
pub fn verify_exit<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
exit: &VoluntaryExit,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
verify_exit_parametric(state, exit, spec, false)
|
||||
) -> Result<()> {
|
||||
verify_exit_parametric(state, exit, verify_signatures, spec, false)
|
||||
}
|
||||
|
||||
/// Like `verify_exit` but doesn't run checks which may become true in future states.
|
||||
@@ -22,9 +29,10 @@ pub fn verify_exit<T: EthSpec>(
|
||||
pub fn verify_exit_time_independent_only<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
exit: &VoluntaryExit,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
verify_exit_parametric(state, exit, spec, true)
|
||||
) -> Result<()> {
|
||||
verify_exit_parametric(state, exit, verify_signatures, spec, true)
|
||||
}
|
||||
|
||||
/// Parametric version of `verify_exit` that skips some checks if `time_independent_only` is true.
|
||||
@@ -33,30 +41,31 @@ pub fn verify_exit_time_independent_only<T: EthSpec>(
|
||||
fn verify_exit_parametric<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
exit: &VoluntaryExit,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
time_independent_only: bool,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let validator = state
|
||||
.validators
|
||||
.get(exit.validator_index as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::ValidatorUnknown(exit.validator_index)))?;
|
||||
.ok_or_else(|| error(ExitInvalid::ValidatorUnknown(exit.validator_index)))?;
|
||||
|
||||
// Verify the validator is active.
|
||||
verify!(
|
||||
validator.is_active_at(state.current_epoch()),
|
||||
Invalid::NotActive(exit.validator_index)
|
||||
ExitInvalid::NotActive(exit.validator_index)
|
||||
);
|
||||
|
||||
// Verify that the validator has not yet exited.
|
||||
verify!(
|
||||
validator.exit_epoch == spec.far_future_epoch,
|
||||
Invalid::AlreadyExited(exit.validator_index)
|
||||
ExitInvalid::AlreadyExited(exit.validator_index)
|
||||
);
|
||||
|
||||
// Exits must specify an epoch when they become valid; they are not valid before then.
|
||||
verify!(
|
||||
time_independent_only || state.current_epoch() >= exit.epoch,
|
||||
Invalid::FutureEpoch {
|
||||
ExitInvalid::FutureEpoch {
|
||||
state: state.current_epoch(),
|
||||
exit: exit.epoch
|
||||
}
|
||||
@@ -65,20 +74,18 @@ fn verify_exit_parametric<T: EthSpec>(
|
||||
// Verify the validator has been active long enough.
|
||||
verify!(
|
||||
state.current_epoch() >= validator.activation_epoch + spec.persistent_committee_period,
|
||||
Invalid::TooYoungToExit {
|
||||
ExitInvalid::TooYoungToExit {
|
||||
current_epoch: state.current_epoch(),
|
||||
earliest_exit_epoch: validator.activation_epoch + spec.persistent_committee_period,
|
||||
}
|
||||
);
|
||||
|
||||
// Verify signature.
|
||||
let message = exit.signed_root();
|
||||
let domain = spec.get_domain(exit.epoch, Domain::VoluntaryExit, &state.fork);
|
||||
verify!(
|
||||
exit.signature
|
||||
.verify(&message[..], domain, &validator.pubkey),
|
||||
Invalid::BadSignature
|
||||
);
|
||||
if verify_signatures.is_true() {
|
||||
verify!(
|
||||
exit_signature_set(state, exit, spec)?.is_valid(),
|
||||
ExitInvalid::BadSignature
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
use super::errors::{ProposerSlashingInvalid as Invalid, ProposerSlashingValidationError as Error};
|
||||
use tree_hash::SignedRoot;
|
||||
use super::errors::{BlockOperationError, ProposerSlashingInvalid as Invalid};
|
||||
use super::signature_sets::proposer_slashing_signature_set;
|
||||
use crate::VerifySignatures;
|
||||
use types::*;
|
||||
|
||||
type Result<T> = std::result::Result<T, BlockOperationError<Invalid>>;
|
||||
|
||||
fn error(reason: Invalid) -> BlockOperationError<Invalid> {
|
||||
BlockOperationError::invalid(reason)
|
||||
}
|
||||
|
||||
/// Indicates if a `ProposerSlashing` is valid to be included in a block in the current epoch of the given
|
||||
/// state.
|
||||
///
|
||||
@@ -11,14 +18,13 @@ use types::*;
|
||||
pub fn verify_proposer_slashing<T: EthSpec>(
|
||||
proposer_slashing: &ProposerSlashing,
|
||||
state: &BeaconState<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let proposer = state
|
||||
.validators
|
||||
.get(proposer_slashing.proposer_index as usize)
|
||||
.ok_or_else(|| {
|
||||
Error::Invalid(Invalid::ProposerUnknown(proposer_slashing.proposer_index))
|
||||
})?;
|
||||
.ok_or_else(|| error(Invalid::ProposerUnknown(proposer_slashing.proposer_index)))?;
|
||||
|
||||
// Verify that the epoch is the same
|
||||
verify!(
|
||||
@@ -42,44 +48,12 @@ pub fn verify_proposer_slashing<T: EthSpec>(
|
||||
Invalid::ProposerNotSlashable(proposer_slashing.proposer_index)
|
||||
);
|
||||
|
||||
verify!(
|
||||
verify_header_signature::<T>(
|
||||
&proposer_slashing.header_1,
|
||||
&proposer.pubkey,
|
||||
&state.fork,
|
||||
spec
|
||||
),
|
||||
Invalid::BadProposal1Signature
|
||||
);
|
||||
verify!(
|
||||
verify_header_signature::<T>(
|
||||
&proposer_slashing.header_2,
|
||||
&proposer.pubkey,
|
||||
&state.fork,
|
||||
spec
|
||||
),
|
||||
Invalid::BadProposal2Signature
|
||||
);
|
||||
if verify_signatures.is_true() {
|
||||
let (signature_set_1, signature_set_2) =
|
||||
proposer_slashing_signature_set(state, proposer_slashing, spec)?;
|
||||
verify!(signature_set_1.is_valid(), Invalid::BadProposal1Signature);
|
||||
verify!(signature_set_2.is_valid(), Invalid::BadProposal2Signature);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verifies the signature of a proposal.
|
||||
///
|
||||
/// Returns `true` if the signature is valid.
|
||||
///
|
||||
/// Spec v0.8.0
|
||||
fn verify_header_signature<T: EthSpec>(
|
||||
header: &BeaconBlockHeader,
|
||||
pubkey: &PublicKey,
|
||||
fork: &Fork,
|
||||
spec: &ChainSpec,
|
||||
) -> bool {
|
||||
let message = header.signed_root();
|
||||
let domain = spec.get_domain(
|
||||
header.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::BeaconProposer,
|
||||
fork,
|
||||
);
|
||||
header.signature.verify(&message[..], domain, pubkey)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
use super::errors::{TransferInvalid as Invalid, TransferValidationError as Error};
|
||||
use super::errors::{BlockOperationError, TransferInvalid as Invalid};
|
||||
use crate::per_block_processing::signature_sets::transfer_signature_set;
|
||||
use crate::per_block_processing::VerifySignatures;
|
||||
use bls::get_withdrawal_credentials;
|
||||
use tree_hash::SignedRoot;
|
||||
use types::*;
|
||||
|
||||
type Result<T> = std::result::Result<T, BlockOperationError<Invalid>>;
|
||||
|
||||
fn error(reason: Invalid) -> BlockOperationError<Invalid> {
|
||||
BlockOperationError::invalid(reason)
|
||||
}
|
||||
|
||||
/// Indicates if a `Transfer` is valid to be included in a block in the current epoch of the given
|
||||
/// state.
|
||||
///
|
||||
@@ -12,9 +19,10 @@ use types::*;
|
||||
pub fn verify_transfer<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
transfer: &Transfer,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
verify_transfer_parametric(state, transfer, spec, false)
|
||||
) -> Result<()> {
|
||||
verify_transfer_parametric(state, transfer, verify_signatures, spec, false)
|
||||
}
|
||||
|
||||
/// Like `verify_transfer` but doesn't run checks which may become true in future states.
|
||||
@@ -23,9 +31,10 @@ pub fn verify_transfer<T: EthSpec>(
|
||||
pub fn verify_transfer_time_independent_only<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
transfer: &Transfer,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
verify_transfer_parametric(state, transfer, spec, true)
|
||||
) -> Result<()> {
|
||||
verify_transfer_parametric(state, transfer, verify_signatures, spec, true)
|
||||
}
|
||||
|
||||
/// Parametric version of `verify_transfer` that allows some checks to be skipped.
|
||||
@@ -41,24 +50,25 @@ pub fn verify_transfer_time_independent_only<T: EthSpec>(
|
||||
fn verify_transfer_parametric<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
transfer: &Transfer,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
time_independent_only: bool,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let sender_balance = *state
|
||||
.balances
|
||||
.get(transfer.sender as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::FromValidatorUnknown(transfer.sender)))?;
|
||||
.ok_or_else(|| error(Invalid::FromValidatorUnknown(transfer.sender)))?;
|
||||
|
||||
let recipient_balance = *state
|
||||
.balances
|
||||
.get(transfer.recipient as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::FromValidatorUnknown(transfer.recipient)))?;
|
||||
.ok_or_else(|| error(Invalid::FromValidatorUnknown(transfer.recipient)))?;
|
||||
|
||||
// Safely determine `amount + fee`.
|
||||
let total_amount = transfer
|
||||
.amount
|
||||
.checked_add(transfer.fee)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::FeeOverflow(transfer.amount, transfer.fee)))?;
|
||||
.ok_or_else(|| error(Invalid::FeeOverflow(transfer.amount, transfer.fee)))?;
|
||||
|
||||
// Verify the sender has adequate balance.
|
||||
verify!(
|
||||
@@ -99,7 +109,7 @@ fn verify_transfer_parametric<T: EthSpec>(
|
||||
let sender_validator = state
|
||||
.validators
|
||||
.get(transfer.sender as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::FromValidatorUnknown(transfer.sender)))?;
|
||||
.ok_or_else(|| error(Invalid::FromValidatorUnknown(transfer.sender)))?;
|
||||
|
||||
// Ensure one of the following is met:
|
||||
//
|
||||
@@ -131,19 +141,12 @@ fn verify_transfer_parametric<T: EthSpec>(
|
||||
)
|
||||
);
|
||||
|
||||
// Verify the transfer signature.
|
||||
let message = transfer.signed_root();
|
||||
let domain = spec.get_domain(
|
||||
transfer.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::Transfer,
|
||||
&state.fork,
|
||||
);
|
||||
verify!(
|
||||
transfer
|
||||
.signature
|
||||
.verify(&message[..], domain, &transfer.pubkey),
|
||||
Invalid::BadSignature
|
||||
);
|
||||
if verify_signatures.is_true() {
|
||||
verify!(
|
||||
transfer_signature_set(state, transfer, spec)?.is_valid(),
|
||||
Invalid::BadSignature
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -157,15 +160,15 @@ pub fn execute_transfer<T: EthSpec>(
|
||||
state: &mut BeaconState<T>,
|
||||
transfer: &Transfer,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<()> {
|
||||
let sender_balance = *state
|
||||
.balances
|
||||
.get(transfer.sender as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::FromValidatorUnknown(transfer.sender)))?;
|
||||
.ok_or_else(|| error(Invalid::FromValidatorUnknown(transfer.sender)))?;
|
||||
let recipient_balance = *state
|
||||
.balances
|
||||
.get(transfer.recipient as usize)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::ToValidatorUnknown(transfer.recipient)))?;
|
||||
.ok_or_else(|| error(Invalid::ToValidatorUnknown(transfer.recipient)))?;
|
||||
|
||||
let proposer_index =
|
||||
state.get_beacon_proposer_index(state.slot, RelativeEpoch::Current, spec)?;
|
||||
@@ -174,11 +177,11 @@ pub fn execute_transfer<T: EthSpec>(
|
||||
let total_amount = transfer
|
||||
.amount
|
||||
.checked_add(transfer.fee)
|
||||
.ok_or_else(|| Error::Invalid(Invalid::FeeOverflow(transfer.amount, transfer.fee)))?;
|
||||
.ok_or_else(|| error(Invalid::FeeOverflow(transfer.amount, transfer.fee)))?;
|
||||
|
||||
state.balances[transfer.sender as usize] =
|
||||
sender_balance.checked_sub(total_amount).ok_or_else(|| {
|
||||
Error::Invalid(Invalid::FromBalanceInsufficient(
|
||||
error(Invalid::FromBalanceInsufficient(
|
||||
total_amount,
|
||||
sender_balance,
|
||||
))
|
||||
@@ -187,7 +190,7 @@ pub fn execute_transfer<T: EthSpec>(
|
||||
state.balances[transfer.recipient as usize] = recipient_balance
|
||||
.checked_add(transfer.amount)
|
||||
.ok_or_else(|| {
|
||||
Error::Invalid(Invalid::ToBalanceOverflow(
|
||||
error(Invalid::ToBalanceOverflow(
|
||||
recipient_balance,
|
||||
transfer.amount,
|
||||
))
|
||||
@@ -195,7 +198,7 @@ pub fn execute_transfer<T: EthSpec>(
|
||||
|
||||
state.balances[proposer_index] =
|
||||
proposer_balance.checked_add(transfer.fee).ok_or_else(|| {
|
||||
Error::Invalid(Invalid::ProposerBalanceOverflow(
|
||||
error(Invalid::ProposerBalanceOverflow(
|
||||
proposer_balance,
|
||||
transfer.fee,
|
||||
))
|
||||
|
||||
Reference in New Issue
Block a user