mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-11 04:31:51 +00:00
Directory Restructure (#1163)
* Move tests -> testing * Directory restructure * Update Cargo.toml during restructure * Update Makefile during restructure * Fix arbitrary path
This commit is contained in:
@@ -0,0 +1,380 @@
|
||||
use tree_hash::TreeHash;
|
||||
use types::test_utils::{
|
||||
AttestationTestTask, AttesterSlashingTestTask, DepositTestTask, ProposerSlashingTestTask,
|
||||
TestingAttestationDataBuilder, TestingBeaconBlockBuilder, TestingBeaconStateBuilder,
|
||||
};
|
||||
use types::*;
|
||||
|
||||
pub struct BlockProcessingBuilder<'a, T: EthSpec> {
|
||||
pub state: BeaconState<T>,
|
||||
pub keypairs: Vec<Keypair>,
|
||||
pub block_builder: TestingBeaconBlockBuilder<T>,
|
||||
pub spec: &'a ChainSpec,
|
||||
}
|
||||
|
||||
impl<'a, T: EthSpec> BlockProcessingBuilder<'a, T> {
|
||||
pub fn new(num_validators: usize, state_slot: Slot, spec: &'a ChainSpec) -> Self {
|
||||
let mut state_builder =
|
||||
TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(num_validators, &spec);
|
||||
state_builder.teleport_to_slot(state_slot);
|
||||
let (state, keypairs) = state_builder.build();
|
||||
let block_builder = TestingBeaconBlockBuilder::new(spec);
|
||||
|
||||
Self {
|
||||
state,
|
||||
keypairs,
|
||||
block_builder,
|
||||
spec,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_caches(mut self) -> Self {
|
||||
self.state
|
||||
.build_all_caches(self.spec)
|
||||
.expect("caches build OK");
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build_with_n_deposits(
|
||||
mut self,
|
||||
num_deposits: u64,
|
||||
test_task: DepositTestTask,
|
||||
randao_sk: Option<SecretKey>,
|
||||
previous_block_root: Option<Hash256>,
|
||||
spec: &ChainSpec,
|
||||
) -> (SignedBeaconBlock<T>, BeaconState<T>) {
|
||||
let (mut state, keypairs) = (self.state, self.keypairs);
|
||||
|
||||
let builder = &mut self.block_builder;
|
||||
|
||||
builder.set_slot(state.slot);
|
||||
|
||||
match previous_block_root {
|
||||
Some(root) => builder.set_parent_root(root),
|
||||
None => builder.set_parent_root(state.latest_block_header.tree_hash_root()),
|
||||
}
|
||||
|
||||
let proposer_index = state.get_beacon_proposer_index(state.slot, spec).unwrap();
|
||||
let keypair = &keypairs[proposer_index];
|
||||
|
||||
builder.set_proposer_index(proposer_index as u64);
|
||||
|
||||
match randao_sk {
|
||||
Some(sk) => {
|
||||
builder.set_randao_reveal(&sk, &state.fork, state.genesis_validators_root, spec)
|
||||
}
|
||||
None => builder.set_randao_reveal(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
),
|
||||
}
|
||||
|
||||
self.block_builder.insert_deposits(
|
||||
spec.max_effective_balance,
|
||||
test_task,
|
||||
1,
|
||||
num_deposits,
|
||||
&mut state,
|
||||
spec,
|
||||
);
|
||||
|
||||
let block = self.block_builder.build(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
);
|
||||
|
||||
(block, state)
|
||||
}
|
||||
|
||||
/// Insert a signed `VoluntaryIndex` for the given validator at the given `exit_epoch`.
|
||||
pub fn insert_exit(mut self, validator_index: u64, exit_epoch: Epoch) -> Self {
|
||||
self.block_builder.insert_exit(
|
||||
validator_index,
|
||||
exit_epoch,
|
||||
&self.keypairs[validator_index as usize].sk,
|
||||
&self.state,
|
||||
self.spec,
|
||||
);
|
||||
self
|
||||
}
|
||||
|
||||
/// Insert an attestation for the given slot and index.
|
||||
///
|
||||
/// It will be signed by all validators for which `should_sign` returns `true`
|
||||
/// when called with `(committee_position, validator_index)`.
|
||||
// TODO: consider using this pattern to replace the TestingAttestationBuilder
|
||||
pub fn insert_attestation(
|
||||
mut self,
|
||||
slot: Slot,
|
||||
index: u64,
|
||||
mut should_sign: impl FnMut(usize, usize) -> bool,
|
||||
) -> Self {
|
||||
let committee = self.state.get_beacon_committee(slot, index).unwrap();
|
||||
let data = TestingAttestationDataBuilder::new(
|
||||
AttestationTestTask::Valid,
|
||||
&self.state,
|
||||
index,
|
||||
slot,
|
||||
self.spec,
|
||||
)
|
||||
.build();
|
||||
|
||||
let mut attestation = Attestation {
|
||||
aggregation_bits: BitList::with_capacity(committee.committee.len()).unwrap(),
|
||||
data,
|
||||
signature: AggregateSignature::new(),
|
||||
};
|
||||
|
||||
for (i, &validator_index) in committee.committee.into_iter().enumerate() {
|
||||
if should_sign(i, validator_index) {
|
||||
attestation
|
||||
.sign(
|
||||
&self.keypairs[validator_index].sk,
|
||||
i,
|
||||
&self.state.fork,
|
||||
self.state.genesis_validators_root,
|
||||
self.spec,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
self.block_builder
|
||||
.block
|
||||
.body
|
||||
.attestations
|
||||
.push(attestation)
|
||||
.unwrap();
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Apply a mutation to the `BeaconBlock` before signing.
|
||||
pub fn modify(mut self, f: impl FnOnce(&mut BeaconBlock<T>)) -> Self {
|
||||
self.block_builder.modify(f);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build_with_n_attestations(
|
||||
mut self,
|
||||
test_task: AttestationTestTask,
|
||||
num_attestations: u64,
|
||||
randao_sk: Option<SecretKey>,
|
||||
previous_block_root: Option<Hash256>,
|
||||
spec: &ChainSpec,
|
||||
) -> (SignedBeaconBlock<T>, BeaconState<T>) {
|
||||
let (state, keypairs) = (self.state, self.keypairs);
|
||||
let builder = &mut self.block_builder;
|
||||
|
||||
builder.set_slot(state.slot);
|
||||
|
||||
match previous_block_root {
|
||||
Some(root) => builder.set_parent_root(root),
|
||||
None => builder.set_parent_root(state.latest_block_header.tree_hash_root()),
|
||||
}
|
||||
|
||||
let proposer_index = state.get_beacon_proposer_index(state.slot, spec).unwrap();
|
||||
let keypair = &keypairs[proposer_index];
|
||||
|
||||
builder.set_proposer_index(proposer_index as u64);
|
||||
|
||||
match randao_sk {
|
||||
Some(sk) => {
|
||||
builder.set_randao_reveal(&sk, &state.fork, state.genesis_validators_root, spec)
|
||||
}
|
||||
None => builder.set_randao_reveal(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
),
|
||||
}
|
||||
|
||||
let all_secret_keys: Vec<&SecretKey> = keypairs.iter().map(|keypair| &keypair.sk).collect();
|
||||
self.block_builder
|
||||
.insert_attestations(
|
||||
test_task,
|
||||
&state,
|
||||
&all_secret_keys,
|
||||
num_attestations as usize,
|
||||
spec,
|
||||
)
|
||||
.unwrap();
|
||||
let block = self.block_builder.build(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
);
|
||||
|
||||
(block, state)
|
||||
}
|
||||
|
||||
pub fn build_with_attester_slashing(
|
||||
mut self,
|
||||
test_task: AttesterSlashingTestTask,
|
||||
num_attester_slashings: u64,
|
||||
randao_sk: Option<SecretKey>,
|
||||
previous_block_root: Option<Hash256>,
|
||||
spec: &ChainSpec,
|
||||
) -> (SignedBeaconBlock<T>, BeaconState<T>) {
|
||||
let (state, keypairs) = (self.state, self.keypairs);
|
||||
let builder = &mut self.block_builder;
|
||||
|
||||
builder.set_slot(state.slot);
|
||||
|
||||
match previous_block_root {
|
||||
Some(root) => builder.set_parent_root(root),
|
||||
None => builder.set_parent_root(state.latest_block_header.tree_hash_root()),
|
||||
}
|
||||
|
||||
let proposer_index = state.get_beacon_proposer_index(state.slot, spec).unwrap();
|
||||
let keypair = &keypairs[proposer_index];
|
||||
|
||||
builder.set_proposer_index(proposer_index as u64);
|
||||
|
||||
match randao_sk {
|
||||
Some(sk) => {
|
||||
builder.set_randao_reveal(&sk, &state.fork, state.genesis_validators_root, spec)
|
||||
}
|
||||
None => builder.set_randao_reveal(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
),
|
||||
}
|
||||
|
||||
let mut validator_indices = vec![];
|
||||
let mut secret_keys = vec![];
|
||||
for i in 0..num_attester_slashings {
|
||||
validator_indices.push(i);
|
||||
secret_keys.push(&keypairs[i as usize].sk);
|
||||
}
|
||||
|
||||
for _ in 0..num_attester_slashings {
|
||||
self.block_builder.insert_attester_slashing(
|
||||
test_task,
|
||||
&validator_indices,
|
||||
&secret_keys,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
);
|
||||
}
|
||||
let block = self.block_builder.build(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
);
|
||||
|
||||
(block, state)
|
||||
}
|
||||
|
||||
pub fn build_with_proposer_slashing(
|
||||
mut self,
|
||||
test_task: ProposerSlashingTestTask,
|
||||
num_proposer_slashings: u64,
|
||||
randao_sk: Option<SecretKey>,
|
||||
previous_block_root: Option<Hash256>,
|
||||
spec: &ChainSpec,
|
||||
) -> (SignedBeaconBlock<T>, BeaconState<T>) {
|
||||
let (state, keypairs) = (self.state, self.keypairs);
|
||||
let builder = &mut self.block_builder;
|
||||
|
||||
builder.set_slot(state.slot);
|
||||
|
||||
match previous_block_root {
|
||||
Some(root) => builder.set_parent_root(root),
|
||||
None => builder.set_parent_root(state.latest_block_header.tree_hash_root()),
|
||||
}
|
||||
|
||||
let proposer_index = state.get_beacon_proposer_index(state.slot, spec).unwrap();
|
||||
let keypair = &keypairs[proposer_index];
|
||||
|
||||
builder.set_proposer_index(proposer_index as u64);
|
||||
|
||||
match randao_sk {
|
||||
Some(sk) => {
|
||||
builder.set_randao_reveal(&sk, &state.fork, state.genesis_validators_root, spec)
|
||||
}
|
||||
None => builder.set_randao_reveal(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
),
|
||||
}
|
||||
|
||||
for i in 0..num_proposer_slashings {
|
||||
let validator_indices = i;
|
||||
let secret_keys = &keypairs[i as usize].sk;
|
||||
self.block_builder.insert_proposer_slashing(
|
||||
test_task,
|
||||
validator_indices,
|
||||
&secret_keys,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
);
|
||||
}
|
||||
let block = self.block_builder.build(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
);
|
||||
|
||||
(block, state)
|
||||
}
|
||||
|
||||
// NOTE: could remove optional args
|
||||
// NOTE: could return keypairs as well
|
||||
pub fn build(
|
||||
mut self,
|
||||
randao_sk: Option<SecretKey>,
|
||||
previous_block_root: Option<Hash256>,
|
||||
) -> (SignedBeaconBlock<T>, BeaconState<T>) {
|
||||
let (state, keypairs) = (self.state, self.keypairs);
|
||||
let spec = self.spec;
|
||||
let builder = &mut self.block_builder;
|
||||
|
||||
builder.set_slot(state.slot);
|
||||
|
||||
match previous_block_root {
|
||||
Some(root) => builder.set_parent_root(root),
|
||||
None => builder.set_parent_root(state.latest_block_header.tree_hash_root()),
|
||||
}
|
||||
|
||||
let proposer_index = state.get_beacon_proposer_index(state.slot, spec).unwrap();
|
||||
let keypair = &keypairs[proposer_index];
|
||||
|
||||
builder.set_proposer_index(proposer_index as u64);
|
||||
|
||||
match randao_sk {
|
||||
Some(sk) => {
|
||||
builder.set_randao_reveal(&sk, &state.fork, state.genesis_validators_root, spec)
|
||||
}
|
||||
None => builder.set_randao_reveal(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
),
|
||||
}
|
||||
|
||||
let block = self.block_builder.build(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
spec,
|
||||
);
|
||||
|
||||
(block, state)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
#![allow(clippy::integer_arithmetic)]
|
||||
|
||||
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, PublicKey, SignatureSet};
|
||||
use rayon::prelude::*;
|
||||
use std::borrow::Cow;
|
||||
use types::{
|
||||
BeaconState, BeaconStateError, ChainSpec, EthSpec, Hash256, IndexedAttestation,
|
||||
SignedBeaconBlock,
|
||||
};
|
||||
|
||||
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),
|
||||
/// The `BeaconBlock` has a `proposer_index` that does not match the index we computed locally.
|
||||
///
|
||||
/// The block is invalid.
|
||||
IncorrectBlockProposer { block: u64, local_shuffling: u64 },
|
||||
/// 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 {
|
||||
match e {
|
||||
// Make a special distinction for `IncorrectBlockProposer` since it indicates an
|
||||
// invalid block, not an internal error.
|
||||
SignatureSetError::IncorrectBlockProposer {
|
||||
block,
|
||||
local_shuffling,
|
||||
} => Error::IncorrectBlockProposer {
|
||||
block,
|
||||
local_shuffling,
|
||||
},
|
||||
e => 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 `SignedBeaconBlock`, 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, F>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>> + Clone,
|
||||
{
|
||||
get_pubkey: F,
|
||||
state: &'a BeaconState<T>,
|
||||
spec: &'a ChainSpec,
|
||||
sets: Vec<SignatureSet>,
|
||||
}
|
||||
|
||||
impl<'a, T, F> BlockSignatureVerifier<'a, T, F>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>> + Clone,
|
||||
{
|
||||
/// 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>, get_pubkey: F, spec: &'a ChainSpec) -> Self {
|
||||
Self {
|
||||
get_pubkey: get_pubkey,
|
||||
state,
|
||||
spec,
|
||||
sets: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify all* the signatures in the given `SignedBeaconBlock`, 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>,
|
||||
get_pubkey: F,
|
||||
block: &'a SignedBeaconBlock<T>,
|
||||
block_root: Option<Hash256>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<()> {
|
||||
let mut verifier = Self::new(state, get_pubkey, spec);
|
||||
verifier.include_all_signatures(block, block_root)?;
|
||||
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))
|
||||
.reduce(|| true, |current, this| current && this);
|
||||
|
||||
if result {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::SignatureInvalid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Includes all signatures on the block (except the deposit signatures) for verification.
|
||||
pub fn include_all_signatures(
|
||||
&mut self,
|
||||
block: &'a SignedBeaconBlock<T>,
|
||||
block_root: Option<Hash256>,
|
||||
) -> Result<()> {
|
||||
self.include_block_proposal(block, block_root)?;
|
||||
self.include_randao_reveal(block)?;
|
||||
self.include_proposer_slashings(block)?;
|
||||
self.include_attester_slashings(block)?;
|
||||
self.include_attestations(block)?;
|
||||
// Deposits are not included because they can legally have invalid signatures.
|
||||
self.include_exits(block)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes all signatures on the block (except the deposit signatures and the proposal
|
||||
/// signature) for verification.
|
||||
pub fn include_all_signatures_except_proposal(
|
||||
&mut self,
|
||||
block: &'a SignedBeaconBlock<T>,
|
||||
) -> Result<()> {
|
||||
self.include_randao_reveal(block)?;
|
||||
self.include_proposer_slashings(block)?;
|
||||
self.include_attester_slashings(block)?;
|
||||
self.include_attestations(block)?;
|
||||
// Deposits are not included because they can legally have invalid signatures.
|
||||
self.include_exits(block)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes the block signature for `self.block` for verification.
|
||||
pub fn include_block_proposal(
|
||||
&mut self,
|
||||
block: &'a SignedBeaconBlock<T>,
|
||||
block_root: Option<Hash256>,
|
||||
) -> Result<()> {
|
||||
let set = block_proposal_signature_set(
|
||||
self.state,
|
||||
self.get_pubkey.clone(),
|
||||
block,
|
||||
block_root,
|
||||
self.spec,
|
||||
)?;
|
||||
self.sets.push(set);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes the randao signature for `self.block` for verification.
|
||||
pub fn include_randao_reveal(&mut self, block: &'a SignedBeaconBlock<T>) -> Result<()> {
|
||||
let set = randao_signature_set(
|
||||
self.state,
|
||||
self.get_pubkey.clone(),
|
||||
&block.message,
|
||||
self.spec,
|
||||
)?;
|
||||
self.sets.push(set);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes all signatures in `self.block.body.proposer_slashings` for verification.
|
||||
pub fn include_proposer_slashings(&mut self, block: &'a SignedBeaconBlock<T>) -> Result<()> {
|
||||
let mut sets: Vec<SignatureSet> = block
|
||||
.message
|
||||
.body
|
||||
.proposer_slashings
|
||||
.iter()
|
||||
.map(|proposer_slashing| {
|
||||
let (set_1, set_2) = proposer_slashing_signature_set(
|
||||
self.state,
|
||||
self.get_pubkey.clone(),
|
||||
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.
|
||||
pub fn include_attester_slashings(&mut self, block: &'a SignedBeaconBlock<T>) -> Result<()> {
|
||||
block
|
||||
.message
|
||||
.body
|
||||
.attester_slashings
|
||||
.iter()
|
||||
.try_for_each(|attester_slashing| {
|
||||
let (set_1, set_2) = attester_slashing_signature_sets(
|
||||
&self.state,
|
||||
self.get_pubkey.clone(),
|
||||
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.
|
||||
pub fn include_attestations(
|
||||
&mut self,
|
||||
block: &'a SignedBeaconBlock<T>,
|
||||
) -> Result<Vec<IndexedAttestation<T>>> {
|
||||
block
|
||||
.message
|
||||
.body
|
||||
.attestations
|
||||
.iter()
|
||||
.map(|attestation| {
|
||||
let committee = self
|
||||
.state
|
||||
.get_beacon_committee(attestation.data.slot, attestation.data.index)?;
|
||||
let indexed_attestation =
|
||||
get_indexed_attestation(committee.committee, attestation)?;
|
||||
|
||||
self.sets.push(indexed_attestation_signature_set(
|
||||
&self.state,
|
||||
self.get_pubkey.clone(),
|
||||
&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.
|
||||
pub fn include_exits(&mut self, block: &'a SignedBeaconBlock<T>) -> Result<()> {
|
||||
let mut sets = block
|
||||
.message
|
||||
.body
|
||||
.voluntary_exits
|
||||
.iter()
|
||||
.map(|exit| exit_signature_set(&self.state, self.get_pubkey.clone(), exit, &self.spec))
|
||||
.collect::<SignatureSetResult<_>>()?;
|
||||
|
||||
self.sets.append(&mut sets);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
344
consensus/state_processing/src/per_block_processing/errors.rs
Normal file
344
consensus/state_processing/src/per_block_processing/errors.rs
Normal file
@@ -0,0 +1,344 @@
|
||||
use super::signature_sets::Error as SignatureSetError;
|
||||
use merkle_proof::MerkleTreeError;
|
||||
use safe_arith::ArithError;
|
||||
use types::*;
|
||||
|
||||
/// The error returned from the `per_block_processing` function. Indicates that a block is either
|
||||
/// invalid, or we were unable to determine its 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, Clone)]
|
||||
pub enum BlockProcessingError {
|
||||
RandaoSignatureInvalid,
|
||||
BulkSignatureVerificationFailed,
|
||||
StateRootMismatch,
|
||||
DepositCountInvalid {
|
||||
expected: usize,
|
||||
found: 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,
|
||||
},
|
||||
BeaconStateError(BeaconStateError),
|
||||
SignatureSetError(SignatureSetError),
|
||||
SszTypesError(ssz_types::Error),
|
||||
MerkleTreeError(MerkleTreeError),
|
||||
ArithError(ArithError),
|
||||
}
|
||||
|
||||
impl From<BeaconStateError> for BlockProcessingError {
|
||||
fn from(e: BeaconStateError) -> Self {
|
||||
BlockProcessingError::BeaconStateError(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<ArithError> for BlockProcessingError {
|
||||
fn from(e: ArithError) -> Self {
|
||||
BlockProcessingError::ArithError(e)
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
BlockOperationError::ArithError(e) => BlockProcessingError::ArithError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A conversion that consumes `self` and adds an `index` variable to resulting struct.
|
||||
///
|
||||
/// Used here to allow converting an error into an upstream error that points to the object that
|
||||
/// caused the error. For example, pointing to the index of an attestation that caused the
|
||||
/// `AttestationInvalid` error.
|
||||
pub trait IntoWithIndex<T>: Sized {
|
||||
fn into_with_index(self, index: usize) -> T;
|
||||
}
|
||||
|
||||
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),
|
||||
BlockOperationError::ArithError(e) => BlockProcessingError::ArithError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_into_block_processing_error_with_index!(
|
||||
ProposerSlashingInvalid,
|
||||
AttesterSlashingInvalid,
|
||||
IndexedAttestationInvalid,
|
||||
AttestationInvalid,
|
||||
DepositInvalid,
|
||||
ExitInvalid
|
||||
);
|
||||
|
||||
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>;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum BlockOperationError<T> {
|
||||
Invalid(T),
|
||||
BeaconStateError(BeaconStateError),
|
||||
SignatureSetError(SignatureSetError),
|
||||
SszTypesError(ssz_types::Error),
|
||||
ArithError(ArithError),
|
||||
}
|
||||
|
||||
impl<T> BlockOperationError<T> {
|
||||
pub fn invalid(reason: T) -> BlockOperationError<T> {
|
||||
BlockOperationError::Invalid(reason)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
BlockOperationError::SszTypesError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<ArithError> for BlockOperationError<T> {
|
||||
fn from(e: ArithError) -> Self {
|
||||
BlockOperationError::ArithError(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum HeaderInvalid {
|
||||
ProposalSignatureInvalid,
|
||||
StateSlotMismatch,
|
||||
ProposerIndexMismatch {
|
||||
block_proposer_index: usize,
|
||||
state_proposer_index: usize,
|
||||
},
|
||||
ParentBlockRootMismatch {
|
||||
state: Hash256,
|
||||
block: Hash256,
|
||||
},
|
||||
ProposerSlashed(usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum ProposerSlashingInvalid {
|
||||
/// The proposer index is not a known validator.
|
||||
ProposerUnknown(u64),
|
||||
/// The two proposal have different slots.
|
||||
///
|
||||
/// (proposal_1_slot, proposal_2_slot)
|
||||
ProposalSlotMismatch(Slot, Slot),
|
||||
/// The two proposals have different proposer indices.
|
||||
///
|
||||
/// (proposer_index_1, proposer_index_2)
|
||||
ProposerIndexMismatch(u64, u64),
|
||||
/// 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, Clone)]
|
||||
pub enum AttesterSlashingInvalid {
|
||||
/// 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.
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum AttestationInvalid {
|
||||
/// Commmittee index exceeds number of committees in that slot.
|
||||
BadCommitteeIndex,
|
||||
/// Attestation included before the inclusion delay.
|
||||
IncludedTooEarly {
|
||||
state: Slot,
|
||||
delay: u64,
|
||||
attestation: Slot,
|
||||
},
|
||||
/// Attestation slot is too far in the past to be included in a block.
|
||||
IncludedTooLate { state: Slot, attestation: Slot },
|
||||
/// Attestation target epoch does not match attestation slot.
|
||||
TargetEpochSlotMismatch {
|
||||
target_epoch: Epoch,
|
||||
slot_epoch: Epoch,
|
||||
},
|
||||
/// Attestation target epoch does not match the current or previous epoch.
|
||||
BadTargetEpoch,
|
||||
/// Attestation justified checkpoint doesn't match the state's current or previous justified
|
||||
/// checkpoint.
|
||||
///
|
||||
/// `is_current` is `true` if the attestation was compared to the
|
||||
/// `state.current_justified_checkpoint`, `false` if compared to `state.previous_justified_checkpoint`.
|
||||
WrongJustifiedCheckpoint {
|
||||
state: Checkpoint,
|
||||
attestation: Checkpoint,
|
||||
is_current: bool,
|
||||
},
|
||||
/// There are no set bits on the attestation -- an attestation must be signed by at least one
|
||||
/// validator.
|
||||
AggregationBitfieldIsEmpty,
|
||||
/// The aggregation bitfield length is not the smallest possible size to represent the committee.
|
||||
BadAggregationBitfieldLength {
|
||||
committee_len: usize,
|
||||
bitfield_len: usize,
|
||||
},
|
||||
/// The attestation was not disjoint compared to already seen attestations.
|
||||
NotDisjoint,
|
||||
/// The validator index was unknown.
|
||||
UnknownValidator(u64),
|
||||
/// The attestation signature verification failed.
|
||||
BadSignature,
|
||||
/// The indexed attestation created from this attestation was found to be invalid.
|
||||
BadIndexedAttestation(IndexedAttestationInvalid),
|
||||
}
|
||||
|
||||
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),
|
||||
BlockOperationError::ArithError(e) => BlockOperationError::ArithError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum IndexedAttestationInvalid {
|
||||
/// The number of indices exceeds the global maximum.
|
||||
///
|
||||
/// (max_indices, indices_given)
|
||||
MaxIndicesExceed(usize, usize),
|
||||
/// The validator indices were not in increasing order.
|
||||
///
|
||||
/// The error occurred between the given `index` and `index + 1`
|
||||
BadValidatorIndicesOrdering(usize),
|
||||
/// The validator index is unknown. One cannot slash one who does not exist.
|
||||
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),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum DepositInvalid {
|
||||
/// The signature (proof-of-possession) does not match the given pubkey.
|
||||
BadSignature,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum ExitInvalid {
|
||||
/// The specified validator is not active.
|
||||
NotActive(u64),
|
||||
/// The specified validator is not in the state's validator registry.
|
||||
ValidatorUnknown(u64),
|
||||
/// The specified validator has a non-maximum exit epoch.
|
||||
AlreadyExited(u64),
|
||||
/// The specified validator has already initiated exit.
|
||||
AlreadyInitiatedExit(u64),
|
||||
/// The exit is for a future epoch.
|
||||
FutureEpoch { state: Epoch, exit: Epoch },
|
||||
/// The validator has not been active for long enough.
|
||||
TooYoungToExit {
|
||||
current_epoch: Epoch,
|
||||
earliest_exit_epoch: Epoch,
|
||||
},
|
||||
/// 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),
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use super::errors::{BlockOperationError, IndexedAttestationInvalid as Invalid};
|
||||
use super::signature_sets::{get_pubkey_from_state, indexed_attestation_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)
|
||||
}
|
||||
|
||||
/// Verify an `IndexedAttestation`.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn is_valid_indexed_attestation<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
indexed_attestation: &IndexedAttestation<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<()> {
|
||||
let indices = &indexed_attestation.attesting_indices;
|
||||
|
||||
// Verify max number of indices
|
||||
verify!(
|
||||
indices.len() <= T::MaxValidatorsPerCommittee::to_usize(),
|
||||
Invalid::MaxIndicesExceed(T::MaxValidatorsPerCommittee::to_usize(), indices.len())
|
||||
);
|
||||
|
||||
// Check that indices are sorted and unique
|
||||
let check_sorted = |list: &[u64]| -> Result<()> {
|
||||
list.windows(2).enumerate().try_for_each(|(i, pair)| {
|
||||
if pair[0] < pair[1] {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(error(Invalid::BadValidatorIndicesOrdering(i)))
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
};
|
||||
check_sorted(indices)?;
|
||||
|
||||
if verify_signatures.is_true() {
|
||||
verify!(
|
||||
indexed_attestation_signature_set(
|
||||
state,
|
||||
|i| get_pubkey_from_state(state, i),
|
||||
&indexed_attestation.signature,
|
||||
&indexed_attestation,
|
||||
spec
|
||||
)?
|
||||
.is_valid(),
|
||||
Invalid::BadSignature
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
//! 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 ssz::DecodeError;
|
||||
use std::borrow::Cow;
|
||||
use std::convert::TryInto;
|
||||
use tree_hash::TreeHash;
|
||||
use types::{
|
||||
AggregateSignature, AttesterSlashing, BeaconBlock, BeaconState, BeaconStateError, ChainSpec,
|
||||
DepositData, Domain, EthSpec, Fork, Hash256, IndexedAttestation, ProposerSlashing, PublicKey,
|
||||
Signature, SignedAggregateAndProof, SignedBeaconBlock, SignedBeaconBlockHeader, SignedRoot,
|
||||
SignedVoluntaryExit, SigningRoot,
|
||||
};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum Error {
|
||||
/// Signature verification failed. The block is invalid.
|
||||
SignatureInvalid(DecodeError),
|
||||
/// 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 `BeaconBlock` has a `proposer_index` that does not match the index we computed locally.
|
||||
///
|
||||
/// The block is invalid.
|
||||
IncorrectBlockProposer { block: u64, local_shuffling: 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 },
|
||||
/// The public key bytes stored in the `BeaconState` were not valid. This is a serious internal
|
||||
/// error.
|
||||
BadBlsBytes { validator_index: u64 },
|
||||
}
|
||||
|
||||
impl From<BeaconStateError> for Error {
|
||||
fn from(e: BeaconStateError) -> Error {
|
||||
Error::BeaconStateError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function to get a public key from a `state`.
|
||||
pub fn get_pubkey_from_state<'a, T>(
|
||||
state: &'a BeaconState<T>,
|
||||
validator_index: usize,
|
||||
) -> Option<Cow<'a, PublicKey>>
|
||||
where
|
||||
T: EthSpec,
|
||||
{
|
||||
state
|
||||
.validators
|
||||
.get(validator_index)
|
||||
.and_then(|v| {
|
||||
let pk: Option<PublicKey> = (&v.pubkey).try_into().ok();
|
||||
pk
|
||||
})
|
||||
.map(Cow::Owned)
|
||||
}
|
||||
|
||||
/// A signature set that is valid if a block was signed by the expected block producer.
|
||||
pub fn block_proposal_signature_set<'a, T, F>(
|
||||
state: &'a BeaconState<T>,
|
||||
get_pubkey: F,
|
||||
signed_block: &'a SignedBeaconBlock<T>,
|
||||
block_root: Option<Hash256>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let block = &signed_block.message;
|
||||
let proposer_index = state.get_beacon_proposer_index(block.slot, spec)?;
|
||||
|
||||
if proposer_index as u64 != block.proposer_index {
|
||||
return Err(Error::IncorrectBlockProposer {
|
||||
block: block.proposer_index,
|
||||
local_shuffling: proposer_index as u64,
|
||||
});
|
||||
}
|
||||
|
||||
let domain = spec.get_domain(
|
||||
block.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::BeaconProposer,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
);
|
||||
|
||||
let message = if let Some(root) = block_root {
|
||||
SigningRoot {
|
||||
object_root: root,
|
||||
domain,
|
||||
}
|
||||
.tree_hash_root()
|
||||
} else {
|
||||
block.signing_root(domain)
|
||||
};
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&signed_block.signature,
|
||||
get_pubkey(proposer_index).ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
|
||||
message.as_bytes().to_vec(),
|
||||
))
|
||||
}
|
||||
|
||||
/// A signature set that is valid if the block proposers randao reveal signature is correct.
|
||||
pub fn randao_signature_set<'a, T, F>(
|
||||
state: &'a BeaconState<T>,
|
||||
get_pubkey: F,
|
||||
block: &'a BeaconBlock<T>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let proposer_index = state.get_beacon_proposer_index(block.slot, spec)?;
|
||||
|
||||
let domain = spec.get_domain(
|
||||
block.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::Randao,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
);
|
||||
|
||||
let message = block.slot.epoch(T::slots_per_epoch()).signing_root(domain);
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&block.body.randao_reveal,
|
||||
get_pubkey(proposer_index).ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
|
||||
message.as_bytes().to_vec(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns two signature sets, one for each `BlockHeader` included in the `ProposerSlashing`.
|
||||
pub fn proposer_slashing_signature_set<'a, T, F>(
|
||||
state: &'a BeaconState<T>,
|
||||
get_pubkey: F,
|
||||
proposer_slashing: &'a ProposerSlashing,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<(SignatureSet, SignatureSet)>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let proposer_index = proposer_slashing.signed_header_1.message.proposer_index as usize;
|
||||
|
||||
Ok((
|
||||
block_header_signature_set(
|
||||
state,
|
||||
&proposer_slashing.signed_header_1,
|
||||
get_pubkey(proposer_index)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
|
||||
spec,
|
||||
)?,
|
||||
block_header_signature_set(
|
||||
state,
|
||||
&proposer_slashing.signed_header_2,
|
||||
get_pubkey(proposer_index)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
|
||||
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>,
|
||||
signed_header: &'a SignedBeaconBlockHeader,
|
||||
pubkey: Cow<'a, PublicKey>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet> {
|
||||
let domain = spec.get_domain(
|
||||
signed_header.message.slot.epoch(T::slots_per_epoch()),
|
||||
Domain::BeaconProposer,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
);
|
||||
|
||||
let message = signed_header
|
||||
.message
|
||||
.signing_root(domain)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&signed_header.signature,
|
||||
pubkey,
|
||||
message,
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns the signature set for the given `indexed_attestation`.
|
||||
pub fn indexed_attestation_signature_set<'a, 'b, T, F>(
|
||||
state: &'a BeaconState<T>,
|
||||
get_pubkey: F,
|
||||
signature: &'a AggregateSignature,
|
||||
indexed_attestation: &'b IndexedAttestation<T>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let pubkeys = indexed_attestation
|
||||
.attesting_indices
|
||||
.into_iter()
|
||||
.map(|&validator_idx| {
|
||||
Ok(get_pubkey(validator_idx as usize)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(validator_idx))?)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
|
||||
let domain = spec.get_domain(
|
||||
indexed_attestation.data.target.epoch,
|
||||
Domain::BeaconAttester,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
);
|
||||
|
||||
let message = indexed_attestation.data.signing_root(domain);
|
||||
let message = message.as_bytes().to_vec();
|
||||
|
||||
Ok(SignatureSet::new(signature, pubkeys, message))
|
||||
}
|
||||
|
||||
/// Returns the signature set for the given `indexed_attestation` but pubkeys are supplied directly
|
||||
/// instead of from the state.
|
||||
pub fn indexed_attestation_signature_set_from_pubkeys<'a, 'b, T, F>(
|
||||
get_pubkey: F,
|
||||
signature: &'a AggregateSignature,
|
||||
indexed_attestation: &'b IndexedAttestation<T>,
|
||||
fork: &Fork,
|
||||
genesis_validators_root: Hash256,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let pubkeys = indexed_attestation
|
||||
.attesting_indices
|
||||
.into_iter()
|
||||
.map(|&validator_idx| {
|
||||
Ok(get_pubkey(validator_idx as usize)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(validator_idx))?)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
|
||||
let domain = spec.get_domain(
|
||||
indexed_attestation.data.target.epoch,
|
||||
Domain::BeaconAttester,
|
||||
&fork,
|
||||
genesis_validators_root,
|
||||
);
|
||||
|
||||
let message = indexed_attestation.data.signing_root(domain);
|
||||
let message = message.as_bytes().to_vec();
|
||||
|
||||
Ok(SignatureSet::new(signature, pubkeys, message))
|
||||
}
|
||||
|
||||
/// Returns the signature set for the given `attester_slashing` and corresponding `pubkeys`.
|
||||
pub fn attester_slashing_signature_sets<'a, T, F>(
|
||||
state: &'a BeaconState<T>,
|
||||
get_pubkey: F,
|
||||
attester_slashing: &'a AttesterSlashing<T>,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<(SignatureSet, SignatureSet)>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>> + Clone,
|
||||
{
|
||||
Ok((
|
||||
indexed_attestation_signature_set(
|
||||
state,
|
||||
get_pubkey.clone(),
|
||||
&attester_slashing.attestation_1.signature,
|
||||
&attester_slashing.attestation_1,
|
||||
spec,
|
||||
)?,
|
||||
indexed_attestation_signature_set(
|
||||
state,
|
||||
get_pubkey,
|
||||
&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_data: &DepositData,
|
||||
spec: &ChainSpec,
|
||||
) -> Option<(PublicKey, Signature, Vec<u8>)> {
|
||||
let pubkey = (&deposit_data.pubkey).try_into().ok()?;
|
||||
let signature = (&deposit_data.signature).try_into().ok()?;
|
||||
let domain = spec.get_deposit_domain();
|
||||
let message = deposit_data
|
||||
.as_deposit_message()
|
||||
.signing_root(domain)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
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>(
|
||||
pubkey_signature_message: &'a (PublicKey, Signature, Vec<u8>),
|
||||
) -> SignatureSet {
|
||||
let (pubkey, signature, message) = pubkey_signature_message;
|
||||
|
||||
// Note: Deposits are valid across forks, thus the deposit domain is computed
|
||||
// with the fok zeroed.
|
||||
SignatureSet::single(&signature, Cow::Borrowed(pubkey), message.clone())
|
||||
}
|
||||
|
||||
/// Returns a signature set that is valid if the `SignedVoluntaryExit` was signed by the indicated
|
||||
/// validator.
|
||||
pub fn exit_signature_set<'a, T, F>(
|
||||
state: &'a BeaconState<T>,
|
||||
get_pubkey: F,
|
||||
signed_exit: &'a SignedVoluntaryExit,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let exit = &signed_exit.message;
|
||||
let proposer_index = exit.validator_index as usize;
|
||||
|
||||
let domain = spec.get_domain(
|
||||
exit.epoch,
|
||||
Domain::VoluntaryExit,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
);
|
||||
|
||||
let message = exit.signing_root(domain).as_bytes().to_vec();
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
&signed_exit.signature,
|
||||
get_pubkey(proposer_index).ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
|
||||
message,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn signed_aggregate_selection_proof_signature_set<'a, T, F>(
|
||||
get_pubkey: F,
|
||||
signed_aggregate_and_proof: &'a SignedAggregateAndProof<T>,
|
||||
fork: &Fork,
|
||||
genesis_validators_root: Hash256,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let slot = signed_aggregate_and_proof.message.aggregate.data.slot;
|
||||
|
||||
let domain = spec.get_domain(
|
||||
slot.epoch(T::slots_per_epoch()),
|
||||
Domain::SelectionProof,
|
||||
fork,
|
||||
genesis_validators_root,
|
||||
);
|
||||
let message = slot.signing_root(domain).as_bytes().to_vec();
|
||||
let signature = &signed_aggregate_and_proof.message.selection_proof;
|
||||
let validator_index = signed_aggregate_and_proof.message.aggregator_index;
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
signature,
|
||||
get_pubkey(validator_index as usize)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(validator_index))?,
|
||||
message,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn signed_aggregate_signature_set<'a, T, F>(
|
||||
get_pubkey: F,
|
||||
signed_aggregate_and_proof: &'a SignedAggregateAndProof<T>,
|
||||
fork: &Fork,
|
||||
genesis_validators_root: Hash256,
|
||||
spec: &'a ChainSpec,
|
||||
) -> Result<SignatureSet>
|
||||
where
|
||||
T: EthSpec,
|
||||
F: Fn(usize) -> Option<Cow<'a, PublicKey>>,
|
||||
{
|
||||
let target_epoch = signed_aggregate_and_proof
|
||||
.message
|
||||
.aggregate
|
||||
.data
|
||||
.target
|
||||
.epoch;
|
||||
|
||||
let domain = spec.get_domain(
|
||||
target_epoch,
|
||||
Domain::AggregateAndProof,
|
||||
fork,
|
||||
genesis_validators_root,
|
||||
);
|
||||
let message = signed_aggregate_and_proof
|
||||
.message
|
||||
.signing_root(domain)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
let signature = &signed_aggregate_and_proof.signature;
|
||||
let validator_index = signed_aggregate_and_proof.message.aggregator_index;
|
||||
|
||||
Ok(SignatureSet::single(
|
||||
signature,
|
||||
get_pubkey(validator_index as usize)
|
||||
.ok_or_else(|| Error::ValidatorUnknown(validator_index))?,
|
||||
message,
|
||||
))
|
||||
}
|
||||
896
consensus/state_processing/src/per_block_processing/tests.rs
Normal file
896
consensus/state_processing/src/per_block_processing/tests.rs
Normal file
@@ -0,0 +1,896 @@
|
||||
#![cfg(all(test, not(feature = "fake_crypto")))]
|
||||
|
||||
use super::block_processing_builder::BlockProcessingBuilder;
|
||||
use super::errors::*;
|
||||
use crate::{per_block_processing, BlockSignatureStrategy};
|
||||
use types::test_utils::{
|
||||
AttestationTestTask, AttesterSlashingTestTask, DepositTestTask, ProposerSlashingTestTask,
|
||||
};
|
||||
use types::*;
|
||||
|
||||
pub const NUM_DEPOSITS: u64 = 1;
|
||||
pub const VALIDATOR_COUNT: usize = 64;
|
||||
pub const EPOCH_OFFSET: u64 = 4;
|
||||
pub const NUM_ATTESTATIONS: u64 = 1;
|
||||
|
||||
type E = MainnetEthSpec;
|
||||
|
||||
#[test]
|
||||
fn valid_block_ok() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let (block, mut state) = builder.build(None, None);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_block_header_state_slot() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let (mut block, mut state) = builder.build(None, None);
|
||||
|
||||
state.slot = Slot::new(133_713);
|
||||
block.message.slot = Slot::new(424_242);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::HeaderInvalid {
|
||||
reason: HeaderInvalid::StateSlotMismatch
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_parent_block_root() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let invalid_parent_root = Hash256::from([0xAA; 32]);
|
||||
let (block, mut state) = builder.build(None, Some(invalid_parent_root));
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::HeaderInvalid {
|
||||
reason: HeaderInvalid::ParentBlockRootMismatch {
|
||||
state: state.latest_block_header.canonical_root(),
|
||||
block: block.parent_root()
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_block_signature() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let (block, mut state) = builder.build(None, None);
|
||||
|
||||
// sign the block with a keypair that is not the expected proposer
|
||||
let keypair = Keypair::random();
|
||||
let block = block.message.sign(
|
||||
&keypair.sk,
|
||||
&state.fork,
|
||||
state.genesis_validators_root,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// process block with invalid block signature
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// should get a BadSignature error
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::HeaderInvalid {
|
||||
reason: HeaderInvalid::ProposalSignatureInvalid
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_randao_reveal_signature() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
|
||||
// sign randao reveal with random keypair
|
||||
let keypair = Keypair::random();
|
||||
let (block, mut state) = builder.build(Some(keypair.sk), None);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// should get a BadRandaoSignature error
|
||||
assert_eq!(result, Err(BlockProcessingError::RandaoSignatureInvalid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_4_deposits() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = DepositTestTask::Valid;
|
||||
|
||||
let (block, mut state) = builder.build_with_n_deposits(4, test_task, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting Ok because these are valid deposits.
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_deposit_deposit_count_too_big() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = DepositTestTask::Valid;
|
||||
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_deposits(NUM_DEPOSITS, test_task, None, None, &spec);
|
||||
|
||||
let big_deposit_count = NUM_DEPOSITS + 1;
|
||||
state.eth1_data.deposit_count = big_deposit_count;
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting DepositCountInvalid because we incremented the deposit_count
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::DepositCountInvalid {
|
||||
expected: big_deposit_count as usize,
|
||||
found: 1
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_deposit_count_too_small() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = DepositTestTask::Valid;
|
||||
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_deposits(NUM_DEPOSITS, test_task, None, None, &spec);
|
||||
|
||||
let small_deposit_count = NUM_DEPOSITS - 1;
|
||||
state.eth1_data.deposit_count = small_deposit_count;
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting DepositCountInvalid because we decremented the deposit_count
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::DepositCountInvalid {
|
||||
expected: small_deposit_count as usize,
|
||||
found: 1
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_deposit_bad_merkle_proof() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = DepositTestTask::Valid;
|
||||
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_deposits(NUM_DEPOSITS, test_task, None, None, &spec);
|
||||
|
||||
let bad_index = state.eth1_deposit_index as usize;
|
||||
|
||||
// Manually offsetting deposit count and index to trigger bad merkle proof
|
||||
state.eth1_data.deposit_count += 1;
|
||||
state.eth1_deposit_index += 1;
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting BadMerkleProof because the proofs were created with different indices
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::DepositInvalid {
|
||||
index: bad_index,
|
||||
reason: DepositInvalid::BadMerkleProof
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_deposit_wrong_pubkey() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = DepositTestTask::BadPubKey;
|
||||
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_deposits(NUM_DEPOSITS, test_task, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting Ok(()) even though the public key provided does not correspond to the correct public key
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_deposit_wrong_sig() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = DepositTestTask::BadSig;
|
||||
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_deposits(NUM_DEPOSITS, test_task, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting Ok(()) even though the block signature does not correspond to the correct public key
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_deposit_invalid_pub_key() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = DepositTestTask::InvalidPubKey;
|
||||
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_deposits(NUM_DEPOSITS, test_task, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting Ok(()) even though we passed in invalid publickeybytes in the public key field of the deposit data.
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_attestations() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttestationTestTask::Valid;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting Ok(()) because these are valid attestations
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_no_committee_for_index() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let slot = Epoch::new(EPOCH_OFFSET).start_slot(E::slots_per_epoch());
|
||||
let builder =
|
||||
get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT).insert_attestation(slot, 0, |_, _| true);
|
||||
let committee_index = builder.state.get_committee_count_at_slot(slot).unwrap();
|
||||
let (block, mut state) = builder
|
||||
.modify(|block| {
|
||||
block.body.attestations[0].data.index = committee_index;
|
||||
})
|
||||
.build(None, None);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting NoCommitee because we manually set the attestation's index to be invalid
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttestationInvalid {
|
||||
index: 0,
|
||||
reason: AttestationInvalid::BadCommitteeIndex
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_wrong_justified_checkpoint() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttestationTestTask::WrongJustifiedCheckpoint;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting WrongJustifiedCheckpoint because we manually set the
|
||||
// source field of the AttestationData object to be invalid
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttestationInvalid {
|
||||
index: 0,
|
||||
reason: AttestationInvalid::WrongJustifiedCheckpoint {
|
||||
state: Checkpoint {
|
||||
epoch: Epoch::from(2 as u64),
|
||||
root: Hash256::zero(),
|
||||
},
|
||||
attestation: Checkpoint {
|
||||
epoch: Epoch::from(0 as u64),
|
||||
root: Hash256::zero(),
|
||||
},
|
||||
is_current: true,
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_bad_indexed_attestation_bad_signature() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttestationTestTask::BadIndexedAttestationBadSignature;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting BadIndexedAttestation(BadSignature) because we ommitted the aggregation bits in the attestation
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttestationInvalid {
|
||||
index: 0,
|
||||
reason: AttestationInvalid::BadIndexedAttestation(
|
||||
IndexedAttestationInvalid::BadSignature
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_bad_aggregation_bitfield_len() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttestationTestTask::BadAggregationBitfieldLen;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting InvalidBitfield because the size of the aggregation_bitfield is bigger than the commitee size.
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::BeaconStateError(
|
||||
BeaconStateError::InvalidBitfield
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_bad_signature() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, 97); // minimal number of required validators for this test
|
||||
let test_task = AttestationTestTask::BadSignature;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting BadSignature because we're signing with invalid secret_keys
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttestationInvalid {
|
||||
index: 0,
|
||||
reason: AttestationInvalid::BadIndexedAttestation(
|
||||
IndexedAttestationInvalid::BadSignature
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_included_too_early() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttestationTestTask::IncludedTooEarly;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting IncludedTooEarly because the shard included in the crosslink is bigger than expected
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttestationInvalid {
|
||||
index: 0,
|
||||
reason: AttestationInvalid::IncludedTooEarly {
|
||||
state: state.slot,
|
||||
delay: spec.min_attestation_inclusion_delay,
|
||||
attestation: block.message.body.attestations[0].data.slot,
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_included_too_late() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
// note to maintainer: might need to increase validator count if we get NoCommittee
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttestationTestTask::IncludedTooLate;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttestationInvalid {
|
||||
index: 0,
|
||||
reason: AttestationInvalid::IncludedTooLate {
|
||||
state: state.slot,
|
||||
attestation: block.message.body.attestations[0].data.slot,
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attestation_target_epoch_slot_mismatch() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
// note to maintainer: might need to increase validator count if we get NoCommittee
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttestationTestTask::TargetEpochSlotMismatch;
|
||||
let (block, mut state) =
|
||||
builder.build_with_n_attestations(test_task, NUM_ATTESTATIONS, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
let attestation = &block.message.body.attestations[0].data;
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttestationInvalid {
|
||||
index: 0,
|
||||
reason: AttestationInvalid::TargetEpochSlotMismatch {
|
||||
target_epoch: attestation.target.epoch,
|
||||
slot_epoch: attestation.slot.epoch(E::slots_per_epoch()),
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_insert_attester_slashing() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttesterSlashingTestTask::Valid;
|
||||
let num_attester_slashings = 1;
|
||||
let (block, mut state) =
|
||||
builder.build_with_attester_slashing(test_task, num_attester_slashings, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting Ok(()) because attester slashing is valid
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attester_slashing_not_slashable() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttesterSlashingTestTask::NotSlashable;
|
||||
let num_attester_slashings = 1;
|
||||
let (block, mut state) =
|
||||
builder.build_with_attester_slashing(test_task, num_attester_slashings, None, None, &spec);
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting NotSlashable because the two attestations are the same
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::AttesterSlashingInvalid {
|
||||
index: 0,
|
||||
reason: AttesterSlashingInvalid::NotSlashable
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attester_slashing_1_invalid() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttesterSlashingTestTask::IndexedAttestation1Invalid;
|
||||
let num_attester_slashings = 1;
|
||||
let (block, mut state) =
|
||||
builder.build_with_attester_slashing(test_task, num_attester_slashings, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(
|
||||
BlockOperationError::Invalid(AttesterSlashingInvalid::IndexedAttestation1Invalid(
|
||||
BlockOperationError::Invalid(
|
||||
IndexedAttestationInvalid::BadValidatorIndicesOrdering(0)
|
||||
)
|
||||
))
|
||||
.into_with_index(0)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_attester_slashing_2_invalid() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = AttesterSlashingTestTask::IndexedAttestation2Invalid;
|
||||
let num_attester_slashings = 1;
|
||||
let (block, mut state) =
|
||||
builder.build_with_attester_slashing(test_task, num_attester_slashings, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(
|
||||
BlockOperationError::Invalid(AttesterSlashingInvalid::IndexedAttestation2Invalid(
|
||||
BlockOperationError::Invalid(
|
||||
IndexedAttestationInvalid::BadValidatorIndicesOrdering(0)
|
||||
)
|
||||
))
|
||||
.into_with_index(0)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_insert_proposer_slashing() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::Valid;
|
||||
let (block, mut state) = builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting Ok(()) because we inserted a valid proposer slashing
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_proposer_slashing_proposals_identical() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::ProposalsIdentical;
|
||||
let (block, mut state) = builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
// Expecting ProposalsIdentical because we the two headers are identical
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::ProposerSlashingInvalid {
|
||||
index: 0,
|
||||
reason: ProposerSlashingInvalid::ProposalsIdentical
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_proposer_slashing_proposer_unknown() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::ProposerUnknown;
|
||||
let (block, mut state) = builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting ProposerUnknown because validator_index is unknown
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::ProposerSlashingInvalid {
|
||||
index: 0,
|
||||
reason: ProposerSlashingInvalid::ProposerUnknown(3_141_592)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_proposer_slashing_not_slashable() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::ProposerNotSlashable;
|
||||
let (block, mut state) = builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
state.validators[0].slashed = true;
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting ProposerNotSlashable because we've already slashed the validator
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::ProposerSlashingInvalid {
|
||||
index: 0,
|
||||
reason: ProposerSlashingInvalid::ProposerNotSlashable(0)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_proposer_slashing_duplicate_slashing() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::Valid;
|
||||
let (mut block, mut state) =
|
||||
builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
let slashing = block.message.body.proposer_slashings[0].clone();
|
||||
let slashed_proposer = slashing.signed_header_1.message.proposer_index;
|
||||
block
|
||||
.message
|
||||
.body
|
||||
.proposer_slashings
|
||||
.push(slashing)
|
||||
.expect("should push slashing");
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::NoVerification,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting ProposerNotSlashable for the 2nd slashing because the validator has been
|
||||
// slashed by the 1st slashing.
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::ProposerSlashingInvalid {
|
||||
index: 1,
|
||||
reason: ProposerSlashingInvalid::ProposerNotSlashable(slashed_proposer)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_bad_proposal_1_signature() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::BadProposal1Signature;
|
||||
let (block, mut state) = builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting BadProposal1Signature because signature of proposal 1 is invalid
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::ProposerSlashingInvalid {
|
||||
index: 0,
|
||||
reason: ProposerSlashingInvalid::BadProposal1Signature
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_bad_proposal_2_signature() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::BadProposal2Signature;
|
||||
let (block, mut state) = builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting BadProposal2Signature because signature of proposal 2 is invalid
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::ProposerSlashingInvalid {
|
||||
index: 0,
|
||||
reason: ProposerSlashingInvalid::BadProposal2Signature
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_proposer_slashing_proposal_epoch_mismatch() {
|
||||
let spec = MainnetEthSpec::default_spec();
|
||||
let builder = get_builder(&spec, EPOCH_OFFSET, VALIDATOR_COUNT);
|
||||
let test_task = ProposerSlashingTestTask::ProposalEpochMismatch;
|
||||
let (block, mut state) = builder.build_with_proposer_slashing(test_task, 1, None, None, &spec);
|
||||
|
||||
let result = per_block_processing(
|
||||
&mut state,
|
||||
&block,
|
||||
None,
|
||||
BlockSignatureStrategy::VerifyIndividual,
|
||||
&spec,
|
||||
);
|
||||
|
||||
// Expecting ProposalEpochMismatch because the two epochs are different
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(BlockProcessingError::ProposerSlashingInvalid {
|
||||
index: 0,
|
||||
reason: ProposerSlashingInvalid::ProposalSlotMismatch(
|
||||
Slot::from(0 as u64),
|
||||
Slot::from(128 as u64)
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn get_builder(
|
||||
spec: &ChainSpec,
|
||||
epoch_offset: u64,
|
||||
num_validators: usize,
|
||||
) -> BlockProcessingBuilder<MainnetEthSpec> {
|
||||
// Set the state and block to be in the last slot of the `epoch_offset`th epoch.
|
||||
let last_slot_of_epoch = (MainnetEthSpec::genesis_epoch() + epoch_offset)
|
||||
.end_slot(MainnetEthSpec::slots_per_epoch());
|
||||
BlockProcessingBuilder::new(num_validators, last_slot_of_epoch, &spec).build_caches()
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
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;
|
||||
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`.
|
||||
///
|
||||
/// Optionally verifies the aggregate signature, depending on `verify_signatures`.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn verify_attestation_for_block_inclusion<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attestation: &Attestation<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<()> {
|
||||
let data = &attestation.data;
|
||||
|
||||
verify!(
|
||||
data.slot + spec.min_attestation_inclusion_delay <= state.slot,
|
||||
Invalid::IncludedTooEarly {
|
||||
state: state.slot,
|
||||
delay: spec.min_attestation_inclusion_delay,
|
||||
attestation: data.slot,
|
||||
}
|
||||
);
|
||||
verify!(
|
||||
state.slot <= data.slot + T::slots_per_epoch(),
|
||||
Invalid::IncludedTooLate {
|
||||
state: state.slot,
|
||||
attestation: data.slot,
|
||||
}
|
||||
);
|
||||
|
||||
verify_attestation_for_state(state, attestation, verify_signatures, spec)
|
||||
}
|
||||
|
||||
/// Returns `Ok(())` if `attestation` is a valid attestation to the chain that precedes the given
|
||||
/// `state`.
|
||||
///
|
||||
/// Returns a descriptive `Err` if the attestation is malformed or does not accurately reflect the
|
||||
/// prior blocks in `state`.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn verify_attestation_for_state<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attestation: &Attestation<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<()> {
|
||||
let data = &attestation.data;
|
||||
|
||||
// This emptiness check is required *in addition* to the length check in `get_attesting_indices`
|
||||
// because we can parse a bitfield and know its length, even if it has no bits set.
|
||||
verify!(
|
||||
!attestation.aggregation_bits.is_zero(),
|
||||
Invalid::AggregationBitfieldIsEmpty
|
||||
);
|
||||
|
||||
verify!(
|
||||
data.index < state.get_committee_count_at_slot(data.slot)?,
|
||||
Invalid::BadCommitteeIndex
|
||||
);
|
||||
|
||||
// Verify the Casper FFG vote.
|
||||
verify_casper_ffg_vote(attestation, state)?;
|
||||
|
||||
// Check signature and bitfields
|
||||
let committee = state.get_beacon_committee(attestation.data.slot, attestation.data.index)?;
|
||||
let indexed_attestation = get_indexed_attestation(committee.committee, attestation)?;
|
||||
is_valid_indexed_attestation(state, &indexed_attestation, verify_signatures, spec)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check target epoch and source checkpoint.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
fn verify_casper_ffg_vote<T: EthSpec>(
|
||||
attestation: &Attestation<T>,
|
||||
state: &BeaconState<T>,
|
||||
) -> Result<()> {
|
||||
let data = &attestation.data;
|
||||
verify!(
|
||||
data.target.epoch == data.slot.epoch(T::slots_per_epoch()),
|
||||
Invalid::TargetEpochSlotMismatch {
|
||||
target_epoch: data.target.epoch,
|
||||
slot_epoch: data.slot.epoch(T::slots_per_epoch()),
|
||||
}
|
||||
);
|
||||
if data.target.epoch == state.current_epoch() {
|
||||
verify!(
|
||||
data.source == state.current_justified_checkpoint,
|
||||
Invalid::WrongJustifiedCheckpoint {
|
||||
state: state.current_justified_checkpoint.clone(),
|
||||
attestation: data.source.clone(),
|
||||
is_current: true,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
} else if data.target.epoch == state.previous_epoch() {
|
||||
verify!(
|
||||
data.source == state.previous_justified_checkpoint,
|
||||
Invalid::WrongJustifiedCheckpoint {
|
||||
state: state.previous_justified_checkpoint.clone(),
|
||||
attestation: data.source.clone(),
|
||||
is_current: false,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(error(Invalid::BadTargetEpoch))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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.
|
||||
///
|
||||
/// Returns `Ok(())` if the `AttesterSlashing` is valid, otherwise indicates the reason for
|
||||
/// invalidity.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn verify_attester_slashing<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attester_slashing: &AttesterSlashing<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<()> {
|
||||
let attestation_1 = &attester_slashing.attestation_1;
|
||||
let attestation_2 = &attester_slashing.attestation_2;
|
||||
|
||||
// Spec: is_slashable_attestation_data
|
||||
verify!(
|
||||
attestation_1.is_double_vote(attestation_2)
|
||||
|| attestation_1.is_surround_vote(attestation_2),
|
||||
Invalid::NotSlashable
|
||||
);
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
/// For a given attester slashing, return the indices able to be slashed in ascending order.
|
||||
///
|
||||
/// Returns Ok(indices) if `indices.len() > 0`.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn get_slashable_indices<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attester_slashing: &AttesterSlashing<T>,
|
||||
) -> Result<Vec<u64>> {
|
||||
get_slashable_indices_modular(state, attester_slashing, |_, validator| {
|
||||
validator.is_slashable_at(state.current_epoch())
|
||||
})
|
||||
}
|
||||
|
||||
/// Same as `gather_attester_slashing_indices` but allows the caller to specify the criteria
|
||||
/// for determining whether a given validator should be considered slashable.
|
||||
pub fn get_slashable_indices_modular<F, T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
attester_slashing: &AttesterSlashing<T>,
|
||||
is_slashable: F,
|
||||
) -> Result<Vec<u64>>
|
||||
where
|
||||
F: Fn(u64, &Validator) -> bool,
|
||||
{
|
||||
let attestation_1 = &attester_slashing.attestation_1;
|
||||
let attestation_2 = &attester_slashing.attestation_2;
|
||||
|
||||
let attesting_indices_1 = attestation_1
|
||||
.attesting_indices
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
let attesting_indices_2 = attestation_2
|
||||
.attesting_indices
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
|
||||
let mut slashable_indices = vec![];
|
||||
|
||||
for index in &attesting_indices_1 & &attesting_indices_2 {
|
||||
let validator = state
|
||||
.validators
|
||||
.get(index as usize)
|
||||
.ok_or_else(|| error(Invalid::UnknownValidator(index)))?;
|
||||
|
||||
if is_slashable(index, validator) {
|
||||
slashable_indices.push(index);
|
||||
}
|
||||
}
|
||||
|
||||
verify!(!slashable_indices.is_empty(), Invalid::NoSlashableIndices);
|
||||
|
||||
Ok(slashable_indices)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
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 safe_arith::SafeArith;
|
||||
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.11.1
|
||||
pub fn verify_deposit_signature(deposit_data: &DepositData, spec: &ChainSpec) -> Result<()> {
|
||||
let deposit_signature_message = deposit_pubkey_signature_message(&deposit_data, spec)
|
||||
.ok_or_else(|| error(DepositInvalid::BadBlsBytes))?;
|
||||
|
||||
verify!(
|
||||
deposit_signature_set(&deposit_signature_message).is_valid(),
|
||||
DepositInvalid::BadSignature
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a `Some(validator index)` if a pubkey already exists in the `validators`,
|
||||
/// otherwise returns `None`.
|
||||
///
|
||||
/// ## Errors
|
||||
///
|
||||
/// Errors if the state's `pubkey_cache` is not current.
|
||||
pub fn get_existing_validator_index<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
pub_key: &PublicKeyBytes,
|
||||
) -> Result<Option<u64>> {
|
||||
let validator_index = state.get_validator_index(pub_key)?;
|
||||
Ok(validator_index.map(|idx| idx as u64))
|
||||
}
|
||||
|
||||
/// Verify that a deposit is included in the state's eth1 deposit root.
|
||||
///
|
||||
/// The deposit index is provided as a parameter so we can check proofs
|
||||
/// before they're due to be processed, and in parallel.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn verify_deposit_merkle_proof<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
deposit: &Deposit,
|
||||
deposit_index: u64,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<()> {
|
||||
let leaf = deposit.data.tree_hash_root();
|
||||
|
||||
verify!(
|
||||
verify_merkle_proof(
|
||||
leaf,
|
||||
&deposit.proof[..],
|
||||
spec.deposit_contract_tree_depth.safe_add(1)? as usize,
|
||||
deposit_index as usize,
|
||||
state.eth1_data.deposit_root,
|
||||
),
|
||||
DepositInvalid::BadMerkleProof
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use super::errors::{BlockOperationError, ExitInvalid};
|
||||
use crate::per_block_processing::{
|
||||
signature_sets::{exit_signature_set, get_pubkey_from_state},
|
||||
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.
|
||||
///
|
||||
/// Returns `Ok(())` if the `Exit` is valid, otherwise indicates the reason for invalidity.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn verify_exit<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
exit: &SignedVoluntaryExit,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> 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.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn verify_exit_time_independent_only<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
exit: &SignedVoluntaryExit,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> 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.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
fn verify_exit_parametric<T: EthSpec>(
|
||||
state: &BeaconState<T>,
|
||||
signed_exit: &SignedVoluntaryExit,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
time_independent_only: bool,
|
||||
) -> Result<()> {
|
||||
let exit = &signed_exit.message;
|
||||
|
||||
let validator = state
|
||||
.validators
|
||||
.get(exit.validator_index as usize)
|
||||
.ok_or_else(|| error(ExitInvalid::ValidatorUnknown(exit.validator_index)))?;
|
||||
|
||||
// Verify the validator is active.
|
||||
verify!(
|
||||
validator.is_active_at(state.current_epoch()),
|
||||
ExitInvalid::NotActive(exit.validator_index)
|
||||
);
|
||||
|
||||
// Verify that the validator has not yet exited.
|
||||
verify!(
|
||||
validator.exit_epoch == spec.far_future_epoch,
|
||||
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,
|
||||
ExitInvalid::FutureEpoch {
|
||||
state: state.current_epoch(),
|
||||
exit: exit.epoch
|
||||
}
|
||||
);
|
||||
|
||||
// Verify the validator has been active long enough.
|
||||
verify!(
|
||||
state.current_epoch() >= validator.activation_epoch + spec.persistent_committee_period,
|
||||
ExitInvalid::TooYoungToExit {
|
||||
current_epoch: state.current_epoch(),
|
||||
earliest_exit_epoch: validator.activation_epoch + spec.persistent_committee_period,
|
||||
}
|
||||
);
|
||||
|
||||
if verify_signatures.is_true() {
|
||||
verify!(
|
||||
exit_signature_set(
|
||||
state,
|
||||
|i| get_pubkey_from_state(state, i),
|
||||
signed_exit,
|
||||
spec
|
||||
)?
|
||||
.is_valid(),
|
||||
ExitInvalid::BadSignature
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
use super::errors::{BlockOperationError, ProposerSlashingInvalid as Invalid};
|
||||
use super::signature_sets::{get_pubkey_from_state, 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.
|
||||
///
|
||||
/// Returns `Ok(())` if the `ProposerSlashing` is valid, otherwise indicates the reason for invalidity.
|
||||
///
|
||||
/// Spec v0.11.1
|
||||
pub fn verify_proposer_slashing<T: EthSpec>(
|
||||
proposer_slashing: &ProposerSlashing,
|
||||
state: &BeaconState<T>,
|
||||
verify_signatures: VerifySignatures,
|
||||
spec: &ChainSpec,
|
||||
) -> Result<()> {
|
||||
let header_1 = &proposer_slashing.signed_header_1.message;
|
||||
let header_2 = &proposer_slashing.signed_header_2.message;
|
||||
|
||||
// Verify slots match
|
||||
verify!(
|
||||
header_1.slot == header_2.slot,
|
||||
Invalid::ProposalSlotMismatch(header_1.slot, header_2.slot)
|
||||
);
|
||||
|
||||
// Verify header proposer indices match
|
||||
verify!(
|
||||
header_1.proposer_index == header_2.proposer_index,
|
||||
Invalid::ProposerIndexMismatch(header_1.proposer_index, header_2.proposer_index)
|
||||
);
|
||||
|
||||
// But the headers are different
|
||||
verify!(header_1 != header_2, Invalid::ProposalsIdentical);
|
||||
|
||||
// Check proposer is slashable
|
||||
let proposer = state
|
||||
.validators
|
||||
.get(header_1.proposer_index as usize)
|
||||
.ok_or_else(|| error(Invalid::ProposerUnknown(header_1.proposer_index)))?;
|
||||
|
||||
verify!(
|
||||
proposer.is_slashable_at(state.current_epoch()),
|
||||
Invalid::ProposerNotSlashable(header_1.proposer_index)
|
||||
);
|
||||
|
||||
if verify_signatures.is_true() {
|
||||
let (signature_set_1, signature_set_2) = proposer_slashing_signature_set(
|
||||
state,
|
||||
|i| get_pubkey_from_state(state, i),
|
||||
proposer_slashing,
|
||||
spec,
|
||||
)?;
|
||||
verify!(signature_set_1.is_valid(), Invalid::BadProposal1Signature);
|
||||
verify!(signature_set_2.is_valid(), Invalid::BadProposal2Signature);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user