From 7d6fdf708a8b460a139a0babb480ae8392b2160b Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Wed, 13 Jul 2022 15:04:43 +0300 Subject: [PATCH 1/3] Move `MultiaddrWithPeerId` and related parsing functions into `sc-network-common`, remove dependency on `sc-network` from `sc-chain-spec` --- Cargo.lock | 5 +- client/authority-discovery/Cargo.toml | 1 - client/authority-discovery/src/error.rs | 2 +- client/chain-spec/Cargo.toml | 2 +- client/chain-spec/src/chain_spec.rs | 2 +- client/chain-spec/src/lib.rs | 2 +- client/network/common/Cargo.toml | 1 + client/network/common/src/config.rs | 129 +++++++++++++++++++++++- client/network/src/config.rs | 129 +----------------------- client/network/src/service.rs | 3 +- client/network/src/service/tests.rs | 16 +-- client/network/test/src/lib.rs | 6 +- client/rpc/Cargo.toml | 1 + client/rpc/src/system/tests.rs | 2 +- client/service/src/config.rs | 5 +- 15 files changed, 155 insertions(+), 151 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 38063e8060835..a7ad1d1f881c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7714,7 +7714,6 @@ dependencies = [ "quickcheck", "rand 0.7.3", "sc-client-api", - "sc-network", "sc-network-common", "sp-api", "sp-authority-discovery", @@ -7777,7 +7776,7 @@ dependencies = [ "memmap2 0.5.0", "parity-scale-codec", "sc-chain-spec-derive", - "sc-network", + "sc-network-common", "sc-telemetry", "serde", "serde_json", @@ -8408,6 +8407,7 @@ dependencies = [ "prost-build", "sc-consensus", "sc-peerset", + "serde", "smallvec", "sp-consensus", "sp-finality-grandpa", @@ -8592,6 +8592,7 @@ dependencies = [ "sc-chain-spec", "sc-client-api", "sc-network", + "sc-network-common", "sc-rpc-api", "sc-tracing", "sc-transaction-pool", diff --git a/client/authority-discovery/Cargo.toml b/client/authority-discovery/Cargo.toml index 544df4c8d4812..b7a140f24a111 100644 --- a/client/authority-discovery/Cargo.toml +++ b/client/authority-discovery/Cargo.toml @@ -29,7 +29,6 @@ thiserror = "1.0" prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0.10.0-dev", path = "../../utils/prometheus" } sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-network-common = { version = "0.10.0-dev", path = "../network/common" } -sc-network = { version = "0.10.0-dev", path = "../network" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } sp-authority-discovery = { version = "4.0.0-dev", path = "../../primitives/authority-discovery" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } diff --git a/client/authority-discovery/src/error.rs b/client/authority-discovery/src/error.rs index bce39069ef7c7..285a2714b81f5 100644 --- a/client/authority-discovery/src/error.rs +++ b/client/authority-discovery/src/error.rs @@ -57,7 +57,7 @@ pub enum Error { ParsingMultiaddress(#[from] libp2p::core::multiaddr::Error), #[error("Failed to parse a libp2p key.")] - ParsingLibp2pIdentity(#[from] sc_network::DecodingError), + ParsingLibp2pIdentity(#[from] libp2p::identity::error::DecodingError), #[error("Failed to sign using a specific public key.")] MissingSignature(CryptoTypePublicPair), diff --git a/client/chain-spec/Cargo.toml b/client/chain-spec/Cargo.toml index 6ab559dea46fd..bd4ee548e296b 100644 --- a/client/chain-spec/Cargo.toml +++ b/client/chain-spec/Cargo.toml @@ -19,7 +19,7 @@ memmap2 = "0.5.0" serde = { version = "1.0.136", features = ["derive"] } serde_json = "1.0.79" sc-chain-spec-derive = { version = "4.0.0-dev", path = "./derive" } -sc-network = { version = "0.10.0-dev", path = "../network" } +sc-network-common = { version = "0.10.0-dev", path = "../network/common" } sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" } sp-core = { version = "6.0.0", path = "../../primitives/core" } sp-runtime = { version = "6.0.0", path = "../../primitives/runtime" } diff --git a/client/chain-spec/src/chain_spec.rs b/client/chain-spec/src/chain_spec.rs index 5aafc28524dbf..2cc9f356e4df7 100644 --- a/client/chain-spec/src/chain_spec.rs +++ b/client/chain-spec/src/chain_spec.rs @@ -20,7 +20,7 @@ #![warn(missing_docs)] use crate::{extension::GetExtension, ChainType, Properties, RuntimeGenesis}; -use sc_network::config::MultiaddrWithPeerId; +use sc_network_common::config::MultiaddrWithPeerId; use sc_telemetry::TelemetryEndpoints; use serde::{Deserialize, Serialize}; use serde_json as json; diff --git a/client/chain-spec/src/lib.rs b/client/chain-spec/src/lib.rs index 73d3e1af15492..9d2cc728b8288 100644 --- a/client/chain-spec/src/lib.rs +++ b/client/chain-spec/src/lib.rs @@ -184,7 +184,7 @@ pub use extension::{ }; pub use sc_chain_spec_derive::{ChainSpecExtension, ChainSpecGroup}; -use sc_network::config::MultiaddrWithPeerId; +use sc_network_common::config::MultiaddrWithPeerId; use sc_telemetry::TelemetryEndpoints; use serde::{de::DeserializeOwned, Serialize}; use sp_core::storage::Storage; diff --git a/client/network/common/Cargo.toml b/client/network/common/Cargo.toml index 1b10bd248292c..8f0702e05cac5 100644 --- a/client/network/common/Cargo.toml +++ b/client/network/common/Cargo.toml @@ -28,6 +28,7 @@ libp2p = "0.46.1" smallvec = "1.8.0" sc-consensus = { version = "0.10.0-dev", path = "../../consensus/common" } sc-peerset = { version = "4.0.0-dev", path = "../../peerset" } +serde = { version = "1.0.136", features = ["derive"] } sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/common" } sp-finality-grandpa = { version = "4.0.0-dev", path = "../../../primitives/finality-grandpa" } sp-runtime = { version = "6.0.0", path = "../../../primitives/runtime" } diff --git a/client/network/common/src/config.rs b/client/network/common/src/config.rs index 92f8df5cd380f..c2e61424c88e0 100644 --- a/client/network/common/src/config.rs +++ b/client/network/common/src/config.rs @@ -18,7 +18,8 @@ //! Configuration of the networking layer. -use std::{fmt, str}; +use libp2p::{multiaddr, Multiaddr, PeerId}; +use std::{fmt, str, str::FromStr}; /// Name of a protocol, transmitted on the wire. Should be unique for each chain. Always UTF-8. #[derive(Clone, PartialEq, Eq, Hash)] @@ -42,3 +43,129 @@ impl fmt::Debug for ProtocolId { fmt::Debug::fmt(self.as_ref(), f) } } + +/// Parses a string address and splits it into Multiaddress and PeerId, if +/// valid. +/// +/// # Example +/// +/// ``` +/// # use libp2p::{Multiaddr, PeerId}; +/// # use sc_network_common::config::parse_str_addr; +/// let (peer_id, addr) = parse_str_addr( +/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV" +/// ).unwrap(); +/// assert_eq!(peer_id, "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse::().unwrap()); +/// assert_eq!(addr, "/ip4/198.51.100.19/tcp/30333".parse::().unwrap()); +/// ``` +pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> { + let addr: Multiaddr = addr_str.parse()?; + parse_addr(addr) +} + +/// Splits a Multiaddress into a Multiaddress and PeerId. +pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr> { + let who = match addr.pop() { + Some(multiaddr::Protocol::P2p(key)) => + PeerId::from_multihash(key).map_err(|_| ParseErr::InvalidPeerId)?, + _ => return Err(ParseErr::PeerIdMissing), + }; + + Ok((who, addr)) +} + +/// Address of a node, including its identity. +/// +/// This struct represents a decoded version of a multiaddress that ends with `/p2p/`. +/// +/// # Example +/// +/// ``` +/// # use libp2p::{Multiaddr, PeerId}; +/// # use sc_network_common::config::MultiaddrWithPeerId; +/// let addr: MultiaddrWithPeerId = +/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse().unwrap(); +/// assert_eq!(addr.peer_id.to_base58(), "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"); +/// assert_eq!(addr.multiaddr.to_string(), "/ip4/198.51.100.19/tcp/30333"); +/// ``` +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] +#[serde(try_from = "String", into = "String")] +pub struct MultiaddrWithPeerId { + /// Address of the node. + pub multiaddr: Multiaddr, + /// Its identity. + pub peer_id: PeerId, +} + +impl MultiaddrWithPeerId { + /// Concatenates the multiaddress and peer ID into one multiaddress containing both. + pub fn concat(&self) -> Multiaddr { + let proto = multiaddr::Protocol::P2p(From::from(self.peer_id)); + self.multiaddr.clone().with(proto) + } +} + +impl fmt::Display for MultiaddrWithPeerId { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.concat(), f) + } +} + +impl FromStr for MultiaddrWithPeerId { + type Err = ParseErr; + + fn from_str(s: &str) -> Result { + let (peer_id, multiaddr) = parse_str_addr(s)?; + Ok(Self { peer_id, multiaddr }) + } +} + +impl From for String { + fn from(ma: MultiaddrWithPeerId) -> String { + format!("{}", ma) + } +} + +impl TryFrom for MultiaddrWithPeerId { + type Error = ParseErr; + fn try_from(string: String) -> Result { + string.parse() + } +} + +/// Error that can be generated by `parse_str_addr`. +#[derive(Debug)] +pub enum ParseErr { + /// Error while parsing the multiaddress. + MultiaddrParse(multiaddr::Error), + /// Multihash of the peer ID is invalid. + InvalidPeerId, + /// The peer ID is missing from the address. + PeerIdMissing, +} + +impl fmt::Display for ParseErr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MultiaddrParse(err) => write!(f, "{}", err), + Self::InvalidPeerId => write!(f, "Peer id at the end of the address is invalid"), + Self::PeerIdMissing => write!(f, "Peer id is missing from the address"), + } + } +} + +impl std::error::Error for ParseErr { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::MultiaddrParse(err) => Some(err), + Self::InvalidPeerId => None, + Self::PeerIdMissing => None, + } + } +} + +impl From for ParseErr { + fn from(err: multiaddr::Error) -> ParseErr { + Self::MultiaddrParse(err) + } +} diff --git a/client/network/src/config.rs b/client/network/src/config.rs index afd61cae6c83b..52fa28e76e207 100644 --- a/client/network/src/config.rs +++ b/client/network/src/config.rs @@ -37,11 +37,11 @@ use core::{fmt, iter}; use futures::future; use libp2p::{ identity::{ed25519, Keypair}, - multiaddr, Multiaddr, PeerId, + multiaddr, Multiaddr, }; use prometheus_endpoint::Registry; use sc_consensus::ImportQueue; -use sc_network_common::sync::ChainSync; +use sc_network_common::{config::MultiaddrWithPeerId, sync::ChainSync}; use sp_runtime::traits::Block as BlockT; use std::{ borrow::Cow, @@ -54,7 +54,6 @@ use std::{ path::{Path, PathBuf}, pin::Pin, str, - str::FromStr, sync::Arc, }; use zeroize::Zeroize; @@ -225,130 +224,6 @@ impl TransactionPool for EmptyTransaction } } -/// Parses a string address and splits it into Multiaddress and PeerId, if -/// valid. -/// -/// # Example -/// -/// ``` -/// # use sc_network::{Multiaddr, PeerId, config::parse_str_addr}; -/// let (peer_id, addr) = parse_str_addr( -/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV" -/// ).unwrap(); -/// assert_eq!(peer_id, "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse::().unwrap()); -/// assert_eq!(addr, "/ip4/198.51.100.19/tcp/30333".parse::().unwrap()); -/// ``` -pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> { - let addr: Multiaddr = addr_str.parse()?; - parse_addr(addr) -} - -/// Splits a Multiaddress into a Multiaddress and PeerId. -pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr> { - let who = match addr.pop() { - Some(multiaddr::Protocol::P2p(key)) => - PeerId::from_multihash(key).map_err(|_| ParseErr::InvalidPeerId)?, - _ => return Err(ParseErr::PeerIdMissing), - }; - - Ok((who, addr)) -} - -/// Address of a node, including its identity. -/// -/// This struct represents a decoded version of a multiaddress that ends with `/p2p/`. -/// -/// # Example -/// -/// ``` -/// # use sc_network::{Multiaddr, PeerId, config::MultiaddrWithPeerId}; -/// let addr: MultiaddrWithPeerId = -/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse().unwrap(); -/// assert_eq!(addr.peer_id.to_base58(), "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"); -/// assert_eq!(addr.multiaddr.to_string(), "/ip4/198.51.100.19/tcp/30333"); -/// ``` -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] -#[serde(try_from = "String", into = "String")] -pub struct MultiaddrWithPeerId { - /// Address of the node. - pub multiaddr: Multiaddr, - /// Its identity. - pub peer_id: PeerId, -} - -impl MultiaddrWithPeerId { - /// Concatenates the multiaddress and peer ID into one multiaddress containing both. - pub fn concat(&self) -> Multiaddr { - let proto = multiaddr::Protocol::P2p(From::from(self.peer_id)); - self.multiaddr.clone().with(proto) - } -} - -impl fmt::Display for MultiaddrWithPeerId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.concat(), f) - } -} - -impl FromStr for MultiaddrWithPeerId { - type Err = ParseErr; - - fn from_str(s: &str) -> Result { - let (peer_id, multiaddr) = parse_str_addr(s)?; - Ok(Self { peer_id, multiaddr }) - } -} - -impl From for String { - fn from(ma: MultiaddrWithPeerId) -> String { - format!("{}", ma) - } -} - -impl TryFrom for MultiaddrWithPeerId { - type Error = ParseErr; - fn try_from(string: String) -> Result { - string.parse() - } -} - -/// Error that can be generated by `parse_str_addr`. -#[derive(Debug)] -pub enum ParseErr { - /// Error while parsing the multiaddress. - MultiaddrParse(multiaddr::Error), - /// Multihash of the peer ID is invalid. - InvalidPeerId, - /// The peer ID is missing from the address. - PeerIdMissing, -} - -impl fmt::Display for ParseErr { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MultiaddrParse(err) => write!(f, "{}", err), - Self::InvalidPeerId => write!(f, "Peer id at the end of the address is invalid"), - Self::PeerIdMissing => write!(f, "Peer id is missing from the address"), - } - } -} - -impl std::error::Error for ParseErr { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::MultiaddrParse(err) => Some(err), - Self::InvalidPeerId => None, - Self::PeerIdMissing => None, - } - } -} - -impl From for ParseErr { - fn from(err: multiaddr::Error) -> ParseErr { - Self::MultiaddrParse(err) - } -} - /// Sync operation mode. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum SyncMode { diff --git a/client/network/src/service.rs b/client/network/src/service.rs index bf15a9250d82c..d36e310795818 100644 --- a/client/network/src/service.rs +++ b/client/network/src/service.rs @@ -30,7 +30,7 @@ use crate::{ behaviour::{self, Behaviour, BehaviourOut}, bitswap::Bitswap, - config::{parse_str_addr, Params, TransportConfig}, + config::{Params, TransportConfig}, discovery::DiscoveryConfig, error::Error, network_state::{ @@ -62,6 +62,7 @@ use parking_lot::Mutex; use sc_client_api::{BlockBackend, ProofProvider}; use sc_consensus::{BlockImportError, BlockImportStatus, ImportQueue, Link}; use sc_network_common::{ + config::parse_str_addr, protocol::event::{DhtEvent, Event}, request_responses::{IfDisconnected, RequestFailure}, service::{ diff --git a/client/network/src/service/tests.rs b/client/network/src/service/tests.rs index 6ccca17650b67..e2fe58423abfe 100644 --- a/client/network/src/service/tests.rs +++ b/client/network/src/service/tests.rs @@ -21,7 +21,7 @@ use crate::{config, NetworkService, NetworkWorker}; use futures::prelude::*; use libp2p::PeerId; use sc_network_common::{ - config::ProtocolId, + config::{MultiaddrWithPeerId, ProtocolId}, protocol::event::Event, service::{NetworkEventStream, NetworkNotification, NetworkPeers, NetworkStateInfo}, }; @@ -194,7 +194,7 @@ fn build_nodes_one_proto() -> ( fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: config::SetConfig { - reserved_nodes: vec![config::MultiaddrWithPeerId { + reserved_nodes: vec![MultiaddrWithPeerId { multiaddr: listen_addr, peer_id: node1.local_peer_id(), }], @@ -383,7 +383,7 @@ fn lots_of_incoming_peers_works() { fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: config::SetConfig { - reserved_nodes: vec![config::MultiaddrWithPeerId { + reserved_nodes: vec![MultiaddrWithPeerId { multiaddr: listen_addr.clone(), peer_id: main_node_peer_id, }], @@ -513,7 +513,7 @@ fn fallback_name_working() { fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: config::SetConfig { - reserved_nodes: vec![config::MultiaddrWithPeerId { + reserved_nodes: vec![MultiaddrWithPeerId { multiaddr: listen_addr, peer_id: node1.local_peer_id(), }], @@ -584,7 +584,7 @@ fn ensure_listen_addresses_consistent_with_transport_not_memory() { #[should_panic(expected = "don't match the transport")] fn ensure_boot_node_addresses_consistent_with_transport_memory() { let listen_addr = config::build_multiaddr![Memory(rand::random::())]; - let boot_node = config::MultiaddrWithPeerId { + let boot_node = MultiaddrWithPeerId { multiaddr: config::build_multiaddr![Ip4([127, 0, 0, 1]), Tcp(0_u16)], peer_id: PeerId::random(), }; @@ -601,7 +601,7 @@ fn ensure_boot_node_addresses_consistent_with_transport_memory() { #[should_panic(expected = "don't match the transport")] fn ensure_boot_node_addresses_consistent_with_transport_not_memory() { let listen_addr = config::build_multiaddr![Ip4([127, 0, 0, 1]), Tcp(0_u16)]; - let boot_node = config::MultiaddrWithPeerId { + let boot_node = MultiaddrWithPeerId { multiaddr: config::build_multiaddr![Memory(rand::random::())], peer_id: PeerId::random(), }; @@ -617,7 +617,7 @@ fn ensure_boot_node_addresses_consistent_with_transport_not_memory() { #[should_panic(expected = "don't match the transport")] fn ensure_reserved_node_addresses_consistent_with_transport_memory() { let listen_addr = config::build_multiaddr![Memory(rand::random::())]; - let reserved_node = config::MultiaddrWithPeerId { + let reserved_node = MultiaddrWithPeerId { multiaddr: config::build_multiaddr![Ip4([127, 0, 0, 1]), Tcp(0_u16)], peer_id: PeerId::random(), }; @@ -637,7 +637,7 @@ fn ensure_reserved_node_addresses_consistent_with_transport_memory() { #[should_panic(expected = "don't match the transport")] fn ensure_reserved_node_addresses_consistent_with_transport_not_memory() { let listen_addr = config::build_multiaddr![Ip4([127, 0, 0, 1]), Tcp(0_u16)]; - let reserved_node = config::MultiaddrWithPeerId { + let reserved_node = MultiaddrWithPeerId { multiaddr: config::build_multiaddr![Memory(rand::random::())], peer_id: PeerId::random(), }; diff --git a/client/network/test/src/lib.rs b/client/network/test/src/lib.rs index 3ba663aba2267..fbe56f463d0f3 100644 --- a/client/network/test/src/lib.rs +++ b/client/network/test/src/lib.rs @@ -51,13 +51,13 @@ use sc_consensus::{ pub use sc_network::config::EmptyTransactionPool; use sc_network::{ config::{ - MultiaddrWithPeerId, NetworkConfiguration, NonDefaultSetConfig, NonReservedPeerMode, Role, - SyncMode, TransportConfig, + NetworkConfiguration, NonDefaultSetConfig, NonReservedPeerMode, Role, SyncMode, + TransportConfig, }, Multiaddr, NetworkService, NetworkWorker, }; -pub use sc_network_common::config::ProtocolId; use sc_network_common::{ + config::{MultiaddrWithPeerId, ProtocolId}, service::{NetworkBlock, NetworkStateInfo, NetworkSyncForkRequest}, sync::warp::{AuthorityList, EncodedProof, SetId, VerificationResult, WarpSyncProvider}, }; diff --git a/client/rpc/Cargo.toml b/client/rpc/Cargo.toml index 5a05ae6e29df1..2381323d25a24 100644 --- a/client/rpc/Cargo.toml +++ b/client/rpc/Cargo.toml @@ -46,6 +46,7 @@ assert_matches = "1.3.0" lazy_static = "1.4.0" sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sc-network = { version = "0.10.0-dev", path = "../network" } +sc-network-common = { version = "0.10.0-dev", path = "../network/common" } sc-transaction-pool = { version = "4.0.0-dev", path = "../transaction-pool" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } tokio = "1.17.0" diff --git a/client/rpc/src/system/tests.rs b/client/rpc/src/system/tests.rs index facad7a0b347a..2f91648008ff7 100644 --- a/client/rpc/src/system/tests.rs +++ b/client/rpc/src/system/tests.rs @@ -99,7 +99,7 @@ fn api>>(sync: T) -> RpcModule> { ); }, Request::NetworkAddReservedPeer(peer, sender) => { - let _ = match sc_network::config::parse_str_addr(&peer) { + let _ = match sc_network_common::config::parse_str_addr(&peer) { Ok(_) => sender.send(Ok(())), Err(s) => sender.send(Err(error::Error::MalformattedPeerArg(s.to_string()))), diff --git a/client/service/src/config.rs b/client/service/src/config.rs index 7860ff2281fe4..d7ca527b56e48 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -25,13 +25,12 @@ pub use sc_executor::WasmExecutionMethod; pub use sc_executor::WasmtimeInstantiationStrategy; pub use sc_network::{ config::{ - MultiaddrWithPeerId, NetworkConfiguration, NodeKeyConfig, NonDefaultSetConfig, Role, - SetConfig, TransportConfig, + NetworkConfiguration, NodeKeyConfig, NonDefaultSetConfig, Role, SetConfig, TransportConfig, }, Multiaddr, }; pub use sc_network_common::{ - config::ProtocolId, + config::{MultiaddrWithPeerId, ProtocolId}, request_responses::{ IncomingRequest, OutgoingResponse, ProtocolConfig as RequestResponseConfig, }, From 46cf3d249269fb11e8401ebaa626698210aeaaf7 Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Wed, 13 Jul 2022 15:17:02 +0300 Subject: [PATCH 2/3] Remove dependency on `sc-network` from `sc-offchain` --- Cargo.lock | 3 ++- client/offchain/Cargo.toml | 3 ++- client/offchain/src/api.rs | 5 +++-- client/offchain/src/lib.rs | 3 ++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a7ad1d1f881c8..9cdccd2473b78 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8529,6 +8529,7 @@ dependencies = [ "hyper", "hyper-rustls", "lazy_static", + "libp2p", "num_cpus", "once_cell", "parity-scale-codec", @@ -8537,8 +8538,8 @@ dependencies = [ "sc-block-builder", "sc-client-api", "sc-client-db", - "sc-network", "sc-network-common", + "sc-peerset", "sc-transaction-pool", "sc-transaction-pool-api", "sc-utils", diff --git a/client/offchain/Cargo.toml b/client/offchain/Cargo.toml index ab26c0c38596c..89b77dbb5fea7 100644 --- a/client/offchain/Cargo.toml +++ b/client/offchain/Cargo.toml @@ -21,6 +21,7 @@ futures-timer = "3.0.2" hex = "0.4" hyper = { version = "0.14.16", features = ["stream", "http2"] } hyper-rustls = { version = "0.23.0", features = ["http2"] } +libp2p = { version = "0.46.1", default-features = false } num_cpus = "1.13" once_cell = "1.8" parking_lot = "0.12.0" @@ -28,8 +29,8 @@ rand = "0.7.2" threadpool = "1.7" tracing = "0.1.29" sc-client-api = { version = "4.0.0-dev", path = "../api" } -sc-network = { version = "0.10.0-dev", path = "../network" } sc-network-common = { version = "0.10.0-dev", path = "../network/common" } +sc-peerset = { version = "4.0.0-dev", path = "../peerset" } sc-utils = { version = "4.0.0-dev", path = "../utils" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } sp-core = { version = "6.0.0", path = "../../primitives/core" } diff --git a/client/offchain/src/api.rs b/client/offchain/src/api.rs index f379ebad17bbf..5c8139d4505e7 100644 --- a/client/offchain/src/api.rs +++ b/client/offchain/src/api.rs @@ -22,7 +22,7 @@ use crate::NetworkProvider; use codec::{Decode, Encode}; use futures::Future; pub use http::SharedClient; -use sc_network::{Multiaddr, PeerId}; +use libp2p::{Multiaddr, PeerId}; use sp_core::{ offchain::{ self, HttpError, HttpRequestId, HttpRequestStatus, OffchainStorage, OpaqueMultiaddr, @@ -324,9 +324,10 @@ impl AsyncApi { #[cfg(test)] mod tests { use super::*; + use libp2p::PeerId; use sc_client_db::offchain::LocalStorage; - use sc_network::{PeerId, ReputationChange}; use sc_network_common::service::{NetworkPeers, NetworkStateInfo}; + use sc_peerset::ReputationChange; use sp_core::offchain::{DbExternalities, Externalities}; use std::{borrow::Cow, time::SystemTime}; diff --git a/client/offchain/src/lib.rs b/client/offchain/src/lib.rs index 14a2408e61a70..5eed142ff3871 100644 --- a/client/offchain/src/lib.rs +++ b/client/offchain/src/lib.rs @@ -246,9 +246,10 @@ pub async fn notification_future( mod tests { use super::*; use futures::executor::block_on; + use libp2p::{Multiaddr, PeerId}; use sc_block_builder::BlockBuilderProvider as _; use sc_client_api::Backend as _; - use sc_network::{Multiaddr, PeerId, ReputationChange}; + use sc_peerset::ReputationChange; use sc_transaction_pool::{BasicPool, FullChainApi}; use sc_transaction_pool_api::{InPoolTransaction, TransactionPool}; use sp_consensus::BlockOrigin; From 2de8fb454db2461905ea11e582502a3f5e10a4fa Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Wed, 13 Jul 2022 21:41:13 +0300 Subject: [PATCH 3/3] Remove dependency on `sc-network` from `sc-network-gossip` --- Cargo.lock | 2 +- client/network-gossip/Cargo.toml | 2 +- client/network-gossip/src/bridge.rs | 4 ++-- client/network-gossip/src/lib.rs | 2 +- client/network-gossip/src/state_machine.rs | 6 +++--- client/network-gossip/src/validator.rs | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9cdccd2473b78..6cbcc53b9c00c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8427,8 +8427,8 @@ dependencies = [ "log", "lru", "quickcheck", - "sc-network", "sc-network-common", + "sc-peerset", "sp-runtime", "substrate-prometheus-endpoint", "substrate-test-runtime-client", diff --git a/client/network-gossip/Cargo.toml b/client/network-gossip/Cargo.toml index 185c37985b585..8ecf2b9cec787 100644 --- a/client/network-gossip/Cargo.toml +++ b/client/network-gossip/Cargo.toml @@ -22,8 +22,8 @@ log = "0.4.17" lru = "0.7.5" tracing = "0.1.29" prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0.10.0-dev", path = "../../utils/prometheus" } -sc-network = { version = "0.10.0-dev", path = "../network" } sc-network-common = { version = "0.10.0-dev", path = "../network/common" } +sc-peerset = { version = "4.0.0-dev", path = "../peerset" } sp-runtime = { version = "6.0.0", path = "../../primitives/runtime" } [dev-dependencies] diff --git a/client/network-gossip/src/bridge.rs b/client/network-gossip/src/bridge.rs index 8a6c3358e4409..affd33889ecf3 100644 --- a/client/network-gossip/src/bridge.rs +++ b/client/network-gossip/src/bridge.rs @@ -21,8 +21,8 @@ use crate::{ Network, Validator, }; -use sc_network::ReputationChange; use sc_network_common::protocol::event::Event; +use sc_peerset::ReputationChange; use futures::{ channel::mpsc::{channel, Receiver, Sender}, @@ -152,7 +152,7 @@ impl GossipEngine { /// Send addressed message to the given peers. The message is not kept or multicast /// later on. - pub fn send_message(&mut self, who: Vec, data: Vec) { + pub fn send_message(&mut self, who: Vec, data: Vec) { for who in &who { self.state_machine.send_message(&mut *self.network, who, data.clone()); } diff --git a/client/network-gossip/src/lib.rs b/client/network-gossip/src/lib.rs index b9dff0bcd4d00..0fdde1feac6c6 100644 --- a/client/network-gossip/src/lib.rs +++ b/client/network-gossip/src/lib.rs @@ -67,7 +67,7 @@ pub use self::{ validator::{DiscardAll, MessageIntent, ValidationResult, Validator, ValidatorContext}, }; -use sc_network::{multiaddr, PeerId}; +use libp2p::{multiaddr, PeerId}; use sc_network_common::service::{ NetworkBlock, NetworkEventStream, NetworkNotification, NetworkPeers, }; diff --git a/client/network-gossip/src/state_machine.rs b/client/network-gossip/src/state_machine.rs index 4cc4e25529af4..26a83ffeb6942 100644 --- a/client/network-gossip/src/state_machine.rs +++ b/client/network-gossip/src/state_machine.rs @@ -42,9 +42,9 @@ const REBROADCAST_INTERVAL: time::Duration = time::Duration::from_millis(750); pub(crate) const PERIODIC_MAINTENANCE_INTERVAL: time::Duration = time::Duration::from_millis(1100); mod rep { - use sc_network::ReputationChange as Rep; + use sc_peerset::ReputationChange as Rep; /// Reputation change when a peer sends us a gossip message that we didn't know about. - pub const GOSSIP_SUCCESS: Rep = Rep::new(1 << 4, "Successfull gossip"); + pub const GOSSIP_SUCCESS: Rep = Rep::new(1 << 4, "Successful gossip"); /// Reputation change when a peer sends us a gossip message that we already knew about. pub const DUPLICATE_GOSSIP: Rep = Rep::new(-(1 << 2), "Duplicate gossip"); } @@ -513,7 +513,6 @@ mod tests { use super::*; use crate::multiaddr::Multiaddr; use futures::prelude::*; - use sc_network::ReputationChange; use sc_network_common::{ protocol::event::Event, service::{ @@ -521,6 +520,7 @@ mod tests { NotificationSender, NotificationSenderError, }, }; + use sc_peerset::ReputationChange; use sp_runtime::{ testing::{Block as RawBlock, ExtrinsicWrapper, H256}, traits::NumberFor, diff --git a/client/network-gossip/src/validator.rs b/client/network-gossip/src/validator.rs index a98c62ab5a9eb..185c2cfeed2c7 100644 --- a/client/network-gossip/src/validator.rs +++ b/client/network-gossip/src/validator.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use sc_network::PeerId; +use libp2p::PeerId; use sc_network_common::protocol::event::ObservedRole; use sp_runtime::traits::Block as BlockT;