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

@@ -0,0 +1,80 @@
use super::{Attestation, Domain, EthSpec, Fork, PublicKey, SecretKey, Signature, SignedRoot};
use crate::test_utils::TestRandom;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// A Validators aggregate attestation and selection proof.
///
/// Spec v0.10.1
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode, TestRandom, TreeHash)]
#[serde(bound = "T: EthSpec")]
pub struct AggregateAndProof<T: EthSpec> {
/// The index of the validator that created the attestation.
pub aggregator_index: u64,
/// The aggregate attestation.
pub aggregate: Attestation<T>,
/// A proof provided by the validator that permits them to publish on the
/// `beacon_aggregate_and_proof` gossipsub topic.
pub selection_proof: Signature,
}
impl<T: EthSpec> AggregateAndProof<T> {
pub fn is_valid_selection_proof(&self, validator_pubkey: &PublicKey, fork: &Fork) -> bool {
let target_epoch = self.aggregate.data.slot.epoch(T::slots_per_epoch());
let domain = T::default_spec().get_domain(target_epoch, Domain::SelectionProof, fork);
let message = self.aggregate.data.slot.signing_root(domain);
self.selection_proof
.verify(message.as_bytes(), validator_pubkey)
}
/// Converts Self into a SignedAggregateAndProof.
pub fn into_signed(self, secret_key: &SecretKey, fork: &Fork) -> SignedAggregateAndProof<T> {
let target_epoch = self.aggregate.data.slot.epoch(T::slots_per_epoch());
let domain = T::default_spec().get_domain(target_epoch, Domain::AggregateAndProof, fork);
let sign_message = self.signing_root(domain);
let signature = Signature::new(sign_message.as_bytes(), &secret_key);
SignedAggregateAndProof {
message: self,
signature,
}
}
}
impl<T: EthSpec> SignedRoot for AggregateAndProof<T> {}
/// A Validators signed aggregate proof to publish on the `beacon_aggregate_and_proof`
/// gossipsub topic.
///
/// Spec v0.10.1
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode, TestRandom, TreeHash)]
#[serde(bound = "T: EthSpec")]
pub struct SignedAggregateAndProof<T: EthSpec> {
/// The `AggregateAndProof` that was signed.
pub message: AggregateAndProof<T>,
/// The aggregate attestation.
pub signature: Signature,
}
impl<T: EthSpec> SignedRoot for SignedAggregateAndProof<T> {}
impl<T: EthSpec> SignedAggregateAndProof<T> {
/// Verifies the signature of the `AggregateAndProof`
pub fn is_valid_signature(&self, validator_pubkey: &PublicKey, fork: &Fork) -> bool {
let target_epoch = self.message.aggregate.data.slot.epoch(T::slots_per_epoch());
let domain = T::default_spec().get_domain(target_epoch, Domain::AggregateAndProof, fork);
let message = self.signing_root(domain);
self.signature.verify(message.as_bytes(), validator_pubkey)
}
/// Verifies the signature of the `AggregateAndProof` as well the underlying selection_proof in
/// the contained `AggregateAndProof`.
pub fn is_valid(&self, validator_pubkey: &PublicKey, fork: &Fork) -> bool {
self.is_valid_signature(validator_pubkey, fork)
&& self
.message
.is_valid_selection_proof(validator_pubkey, fork)
}
}

View File

@@ -1,6 +1,6 @@
use super::{
AggregateSignature, AttestationData, BitList, ChainSpec, Domain, EthSpec, Fork, SecretKey,
Signature, SignedRoot,
Signature, SignedRoot, SubnetId,
};
use crate::test_utils::TestRandom;
@@ -75,6 +75,14 @@ impl<T: EthSpec> Attestation<T> {
Ok(())
}
}
/// Returns the subnet id associated with the attestation.
///
/// Note, this will return the subnet id for an aggregated attestation. This is done
/// to avoid checking aggregate bits every time we wish to get an id.
pub fn subnet_id(&self) -> SubnetId {
SubnetId::new(self.data.index % T::default_spec().attestation_subnet_count)
}
}
#[cfg(test)]

View File

