diff --git a/core/src/either.rs b/core/src/either.rs index 8049717a878..a04029cc035 100644 --- a/core/src/either.rs +++ b/core/src/either.rs @@ -22,7 +22,7 @@ use crate::muxing::StreamMuxerEvent; use crate::{ muxing::StreamMuxer, transport::{ListenerId, Transport, TransportError, TransportEvent}, - Multiaddr, ProtocolName, + Multiaddr, }; use either::Either; use futures::prelude::*; @@ -121,15 +121,6 @@ pub enum EitherName { B(B), } -impl ProtocolName for EitherName { - fn protocol_name(&self) -> &[u8] { - match self { - EitherName::A(a) => a.protocol_name(), - EitherName::B(b) => b.protocol_name(), - } - } -} - impl Transport for Either where B: Transport, diff --git a/core/src/lib.rs b/core/src/lib.rs index 7a9abce1e7d..e7b7c53206c 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -126,7 +126,9 @@ pub use peer_record::PeerRecord; pub use signed_envelope::SignedEnvelope; pub use translation::address_translation; pub use transport::Transport; -pub use upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeError, UpgradeProtocols}; +#[allow(deprecated)] +pub use upgrade::ProtocolName; +pub use upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeError, UpgradeProtocols}; #[allow(deprecated)] pub use upgrade::UpgradeInfo; diff --git a/core/src/upgrade.rs b/core/src/upgrade.rs index cb19118ebc7..e7c27581fd6 100644 --- a/core/src/upgrade.rs +++ b/core/src/upgrade.rs @@ -121,6 +121,7 @@ pub use multistream_select::{NegotiatedComplete, NegotiationError, ProtocolError /// } /// ``` /// +#[deprecated(note = "Use the `Protocol` new-type instead.")] pub trait ProtocolName { /// The protocol name as bytes. Transmitted on the network. /// @@ -129,6 +130,7 @@ pub trait ProtocolName { fn protocol_name(&self) -> &[u8]; } +#[allow(deprecated)] impl> ProtocolName for T { fn protocol_name(&self) -> &[u8] { self.as_ref() @@ -138,6 +140,7 @@ impl> ProtocolName for T { /// Common trait for upgrades that can be applied on inbound substreams, outbound substreams, /// or both. #[deprecated(note = "Implement `UpgradeProtocols` instead.")] +#[allow(deprecated)] pub trait UpgradeInfo { /// Opaque type representing a negotiable protocol. type Info: ProtocolName + Clone; @@ -237,6 +240,7 @@ where } } +#[allow(deprecated)] fn filter_non_utf8_protocols(p: impl ProtocolName) -> Option { let name = p.protocol_name(); diff --git a/core/src/upgrade/from_fn.rs b/core/src/upgrade/from_fn.rs index 8e81ebd2dc8..1baee00020c 100644 --- a/core/src/upgrade/from_fn.rs +++ b/core/src/upgrade/from_fn.rs @@ -19,9 +19,9 @@ // DEALINGS IN THE SOFTWARE. #[allow(deprecated)] -use crate::upgrade::UpgradeInfo; +use crate::upgrade::{ProtocolName, UpgradeInfo}; use crate::{ - upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName}, + upgrade::{InboundUpgrade, OutboundUpgrade}, Endpoint, }; @@ -55,6 +55,7 @@ use std::iter; /// }); /// ``` /// +#[allow(deprecated)] pub fn from_fn(protocol_name: P, fun: F) -> FromFnUpgrade where // Note: these bounds are there in order to help the compiler infer types @@ -87,6 +88,7 @@ where } } +#[allow(deprecated)] impl InboundUpgrade for FromFnUpgrade where P: ProtocolName + Clone, @@ -102,6 +104,7 @@ where } } +#[allow(deprecated)] impl OutboundUpgrade for FromFnUpgrade where P: ProtocolName + Clone, diff --git a/examples/file-sharing/src/network.rs b/examples/file-sharing/src/network.rs index f21ff95276d..749a59d38b7 100644 --- a/examples/file-sharing/src/network.rs +++ b/examples/file-sharing/src/network.rs @@ -6,7 +6,7 @@ use futures::prelude::*; use libp2p::{ core::{ - upgrade::{read_length_prefixed, write_length_prefixed, ProtocolName}, + upgrade::{read_length_prefixed, write_length_prefixed}, Multiaddr, }, identity, @@ -19,6 +19,7 @@ use libp2p::{ PeerId, }; +use libp2p::core::upgrade; use std::collections::{hash_map, HashMap, HashSet}; use std::error::Error; use std::iter; @@ -53,7 +54,7 @@ pub async fn new( kademlia: Kademlia::new(peer_id, MemoryStore::new(peer_id)), request_response: request_response::Behaviour::new( FileExchangeCodec(), - iter::once((FileExchangeProtocol(), ProtocolSupport::Full)), + iter::once((FILE_EXCHANGE_PROTOCOL, ProtocolSupport::Full)), Default::default(), ), }, @@ -453,8 +454,9 @@ pub enum Event { // Simple file exchange protocol -#[derive(Debug, Clone)] -struct FileExchangeProtocol(); +const FILE_EXCHANGE_PROTOCOL: upgrade::Protocol = + upgrade::Protocol::from_static("/file-exchange/1"); + #[derive(Clone)] struct FileExchangeCodec(); #[derive(Debug, Clone, PartialEq, Eq)] @@ -462,21 +464,14 @@ struct FileRequest(String); #[derive(Debug, Clone, PartialEq, Eq)] pub struct FileResponse(Vec); -impl ProtocolName for FileExchangeProtocol { - fn protocol_name(&self) -> &[u8] { - "/file-exchange/1".as_bytes() - } -} - #[async_trait] impl request_response::Codec for FileExchangeCodec { - type Protocol = FileExchangeProtocol; type Request = FileRequest; type Response = FileResponse; async fn read_request( &mut self, - _: &FileExchangeProtocol, + _: &upgrade::Protocol, io: &mut T, ) -> io::Result where @@ -493,7 +488,7 @@ impl request_response::Codec for FileExchangeCodec { async fn read_response( &mut self, - _: &FileExchangeProtocol, + _: &upgrade::Protocol, io: &mut T, ) -> io::Result where @@ -510,7 +505,7 @@ impl request_response::Codec for FileExchangeCodec { async fn write_request( &mut self, - _: &FileExchangeProtocol, + _: &upgrade::Protocol, io: &mut T, FileRequest(data): FileRequest, ) -> io::Result<()> @@ -525,7 +520,7 @@ impl request_response::Codec for FileExchangeCodec { async fn write_response( &mut self, - _: &FileExchangeProtocol, + _: &upgrade::Protocol, io: &mut T, FileResponse(data): FileResponse, ) -> io::Result<()> diff --git a/misc/metrics/src/identify.rs b/misc/metrics/src/identify.rs index e93620b4fef..0f40c1978c8 100644 --- a/misc/metrics/src/identify.rs +++ b/misc/metrics/src/identify.rs @@ -19,6 +19,7 @@ // DEALINGS IN THE SOFTWARE. use crate::protocol_stack; +use libp2p_core::upgrade::Protocol; use libp2p_identity::PeerId; use prometheus_client::encoding::{EncodeLabelSet, EncodeMetric, MetricEncoder}; use prometheus_client::metrics::counter::Counter; @@ -134,12 +135,12 @@ impl super::Recorder for Metrics { } libp2p_identify::Event::Received { peer_id, info, .. } => { { - let mut protocols: Vec = info + let mut protocols = info .protocols .iter() + .filter_map(|p| Protocol::try_from_owned(p.to_owned()).ok()) .filter(|p| { - let allowed_protocols: &[&[u8]] = &[ - #[cfg(feature = "dcutr")] + let allowed_protocols = [ libp2p_dcutr::PROTOCOL_NAME, // #[cfg(feature = "gossipsub")] // #[cfg(not(target_os = "unknown"))] @@ -156,10 +157,10 @@ impl super::Recorder for Metrics { libp2p_relay::HOP_PROTOCOL_NAME, ]; - allowed_protocols.contains(&p.as_bytes()) + allowed_protocols.contains(p) }) - .cloned() - .collect(); + .map(|p| p.to_string()) + .collect::>(); // Signal via an additional label value that one or more // protocols of the remote peer have not been recognized. diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index b0d07f7a37b..c46d8044989 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -21,7 +21,8 @@ mod as_client; mod as_server; -use crate::protocol::{AutoNatCodec, AutoNatProtocol, DialRequest, DialResponse, ResponseError}; +use crate::protocol::{AutoNatCodec, DialRequest, DialResponse, ResponseError}; +use crate::DEFAULT_PROTOCOL_NAME; use as_client::AsClient; pub use as_client::{OutboundProbeError, OutboundProbeEvent}; use as_server::AsServer; @@ -218,7 +219,7 @@ pub struct Behaviour { impl Behaviour { pub fn new(local_peer_id: PeerId, config: Config) -> Self { - let protocols = iter::once((AutoNatProtocol, ProtocolSupport::Full)); + let protocols = iter::once((DEFAULT_PROTOCOL_NAME, ProtocolSupport::Full)); let mut cfg = request_response::Config::default(); cfg.set_request_timeout(config.timeout); let inner = request_response::Behaviour::new(AutoNatCodec, protocols, cfg); diff --git a/protocols/autonat/src/protocol.rs b/protocols/autonat/src/protocol.rs index 82e448cda24..7bb206174a1 100644 --- a/protocols/autonat/src/protocol.rs +++ b/protocols/autonat/src/protocol.rs @@ -21,38 +21,25 @@ use crate::proto; use async_trait::async_trait; use futures::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; +use libp2p_core::upgrade::Protocol; use libp2p_core::{upgrade, Multiaddr}; use libp2p_identity::PeerId; -use libp2p_request_response::{self as request_response, ProtocolName}; +use libp2p_request_response::{self as request_response}; use quick_protobuf::{BytesReader, Writer}; use std::{convert::TryFrom, io}; -#[derive(Clone, Debug)] -pub struct AutoNatProtocol; - /// The protocol name used for negotiating with multistream-select. -pub const DEFAULT_PROTOCOL_NAME: &[u8] = b"/libp2p/autonat/1.0.0"; - -impl ProtocolName for AutoNatProtocol { - fn protocol_name(&self) -> &[u8] { - DEFAULT_PROTOCOL_NAME - } -} +pub const DEFAULT_PROTOCOL_NAME: Protocol = Protocol::from_static("/libp2p/autonat/1.0.0"); #[derive(Clone)] pub struct AutoNatCodec; #[async_trait] impl request_response::Codec for AutoNatCodec { - type Protocol = AutoNatProtocol; type Request = DialRequest; type Response = DialResponse; - async fn read_request( - &mut self, - _: &AutoNatProtocol, - io: &mut T, - ) -> io::Result + async fn read_request(&mut self, _: &Protocol, io: &mut T) -> io::Result where T: AsyncRead + Send + Unpin, { @@ -61,11 +48,7 @@ impl request_response::Codec for AutoNatCodec { Ok(request) } - async fn read_response( - &mut self, - _: &AutoNatProtocol, - io: &mut T, - ) -> io::Result + async fn read_response(&mut self, _: &Protocol, io: &mut T) -> io::Result where T: AsyncRead + Send + Unpin, { @@ -76,7 +59,7 @@ impl request_response::Codec for AutoNatCodec { async fn write_request( &mut self, - _: &AutoNatProtocol, + _: &Protocol, io: &mut T, data: Self::Request, ) -> io::Result<()> @@ -89,7 +72,7 @@ impl request_response::Codec for AutoNatCodec { async fn write_response( &mut self, - _: &AutoNatProtocol, + _: &Protocol, io: &mut T, data: Self::Response, ) -> io::Result<()> diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index fb58e55f24a..e292cb0b13b 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -3249,7 +3249,7 @@ where .get(&peer_id) .expect("Connected peer must be registered") .kind; - metrics.peer_protocol_disconnected(peer_kind.clone()); + metrics.peer_protocol_disconnected(*peer_kind); } self.connected_peers.remove(&peer_id); @@ -3346,7 +3346,7 @@ where // We have identified the protocol this peer is using if let Some(metrics) = self.metrics.as_mut() { - metrics.peer_protocol_connected(kind.clone()); + metrics.peer_protocol_connected(kind); } if let PeerKind::NotSupported = kind { diff --git a/protocols/gossipsub/src/config.rs b/protocols/gossipsub/src/config.rs index 1f0b23848d6..3ecef1fad0c 100644 --- a/protocols/gossipsub/src/config.rs +++ b/protocols/gossipsub/src/config.rs @@ -886,9 +886,9 @@ mod test { use super::*; use crate::protocol::ProtocolConfig; use crate::topic::IdentityHash; - use crate::types::PeerKind; use crate::Topic; - use libp2p_core::UpgradeInfo; + use libp2p_core::upgrade::Protocol; + use libp2p_core::UpgradeProtocols; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -991,15 +991,15 @@ mod test { assert_eq!(builder.custom_id_version(), &None); let protocol_config = ProtocolConfig::new(&builder); - let protocol_ids = protocol_config.protocol_info(); + let protocol_ids = protocol_config.protocols().collect::>(); assert_eq!(protocol_ids.len(), 2); - assert_eq!(protocol_ids[0].protocol_id, b"/purple/1.1.0".to_vec()); - assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsubv1_1); + assert_eq!(protocol_ids[0], Protocol::from_static("/purple/1.1.0")); + // assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsubv1_1); // TODO - assert_eq!(protocol_ids[1].protocol_id, b"/purple/1.0.0".to_vec()); - assert_eq!(protocol_ids[1].kind, PeerKind::Gossipsub); + assert_eq!(protocol_ids[1], Protocol::from_static("/purple/1.0.0")); + // assert_eq!(protocol_ids[1].kind, PeerKind::Gossipsub); // TODO } #[test] @@ -1015,11 +1015,11 @@ mod test { assert_eq!(builder.custom_id_version(), &Some(Version::V1_0)); let protocol_config = ProtocolConfig::new(&builder); - let protocol_ids = protocol_config.protocol_info(); + let protocol_ids = protocol_config.protocols().collect::>(); assert_eq!(protocol_ids.len(), 1); - assert_eq!(protocol_ids[0].protocol_id, b"purple".to_vec()); - assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsub); + assert_eq!(protocol_ids[0], Protocol::from_static("purple")); + // assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsub); } } diff --git a/protocols/gossipsub/src/handler.rs b/protocols/gossipsub/src/handler.rs index 609bb81a306..09f28fcc106 100644 --- a/protocols/gossipsub/src/handler.rs +++ b/protocols/gossipsub/src/handler.rs @@ -79,6 +79,7 @@ pub enum HandlerIn { /// creation loops. const MAX_SUBSTREAM_ATTEMPTS: usize = 5; +#[allow(clippy::large_enum_variant)] pub enum Handler { Enabled(EnabledHandler), Disabled(DisabledHandler), @@ -229,10 +230,10 @@ impl EnabledHandler { >, > { if !self.peer_kind_sent { - if let Some(peer_kind) = self.peer_kind.as_ref() { + if let Some(peer_kind) = self.peer_kind { self.peer_kind_sent = true; return Poll::Ready(ConnectionHandlerEvent::Custom(HandlerEvent::PeerKind( - peer_kind.clone(), + peer_kind, ))); } } diff --git a/protocols/gossipsub/src/protocol.rs b/protocols/gossipsub/src/protocol.rs index 996bd402279..14be513e2b4 100644 --- a/protocols/gossipsub/src/protocol.rs +++ b/protocols/gossipsub/src/protocol.rs @@ -32,7 +32,7 @@ use bytes::BytesMut; use futures::future; use futures::prelude::*; use libp2p_core::upgrade::Protocol; -use libp2p_core::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeInfo}; +use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeProtocols}; use libp2p_identity::{PeerId, PublicKey}; use log::{debug, warn}; use quick_protobuf::Writer; @@ -117,7 +117,7 @@ impl ProtocolId { }; } - let protocol_id = match kind { + let protocol = match kind { PeerKind::Gossipsubv1_1 => { Protocol::try_from_owned(format!("/{}/1.1.0", id)).expect("starts with a slash") } @@ -128,24 +128,20 @@ impl ProtocolId { // NOTE: This is used for informing the behaviour of unsupported peers. We do not // advertise this variant. PeerKind::NotSupported => unreachable!("Should never advertise NotSupported"), - } - .into_bytes(); - ProtocolId { protocol_id, kind } - } -} + }; -impl ProtocolName for ProtocolId { - fn protocol_name(&self) -> &[u8] { - &self.protocol_id + ProtocolId { + protocol_id: protocol, + kind, + } } } -impl UpgradeInfo for ProtocolConfig { - type Info = ProtocolId; - type InfoIter = Vec; +impl UpgradeProtocols for ProtocolConfig { + type Iter = std::iter::Map, fn(ProtocolId) -> Protocol>; - fn protocol_info(&self) -> Self::InfoIter { - self.protocol_ids.clone() + fn protocols(&self) -> Self::Iter { + self.protocol_ids.clone().into_iter().map(|p| p.protocol_id) } } @@ -160,12 +156,19 @@ where fn upgrade_inbound(self, socket: TSocket, protocol_id: Protocol) -> Self::Future { let mut length_codec = codec::UviBytes::default(); length_codec.set_max_len(self.max_transmit_size); + + let peer_kind = self + .protocol_ids + .iter() + .find_map(|p| (p.protocol_id == protocol_id).then_some(p.kind)) + .expect("to receive a protocol id we support"); + Box::pin(future::ok(( Framed::new( socket, GossipsubCodec::new(length_codec, self.validation_mode), ), - protocol_id.kind, + peer_kind, ))) } } @@ -181,12 +184,19 @@ where fn upgrade_outbound(self, socket: TSocket, protocol_id: Protocol) -> Self::Future { let mut length_codec = codec::UviBytes::default(); length_codec.set_max_len(self.max_transmit_size); + + let peer_kind = self + .protocol_ids + .iter() + .find_map(|p| (p.protocol_id == protocol_id).then_some(p.kind)) + .expect("to receive a protocol id we support"); + Box::pin(future::ok(( Framed::new( socket, GossipsubCodec::new(length_codec, self.validation_mode), ), - protocol_id.kind, + peer_kind, ))) } } diff --git a/protocols/gossipsub/src/types.rs b/protocols/gossipsub/src/types.rs index ae9b5a09f35..e48f011c153 100644 --- a/protocols/gossipsub/src/types.rs +++ b/protocols/gossipsub/src/types.rs @@ -96,7 +96,7 @@ pub struct PeerConnections { } /// Describes the types of peers that can exist in the gossipsub context. -#[derive(Debug, Clone, PartialEq, Hash, EncodeLabelValue, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Hash, EncodeLabelValue, Eq)] pub enum PeerKind { /// A gossipsub 1.1 peer. Gossipsubv1_1, diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index b34c5e428f7..56bc5738a2a 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -39,6 +39,7 @@ use crate::record_priv::{ use crate::K_VALUE; use fnv::{FnvHashMap, FnvHashSet}; use instant::Instant; +use libp2p_core::upgrade::Protocol; use libp2p_core::{ConnectedPoint, Endpoint, Multiaddr}; use libp2p_identity::PeerId; use libp2p_swarm::behaviour::{ @@ -56,8 +57,8 @@ use std::collections::{BTreeMap, HashSet, VecDeque}; use std::fmt; use std::num::NonZeroUsize; use std::task::{Context, Poll}; +use std::time::Duration; use std::vec; -use std::{borrow::Cow, time::Duration}; use thiserror::Error; pub use crate::query::QueryStats; @@ -228,7 +229,7 @@ impl KademliaConfig { /// More than one protocol name can be supplied. In this case the node will /// be able to talk to other nodes supporting any of the provided names. /// Multiple names must be used with caution to avoid network partitioning. - pub fn set_protocol_names(&mut self, names: Vec>) -> &mut Self { + pub fn set_protocol_names(&mut self, names: Vec) -> &mut Self { self.protocol_config.set_protocol_names(names); self } @@ -411,7 +412,7 @@ where } /// Get the protocol name of this kademlia instance. - pub fn protocol_names(&self) -> &[Cow<'static, [u8]>] { + pub fn protocol_names(&self) -> &[Protocol] { self.protocol_config.protocol_names() } diff --git a/protocols/kad/src/protocol_priv.rs b/protocols/kad/src/protocol_priv.rs index c3c3b29700c..47d3a14b9a9 100644 --- a/protocols/kad/src/protocol_priv.rs +++ b/protocols/kad/src/protocol_priv.rs @@ -33,16 +33,16 @@ use bytes::BytesMut; use codec::UviBytes; use futures::prelude::*; use instant::Instant; -use libp2p_core::upgrade::{InboundUpgrade, OutboundUpgrade, Protocol, UpgradeInfo}; -use libp2p_core::Multiaddr; +use libp2p_core::upgrade::{InboundUpgrade, OutboundUpgrade, Protocol}; +use libp2p_core::{Multiaddr, UpgradeProtocols}; use libp2p_identity::PeerId; use quick_protobuf::{BytesReader, Writer}; -use std::{borrow::Cow, convert::TryFrom, time::Duration}; +use std::{convert::TryFrom, time::Duration}; use std::{io, iter}; use unsigned_varint::codec; /// The protocol name used for negotiating with multistream-select. -pub const DEFAULT_PROTO_NAME: &[u8] = b"/ipfs/kad/1.0.0"; +pub const DEFAULT_PROTO_NAME: Protocol = Protocol::from_static("/ipfs/kad/1.0.0"); /// The default maximum size for a varint length-delimited packet. pub const DEFAULT_MAX_PACKET_SIZE: usize = 16 * 1024; @@ -139,20 +139,20 @@ impl From for proto::Peer { // `OutboundUpgrade` to be just a single message #[derive(Debug, Clone)] pub struct KademliaProtocolConfig { - protocol_names: Vec>, + protocol_names: Vec, /// Maximum allowed size of a packet. max_packet_size: usize, } impl KademliaProtocolConfig { /// Returns the configured protocol name. - pub fn protocol_names(&self) -> &[Cow<'static, [u8]>] { + pub fn protocol_names(&self) -> &[Protocol] { &self.protocol_names } /// Modifies the protocol names used on the wire. Can be used to create incompatibilities /// between networks on purpose. - pub fn set_protocol_names(&mut self, names: Vec>) { + pub fn set_protocol_names(&mut self, names: Vec) { self.protocol_names = names; } @@ -165,17 +165,16 @@ impl KademliaProtocolConfig { impl Default for KademliaProtocolConfig { fn default() -> Self { KademliaProtocolConfig { - protocol_names: iter::once(Cow::Borrowed(DEFAULT_PROTO_NAME)).collect(), + protocol_names: iter::once(DEFAULT_PROTO_NAME).collect(), max_packet_size: DEFAULT_MAX_PACKET_SIZE, } } } -impl UpgradeInfo for KademliaProtocolConfig { - type Info = Cow<'static, [u8]>; - type InfoIter = std::vec::IntoIter; +impl UpgradeProtocols for KademliaProtocolConfig { + type Iter = std::vec::IntoIter; - fn protocol_info(&self) -> Self::InfoIter { + fn protocols(&self) -> Self::Iter { self.protocol_names.clone().into_iter() } } diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index baaf148f2b5..819c1ef6930 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -155,17 +155,18 @@ pub mod protocol { )] pub type OutboundStopFatalUpgradeError = crate::outbound::stop::FatalUpgradeError; - #[deprecated( - since = "0.15.0", - note = "Use libp2p_relay::HOP_PROTOCOL_NAME instead." - )] - pub const HOP_PROTOCOL_NAME: &[u8; 31] = crate::HOP_PROTOCOL_NAME; - - #[deprecated( - since = "0.15.0", - note = "Use libp2p_relay::STOP_PROTOCOL_NAME instead." - )] - pub const STOP_PROTOCOL_NAME: &[u8; 32] = crate::STOP_PROTOCOL_NAME; + // TODO: Need to delete these before we can merge this PR. + // #[deprecated( + // since = "0.15.0", + // note = "Use libp2p_relay::HOP_PROTOCOL_NAME instead." + // )] + // pub const HOP_PROTOCOL_NAME: &[u8; 31] = crate::HOP_PROTOCOL_NAME; + + // #[deprecated( + // since = "0.15.0", + // note = "Use libp2p_relay::STOP_PROTOCOL_NAME instead." + // )] + // pub const STOP_PROTOCOL_NAME: &[u8; 32] = crate::STOP_PROTOCOL_NAME; } #[deprecated( diff --git a/protocols/rendezvous/src/handler.rs b/protocols/rendezvous/src/handler.rs index d07bf4d248f..0bb07a0afd7 100644 --- a/protocols/rendezvous/src/handler.rs +++ b/protocols/rendezvous/src/handler.rs @@ -20,9 +20,10 @@ use crate::codec; use crate::codec::Message; +use libp2p_core::upgrade::Protocol; use void::Void; -const PROTOCOL_IDENT: &[u8] = b"/rendezvous/1.0.0"; +const PROTOCOL_IDENT: Protocol = Protocol::from_static("/rendezvous/1.0.0"); pub mod inbound; pub mod outbound; diff --git a/protocols/request-response/src/codec.rs b/protocols/request-response/src/codec.rs index 91157472718..46ae1a0b0fc 100644 --- a/protocols/request-response/src/codec.rs +++ b/protocols/request-response/src/codec.rs @@ -18,72 +18,11 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -pub use libp2p_core::ProtocolName; - use async_trait::async_trait; use futures::prelude::*; use libp2p_core::upgrade::Protocol; use std::io; -/// A `RequestResponseCodec` defines the request and response types -/// for a request-response `Behaviour` protocol or -/// protocol family and how they are encoded / decoded on an I/O stream. -#[deprecated( - since = "0.24.0", - note = "Use re-exports that omit `RequestResponse` prefix, i.e. `libp2p::request_response::Codec`" -)] -#[async_trait] -pub trait RequestResponseCodec { - /// The type of protocol(s) or protocol versions being negotiated. - type Protocol: ProtocolName + Send + Clone; - /// The type of inbound and outbound requests. - type Request: Send; - /// The type of inbound and outbound responses. - type Response: Send; - - /// Reads a request from the given I/O stream according to the - /// negotiated protocol. - async fn read_request( - &mut self, - protocol: &Self::Protocol, - io: &mut T, - ) -> io::Result - where - T: AsyncRead + Unpin + Send; - - /// Reads a response from the given I/O stream according to the - /// negotiated protocol. - async fn read_response( - &mut self, - protocol: &Self::Protocol, - io: &mut T, - ) -> io::Result - where - T: AsyncRead + Unpin + Send; - - /// Writes a request to the given I/O stream according to the - /// negotiated protocol. - async fn write_request( - &mut self, - protocol: &Self::Protocol, - io: &mut T, - req: Self::Request, - ) -> io::Result<()> - where - T: AsyncWrite + Unpin + Send; - - /// Writes a response to the given I/O stream according to the - /// negotiated protocol. - async fn write_response( - &mut self, - protocol: &Self::Protocol, - io: &mut T, - res: Self::Response, - ) -> io::Result<()> - where - T: AsyncWrite + Unpin + Send; -} - /// A `Codec` defines the request and response types /// for a request-response [`Behaviour`](crate::Behaviour) protocol or /// protocol family and how they are encoded / decoded on an I/O stream. @@ -136,61 +75,3 @@ pub trait Codec { where T: AsyncWrite + Unpin + Send; } - -#[allow(deprecated)] -#[async_trait] -impl Codec for U -where - U: RequestResponseCodec + Send, - U::Protocol: Sync, -{ - type Request = U::Request; - - type Response = U::Response; - - async fn read_request( - &mut self, - protocol: &Protocol, - io: &mut T, - ) -> io::Result - where - T: AsyncRead + Unpin + Send, - { - self.read_request(protocol, io).await - } - - async fn read_response( - &mut self, - protocol: &Protocol, - io: &mut T, - ) -> io::Result - where - T: AsyncRead + Unpin + Send, - { - self.read_response(protocol, io).await - } - - async fn write_request( - &mut self, - protocol: &Protocol, - io: &mut T, - req: Self::Request, - ) -> io::Result<()> - where - T: AsyncWrite + Unpin + Send, - { - self.write_request(protocol, io, req).await - } - - async fn write_response( - &mut self, - protocol: &Protocol, - io: &mut T, - res: Self::Response, - ) -> io::Result<()> - where - T: AsyncWrite + Unpin + Send, - { - self.write_response(protocol, io, res).await - } -} diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index dd163d7252f..33cc339b27d 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -61,10 +61,7 @@ pub mod codec; pub mod handler; -pub use codec::{Codec, ProtocolName}; - -#[allow(deprecated)] -pub use codec::RequestResponseCodec; +pub use codec::Codec; pub use handler::ProtocolSupport; diff --git a/protocols/request-response/tests/ping.rs b/protocols/request-response/tests/ping.rs index c69f771dbe0..cc21dfdd1d6 100644 --- a/protocols/request-response/tests/ping.rs +++ b/protocols/request-response/tests/ping.rs @@ -22,10 +22,8 @@ use async_trait::async_trait; use futures::{prelude::*, AsyncWriteExt}; -use libp2p_core::{ - upgrade::{read_length_prefixed, write_length_prefixed}, - ProtocolName, -}; +use libp2p_core::upgrade::Protocol; +use libp2p_core::upgrade::{read_length_prefixed, write_length_prefixed}; use libp2p_identity::PeerId; use libp2p_request_response as request_response; use libp2p_request_response::ProtocolSupport; @@ -40,7 +38,7 @@ async fn is_response_outbound() { let ping = Ping("ping".to_string().into_bytes()); let offline_peer = PeerId::random(); - let protocols = iter::once((PingProtocol(), request_response::ProtocolSupport::Full)); + let protocols = iter::once((PING_PROTOCOL, request_response::ProtocolSupport::Full)); let cfg = request_response::Config::default(); let mut swarm1 = @@ -83,7 +81,7 @@ async fn ping_protocol() { let ping = Ping("ping".to_string().into_bytes()); let pong = Pong("pong".to_string().into_bytes()); - let protocols = iter::once((PingProtocol(), ProtocolSupport::Full)); + let protocols = iter::once((PING_PROTOCOL, ProtocolSupport::Full)); let cfg = request_response::Config::default(); let mut swarm1 = Swarm::new_ephemeral(|_| { @@ -174,7 +172,7 @@ async fn ping_protocol() { async fn emits_inbound_connection_closed_failure() { let ping = Ping("ping".to_string().into_bytes()); - let protocols = iter::once((PingProtocol(), ProtocolSupport::Full)); + let protocols = iter::once((PING_PROTOCOL, ProtocolSupport::Full)); let cfg = request_response::Config::default(); let mut swarm1 = Swarm::new_ephemeral(|_| { @@ -237,7 +235,7 @@ async fn emits_inbound_connection_closed_failure() { async fn emits_inbound_connection_closed_if_channel_is_dropped() { let ping = Ping("ping".to_string().into_bytes()); - let protocols = iter::once((PingProtocol(), ProtocolSupport::Full)); + let protocols = iter::once((PING_PROTOCOL, ProtocolSupport::Full)); let cfg = request_response::Config::default(); let mut swarm1 = Swarm::new_ephemeral(|_| { @@ -286,8 +284,6 @@ async fn emits_inbound_connection_closed_if_channel_is_dropped() { // Simple Ping-Pong Protocol -#[derive(Debug, Clone)] -struct PingProtocol(); #[derive(Clone)] struct PingCodec(); #[derive(Debug, Clone, PartialEq, Eq)] @@ -295,19 +291,14 @@ struct Ping(Vec); #[derive(Debug, Clone, PartialEq, Eq)] struct Pong(Vec); -impl ProtocolName for PingProtocol { - fn protocol_name(&self) -> &[u8] { - "/ping/1".as_bytes() - } -} +const PING_PROTOCOL: Protocol = Protocol::from_static("/ping/1"); #[async_trait] impl libp2p_request_response::Codec for PingCodec { - type Protocol = PingProtocol; type Request = Ping; type Response = Pong; - async fn read_request(&mut self, _: &PingProtocol, io: &mut T) -> io::Result + async fn read_request(&mut self, _: &Protocol, io: &mut T) -> io::Result where T: AsyncRead + Unpin + Send, { @@ -320,7 +311,7 @@ impl libp2p_request_response::Codec for PingCodec { Ok(Ping(vec)) } - async fn read_response(&mut self, _: &PingProtocol, io: &mut T) -> io::Result + async fn read_response(&mut self, _: &Protocol, io: &mut T) -> io::Result where T: AsyncRead + Unpin + Send, { @@ -335,7 +326,7 @@ impl libp2p_request_response::Codec for PingCodec { async fn write_request( &mut self, - _: &PingProtocol, + _: &Protocol, io: &mut T, Ping(data): Ping, ) -> io::Result<()> @@ -350,7 +341,7 @@ impl libp2p_request_response::Codec for PingCodec { async fn write_response( &mut self, - _: &PingProtocol, + _: &Protocol, io: &mut T, Pong(data): Pong, ) -> io::Result<()> diff --git a/swarm/src/handler/multi.rs b/swarm/src/handler/multi.rs index a3481f25608..d8558c09612 100644 --- a/swarm/src/handler/multi.rs +++ b/swarm/src/handler/multi.rs @@ -32,7 +32,7 @@ use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend}; use crate::NegotiatedSubstream; use futures::{future::BoxFuture, prelude::*}; use libp2p_core::upgrade::{ - NegotiationError, Protocol, ProtocolError, ProtocolName, UpgradeError, UpgradeProtocols, + NegotiationError, Protocol, ProtocolError, UpgradeError, UpgradeProtocols, }; use libp2p_core::ConnectedPoint; use libp2p_identity::PeerId; @@ -469,16 +469,6 @@ where } } -/// Index and protocol name pair used as `UpgradeInfo::Info`. -#[derive(Debug, Clone)] -pub struct IndexedProtoName(usize, H); - -impl ProtocolName for IndexedProtoName { - fn protocol_name(&self) -> &[u8] { - self.1.protocol_name() - } -} - /// The aggregated `InboundOpenInfo`s of supported inbound substream protocols. #[derive(Clone)] pub struct Info {