diff --git a/substrate/client/beefy/src/lib.rs b/substrate/client/beefy/src/lib.rs index bdf44e0567..cdb7fca103 100644 --- a/substrate/client/beefy/src/lib.rs +++ b/substrate/client/beefy/src/lib.rs @@ -20,6 +20,7 @@ use beefy_primitives::{BeefyApi, MmrRootHash}; use prometheus::Registry; use sc_client_api::{Backend, BlockchainEvents, Finalizer}; use sc_consensus::BlockImport; +use sc_network::ProtocolName; use sc_network_gossip::Network as GossipNetwork; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; @@ -55,6 +56,7 @@ pub use beefy_protocol_name::standard_name as protocol_standard_name; pub(crate) mod beefy_protocol_name { use sc_chain_spec::ChainSpec; + use sc_network::ProtocolName; const NAME: &str = "/beefy/1"; /// Old names for the notifications protocol, used for backward compatibility. @@ -66,7 +68,7 @@ pub(crate) mod beefy_protocol_name { pub fn standard_name>( genesis_hash: &Hash, chain_spec: &Box, - ) -> std::borrow::Cow<'static, str> { + ) -> ProtocolName { let chain_prefix = match chain_spec.fork_id() { Some(fork_id) => format!("/{}/{}", hex::encode(genesis_hash), fork_id), None => format!("/{}", hex::encode(genesis_hash)), @@ -79,7 +81,7 @@ pub(crate) mod beefy_protocol_name { /// [`sc_network::config::NetworkConfiguration::extra_sets`]. /// For standard protocol name see [`beefy_protocol_name::standard_name`]. pub fn beefy_peers_set_config( - protocol_name: std::borrow::Cow<'static, str>, + protocol_name: ProtocolName, ) -> sc_network::config::NonDefaultSetConfig { let mut cfg = sc_network::config::NonDefaultSetConfig::new(protocol_name, 1024 * 1024); @@ -202,7 +204,7 @@ where /// Prometheus metric registry pub prometheus_registry: Option, /// Chain specific GRANDPA protocol name. See [`beefy_protocol_name::standard_name`]. - pub protocol_name: std::borrow::Cow<'static, str>, + pub protocol_name: ProtocolName, /// Links between the block importer, the background voter and the RPC layer. pub links: BeefyVoterLinks, } diff --git a/substrate/client/finality-grandpa/src/communication/mod.rs b/substrate/client/finality-grandpa/src/communication/mod.rs index 7a47ebe214..04d7ceaa05 100644 --- a/substrate/client/finality-grandpa/src/communication/mod.rs +++ b/substrate/client/finality-grandpa/src/communication/mod.rs @@ -70,6 +70,7 @@ pub(crate) mod tests; pub mod grandpa_protocol_name { use sc_chain_spec::ChainSpec; + use sc_network_common::protocol::ProtocolName; pub(crate) const NAME: &str = "/grandpa/1"; /// Old names for the notifications protocol, used for backward compatibility. @@ -81,7 +82,7 @@ pub mod grandpa_protocol_name { pub fn standard_name>( genesis_hash: &Hash, chain_spec: &Box, - ) -> std::borrow::Cow<'static, str> { + ) -> ProtocolName { let chain_prefix = match chain_spec.fork_id() { Some(fork_id) => format!("/{}/{}", hex::encode(genesis_hash), fork_id), None => format!("/{}", hex::encode(genesis_hash)), diff --git a/substrate/client/finality-grandpa/src/communication/tests.rs b/substrate/client/finality-grandpa/src/communication/tests.rs index 4d709f56f3..1f607e8d68 100644 --- a/substrate/client/finality-grandpa/src/communication/tests.rs +++ b/substrate/client/finality-grandpa/src/communication/tests.rs @@ -28,7 +28,10 @@ use parity_scale_codec::Encode; use sc_network::{config::Role, Multiaddr, PeerId, ReputationChange}; use sc_network_common::{ config::MultiaddrWithPeerId, - protocol::event::{Event as NetworkEvent, ObservedRole}, + protocol::{ + event::{Event as NetworkEvent, ObservedRole}, + ProtocolName, + }, service::{ NetworkBlock, NetworkEventStream, NetworkNotification, NetworkPeers, NetworkSyncForkRequest, NotificationSender, NotificationSenderError, @@ -41,7 +44,6 @@ use sp_finality_grandpa::AuthorityList; use sp_keyring::Ed25519Keyring; use sp_runtime::traits::NumberFor; use std::{ - borrow::Cow, collections::HashSet, pin::Pin, sync::Arc, @@ -78,7 +80,7 @@ impl NetworkPeers for TestNetwork { let _ = self.sender.unbounded_send(Event::Report(who, cost_benefit)); } - fn disconnect_peer(&self, _who: PeerId, _protocol: Cow<'static, str>) {} + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) {} fn accept_unreserved_peers(&self) { unimplemented!(); @@ -98,7 +100,7 @@ impl NetworkPeers for TestNetwork { fn set_reserved_peers( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); @@ -106,23 +108,23 @@ impl NetworkPeers for TestNetwork { fn add_peers_to_reserved_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_peers_from_reserved_set(&self, _protocol: Cow<'static, str>, _peers: Vec) {} + fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec) {} fn add_to_peers_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec) { + fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec) { unimplemented!(); } @@ -143,14 +145,14 @@ impl NetworkEventStream for TestNetwork { } impl NetworkNotification for TestNetwork { - fn write_notification(&self, target: PeerId, _protocol: Cow<'static, str>, message: Vec) { + fn write_notification(&self, target: PeerId, _protocol: ProtocolName, message: Vec) { let _ = self.sender.unbounded_send(Event::WriteNotification(target, message)); } fn notification_sender( &self, _target: PeerId, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, ) -> Result, NotificationSenderError> { unimplemented!(); } diff --git a/substrate/client/finality-grandpa/src/lib.rs b/substrate/client/finality-grandpa/src/lib.rs index cb32957c0b..149cf1f89a 100644 --- a/substrate/client/finality-grandpa/src/lib.rs +++ b/substrate/client/finality-grandpa/src/lib.rs @@ -68,6 +68,7 @@ use sc_client_api::{ StorageProvider, TransactionFor, }; use sc_consensus::BlockImport; +use sc_network_common::protocol::ProtocolName; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver}; use sp_api::ProvideRuntimeApi; @@ -266,7 +267,7 @@ pub struct Config { /// TelemetryHandle instance. pub telemetry: Option, /// Chain specific GRANDPA protocol name. See [`crate::protocol_standard_name`]. - pub protocol_name: std::borrow::Cow<'static, str>, + pub protocol_name: ProtocolName, } impl Config { @@ -723,7 +724,7 @@ pub struct GrandpaParams { /// [`sc_network::config::NetworkConfiguration::extra_sets`]. /// For standard protocol name see [`crate::protocol_standard_name`]. pub fn grandpa_peers_set_config( - protocol_name: std::borrow::Cow<'static, str>, + protocol_name: ProtocolName, ) -> sc_network::config::NonDefaultSetConfig { use communication::grandpa_protocol_name; sc_network::config::NonDefaultSetConfig { diff --git a/substrate/client/network-gossip/src/bridge.rs b/substrate/client/network-gossip/src/bridge.rs index 45eff09332..121fa6dc9a 100644 --- a/substrate/client/network-gossip/src/bridge.rs +++ b/substrate/client/network-gossip/src/bridge.rs @@ -21,7 +21,7 @@ use crate::{ Network, Validator, }; -use sc_network_common::protocol::event::Event; +use sc_network_common::protocol::{event::Event, ProtocolName}; use sc_peerset::ReputationChange; use futures::{ @@ -33,7 +33,6 @@ use log::trace; use prometheus_endpoint::Registry; use sp_runtime::traits::Block as BlockT; use std::{ - borrow::Cow, collections::{HashMap, VecDeque}, pin::Pin, sync::Arc, @@ -46,7 +45,7 @@ pub struct GossipEngine { state_machine: ConsensusGossip, network: Box + Send>, periodic_maintenance_interval: futures_timer::Delay, - protocol: Cow<'static, str>, + protocol: ProtocolName, /// Incoming events from the network. network_event_stream: Pin + Send>>, @@ -78,7 +77,7 @@ impl GossipEngine { /// Create a new instance. pub fn new + Send + Clone + 'static>( network: N, - protocol: impl Into>, + protocol: impl Into, validator: Arc>, metrics_registry: Option<&Registry>, ) -> Self @@ -329,7 +328,6 @@ mod tests { traits::{Block as BlockT, NumberFor}, }; use std::{ - borrow::Cow, collections::HashSet, sync::{Arc, Mutex}, }; @@ -360,7 +358,7 @@ mod tests { fn report_peer(&self, _who: PeerId, _cost_benefit: ReputationChange) {} - fn disconnect_peer(&self, _who: PeerId, _protocol: Cow<'static, str>) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -382,7 +380,7 @@ mod tests { fn set_reserved_peers( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); @@ -390,28 +388,23 @@ mod tests { fn add_peers_to_reserved_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_peers_from_reserved_set( - &self, - _protocol: Cow<'static, str>, - _peers: Vec, - ) { - } + fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec) {} fn add_to_peers_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec) { + fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec) { unimplemented!(); } @@ -430,19 +423,14 @@ mod tests { } impl NetworkNotification for TestNetwork { - fn write_notification( - &self, - _target: PeerId, - _protocol: Cow<'static, str>, - _message: Vec, - ) { + fn write_notification(&self, _target: PeerId, _protocol: ProtocolName, _message: Vec) { unimplemented!(); } fn notification_sender( &self, _target: PeerId, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, ) -> Result, NotificationSenderError> { unimplemented!(); } @@ -505,7 +493,7 @@ mod tests { #[test] fn keeps_multiple_subscribers_per_topic_updated_with_both_old_and_new_messages() { let topic = H256::default(); - let protocol = Cow::Borrowed("/my_protocol"); + let protocol = ProtocolName::from("/my_protocol"); let remote_peer = PeerId::random(); let network = TestNetwork::default(); @@ -622,7 +610,7 @@ mod tests { } fn prop(channels: Vec, notifications: Vec>) { - let protocol = Cow::Borrowed("/my_protocol"); + let protocol = ProtocolName::from("/my_protocol"); let remote_peer = PeerId::random(); let network = TestNetwork::default(); diff --git a/substrate/client/network-gossip/src/lib.rs b/substrate/client/network-gossip/src/lib.rs index 0fdde1feac..1c8fb8ba05 100644 --- a/substrate/client/network-gossip/src/lib.rs +++ b/substrate/client/network-gossip/src/lib.rs @@ -68,11 +68,12 @@ pub use self::{ }; use libp2p::{multiaddr, PeerId}; -use sc_network_common::service::{ - NetworkBlock, NetworkEventStream, NetworkNotification, NetworkPeers, +use sc_network_common::{ + protocol::ProtocolName, + service::{NetworkBlock, NetworkEventStream, NetworkNotification, NetworkPeers}, }; use sp_runtime::traits::{Block as BlockT, NumberFor}; -use std::{borrow::Cow, iter}; +use std::iter; mod bridge; mod state_machine; @@ -82,7 +83,7 @@ mod validator; pub trait Network: NetworkPeers + NetworkEventStream + NetworkNotification + NetworkBlock> { - fn add_set_reserved(&self, who: PeerId, protocol: Cow<'static, str>) { + fn add_set_reserved(&self, who: PeerId, protocol: ProtocolName) { let addr = iter::once(multiaddr::Protocol::P2p(who.into())).collect::(); let result = self.add_peers_to_reserved_set(protocol, iter::once(addr).collect()); diff --git a/substrate/client/network-gossip/src/state_machine.rs b/substrate/client/network-gossip/src/state_machine.rs index ff75b4520b..30a2e9d149 100644 --- a/substrate/client/network-gossip/src/state_machine.rs +++ b/substrate/client/network-gossip/src/state_machine.rs @@ -22,9 +22,9 @@ use ahash::AHashSet; use libp2p::PeerId; use lru::LruCache; use prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64}; -use sc_network_common::protocol::event::ObservedRole; +use sc_network_common::protocol::{event::ObservedRole, ProtocolName}; use sp_runtime::traits::{Block as BlockT, Hash, HashFor}; -use std::{borrow::Cow, collections::HashMap, iter, sync::Arc, time, time::Instant}; +use std::{collections::HashMap, iter, sync::Arc, time, time::Instant}; // FIXME: Add additional spam/DoS attack protection: https://github.com/paritytech/substrate/issues/1115 // NOTE: The current value is adjusted based on largest production network deployment (Kusama) and @@ -99,7 +99,7 @@ impl<'g, 'p, B: BlockT> ValidatorContext for NetworkContext<'g, 'p, B> { fn propagate<'a, B: BlockT, I>( network: &mut dyn Network, - protocol: Cow<'static, str>, + protocol: ProtocolName, messages: I, intent: MessageIntent, peers: &mut HashMap>, @@ -155,7 +155,7 @@ pub struct ConsensusGossip { peers: HashMap>, messages: Vec>, known_messages: LruCache, - protocol: Cow<'static, str>, + protocol: ProtocolName, validator: Arc>, next_broadcast: Instant, metrics: Option, @@ -165,7 +165,7 @@ impl ConsensusGossip { /// Create a new instance using the given validator. pub fn new( validator: Arc>, - protocol: Cow<'static, str>, + protocol: ProtocolName, metrics_registry: Option<&Registry>, ) -> Self { let metrics = match metrics_registry.map(Metrics::register) { @@ -527,7 +527,6 @@ mod tests { traits::NumberFor, }; use std::{ - borrow::Cow, collections::HashSet, pin::Pin, sync::{Arc, Mutex}, @@ -599,7 +598,7 @@ mod tests { self.inner.lock().unwrap().peer_reports.push((who, cost_benefit)); } - fn disconnect_peer(&self, _who: PeerId, _protocol: Cow<'static, str>) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -621,7 +620,7 @@ mod tests { fn set_reserved_peers( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); @@ -629,28 +628,23 @@ mod tests { fn add_peers_to_reserved_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_peers_from_reserved_set( - &self, - _protocol: Cow<'static, str>, - _peers: Vec, - ) { - } + fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec) {} fn add_to_peers_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec) { + fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec) { unimplemented!(); } @@ -666,19 +660,14 @@ mod tests { } impl NetworkNotification for NoOpNetwork { - fn write_notification( - &self, - _target: PeerId, - _protocol: Cow<'static, str>, - _message: Vec, - ) { + fn write_notification(&self, _target: PeerId, _protocol: ProtocolName, _message: Vec) { unimplemented!(); } fn notification_sender( &self, _target: PeerId, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, ) -> Result, NotificationSenderError> { unimplemented!(); } diff --git a/substrate/client/network/common/src/config.rs b/substrate/client/network/common/src/config.rs index c2e61424c8..8b7e045780 100644 --- a/substrate/client/network/common/src/config.rs +++ b/substrate/client/network/common/src/config.rs @@ -21,7 +21,9 @@ 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. +/// Protocol name prefix, transmitted on the wire for legacy protocol names. +/// I.e., `dot` in `/dot/sync/2`. Should be unique for each chain. Always UTF-8. +/// Deprecated in favour of genesis hash & fork ID based protocol names. #[derive(Clone, PartialEq, Eq, Hash)] pub struct ProtocolId(smallvec::SmallVec<[u8; 6]>); diff --git a/substrate/client/network/common/src/protocol.rs b/substrate/client/network/common/src/protocol.rs index 0fd36cb511..11edc373a2 100644 --- a/substrate/client/network/common/src/protocol.rs +++ b/substrate/client/network/common/src/protocol.rs @@ -16,4 +16,131 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use std::{ + borrow::Borrow, + fmt, + hash::{Hash, Hasher}, + ops::Deref, + sync::Arc, +}; + +use libp2p::core::upgrade; + pub mod event; + +/// The protocol name transmitted on the wire. +#[derive(Debug, Clone)] +pub enum ProtocolName { + /// The protocol name as a static string. + Static(&'static str), + /// The protocol name as a dynamically allocated string. + OnHeap(Arc), +} + +impl From<&'static str> for ProtocolName { + fn from(name: &'static str) -> Self { + Self::Static(name) + } +} + +impl From> for ProtocolName { + fn from(name: Arc) -> Self { + Self::OnHeap(name) + } +} + +impl From for ProtocolName { + fn from(name: String) -> Self { + Self::OnHeap(Arc::from(name)) + } +} + +impl Deref for ProtocolName { + type Target = str; + + fn deref(&self) -> &str { + match self { + Self::Static(name) => name, + Self::OnHeap(name) => &name, + } + } +} + +impl Borrow for ProtocolName { + fn borrow(&self) -> &str { + self + } +} + +impl PartialEq for ProtocolName { + fn eq(&self, other: &Self) -> bool { + (self as &str) == (other as &str) + } +} + +impl Eq for ProtocolName {} + +impl Hash for ProtocolName { + fn hash(&self, state: &mut H) { + (self as &str).hash(state) + } +} + +impl fmt::Display for ProtocolName { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(self) + } +} + +impl upgrade::ProtocolName for ProtocolName { + fn protocol_name(&self) -> &[u8] { + (self as &str).as_bytes() + } +} + +#[cfg(test)] +mod tests { + use super::ProtocolName; + use std::{ + borrow::Borrow, + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, + }; + + #[test] + fn protocol_name_keys_are_equivalent_to_str_keys() { + const PROTOCOL: &'static str = "/some/protocol/1"; + let static_protocol_name = ProtocolName::from(PROTOCOL); + let on_heap_protocol_name = ProtocolName::from(String::from(PROTOCOL)); + + assert_eq!(>::borrow(&static_protocol_name), PROTOCOL); + assert_eq!(>::borrow(&on_heap_protocol_name), PROTOCOL); + assert_eq!(static_protocol_name, on_heap_protocol_name); + + assert_eq!(hash(static_protocol_name), hash(PROTOCOL)); + assert_eq!(hash(on_heap_protocol_name), hash(PROTOCOL)); + } + + #[test] + fn different_protocol_names_do_not_compare_equal() { + const PROTOCOL1: &'static str = "/some/protocol/1"; + let static_protocol_name1 = ProtocolName::from(PROTOCOL1); + let on_heap_protocol_name1 = ProtocolName::from(String::from(PROTOCOL1)); + + const PROTOCOL2: &'static str = "/some/protocol/2"; + let static_protocol_name2 = ProtocolName::from(PROTOCOL2); + let on_heap_protocol_name2 = ProtocolName::from(String::from(PROTOCOL2)); + + assert_ne!(>::borrow(&static_protocol_name1), PROTOCOL2); + assert_ne!(>::borrow(&on_heap_protocol_name1), PROTOCOL2); + assert_ne!(static_protocol_name1, static_protocol_name2); + assert_ne!(static_protocol_name1, on_heap_protocol_name2); + assert_ne!(on_heap_protocol_name1, on_heap_protocol_name2); + } + + fn hash(x: T) -> u64 { + let mut hasher = DefaultHasher::new(); + x.hash(&mut hasher); + hasher.finish() + } +} diff --git a/substrate/client/network/common/src/protocol/event.rs b/substrate/client/network/common/src/protocol/event.rs index c6fb4a2faf..3d8c183da4 100644 --- a/substrate/client/network/common/src/protocol/event.rs +++ b/substrate/client/network/common/src/protocol/event.rs @@ -19,9 +19,9 @@ //! Network event types. These are are not the part of the protocol, but rather //! events that happen on the network like DHT get/put results received. +use super::ProtocolName; use bytes::Bytes; use libp2p::{core::PeerId, kad::record::Key}; -use std::borrow::Cow; /// Events generated by DHT as a response to get_value and put_value requests. #[derive(Debug, Clone)] @@ -69,13 +69,13 @@ pub enum Event { /// This is always equal to the value of /// `sc_network::config::NonDefaultSetConfig::notifications_protocol` of one of the /// configured sets. - protocol: Cow<'static, str>, + protocol: ProtocolName, /// If the negotiation didn't use the main name of the protocol (the one in /// `notifications_protocol`), then this field contains which name has actually been /// used. /// Always contains a value equal to the value in /// `sc_network::config::NonDefaultSetConfig::fallback_names`. - negotiated_fallback: Option>, + negotiated_fallback: Option, /// Role of the remote. role: ObservedRole, }, @@ -86,7 +86,7 @@ pub enum Event { /// Node we closed the substream with. remote: PeerId, /// The concerned protocol. Each protocol uses a different substream. - protocol: Cow<'static, str>, + protocol: ProtocolName, }, /// Received one or more messages from the given node using the given protocol. @@ -94,7 +94,7 @@ pub enum Event { /// Node we received the message from. remote: PeerId, /// Concerned protocol and associated message. - messages: Vec<(Cow<'static, str>, Bytes)>, + messages: Vec<(ProtocolName, Bytes)>, }, } diff --git a/substrate/client/network/common/src/request_responses.rs b/substrate/client/network/common/src/request_responses.rs index a216c9c2d2..1a8d48e11b 100644 --- a/substrate/client/network/common/src/request_responses.rs +++ b/substrate/client/network/common/src/request_responses.rs @@ -18,19 +18,20 @@ //! Collection of generic data structures for request-response protocols. +use crate::protocol::ProtocolName; use futures::channel::{mpsc, oneshot}; use libp2p::{request_response::OutboundFailure, PeerId}; use sc_peerset::ReputationChange; -use std::{borrow::Cow, time::Duration}; +use std::time::Duration; /// Configuration for a single request-response protocol. #[derive(Debug, Clone)] pub struct ProtocolConfig { /// Name of the protocol on the wire. Should be something like `/foo/bar`. - pub name: Cow<'static, str>, + pub name: ProtocolName, /// Fallback on the wire protocol names to support. - pub fallback_names: Vec>, + pub fallback_names: Vec, /// Maximum allowed size, in bytes, of a request. /// diff --git a/substrate/client/network/common/src/service.rs b/substrate/client/network/common/src/service.rs index 9544cddf01..88583832e4 100644 --- a/substrate/client/network/common/src/service.rs +++ b/substrate/client/network/common/src/service.rs @@ -20,7 +20,7 @@ use crate::{ config::MultiaddrWithPeerId, - protocol::event::Event, + protocol::{event::Event, ProtocolName}, request_responses::{IfDisconnected, RequestFailure}, sync::{warp::WarpSyncProgress, StateDownloadProgress, SyncState}, }; @@ -30,7 +30,7 @@ use libp2p::{Multiaddr, PeerId}; use sc_peerset::ReputationChange; pub use signature::Signature; use sp_runtime::traits::{Block as BlockT, NumberFor}; -use std::{borrow::Cow, collections::HashSet, future::Future, pin::Pin, sync::Arc}; +use std::{collections::HashSet, future::Future, pin::Pin, sync::Arc}; mod signature; @@ -171,7 +171,7 @@ pub trait NetworkPeers { /// See also [`NetworkPeers::remove_from_peers_set`], which has the same effect but also /// prevents the local node from re-establishing an outgoing substream to this peer until it /// is added again. - fn disconnect_peer(&self, who: PeerId, protocol: Cow<'static, str>); + fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName); /// Connect to unreserved peers and allow unreserved peers to connect for syncing purposes. fn accept_unreserved_peers(&self); @@ -207,7 +207,7 @@ pub trait NetworkPeers { /// invalid peer ID (which includes the local peer ID). fn set_reserved_peers( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String>; @@ -220,12 +220,12 @@ pub trait NetworkPeers { /// invalid peer ID (which includes the local peer ID). fn add_peers_to_reserved_set( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String>; /// Remove peers from a peer set. - fn remove_peers_from_reserved_set(&self, protocol: Cow<'static, str>, peers: Vec); + fn remove_peers_from_reserved_set(&self, protocol: ProtocolName, peers: Vec); /// Add a peer to a set of peers. /// @@ -238,14 +238,14 @@ pub trait NetworkPeers { /// invalid peer ID (which includes the local peer ID). fn add_to_peers_set( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String>; /// Remove peers from a peer set. /// /// If we currently have an open substream with this peer, it will soon be closed. - fn remove_from_peers_set(&self, protocol: Cow<'static, str>, peers: Vec); + fn remove_from_peers_set(&self, protocol: ProtocolName, peers: Vec); /// Returns the number of peers in the sync peer set we're connected to. fn sync_num_connected(&self) -> usize; @@ -273,7 +273,7 @@ where T::report_peer(self, who, cost_benefit) } - fn disconnect_peer(&self, who: PeerId, protocol: Cow<'static, str>) { + fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName) { T::disconnect_peer(self, who, protocol) } @@ -295,7 +295,7 @@ where fn set_reserved_peers( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String> { T::set_reserved_peers(self, protocol, peers) @@ -303,25 +303,25 @@ where fn add_peers_to_reserved_set( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String> { T::add_peers_to_reserved_set(self, protocol, peers) } - fn remove_peers_from_reserved_set(&self, protocol: Cow<'static, str>, peers: Vec) { + fn remove_peers_from_reserved_set(&self, protocol: ProtocolName, peers: Vec) { T::remove_peers_from_reserved_set(self, protocol, peers) } fn add_to_peers_set( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String> { T::add_to_peers_set(self, protocol, peers) } - fn remove_from_peers_set(&self, protocol: Cow<'static, str>, peers: Vec) { + fn remove_from_peers_set(&self, protocol: ProtocolName, peers: Vec) { T::remove_from_peers_set(self, protocol, peers) } @@ -431,7 +431,7 @@ pub trait NetworkNotification { /// /// The protocol must have been registered with /// `crate::config::NetworkConfiguration::notifications_protocols`. - fn write_notification(&self, target: PeerId, protocol: Cow<'static, str>, message: Vec); + fn write_notification(&self, target: PeerId, protocol: ProtocolName, message: Vec); /// Obtains a [`NotificationSender`] for a connected peer, if it exists. /// @@ -502,7 +502,7 @@ pub trait NetworkNotification { fn notification_sender( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, ) -> Result, NotificationSenderError>; } @@ -511,14 +511,14 @@ where T: ?Sized, T: NetworkNotification, { - fn write_notification(&self, target: PeerId, protocol: Cow<'static, str>, message: Vec) { + fn write_notification(&self, target: PeerId, protocol: ProtocolName, message: Vec) { T::write_notification(self, target, protocol, message) } fn notification_sender( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, ) -> Result, NotificationSenderError> { T::notification_sender(self, target, protocol) } @@ -547,7 +547,7 @@ pub trait NetworkRequest { async fn request( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, request: Vec, connect: IfDisconnected, ) -> Result, RequestFailure>; @@ -565,7 +565,7 @@ pub trait NetworkRequest { fn start_request( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, request: Vec, tx: oneshot::Sender, RequestFailure>>, connect: IfDisconnected, @@ -581,7 +581,7 @@ where fn request<'life0, 'async_trait>( &'life0 self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, request: Vec, connect: IfDisconnected, ) -> Pin, RequestFailure>> + Send + 'async_trait>> @@ -595,7 +595,7 @@ where fn start_request( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, request: Vec, tx: oneshot::Sender, RequestFailure>>, connect: IfDisconnected, diff --git a/substrate/client/network/src/behaviour.rs b/substrate/client/network/src/behaviour.rs index 4177c2452c..24df47db68 100644 --- a/substrate/client/network/src/behaviour.rs +++ b/substrate/client/network/src/behaviour.rs @@ -42,7 +42,10 @@ use log::debug; use sc_consensus::import_queue::{IncomingBlock, Origin}; use sc_network_common::{ config::ProtocolId, - protocol::event::{DhtEvent, ObservedRole}, + protocol::{ + event::{DhtEvent, ObservedRole}, + ProtocolName, + }, request_responses::{IfDisconnected, ProtocolConfig, RequestFailure}, }; use sc_peerset::PeersetHandle; @@ -53,7 +56,6 @@ use sp_runtime::{ Justifications, }; use std::{ - borrow::Cow, collections::{HashSet, VecDeque}, iter, task::{Context, Poll}, @@ -117,7 +119,7 @@ pub enum BehaviourOut { /// Peer which sent us a request. peer: PeerId, /// Protocol name of the request. - protocol: Cow<'static, str>, + protocol: ProtocolName, /// If `Ok`, contains the time elapsed between when we received the request and when we /// sent back the response. If `Err`, the error that happened. result: Result, @@ -130,7 +132,7 @@ pub enum BehaviourOut { /// Peer that we send a request to. peer: PeerId, /// Name of the protocol in question. - protocol: Cow<'static, str>, + protocol: ProtocolName, /// Duration the request took. duration: Duration, /// Result of the request. @@ -144,12 +146,12 @@ pub enum BehaviourOut { /// Node we opened the substream with. remote: PeerId, /// The concerned protocol. Each protocol uses a different substream. - protocol: Cow<'static, str>, + protocol: ProtocolName, /// If the negotiation didn't use the main name of the protocol (the one in /// `notifications_protocol`), then this field contains which name has actually been /// used. /// See also [`crate::Event::NotificationStreamOpened`]. - negotiated_fallback: Option>, + negotiated_fallback: Option, /// Object that permits sending notifications to the peer. notifications_sink: NotificationsSink, /// Role of the remote. @@ -165,7 +167,7 @@ pub enum BehaviourOut { /// Id of the peer we are connected to. remote: PeerId, /// The concerned protocol. Each protocol uses a different substream. - protocol: Cow<'static, str>, + protocol: ProtocolName, /// Replacement for the previous [`NotificationsSink`]. notifications_sink: NotificationsSink, }, @@ -176,7 +178,7 @@ pub enum BehaviourOut { /// Node we closed the substream with. remote: PeerId, /// The concerned protocol. Each protocol uses a different substream. - protocol: Cow<'static, str>, + protocol: ProtocolName, }, /// Received one or more messages from the given node using the given protocol. @@ -184,7 +186,7 @@ pub enum BehaviourOut { /// Node we received the message from. remote: PeerId, /// Concerned protocol and associated message. - messages: Vec<(Cow<'static, str>, Bytes)>, + messages: Vec<(ProtocolName, Bytes)>, }, /// Now connected to a new peer for syncing purposes. diff --git a/substrate/client/network/src/config.rs b/substrate/client/network/src/config.rs index 521aa42827..3fe95deb0c 100644 --- a/substrate/client/network/src/config.rs +++ b/substrate/client/network/src/config.rs @@ -41,10 +41,9 @@ use libp2p::{ }; use prometheus_endpoint::Registry; use sc_consensus::ImportQueue; -use sc_network_common::{config::MultiaddrWithPeerId, sync::ChainSync}; +use sc_network_common::{config::MultiaddrWithPeerId, protocol::ProtocolName, sync::ChainSync}; use sp_runtime::traits::Block as BlockT; use std::{ - borrow::Cow, collections::HashMap, error::Error, fs, @@ -431,14 +430,14 @@ pub struct NonDefaultSetConfig { /// /// > **Note**: This field isn't present for the default set, as this is handled internally /// > by the networking code. - pub notifications_protocol: Cow<'static, str>, + pub notifications_protocol: ProtocolName, /// If the remote reports that it doesn't support the protocol indicated in the /// `notifications_protocol` field, then each of these fallback names will be tried one by /// one. /// /// If a fallback is used, it will be reported in /// [`crate::Event::NotificationStreamOpened::negotiated_fallback`]. - pub fallback_names: Vec>, + pub fallback_names: Vec, /// Maximum allowed size of single notifications. pub max_notification_size: u64, /// Base configuration. @@ -447,7 +446,7 @@ pub struct NonDefaultSetConfig { impl NonDefaultSetConfig { /// Creates a new [`NonDefaultSetConfig`]. Zero slots and accepts only reserved nodes. - pub fn new(notifications_protocol: Cow<'static, str>, max_notification_size: u64) -> Self { + pub fn new(notifications_protocol: ProtocolName, max_notification_size: u64) -> Self { Self { notifications_protocol, max_notification_size, @@ -476,7 +475,7 @@ impl NonDefaultSetConfig { /// Add a list of protocol names used for backward compatibility. /// /// See the explanations in [`NonDefaultSetConfig::fallback_names`]. - pub fn add_fallback_names(&mut self, fallback_names: Vec>) { + pub fn add_fallback_names(&mut self, fallback_names: Vec) { self.fallback_names.extend(fallback_names); } } diff --git a/substrate/client/network/src/error.rs b/substrate/client/network/src/error.rs index 716235193a..b4287ffbd5 100644 --- a/substrate/client/network/src/error.rs +++ b/substrate/client/network/src/error.rs @@ -20,8 +20,9 @@ use crate::config::TransportConfig; use libp2p::{Multiaddr, PeerId}; +use sc_network_common::protocol::ProtocolName; -use std::{borrow::Cow, fmt}; +use std::fmt; /// Result type alias for the network. pub type Result = std::result::Result; @@ -65,7 +66,7 @@ pub enum Error { #[error("Request-response protocol registered multiple times: {protocol}")] DuplicateRequestResponseProtocol { /// Name of the protocol registered multiple times. - protocol: Cow<'static, str>, + protocol: ProtocolName, }, } diff --git a/substrate/client/network/src/lib.rs b/substrate/client/network/src/lib.rs index b1d70c2828..35a91e77da 100644 --- a/substrate/client/network/src/lib.rs +++ b/substrate/client/network/src/lib.rs @@ -264,7 +264,10 @@ pub mod transactions; pub use libp2p::{multiaddr, Multiaddr, PeerId}; pub use protocol::PeerInfo; pub use sc_network_common::{ - protocol::event::{DhtEvent, Event, ObservedRole}, + protocol::{ + event::{DhtEvent, Event, ObservedRole}, + ProtocolName, + }, request_responses::{IfDisconnected, RequestFailure}, service::{ KademliaKey, NetworkBlock, NetworkDHTProvider, NetworkRequest, NetworkSigner, diff --git a/substrate/client/network/src/protocol.rs b/substrate/client/network/src/protocol.rs index 6479453899..9bcf363cd0 100644 --- a/substrate/client/network/src/protocol.rs +++ b/substrate/client/network/src/protocol.rs @@ -44,6 +44,7 @@ use sc_client_api::HeaderBackend; use sc_consensus::import_queue::{BlockImportError, BlockImportStatus, IncomingBlock, Origin}; use sc_network_common::{ config::ProtocolId, + protocol::ProtocolName, request_responses::RequestFailure, sync::{ message::{ @@ -63,7 +64,6 @@ use sp_runtime::{ Justifications, }; use std::{ - borrow::Cow, collections::{HashMap, HashSet, VecDeque}, io, iter, num::NonZeroUsize, @@ -190,7 +190,7 @@ pub struct Protocol { /// Handles opening the unique substream and sending and receiving raw messages. behaviour: Notifications, /// List of notifications protocols that have been registered. - notification_protocols: Vec>, + notification_protocols: Vec, /// If we receive a new "substream open" event that contains an invalid handshake, we ask the /// inner layer to force-close the substream. Force-closing the substream will generate a /// "substream closed" event. This is a problem: since we can't propagate the "substream open" @@ -460,7 +460,7 @@ where } /// Disconnects the given peer if we are connected to it. - pub fn disconnect_peer(&mut self, peer_id: &PeerId, protocol_name: &str) { + pub fn disconnect_peer(&mut self, peer_id: &PeerId, protocol_name: ProtocolName) { if let Some(position) = self.notification_protocols.iter().position(|p| *p == protocol_name) { self.behaviour.disconnect_peer( @@ -1085,7 +1085,7 @@ where } /// Sets the list of reserved peers for the given protocol/peerset. - pub fn set_reserved_peerset_peers(&self, protocol: Cow<'static, str>, peers: HashSet) { + pub fn set_reserved_peerset_peers(&self, protocol: ProtocolName, peers: HashSet) { if let Some(index) = self.notification_protocols.iter().position(|p| *p == protocol) { self.peerset_handle .set_reserved_peers(sc_peerset::SetId::from(index + NUM_HARDCODED_PEERSETS), peers); @@ -1099,7 +1099,7 @@ where } /// Removes a `PeerId` from the list of reserved peers. - pub fn remove_set_reserved_peer(&self, protocol: Cow<'static, str>, peer: PeerId) { + pub fn remove_set_reserved_peer(&self, protocol: ProtocolName, peer: PeerId) { if let Some(index) = self.notification_protocols.iter().position(|p| *p == protocol) { self.peerset_handle.remove_reserved_peer( sc_peerset::SetId::from(index + NUM_HARDCODED_PEERSETS), @@ -1115,7 +1115,7 @@ where } /// Adds a `PeerId` to the list of reserved peers. - pub fn add_set_reserved_peer(&self, protocol: Cow<'static, str>, peer: PeerId) { + pub fn add_set_reserved_peer(&self, protocol: ProtocolName, peer: PeerId) { if let Some(index) = self.notification_protocols.iter().position(|p| *p == protocol) { self.peerset_handle .add_reserved_peer(sc_peerset::SetId::from(index + NUM_HARDCODED_PEERSETS), peer); @@ -1138,7 +1138,7 @@ where } /// Add a peer to a peers set. - pub fn add_to_peers_set(&self, protocol: Cow<'static, str>, peer: PeerId) { + pub fn add_to_peers_set(&self, protocol: ProtocolName, peer: PeerId) { if let Some(index) = self.notification_protocols.iter().position(|p| *p == protocol) { self.peerset_handle .add_to_peers_set(sc_peerset::SetId::from(index + NUM_HARDCODED_PEERSETS), peer); @@ -1152,7 +1152,7 @@ where } /// Remove a peer from a peers set. - pub fn remove_from_peers_set(&self, protocol: Cow<'static, str>, peer: PeerId) { + pub fn remove_from_peers_set(&self, protocol: ProtocolName, peer: PeerId) { if let Some(index) = self.notification_protocols.iter().position(|p| *p == protocol) { self.peerset_handle.remove_from_peers_set( sc_peerset::SetId::from(index + NUM_HARDCODED_PEERSETS), @@ -1259,27 +1259,27 @@ pub enum CustomMessageOutcome { /// Notification protocols have been opened with a remote. NotificationStreamOpened { remote: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, /// See [`crate::Event::NotificationStreamOpened::negotiated_fallback`]. - negotiated_fallback: Option>, + negotiated_fallback: Option, roles: Roles, notifications_sink: NotificationsSink, }, /// The [`NotificationsSink`] of some notification protocols need an update. NotificationStreamReplaced { remote: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, notifications_sink: NotificationsSink, }, /// Notification protocols have been closed with a remote. NotificationStreamClosed { remote: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, }, /// Messages have been received on one or more notifications protocols. NotificationsReceived { remote: PeerId, - messages: Vec<(Cow<'static, str>, Bytes)>, + messages: Vec<(ProtocolName, Bytes)>, }, /// A new block request must be emitted. BlockRequest { diff --git a/substrate/client/network/src/protocol/notifications/behaviour.rs b/substrate/client/network/src/protocol/notifications/behaviour.rs index 1f872ec857..04f6fe445a 100644 --- a/substrate/client/network/src/protocol/notifications/behaviour.rs +++ b/substrate/client/network/src/protocol/notifications/behaviour.rs @@ -33,15 +33,14 @@ use libp2p::{ use log::{error, trace, warn}; use parking_lot::RwLock; use rand::distributions::{Distribution as _, Uniform}; +use sc_network_common::protocol::ProtocolName; use sc_peerset::DropReason; use smallvec::SmallVec; use std::{ - borrow::Cow, cmp, collections::{hash_map::Entry, VecDeque}, mem, pin::Pin, - str, sync::Arc, task::{Context, Poll}, time::{Duration, Instant}, @@ -140,9 +139,9 @@ pub struct Notifications { #[derive(Debug, Clone)] pub struct ProtocolConfig { /// Name of the protocol. - pub name: Cow<'static, str>, + pub name: ProtocolName, /// Names of the protocol to use if the main one isn't available. - pub fallback_names: Vec>, + pub fallback_names: Vec, /// Handshake of the protocol. pub handshake: Vec, /// Maximum allowed size for a notification. @@ -309,7 +308,7 @@ pub enum NotificationsOut { set_id: sc_peerset::SetId, /// If `Some`, a fallback protocol name has been used rather the main protocol name. /// Always matches one of the fallback names passed at initialization. - negotiated_fallback: Option>, + negotiated_fallback: Option, /// Handshake that was sent to us. /// This is normally a "Status" message, but this is out of the concern of this code. received_handshake: Vec, diff --git a/substrate/client/network/src/protocol/notifications/handler.rs b/substrate/client/network/src/protocol/notifications/handler.rs index c1602319d0..ea09cb76ed 100644 --- a/substrate/client/network/src/protocol/notifications/handler.rs +++ b/substrate/client/network/src/protocol/notifications/handler.rs @@ -80,12 +80,11 @@ use libp2p::{ }; use log::error; use parking_lot::{Mutex, RwLock}; +use sc_network_common::protocol::ProtocolName; use std::{ - borrow::Cow, collections::VecDeque, mem, pin::Pin, - str, sync::Arc, task::{Context, Poll}, time::{Duration, Instant}, @@ -146,9 +145,9 @@ pub struct NotifsHandler { #[derive(Debug, Clone)] pub struct ProtocolConfig { /// Name of the protocol. - pub name: Cow<'static, str>, + pub name: ProtocolName, /// Names of the protocol to use if the main one isn't available. - pub fallback_names: Vec>, + pub fallback_names: Vec, /// Handshake of the protocol. The `RwLock` is locked every time a new substream is opened. pub handshake: Arc>>, /// Maximum allowed size for a notification. @@ -297,7 +296,7 @@ pub enum NotifsHandlerOut { /// Index of the protocol in the list of protocols passed at initialization. protocol_index: usize, /// Name of the protocol that was actually negotiated, if the default one wasn't available. - negotiated_fallback: Option>, + negotiated_fallback: Option, /// The endpoint of the connection that is open for custom protocols. endpoint: ConnectedPoint, /// Handshake that was sent to us. diff --git a/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs b/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs index 3fbb59d399..56cfefd75d 100644 --- a/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs +++ b/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs @@ -39,8 +39,8 @@ use bytes::BytesMut; use futures::prelude::*; use libp2p::core::{upgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use log::{error, warn}; +use sc_network_common::protocol::ProtocolName; use std::{ - borrow::Cow, convert::Infallible, io, mem, pin::Pin, @@ -58,7 +58,7 @@ const MAX_HANDSHAKE_SIZE: usize = 1024; pub struct NotificationsIn { /// Protocol name to use when negotiating the substream. /// The first one is the main name, while the other ones are fall backs. - protocol_names: Vec>, + protocol_names: Vec, /// Maximum allowed size for a single notification. max_notification_size: u64, } @@ -69,7 +69,7 @@ pub struct NotificationsIn { pub struct NotificationsOut { /// Protocol name to use when negotiating the substream. /// The first one is the main name, while the other ones are fall backs. - protocol_names: Vec>, + protocol_names: Vec, /// Message to send when we start the handshake. initial_message: Vec, /// Maximum allowed size for a single notification. @@ -114,8 +114,8 @@ pub struct NotificationsOutSubstream { impl NotificationsIn { /// Builds a new potential upgrade. pub fn new( - main_protocol_name: impl Into>, - fallback_names: Vec>, + main_protocol_name: impl Into, + fallback_names: Vec, max_notification_size: u64, ) -> Self { let mut protocol_names = fallback_names; @@ -126,16 +126,11 @@ impl NotificationsIn { } impl UpgradeInfo for NotificationsIn { - type Info = StringProtocolName; + type Info = ProtocolName; type InfoIter = vec::IntoIter; fn protocol_info(&self) -> Self::InfoIter { - self.protocol_names - .iter() - .cloned() - .map(StringProtocolName) - .collect::>() - .into_iter() + self.protocol_names.clone().into_iter() } } @@ -172,10 +167,10 @@ where Ok(NotificationsInOpen { handshake, - negotiated_fallback: if negotiated_name.0 == self.protocol_names[0] { + negotiated_fallback: if negotiated_name == self.protocol_names[0] { None } else { - Some(negotiated_name.0) + Some(negotiated_name) }, substream, }) @@ -189,7 +184,7 @@ pub struct NotificationsInOpen { pub handshake: Vec, /// If the negotiated name is not the "main" protocol name but a fallback, contains the /// name of the negotiated fallback. - pub negotiated_fallback: Option>, + pub negotiated_fallback: Option, /// Implementation of `Stream` that allows receives messages from the substream. pub substream: NotificationsInSubstream, } @@ -334,8 +329,8 @@ where impl NotificationsOut { /// Builds a new potential upgrade. pub fn new( - main_protocol_name: impl Into>, - fallback_names: Vec>, + main_protocol_name: impl Into, + fallback_names: Vec, initial_message: impl Into>, max_notification_size: u64, ) -> Self { @@ -351,27 +346,12 @@ impl NotificationsOut { } } -/// Implementation of the `ProtocolName` trait, where the protocol name is a string. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct StringProtocolName(Cow<'static, str>); - -impl upgrade::ProtocolName for StringProtocolName { - fn protocol_name(&self) -> &[u8] { - self.0.as_bytes() - } -} - impl UpgradeInfo for NotificationsOut { - type Info = StringProtocolName; + type Info = ProtocolName; type InfoIter = vec::IntoIter; fn protocol_info(&self) -> Self::InfoIter { - self.protocol_names - .iter() - .cloned() - .map(StringProtocolName) - .collect::>() - .into_iter() + self.protocol_names.clone().into_iter() } } @@ -406,10 +386,10 @@ where Ok(NotificationsOutOpen { handshake, - negotiated_fallback: if negotiated_name.0 == self.protocol_names[0] { + negotiated_fallback: if negotiated_name == self.protocol_names[0] { None } else { - Some(negotiated_name.0) + Some(negotiated_name) }, substream: NotificationsOutSubstream { socket: Framed::new(socket, codec) }, }) @@ -423,7 +403,7 @@ pub struct NotificationsOutOpen { pub handshake: Vec, /// If the negotiated name is not the "main" protocol name but a fallback, contains the /// name of the negotiated fallback. - pub negotiated_fallback: Option>, + pub negotiated_fallback: Option, /// Implementation of `Sink` that allows sending messages on the substream. pub substream: NotificationsOutSubstream, } @@ -505,11 +485,10 @@ mod tests { use async_std::net::{TcpListener, TcpStream}; use futures::{channel::oneshot, prelude::*}; use libp2p::core::upgrade; - use std::borrow::Cow; #[test] fn basic_works() { - const PROTO_NAME: Cow<'static, str> = Cow::Borrowed("/test/proto/1"); + const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = async_std::task::spawn(async move { @@ -552,7 +531,7 @@ mod tests { fn empty_handshake() { // Check that everything still works when the handshake messages are empty. - const PROTO_NAME: Cow<'static, str> = Cow::Borrowed("/test/proto/1"); + const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = async_std::task::spawn(async move { @@ -593,7 +572,7 @@ mod tests { #[test] fn refused() { - const PROTO_NAME: Cow<'static, str> = Cow::Borrowed("/test/proto/1"); + const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = async_std::task::spawn(async move { @@ -634,7 +613,7 @@ mod tests { #[test] fn large_initial_message_refused() { - const PROTO_NAME: Cow<'static, str> = Cow::Borrowed("/test/proto/1"); + const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = async_std::task::spawn(async move { @@ -672,7 +651,7 @@ mod tests { #[test] fn large_handshake_refused() { - const PROTO_NAME: Cow<'static, str> = Cow::Borrowed("/test/proto/1"); + const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = async_std::task::spawn(async move { diff --git a/substrate/client/network/src/request_responses.rs b/substrate/client/network/src/request_responses.rs index 9eab85a4c1..d49cbd8051 100644 --- a/substrate/client/network/src/request_responses.rs +++ b/substrate/client/network/src/request_responses.rs @@ -50,11 +50,13 @@ use libp2p::{ NetworkBehaviourAction, PollParameters, }, }; -use sc_network_common::request_responses::{ - IfDisconnected, IncomingRequest, OutgoingResponse, ProtocolConfig, RequestFailure, +use sc_network_common::{ + protocol::ProtocolName, + request_responses::{ + IfDisconnected, IncomingRequest, OutgoingResponse, ProtocolConfig, RequestFailure, + }, }; use std::{ - borrow::Cow, collections::{hash_map::Entry, HashMap}, io, iter, pin::Pin, @@ -75,7 +77,7 @@ pub enum Event { /// Peer which has emitted the request. peer: PeerId, /// Name of the protocol in question. - protocol: Cow<'static, str>, + protocol: ProtocolName, /// Whether handling the request was successful or unsuccessful. /// /// When successful contains the time elapsed between when we received the request and when @@ -91,7 +93,7 @@ pub enum Event { /// Peer that we send a request to. peer: PeerId, /// Name of the protocol in question. - protocol: Cow<'static, str>, + protocol: ProtocolName, /// Duration the request took. duration: Duration, /// Result of the request. @@ -110,12 +112,12 @@ pub enum Event { /// [`ProtocolRequestId`]s. #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct ProtocolRequestId { - protocol: Cow<'static, str>, + protocol: ProtocolName, request_id: RequestId, } -impl From<(Cow<'static, str>, RequestId)> for ProtocolRequestId { - fn from((protocol, request_id): (Cow<'static, str>, RequestId)) -> Self { +impl From<(ProtocolName, RequestId)> for ProtocolRequestId { + fn from((protocol, request_id): (ProtocolName, RequestId)) -> Self { Self { protocol, request_id } } } @@ -126,7 +128,7 @@ pub struct RequestResponsesBehaviour { /// Contains the underlying libp2p `RequestResponse` behaviour, plus an optional /// "response builder" used to build responses for incoming requests. protocols: HashMap< - Cow<'static, str>, + ProtocolName, (RequestResponse, Option>), >, @@ -162,7 +164,7 @@ struct MessageRequest { request_id: RequestId, request: Vec, channel: ResponseChannel, ()>>, - protocol: String, + protocol: ProtocolName, resp_builder: Option>, // Once we get incoming request we save all params, create an async call to Peerset // to get the reputation of the peer. @@ -173,7 +175,7 @@ struct MessageRequest { struct RequestProcessingOutcome { peer: PeerId, request_id: RequestId, - protocol: Cow<'static, str>, + protocol: ProtocolName, inner_channel: ResponseChannel, ()>>, response: OutgoingResponse, } @@ -495,7 +497,6 @@ impl NetworkBehaviour for RequestResponsesBehaviour { debug_assert!(false, "Received message on outbound-only protocol."); } - let protocol = Cow::from(protocol); self.pending_responses.push(Box::pin(async move { // The `tx` created above can be dropped if we are not capable of // processing this request, which is reflected as a @@ -618,7 +619,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour { request_id, request, channel, - protocol: protocol.to_string(), + protocol: protocol.clone(), resp_builder: resp_builder.clone(), get_peer_reputation, }); @@ -766,7 +767,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour { pub enum RegisterError { /// A protocol has been specified multiple times. #[error("{0}")] - DuplicateProtocol(Cow<'static, str>), + DuplicateProtocol(ProtocolName), } /// Error when processing a request sent by a remote. diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index 7a196da252..4610b025dd 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -61,7 +61,10 @@ use parking_lot::Mutex; use sc_consensus::{BlockImportError, BlockImportStatus, ImportQueue, Link}; use sc_network_common::{ config::MultiaddrWithPeerId, - protocol::event::{DhtEvent, Event}, + protocol::{ + event::{DhtEvent, Event}, + ProtocolName, + }, request_responses::{IfDisconnected, RequestFailure}, service::{ NetworkDHTProvider, NetworkEventStream, NetworkNotification, NetworkPeers, NetworkSigner, @@ -76,7 +79,6 @@ use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnbound use sp_blockchain::HeaderBackend; use sp_runtime::traits::{Block as BlockT, NumberFor}; use std::{ - borrow::Cow, cmp, collections::{HashMap, HashSet}, fs, iter, @@ -122,7 +124,7 @@ pub struct NetworkService { to_worker: TracingUnboundedSender>, /// For each peer and protocol combination, an object that allows sending notifications to /// that peer. Updated by the [`NetworkWorker`]. - peers_notifications_sinks: Arc), NotificationsSink>>>, + peers_notifications_sinks: Arc>>, /// Field extracted from the [`Metrics`] struct and necessary to report the /// notifications-related metrics. notifications_sizes_metric: Option, @@ -890,7 +892,7 @@ where self.peerset.report_peer(who, cost_benefit); } - fn disconnect_peer(&self, who: PeerId, protocol: Cow<'static, str>) { + fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName) { let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::DisconnectPeer(who, protocol)); } @@ -921,7 +923,7 @@ where fn set_reserved_peers( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String> { let peers_addrs = self.split_multiaddr_and_peer_id(peers)?; @@ -952,7 +954,7 @@ where fn add_peers_to_reserved_set( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String> { let peers = self.split_multiaddr_and_peer_id(peers)?; @@ -976,7 +978,7 @@ where Ok(()) } - fn remove_peers_from_reserved_set(&self, protocol: Cow<'static, str>, peers: Vec) { + fn remove_peers_from_reserved_set(&self, protocol: ProtocolName, peers: Vec) { for peer_id in peers.into_iter() { let _ = self .to_worker @@ -986,7 +988,7 @@ where fn add_to_peers_set( &self, - protocol: Cow<'static, str>, + protocol: ProtocolName, peers: HashSet, ) -> Result<(), String> { let peers = self.split_multiaddr_and_peer_id(peers)?; @@ -1010,7 +1012,7 @@ where Ok(()) } - fn remove_from_peers_set(&self, protocol: Cow<'static, str>, peers: Vec) { + fn remove_from_peers_set(&self, protocol: ProtocolName, peers: Vec) { for peer_id in peers.into_iter() { let _ = self .to_worker @@ -1040,7 +1042,7 @@ where B: BlockT + 'static, H: ExHashT, { - fn write_notification(&self, target: PeerId, protocol: Cow<'static, str>, message: Vec) { + fn write_notification(&self, target: PeerId, protocol: ProtocolName, message: Vec) { // We clone the `NotificationsSink` in order to be able to unlock the network-wide // `peers_notifications_sinks` mutex as soon as possible. let sink = { @@ -1077,7 +1079,7 @@ where fn notification_sender( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, ) -> Result, NotificationSenderError> { // We clone the `NotificationsSink` in order to be able to unlock the network-wide // `peers_notifications_sinks` mutex as soon as possible. @@ -1108,7 +1110,7 @@ where async fn request( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, request: Vec, connect: IfDisconnected, ) -> Result, RequestFailure> { @@ -1128,7 +1130,7 @@ where fn start_request( &self, target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, request: Vec, tx: oneshot::Sender, RequestFailure>>, connect: IfDisconnected, @@ -1179,7 +1181,7 @@ pub struct NotificationSender { sink: NotificationsSink, /// Name of the protocol on the wire. - protocol_name: Cow<'static, str>, + protocol_name: ProtocolName, /// Field extracted from the [`Metrics`] struct and necessary to report the /// notifications-related metrics. @@ -1212,7 +1214,7 @@ pub struct NotificationSenderReady<'a> { peer_id: &'a PeerId, /// Name of the protocol on the wire. - protocol_name: &'a Cow<'static, str>, + protocol_name: &'a ProtocolName, /// Field extracted from the [`Metrics`] struct and necessary to report the /// notifications-related metrics. @@ -1256,16 +1258,16 @@ enum ServiceToWorkerMsg { AddReserved(PeerId), RemoveReserved(PeerId), SetReserved(HashSet), - SetPeersetReserved(Cow<'static, str>, HashSet), - AddSetReserved(Cow<'static, str>, PeerId), - RemoveSetReserved(Cow<'static, str>, PeerId), - AddToPeersSet(Cow<'static, str>, PeerId), - RemoveFromPeersSet(Cow<'static, str>, PeerId), + SetPeersetReserved(ProtocolName, HashSet), + AddSetReserved(ProtocolName, PeerId), + RemoveSetReserved(ProtocolName, PeerId), + AddToPeersSet(ProtocolName, PeerId), + RemoveFromPeersSet(ProtocolName, PeerId), SyncFork(Vec, B::Hash, NumberFor), EventStream(out_events::Sender), Request { target: PeerId, - protocol: Cow<'static, str>, + protocol: ProtocolName, request: Vec, pending_response: oneshot::Sender, RequestFailure>>, connect: IfDisconnected, @@ -1276,7 +1278,7 @@ enum ServiceToWorkerMsg { NetworkState { pending_response: oneshot::Sender>, }, - DisconnectPeer(PeerId, Cow<'static, str>), + DisconnectPeer(PeerId, ProtocolName), NewBestBlockImported(B::Hash, NumberFor), } @@ -1312,7 +1314,7 @@ where boot_node_ids: Arc>, /// For each peer and protocol combination, an object that allows sending notifications to /// that peer. Shared with the [`NetworkService`]. - peers_notifications_sinks: Arc), NotificationsSink>>>, + peers_notifications_sinks: Arc>>, /// Controller for the handler of incoming and outgoing transactions. tx_handler_controller: transactions::TransactionsHandlerController, } @@ -1456,7 +1458,7 @@ where .network_service .behaviour_mut() .user_protocol_mut() - .disconnect_peer(&who, &protocol_name), + .disconnect_peer(&who, protocol_name), ServiceToWorkerMsg::NewBestBlockImported(hash, number) => this .network_service .behaviour_mut() diff --git a/substrate/client/network/src/service/tests.rs b/substrate/client/network/src/service/tests.rs index e0d8798aef..8770e14bf5 100644 --- a/substrate/client/network/src/service/tests.rs +++ b/substrate/client/network/src/service/tests.rs @@ -32,7 +32,7 @@ use sc_network_sync::{ }; use sp_consensus::block_validation::DefaultBlockAnnounceValidator; use sp_runtime::traits::{Block as BlockT, Header as _}; -use std::{borrow::Cow, sync::Arc, time::Duration}; +use std::{sync::Arc, time::Duration}; use substrate_test_runtime_client::{TestClientBuilder, TestClientBuilderExt as _}; type TestNetworkService = NetworkService< @@ -165,7 +165,7 @@ fn build_test_full_node( (service, event_stream) } -const PROTOCOL_NAME: Cow<'static, str> = Cow::Borrowed("/foo"); +const PROTOCOL_NAME: &str = "/foo"; /// Builds two nodes and their associated events stream. /// The nodes are connected together and have the `PROTOCOL_NAME` protocol registered. @@ -179,7 +179,7 @@ fn build_nodes_one_proto() -> ( let (node1, events_stream1) = build_test_full_node(config::NetworkConfiguration { extra_sets: vec![config::NonDefaultSetConfig { - notifications_protocol: PROTOCOL_NAME, + notifications_protocol: PROTOCOL_NAME.into(), fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: Default::default(), @@ -191,7 +191,7 @@ fn build_nodes_one_proto() -> ( let (node2, events_stream2) = build_test_full_node(config::NetworkConfiguration { extra_sets: vec![config::NonDefaultSetConfig { - notifications_protocol: PROTOCOL_NAME, + notifications_protocol: PROTOCOL_NAME.into(), fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: config::SetConfig { @@ -219,10 +219,18 @@ fn notifications_state_consistent() { // Write some initial notifications that shouldn't get through. for _ in 0..(rand::random::() % 5) { - node1.write_notification(node2.local_peer_id(), PROTOCOL_NAME, b"hello world".to_vec()); + node1.write_notification( + node2.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } for _ in 0..(rand::random::() % 5) { - node2.write_notification(node1.local_peer_id(), PROTOCOL_NAME, b"hello world".to_vec()); + node2.write_notification( + node1.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } async_std::task::block_on(async move { @@ -247,24 +255,24 @@ fn notifications_state_consistent() { if rand::random::() % 5 >= 3 { node1.write_notification( node2.local_peer_id(), - PROTOCOL_NAME, + PROTOCOL_NAME.into(), b"hello world".to_vec(), ); } if rand::random::() % 5 >= 3 { node2.write_notification( node1.local_peer_id(), - PROTOCOL_NAME, + PROTOCOL_NAME.into(), b"hello world".to_vec(), ); } // Also randomly disconnect the two nodes from time to time. if rand::random::() % 20 == 0 { - node1.disconnect_peer(node2.local_peer_id(), PROTOCOL_NAME); + node1.disconnect_peer(node2.local_peer_id(), PROTOCOL_NAME.into()); } if rand::random::() % 20 == 0 { - node2.disconnect_peer(node1.local_peer_id(), PROTOCOL_NAME); + node2.disconnect_peer(node1.local_peer_id(), PROTOCOL_NAME.into()); } // Grab next event from either `events_stream1` or `events_stream2`. @@ -288,7 +296,7 @@ fn notifications_state_consistent() { future::Either::Left(Event::NotificationStreamOpened { remote, protocol, .. }) => - if protocol == PROTOCOL_NAME { + if protocol == PROTOCOL_NAME.into() { something_happened = true; assert!(!node1_to_node2_open); node1_to_node2_open = true; @@ -297,7 +305,7 @@ fn notifications_state_consistent() { future::Either::Right(Event::NotificationStreamOpened { remote, protocol, .. }) => - if protocol == PROTOCOL_NAME { + if protocol == PROTOCOL_NAME.into() { something_happened = true; assert!(!node2_to_node1_open); node2_to_node1_open = true; @@ -306,7 +314,7 @@ fn notifications_state_consistent() { future::Either::Left(Event::NotificationStreamClosed { remote, protocol, .. }) => - if protocol == PROTOCOL_NAME { + if protocol == PROTOCOL_NAME.into() { assert!(node1_to_node2_open); node1_to_node2_open = false; assert_eq!(remote, node2.local_peer_id()); @@ -314,7 +322,7 @@ fn notifications_state_consistent() { future::Either::Right(Event::NotificationStreamClosed { remote, protocol, .. }) => - if protocol == PROTOCOL_NAME { + if protocol == PROTOCOL_NAME.into() { assert!(node2_to_node1_open); node2_to_node1_open = false; assert_eq!(remote, node1.local_peer_id()); @@ -325,7 +333,7 @@ fn notifications_state_consistent() { if rand::random::() % 5 >= 4 { node1.write_notification( node2.local_peer_id(), - PROTOCOL_NAME, + PROTOCOL_NAME.into(), b"hello world".to_vec(), ); } @@ -336,7 +344,7 @@ fn notifications_state_consistent() { if rand::random::() % 5 >= 4 { node2.write_notification( node1.local_peer_id(), - PROTOCOL_NAME, + PROTOCOL_NAME.into(), b"hello world".to_vec(), ); } @@ -361,7 +369,7 @@ fn lots_of_incoming_peers_works() { let (main_node, _) = build_test_full_node(config::NetworkConfiguration { listen_addresses: vec![listen_addr.clone()], extra_sets: vec![config::NonDefaultSetConfig { - notifications_protocol: PROTOCOL_NAME, + notifications_protocol: PROTOCOL_NAME.into(), fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: config::SetConfig { in_peers: u32::MAX, ..Default::default() }, @@ -380,7 +388,7 @@ fn lots_of_incoming_peers_works() { let (_dialing_node, event_stream) = build_test_full_node(config::NetworkConfiguration { listen_addresses: vec![], extra_sets: vec![config::NonDefaultSetConfig { - notifications_protocol: PROTOCOL_NAME, + notifications_protocol: PROTOCOL_NAME.into(), fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: config::SetConfig { @@ -449,7 +457,7 @@ fn notifications_back_pressure() { Event::NotificationStreamClosed { .. } => panic!(), Event::NotificationsReceived { messages, .. } => for message in messages { - assert_eq!(message.0, PROTOCOL_NAME); + assert_eq!(message.0, PROTOCOL_NAME.into()); assert_eq!(message.1, format!("hello #{}", received_notifications)); received_notifications += 1; }, @@ -473,7 +481,7 @@ fn notifications_back_pressure() { // Sending! for num in 0..TOTAL_NOTIFS { - let notif = node1.notification_sender(node2_id, PROTOCOL_NAME).unwrap(); + let notif = node1.notification_sender(node2_id, PROTOCOL_NAME.into()).unwrap(); notif .ready() .await @@ -491,15 +499,14 @@ fn fallback_name_working() { // Node 1 supports the protocols "new" and "old". Node 2 only supports "old". Checks whether // they can connect. - const NEW_PROTOCOL_NAME: Cow<'static, str> = - Cow::Borrowed("/new-shiny-protocol-that-isnt-PROTOCOL_NAME"); + const NEW_PROTOCOL_NAME: &str = "/new-shiny-protocol-that-isnt-PROTOCOL_NAME"; let listen_addr = config::build_multiaddr![Memory(rand::random::())]; let (node1, mut events_stream1) = build_test_full_node(config::NetworkConfiguration { extra_sets: vec![config::NonDefaultSetConfig { - notifications_protocol: NEW_PROTOCOL_NAME.clone(), - fallback_names: vec![PROTOCOL_NAME], + notifications_protocol: NEW_PROTOCOL_NAME.into(), + fallback_names: vec![PROTOCOL_NAME.into()], max_notification_size: 1024 * 1024, set_config: Default::default(), }], @@ -510,7 +517,7 @@ fn fallback_name_working() { let (_, mut events_stream2) = build_test_full_node(config::NetworkConfiguration { extra_sets: vec![config::NonDefaultSetConfig { - notifications_protocol: PROTOCOL_NAME, + notifications_protocol: PROTOCOL_NAME.into(), fallback_names: Vec::new(), max_notification_size: 1024 * 1024, set_config: config::SetConfig { @@ -531,7 +538,7 @@ fn fallback_name_working() { loop { match events_stream2.next().await.unwrap() { Event::NotificationStreamOpened { protocol, negotiated_fallback, .. } => { - assert_eq!(protocol, PROTOCOL_NAME); + assert_eq!(protocol, PROTOCOL_NAME.into()); assert_eq!(negotiated_fallback, None); break }, @@ -545,9 +552,9 @@ fn fallback_name_working() { loop { match events_stream1.next().await.unwrap() { Event::NotificationStreamOpened { protocol, negotiated_fallback, .. } - if protocol == NEW_PROTOCOL_NAME => + if protocol == NEW_PROTOCOL_NAME.into() => { - assert_eq!(negotiated_fallback, Some(PROTOCOL_NAME)); + assert_eq!(negotiated_fallback, Some(PROTOCOL_NAME.into())); break }, _ => {}, diff --git a/substrate/client/network/src/transactions.rs b/substrate/client/network/src/transactions.rs index f557ec0cec..1cf532f33d 100644 --- a/substrate/client/network/src/transactions.rs +++ b/substrate/client/network/src/transactions.rs @@ -42,12 +42,14 @@ use log::{debug, trace, warn}; use prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64}; use sc_network_common::{ config::ProtocolId, - protocol::event::{Event, ObservedRole}, + protocol::{ + event::{Event, ObservedRole}, + ProtocolName, + }, service::{NetworkEventStream, NetworkNotification, NetworkPeers}, }; use sp_runtime::traits::Block as BlockT; use std::{ - borrow::Cow, collections::{hash_map::Entry, HashMap}, iter, num::NonZeroUsize, @@ -130,8 +132,8 @@ impl Future for PendingTransaction { /// Prototype for a [`TransactionsHandler`]. pub struct TransactionsHandlerPrototype { - protocol_name: Cow<'static, str>, - fallback_protocol_names: Vec>, + protocol_name: ProtocolName, + fallback_protocol_names: Vec, } impl TransactionsHandlerPrototype { @@ -244,7 +246,7 @@ enum ToHandler { /// Handler for transactions. Call [`TransactionsHandler::run`] to start the processing. pub struct TransactionsHandler { - protocol_name: Cow<'static, str>, + protocol_name: ProtocolName, /// Interval at which we call `propagate_transactions`. propagate_timeout: Pin + Send>>, /// Pending transactions verification tasks. diff --git a/substrate/client/network/test/src/lib.rs b/substrate/client/network/test/src/lib.rs index 323af13943..837cdeed0f 100644 --- a/substrate/client/network/test/src/lib.rs +++ b/substrate/client/network/test/src/lib.rs @@ -23,7 +23,6 @@ mod block_import; mod sync; use std::{ - borrow::Cow, collections::HashMap, marker::PhantomData, pin::Pin, @@ -58,6 +57,7 @@ use sc_network::{ }; use sc_network_common::{ config::{MultiaddrWithPeerId, ProtocolId}, + protocol::ProtocolName, service::{NetworkBlock, NetworkStateInfo, NetworkSyncForkRequest}, sync::warp::{AuthorityList, EncodedProof, SetId, VerificationResult, WarpSyncProvider}, }; @@ -682,7 +682,7 @@ pub struct FullPeerConfig { /// Block announce validator. pub block_announce_validator: Option + Send + Sync>>, /// List of notification protocols that the network must support. - pub notifications_protocols: Vec>, + pub notifications_protocols: Vec, /// The indices of the peers the peer should be connected to. /// /// If `None`, it will be connected to all other peers. diff --git a/substrate/client/offchain/src/api.rs b/substrate/client/offchain/src/api.rs index f40bceb615..6d6c52c989 100644 --- a/substrate/client/offchain/src/api.rs +++ b/substrate/client/offchain/src/api.rs @@ -328,11 +328,12 @@ mod tests { use sc_client_db::offchain::LocalStorage; use sc_network_common::{ config::MultiaddrWithPeerId, + protocol::ProtocolName, service::{NetworkPeers, NetworkStateInfo}, }; use sc_peerset::ReputationChange; use sp_core::offchain::{DbExternalities, Externalities}; - use std::{borrow::Cow, time::SystemTime}; + use std::time::SystemTime; pub(super) struct TestNetwork(); @@ -353,7 +354,7 @@ mod tests { unimplemented!(); } - fn disconnect_peer(&self, _who: PeerId, _protocol: Cow<'static, str>) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -375,7 +376,7 @@ mod tests { fn set_reserved_peers( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); @@ -383,29 +384,25 @@ mod tests { fn add_peers_to_reserved_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_peers_from_reserved_set( - &self, - _protocol: Cow<'static, str>, - _peers: Vec, - ) { + fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec) { unimplemented!(); } fn add_to_peers_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec) { + fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec) { unimplemented!(); } diff --git a/substrate/client/offchain/src/lib.rs b/substrate/client/offchain/src/lib.rs index e215a01687..87e79833b9 100644 --- a/substrate/client/offchain/src/lib.rs +++ b/substrate/client/offchain/src/lib.rs @@ -249,12 +249,12 @@ mod tests { use libp2p::{Multiaddr, PeerId}; use sc_block_builder::BlockBuilderProvider as _; use sc_client_api::Backend as _; - use sc_network_common::config::MultiaddrWithPeerId; + use sc_network_common::{config::MultiaddrWithPeerId, protocol::ProtocolName}; use sc_peerset::ReputationChange; use sc_transaction_pool::{BasicPool, FullChainApi}; use sc_transaction_pool_api::{InPoolTransaction, TransactionPool}; use sp_consensus::BlockOrigin; - use std::{borrow::Cow, collections::HashSet, sync::Arc}; + use std::{collections::HashSet, sync::Arc}; use substrate_test_runtime_client::{ runtime::Block, ClientBlockImportExt, DefaultTestClientBuilderExt, TestClient, TestClientBuilderExt, @@ -289,7 +289,7 @@ mod tests { unimplemented!(); } - fn disconnect_peer(&self, _who: PeerId, _protocol: Cow<'static, str>) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -311,7 +311,7 @@ mod tests { fn set_reserved_peers( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); @@ -319,29 +319,25 @@ mod tests { fn add_peers_to_reserved_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_peers_from_reserved_set( - &self, - _protocol: Cow<'static, str>, - _peers: Vec, - ) { + fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec) { unimplemented!(); } fn add_to_peers_set( &self, - _protocol: Cow<'static, str>, + _protocol: ProtocolName, _peers: HashSet, ) -> Result<(), String> { unimplemented!(); } - fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec) { + fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec) { unimplemented!(); }