2020-06-18 01:53:08 +00:00
use crate ::behaviour ::{ Behaviour , BehaviourEvent , PeerRequestId , Request , Response } ;
2020-04-07 15:08:05 +00:00
use crate ::discovery ::enr ;
2019-03-08 01:15:57 +00:00
use crate ::multiaddr ::Protocol ;
2020-07-07 00:13:16 +00:00
use crate ::rpc ::{ GoodbyeReason , RPCResponseErrorCode , RequestId } ;
2020-04-01 06:20:32 +00:00
use crate ::types ::{ error , GossipKind } ;
2020-05-17 11:16:48 +00:00
use crate ::EnrExt ;
2020-07-07 00:13:16 +00:00
use crate ::{ NetworkConfig , NetworkGlobals , PeerAction } ;
2019-03-07 05:17:06 +00:00
use futures ::prelude ::* ;
use libp2p ::core ::{
2020-08-08 02:17:32 +00:00
identity ::Keypair , multiaddr ::Multiaddr , muxing ::StreamMuxerBox , transport ::boxed ::Boxed ,
2019-03-07 05:17:06 +00:00
} ;
2020-05-17 11:16:48 +00:00
use libp2p ::{
2020-08-08 02:17:32 +00:00
core , noise ,
2020-07-07 00:13:16 +00:00
swarm ::{ SwarmBuilder , SwarmEvent } ,
2020-05-17 11:16:48 +00:00
PeerId , Swarm , Transport ,
} ;
2020-05-18 11:35:14 +00:00
use slog ::{ crit , debug , info , o , trace , warn } ;
2019-07-01 06:38:42 +00:00
use std ::fs ::File ;
use std ::io ::prelude ::* ;
2019-03-07 05:17:06 +00:00
use std ::io ::{ Error , ErrorKind } ;
2020-05-17 11:16:48 +00:00
use std ::pin ::Pin ;
2020-02-19 11:12:25 +00:00
use std ::sync ::Arc ;
2019-03-07 05:17:06 +00:00
use std ::time ::Duration ;
2020-03-25 11:18:06 +00:00
use types ::{ EnrForkId , EthSpec } ;
2019-03-04 07:31:01 +00:00
2020-04-19 02:20:43 +00:00
pub const NETWORK_KEY_FILENAME : & str = " key " ;
2020-05-17 11:16:48 +00:00
/// The maximum simultaneous libp2p connections per peer.
const MAX_CONNECTIONS_PER_PEER : usize = 1 ;
/// The types of events than can be obtained from polling the libp2p service.
///
/// This is a subset of the events that a libp2p swarm emits.
#[ derive(Debug) ]
pub enum Libp2pEvent < TSpec : EthSpec > {
/// A behaviour event
Behaviour ( BehaviourEvent < TSpec > ) ,
/// A new listening address has been established.
NewListenAddr ( Multiaddr ) ,
}
2019-07-01 06:38:42 +00:00
2019-03-04 07:31:01 +00:00
/// The configuration and state of the libp2p components for the beacon node.
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 cd73dcd6434fb8d8e6bf30c5356355598ea7b78e.
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>
2020-03-17 06:24:44 +00:00
pub struct Service < TSpec : EthSpec > {
2019-03-07 00:43:55 +00:00
/// The libp2p Swarm handler.
2020-05-17 11:16:48 +00:00
pub swarm : Swarm < Behaviour < TSpec > > ,
2019-11-27 01:47:46 +00:00
2019-03-06 12:31:08 +00:00
/// This node's PeerId.
2019-08-23 05:53:53 +00:00
pub local_peer_id : PeerId ,
2019-11-27 01:47:46 +00:00
2019-03-12 06:28:11 +00:00
/// The libp2p logger handle.
pub log : slog ::Logger ,
2019-03-06 12:31:08 +00:00
}
2019-03-04 07:31:01 +00:00
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 cd73dcd6434fb8d8e6bf30c5356355598ea7b78e.
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>
2020-03-17 06:24:44 +00:00
impl < TSpec : EthSpec > Service < TSpec > {
2020-02-19 11:12:25 +00:00
pub fn new (
2020-06-04 11:48:05 +00:00
executor : environment ::TaskExecutor ,
2020-02-19 11:12:25 +00:00
config : & NetworkConfig ,
2020-03-25 11:18:06 +00:00
enr_fork_id : EnrForkId ,
2020-05-17 11:16:48 +00:00
log : & slog ::Logger ,
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 cd73dcd6434fb8d8e6bf30c5356355598ea7b78e.
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>
2020-03-17 06:24:44 +00:00
) -> error ::Result < ( Arc < NetworkGlobals < TSpec > > , Self ) > {
2020-05-17 11:16:48 +00:00
let log = log . new ( o! ( " service " = > " libp2p " ) ) ;
2019-08-29 11:23:28 +00:00
trace! ( log , " Libp2p Service starting " ) ;
2019-03-06 12:31:08 +00:00
2020-04-07 15:08:05 +00:00
// initialise the node's ID
2020-06-19 23:34:28 +00:00
let local_keypair = load_private_key ( config , & log ) ;
2019-09-10 16:13:54 +00:00
2020-04-07 15:08:05 +00:00
// Create an ENR or load from disk if appropriate
let enr =
enr ::build_or_load_enr ::< TSpec > ( local_keypair . clone ( ) , config , enr_fork_id , & log ) ? ;
2019-03-06 12:31:08 +00:00
2020-04-07 15:08:05 +00:00
let local_peer_id = enr . peer_id ( ) ;
2020-02-19 11:12:25 +00:00
// set up a collection of variables accessible outside of the network crate
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 cd73dcd6434fb8d8e6bf30c5356355598ea7b78e.
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>
2020-03-17 06:24:44 +00:00
let network_globals = Arc ::new ( NetworkGlobals ::new (
2020-04-07 15:08:05 +00:00
enr . clone ( ) ,
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 cd73dcd6434fb8d8e6bf30c5356355598ea7b78e.
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>
2020-03-17 06:24:44 +00:00
config . libp2p_port ,
config . discovery_port ,
2020-04-07 15:08:05 +00:00
& log ,
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 cd73dcd6434fb8d8e6bf30c5356355598ea7b78e.
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>
2020-03-17 06:24:44 +00:00
) ) ;
2020-02-19 11:12:25 +00:00
2020-04-07 15:08:05 +00:00
info! ( log , " Libp2p Service " ; " peer_id " = > format! ( " {:?} " , enr . peer_id ( ) ) ) ;
2020-06-23 03:45:40 +00:00
let discovery_string = if config . disable_discovery {
" None " . into ( )
} else {
config . discovery_port . to_string ( )
} ;
debug! ( log , " Attempting to open listening ports " ; " address " = > format! ( " {} " , config . listen_address ) , " tcp_port " = > config . libp2p_port , " udp_port " = > discovery_string ) ;
2020-04-07 15:08:05 +00:00
2019-03-08 00:07:30 +00:00
let mut swarm = {
2020-06-12 00:06:30 +00:00
// Set up the transport - tcp/ws with noise and yamux/mplex
2020-05-17 11:16:48 +00:00
let transport = build_transport ( local_keypair . clone ( ) )
. map_err ( | e | format! ( " Failed to build transport: {:?} " , e ) ) ? ;
2019-06-25 04:51:45 +00:00
// Lighthouse network behaviour
2020-04-07 15:08:05 +00:00
let behaviour = Behaviour ::new ( & local_keypair , config , network_globals . clone ( ) , & log ) ? ;
2020-05-17 11:16:48 +00:00
// use the executor for libp2p
2020-06-04 11:48:05 +00:00
struct Executor ( environment ::TaskExecutor ) ;
2020-05-17 11:16:48 +00:00
impl libp2p ::core ::Executor for Executor {
fn exec ( & self , f : Pin < Box < dyn Future < Output = ( ) > + Send > > ) {
2020-06-04 11:48:05 +00:00
self . 0. spawn ( f , " libp2p " ) ;
2020-05-17 11:16:48 +00:00
}
}
SwarmBuilder ::new ( transport , behaviour , local_peer_id . clone ( ) )
2020-07-29 06:39:30 +00:00
. notify_handler_buffer_size ( std ::num ::NonZeroUsize ::new ( 32 ) . expect ( " Not zero " ) )
. connection_event_buffer_size ( 64 )
. incoming_connection_limit ( 10 )
2020-08-11 02:16:31 +00:00
. outgoing_connection_limit ( config . target_peers * 2 )
2020-05-17 11:16:48 +00:00
. peer_connection_limit ( MAX_CONNECTIONS_PER_PEER )
2020-06-04 11:48:05 +00:00
. executor ( Box ::new ( Executor ( executor ) ) )
2020-05-17 11:16:48 +00:00
. build ( )
2019-03-08 00:07:30 +00:00
} ;
2019-03-06 12:31:08 +00:00
2019-06-25 08:02:11 +00:00
// listen on the specified address
let listen_multiaddr = {
let mut m = Multiaddr ::from ( config . listen_address ) ;
m . push ( Protocol ::Tcp ( config . libp2p_port ) ) ;
m
} ;
match Swarm ::listen_on ( & mut swarm , listen_multiaddr . clone ( ) ) {
Ok ( _ ) = > {
let mut log_address = listen_multiaddr ;
log_address . push ( Protocol ::P2p ( local_peer_id . clone ( ) . into ( ) ) ) ;
2019-08-29 11:23:28 +00:00
info! ( log , " Listening established " ; " address " = > format! ( " {} " , log_address ) ) ;
2019-06-25 08:02:11 +00:00
}
2019-08-23 05:53:53 +00:00
Err ( err ) = > {
crit! (
log ,
" Unable to listen on libp2p address " ;
" error " = > format! ( " {:?} " , err ) ,
" listen_multiaddr " = > format! ( " {} " , listen_multiaddr ) ,
) ;
return Err ( " Libp2p was unable to listen on the given listen address. " . into ( ) ) ;
}
2019-06-25 08:02:11 +00:00
} ;
2019-03-06 12:31:08 +00:00
2019-09-02 21:50:44 +00:00
// helper closure for dialing peers
2020-07-07 00:13:16 +00:00
let mut dial_addr = | mut multiaddr : Multiaddr | {
// strip the p2p protocol if it exists
strip_peer_id ( & mut multiaddr ) ;
2019-08-10 01:44:17 +00:00
match Swarm ::dial_addr ( & mut swarm , multiaddr . clone ( ) ) {
2019-08-29 11:23:28 +00:00
Ok ( ( ) ) = > debug! ( log , " Dialing libp2p peer " ; " address " = > format! ( " {} " , multiaddr ) ) ,
2019-08-10 01:44:17 +00:00
Err ( err ) = > debug! (
log ,
2019-09-02 14:34:41 +00:00
" Could not connect to peer " ; " address " = > format! ( " {} " , multiaddr ) , " error " = > format! ( " {:?} " , err )
2019-08-10 01:44:17 +00:00
) ,
} ;
2019-09-02 21:50:44 +00:00
} ;
// attempt to connect to user-input libp2p nodes
2020-02-19 11:12:25 +00:00
for multiaddr in & config . libp2p_nodes {
2020-07-07 00:13:16 +00:00
dial_addr ( multiaddr . clone ( ) ) ;
2019-09-02 21:50:44 +00:00
}
// attempt to connect to any specified boot-nodes
2020-05-17 11:16:48 +00:00
let mut boot_nodes = config . boot_nodes . clone ( ) ;
boot_nodes . dedup ( ) ;
for bootnode_enr in boot_nodes {
2020-02-19 11:12:25 +00:00
for multiaddr in & bootnode_enr . multiaddr ( ) {
2019-09-04 22:07:57 +00:00
// ignore udp multiaddr if it exists
let components = multiaddr . iter ( ) . collect ::< Vec < _ > > ( ) ;
if let Protocol ::Udp ( _ ) = components [ 1 ] {
continue ;
}
2020-05-17 11:16:48 +00:00
if ! network_globals
2020-04-21 14:29:19 +00:00
. peers
2020-05-17 11:16:48 +00:00
. read ( )
. is_connected_or_dialing ( & bootnode_enr . peer_id ( ) )
{
2020-07-07 00:13:16 +00:00
dial_addr ( multiaddr . clone ( ) ) ;
2020-05-17 11:16:48 +00:00
}
2019-09-02 21:50:44 +00:00
}
2019-08-10 01:44:17 +00:00
}
2020-04-01 06:20:32 +00:00
let mut subscribed_topics : Vec < GossipKind > = vec! [ ] ;
for topic_kind in & config . topics {
if swarm . subscribe_kind ( topic_kind . clone ( ) ) {
subscribed_topics . push ( topic_kind . clone ( ) ) ;
2019-03-19 12:20:39 +00:00
} else {
2020-04-01 06:20:32 +00:00
warn! ( log , " Could not subscribe to topic " ; " topic " = > format! ( " {} " , topic_kind ) ) ;
2019-03-19 12:20:39 +00:00
}
2019-03-13 04:37:44 +00:00
}
2019-12-20 05:26:30 +00:00
info! ( log , " Subscribed to topics " ; " topics " = > format! ( " {:?} " , subscribed_topics ) ) ;
2019-03-13 04:37:44 +00:00
2020-02-19 11:12:25 +00:00
let service = Service {
2019-08-23 05:53:53 +00:00
local_peer_id ,
2019-03-07 00:43:55 +00:00
swarm ,
2019-03-12 06:28:11 +00:00
log ,
2020-02-19 11:12:25 +00:00
} ;
Ok ( ( network_globals , service ) )
2019-03-12 06:28:11 +00:00
}
2019-11-29 02:04:44 +00:00
2020-06-05 03:07:59 +00:00
/// Sends a request to a peer, with a given Id.
pub fn send_request ( & mut self , peer_id : PeerId , request_id : RequestId , request : Request ) {
self . swarm . send_request ( peer_id , request_id , request ) ;
}
/// Informs the peer that their request failed.
pub fn respond_with_error (
& mut self ,
peer_id : PeerId ,
2020-06-18 01:53:08 +00:00
id : PeerRequestId ,
2020-06-05 03:07:59 +00:00
error : RPCResponseErrorCode ,
reason : String ,
) {
2020-06-18 01:53:08 +00:00
self . swarm . _send_error_reponse ( peer_id , id , error , reason ) ;
2020-06-05 03:07:59 +00:00
}
2020-07-07 00:13:16 +00:00
/// Report a peer's action.
pub fn report_peer ( & mut self , peer_id : & PeerId , action : PeerAction ) {
self . swarm . report_peer ( peer_id , action ) ;
}
// Disconnect and ban a peer, providing a reason.
pub fn goodbye_peer ( & mut self , peer_id : & PeerId , reason : GoodbyeReason ) {
self . swarm . goodbye_peer ( peer_id , reason ) ;
}
2020-06-05 03:07:59 +00:00
/// Sends a response to a peer's request.
2020-06-18 01:53:08 +00:00
pub fn send_response ( & mut self , peer_id : PeerId , id : PeerRequestId , response : Response < TSpec > ) {
self . swarm . send_successful_response ( peer_id , id , response ) ;
2020-06-05 03:07:59 +00:00
}
2020-05-17 11:16:48 +00:00
pub async fn next_event ( & mut self ) -> Libp2pEvent < TSpec > {
2019-03-12 06:28:11 +00:00
loop {
2020-07-07 00:13:16 +00:00
match self . swarm . next_event ( ) . await {
SwarmEvent ::Behaviour ( behaviour ) = > return Libp2pEvent ::Behaviour ( behaviour ) ,
SwarmEvent ::ConnectionEstablished { .. } = > {
// A connection could be established with a banned peer. This is
// handled inside the behaviour.
}
SwarmEvent ::ConnectionClosed {
peer_id ,
cause ,
endpoint : _ ,
num_established ,
} = > {
2020-08-08 02:17:32 +00:00
debug! ( self . log , " Connection closed " ; " peer_id " = > peer_id . to_string ( ) , " cause " = > format! ( " {:?} " , cause ) , " connections " = > num_established ) ;
2020-07-07 00:13:16 +00:00
}
SwarmEvent ::NewListenAddr ( multiaddr ) = > {
return Libp2pEvent ::NewListenAddr ( multiaddr )
}
SwarmEvent ::IncomingConnection {
local_addr ,
send_back_addr ,
} = > {
debug! ( self . log , " Incoming connection " ; " our_addr " = > local_addr . to_string ( ) , " from " = > send_back_addr . to_string ( ) )
2019-12-06 03:13:43 +00:00
}
2020-07-07 00:13:16 +00:00
SwarmEvent ::IncomingConnectionError {
local_addr ,
send_back_addr ,
error ,
} = > {
debug! ( self . log , " Failed incoming connection " ; " our_addr " = > local_addr . to_string ( ) , " from " = > send_back_addr . to_string ( ) , " error " = > error . to_string ( ) )
2020-06-05 03:07:59 +00:00
}
2020-07-07 00:13:16 +00:00
SwarmEvent ::BannedPeer { .. } = > {
// We do not ban peers at the swarm layer, so this should never occur.
}
SwarmEvent ::UnreachableAddr {
peer_id ,
address ,
error ,
attempts_remaining ,
} = > {
debug! ( self . log , " Failed to dial address " ; " peer_id " = > peer_id . to_string ( ) , " address " = > address . to_string ( ) , " error " = > error . to_string ( ) , " attempts_remaining " = > attempts_remaining ) ;
}
SwarmEvent ::UnknownPeerUnreachableAddr { address , error } = > {
debug! ( self . log , " Peer not known at dialed address " ; " address " = > address . to_string ( ) , " error " = > error . to_string ( ) ) ;
}
SwarmEvent ::ExpiredListenAddr ( multiaddr ) = > {
debug! ( self . log , " Listen address expired " ; " multiaddr " = > multiaddr . to_string ( ) )
}
SwarmEvent ::ListenerClosed { addresses , reason } = > {
2020-08-10 05:19:51 +00:00
crit! ( self . log , " Listener closed " ; " addresses " = > format! ( " {:?} " , addresses ) , " reason " = > format! ( " {:?} " , reason ) )
2020-07-07 00:13:16 +00:00
}
SwarmEvent ::ListenerError { error } = > {
2020-08-10 05:19:51 +00:00
warn! ( self . log , " Listener error " ; " error " = > format! ( " {:?} " , error . to_string ( ) ) )
2020-07-07 00:13:16 +00:00
}
SwarmEvent ::Dialing ( peer_id ) = > {
debug! ( self . log , " Dialing peer " ; " peer_id " = > peer_id . to_string ( ) ) ;
2020-06-05 03:07:59 +00:00
}
2019-12-06 03:13:43 +00:00
}
}
2019-03-04 07:31:01 +00:00
}
}
2019-03-06 12:31:08 +00:00
2020-06-12 00:06:30 +00:00
/// The implementation supports TCP/IP, WebSockets over TCP/IP, noise as the encryption layer, and
/// yamux or mplex as the multiplexing layer.
2020-05-17 11:16:48 +00:00
fn build_transport (
local_private_key : Keypair ,
) -> Result < Boxed < ( PeerId , StreamMuxerBox ) , Error > , Error > {
2020-06-29 10:25:42 +00:00
let transport = libp2p ::tcp ::TokioTcpConfig ::new ( ) . nodelay ( true ) ;
2020-05-17 11:16:48 +00:00
let transport = libp2p ::dns ::DnsConfig ::new ( transport ) ? ;
2019-03-07 05:17:06 +00:00
#[ cfg(feature = " libp2p-websocket " ) ]
let transport = {
let trans_clone = transport . clone ( ) ;
2020-06-18 07:42:42 +00:00
transport . or_transport ( libp2p ::websocket ::WsConfig ::new ( trans_clone ) )
2019-03-07 05:17:06 +00:00
} ;
2020-03-02 02:35:20 +00:00
// Authentication
2020-08-08 02:17:32 +00:00
Ok ( transport
. upgrade ( core ::upgrade ::Version ::V1 )
. authenticate ( generate_noise_config ( & local_private_key ) )
. multiplex ( core ::upgrade ::SelectUpgrade ::new (
libp2p ::mplex ::MplexConfig ::new ( ) ,
libp2p ::yamux ::Config ::default ( ) ,
) )
. map ( | ( peer , muxer ) , _ | ( peer , core ::muxing ::StreamMuxerBox ::new ( muxer ) ) )
. timeout ( Duration ::from_secs ( 10 ) )
. timeout ( Duration ::from_secs ( 10 ) )
2019-03-07 05:17:06 +00:00
. map_err ( | err | Error ::new ( ErrorKind ::Other , err ) )
2020-08-08 02:17:32 +00:00
. boxed ( ) )
2019-03-07 00:43:55 +00:00
}
2019-03-12 06:28:11 +00:00
2020-06-19 23:34:28 +00:00
// Useful helper functions for debugging. Currently not used in the client.
#[ allow(dead_code) ]
2019-09-10 16:13:54 +00:00
fn keypair_from_hex ( hex_bytes : & str ) -> error ::Result < Keypair > {
let hex_bytes = if hex_bytes . starts_with ( " 0x " ) {
hex_bytes [ 2 .. ] . to_string ( )
} else {
hex_bytes . to_string ( )
} ;
hex ::decode ( & hex_bytes )
. map_err ( | e | format! ( " Failed to parse p2p secret key bytes: {:?} " , e ) . into ( ) )
. and_then ( keypair_from_bytes )
}
2020-06-19 23:34:28 +00:00
#[ allow(dead_code) ]
2019-09-10 16:13:54 +00:00
fn keypair_from_bytes ( mut bytes : Vec < u8 > ) -> error ::Result < Keypair > {
libp2p ::core ::identity ::secp256k1 ::SecretKey ::from_bytes ( & mut bytes )
. map ( | secret | {
let keypair : libp2p ::core ::identity ::secp256k1 ::Keypair = secret . into ( ) ;
Keypair ::Secp256k1 ( keypair )
} )
. map_err ( | e | format! ( " Unable to parse p2p secret key: {:?} " , e ) . into ( ) )
}
2019-07-01 06:38:42 +00:00
/// Loads a private key from disk. If this fails, a new key is
/// generated and is then saved to disk.
///
/// Currently only secp256k1 keys are allowed, as these are the only keys supported by discv5.
fn load_private_key ( config : & NetworkConfig , log : & slog ::Logger ) -> Keypair {
// check for key from disk
let network_key_f = config . network_dir . join ( NETWORK_KEY_FILENAME ) ;
if let Ok ( mut network_key_file ) = File ::open ( network_key_f . clone ( ) ) {
let mut key_bytes : Vec < u8 > = Vec ::with_capacity ( 36 ) ;
match network_key_file . read_to_end ( & mut key_bytes ) {
Err ( _ ) = > debug! ( log , " Could not read network key file " ) ,
Ok ( _ ) = > {
// only accept secp256k1 keys for now
if let Ok ( secret_key ) =
libp2p ::core ::identity ::secp256k1 ::SecretKey ::from_bytes ( & mut key_bytes )
{
let kp : libp2p ::core ::identity ::secp256k1 ::Keypair = secret_key . into ( ) ;
debug! ( log , " Loaded network key from disk. " ) ;
return Keypair ::Secp256k1 ( kp ) ;
} else {
debug! ( log , " Network key file is not a valid secp256k1 key " ) ;
}
}
}
}
// if a key could not be loaded from disk, generate a new one and save it
let local_private_key = Keypair ::generate_secp256k1 ( ) ;
if let Keypair ::Secp256k1 ( key ) = local_private_key . clone ( ) {
let _ = std ::fs ::create_dir_all ( & config . network_dir ) ;
match File ::create ( network_key_f . clone ( ) )
. and_then ( | mut f | f . write_all ( & key . secret ( ) . to_bytes ( ) ) )
{
Ok ( _ ) = > {
debug! ( log , " New network key generated and written to disk " ) ;
}
Err ( e ) = > {
warn! (
log ,
2019-08-29 11:23:28 +00:00
" Could not write node key to file: {:?}. error: {} " , network_key_f , e
2019-07-01 06:38:42 +00:00
) ;
}
}
}
local_private_key
}
2020-03-02 02:35:20 +00:00
/// Generate authenticated XX Noise config from identity keys
fn generate_noise_config (
identity_keypair : & Keypair ,
2020-05-29 02:03:30 +00:00
) -> noise ::NoiseAuthenticated < noise ::XX , noise ::X25519Spec , ( ) > {
let static_dh_keys = noise ::Keypair ::< noise ::X25519Spec > ::new ( )
2020-03-02 02:35:20 +00:00
. into_authentic ( identity_keypair )
. expect ( " signing can fail only once during starting a node " ) ;
noise ::NoiseConfig ::xx ( static_dh_keys ) . into_authenticated ( )
}
2020-07-07 00:13:16 +00:00
/// For a multiaddr that ends with a peer id, this strips this suffix. Rust-libp2p
/// only supports dialing to an address without providing the peer id.
fn strip_peer_id ( addr : & mut Multiaddr ) {
let last = addr . pop ( ) ;
match last {
Some ( Protocol ::P2p ( _ ) ) = > { }
Some ( other ) = > addr . push ( other ) ,
_ = > { }
}
}