@@ -11,6 +11,7 @@ use serde_derive::{Deserialize, Serialize};
use ssz::ssz_encode;
use ssz_derive::{Decode, Encode};
use ssz_types::{typenum::Unsigned, BitVector, FixedVector};
use std::convert::TryInto;
use swap_or_not_shuffle::compute_shuffled_index;
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
@@ -36,7 +37,7 @@ const MAX_RANDOM_BYTE: u64 = (1 << 8) - 1;
pub enum Error {
EpochOutOfBounds,
SlotOutOfBounds,
UnknownValidator,
UnknownValidator(u64),
UnableToDetermineProducer,
InvalidBitfield,
ValidatorIsWithdrawable,
@@ -332,6 +333,7 @@ impl<T: EthSpec> BeaconState<T> {
///
/// Spec v0.10.1
pub fn get_active_validator_indices(&self, epoch: Epoch) -> Vec<usize> {
// FIXME(sproul): put a bounds check on here based on the maximum lookahead
get_active_validator_indices(&self.validators, epoch)
}
@@ -427,6 +429,30 @@ impl<T: EthSpec> BeaconState<T> {
}
}
/// Return `true` if the validator who produced `slot_signature` is eligible to aggregate.
///
/// Spec v0.10.1
pub fn is_aggregator(
&self,
slot: Slot,
index: CommitteeIndex,
slot_signature: &Signature,
spec: &ChainSpec,
) -> Result<bool, Error> {
let committee = self.get_beacon_committee(slot, index)?;
let modulo = std::cmp::max(
1,
committee.committee.len() as u64 / spec.target_aggregators_per_committee,
);
let signature_hash = hash(&slot_signature.as_bytes());
let signature_hash_int = u64::from_le_bytes(
signature_hash[0..8]
.try_into()
.expect("first 8 bytes of signature should always convert to fixed array"),
);
Ok(signature_hash_int % modulo == 0)
}
/// Returns the beacon proposer index for the `slot` in the given `relative_epoch`.
///
/// Spec v0.10.1
@@ -710,7 +736,7 @@ impl<T: EthSpec> BeaconState<T> {
self.validators
.get(validator_index)
.map(|v| v.effective_balance)
.ok_or_else(|| Error::UnknownValidator)
.ok_or_else(|| Error::UnknownValidator(validator_index as u64))
}
/// Return the epoch at which an activation or exit triggered in ``epoch`` takes effect.
@@ -734,7 +760,7 @@ impl<T: EthSpec> BeaconState<T> {
))
}
/// Returns the `slot`, `index` and `committee_position` for which a validator must produce an
/// Returns the `slot`, `index`, `committee_position` and `committee_len` for which a validator must produce an
/// attestation.
///
/// Note: Utilizes the cache and will fail if the appropriate cache is not initialized.
@@ -770,7 +796,6 @@ impl<T: EthSpec> BeaconState<T> {
self.update_pubkey_cache()?;
self.build_tree_hash_cache()?;
self.exit_cache.build(&self.validators, spec)?;
self.decompress_validator_pubkeys()?;
Ok(())
}
@@ -938,23 +963,6 @@ impl<T: EthSpec> BeaconState<T> {
self.tree_hash_cache = None;
}
/// Iterate through all validators and decompress their public key, unless it has already been
/// decompressed.
///
/// Does not check the validity of already decompressed keys.
pub fn decompress_validator_pubkeys(&mut self) -> Result<(), Error> {
self.validators.iter_mut().try_for_each(|validator| {
if validator.pubkey.decompressed().is_none() {
validator
.pubkey
.decompress()
.map_err(Error::InvalidValidatorPubkey)
} else {
Ok(())
}
})
}
/// Clone the state whilst preserving only the selected caches.
pub fn clone_with(&self, config: CloneConfig) -> Self {
BeaconState {

View File

@@ -17,6 +17,8 @@ pub enum Domain {
Randao,
Deposit,
VoluntaryExit,
SelectionProof,
AggregateAndProof,
}
/// Holds all the "constants" for a BeaconChain.
@@ -93,6 +95,8 @@ pub struct ChainSpec {
domain_randao: u32,
domain_deposit: u32,
domain_voluntary_exit: u32,
domain_selection_proof: u32,
domain_aggregate_and_proof: u32,
/*
* Fork choice
@@ -105,8 +109,17 @@ pub struct ChainSpec {
pub eth1_follow_distance: u64,
pub seconds_per_eth1_block: u64,
/*
* Networking
*/
pub boot_nodes: Vec<String>,
pub network_id: u8,
pub attestation_propagation_slot_range: u64,
pub maximum_gossip_clock_disparity_millis: u64,
pub target_aggregators_per_committee: u64,
pub attestation_subnet_count: u64,
pub random_subnets_per_validator: u64,
pub epochs_per_random_subnet_subscription: u64,
}
impl ChainSpec {
@@ -120,6 +133,8 @@ impl ChainSpec {
Domain::Randao => self.domain_randao,
Domain::Deposit => self.domain_deposit,
Domain::VoluntaryExit => self.domain_voluntary_exit,
Domain::SelectionProof => self.domain_selection_proof,
Domain::AggregateAndProof => self.domain_aggregate_and_proof,
}
}
@@ -223,6 +238,8 @@ impl ChainSpec {
domain_randao: 2,
domain_deposit: 3,
domain_voluntary_exit: 4,
domain_selection_proof: 5,
domain_aggregate_and_proof: 6,
/*
* Fork choice
@@ -240,6 +257,12 @@ impl ChainSpec {
*/
boot_nodes: vec![],
network_id: 1, // mainnet network id
attestation_propagation_slot_range: 32,
attestation_subnet_count: 64,
random_subnets_per_validator: 1,
maximum_gossip_clock_disparity_millis: 500,
target_aggregators_per_committee: 16,
epochs_per_random_subnet_subscription: 256,
}
}

View File

@@ -12,6 +12,7 @@ pub trait EthSpec: 'static + Default + Sync + Send + Clone + Debug + PartialEq {
*/
type GenesisEpoch: Unsigned + Clone + Sync + Send + Debug + PartialEq;
type JustificationBitsLength: Unsigned + Clone + Sync + Send + Debug + PartialEq + Default;
type SubnetBitfieldLength: Unsigned + Clone + Sync + Send + Debug + PartialEq + Default;
/*
* Misc
*/
@@ -125,6 +126,7 @@ pub struct MainnetEthSpec;
impl EthSpec for MainnetEthSpec {
type JustificationBitsLength = U4;
type SubnetBitfieldLength = U64;
type MaxValidatorsPerCommittee = U2048;
type GenesisEpoch = U0;
type SlotsPerEpoch = U32;
@@ -164,6 +166,7 @@ impl EthSpec for MinimalEthSpec {
params_from_eth_spec!(MainnetEthSpec {
JustificationBitsLength,
SubnetBitfieldLength,
MaxValidatorsPerCommittee,
GenesisEpoch,
HistoricalRootsLimit,
@@ -196,6 +199,7 @@ impl EthSpec for InteropEthSpec {
params_from_eth_spec!(MainnetEthSpec {
JustificationBitsLength,
SubnetBitfieldLength,
MaxValidatorsPerCommittee,
GenesisEpoch,
HistoricalRootsLimit,

View File

@@ -6,6 +6,7 @@
#[macro_use]
pub mod test_utils;
pub mod aggregate_and_proof;
pub mod attestation;
pub mod attestation_data;
pub mod attestation_duty;
@@ -39,10 +40,12 @@ pub mod voluntary_exit;
#[macro_use]
pub mod slot_epoch_macros;
pub mod slot_epoch;
pub mod subnet_id;
mod tree_hash_impls;
use ethereum_types::{H160, H256};
pub use crate::aggregate_and_proof::{AggregateAndProof, SignedAggregateAndProof};
pub use crate::attestation::{Attestation, Error as AttestationError};
pub use crate::attestation_data::AttestationData;
pub use crate::attestation_duty::AttestationDuty;
@@ -70,6 +73,7 @@ pub use crate::signed_beacon_block_header::SignedBeaconBlockHeader;
pub use crate::signed_voluntary_exit::SignedVoluntaryExit;
pub use crate::signing_root::{SignedRoot, SigningRoot};
pub use crate::slot_epoch::{Epoch, Slot};
pub use crate::subnet_id::SubnetId;
pub use crate::validator::Validator;
pub use crate::voluntary_exit::VoluntaryExit;

View File

@@ -94,6 +94,7 @@ impl Epoch {
}
impl SignedRoot for Epoch {}
impl SignedRoot for Slot {}
pub struct SlotIter<'a> {
current_iteration: u64,

View File

@@ -0,0 +1,26 @@
//! Identifies each shard by an integer identifier.
use serde_derive::{Deserialize, Serialize};
use std::ops::{Deref, DerefMut};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SubnetId(u64);
impl SubnetId {
pub fn new(id: u64) -> Self {
SubnetId(id)
}
}
impl Deref for SubnetId {
type Target = u64;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for SubnetId {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}