Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 1 addition & 10 deletions core/src/either.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -121,15 +121,6 @@ pub enum EitherName<A, B> {
B(B),
}

impl<A: ProtocolName, B: ProtocolName> ProtocolName for EitherName<A, B> {
fn protocol_name(&self) -> &[u8] {
match self {
EitherName::A(a) => a.protocol_name(),
EitherName::B(b) => b.protocol_name(),
}
}
}

impl<A, B> Transport for Either<A, B>
where
B: Transport,
Expand Down
7 changes: 6 additions & 1 deletion core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,12 @@ 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, UpgradeInfo};
#[allow(deprecated)]
pub use upgrade::ProtocolName;
pub use upgrade::{InboundUpgrade, OutboundUpgrade, ToProtocolsIter, UpgradeError};

#[allow(deprecated)]
pub use upgrade::UpgradeInfo;

#[derive(Debug, thiserror::Error)]
pub struct DecodeError(String);
Expand Down
193 changes: 122 additions & 71 deletions core/src/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,15 @@ mod apply;
mod denied;
mod either;
mod error;
mod from_fn;
mod map;
mod optional;
mod pending;
mod ready;
mod select;
mod transfer;

use futures::future::Future;
use std::fmt;
use std::iter::FilterMap;

#[allow(deprecated)]
pub use self::from_fn::{from_fn, FromFnUpgrade};
pub use self::{
apply::{apply, apply_inbound, apply_outbound, InboundUpgradeApply, OutboundUpgradeApply},
denied::DeniedUpgrade,
Expand All @@ -83,11 +80,7 @@ pub use self::{
transfer::{read_length_prefixed, read_varint, write_length_prefixed, write_varint},
};
pub use crate::Negotiated;
#[allow(deprecated)]
pub use map::{MapInboundUpgrade, MapInboundUpgradeErr, MapOutboundUpgrade, MapOutboundUpgradeErr};
pub use multistream_select::{NegotiatedComplete, NegotiationError, ProtocolError, Version};
#[allow(deprecated)]
pub use optional::OptionalUpgrade;

/// Types serving as protocol names.
///
Expand Down Expand Up @@ -122,6 +115,7 @@ pub use optional::OptionalUpgrade;
/// }
/// ```
///
#[deprecated(note = "Use the `Protocol` new-type instead.")]
pub trait ProtocolName {
/// The protocol name as bytes. Transmitted on the network.
///
Expand All @@ -130,6 +124,7 @@ pub trait ProtocolName {
fn protocol_name(&self) -> &[u8];
}

#[allow(deprecated)]
impl<T: AsRef<[u8]>> ProtocolName for T {
fn protocol_name(&self) -> &[u8] {
self.as_ref()
Expand All @@ -138,6 +133,8 @@ impl<T: AsRef<[u8]>> ProtocolName for T {

/// Common trait for upgrades that can be applied on inbound substreams, outbound substreams,
/// or both.
#[deprecated(note = "Implement `ToProtocolsIter` instead.")]
#[allow(deprecated)]
pub trait UpgradeInfo {
/// Opaque type representing a negotiable protocol.
type Info: ProtocolName + Clone;
Expand All @@ -148,8 +145,120 @@ pub trait UpgradeInfo {
fn protocol_info(&self) -> Self::InfoIter;
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Protocol {
inner: multistream_select::Protocol,
}

impl Protocol {
/// Construct a new protocol from a static string slice.
///
/// # Panics
///
/// This function panics if the protocol does not start with a forward slash: `/`.
pub const fn from_static(s: &'static str) -> Self {
Protocol {
inner: multistream_select::Protocol::from_static(s),
}
}

/// Attempt to construct a protocol from an owned string.
///
/// This function will fail if the protocol does not start with a forward slash: `/`.
/// Where possible, you should use [`Protocol::from_static`] instead to avoid allocations.
pub fn try_from_owned(protocol: String) -> Result<Self, InvalidProtocol> {
Ok(Protocol {
inner: multistream_select::Protocol::try_from_owned(protocol)
.map_err(InvalidProtocol)?,
})
}

/// View the protocol as a string slice.
pub fn as_str(&self) -> &str {
self.inner.as_str()
}

pub(crate) fn from_inner(inner: multistream_select::Protocol) -> Self {
Protocol { inner }
}

pub(crate) fn into_inner(self) -> multistream_select::Protocol {
self.inner
}
}

impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}

impl PartialEq<str> for Protocol {
fn eq(&self, other: &str) -> bool {
self.inner.as_str() == other
}
}

#[derive(Debug)]
pub struct InvalidProtocol(multistream_select::ProtocolError);

impl fmt::Display for InvalidProtocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid protocol")
}
}

impl std::error::Error for InvalidProtocol {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}

/// Each protocol upgrade must implement the [`ToProtocolsIter`] trait.
///
/// The returned iterator should yield the protocols that the upgrade supports.
pub trait ToProtocolsIter {
type Iter: Iterator<Item = Protocol> + Send;

fn to_protocols_iter(&self) -> Self::Iter;
}

#[allow(deprecated)]
impl<U> ToProtocolsIter for U
where
U: UpgradeInfo + Send + 'static,
U::Info: Send + 'static,
U::InfoIter: Send + 'static,
<U::InfoIter as IntoIterator>::IntoIter: Send + 'static,
{
type Iter = FilterMap<<U::InfoIter as IntoIterator>::IntoIter, fn(U::Info) -> Option<Protocol>>;

fn to_protocols_iter(&self) -> Self::Iter {
self.protocol_info()
.into_iter()
.filter_map(filter_non_utf8_protocols)
}
}

#[allow(deprecated)]
fn filter_non_utf8_protocols(p: impl ProtocolName) -> Option<Protocol> {
let name = p.protocol_name();

match multistream_select::Protocol::try_from(name) {
Ok(p) => Some(Protocol::from_inner(p)),
Err(e) => {
log::warn!(
"ignoring protocol {} during upgrade because it is malformed: {e}",
String::from_utf8_lossy(name)
);

None
}
}
}

/// Possible upgrade on an inbound connection or substream.
pub trait InboundUpgrade<C>: UpgradeInfo {
pub trait InboundUpgrade<C>: ToProtocolsIter {
/// Output after the upgrade has been successfully negotiated and the handshake performed.
type Output;
/// Possible error during the handshake.
Expand All @@ -161,40 +270,11 @@ pub trait InboundUpgrade<C>: UpgradeInfo {
/// method is called to start the handshake.
///
/// The `info` is the identifier of the protocol, as produced by `protocol_info`.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs updating.

fn upgrade_inbound(self, socket: C, info: Self::Info) -> Self::Future;
fn upgrade_inbound(self, socket: C, selected_protocol: Protocol) -> Self::Future;
}

/// Extension trait for `InboundUpgrade`. Automatically implemented on all types that implement
/// `InboundUpgrade`.
#[deprecated(
note = "Will be removed without replacement because it is not used within rust-libp2p."
)]
#[allow(deprecated)]
pub trait InboundUpgradeExt<C>: InboundUpgrade<C> {
/// Returns a new object that wraps around `Self` and applies a closure to the `Output`.
fn map_inbound<F, T>(self, f: F) -> MapInboundUpgrade<Self, F>
where
Self: Sized,
F: FnOnce(Self::Output) -> T,
{
MapInboundUpgrade::new(self, f)
}

/// Returns a new object that wraps around `Self` and applies a closure to the `Error`.
fn map_inbound_err<F, T>(self, f: F) -> MapInboundUpgradeErr<Self, F>
where
Self: Sized,
F: FnOnce(Self::Error) -> T,
{
MapInboundUpgradeErr::new(self, f)
}
}

#[allow(deprecated)]
impl<C, U: InboundUpgrade<C>> InboundUpgradeExt<C> for U {}

/// Possible upgrade on an outbound connection or substream.
pub trait OutboundUpgrade<C>: UpgradeInfo {
pub trait OutboundUpgrade<C>: ToProtocolsIter {
/// Output after the upgrade has been successfully negotiated and the handshake performed.
type Output;
/// Possible error during the handshake.
Expand All @@ -206,34 +286,5 @@ pub trait OutboundUpgrade<C>: UpgradeInfo {
/// method is called to start the handshake.
///
/// The `info` is the identifier of the protocol, as produced by `protocol_info`.
fn upgrade_outbound(self, socket: C, info: Self::Info) -> Self::Future;
fn upgrade_outbound(self, socket: C, selected_protocol: Protocol) -> Self::Future;
}

/// Extention trait for `OutboundUpgrade`. Automatically implemented on all types that implement
/// `OutboundUpgrade`.
#[deprecated(
note = "Will be removed without replacement because it is not used within rust-libp2p."
)]
#[allow(deprecated)]
pub trait OutboundUpgradeExt<C>: OutboundUpgrade<C> {
/// Returns a new object that wraps around `Self` and applies a closure to the `Output`.
fn map_outbound<F, T>(self, f: F) -> MapOutboundUpgrade<Self, F>
where
Self: Sized,
F: FnOnce(Self::Output) -> T,
{
MapOutboundUpgrade::new(self, f)
}

/// Returns a new object that wraps around `Self` and applies a closure to the `Error`.
fn map_outbound_err<F, T>(self, f: F) -> MapOutboundUpgradeErr<Self, F>
where
Self: Sized,
F: FnOnce(Self::Error) -> T,
{
MapOutboundUpgradeErr::new(self, f)
}
}

#[allow(deprecated)]
impl<C, U: OutboundUpgrade<C>> OutboundUpgradeExt<C> for U {}
Loading