Initial work towards v0.2.0 (#924)

* Remove ping protocol

* Initial renaming of network services

* Correct rebasing relative to latest master

* Start updating types

* Adds HashMapDelay struct to utils

* Initial network restructure

* Network restructure. Adds new types for v0.2.0

* Removes build artefacts

* Shift validation to beacon chain

* Temporarily remove gossip validation

This is to be updated to match current optimisation efforts.

* Adds AggregateAndProof

* Begin rebuilding pubsub encoding/decoding

* Signature hacking

* Shift gossipsup decoding into eth2_libp2p

* Existing EF tests passing with fake_crypto

* Shifts block encoding/decoding into RPC

* Delete outdated API spec

* All release tests passing bar genesis state parsing

* Update and test YamlConfig

* Update to spec v0.10 compatible BLS

* Updates to BLS EF tests

* Add EF test for AggregateVerify

And delete unused hash2curve tests for uncompressed points

* Update EF tests to v0.10.1

* Use optional block root correctly in block proc

* Use genesis fork in deposit domain. All tests pass

* Fast aggregate verify test

* Update REST API docs

* Fix unused import

* Bump spec tags to v0.10.1

* Add `seconds_per_eth1_block` to chainspec

* Update to timestamp based eth1 voting scheme

* Return None from `get_votes_to_consider` if block cache is empty

* Handle overflows in `is_candidate_block`

* Revert to failing tests

* Fix eth1 data sets test

* Choose default vote according to spec

* Fix collect_valid_votes tests

* Fix `get_votes_to_consider` to choose all eligible blocks

* Uncomment winning_vote tests

* Add comments; remove unused code

* Reduce seconds_per_eth1_block for simulation

* Addressed review comments

* Add test for default vote case

* Fix logs

* Remove unused functions

* Meter default eth1 votes

* Fix comments

* Progress on attestation service

* Address review comments; remove unused dependency

* Initial work on removing libp2p lock

* Add LRU caches to store (rollup)

* Update attestation validation for DB changes (WIP)

* Initial version of should_forward_block

* Scaffold

* Progress on attestation validation

Also, consolidate prod+testing slot clocks so that they share much
of the same implementation and can both handle sub-slot time changes.

* Removes lock from libp2p service

* Completed network lock removal

* Finish(?) attestation processing

* Correct network termination future

* Add slot check to block check

* Correct fmt issues

* Remove Drop implementation for network service

* Add first attempt at attestation proc. re-write

* Add version 2 of attestation processing

* Minor fixes

* Add validator pubkey cache

* Make get_indexed_attestation take a committee

* Link signature processing into new attn verification

* First working version

* Ensure pubkey cache is updated

* Add more metrics, slight optimizations

* Clone committee cache during attestation processing

* Update shuffling cache during block processing

* Remove old commented-out code

* Fix shuffling cache insert bug

* Used indexed attestation in fork choice

* Restructure attn processing, add metrics

* Add more detailed metrics

* Tidy, fix failing tests

* Fix failing tests, tidy

* Address reviewers suggestions

* Disable/delete two outdated tests

* Modification of validator for subscriptions

* Add slot signing to validator client

* Further progress on validation subscription

* Adds necessary validator subscription functionality

* Add new Pubkeys struct to signature_sets

* Refactor with functional approach

* Update beacon chain

* Clean up validator <-> beacon node http types

* Add aggregator status to ValidatorDuty

* Impl Clone for manual slot clock

* Fix minor errors

* Further progress validator client subscription

* Initial subscription and aggregation handling

* Remove decompressed member from pubkey bytes

* Progress to modifying val client for attestation aggregation

* First draft of validator client upgrade for aggregate attestations

* Add hashmap for indices lookup

* Add state cache, remove store cache

* Only build the head committee cache

* Removes lock on a network channel

* Partially implement beacon node subscription http api

* Correct compilation issues

* Change `get_attesting_indices` to use Vec

* Fix failing test

* Partial implementation of timer

* Adds timer, removes exit_future, http api to op pool

* Partial multiple aggregate attestation handling

* Permits bulk messages accross gossipsub network channel

* Correct compile issues

* Improve gosispsub messaging and correct rest api helpers

* Added global gossipsub subscriptions

* Update validator subscriptions data structs

* Tidy

* Re-structure validator subscriptions

* Initial handling of subscriptions

* Re-structure network service

* Add pubkey cache persistence file

* Add more comments

* Integrate persistence file into builder

* Add pubkey cache tests

* Add HashSetDelay and introduce into attestation service

* Handles validator subscriptions

* Add data_dir to beacon chain builder

* Remove Option in pubkey cache persistence file

* Ensure consistency between datadir/data_dir

* Fix failing network test

* Peer subnet discovery gets queued for future subscriptions

* Reorganise attestation service functions

* Initial wiring of attestation service

* First draft of attestation service timing logic

* Correct minor typos

* Tidy

* Fix todos

* Improve tests

* Add PeerInfo to connected peers mapping

* Fix compile error

* Fix compile error from merge

* Split up block processing metrics

* Tidy

* Refactor get_pubkey_from_state

* Remove commented-out code

* Rename state_cache -> checkpoint_cache

* Rename Checkpoint -> Snapshot

* Tidy, add comments

* Tidy up find_head function

* Change some checkpoint -> snapshot

* Add tests

* Expose max_len

* Remove dead code

* Tidy

* Fix bug

* Add sync-speed metric

* Add first attempt at VerifiableBlock

* Start integrating into beacon chain

* Integrate VerifiableBlock

* Rename VerifableBlock -> PartialBlockVerification

* Add start of typed methods

* Add progress

* Add further progress

* Rename structs

* Add full block verification to block_processing.rs

* Further beacon chain integration

* Update checks for gossip

* Add todo

* Start adding segement verification

* Add passing chain segement test

* Initial integration with batch sync

* Minor changes

* Tidy, add more error checking

* Start adding chain_segment tests

* Finish invalid signature tests

* Include single and gossip verified blocks in tests

* Add gossip verification tests

* Start adding docs

* Finish adding comments to block_processing.rs

* Rename block_processing.rs -> block_verification

* Start removing old block processing code

* Fixes beacon_chain compilation

* Fix project-wide compile errors

* Remove old code

* Correct code to pass all tests

* Fix bug with beacon proposer index

* Fix shim for BlockProcessingError

* Only process one epoch at a time

* Fix loop in chain segment processing

* Correct tests from master merge

* Add caching for state.eth1_data_votes

* Add BeaconChain::validator_pubkey

* Revert "Add caching for state.eth1_data_votes"

This reverts commit cd73dcd643.

Co-authored-by: Grant Wuerker <gwuerker@gmail.com>
Co-authored-by: Michael Sproul <michael@sigmaprime.io>
Co-authored-by: Michael Sproul <micsproul@gmail.com>
Co-authored-by: pawan <pawandhananjay@gmail.com>
Co-authored-by: Paul Hauner <paul@paulhauner.com>
This commit is contained in:
Age Manning
2020-03-17 17:24:44 +11:00
committed by GitHub
parent c198bddf9e
commit 95c8e476bc
161 changed files with 9771 additions and 5266 deletions

View File

@@ -1,4 +1,3 @@
use std::collections::BTreeSet;
use types::*;
/// Returns validator indices which participated in the attestation, sorted by increasing index.
@@ -7,17 +6,20 @@ use types::*;
pub fn get_attesting_indices<T: EthSpec>(
committee: &[usize],
bitlist: &BitList<T::MaxValidatorsPerCommittee>,
) -> Result<BTreeSet<usize>, BeaconStateError> {
) -> Result<Vec<usize>, BeaconStateError> {
if bitlist.len() != committee.len() {
return Err(BeaconStateError::InvalidBitfield);
}
Ok(committee
.iter()
.enumerate()
.filter_map(|(i, validator_index)| match bitlist.get(i) {
Ok(true) => Some(*validator_index),
_ => None,
})
.collect())
let mut indices = Vec::with_capacity(bitlist.num_set_bits());
for (i, validator_index) in committee.iter().enumerate() {
if let Ok(true) = bitlist.get(i) {
indices.push(*validator_index)
}
}
indices.sort_unstable();
Ok(indices)
}

View File

@@ -10,7 +10,7 @@ pub fn initiate_validator_exit<T: EthSpec>(
spec: &ChainSpec,
) -> Result<(), Error> {
if index >= state.validators.len() {
return Err(Error::UnknownValidator);
return Err(Error::UnknownValidator(index as u64));
}
// Return if the validator already initiated exit

View File

@@ -12,7 +12,7 @@ pub fn slash_validator<T: EthSpec>(
spec: &ChainSpec,
) -> Result<(), Error> {
if slashed_index >= state.validators.len() || slashed_index >= state.balances.len() {
return Err(BeaconStateError::UnknownValidator);
return Err(BeaconStateError::UnknownValidator(slashed_index as u64));
}
let epoch = state.current_epoch();

View File

@@ -10,8 +10,8 @@ pub mod test_utils;
pub use genesis::{initialize_beacon_state_from_eth1, is_valid_genesis_state, process_activations};
pub use per_block_processing::{
errors::BlockProcessingError, per_block_processing, signature_sets, BlockSignatureStrategy,
VerifySignatures,
block_signature_verifier, errors::BlockProcessingError, per_block_processing, signature_sets,
BlockSignatureStrategy, BlockSignatureVerifier, VerifySignatures,
};
pub use per_epoch_processing::{errors::EpochProcessingError, per_epoch_processing};
pub use per_slot_processing::{per_slot_processing, Error as SlotProcessingError};

View File

@@ -1,7 +1,7 @@
use crate::common::{initiate_validator_exit, slash_validator};
use errors::{BlockOperationError, BlockProcessingError, HeaderInvalid, IntoWithIndex};
use rayon::prelude::*;
use signature_sets::{block_proposal_signature_set, randao_signature_set};
use signature_sets::{block_proposal_signature_set, get_pubkey_from_state, randao_signature_set};
use std::convert::TryInto;
use tree_hash::TreeHash;
use types::*;
@@ -21,7 +21,7 @@ pub use verify_deposit::{
pub use verify_exit::{verify_exit, verify_exit_time_independent_only};
pub mod block_processing_builder;
mod block_signature_verifier;
pub mod block_signature_verifier;
pub mod errors;
mod is_valid_indexed_attestation;
pub mod signature_sets;
@@ -83,8 +83,14 @@ pub fn per_block_processing<T: EthSpec>(
BlockSignatureStrategy::VerifyBulk => {
// Verify all signatures in the block at once.
block_verify!(
BlockSignatureVerifier::verify_entire_block(state, signed_block, block_root, spec)
.is_ok(),
BlockSignatureVerifier::verify_entire_block(
state,
|i| get_pubkey_from_state(state, i),
signed_block,
block_root,
spec
)
.is_ok(),
BlockProcessingError::BulkSignatureVerificationFailed
);
VerifySignatures::False
@@ -176,7 +182,14 @@ pub fn verify_block_signature<T: EthSpec>(
spec: &ChainSpec,
) -> Result<(), BlockOperationError<HeaderInvalid>> {
verify!(
block_proposal_signature_set(state, block, block_root, spec)?.is_valid(),
block_proposal_signature_set(
state,
|i| get_pubkey_from_state(state, i),
block,
block_root,
spec
)?
.is_valid(),
HeaderInvalid::ProposalSignatureInvalid
);
@@ -196,7 +209,8 @@ pub fn process_randao<T: EthSpec>(
if verify_signatures.is_true() {
// Verify RANDAO reveal signature.
block_verify!(
randao_signature_set(state, block, spec)?.is_valid(),
randao_signature_set(state, |i| get_pubkey_from_state(state, i), block, spec)?
.is_valid(),
BlockProcessingError::RandaoSignatureInvalid
);
}

View File

@@ -1,14 +1,16 @@
use super::signature_sets::{Error as SignatureSetError, Result as SignatureSetResult, *};
use crate::common::get_indexed_attestation;
use crate::per_block_processing::errors::{AttestationInvalid, BlockOperationError};
use bls::{verify_signature_sets, SignatureSet};
use rayon::prelude::*;
use std::borrow::Cow;
use types::{
BeaconState, BeaconStateError, ChainSpec, EthSpec, Hash256, IndexedAttestation,
SignedBeaconBlock,
};
pub use bls::G1Point;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, PartialEq)]
@@ -46,23 +48,27 @@ impl From<BlockOperationError<AttestationInvalid>> for Error {
///
/// This allows for optimizations related to batch BLS operations (see the
/// `Self::verify_entire_block(..)` function).
pub struct BlockSignatureVerifier<'a, T: EthSpec> {
block: &'a SignedBeaconBlock<T>,
pub struct BlockSignatureVerifier<'a, T, F>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>> + Clone,
{
get_pubkey: Box<F>,
state: &'a BeaconState<T>,
spec: &'a ChainSpec,
sets: Vec<SignatureSet<'a>>,
}
impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
impl<'a, T, F> BlockSignatureVerifier<'a, T, F>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>> + 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>,
block: &'a SignedBeaconBlock<T>,
spec: &'a ChainSpec,
) -> Self {
pub fn new(state: &'a BeaconState<T>, get_pubkey: F, spec: &'a ChainSpec) -> Self {
Self {
block,
get_pubkey: Box::new(get_pubkey),
state,
spec,
sets: vec![],
@@ -78,22 +84,13 @@ impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
/// 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, block, spec);
verifier.include_block_proposal(block_root)?;
verifier.include_randao_reveal()?;
verifier.include_proposer_slashings()?;
verifier.include_attester_slashings()?;
verifier.include_attestations()?;
/*
* Deposits are not included because they can legally have invalid signatures.
*/
verifier.include_exits()?;
let mut verifier = Self::new(state, get_pubkey, spec);
verifier.include_all_signatures(block, block_root)?;
verifier.verify()
}
@@ -127,31 +124,82 @@ impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
}
}
/// 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.
fn include_block_proposal(&mut self, block_root: Option<Hash256>) -> Result<()> {
let set = block_proposal_signature_set(self.state, self.block, block_root, self.spec)?;
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.
fn include_randao_reveal(&mut self) -> Result<()> {
let set = randao_signature_set(self.state, &self.block.message, self.spec)?;
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.
fn include_proposer_slashings(&mut self) -> Result<()> {
let mut sets: Vec<SignatureSet> = self
.block
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, proposer_slashing, self.spec)?;
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>>>>()?
@@ -164,15 +212,19 @@ impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
}
/// Includes all signatures in `self.block.body.attester_slashings` for verification.
fn include_attester_slashings(&mut self) -> Result<()> {
self.block
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, attester_slashing, &self.spec)?;
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);
@@ -182,8 +234,11 @@ impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
}
/// Includes all signatures in `self.block.body.attestations` for verification.
fn include_attestations(&mut self) -> Result<Vec<IndexedAttestation<T>>> {
self.block
pub fn include_attestations(
&mut self,
block: &'a SignedBeaconBlock<T>,
) -> Result<Vec<IndexedAttestation<T>>> {
block
.message
.body
.attestations
@@ -197,6 +252,7 @@ impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
self.sets.push(indexed_attestation_signature_set(
&self.state,
self.get_pubkey.clone(),
&attestation.signature,
&indexed_attestation,
&self.spec,
@@ -209,14 +265,13 @@ impl<'a, T: EthSpec> BlockSignatureVerifier<'a, T> {
}
/// Includes all signatures in `self.block.body.voluntary_exits` for verification.
fn include_exits(&mut self) -> Result<()> {
let mut sets = self
.block
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, exit, &self.spec))
.map(|exit| exit_signature_set(&self.state, self.get_pubkey.clone(), exit, &self.spec))
.collect::<SignatureSetResult<_>>()?;
self.sets.append(&mut sets);

View File

@@ -235,6 +235,8 @@ pub enum AttestationInvalid {
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.

View File

@@ -1,5 +1,5 @@
use super::errors::{BlockOperationError, IndexedAttestationInvalid as Invalid};
use super::signature_sets::indexed_attestation_signature_set;
use super::signature_sets::{get_pubkey_from_state, indexed_attestation_signature_set};
use crate::VerifySignatures;
use types::*;
@@ -43,6 +43,7 @@ pub fn is_valid_indexed_attestation<T: EthSpec>(
verify!(
indexed_attestation_signature_set(
state,
|i| get_pubkey_from_state(state, i),
&indexed_attestation.signature,
&indexed_attestation,
spec

View File

@@ -3,6 +3,7 @@
//!
//! This module exposes one function to extract each type of `SignatureSet` from a `BeaconBlock`.
use bls::{G1Point, G1Ref, SignatureSet, SignedMessage};
use ssz::DecodeError;
use std::borrow::Cow;
use std::convert::TryInto;
use tree_hash::TreeHash;
@@ -18,7 +19,7 @@ pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, PartialEq, Clone)]
pub enum Error {
/// Signature verification failed. The block is invalid.
SignatureInvalid,
SignatureInvalid(DecodeError),
/// There was an error attempting to read from a `BeaconState`. Block
/// validity was not determined.
BeaconStateError(BeaconStateError),
@@ -39,13 +40,36 @@ impl From<BeaconStateError> for Error {
}
}
/// A signature set that is valid if a block was signed by the expected block producer.
pub fn block_proposal_signature_set<'a, T: EthSpec>(
/// 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, G1Point>>
where
T: EthSpec,
{
state
.validators
.get(validator_index)
.and_then(|v| {
let pk: Option<PublicKey> = (&v.pubkey).try_into().ok();
pk
})
.map(|pk| Cow::Owned(pk.into_point()))
}
/// 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<'a>> {
) -> Result<SignatureSet<'a>>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>>,
{
let block = &signed_block.message;
let proposer_index = state.get_beacon_proposer_index(block.slot, spec)?;
@@ -67,17 +91,22 @@ pub fn block_proposal_signature_set<'a, T: EthSpec>(
Ok(SignatureSet::single(
&signed_block.signature,
validator_pubkey(state, proposer_index)?,
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: EthSpec>(
pub fn randao_signature_set<'a, T, F>(
state: &'a BeaconState<T>,
get_pubkey: F,
block: &'a BeaconBlock<T>,
spec: &'a ChainSpec,
) -> Result<SignatureSet<'a>> {
) -> Result<SignatureSet<'a>>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>>,
{
let proposer_index = state.get_beacon_proposer_index(block.slot, spec)?;
let domain = spec.get_domain(
@@ -86,34 +115,41 @@ pub fn randao_signature_set<'a, T: EthSpec>(
&state.fork,
);
let message = state.current_epoch().signing_root(domain);
let message = block.slot.epoch(T::slots_per_epoch()).signing_root(domain);
Ok(SignatureSet::single(
&block.body.randao_reveal,
validator_pubkey(state, proposer_index)?,
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: EthSpec>(
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<'a>, SignatureSet<'a>)> {
) -> Result<(SignatureSet<'a>, SignatureSet<'a>)>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>>,
{
let proposer_index = proposer_slashing.proposer_index as usize;
Ok((
block_header_signature_set(
state,
&proposer_slashing.signed_header_1,
validator_pubkey(state, proposer_index)?,
get_pubkey(proposer_index)
.ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
spec,
)?,
block_header_signature_set(
state,
&proposer_slashing.signed_header_2,
validator_pubkey(state, proposer_index)?,
get_pubkey(proposer_index)
.ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
spec,
)?,
))
@@ -146,16 +182,24 @@ fn block_header_signature_set<'a, T: EthSpec>(
}
/// Returns the signature set for the given `indexed_attestation`.
pub fn indexed_attestation_signature_set<'a, 'b, T: EthSpec>(
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<'a>> {
) -> Result<SignatureSet<'a>>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>>,
{
let pubkeys = indexed_attestation
.attesting_indices
.into_iter()
.map(|&validator_idx| Ok(validator_pubkey(state, validator_idx as usize)?))
.map(|&validator_idx| {
Ok(get_pubkey(validator_idx as usize)
.ok_or_else(|| Error::ValidatorUnknown(validator_idx))?)
})
.collect::<Result<_>>()?;
let domain = spec.get_domain(
@@ -172,17 +216,25 @@ pub fn indexed_attestation_signature_set<'a, 'b, T: EthSpec>(
/// 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: EthSpec>(
pubkeys: Vec<&'a PublicKey>,
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,
spec: &'a ChainSpec,
) -> Result<SignatureSet<'a>> {
let pubkeys = pubkeys
) -> Result<SignatureSet<'a>>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>>,
{
let pubkeys = indexed_attestation
.attesting_indices
.into_iter()
.map(|pubkey| Cow::Borrowed(&pubkey.as_raw().point))
.collect();
.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,
@@ -197,20 +249,27 @@ pub fn indexed_attestation_signature_set_from_pubkeys<'a, 'b, T: EthSpec>(
}
/// Returns the signature set for the given `attester_slashing` and corresponding `pubkeys`.
pub fn attester_slashing_signature_sets<'a, T: EthSpec>(
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<'a>, SignatureSet<'a>)> {
) -> Result<(SignatureSet<'a>, SignatureSet<'a>)>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>> + 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,
@@ -250,11 +309,16 @@ pub fn deposit_signature_set<'a>(
/// Returns a signature set that is valid if the `SignedVoluntaryExit` was signed by the indicated
/// validator.
pub fn exit_signature_set<'a, T: EthSpec>(
pub fn exit_signature_set<'a, T, F>(
state: &'a BeaconState<T>,
get_pubkey: F,
signed_exit: &'a SignedVoluntaryExit,
spec: &'a ChainSpec,
) -> Result<SignatureSet<'a>> {
) -> Result<SignatureSet<'a>>
where
T: EthSpec,
F: Fn(usize) -> Option<Cow<'a, G1Point>>,
{
let exit = &signed_exit.message;
let proposer_index = exit.validator_index as usize;
@@ -264,30 +328,7 @@ pub fn exit_signature_set<'a, T: EthSpec>(
Ok(SignatureSet::single(
&signed_exit.signature,
validator_pubkey(state, proposer_index)?,
get_pubkey(proposer_index).ok_or_else(|| Error::ValidatorUnknown(proposer_index as u64))?,
message,
))
}
/// Maps a validator index to a `PublicKey`.
pub fn validator_pubkey<'a, T: EthSpec>(
state: &'a BeaconState<T>,
validator_index: usize,
) -> Result<Cow<'a, G1Point>> {
let pubkey_bytes = &state
.validators
.get(validator_index)
.ok_or_else(|| Error::ValidatorUnknown(validator_index as u64))?
.pubkey;
if let Some(pubkey) = pubkey_bytes.decompressed() {
Ok(Cow::Borrowed(&pubkey.as_raw().point))
} else {
pubkey_bytes
.try_into()
.map(|pubkey: PublicKey| Cow::Owned(pubkey.as_raw().point.clone()))
.map_err(|_| Error::BadBlsBytes {
validator_index: validator_index as u64,
})
}
}

View File

@@ -1,5 +1,8 @@
use super::errors::{BlockOperationError, ExitInvalid};
use crate::per_block_processing::{signature_sets::exit_signature_set, VerifySignatures};
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>>;
@@ -84,7 +87,13 @@ fn verify_exit_parametric<T: EthSpec>(
if verify_signatures.is_true() {
verify!(
exit_signature_set(state, signed_exit, spec)?.is_valid(),
exit_signature_set(
state,
|i| get_pubkey_from_state(state, i),
signed_exit,
spec
)?
.is_valid(),
ExitInvalid::BadSignature
);
}

View File

@@ -1,5 +1,5 @@
use super::errors::{BlockOperationError, ProposerSlashingInvalid as Invalid};
use super::signature_sets::proposer_slashing_signature_set;
use super::signature_sets::{get_pubkey_from_state, proposer_slashing_signature_set};
use crate::VerifySignatures;
use types::*;
@@ -49,8 +49,12 @@ pub fn verify_proposer_slashing<T: EthSpec>(
);
if verify_signatures.is_true() {
let (signature_set_1, signature_set_2) =
proposer_slashing_signature_set(state, proposer_slashing, spec)?;
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);
}