Remove NetworkSpecialization (#4665)

* remove networkspecialization

* Fix most of the fallout

* get all tests compiling

Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
This commit is contained in:
Robert Habermeier
2020-02-21 05:02:12 -08:00
committed by GitHub
parent e8000e7429
commit 0090fe979b
20 changed files with 136 additions and 503 deletions
@@ -6,7 +6,6 @@ use sc_client::LongestChain;
use node_template_runtime::{self, GenesisConfig, opaque::Block, RuntimeApi};
use sc_service::{error::{Error as ServiceError}, AbstractService, Configuration, ServiceBuilder};
use sp_inherents::InherentDataProviders;
use sc_network::{construct_simple_protocol};
use sc_executor::native_executor_instance;
pub use sc_executor::NativeExecutor;
use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair};
@@ -19,11 +18,6 @@ native_executor_instance!(
node_template_runtime::native_version,
);
construct_simple_protocol! {
/// Demo protocol attachment for substrate.
pub struct NodeProtocol where Block = Block { }
}
/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
@@ -95,7 +89,7 @@ pub fn new_full(config: Configuration<GenesisConfig>)
import_setup.take()
.expect("Link Half and Block Import are present for Full Services or setup failed before. qed");
let service = builder.with_network_protocol(|_| Ok(NodeProtocol::new()))?
let service = builder
.with_finality_proof_provider(|client, backend|
Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
)?
@@ -228,7 +222,6 @@ pub fn new_light(config: Configuration<GenesisConfig>)
Ok((import_queue, finality_proof_request_builder))
})?
.with_network_protocol(|_| Ok(NodeProtocol::new()))?
.with_finality_proof_provider(|client, backend|
Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
)?
+2 -9
View File
@@ -30,7 +30,6 @@ use sc_service::{
AbstractService, ServiceBuilder, config::Configuration, error::{Error as ServiceError},
};
use sp_inherents::InherentDataProviders;
use sc_network::construct_simple_protocol;
use sc_service::{Service, NetworkStatus};
use sc_client::{Client, LocalCallExecutor};
@@ -40,11 +39,6 @@ use node_executor::NativeExecutor;
use sc_network::NetworkService;
use sc_offchain::OffchainWorkers;
construct_simple_protocol! {
/// Demo protocol attachment for substrate.
pub struct NodeProtocol where Block = Block { }
}
/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
@@ -144,7 +138,7 @@ macro_rules! new_full {
let (builder, mut import_setup, inherent_data_providers) = new_full_start!($config);
let service = builder.with_network_protocol(|_| Ok(crate::service::NodeProtocol::new()))?
let service = builder
.with_finality_proof_provider(|client, backend|
Ok(Arc::new(grandpa::FinalityProofProvider::new(backend, client)) as _)
)?
@@ -283,7 +277,7 @@ pub fn new_full(config: NodeConfiguration)
ConcreteClient,
LongestChain<ConcreteBackend, ConcreteBlock>,
NetworkStatus<ConcreteBlock>,
NetworkService<ConcreteBlock, crate::service::NodeProtocol, <ConcreteBlock as BlockT>::Hash>,
NetworkService<ConcreteBlock, <ConcreteBlock as BlockT>::Hash>,
ConcreteTransactionPool,
OffchainWorkers<
ConcreteClient,
@@ -348,7 +342,6 @@ pub fn new_light(config: NodeConfiguration)
Ok((import_queue, finality_proof_request_builder))
})?
.with_network_protocol(|_| Ok(NodeProtocol::new()))?
.with_finality_proof_provider(|client, backend|
Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
)?
@@ -60,7 +60,6 @@ use libp2p::Multiaddr;
use log::{debug, error, log_enabled, warn};
use prost::Message;
use sc_client_api::blockchain::HeaderBackend;
use sc_network::specialization::NetworkSpecialization;
use sc_network::{DhtEvent, ExHashT, NetworkStateInfo};
use sp_authority_discovery::{AuthorityDiscoveryApi, AuthorityId, AuthoritySignature, AuthorityPair};
use sp_core::crypto::{key_types, Pair};
@@ -477,10 +476,9 @@ pub trait NetworkProvider: NetworkStateInfo {
fn get_value(&self, key: &libp2p::kad::record::Key);
}
impl<B, S, H> NetworkProvider for sc_network::NetworkService<B, S, H>
impl<B, H> NetworkProvider for sc_network::NetworkService<B, H>
where
B: BlockT + 'static,
S: NetworkSpecialization<B>,
H: ExHashT,
{
fn set_priority_group(
+4 -5
View File
@@ -896,11 +896,10 @@ mod tests {
const SLOT_DURATION: u64 = 1000;
pub struct AuraTestNet {
peers: Vec<Peer<(), DummySpecialization>>,
peers: Vec<Peer<()>>,
}
impl TestNetFactory for AuraTestNet {
type Specialization = DummySpecialization;
type Verifier = AuraVerifier<PeersFullClient, AuthorityPair, ()>;
type PeerData = ();
@@ -935,15 +934,15 @@ mod tests {
}
}
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData, DummySpecialization> {
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData> {
&mut self.peers[i]
}
fn peers(&self) -> &Vec<Peer<Self::PeerData, DummySpecialization>> {
fn peers(&self) -> &Vec<Peer<Self::PeerData>> {
&self.peers
}
fn mut_peers<F: FnOnce(&mut Vec<Peer<Self::PeerData, DummySpecialization>>)>(&mut self, closure: F) {
fn mut_peers<F: FnOnce(&mut Vec<Peer<Self::PeerData>>)>(&mut self, closure: F) {
closure(&mut self.peers);
}
}
+4 -5
View File
@@ -199,7 +199,7 @@ impl<B: BlockImport<TestBlock>> BlockImport<TestBlock> for PanickingBlockImport<
}
pub struct BabeTestNet {
peers: Vec<Peer<Option<PeerData>, DummySpecialization>>,
peers: Vec<Peer<Option<PeerData>>>,
}
type TestHeader = <TestBlock as BlockT>::Header;
@@ -236,7 +236,6 @@ pub struct PeerData {
}
impl TestNetFactory for BabeTestNet {
type Specialization = DummySpecialization;
type Verifier = TestVerifier;
type PeerData = Option<PeerData>;
@@ -307,17 +306,17 @@ impl TestNetFactory for BabeTestNet {
}
}
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData, DummySpecialization> {
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData> {
trace!(target: "babe", "Retrieving a peer");
&mut self.peers[i]
}
fn peers(&self) -> &Vec<Peer<Self::PeerData, DummySpecialization>> {
fn peers(&self) -> &Vec<Peer<Self::PeerData>> {
trace!(target: "babe", "Retrieving peers");
&self.peers
}
fn mut_peers<F: FnOnce(&mut Vec<Peer<Self::PeerData, DummySpecialization>>)>(
fn mut_peers<F: FnOnce(&mut Vec<Peer<Self::PeerData>>)>(
&mut self,
closure: F,
) {
@@ -120,9 +120,8 @@ pub trait Network<Block: BlockT>: GossipNetwork<Block> + Clone + Send + 'static
fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: Block::Hash, number: NumberFor<Block>);
}
impl<B, S, H> Network<B> for Arc<NetworkService<B, S, H>> where
impl<B, H> Network<B> for Arc<NetworkService<B, H>> where
B: BlockT,
S: sc_network::specialization::NetworkSpecialization<B>,
H: sc_network::ExHashT,
{
fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
@@ -19,7 +19,7 @@
use super::*;
use environment::HasVoted;
use sc_network_test::{
Block, DummySpecialization, Hash, TestNetFactory, BlockImportAdapter, Peer,
Block, Hash, TestNetFactory, BlockImportAdapter, Peer,
PeersClient, PassThroughVerifier,
};
use sc_network::config::{ProtocolConfig, Roles, BoxFinalityProofRequestBuilder};
@@ -68,7 +68,7 @@ type PeerData =
>
>
>;
type GrandpaPeer = Peer<PeerData, DummySpecialization>;
type GrandpaPeer = Peer<PeerData>;
struct GrandpaTestNet {
peers: Vec<GrandpaPeer>,
@@ -90,7 +90,6 @@ impl GrandpaTestNet {
}
impl TestNetFactory for GrandpaTestNet {
type Specialization = DummySpecialization;
type Verifier = PassThroughVerifier;
type PeerData = PeerData;
+2 -2
View File
@@ -59,7 +59,7 @@ pub use self::state_machine::TopicNotification;
pub use self::validator::{DiscardAll, MessageIntent, Validator, ValidatorContext, ValidationResult};
use futures::prelude::*;
use sc_network::{specialization::NetworkSpecialization, Event, ExHashT, NetworkService, PeerId, ReputationChange};
use sc_network::{Event, ExHashT, NetworkService, PeerId, ReputationChange};
use sp_runtime::{traits::Block as BlockT, ConsensusEngineId};
use std::{borrow::Cow, pin::Pin, sync::Arc};
@@ -97,7 +97,7 @@ pub trait Network<B: BlockT> {
fn announce(&self, block: B::Hash, associated_data: Vec<u8>);
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Network<B> for Arc<NetworkService<B, S, H>> {
impl<B: BlockT, H: ExHashT> Network<B> for Arc<NetworkService<B, H>> {
fn event_stream(&self) -> Pin<Box<dyn Stream<Item = Event> + Send>> {
Box::pin(NetworkService::event_stream(self))
}
+16 -17
View File
@@ -16,9 +16,8 @@
use crate::{
debug_info, discovery::DiscoveryBehaviour, discovery::DiscoveryOut, DiscoveryNetBehaviour,
Event, protocol::event::DhtEvent
Event, protocol::event::DhtEvent, ExHashT,
};
use crate::{ExHashT, specialization::NetworkSpecialization};
use crate::protocol::{self, light_client_handler, CustomMessageOutcome, Protocol};
use libp2p::NetworkBehaviour;
use libp2p::core::{Multiaddr, PeerId, PublicKey};
@@ -33,9 +32,9 @@ use void;
/// General behaviour of the network. Combines all protocols together.
#[derive(NetworkBehaviour)]
#[behaviour(out_event = "BehaviourOut<B>", poll_method = "poll")]
pub struct Behaviour<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> {
pub struct Behaviour<B: BlockT, H: ExHashT> {
/// All the substrate-specific protocols.
substrate: Protocol<B, S, H>,
substrate: Protocol<B, H>,
/// Periodically pings and identifies the nodes we are connected to, and store information in a
/// cache.
debug_info: debug_info::DebugInfoBehaviour,
@@ -58,10 +57,10 @@ pub enum BehaviourOut<B: BlockT> {
Event(Event),
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Behaviour<B, S, H> {
impl<B: BlockT, H: ExHashT> Behaviour<B, H> {
/// Builds a new `Behaviour`.
pub async fn new(
substrate: Protocol<B, S, H>,
substrate: Protocol<B, H>,
user_agent: String,
local_public_key: PublicKey,
known_addresses: Vec<(PeerId, Multiaddr)>,
@@ -107,12 +106,12 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Behaviour<B, S, H> {
}
/// Returns a shared reference to the user protocol.
pub fn user_protocol(&self) -> &Protocol<B, S, H> {
pub fn user_protocol(&self) -> &Protocol<B, H> {
&self.substrate
}
/// Returns a mutable reference to the user protocol.
pub fn user_protocol_mut(&mut self) -> &mut Protocol<B, S, H> {
pub fn user_protocol_mut(&mut self) -> &mut Protocol<B, H> {
&mut self.substrate
}
@@ -133,15 +132,15 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Behaviour<B, S, H> {
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviourEventProcess<void::Void> for
Behaviour<B, S, H> {
impl<B: BlockT, H: ExHashT> NetworkBehaviourEventProcess<void::Void> for
Behaviour<B, H> {
fn inject_event(&mut self, event: void::Void) {
void::unreachable(event)
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviourEventProcess<CustomMessageOutcome<B>> for
Behaviour<B, S, H> {
impl<B: BlockT, H: ExHashT> NetworkBehaviourEventProcess<CustomMessageOutcome<B>> for
Behaviour<B, H> {
fn inject_event(&mut self, event: CustomMessageOutcome<B>) {
match event {
CustomMessageOutcome::BlockImport(origin, blocks) =>
@@ -174,8 +173,8 @@ Behaviour<B, S, H> {
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviourEventProcess<debug_info::DebugInfoEvent>
for Behaviour<B, S, H> {
impl<B: BlockT, H: ExHashT> NetworkBehaviourEventProcess<debug_info::DebugInfoEvent>
for Behaviour<B, H> {
fn inject_event(&mut self, event: debug_info::DebugInfoEvent) {
let debug_info::DebugInfoEvent::Identified { peer_id, mut info } = event;
if info.listen_addrs.len() > 30 {
@@ -192,8 +191,8 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviourEventPr
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviourEventProcess<DiscoveryOut>
for Behaviour<B, S, H> {
impl<B: BlockT, H: ExHashT> NetworkBehaviourEventProcess<DiscoveryOut>
for Behaviour<B, H> {
fn inject_event(&mut self, out: DiscoveryOut) {
match out {
DiscoveryOut::UnroutablePeer(_peer_id) => {
@@ -221,7 +220,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviourEventPr
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Behaviour<B, S, H> {
impl<B: BlockT, H: ExHashT> Behaviour<B, H> {
fn poll<TEv>(&mut self, _: &mut Context, _: &mut impl PollParameters) -> Poll<NetworkBehaviourAction<TEv, BehaviourOut<B>>> {
if !self.events.is_empty() {
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(self.events.remove(0)))
+1 -4
View File
@@ -43,7 +43,7 @@ use std::{error::Error, fs, io::{self, Write}, net::Ipv4Addr, path::{Path, PathB
use zeroize::Zeroize;
/// Network initialization parameters.
pub struct Params<B: BlockT, S, H: ExHashT> {
pub struct Params<B: BlockT, H: ExHashT> {
/// Assigned roles for our node (full, light, ...).
pub roles: Roles,
@@ -88,9 +88,6 @@ pub struct Params<B: BlockT, S, H: ExHashT> {
/// valid.
pub import_queue: Box<dyn ImportQueue<B>>,
/// Customization of the network. Use this to plug additional networking capabilities.
pub specialization: S,
/// Type to check incoming block announcements.
pub block_announce_validator: Box<dyn BlockAnnounceValidator<B> + Send>,
}
+1 -9
View File
@@ -136,10 +136,6 @@
//! - Light-client requests. When a light client requires information, a random node we have a
//! substream open with is chosen, and the information is requested from it.
//! - Gossiping. Used for example by grandpa.
//! - Network specialization. The network protocol can be specialized through a template parameter
//! of the network service. This specialization is free to send and receive messages with the
//! remote. This is meant to be used by the chain that is being built on top of Substrate
//! (eg. Polkadot).
//!
//! It is intended that in the future each of these components gets more isolated, so that they
//! are free to open and close their own substreams, and so that syncing and light client requests
@@ -180,7 +176,7 @@ pub mod error;
pub mod network_state;
pub use service::{NetworkService, NetworkStateInfo, NetworkWorker, ExHashT, ReportHandle};
pub use protocol::{PeerInfo, Context, specialization};
pub use protocol::PeerInfo;
pub use protocol::event::{Event, DhtEvent};
pub use protocol::sync::SyncState;
pub use libp2p::{Multiaddr, PeerId};
@@ -196,10 +192,6 @@ pub use protocol::message::Status as StatusMessage;
pub use sc_peerset::ReputationChange;
// Used by the `construct_simple_protocol!` macro.
#[doc(hidden)]
pub use sp_runtime::traits::Block as BlockT;
/// Extension trait for `NetworkBehaviour` that also accepts discovering nodes.
trait DiscoveryNetBehaviour {
/// Notify the protocol that we have learned about the existence of nodes.
+8 -89
View File
@@ -38,7 +38,6 @@ use sp_arithmetic::traits::SaturatedConversion;
use message::{BlockAnnounce, BlockAttributes, Direction, FromBlock, Message, RequestId};
use message::generic::Message as GenericMessage;
use light_dispatch::{LightDispatch, LightDispatchNetwork, RequestData};
use specialization::NetworkSpecialization;
use sync::{ChainSync, SyncState};
use crate::service::{TransactionPool, ExHashT};
use crate::config::{BoxFinalityProofRequestBuilder, Roles};
@@ -73,7 +72,6 @@ pub mod message;
pub mod event;
pub mod light_client_handler;
pub mod light_dispatch;
pub mod specialization;
pub mod sync;
pub use block_requests::BlockRequests;
@@ -136,7 +134,7 @@ mod rep {
}
// Lock must always be taken in order declared here.
pub struct Protocol<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> {
pub struct Protocol<B: BlockT, H: ExHashT> {
/// Interval at which we call `tick`.
tick_timeout: Pin<Box<dyn Stream<Item = ()> + Send>>,
/// Interval at which we call `propagate_extrinsics`.
@@ -146,7 +144,6 @@ pub struct Protocol<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> {
light_dispatch: LightDispatch<B>,
genesis_hash: B::Hash,
sync: ChainSync<B>,
specialization: S,
context_data: ContextData<B, H>,
/// List of nodes for which we perform additional logging because they are important for the
/// user.
@@ -335,55 +332,6 @@ impl<'a, B: BlockT> LightDispatchNetwork<B> for LightDispatchIn<'a> {
}
}
/// Context for a network-specific handler.
pub trait Context<B: BlockT> {
/// Adjusts the reputation of the peer. Use this to point out that a peer has been malign or
/// irresponsible or appeared lazy.
fn report_peer(&mut self, who: PeerId, reputation: sc_peerset::ReputationChange);
/// Force disconnecting from a peer. Use this when a peer misbehaved.
fn disconnect_peer(&mut self, who: PeerId);
/// Send a chain-specific message to a peer.
fn send_chain_specific(&mut self, who: PeerId, message: Vec<u8>);
}
/// Protocol context.
struct ProtocolContext<'a, B: 'a + BlockT, H: 'a + ExHashT> {
behaviour: &'a mut GenericProto,
context_data: &'a mut ContextData<B, H>,
peerset_handle: &'a sc_peerset::PeersetHandle,
}
impl<'a, B: BlockT + 'a, H: 'a + ExHashT> ProtocolContext<'a, B, H> {
fn new(
context_data: &'a mut ContextData<B, H>,
behaviour: &'a mut GenericProto,
peerset_handle: &'a sc_peerset::PeersetHandle,
) -> Self {
ProtocolContext { context_data, peerset_handle, behaviour }
}
}
impl<'a, B: BlockT + 'a, H: ExHashT + 'a> Context<B> for ProtocolContext<'a, B, H> {
fn report_peer(&mut self, who: PeerId, reputation: sc_peerset::ReputationChange) {
self.peerset_handle.report_peer(who, reputation)
}
fn disconnect_peer(&mut self, who: PeerId) {
self.behaviour.disconnect_peer(&who)
}
fn send_chain_specific(&mut self, who: PeerId, message: Vec<u8>) {
send_message::<B> (
self.behaviour,
&mut self.context_data.stats,
&who,
GenericMessage::ChainSpecific(message)
)
}
}
/// Data necessary to create a context.
struct ContextData<B: BlockT, H: ExHashT> {
// All connected peers
@@ -410,20 +358,19 @@ impl Default for ProtocolConfig {
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
impl<B: BlockT, H: ExHashT> Protocol<B, H> {
/// Create a new instance.
pub fn new(
config: ProtocolConfig,
chain: Arc<dyn Client<B>>,
checker: Arc<dyn FetchChecker<B>>,
specialization: S,
transaction_pool: Arc<dyn TransactionPool<H, B>>,
finality_proof_provider: Option<Arc<dyn FinalityProofProvider<B>>>,
finality_proof_request_builder: Option<BoxFinalityProofRequestBuilder<B>>,
protocol_id: ProtocolId,
peerset_config: sc_peerset::PeersetConfig,
block_announce_validator: Box<dyn BlockAnnounceValidator<B> + Send>
) -> error::Result<(Protocol<B, S, H>, sc_peerset::PeersetHandle)> {
) -> error::Result<(Protocol<B, H>, sc_peerset::PeersetHandle)> {
let info = chain.info();
let sync = ChainSync::new(
config.roles,
@@ -459,7 +406,6 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
light_dispatch: LightDispatch::new(checker),
genesis_hash: info.genesis_hash,
sync,
specialization,
handshaking_peers: HashMap::new(),
important_peers,
transaction_pool,
@@ -681,11 +627,6 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
CustomMessageOutcome::None
};
},
GenericMessage::ChainSpecific(msg) => self.specialization.on_message(
&mut ProtocolContext::new(&mut self.context_data, &mut self.behaviour, &self.peerset_handle),
who,
msg,
),
}
CustomMessageOutcome::None
@@ -710,14 +651,6 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
);
}
/// Locks `self` and returns a context plus the network specialization.
pub fn specialization_lock<'a>(
&'a mut self,
) -> (impl Context<B> + 'a, &'a mut S) {
let context = ProtocolContext::new(&mut self.context_data, &mut self.behaviour, &self.peerset_handle);
(context, &mut self.specialization)
}
/// Called when a new peer is connected
pub fn on_peer_connected(&mut self, who: PeerId) {
trace!(target: "sync", "Connecting {}", who);
@@ -739,9 +672,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
self.context_data.peers.remove(&peer)
};
if let Some(_peer_data) = removed {
let mut context = ProtocolContext::new(&mut self.context_data, &mut self.behaviour, &self.peerset_handle);
self.sync.peer_disconnected(peer.clone());
self.specialization.on_disconnect(&mut context, peer.clone());
self.light_dispatch.on_disconnect(LightDispatchIn {
behaviour: &mut self.behaviour,
peerset: self.peerset_handle.clone(),
@@ -940,9 +871,6 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
}
}
self.specialization.maintain_peers(
&mut ProtocolContext::new(&mut self.context_data, &mut self.behaviour, &self.peerset_handle)
);
for p in aborting {
self.behaviour.disconnect_peer(&p);
self.peerset_handle.report_peer(p, rep::TIMEOUT);
@@ -1058,9 +986,6 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
}
}
let mut context = ProtocolContext::new(&mut self.context_data, &mut self.behaviour, &self.peerset_handle);
self.specialization.on_connect(&mut context, who.clone(), status);
// Notify all the notification protocols as open.
CustomMessageOutcome::NotificationStreamOpened {
remote: who,
@@ -1292,7 +1217,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
roles: self.config.roles.into(),
best_number: info.best_number,
best_hash: info.best_hash,
chain_status: self.specialization.status(),
chain_status: Vec::new(), // TODO: find a way to make this backwards-compatible
};
self.send_message(&who, GenericMessage::Status(status))
@@ -1361,15 +1286,10 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
/// Call this when a block has been imported in the import queue and we should announce it on
/// the network.
pub fn on_block_imported(&mut self, hash: B::Hash, header: &B::Header, data: Vec<u8>, is_best: bool) {
pub fn on_block_imported(&mut self, header: &B::Header, data: Vec<u8>, is_best: bool) {
if is_best {
self.sync.update_chain_info(header);
}
self.specialization.on_block_imported(
&mut ProtocolContext::new(&mut self.context_data, &mut self.behaviour, &self.peerset_handle),
hash.clone(),
header,
);
// blocks are not announced by light clients
if self.config.roles.is_light() {
@@ -1872,8 +1792,7 @@ fn send_message<B: BlockT>(
behaviour.send_packet(who, encoded);
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviour for
Protocol<B, S, H> {
impl<B: BlockT, H: ExHashT> NetworkBehaviour for Protocol<B, H> {
type ProtocolsHandler = <GenericProto as NetworkBehaviour>::ProtocolsHandler;
type OutEvent = CustomMessageOutcome<B>;
@@ -2030,13 +1949,13 @@ Protocol<B, S, H> {
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> DiscoveryNetBehaviour for Protocol<B, S, H> {
impl<B: BlockT, H: ExHashT> DiscoveryNetBehaviour for Protocol<B, H> {
fn add_discovered_nodes(&mut self, peer_ids: impl Iterator<Item = PeerId>) {
self.behaviour.add_discovered_nodes(peer_ids)
}
}
impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Drop for Protocol<B, S, H> {
impl<B: BlockT, H: ExHashT> Drop for Protocol<B, H> {
fn drop(&mut self) {
debug!(target: "sync", "Network stats:\n{}", self.format_stats());
}
@@ -25,7 +25,8 @@ use libp2p::swarm::{PollParameters, NetworkBehaviour, NetworkBehaviourAction};
use libp2p::{PeerId, Multiaddr, Transport};
use rand::seq::SliceRandom;
use std::{error, io, task::Context, task::Poll, time::Duration};
use crate::message::Message;
use std::collections::HashSet;
use crate::message::{generic::BlockResponse, Message};
use crate::protocol::generic_proto::{GenericProto, GenericProtoOut};
use sp_test_primitives::Block;
@@ -227,7 +228,10 @@ fn two_nodes_transfer_lots_of_packets() {
for n in 0 .. NUM_PACKETS {
service1.send_packet(
&peer_id,
Message::<Block>::ChainSpecific(vec![(n % 256) as u8]).encode()
Message::<Block>::BlockResponse(BlockResponse {
id: n as _,
blocks: Vec::new(),
}).encode()
);
}
},
@@ -243,8 +247,8 @@ fn two_nodes_transfer_lots_of_packets() {
Some(GenericProtoOut::CustomProtocolOpen { .. }) => {},
Some(GenericProtoOut::CustomMessage { message, .. }) => {
match Message::<Block>::decode(&mut &message[..]).unwrap() {
Message::<Block>::ChainSpecific(message) => {
assert_eq!(message.len(), 1);
Message::<Block>::BlockResponse(BlockResponse { id: _, blocks }) => {
assert!(blocks.is_empty());
packet_counter += 1;
if packet_counter == NUM_PACKETS {
return Poll::Ready(())
@@ -270,9 +274,21 @@ fn basic_two_nodes_requests_in_parallel() {
// Generate random messages with or without a request id.
let mut to_send = {
let mut to_send = Vec::new();
let mut existing_ids = HashSet::new();
for _ in 0..200 { // Note: don't make that number too high or the CPU usage will explode.
let msg = (0..10).map(|_| rand::random::<u8>()).collect::<Vec<_>>();
to_send.push(Message::<Block>::ChainSpecific(msg));
let req_id = loop {
let req_id = rand::random::<u64>();
// ensure uniqueness - odds of randomly sampling collisions
// is unlikely, but possible to cause spurious test failures.
if existing_ids.insert(req_id) {
break req_id;
}
};
to_send.push(Message::<Block>::BlockResponse(
BlockResponse { id: req_id, blocks: Vec::new() }
));
}
to_send
};
@@ -219,9 +219,6 @@ pub mod generic {
FinalityProofResponse(FinalityProofResponse<Hash>),
/// Batch of consensus protocol messages.
ConsensusBatch(Vec<ConsensusMessage>),
/// Chain-specific message.
#[codec(index = "255")]
ChainSpecific(Vec<u8>),
}
impl<Header, Hash, Number, Extrinsic> Message<Header, Hash, Number, Extrinsic> {
@@ -246,7 +243,6 @@ pub mod generic {
Message::FinalityProofRequest(_) => "FinalityProofRequest",
Message::FinalityProofResponse(_) => "FinalityProofResponse",
Message::ConsensusBatch(_) => "ConsensusBatch",
Message::ChainSpecific(_) => "ChainSpecific",
}
}
}
@@ -1,171 +0,0 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Specializations of the substrate network protocol to allow more complex forms of communication.
pub use crate::protocol::event::{DhtEvent, Event};
use crate::protocol::Context;
use libp2p::PeerId;
use sp_runtime::traits::Block as BlockT;
/// A specialization of the substrate network protocol. Handles events and sends messages.
pub trait NetworkSpecialization<B: BlockT>: Send + Sync + 'static {
/// Get the current specialization-status.
fn status(&self) -> Vec<u8>;
/// Called when a peer successfully handshakes.
fn on_connect(&mut self, ctx: &mut dyn Context<B>, who: PeerId, status: crate::protocol::message::Status<B>);
/// Called when a peer is disconnected. If the peer ID is unknown, it should be ignored.
fn on_disconnect(&mut self, ctx: &mut dyn Context<B>, who: PeerId);
/// Called when a network-specific message arrives.
fn on_message(
&mut self,
ctx: &mut dyn Context<B>,
who: PeerId,
message: Vec<u8>
);
/// Called periodically to maintain peers and handle timeouts.
fn maintain_peers(&mut self, _ctx: &mut dyn Context<B>) { }
/// Called when a block is _imported_ at the head of the chain (not during major sync).
/// Not guaranteed to be called for every block, but will be most of the after major sync.
fn on_block_imported(&mut self, _ctx: &mut dyn Context<B>, _hash: B::Hash, _header: &B::Header) { }
}
/// A specialization that does nothing.
#[derive(Clone)]
pub struct DummySpecialization;
impl<B: BlockT> NetworkSpecialization<B> for DummySpecialization {
fn status(&self) -> Vec<u8> {
vec![]
}
fn on_connect(
&mut self,
_ctx: &mut dyn Context<B>,
_peer_id: PeerId,
_status: crate::protocol::message::Status<B>
) {}
fn on_disconnect(&mut self, _ctx: &mut dyn Context<B>, _peer_id: PeerId) {}
fn on_message(
&mut self,
_ctx: &mut dyn Context<B>,
_peer_id: PeerId,
_message: Vec<u8>,
) {}
}
/// Construct a simple protocol that is composed of several sub protocols.
/// Each "sub protocol" needs to implement `Specialization` and needs to provide a `new()` function.
/// For more fine grained implementations, this macro is not usable.
///
/// # Example
///
/// ```nocompile
/// construct_simple_protocol! {
/// pub struct MyProtocol where Block = MyBlock {
/// consensus_gossip: ConsensusGossip<MyBlock>,
/// other_protocol: MyCoolStuff,
/// }
/// }
/// ```
///
/// You can also provide an optional parameter after `where Block = MyBlock`, so it looks like
/// `where Block = MyBlock, Status = consensus_gossip`. This will instruct the implementation to
/// use the `status()` function from the `ConsensusGossip` protocol. By default, `status()` returns
/// an empty vector.
#[macro_export]
macro_rules! construct_simple_protocol {
(
$( #[ $attr:meta ] )*
pub struct $protocol:ident where
Block = $block:ident
$( , Status = $status_protocol_name:ident )*
{
$( $sub_protocol_name:ident : $sub_protocol:ident $( <$protocol_block:ty> )*, )*
}
) => {
$( #[$attr] )*
pub struct $protocol {
$( $sub_protocol_name: $sub_protocol $( <$protocol_block> )*, )*
}
impl $protocol {
/// Instantiate a node protocol handler.
pub fn new() -> Self {
Self {
$( $sub_protocol_name: $sub_protocol::new(), )*
}
}
}
impl $crate::specialization::NetworkSpecialization<$block> for $protocol {
fn status(&self) -> Vec<u8> {
$(
let status = self.$status_protocol_name.status();
if !status.is_empty() {
return status;
}
)*
Vec::new()
}
fn on_connect(
&mut self,
_ctx: &mut $crate::Context<$block>,
_who: $crate::PeerId,
_status: $crate::StatusMessage<$block>
) {
$( self.$sub_protocol_name.on_connect(_ctx, _who, _status); )*
}
fn on_disconnect(&mut self, _ctx: &mut $crate::Context<$block>, _who: $crate::PeerId) {
$( self.$sub_protocol_name.on_disconnect(_ctx, _who); )*
}
fn on_message(
&mut self,
_ctx: &mut $crate::Context<$block>,
_who: $crate::PeerId,
_message: Vec<u8>,
) {
$( self.$sub_protocol_name.on_message(_ctx, _who, _message); )*
}
fn maintain_peers(&mut self, _ctx: &mut $crate::Context<$block>) {
$( self.$sub_protocol_name.maintain_peers(_ctx); )*
}
fn on_block_imported(
&mut self,
_ctx: &mut $crate::Context<$block>,
_hash: <$block as $crate::BlockT>::Hash,
_header: &<$block as $crate::BlockT>::Header
) {
$( self.$sub_protocol_name.on_block_imported(_ctx, _hash, _header); )*
}
}
}
}
+32 -52
View File
@@ -45,9 +45,8 @@ use crate::{transport, config::NonReservedPeerMode, ReputationChange};
use crate::config::{Params, TransportConfig};
use crate::error::Error;
use crate::network_state::{NetworkState, NotConnectedPeer as NetworkStateNotConnectedPeer, Peer as NetworkStatePeer};
use crate::protocol::{self, Protocol, Context, PeerInfo};
use crate::protocol::{self, Protocol, PeerInfo};
use crate::protocol::{event::Event, light_dispatch::{AlwaysBadChecker, RequestData}};
use crate::protocol::specialization::NetworkSpecialization;
use crate::protocol::sync::SyncState;
/// Minimum Requirements for a Hash within Networking
@@ -101,7 +100,7 @@ impl ReportHandle {
}
/// Substrate network service. Handles network IO and manages connectivity.
pub struct NetworkService<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> {
pub struct NetworkService<B: BlockT + 'static, H: ExHashT> {
/// Number of peers we're connected to.
num_connected: Arc<AtomicUsize>,
/// The local external addresses.
@@ -116,19 +115,19 @@ pub struct NetworkService<B: BlockT + 'static, S: NetworkSpecialization<B>, H: E
/// nodes it should be connected to or not.
peerset: PeersetHandle,
/// Channel that sends messages to the actual worker.
to_worker: mpsc::UnboundedSender<ServiceToWorkerMsg<B, H, S>>,
to_worker: mpsc::UnboundedSender<ServiceToWorkerMsg<B, H>>,
/// Marker to pin the `H` generic. Serves no purpose except to not break backwards
/// compatibility.
_marker: PhantomData<H>,
}
impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkWorker<B, S, H> {
impl<B: BlockT + 'static, H: ExHashT> NetworkWorker<B, H> {
/// Creates the network service.
///
/// Returns a `NetworkWorker` that implements `Future` and must be regularly polled in order
/// for the network processing to advance. From it, you can extract a `NetworkService` using
/// `worker.service()`. The `NetworkService` can be shared through the codebase.
pub fn new(params: Params<B, S, H>) -> Result<NetworkWorker<B, S, H>, Error> {
pub fn new(params: Params<B, H>) -> Result<NetworkWorker<B, H>, Error> {
let (to_worker, from_worker) = mpsc::unbounded();
if let Some(ref path) = params.network_config.net_config_path {
@@ -205,7 +204,6 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkWorker
},
params.chain.clone(),
checker.clone(),
params.specialization,
params.transaction_pool,
params.finality_proof_provider.clone(),
params.finality_proof_request_builder,
@@ -215,7 +213,7 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkWorker
)?;
// Build the swarm.
let (mut swarm, bandwidth): (Swarm::<B, S, H>, _) = {
let (mut swarm, bandwidth): (Swarm::<B, H>, _) = {
let user_agent = format!(
"{} ({})",
params.network_config.client_version,
@@ -263,14 +261,14 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkWorker
// Listen on multiaddresses.
for addr in &params.network_config.listen_addresses {
if let Err(err) = Swarm::<B, S, H>::listen_on(&mut swarm, addr.clone()) {
if let Err(err) = Swarm::<B, H>::listen_on(&mut swarm, addr.clone()) {
warn!(target: "sub-libp2p", "Can't listen on {} because: {:?}", addr, err)
}
}
// Add external addresses.
for addr in &params.network_config.public_addresses {
Swarm::<B, S, H>::add_external_address(&mut swarm, addr.clone());
Swarm::<B, H>::add_external_address(&mut swarm, addr.clone());
}
let external_addresses = Arc::new(Mutex::new(Vec::new()));
@@ -351,13 +349,13 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkWorker
/// Return a `NetworkService` that can be shared through the code base and can be used to
/// manipulate the worker.
pub fn service(&self) -> &Arc<NetworkService<B, S, H>> {
pub fn service(&self) -> &Arc<NetworkService<B, H>> {
&self.service
}
/// You must call this when a new block is imported by the client.
pub fn on_block_imported(&mut self, hash: B::Hash, header: B::Header, data: Vec<u8>, is_best: bool) {
self.network_service.user_protocol_mut().on_block_imported(hash, &header, data, is_best);
pub fn on_block_imported(&mut self, header: B::Header, data: Vec<u8>, is_best: bool) {
self.network_service.user_protocol_mut().on_block_imported(&header, data, is_best);
}
/// You must call this when a new block is finalized by the client.
@@ -415,9 +413,9 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkWorker
};
NetworkState {
peer_id: Swarm::<B, S, H>::local_peer_id(&swarm).to_base58(),
listened_addresses: Swarm::<B, S, H>::listeners(&swarm).cloned().collect(),
external_addresses: Swarm::<B, S, H>::external_addresses(&swarm).cloned().collect(),
peer_id: Swarm::<B, H>::local_peer_id(&swarm).to_base58(),
listened_addresses: Swarm::<B, H>::listeners(&swarm).cloned().collect(),
external_addresses: Swarm::<B, H>::external_addresses(&swarm).cloned().collect(),
average_download_per_sec: self.service.bandwidth.average_download_per_sec(),
average_upload_per_sec: self.service.bandwidth.average_upload_per_sec(),
connected_peers,
@@ -446,7 +444,7 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkWorker
}
}
impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkService<B, S, H> {
impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
/// Writes a message on an open notifications channel. Has no effect if the notifications
/// channel with this protocol name is closed.
///
@@ -545,15 +543,6 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkServic
.unbounded_send(ServiceToWorkerMsg::RequestJustification(hash.clone(), number));
}
/// Execute a closure with the chain-specific network specialization.
pub fn with_spec<F>(&self, f: F)
where F: FnOnce(&mut S, &mut dyn Context<B>) + Send + 'static
{
let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::ExecuteWithSpec(Box::new(f)));
}
/// Are we in the process of downloading the chain?
pub fn is_major_syncing(&self) -> bool {
self.is_major_syncing.load(Ordering::Relaxed)
@@ -641,8 +630,8 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> NetworkServic
}
}
impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> sp_consensus::SyncOracle
for NetworkService<B, S, H>
impl<B: BlockT + 'static, H: ExHashT> sp_consensus::SyncOracle
for NetworkService<B, H>
{
fn is_major_syncing(&mut self) -> bool {
NetworkService::is_major_syncing(self)
@@ -653,8 +642,8 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> sp_consensus:
}
}
impl<'a, B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> sp_consensus::SyncOracle
for &'a NetworkService<B, S, H>
impl<'a, B: BlockT + 'static, H: ExHashT> sp_consensus::SyncOracle
for &'a NetworkService<B, H>
{
fn is_major_syncing(&mut self) -> bool {
NetworkService::is_major_syncing(self)
@@ -674,10 +663,9 @@ pub trait NetworkStateInfo {
fn local_peer_id(&self) -> PeerId;
}
impl<B, S, H> NetworkStateInfo for NetworkService<B, S, H>
impl<B, H> NetworkStateInfo for NetworkService<B, H>
where
B: sp_runtime::traits::Block,
S: NetworkSpecialization<B>,
H: ExHashT,
{
/// Returns the local external addresses.
@@ -694,12 +682,11 @@ impl<B, S, H> NetworkStateInfo for NetworkService<B, S, H>
/// Messages sent from the `NetworkService` to the `NetworkWorker`.
///
/// Each entry corresponds to a method of `NetworkService`.
enum ServiceToWorkerMsg<B: BlockT, H: ExHashT, S: NetworkSpecialization<B>> {
enum ServiceToWorkerMsg<B: BlockT, H: ExHashT> {
PropagateExtrinsic(H),
PropagateExtrinsics,
RequestJustification(B::Hash, NumberFor<B>),
AnnounceBlock(B::Hash, Vec<u8>),
ExecuteWithSpec(Box<dyn FnOnce(&mut S, &mut dyn Context<B>) + Send>),
GetValue(record::Key),
PutValue(record::Key, Vec<u8>),
AddKnownAddress(PeerId, Multiaddr),
@@ -721,7 +708,7 @@ enum ServiceToWorkerMsg<B: BlockT, H: ExHashT, S: NetworkSpecialization<B>> {
///
/// You are encouraged to poll this in a separate background thread or task.
#[must_use = "The NetworkWorker must be polled in order for the network to work"]
pub struct NetworkWorker<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> {
pub struct NetworkWorker<B: BlockT + 'static, H: ExHashT> {
/// Updated by the `NetworkWorker` and loaded by the `NetworkService`.
external_addresses: Arc<Mutex<Vec<Multiaddr>>>,
/// Updated by the `NetworkWorker` and loaded by the `NetworkService`.
@@ -729,20 +716,20 @@ pub struct NetworkWorker<B: BlockT + 'static, S: NetworkSpecialization<B>, H: Ex
/// Updated by the `NetworkWorker` and loaded by the `NetworkService`.
is_major_syncing: Arc<AtomicBool>,
/// The network service that can be extracted and shared through the codebase.
service: Arc<NetworkService<B, S, H>>,
service: Arc<NetworkService<B, H>>,
/// The *actual* network.
network_service: Swarm<B, S, H>,
network_service: Swarm<B, H>,
/// The import queue that was passed as initialization.
import_queue: Box<dyn ImportQueue<B>>,
/// Messages from the `NetworkService` and that must be processed.
from_worker: mpsc::UnboundedReceiver<ServiceToWorkerMsg<B, H, S>>,
from_worker: mpsc::UnboundedReceiver<ServiceToWorkerMsg<B, H>>,
/// Receiver for queries from the light client that must be processed.
light_client_rqs: Option<mpsc::UnboundedReceiver<RequestData<B>>>,
/// Senders for events that happen on the network.
event_streams: Vec<mpsc::UnboundedSender<Event>>,
}
impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> Future for NetworkWorker<B, S, H> {
impl<B: BlockT + 'static, H: ExHashT> Future for NetworkWorker<B, H> {
type Output = Result<(), io::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
@@ -769,11 +756,6 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> Future for Ne
};
match msg {
ServiceToWorkerMsg::ExecuteWithSpec(task) => {
let protocol = this.network_service.user_protocol_mut();
let (mut context, spec) = protocol.specialization_lock();
task(spec, &mut context);
},
ServiceToWorkerMsg::AnnounceBlock(hash, data) =>
this.network_service.user_protocol_mut().announce_block(hash, data),
ServiceToWorkerMsg::RequestJustification(hash, number) =>
@@ -839,7 +821,7 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> Future for Ne
// Update the variables shared with the `NetworkService`.
this.num_connected.store(this.network_service.user_protocol_mut().num_connected_peers(), Ordering::Relaxed);
{
let external_addresses = Swarm::<B, S, H>::external_addresses(&this.network_service).cloned().collect();
let external_addresses = Swarm::<B, H>::external_addresses(&this.network_service).cloned().collect();
*this.external_addresses.lock() = external_addresses;
}
this.is_major_syncing.store(match this.network_service.user_protocol_mut().sync_state() {
@@ -851,20 +833,18 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> Future for Ne
}
}
impl<B: BlockT + 'static, S: NetworkSpecialization<B>, H: ExHashT> Unpin for NetworkWorker<B, S, H> {
impl<B: BlockT + 'static, H: ExHashT> Unpin for NetworkWorker<B, H> {
}
/// The libp2p swarm, customized for our needs.
type Swarm<B, S, H> = libp2p::swarm::Swarm<
Behaviour<B, S, H>
>;
type Swarm<B, H> = libp2p::swarm::Swarm<Behaviour<B, H>>;
// Implementation of `import_queue::Link` trait using the available local variables.
struct NetworkLink<'a, B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> {
protocol: &'a mut Swarm<B, S, H>,
struct NetworkLink<'a, B: BlockT, H: ExHashT> {
protocol: &'a mut Swarm<B, H>,
}
impl<'a, B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Link<B> for NetworkLink<'a, B, S, H> {
impl<'a, B: BlockT, H: ExHashT> Link<B> for NetworkLink<'a, B, H> {
fn blocks_processed(
&mut self,
imported: usize,
+16 -36
View File
@@ -52,17 +52,14 @@ use sc_network::config::{NetworkConfiguration, TransportConfig, BoxFinalityProof
use libp2p::PeerId;
use parking_lot::Mutex;
use sp_core::H256;
use sc_network::config::ProtocolConfig;
use sc_network::config::{ProtocolConfig, TransactionPool};
use sp_runtime::generic::{BlockId, OpaqueDigestItemId};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use sp_runtime::Justification;
use sc_network::config::TransactionPool;
use sc_network::specialization::NetworkSpecialization;
use substrate_test_runtime_client::{self, AccountKeyring};
pub use substrate_test_runtime_client::runtime::{Block, Extrinsic, Hash, Transfer};
pub use substrate_test_runtime_client::{TestClient, TestClientBuilder, TestClientBuilderExt};
pub use sc_network::specialization::DummySpecialization;
type AuthorityId = sp_consensus_babe::AuthorityId;
@@ -178,7 +175,7 @@ impl PeersClient {
}
}
pub struct Peer<D, S: NetworkSpecialization<Block>> {
pub struct Peer<D> {
pub data: D,
client: PeersClient,
/// We keep a copy of the verifier so that we can invoke it for locally-generated blocks,
@@ -189,12 +186,12 @@ pub struct Peer<D, S: NetworkSpecialization<Block>> {
block_import: BlockImportAdapter<()>,
select_chain: Option<LongestChain<substrate_test_runtime_client::Backend, Block>>,
backend: Option<Arc<substrate_test_runtime_client::Backend>>,
network: NetworkWorker<Block, S, <Block as BlockT>::Hash>,
network: NetworkWorker<Block, <Block as BlockT>::Hash>,
imported_blocks_stream: Box<dyn Stream<Item = BlockImportNotification<Block>, Error = ()> + Send>,
finality_notification_stream: Box<dyn Stream<Item = FinalityNotification<Block>, Error = ()> + Send>,
}
impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
impl<D> Peer<D> {
/// Get this peer ID.
pub fn id(&self) -> PeerId {
self.network.service().local_peer_id()
@@ -283,7 +280,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
Default::default()
};
self.block_import.import_block(import_block, cache).expect("block_import failed");
self.network.on_block_imported(hash, header, Vec::new(), true);
self.network.on_block_imported(header, Vec::new(), true);
at = hash;
}
@@ -336,7 +333,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
}
/// Get a reference to the network service.
pub fn network_service(&self) -> &Arc<NetworkService<Block, S, <Block as BlockT>::Hash>> {
pub fn network_service(&self) -> &Arc<NetworkService<Block, <Block as BlockT>::Hash>> {
&self.network.service()
}
@@ -392,16 +389,6 @@ impl TransactionPool<Hash, Block> for EmptyTransactionPool {
fn transaction(&self, _h: &Hash) -> Option<Extrinsic> { None }
}
pub trait SpecializationFactory {
fn create() -> Self;
}
impl SpecializationFactory for DummySpecialization {
fn create() -> DummySpecialization {
DummySpecialization
}
}
/// Implements `BlockImport` for any `Transaction`. Internally the transaction is
/// "converted", aka the field is set to `None`.
///
@@ -522,7 +509,6 @@ impl<B: BlockT> VerifierAdapter<B> {
}
pub trait TestNetFactory: Sized {
type Specialization: NetworkSpecialization<Block> + SpecializationFactory;
type Verifier: 'static + Verifier<Block>;
type PeerData: Default;
@@ -536,9 +522,9 @@ pub trait TestNetFactory: Sized {
) -> Self::Verifier;
/// Get reference to peer.
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData, Self::Specialization>;
fn peers(&self) -> &Vec<Peer<Self::PeerData, Self::Specialization>>;
fn mut_peers<F: FnOnce(&mut Vec<Peer<Self::PeerData, Self::Specialization>>)>(
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData>;
fn peers(&self) -> &Vec<Peer<Self::PeerData>>;
fn mut_peers<F: FnOnce(&mut Vec<Peer<Self::PeerData>>)>(
&mut self,
closure: F,
);
@@ -636,7 +622,6 @@ pub trait TestNetFactory: Sized {
transaction_pool: Arc::new(EmptyTransactionPool),
protocol_id: ProtocolId::from(&b"test-protocol-name"[..]),
import_queue,
specialization: self::SpecializationFactory::create(),
block_announce_validator: Box::new(DefaultBlockAnnounceValidator::new(client.clone()))
}).unwrap();
@@ -712,7 +697,6 @@ pub trait TestNetFactory: Sized {
transaction_pool: Arc::new(EmptyTransactionPool),
protocol_id: ProtocolId::from(&b"test-protocol-name"[..]),
import_queue,
specialization: self::SpecializationFactory::create(),
block_announce_validator: Box::new(DefaultBlockAnnounceValidator::new(client.clone()))
}).unwrap();
@@ -784,7 +768,6 @@ pub trait TestNetFactory: Sized {
// We poll `imported_blocks_stream`.
while let Ok(Async::Ready(Some(notification))) = peer.imported_blocks_stream.poll() {
peer.network.on_block_imported(
notification.hash,
notification.header,
Vec::new(),
true,
@@ -805,11 +788,10 @@ pub trait TestNetFactory: Sized {
}
pub struct TestNet {
peers: Vec<Peer<(), DummySpecialization>>,
peers: Vec<Peer<()>>,
}
impl TestNetFactory for TestNet {
type Specialization = DummySpecialization;
type Verifier = PassThroughVerifier;
type PeerData = ();
@@ -826,15 +808,15 @@ impl TestNetFactory for TestNet {
PassThroughVerifier(false)
}
fn peer(&mut self, i: usize) -> &mut Peer<(), Self::Specialization> {
fn peer(&mut self, i: usize) -> &mut Peer<()> {
&mut self.peers[i]
}
fn peers(&self) -> &Vec<Peer<(), Self::Specialization>> {
fn peers(&self) -> &Vec<Peer<()>> {
&self.peers
}
fn mut_peers<F: FnOnce(&mut Vec<Peer<(), Self::Specialization>>)>(&mut self, closure: F) {
fn mut_peers<F: FnOnce(&mut Vec<Peer<()>>)>(&mut self, closure: F) {
closure(&mut self.peers);
}
}
@@ -858,7 +840,6 @@ impl JustificationImport<Block> for ForceFinalized {
pub struct JustificationTestNet(TestNet);
impl TestNetFactory for JustificationTestNet {
type Specialization = DummySpecialization;
type Verifier = PassThroughVerifier;
type PeerData = ();
@@ -870,17 +851,16 @@ impl TestNetFactory for JustificationTestNet {
self.0.make_verifier(client, config, peer_data)
}
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData, Self::Specialization> {
fn peer(&mut self, i: usize) -> &mut Peer<Self::PeerData> {
self.0.peer(i)
}
fn peers(&self) -> &Vec<Peer<Self::PeerData, Self::Specialization>> {
fn peers(&self) -> &Vec<Peer<Self::PeerData>> {
self.0.peers()
}
fn mut_peers<F: FnOnce(
&mut Vec<Peer<Self::PeerData,
Self::Specialization>>,
&mut Vec<Peer<Self::PeerData>>,
)>(&mut self, closure: F) {
self.0.mut_peers(closure)
}
+14 -61
View File
@@ -35,7 +35,7 @@ use futures::{
use sc_keystore::{Store as Keystore};
use log::{info, warn, error};
use sc_network::config::{FinalityProofProvider, OnDemand, BoxFinalityProofRequestBuilder};
use sc_network::{NetworkService, NetworkStateInfo, specialization::NetworkSpecialization};
use sc_network::{NetworkService, NetworkStateInfo};
use parking_lot::{Mutex, RwLock};
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{
@@ -102,7 +102,6 @@ pub type BackgroundTask = Pin<Box<dyn Future<Output=()> + Send>>;
///
/// - [`with_select_chain`](ServiceBuilder::with_select_chain)
/// - [`with_import_queue`](ServiceBuilder::with_import_queue)
/// - [`with_network_protocol`](ServiceBuilder::with_network_protocol)
/// - [`with_finality_proof_provider`](ServiceBuilder::with_finality_proof_provider)
/// - [`with_transaction_pool`](ServiceBuilder::with_transaction_pool)
///
@@ -112,7 +111,7 @@ pub type BackgroundTask = Pin<Box<dyn Future<Output=()> + Send>>;
/// generics is done when you call `build`.
///
pub struct ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
TNetP, TExPool, TRpc, Backend>
TExPool, TRpc, Backend>
{
config: Configuration<TGen, TCSExt>,
pub (crate) client: Arc<TCl>,
@@ -123,7 +122,6 @@ pub struct ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TF
pub (crate) import_queue: TImpQu,
finality_proof_request_builder: Option<TFprb>,
finality_proof_provider: Option<TFpp>,
network_protocol: TNetP,
transaction_pool: Arc<TExPool>,
rpc_extensions: TRpc,
remote_backend: Option<Arc<dyn RemoteBlockchain<TBl>>>,
@@ -266,7 +264,7 @@ fn new_full_parts<TBl, TRtApi, TExecDisp, TGen, TCSExt>(
Ok((client, backend, keystore))
}
impl<TGen, TCSExt> ServiceBuilder<(), (), TGen, TCSExt, (), (), (), (), (), (), (), (), (), ()>
impl<TGen, TCSExt> ServiceBuilder<(), (), TGen, TCSExt, (), (), (), (), (), (), (), (), ()>
where TGen: RuntimeGenesis, TCSExt: Extension {
/// Start the service builder with a configuration.
pub fn new_full<TBl: BlockT, TRtApi, TExecDisp: NativeExecutionDispatch + 'static>(
@@ -284,7 +282,6 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
Arc<dyn FinalityProofProvider<TBl>>,
(),
(),
(),
TFullBackend<TBl>,
>, Error> {
let (client, backend, keystore) = new_full_parts(&config)?;
@@ -301,7 +298,6 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
import_queue: (),
finality_proof_request_builder: None,
finality_proof_provider: None,
network_protocol: (),
transaction_pool: Arc::new(()),
rpc_extensions: Default::default(),
remote_backend: None,
@@ -327,7 +323,6 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
Arc<dyn FinalityProofProvider<TBl>>,
(),
(),
(),
TLightBackend<TBl>,
>, Error> {
let keystore = match &config.keystore {
@@ -388,7 +383,6 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
import_queue: (),
finality_proof_request_builder: None,
finality_proof_provider: None,
network_protocol: (),
transaction_pool: Arc::new(()),
rpc_extensions: Default::default(),
remote_backend: Some(remote_blockchain),
@@ -399,9 +393,9 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
}
}
impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TExPool, TRpc, Backend>
impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, TRpc, Backend>
ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
TNetP, TExPool, TRpc, Backend> {
TExPool, TRpc, Backend> {
/// Returns a reference to the client that was stored in this builder.
pub fn client(&self) -> &Arc<TCl> {
@@ -449,7 +443,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
&Configuration<TGen, TCSExt>, &Arc<Backend>
) -> Result<Option<USc>, Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, USc, TImpQu, TFprb, TFpp,
TNetP, TExPool, TRpc, Backend>, Error> {
TExPool, TRpc, Backend>, Error> {
let select_chain = select_chain_builder(&self.config, &self.backend)?;
Ok(ServiceBuilder {
@@ -462,7 +456,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
import_queue: self.import_queue,
finality_proof_request_builder: self.finality_proof_request_builder,
finality_proof_provider: self.finality_proof_provider,
network_protocol: self.network_protocol,
transaction_pool: self.transaction_pool,
rpc_extensions: self.rpc_extensions,
remote_backend: self.remote_backend,
@@ -477,7 +470,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
self,
builder: impl FnOnce(&Configuration<TGen, TCSExt>, &Arc<Backend>) -> Result<USc, Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, USc, TImpQu, TFprb, TFpp,
TNetP, TExPool, TRpc, Backend>, Error> {
TExPool, TRpc, Backend>, Error> {
self.with_opt_select_chain(|cfg, b| builder(cfg, b).map(Option::Some))
}
@@ -487,7 +480,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
builder: impl FnOnce(&Configuration<TGen, TCSExt>, Arc<TCl>, Option<TSc>, Arc<TExPool>)
-> Result<UImpQu, Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, UImpQu, TFprb, TFpp,
TNetP, TExPool, TRpc, Backend>, Error>
TExPool, TRpc, Backend>, Error>
where TSc: Clone {
let import_queue = builder(
&self.config,
@@ -506,35 +499,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
import_queue,
finality_proof_request_builder: self.finality_proof_request_builder,
finality_proof_provider: self.finality_proof_provider,
network_protocol: self.network_protocol,
transaction_pool: self.transaction_pool,
rpc_extensions: self.rpc_extensions,
remote_backend: self.remote_backend,
background_tasks: self.background_tasks,
marker: self.marker,
prometheus_registry: self.prometheus_registry,
})
}
/// Defines which network specialization protocol to use.
pub fn with_network_protocol<UNetP>(
self,
network_protocol_builder: impl FnOnce(&Configuration<TGen, TCSExt>) -> Result<UNetP, Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
UNetP, TExPool, TRpc, Backend>, Error> {
let network_protocol = network_protocol_builder(&self.config)?;
Ok(ServiceBuilder {
config: self.config,
client: self.client,
backend: self.backend,
keystore: self.keystore,
fetcher: self.fetcher,
select_chain: self.select_chain,
import_queue: self.import_queue,
finality_proof_request_builder: self.finality_proof_request_builder,
finality_proof_provider: self.finality_proof_provider,
network_protocol,
transaction_pool: self.transaction_pool,
rpc_extensions: self.rpc_extensions,
remote_backend: self.remote_backend,
@@ -559,7 +523,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
TImpQu,
TFprb,
Arc<dyn FinalityProofProvider<TBl>>,
TNetP,
TExPool,
TRpc,
Backend,
@@ -576,7 +539,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
import_queue: self.import_queue,
finality_proof_request_builder: self.finality_proof_request_builder,
finality_proof_provider,
network_protocol: self.network_protocol,
transaction_pool: self.transaction_pool,
rpc_extensions: self.rpc_extensions,
remote_backend: self.remote_backend,
@@ -601,7 +563,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
TImpQu,
TFprb,
Arc<dyn FinalityProofProvider<TBl>>,
TNetP,
TExPool,
TRpc,
Backend,
@@ -621,7 +582,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
Arc<TExPool>,
) -> Result<(UImpQu, Option<UFprb>), Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, UImpQu, UFprb, TFpp,
TNetP, TExPool, TRpc, Backend>, Error>
TExPool, TRpc, Backend>, Error>
where TSc: Clone, TFchr: Clone {
let (import_queue, fprb) = builder(
&self.config,
@@ -642,7 +603,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
import_queue,
finality_proof_request_builder: fprb,
finality_proof_provider: self.finality_proof_provider,
network_protocol: self.network_protocol,
transaction_pool: self.transaction_pool,
rpc_extensions: self.rpc_extensions,
remote_backend: self.remote_backend,
@@ -664,7 +624,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
Arc<TExPool>,
) -> Result<(UImpQu, UFprb), Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, UImpQu, UFprb, TFpp,
TNetP, TExPool, TRpc, Backend>, Error>
TExPool, TRpc, Backend>, Error>
where TSc: Clone, TFchr: Clone {
self.with_import_queue_and_opt_fprb(|cfg, cl, b, f, sc, tx|
builder(cfg, cl, b, f, sc, tx)
@@ -681,7 +641,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
Option<TFchr>,
) -> Result<(UExPool, Option<BackgroundTask>), Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
TNetP, UExPool, TRpc, Backend>, Error>
UExPool, TRpc, Backend>, Error>
where TSc: Clone, TFchr: Clone {
let (transaction_pool, background_task) = transaction_pool_builder(
self.config.transaction_pool.clone(),
@@ -703,7 +663,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
import_queue: self.import_queue,
finality_proof_request_builder: self.finality_proof_request_builder,
finality_proof_provider: self.finality_proof_provider,
network_protocol: self.network_protocol,
transaction_pool: Arc::new(transaction_pool),
rpc_extensions: self.rpc_extensions,
remote_backend: self.remote_backend,
@@ -718,7 +677,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
self,
rpc_ext_builder: impl FnOnce(&Self) -> Result<URpc, Error>,
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
TNetP, TExPool, URpc, Backend>, Error>
TExPool, URpc, Backend>, Error>
where TSc: Clone, TFchr: Clone {
let rpc_extensions = rpc_ext_builder(&self)?;
@@ -732,7 +691,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
import_queue: self.import_queue,
finality_proof_request_builder: self.finality_proof_request_builder,
finality_proof_provider: self.finality_proof_provider,
network_protocol: self.network_protocol,
transaction_pool: self.transaction_pool,
rpc_extensions,
remote_backend: self.remote_backend,
@@ -754,7 +712,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TEx
import_queue: self.import_queue,
finality_proof_request_builder: self.finality_proof_request_builder,
finality_proof_provider: self.finality_proof_provider,
network_protocol: self.network_protocol,
transaction_pool: self.transaction_pool,
rpc_extensions: self.rpc_extensions,
remote_backend: self.remote_backend,
@@ -801,7 +758,7 @@ pub trait ServiceBuilderCommand {
) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
}
impl<TBl, TRtApi, TGen, TCSExt, TBackend, TExec, TSc, TImpQu, TNetP, TExPool, TRpc>
impl<TBl, TRtApi, TGen, TCSExt, TBackend, TExec, TSc, TImpQu, TExPool, TRpc>
ServiceBuilder<
TBl,
TRtApi,
@@ -813,7 +770,6 @@ ServiceBuilder<
TImpQu,
BoxFinalityProofRequestBuilder<TBl>,
Arc<dyn FinalityProofProvider<TBl>>,
TNetP,
TExPool,
TRpc,
TBackend,
@@ -834,7 +790,6 @@ ServiceBuilder<
TExec: 'static + sc_client::CallExecutor<TBl> + Send + Sync + Clone,
TSc: Clone,
TImpQu: 'static + ImportQueue<TBl>,
TNetP: NetworkSpecialization<TBl>,
TExPool: MaintainedTransactionPool<Block=TBl, Hash = <TBl as BlockT>::Hash> + MallocSizeOfWasm + 'static,
TRpc: sc_rpc::RpcExtension<sc_rpc::Metadata> + Clone,
{
@@ -851,7 +806,7 @@ ServiceBuilder<
Client<TBackend, TExec, TBl, TRtApi>,
TSc,
NetworkStatus<TBl>,
NetworkService<TBl, TNetP, <TBl as BlockT>::Hash>,
NetworkService<TBl, <TBl as BlockT>::Hash>,
TExPool,
sc_offchain::OffchainWorkers<
Client<TBackend, TExec, TBl, TRtApi>,
@@ -870,7 +825,6 @@ ServiceBuilder<
import_queue,
finality_proof_request_builder,
finality_proof_provider,
network_protocol,
transaction_pool,
rpc_extensions,
remote_backend,
@@ -951,7 +905,6 @@ ServiceBuilder<
transaction_pool: transaction_pool_adapter.clone() as _,
import_queue,
protocol_id,
specialization: network_protocol,
block_announce_validator,
};
+2 -2
View File
@@ -46,12 +46,12 @@ pub fn build_spec<G, E>(spec: ChainSpec<G, E>, raw: bool) -> error::Result<Strin
impl<
TBl, TRtApi, TGen, TCSExt, TBackend,
TExecDisp, TFchr, TSc, TImpQu, TFprb, TFpp, TNetP,
TExecDisp, TFchr, TSc, TImpQu, TFprb, TFpp,
TExPool, TRpc, Backend
> ServiceBuilderCommand for ServiceBuilder<
TBl, TRtApi, TGen, TCSExt,
Client<TBackend, LocalCallExecutor<TBackend, NativeExecutor<TExecDisp>>, TBl, TRtApi>,
TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TExPool, TRpc, Backend
TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, TRpc, Backend
> where
TBl: BlockT,
TBackend: 'static + sc_client_api::backend::Backend<TBl> + Send,
+7 -15
View File
@@ -45,10 +45,7 @@ use futures::{
sink::SinkExt,
task::{Spawn, FutureObj, SpawnError},
};
use sc_network::{
NetworkService, network_state::NetworkState, specialization::NetworkSpecialization,
PeerId, ReportHandle,
};
use sc_network::{NetworkService, network_state::NetworkState, PeerId, ReportHandle};
use log::{log, warn, debug, error, Level};
use codec::{Encode, Decode};
use sp_runtime::generic::BlockId;
@@ -176,8 +173,6 @@ pub trait AbstractService: 'static + Future<Output = Result<(), Error>> +
type SelectChain: sp_consensus::SelectChain<Self::Block>;
/// Transaction pool.
type TransactionPool: TransactionPool<Block = Self::Block> + MallocSizeOfWasm;
/// Network specialization.
type NetworkSpecialization: NetworkSpecialization<Self::Block>;
/// Get event stream for telemetry connection established events.
fn telemetry_on_connect_stream(&self) -> futures::channel::mpsc::UnboundedReceiver<()>;
@@ -218,7 +213,7 @@ pub trait AbstractService: 'static + Future<Output = Result<(), Error>> +
/// Get shared network instance.
fn network(&self)
-> Arc<NetworkService<Self::Block, Self::NetworkSpecialization, <Self::Block as BlockT>::Hash>>;
-> Arc<NetworkService<Self::Block, <Self::Block as BlockT>::Hash>>;
/// Returns a receiver that periodically receives a status of the network.
fn network_status(&self, interval: Duration) -> mpsc::UnboundedReceiver<(NetworkStatus<Self::Block>, NetworkState)>;
@@ -230,9 +225,9 @@ pub trait AbstractService: 'static + Future<Output = Result<(), Error>> +
fn on_exit(&self) -> ::exit_future::Exit;
}
impl<TBl, TBackend, TExec, TRtApi, TSc, TNetSpec, TExPool, TOc> AbstractService for
impl<TBl, TBackend, TExec, TRtApi, TSc, TExPool, TOc> AbstractService for
Service<TBl, Client<TBackend, TExec, TBl, TRtApi>, TSc, NetworkStatus<TBl>,
NetworkService<TBl, TNetSpec, TBl::Hash>, TExPool, TOc>
NetworkService<TBl, TBl::Hash>, TExPool, TOc>
where
TBl: BlockT + Unpin,
TBackend: 'static + sc_client_api::backend::Backend<TBl>,
@@ -241,7 +236,6 @@ where
TSc: sp_consensus::SelectChain<TBl> + 'static + Clone + Send + Unpin,
TExPool: 'static + TransactionPool<Block = TBl> + MallocSizeOfWasm,
TOc: 'static + Send + Sync,
TNetSpec: NetworkSpecialization<TBl>,
{
type Block = TBl;
type Backend = TBackend;
@@ -249,7 +243,6 @@ where
type RuntimeApi = TRtApi;
type SelectChain = TSc;
type TransactionPool = TExPool;
type NetworkSpecialization = TNetSpec;
fn telemetry_on_connect_stream(&self) -> futures::channel::mpsc::UnboundedReceiver<()> {
let (sink, stream) = futures::channel::mpsc::unbounded();
@@ -315,7 +308,7 @@ where
}
fn network(&self)
-> Arc<NetworkService<Self::Block, Self::NetworkSpecialization, <Self::Block as BlockT>::Hash>>
-> Arc<NetworkService<Self::Block, <Self::Block as BlockT>::Hash>>
{
self.network.clone()
}
@@ -379,11 +372,10 @@ impl<TBl, TCl, TSc, TNetStatus, TNet, TTxPool, TOc> Spawn for
fn build_network_future<
B: BlockT,
C: sc_client::BlockchainEvents<B>,
S: sc_network::specialization::NetworkSpecialization<B>,
H: sc_network::ExHashT
> (
roles: Roles,
mut network: sc_network::NetworkWorker<B, S, H>,
mut network: sc_network::NetworkWorker<B, H>,
client: Arc<C>,
status_sinks: Arc<Mutex<status_sinks::StatusSinks<(NetworkStatus<B>, NetworkState)>>>,
mut rpc_rx: mpsc::UnboundedReceiver<sc_rpc::system::Request<B>>,
@@ -397,7 +389,7 @@ fn build_network_future<
// We poll `imported_blocks_stream`.
while let Poll::Ready(Some(notification)) = Pin::new(&mut imported_blocks_stream).poll_next(cx) {
network.on_block_imported(notification.hash, notification.header, Vec::new(), notification.is_new_best);
network.on_block_imported(notification.header, Vec::new(), notification.is_new_best);
}
// We poll `finality_notification_stream`, but we only take the last event.