Use custom type for ProtocolName (#12172)

* Add ProtocolName custom type

* Use new ProtocolName in sc_network_common

* Use new ProtocolName in sc_network

* Use new ProtocolName for BEEFY and GRANDPA

* Use new ProtocolName for notifications

* Use new ProtocolName in sc_network (part 2)

* Use new ProtocolName in sc_network_gossip

* Use new ProtocolName in sc_offchain

* Remove unused imports

* Some more fixes

* Add tests

* Fix minor import issues

* Re-export ProtocolName in sc_network

* Revert "Re-export ProtocolName in sc_network"

This reverts commit 8d8ff71927e7750757f29c9bbd88dc0ba181d214.

* Re-export ProtocolName in sc_network

* Remove dependency on sc-network-common from beefy-gadget
This commit is contained in:
Dmitry Markin
2022-09-03 23:34:47 +03:00
committed by GitHub
parent 09a52ef882
commit 24d09fe8c7
27 changed files with 381 additions and 280 deletions
+5 -3
View File
@@ -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<Hash: AsRef<[u8]>>(
genesis_hash: &Hash,
chain_spec: &Box<dyn ChainSpec>,
) -> 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<Registry>,
/// 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<B>,
}
@@ -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<Hash: AsRef<[u8]>>(
genesis_hash: &Hash,
chain_spec: &Box<dyn ChainSpec>,
) -> 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)),
@@ -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<Multiaddr>,
) -> 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<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_peers_from_reserved_set(&self, _protocol: Cow<'static, str>, _peers: Vec<PeerId>) {}
fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {}
fn add_to_peers_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec<PeerId>) {
fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {
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<u8>) {
fn write_notification(&self, target: PeerId, _protocol: ProtocolName, message: Vec<u8>) {
let _ = self.sender.unbounded_send(Event::WriteNotification(target, message));
}
fn notification_sender(
&self,
_target: PeerId,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
) -> Result<Box<dyn NotificationSender>, NotificationSenderError> {
unimplemented!();
}
+3 -2
View File
@@ -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<TelemetryHandle>,
/// 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<Block: BlockT, C, N, SC, VR> {
/// [`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 {
+13 -25
View File
@@ -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<B: BlockT> {
state_machine: ConsensusGossip<B>,
network: Box<dyn Network<B> + Send>,
periodic_maintenance_interval: futures_timer::Delay,
protocol: Cow<'static, str>,
protocol: ProtocolName,
/// Incoming events from the network.
network_event_stream: Pin<Box<dyn Stream<Item = Event> + Send>>,
@@ -78,7 +77,7 @@ impl<B: BlockT> GossipEngine<B> {
/// Create a new instance.
pub fn new<N: Network<B> + Send + Clone + 'static>(
network: N,
protocol: impl Into<Cow<'static, str>>,
protocol: impl Into<ProtocolName>,
validator: Arc<dyn Validator<B>>,
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<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
@@ -390,28 +388,23 @@ mod tests {
fn add_peers_to_reserved_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_peers_from_reserved_set(
&self,
_protocol: Cow<'static, str>,
_peers: Vec<PeerId>,
) {
}
fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {}
fn add_to_peers_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec<PeerId>) {
fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {
unimplemented!();
}
@@ -430,19 +423,14 @@ mod tests {
}
impl NetworkNotification for TestNetwork {
fn write_notification(
&self,
_target: PeerId,
_protocol: Cow<'static, str>,
_message: Vec<u8>,
) {
fn write_notification(&self, _target: PeerId, _protocol: ProtocolName, _message: Vec<u8>) {
unimplemented!();
}
fn notification_sender(
&self,
_target: PeerId,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
) -> Result<Box<dyn NotificationSender>, 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<ChannelLengthAndTopic>, notifications: Vec<Vec<Message>>) {
let protocol = Cow::Borrowed("/my_protocol");
let protocol = ProtocolName::from("/my_protocol");
let remote_peer = PeerId::random();
let network = TestNetwork::default();
+5 -4
View File
@@ -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<B: BlockT>:
NetworkPeers + NetworkEventStream + NetworkNotification + NetworkBlock<B::Hash, NumberFor<B>>
{
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::<multiaddr::Multiaddr>();
let result = self.add_peers_to_reserved_set(protocol, iter::once(addr).collect());
@@ -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<B> for NetworkContext<'g, 'p, B> {
fn propagate<'a, B: BlockT, I>(
network: &mut dyn Network<B>,
protocol: Cow<'static, str>,
protocol: ProtocolName,
messages: I,
intent: MessageIntent,
peers: &mut HashMap<PeerId, PeerConsensus<B::Hash>>,
@@ -155,7 +155,7 @@ pub struct ConsensusGossip<B: BlockT> {
peers: HashMap<PeerId, PeerConsensus<B::Hash>>,
messages: Vec<MessageEntry<B>>,
known_messages: LruCache<B::Hash, ()>,
protocol: Cow<'static, str>,
protocol: ProtocolName,
validator: Arc<dyn Validator<B>>,
next_broadcast: Instant,
metrics: Option<Metrics>,
@@ -165,7 +165,7 @@ impl<B: BlockT> ConsensusGossip<B> {
/// Create a new instance using the given validator.
pub fn new(
validator: Arc<dyn Validator<B>>,
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<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
@@ -629,28 +628,23 @@ mod tests {
fn add_peers_to_reserved_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_peers_from_reserved_set(
&self,
_protocol: Cow<'static, str>,
_peers: Vec<PeerId>,
) {
}
fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {}
fn add_to_peers_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec<PeerId>) {
fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {
unimplemented!();
}
@@ -666,19 +660,14 @@ mod tests {
}
impl NetworkNotification for NoOpNetwork {
fn write_notification(
&self,
_target: PeerId,
_protocol: Cow<'static, str>,
_message: Vec<u8>,
) {
fn write_notification(&self, _target: PeerId, _protocol: ProtocolName, _message: Vec<u8>) {
unimplemented!();
}
fn notification_sender(
&self,
_target: PeerId,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
) -> Result<Box<dyn NotificationSender>, NotificationSenderError> {
unimplemented!();
}
@@ -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]>);
@@ -16,4 +16,131 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
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<str>),
}
impl From<&'static str> for ProtocolName {
fn from(name: &'static str) -> Self {
Self::Static(name)
}
}
impl From<Arc<str>> for ProtocolName {
fn from(name: Arc<str>) -> Self {
Self::OnHeap(name)
}
}
impl From<String> 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<str> 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<H: Hasher>(&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!(<ProtocolName as Borrow<str>>::borrow(&static_protocol_name), PROTOCOL);
assert_eq!(<ProtocolName as Borrow<str>>::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!(<ProtocolName as Borrow<str>>::borrow(&static_protocol_name1), PROTOCOL2);
assert_ne!(<ProtocolName as Borrow<str>>::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<T: Hash>(x: T) -> u64 {
let mut hasher = DefaultHasher::new();
x.hash(&mut hasher);
hasher.finish()
}
}
@@ -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<Cow<'static, str>>,
negotiated_fallback: Option<ProtocolName>,
/// 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)>,
},
}
@@ -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<Cow<'static, str>>,
pub fallback_names: Vec<ProtocolName>,
/// Maximum allowed size, in bytes, of a request.
///
+22 -22
View File
@@ -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<Multiaddr>,
) -> 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<Multiaddr>,
) -> Result<(), String>;
/// Remove peers from a peer set.
fn remove_peers_from_reserved_set(&self, protocol: Cow<'static, str>, peers: Vec<PeerId>);
fn remove_peers_from_reserved_set(&self, protocol: ProtocolName, peers: Vec<PeerId>);
/// 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<Multiaddr>,
) -> 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<PeerId>);
fn remove_from_peers_set(&self, protocol: ProtocolName, peers: Vec<PeerId>);
/// 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<Multiaddr>,
) -> 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<Multiaddr>,
) -> Result<(), String> {
T::add_peers_to_reserved_set(self, protocol, peers)
}
fn remove_peers_from_reserved_set(&self, protocol: Cow<'static, str>, peers: Vec<PeerId>) {
fn remove_peers_from_reserved_set(&self, protocol: ProtocolName, peers: Vec<PeerId>) {
T::remove_peers_from_reserved_set(self, protocol, peers)
}
fn add_to_peers_set(
&self,
protocol: Cow<'static, str>,
protocol: ProtocolName,
peers: HashSet<Multiaddr>,
) -> Result<(), String> {
T::add_to_peers_set(self, protocol, peers)
}
fn remove_from_peers_set(&self, protocol: Cow<'static, str>, peers: Vec<PeerId>) {
fn remove_from_peers_set(&self, protocol: ProtocolName, peers: Vec<PeerId>) {
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<u8>);
fn write_notification(&self, target: PeerId, protocol: ProtocolName, message: Vec<u8>);
/// 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<Box<dyn NotificationSender>, NotificationSenderError>;
}
@@ -511,14 +511,14 @@ where
T: ?Sized,
T: NetworkNotification,
{
fn write_notification(&self, target: PeerId, protocol: Cow<'static, str>, message: Vec<u8>) {
fn write_notification(&self, target: PeerId, protocol: ProtocolName, message: Vec<u8>) {
T::write_notification(self, target, protocol, message)
}
fn notification_sender(
&self,
target: PeerId,
protocol: Cow<'static, str>,
protocol: ProtocolName,
) -> Result<Box<dyn NotificationSender>, 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<u8>,
connect: IfDisconnected,
) -> Result<Vec<u8>, RequestFailure>;
@@ -565,7 +565,7 @@ pub trait NetworkRequest {
fn start_request(
&self,
target: PeerId,
protocol: Cow<'static, str>,
protocol: ProtocolName,
request: Vec<u8>,
tx: oneshot::Sender<Result<Vec<u8>, 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<u8>,
connect: IfDisconnected,
) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, RequestFailure>> + Send + 'async_trait>>
@@ -595,7 +595,7 @@ where
fn start_request(
&self,
target: PeerId,
protocol: Cow<'static, str>,
protocol: ProtocolName,
request: Vec<u8>,
tx: oneshot::Sender<Result<Vec<u8>, RequestFailure>>,
connect: IfDisconnected,
+11 -9
View File
@@ -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<B: BlockT> {
/// 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<Duration, ResponseFailure>,
@@ -130,7 +132,7 @@ pub enum BehaviourOut<B: BlockT> {
/// 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<B: BlockT> {
/// 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<Cow<'static, str>>,
negotiated_fallback: Option<ProtocolName>,
/// Object that permits sending notifications to the peer.
notifications_sink: NotificationsSink,
/// Role of the remote.
@@ -165,7 +167,7 @@ pub enum BehaviourOut<B: BlockT> {
/// 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<B: BlockT> {
/// 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<B: BlockT> {
/// 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.
+5 -6
View File
@@ -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<Cow<'static, str>>,
pub fallback_names: Vec<ProtocolName>,
/// 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<Cow<'static, str>>) {
pub fn add_fallback_names(&mut self, fallback_names: Vec<ProtocolName>) {
self.fallback_names.extend(fallback_names);
}
}
+3 -2
View File
@@ -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<T> = std::result::Result<T, Error>;
@@ -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,
},
}
+4 -1
View File
@@ -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,
+13 -13
View File
@@ -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<B: BlockT, Client> {
/// Handles opening the unique substream and sending and receiving raw messages.
behaviour: Notifications,
/// List of notifications protocols that have been registered.
notification_protocols: Vec<Cow<'static, str>>,
notification_protocols: Vec<ProtocolName>,
/// 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<PeerId>) {
pub fn set_reserved_peerset_peers(&self, protocol: ProtocolName, peers: HashSet<PeerId>) {
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<B: BlockT> {
/// 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<Cow<'static, str>>,
negotiated_fallback: Option<ProtocolName>,
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 {
@@ -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<Cow<'static, str>>,
pub fallback_names: Vec<ProtocolName>,
/// Handshake of the protocol.
pub handshake: Vec<u8>,
/// 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<Cow<'static, str>>,
negotiated_fallback: Option<ProtocolName>,
/// 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<u8>,
@@ -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<Cow<'static, str>>,
pub fallback_names: Vec<ProtocolName>,
/// Handshake of the protocol. The `RwLock` is locked every time a new substream is opened.
pub handshake: Arc<RwLock<Vec<u8>>>,
/// 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<Cow<'static, str>>,
negotiated_fallback: Option<ProtocolName>,
/// The endpoint of the connection that is open for custom protocols.
endpoint: ConnectedPoint,
/// Handshake that was sent to us.
@@ -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<Cow<'static, str>>,
protocol_names: Vec<ProtocolName>,
/// 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<Cow<'static, str>>,
protocol_names: Vec<ProtocolName>,
/// Message to send when we start the handshake.
initial_message: Vec<u8>,
/// Maximum allowed size for a single notification.
@@ -114,8 +114,8 @@ pub struct NotificationsOutSubstream<TSubstream> {
impl NotificationsIn {
/// Builds a new potential upgrade.
pub fn new(
main_protocol_name: impl Into<Cow<'static, str>>,
fallback_names: Vec<Cow<'static, str>>,
main_protocol_name: impl Into<ProtocolName>,
fallback_names: Vec<ProtocolName>,
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<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
self.protocol_names
.iter()
.cloned()
.map(StringProtocolName)
.collect::<Vec<_>>()
.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<TSubstream> {
pub handshake: Vec<u8>,
/// If the negotiated name is not the "main" protocol name but a fallback, contains the
/// name of the negotiated fallback.
pub negotiated_fallback: Option<Cow<'static, str>>,
pub negotiated_fallback: Option<ProtocolName>,
/// Implementation of `Stream` that allows receives messages from the substream.
pub substream: NotificationsInSubstream<TSubstream>,
}
@@ -334,8 +329,8 @@ where
impl NotificationsOut {
/// Builds a new potential upgrade.
pub fn new(
main_protocol_name: impl Into<Cow<'static, str>>,
fallback_names: Vec<Cow<'static, str>>,
main_protocol_name: impl Into<ProtocolName>,
fallback_names: Vec<ProtocolName>,
initial_message: impl Into<Vec<u8>>,
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<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
self.protocol_names
.iter()
.cloned()
.map(StringProtocolName)
.collect::<Vec<_>>()
.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<TSubstream> {
pub handshake: Vec<u8>,
/// If the negotiated name is not the "main" protocol name but a fallback, contains the
/// name of the negotiated fallback.
pub negotiated_fallback: Option<Cow<'static, str>>,
pub negotiated_fallback: Option<ProtocolName>,
/// Implementation of `Sink` that allows sending messages on the substream.
pub substream: NotificationsOutSubstream<TSubstream>,
}
@@ -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 {
@@ -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<GenericCodec>, Option<mpsc::Sender<IncomingRequest>>),
>,
@@ -162,7 +164,7 @@ struct MessageRequest {
request_id: RequestId,
request: Vec<u8>,
channel: ResponseChannel<Result<Vec<u8>, ()>>,
protocol: String,
protocol: ProtocolName,
resp_builder: Option<futures::channel::mpsc::Sender<IncomingRequest>>,
// 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<Result<Vec<u8>, ()>>,
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.
+26 -24
View File
@@ -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<B: BlockT + 'static, H: ExHashT> {
to_worker: TracingUnboundedSender<ServiceToWorkerMsg<B, H>>,
/// For each peer and protocol combination, an object that allows sending notifications to
/// that peer. Updated by the [`NetworkWorker`].
peers_notifications_sinks: Arc<Mutex<HashMap<(PeerId, Cow<'static, str>), NotificationsSink>>>,
peers_notifications_sinks: Arc<Mutex<HashMap<(PeerId, ProtocolName), NotificationsSink>>>,
/// Field extracted from the [`Metrics`] struct and necessary to report the
/// notifications-related metrics.
notifications_sizes_metric: Option<HistogramVec>,
@@ -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<Multiaddr>,
) -> 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<Multiaddr>,
) -> 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<PeerId>) {
fn remove_peers_from_reserved_set(&self, protocol: ProtocolName, peers: Vec<PeerId>) {
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<Multiaddr>,
) -> 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<PeerId>) {
fn remove_from_peers_set(&self, protocol: ProtocolName, peers: Vec<PeerId>) {
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<u8>) {
fn write_notification(&self, target: PeerId, protocol: ProtocolName, message: Vec<u8>) {
// 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<Box<dyn NotificationSenderT>, 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<u8>,
connect: IfDisconnected,
) -> Result<Vec<u8>, RequestFailure> {
@@ -1128,7 +1130,7 @@ where
fn start_request(
&self,
target: PeerId,
protocol: Cow<'static, str>,
protocol: ProtocolName,
request: Vec<u8>,
tx: oneshot::Sender<Result<Vec<u8>, 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<B: BlockT, H: ExHashT> {
AddReserved(PeerId),
RemoveReserved(PeerId),
SetReserved(HashSet<PeerId>),
SetPeersetReserved(Cow<'static, str>, HashSet<PeerId>),
AddSetReserved(Cow<'static, str>, PeerId),
RemoveSetReserved(Cow<'static, str>, PeerId),
AddToPeersSet(Cow<'static, str>, PeerId),
RemoveFromPeersSet(Cow<'static, str>, PeerId),
SetPeersetReserved(ProtocolName, HashSet<PeerId>),
AddSetReserved(ProtocolName, PeerId),
RemoveSetReserved(ProtocolName, PeerId),
AddToPeersSet(ProtocolName, PeerId),
RemoveFromPeersSet(ProtocolName, PeerId),
SyncFork(Vec<PeerId>, B::Hash, NumberFor<B>),
EventStream(out_events::Sender),
Request {
target: PeerId,
protocol: Cow<'static, str>,
protocol: ProtocolName,
request: Vec<u8>,
pending_response: oneshot::Sender<Result<Vec<u8>, RequestFailure>>,
connect: IfDisconnected,
@@ -1276,7 +1278,7 @@ enum ServiceToWorkerMsg<B: BlockT, H: ExHashT> {
NetworkState {
pending_response: oneshot::Sender<Result<NetworkState, RequestFailure>>,
},
DisconnectPeer(PeerId, Cow<'static, str>),
DisconnectPeer(PeerId, ProtocolName),
NewBestBlockImported(B::Hash, NumberFor<B>),
}
@@ -1312,7 +1314,7 @@ where
boot_node_ids: Arc<HashSet<PeerId>>,
/// For each peer and protocol combination, an object that allows sending notifications to
/// that peer. Shared with the [`NetworkService`].
peers_notifications_sinks: Arc<Mutex<HashMap<(PeerId, Cow<'static, str>), NotificationsSink>>>,
peers_notifications_sinks: Arc<Mutex<HashMap<(PeerId, ProtocolName), NotificationsSink>>>,
/// Controller for the handler of incoming and outgoing transactions.
tx_handler_controller: transactions::TransactionsHandlerController<H>,
}
@@ -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()
+35 -28
View File
@@ -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::<u8>() % 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::<u8>() % 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::<u8>() % 5 >= 3 {
node1.write_notification(
node2.local_peer_id(),
PROTOCOL_NAME,
PROTOCOL_NAME.into(),
b"hello world".to_vec(),
);
}
if rand::random::<u8>() % 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::<u8>() % 20 == 0 {
node1.disconnect_peer(node2.local_peer_id(), PROTOCOL_NAME);
node1.disconnect_peer(node2.local_peer_id(), PROTOCOL_NAME.into());
}
if rand::random::<u8>() % 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::<u8>() % 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::<u8>() % 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::<u64>())];
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
},
_ => {},
+7 -5
View File
@@ -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<H: ExHashT> Future for PendingTransaction<H> {
/// Prototype for a [`TransactionsHandler`].
pub struct TransactionsHandlerPrototype {
protocol_name: Cow<'static, str>,
fallback_protocol_names: Vec<Cow<'static, str>>,
protocol_name: ProtocolName,
fallback_protocol_names: Vec<ProtocolName>,
}
impl TransactionsHandlerPrototype {
@@ -244,7 +246,7 @@ enum ToHandler<H: ExHashT> {
/// Handler for transactions. Call [`TransactionsHandler::run`] to start the processing.
pub struct TransactionsHandler<B: BlockT + 'static, H: ExHashT> {
protocol_name: Cow<'static, str>,
protocol_name: ProtocolName,
/// Interval at which we call `propagate_transactions`.
propagate_timeout: Pin<Box<dyn Stream<Item = ()> + Send>>,
/// Pending transactions verification tasks.
+2 -2
View File
@@ -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<Box<dyn BlockAnnounceValidator<Block> + Send + Sync>>,
/// List of notification protocols that the network must support.
pub notifications_protocols: Vec<Cow<'static, str>>,
pub notifications_protocols: Vec<ProtocolName>,
/// The indices of the peers the peer should be connected to.
///
/// If `None`, it will be connected to all other peers.
+8 -11
View File
@@ -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<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
@@ -383,29 +384,25 @@ mod tests {
fn add_peers_to_reserved_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_peers_from_reserved_set(
&self,
_protocol: Cow<'static, str>,
_peers: Vec<PeerId>,
) {
fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {
unimplemented!();
}
fn add_to_peers_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec<PeerId>) {
fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {
unimplemented!();
}
+8 -12
View File
@@ -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<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
@@ -319,29 +319,25 @@ mod tests {
fn add_peers_to_reserved_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_peers_from_reserved_set(
&self,
_protocol: Cow<'static, str>,
_peers: Vec<PeerId>,
) {
fn remove_peers_from_reserved_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {
unimplemented!();
}
fn add_to_peers_set(
&self,
_protocol: Cow<'static, str>,
_protocol: ProtocolName,
_peers: HashSet<Multiaddr>,
) -> Result<(), String> {
unimplemented!();
}
fn remove_from_peers_set(&self, _protocol: Cow<'static, str>, _peers: Vec<PeerId>) {
fn remove_from_peers_set(&self, _protocol: ProtocolName, _peers: Vec<PeerId>) {
unimplemented!();
}