From 6453766472d5b281ca5afcf6f73af264c5071844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 13:34:50 +0000 Subject: [PATCH 01/25] rename relay::Relay to relay::Behaviour. --- protocols/dcutr/tests/lib.rs | 4 ++-- protocols/relay/examples/relay_v2.rs | 6 +++--- protocols/relay/src/v2/client.rs | 2 +- protocols/relay/src/v2/relay.rs | 21 ++++++++++++++------- protocols/relay/tests/v2.rs | 4 ++-- 5 files changed, 22 insertions(+), 15 deletions(-) diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index ac949f0efe5..159468db34f 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -91,7 +91,7 @@ fn connect() { )); } -fn build_relay() -> Swarm { +fn build_relay() -> Swarm { let local_key = identity::Keypair::generate_ed25519(); let local_public_key = local_key.public(); let local_peer_id = local_public_key.to_peer_id(); @@ -100,7 +100,7 @@ fn build_relay() -> Swarm { Swarm::with_threadpool_executor( transport, - relay::Relay::new( + relay::Behaviour::new( local_peer_id, relay::Config { reservation_duration: Duration::from_secs(2), diff --git a/protocols/relay/examples/relay_v2.rs b/protocols/relay/examples/relay_v2.rs index 575b8a70584..abe198d1350 100644 --- a/protocols/relay/examples/relay_v2.rs +++ b/protocols/relay/examples/relay_v2.rs @@ -28,7 +28,7 @@ use libp2p_core::{identity, Multiaddr, PeerId, Transport}; use libp2p_identify as identify; use libp2p_noise as noise; use libp2p_ping as ping; -use libp2p_relay::v2::relay::{self, Relay}; +use libp2p_relay::v2::relay; use libp2p_swarm::{NetworkBehaviour, Swarm, SwarmEvent}; use libp2p_tcp as tcp; use std::error::Error; @@ -57,7 +57,7 @@ fn main() -> Result<(), Box> { .boxed(); let behaviour = Behaviour { - relay: Relay::new(local_peer_id, Default::default()), + relay: relay::Behaviour::new(local_peer_id, Default::default()), ping: ping::Behaviour::new(ping::Config::new()), identify: identify::Behaviour::new(identify::Config::new( "/TODO/0.0.1".to_string(), @@ -98,7 +98,7 @@ fn main() -> Result<(), Box> { prelude = "libp2p_swarm::derive_prelude" )] struct Behaviour { - relay: Relay, + relay: relay::Behaviour, ping: ping::Behaviour, identify: identify::Behaviour, } diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index d9a2d977588..d55723a5a0e 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -322,7 +322,7 @@ impl NetworkBehaviour for Client { } } None => unreachable!( - "`Relay` `NetworkBehaviour` polled after channel from \ + "`relay::Behaviour` polled after channel from \ `RelayTransport` has been closed. Unreachable under \ the assumption that the `Client` is never polled after \ `ClientTransport` is dropped.", diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index 42ccdd69069..8dc3aa5dd1f 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -43,7 +43,7 @@ use std::time::Duration; use super::protocol::outbound_stop; -/// Configuration for the [`Relay`] [`NetworkBehaviour`]. +/// Configuration for the relay [`Behaviour`]. /// /// # Panics /// @@ -126,7 +126,7 @@ impl Default for Config { } } -/// The events produced by the [`Relay`] behaviour. +/// The events produced by the relay `Behaviour`. #[derive(Debug)] pub enum Event { /// An inbound reservation request has been accepted. @@ -189,9 +189,16 @@ pub enum Event { }, } -/// [`Relay`] is a [`NetworkBehaviour`] that implements the relay server +#[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::v2::relay::Behaviour instead." +)] +/// [`Relay`] is a [`NetworkBehaviour`] that implements the relay server. +pub type Relay = Behaviour; + +/// [`NetworkBehaviour`] implementation of the relay server /// functionality of the circuit relay v2 protocol. -pub struct Relay { +pub struct Behaviour { config: Config, local_peer_id: PeerId, @@ -203,7 +210,7 @@ pub struct Relay { queued_actions: VecDeque, } -impl Relay { +impl Behaviour { pub fn new(local_peer_id: PeerId, config: Config) -> Self { Self { config, @@ -248,7 +255,7 @@ impl Relay { } } -impl NetworkBehaviour for Relay { +impl NetworkBehaviour for Behaviour { type ConnectionHandler = handler::Prototype; type OutEvent = Event; @@ -740,7 +747,7 @@ impl Add for CircuitId { } /// A [`NetworkBehaviourAction`], either complete, or still requiring data from [`PollParameters`] -/// before being returned in [`Relay::poll`]. +/// before being returned in [`Behaviour::poll`]. #[allow(clippy::large_enum_variant)] enum Action { Done(NetworkBehaviourAction), diff --git a/protocols/relay/tests/v2.rs b/protocols/relay/tests/v2.rs index 07383a3c66f..b466faefac1 100644 --- a/protocols/relay/tests/v2.rs +++ b/protocols/relay/tests/v2.rs @@ -295,7 +295,7 @@ fn build_relay() -> Swarm { transport, Relay { ping: ping::Behaviour::new(ping::Config::new()), - relay: relay::Relay::new( + relay: relay::Behaviour::new( local_peer_id, relay::Config { reservation_duration: Duration::from_secs(2), @@ -349,7 +349,7 @@ where prelude = "libp2p_swarm::derive_prelude" )] struct Relay { - relay: relay::Relay, + relay: relay::Behaviour, ping: ping::Behaviour, } From 0f1c10eaa6c15e7ba304a9bf653d556f1a4e8e13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 13:38:00 +0000 Subject: [PATCH 02/25] rename client::Client to client::Behaviour. --- protocols/dcutr/examples/dcutr.rs | 6 +++--- protocols/dcutr/tests/lib.rs | 5 +++-- protocols/relay/src/v2/client.rs | 22 ++++++++++++++++------ protocols/relay/src/v2/client/handler.rs | 2 +- protocols/relay/src/v2/client/transport.rs | 6 +++--- protocols/relay/tests/v2.rs | 5 +++-- 6 files changed, 29 insertions(+), 17 deletions(-) diff --git a/protocols/dcutr/examples/dcutr.rs b/protocols/dcutr/examples/dcutr.rs index f543db25dfd..728eb86cb2f 100644 --- a/protocols/dcutr/examples/dcutr.rs +++ b/protocols/dcutr/examples/dcutr.rs @@ -32,7 +32,7 @@ use libp2p_dns::DnsConfig; use libp2p_identify as identify; use libp2p_noise as noise; use libp2p_ping as ping; -use libp2p_relay::v2::client::{self, Client}; +use libp2p_relay::v2::client; use libp2p_swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent}; use libp2p_tcp as tcp; use log::info; @@ -87,7 +87,7 @@ fn main() -> Result<(), Box> { let local_peer_id = PeerId::from(local_key.public()); info!("Local peer id: {:?}", local_peer_id); - let (relay_transport, client) = Client::new_transport_and_behaviour(local_peer_id); + let (relay_transport, client) = client::Behaviour::new_transport_and_behaviour(local_peer_id); let transport = OrTransport::new( relay_transport, @@ -111,7 +111,7 @@ fn main() -> Result<(), Box> { prelude = "libp2p_swarm::derive_prelude" )] struct Behaviour { - relay_client: Client, + relay_client: client::Behaviour, ping: ping::Behaviour, identify: identify::Behaviour, dcutr: dcutr::behaviour::Behaviour, diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index 159468db34f..fec2d1c80ca 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -116,7 +116,8 @@ fn build_client() -> Swarm { let local_public_key = local_key.public(); let local_peer_id = local_public_key.to_peer_id(); - let (relay_transport, behaviour) = client::Client::new_transport_and_behaviour(local_peer_id); + let (relay_transport, behaviour) = + client::Behaviour::new_transport_and_behaviour(local_peer_id); let transport = build_transport( OrTransport::new(relay_transport, MemoryTransport::default()).boxed(), local_public_key, @@ -153,7 +154,7 @@ where prelude = "libp2p_swarm::derive_prelude" )] struct Client { - relay: client::Client, + relay: client::Behaviour, dcutr: dcutr::behaviour::Behaviour, } diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index d55723a5a0e..df01566953f 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -46,7 +46,7 @@ use std::ops::DerefMut; use std::pin::Pin; use std::task::{Context, Poll}; -/// The events produced by the [`Client`] behaviour. +/// The events produced by the client `Behaviour`. #[derive(Debug)] pub enum Event { /// An outbound reservation has been accepted. @@ -88,7 +88,17 @@ pub enum Event { }, } -pub struct Client { +#[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::v2::client::Behaviour instead." +)] +/// [`NetworkBehaviour`] implementation of the relay client +/// functionality of the circuit relay v2 protocol. +pub type Client = Behaviour; + +/// [`NetworkBehaviour`] implementation of the relay client +/// functionality of the circuit relay v2 protocol. +pub struct Behaviour { local_peer_id: PeerId, from_transport: Receiver, @@ -100,12 +110,12 @@ pub struct Client { queued_actions: VecDeque, } -impl Client { +impl Behaviour { pub fn new_transport_and_behaviour( local_peer_id: PeerId, ) -> (transport::ClientTransport, Self) { let (transport, from_transport) = transport::ClientTransport::new(); - let behaviour = Client { + let behaviour = Behaviour { local_peer_id, from_transport, directly_connected_peers: Default::default(), @@ -145,7 +155,7 @@ impl Client { } } -impl NetworkBehaviour for Client { +impl NetworkBehaviour for Behaviour { type ConnectionHandler = handler::Prototype; type OutEvent = Event; @@ -324,7 +334,7 @@ impl NetworkBehaviour for Client { None => unreachable!( "`relay::Behaviour` polled after channel from \ `RelayTransport` has been closed. Unreachable under \ - the assumption that the `Client` is never polled after \ + the assumption that the `client::Behaviour` is never polled after \ `ClientTransport` is dropped.", ), }; diff --git a/protocols/relay/src/v2/client/handler.rs b/protocols/relay/src/v2/client/handler.rs index 5d01cf9dbce..de4970b8240 100644 --- a/protocols/relay/src/v2/client/handler.rs +++ b/protocols/relay/src/v2/client/handler.rs @@ -112,7 +112,7 @@ pub enum Event { pub struct Prototype { local_peer_id: PeerId, - /// Initial [`In`] event from [`super::Client`] provided at creation time. + /// Initial [`In`] event from [`super::Behaviour`] provided at creation time. initial_in: Option, } diff --git a/protocols/relay/src/v2/client/transport.rs b/protocols/relay/src/v2/client/transport.rs index 18e4a989597..4ff2f49676f 100644 --- a/protocols/relay/src/v2/client/transport.rs +++ b/protocols/relay/src/v2/client/transport.rs @@ -52,7 +52,7 @@ use thiserror::Error; /// # use libp2p_core::transport::choice::OrTransport; /// # use libp2p_relay::v2::client; /// let actual_transport = MemoryTransport::default(); -/// let (relay_transport, behaviour) = client::Client::new_transport_and_behaviour( +/// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( /// PeerId::random(), /// ); /// let mut transport = OrTransport::new(relay_transport, actual_transport); @@ -76,7 +76,7 @@ use thiserror::Error; /// # let relay_id = PeerId::random(); /// # let local_peer_id = PeerId::random(); /// let actual_transport = MemoryTransport::default(); -/// let (relay_transport, behaviour) = client::Client::new_transport_and_behaviour( +/// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( /// local_peer_id, /// ); /// let mut transport = OrTransport::new(relay_transport, actual_transport); @@ -105,7 +105,7 @@ impl ClientTransport { /// # use libp2p_core::transport::choice::OrTransport; /// # use libp2p_relay::v2::client; /// let actual_transport = MemoryTransport::default(); - /// let (relay_transport, behaviour) = client::Client::new_transport_and_behaviour( + /// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( /// PeerId::random(), /// ); /// diff --git a/protocols/relay/tests/v2.rs b/protocols/relay/tests/v2.rs index b466faefac1..ded04604349 100644 --- a/protocols/relay/tests/v2.rs +++ b/protocols/relay/tests/v2.rs @@ -312,7 +312,8 @@ fn build_client() -> Swarm { let local_public_key = local_key.public(); let local_peer_id = local_public_key.to_peer_id(); - let (relay_transport, behaviour) = client::Client::new_transport_and_behaviour(local_peer_id); + let (relay_transport, behaviour) = + client::Behaviour::new_transport_and_behaviour(local_peer_id); let transport = upgrade_transport( OrTransport::new(relay_transport, MemoryTransport::default()).boxed(), local_public_key, @@ -378,7 +379,7 @@ impl From for RelayEvent { prelude = "libp2p_swarm::derive_prelude" )] struct Client { - relay: client::Client, + relay: client::Behaviour, ping: ping::Behaviour, } From 796425af1203c29976921569d979c4bf4aced129 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 13:54:57 +0000 Subject: [PATCH 03/25] rename client::transport::ClientTransport to client::transport::Transport. --- protocols/relay/src/v2/client.rs | 8 +++----- protocols/relay/src/v2/client/transport.rs | 22 ++++++++++++++-------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index df01566953f..cfa5ece1917 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -111,10 +111,8 @@ pub struct Behaviour { } impl Behaviour { - pub fn new_transport_and_behaviour( - local_peer_id: PeerId, - ) -> (transport::ClientTransport, Self) { - let (transport, from_transport) = transport::ClientTransport::new(); + pub fn new_transport_and_behaviour(local_peer_id: PeerId) -> (transport::Transport, Self) { + let (transport, from_transport) = transport::Transport::new(); let behaviour = Behaviour { local_peer_id, from_transport, @@ -335,7 +333,7 @@ impl NetworkBehaviour for Behaviour { "`relay::Behaviour` polled after channel from \ `RelayTransport` has been closed. Unreachable under \ the assumption that the `client::Behaviour` is never polled after \ - `ClientTransport` is dropped.", + `client::Transport` is dropped.", ), }; diff --git a/protocols/relay/src/v2/client/transport.rs b/protocols/relay/src/v2/client/transport.rs index 4ff2f49676f..d4da8e0c35f 100644 --- a/protocols/relay/src/v2/client/transport.rs +++ b/protocols/relay/src/v2/client/transport.rs @@ -30,12 +30,18 @@ use futures::stream::SelectAll; use futures::stream::{Stream, StreamExt}; use libp2p_core::multiaddr::{Multiaddr, Protocol}; use libp2p_core::transport::{ListenerId, TransportError, TransportEvent}; -use libp2p_core::{PeerId, Transport}; +use libp2p_core::PeerId; use std::collections::VecDeque; use std::pin::Pin; use std::task::{Context, Poll}; use thiserror::Error; +#[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::v2::client::Transport instead." +)] +pub type ClientTransport = Transport; + /// A [`Transport`] enabling client relay capabilities. /// /// Note: The transport only handles listening and dialing on relayed [`Multiaddr`], and depends on @@ -86,14 +92,14 @@ use thiserror::Error; /// .with(Protocol::P2pCircuit); // Signal to listen via remote relay node. /// transport.listen_on(relay_addr).unwrap(); /// ``` -pub struct ClientTransport { +pub struct Transport { to_behaviour: mpsc::Sender, pending_to_behaviour: VecDeque, listeners: SelectAll, } -impl ClientTransport { - /// Create a new [`ClientTransport`]. +impl Transport { + /// Create a new [`Transport`]. /// /// Note: The transport only handles listening and dialing on relayed [`Multiaddr`], and depends on /// an other transport to do the actual transmission of data. They should be combined through the @@ -114,7 +120,7 @@ impl ClientTransport { /// ``` pub(crate) fn new() -> (Self, mpsc::Receiver) { let (to_behaviour, from_transport) = mpsc::channel(0); - let transport = ClientTransport { + let transport = Transport { to_behaviour, pending_to_behaviour: VecDeque::new(), listeners: SelectAll::new(), @@ -123,7 +129,7 @@ impl ClientTransport { } } -impl Transport for ClientTransport { +impl libp2p_core::Transport for Transport { type Output = RelayedConnection; type Error = RelayError; type ListenerUpgrade = Ready>; @@ -346,7 +352,7 @@ impl RelayListener { } impl Stream for RelayListener { - type Item = TransportEvent<::ListenerUpgrade, RelayError>; + type Item = TransportEvent<::ListenerUpgrade, RelayError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { @@ -439,7 +445,7 @@ impl From for TransportError { } } -/// Message from the [`ClientTransport`] to the [`Relay`](crate::v2::relay::Relay) +/// Message from the [`Transport`] to the [`Behaviour`](crate::v2::relay::Behaviour) /// [`NetworkBehaviour`](libp2p_swarm::NetworkBehaviour). pub enum TransportToBehaviourMsg { /// Dial destination node via relay node. From f0c8429ad2dd06d450c21841f0f43115f0620f89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 17:46:29 +0000 Subject: [PATCH 04/25] rename relay::v2::client::RelayError to relay::v2::client::Error. --- protocols/relay/src/v2/client/transport.rs | 46 ++++++++++++---------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/protocols/relay/src/v2/client/transport.rs b/protocols/relay/src/v2/client/transport.rs index d4da8e0c35f..14616f8c233 100644 --- a/protocols/relay/src/v2/client/transport.rs +++ b/protocols/relay/src/v2/client/transport.rs @@ -131,7 +131,7 @@ impl Transport { impl libp2p_core::Transport for Transport { type Output = RelayedConnection; - type Error = RelayError; + type Error = Error; type ListenerUpgrade = Ready>; type Dial = RelayedDial; @@ -141,12 +141,12 @@ impl libp2p_core::Transport for Transport { relay_peer_id: None, relay_addr: _, .. - } => return Err(RelayError::MissingDstPeerId.into()), + } => return Err(Error::MissingDstPeerId.into()), RelayedMultiaddr { relay_peer_id: _, relay_addr: None, .. - } => return Err(RelayError::MissingRelayAddr.into()), + } => return Err(Error::MissingRelayAddr.into()), RelayedMultiaddr { relay_peer_id: Some(peer_id), relay_addr: Some(addr), @@ -191,9 +191,9 @@ impl libp2p_core::Transport for Transport { } = parse_relayed_multiaddr(addr)?; // TODO: In the future we might want to support dialing a relay by its address only. - let relay_peer_id = relay_peer_id.ok_or(RelayError::MissingRelayPeerId)?; - let relay_addr = relay_addr.ok_or(RelayError::MissingRelayAddr)?; - let dst_peer_id = dst_peer_id.ok_or(RelayError::MissingDstPeerId)?; + let relay_peer_id = relay_peer_id.ok_or(Error::MissingRelayPeerId)?; + let relay_addr = relay_addr.ok_or(Error::MissingRelayAddr)?; + let dst_peer_id = dst_peer_id.ok_or(Error::MissingDstPeerId)?; let mut to_behaviour = self.to_behaviour.clone(); Ok(async move { @@ -208,7 +208,7 @@ impl libp2p_core::Transport for Transport { send_back: tx, }) .await?; - let stream = rx.await?.map_err(|()| RelayError::Connect)?; + let stream = rx.await?.map_err(|()| Error::Connect)?; Ok(stream) } .boxed()) @@ -271,9 +271,7 @@ struct RelayedMultiaddr { } /// Parse a [`Multiaddr`] containing a [`Protocol::P2pCircuit`]. -fn parse_relayed_multiaddr( - addr: Multiaddr, -) -> Result> { +fn parse_relayed_multiaddr(addr: Multiaddr) -> Result> { if !addr.iter().any(|p| matches!(p, Protocol::P2pCircuit)) { return Err(TransportError::MultiaddrNotSupported(addr)); } @@ -287,20 +285,20 @@ fn parse_relayed_multiaddr( if before_circuit { before_circuit = false; } else { - return Err(RelayError::MultipleCircuitRelayProtocolsUnsupported.into()); + return Err(Error::MultipleCircuitRelayProtocolsUnsupported.into()); } } Protocol::P2p(hash) => { - let peer_id = PeerId::from_multihash(hash).map_err(|_| RelayError::InvalidHash)?; + let peer_id = PeerId::from_multihash(hash).map_err(|_| Error::InvalidHash)?; if before_circuit { if relayed_multiaddr.relay_peer_id.is_some() { - return Err(RelayError::MalformedMultiaddr.into()); + return Err(Error::MalformedMultiaddr.into()); } relayed_multiaddr.relay_peer_id = Some(peer_id) } else { if relayed_multiaddr.dst_peer_id.is_some() { - return Err(RelayError::MalformedMultiaddr.into()); + return Err(Error::MalformedMultiaddr.into()); } relayed_multiaddr.dst_peer_id = Some(peer_id) } @@ -341,7 +339,7 @@ impl RelayListener { /// This will create a [`TransportEvent::ListenerClosed`] event /// and terminate the stream once all remaining events in queue have /// been reported. - fn close(&mut self, reason: Result<(), RelayError>) { + fn close(&mut self, reason: Result<(), Error>) { self.queued_events .push_back(TransportEvent::ListenerClosed { listener_id: self.listener_id, @@ -352,7 +350,7 @@ impl RelayListener { } impl Stream for RelayListener { - type Item = TransportEvent<::ListenerUpgrade, RelayError>; + type Item = TransportEvent<::ListenerUpgrade, Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { @@ -404,17 +402,23 @@ impl Stream for RelayListener { send_back_addr: Protocol::P2p(src_peer_id.into()).into(), }) } - ToListenerMsg::Reservation(Err(())) => self.close(Err(RelayError::Reservation)), + ToListenerMsg::Reservation(Err(())) => self.close(Err(Error::Reservation)), }; } } } -pub type RelayedDial = BoxFuture<'static, Result>; +pub type RelayedDial = BoxFuture<'static, Result>; + +#[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::v2::client::Error instead." +)] +pub type RelayError = Error; /// Error that occurred during relay connection setup. #[derive(Debug, Error)] -pub enum RelayError { +pub enum Error { #[error("Missing relay peer id.")] MissingRelayPeerId, #[error("Missing relay address.")] @@ -439,8 +443,8 @@ pub enum RelayError { Connect, } -impl From for TransportError { - fn from(error: RelayError) -> Self { +impl From for TransportError { + fn from(error: Error) -> Self { TransportError::Other(error) } } From 9963cfa4f64695af5e77d73ccdbd22ecfcae2e2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 17:49:43 +0000 Subject: [PATCH 05/25] rename relay::v2::client::RelayListener to relay::v2::client::Listener. --- protocols/relay/src/v2/client/transport.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/protocols/relay/src/v2/client/transport.rs b/protocols/relay/src/v2/client/transport.rs index 14616f8c233..f491dc16782 100644 --- a/protocols/relay/src/v2/client/transport.rs +++ b/protocols/relay/src/v2/client/transport.rs @@ -95,7 +95,7 @@ pub type ClientTransport = Transport; pub struct Transport { to_behaviour: mpsc::Sender, pending_to_behaviour: VecDeque, - listeners: SelectAll, + listeners: SelectAll, } impl Transport { @@ -163,7 +163,7 @@ impl libp2p_core::Transport for Transport { }); let listener_id = ListenerId::new(); - let listener = RelayListener { + let listener = Listener { listener_id, queued_events: Default::default(), from_behaviour, @@ -322,7 +322,13 @@ fn parse_relayed_multiaddr(addr: Multiaddr) -> Result::Item>, @@ -333,7 +339,7 @@ pub struct RelayListener { is_closed: bool, } -impl RelayListener { +impl Listener { /// Close the listener. /// /// This will create a [`TransportEvent::ListenerClosed`] event @@ -349,7 +355,7 @@ impl RelayListener { } } -impl Stream for RelayListener { +impl Stream for Listener { type Item = TransportEvent<::ListenerUpgrade, Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { From 604178bec43c58a2397f742f84aff58ecd44f1af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 17:55:36 +0000 Subject: [PATCH 06/25] add CHANGELOG.md entries --- protocols/relay/CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index 1e597b04be0..c0624a1e03f 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -1,5 +1,12 @@ # 0.15.0 [unreleased] +- Rename types as per [discussion 2174]. + `Relay` has been renamed to `Behaviour`. + The `Relay`, and `Client` prefixes have been removed from various types like `ClientTransport`. + Users should prefer importing the relay protocol as a module (`use libp2p::relay::v2::relay;`), + and refer to its types via `relay::`. For example: `relay::v2::relay::Behaviour` or `relay::v2::client::Behaviour`. + See [PR 3235]. + - Update to `libp2p-swarm` `v0.42.0`. # 0.14.0 From 395d516f795f9e2afcb06047dfb2cfa981c0cbbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 22:30:52 +0000 Subject: [PATCH 07/25] add missing links to CHANGELOG.md --- protocols/relay/CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index c0624a1e03f..5f9a49a5329 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -7,6 +7,9 @@ and refer to its types via `relay::`. For example: `relay::v2::relay::Behaviour` or `relay::v2::client::Behaviour`. See [PR 3235]. +[PR 3235]: https://github.com/libp2p/rust-libp2p/pull/3235 +[discussion 2174]: https://github.com/libp2p/rust-libp2p/issues/2174 + - Update to `libp2p-swarm` `v0.42.0`. # 0.14.0 From 50207baa2669aa4d72f02ba8f60c88757b809da5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 14 Dec 2022 11:41:04 +0000 Subject: [PATCH 08/25] move relay::v2 root symbols to relay:: and use them across the crate. Deprecate the old ones. --- misc/metrics/src/identify.rs | 4 +- protocols/relay/build.rs | 2 +- protocols/relay/src/lib.rs | 24 ++++++++ protocols/relay/src/{v2 => }/message.proto | 0 protocols/relay/src/{v2 => }/protocol.rs | 2 +- .../src/{v2 => }/protocol/inbound_hop.rs | 4 +- .../src/{v2 => }/protocol/inbound_stop.rs | 4 +- .../src/{v2 => }/protocol/outbound_hop.rs | 4 +- .../src/{v2 => }/protocol/outbound_stop.rs | 4 +- protocols/relay/src/v2.rs | 61 ++++++++++++------- protocols/relay/src/v2/client.rs | 2 +- protocols/relay/src/v2/client/handler.rs | 4 +- protocols/relay/src/v2/client/transport.rs | 2 +- protocols/relay/src/v2/relay.rs | 6 +- protocols/relay/src/v2/relay/handler.rs | 4 +- 15 files changed, 83 insertions(+), 44 deletions(-) rename protocols/relay/src/{v2 => }/message.proto (100%) rename protocols/relay/src/{v2 => }/protocol.rs (98%) rename protocols/relay/src/{v2 => }/protocol/inbound_hop.rs (98%) rename protocols/relay/src/{v2 => }/protocol/inbound_stop.rs (97%) rename protocols/relay/src/{v2 => }/protocol/outbound_hop.rs (98%) rename protocols/relay/src/{v2 => }/protocol/outbound_stop.rs (97%) diff --git a/misc/metrics/src/identify.rs b/misc/metrics/src/identify.rs index 688c67a6190..db44109e59a 100644 --- a/misc/metrics/src/identify.rs +++ b/misc/metrics/src/identify.rs @@ -151,9 +151,9 @@ impl super::Recorder for Metrics { #[cfg(feature = "ping")] libp2p_ping::PROTOCOL_NAME, #[cfg(feature = "relay")] - libp2p_relay::v2::STOP_PROTOCOL_NAME, + libp2p_relay::STOP_PROTOCOL_NAME, #[cfg(feature = "relay")] - libp2p_relay::v2::HOP_PROTOCOL_NAME, + libp2p_relay::HOP_PROTOCOL_NAME, ]; allowed_protocols.contains(&p.as_bytes()) diff --git a/protocols/relay/build.rs b/protocols/relay/build.rs index 7859f6171f7..965fb241712 100644 --- a/protocols/relay/build.rs +++ b/protocols/relay/build.rs @@ -19,5 +19,5 @@ // DEALINGS IN THE SOFTWARE. fn main() { - prost_build::compile_protos(&["src/v2/message.proto"], &["src/v2"]).unwrap(); + prost_build::compile_protos(&["src/message.proto"], &["src/"]).unwrap(); } diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index e4a7e7d9c30..be258d2a0c2 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -23,9 +23,33 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +mod protocol; pub mod v2; +#[allow(clippy::derive_partial_eq_without_eq)] +mod message_proto { + include!(concat!(env!("OUT_DIR"), "/message_v2.pb.rs")); +} + +pub use protocol::{ + inbound_hop::FatalUpgradeError as InboundHopFatalUpgradeError, + inbound_stop::FatalUpgradeError as InboundStopFatalUpgradeError, + outbound_hop::FatalUpgradeError as OutboundHopFatalUpgradeError, + outbound_stop::FatalUpgradeError as OutboundStopFatalUpgradeError, HOP_PROTOCOL_NAME, + STOP_PROTOCOL_NAME, +}; + // Check that we can safely cast a `usize` to a `u64`. static_assertions::const_assert! { std::mem::size_of::() <= std::mem::size_of::() } + +/// The ID of an outgoing / incoming, relay / destination request. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct RequestId(u64); + +impl RequestId { + fn new() -> RequestId { + RequestId(rand::random()) + } +} diff --git a/protocols/relay/src/v2/message.proto b/protocols/relay/src/message.proto similarity index 100% rename from protocols/relay/src/v2/message.proto rename to protocols/relay/src/message.proto diff --git a/protocols/relay/src/v2/protocol.rs b/protocols/relay/src/protocol.rs similarity index 98% rename from protocols/relay/src/v2/protocol.rs rename to protocols/relay/src/protocol.rs index 6e9ccc14277..f688fe6ab67 100644 --- a/protocols/relay/src/v2/protocol.rs +++ b/protocols/relay/src/protocol.rs @@ -18,7 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::message_proto; +use crate::message_proto; use std::time::Duration; pub mod inbound_hop; diff --git a/protocols/relay/src/v2/protocol/inbound_hop.rs b/protocols/relay/src/protocol/inbound_hop.rs similarity index 98% rename from protocols/relay/src/v2/protocol/inbound_hop.rs rename to protocols/relay/src/protocol/inbound_hop.rs index 48c851c7732..dec290e0e6c 100644 --- a/protocols/relay/src/v2/protocol/inbound_hop.rs +++ b/protocols/relay/src/protocol/inbound_hop.rs @@ -18,8 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::message_proto::{hop_message, HopMessage, Limit, Reservation, Status}; -use crate::v2::protocol::{HOP_PROTOCOL_NAME, MAX_MESSAGE_SIZE}; +use crate::message_proto::{hop_message, HopMessage, Limit, Reservation, Status}; +use crate::protocol::{HOP_PROTOCOL_NAME, MAX_MESSAGE_SIZE}; use asynchronous_codec::{Framed, FramedParts}; use bytes::Bytes; use futures::{future::BoxFuture, prelude::*}; diff --git a/protocols/relay/src/v2/protocol/inbound_stop.rs b/protocols/relay/src/protocol/inbound_stop.rs similarity index 97% rename from protocols/relay/src/v2/protocol/inbound_stop.rs rename to protocols/relay/src/protocol/inbound_stop.rs index 5c761ebd70f..d3cad292bd7 100644 --- a/protocols/relay/src/v2/protocol/inbound_stop.rs +++ b/protocols/relay/src/protocol/inbound_stop.rs @@ -18,8 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::message_proto::{stop_message, Status, StopMessage}; -use crate::v2::protocol::{self, MAX_MESSAGE_SIZE, STOP_PROTOCOL_NAME}; +use crate::message_proto::{stop_message, Status, StopMessage}; +use crate::protocol::{self, MAX_MESSAGE_SIZE, STOP_PROTOCOL_NAME}; use asynchronous_codec::{Framed, FramedParts}; use bytes::Bytes; use futures::{future::BoxFuture, prelude::*}; diff --git a/protocols/relay/src/v2/protocol/outbound_hop.rs b/protocols/relay/src/protocol/outbound_hop.rs similarity index 98% rename from protocols/relay/src/v2/protocol/outbound_hop.rs rename to protocols/relay/src/protocol/outbound_hop.rs index c8b6bd4e00e..c692c7a2596 100644 --- a/protocols/relay/src/v2/protocol/outbound_hop.rs +++ b/protocols/relay/src/protocol/outbound_hop.rs @@ -18,8 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::message_proto::{hop_message, HopMessage, Peer, Status}; -use crate::v2::protocol::{Limit, HOP_PROTOCOL_NAME, MAX_MESSAGE_SIZE}; +use crate::message_proto::{hop_message, HopMessage, Peer, Status}; +use crate::protocol::{Limit, HOP_PROTOCOL_NAME, MAX_MESSAGE_SIZE}; use asynchronous_codec::{Framed, FramedParts}; use bytes::Bytes; use futures::{future::BoxFuture, prelude::*}; diff --git a/protocols/relay/src/v2/protocol/outbound_stop.rs b/protocols/relay/src/protocol/outbound_stop.rs similarity index 97% rename from protocols/relay/src/v2/protocol/outbound_stop.rs rename to protocols/relay/src/protocol/outbound_stop.rs index 8bd866f0d08..08056412d53 100644 --- a/protocols/relay/src/v2/protocol/outbound_stop.rs +++ b/protocols/relay/src/protocol/outbound_stop.rs @@ -18,8 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::message_proto::{stop_message, Limit, Peer, Status, StopMessage}; -use crate::v2::protocol::{MAX_MESSAGE_SIZE, STOP_PROTOCOL_NAME}; +use crate::message_proto::{stop_message, Limit, Peer, Status, StopMessage}; +use crate::protocol::{MAX_MESSAGE_SIZE, STOP_PROTOCOL_NAME}; use asynchronous_codec::{Framed, FramedParts}; use bytes::Bytes; use futures::{future::BoxFuture, prelude::*}; diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index e58f1fe9eed..152795c34b4 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -21,30 +21,47 @@ //! Implementation of the [libp2p circuit relay v2 //! specification](https://github.com/libp2p/specs/blob/master/relay/circuit-v2.md). -#[allow(clippy::derive_partial_eq_without_eq)] -mod message_proto { - include!(concat!(env!("OUT_DIR"), "/message_v2.pb.rs")); -} - pub mod client; mod copy_future; -mod protocol; pub mod relay; -pub use protocol::{ - inbound_hop::FatalUpgradeError as InboundHopFatalUpgradeError, - inbound_stop::FatalUpgradeError as InboundStopFatalUpgradeError, - outbound_hop::FatalUpgradeError as OutboundHopFatalUpgradeError, - outbound_stop::FatalUpgradeError as OutboundStopFatalUpgradeError, HOP_PROTOCOL_NAME, - STOP_PROTOCOL_NAME, -}; - -/// The ID of an outgoing / incoming, relay / destination request. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub struct RequestId(u64); - -impl RequestId { - fn new() -> RequestId { - RequestId(rand::random()) - } +pub mod protocol { + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::InboundHopFatalUpgradeError instead." + )] + pub type InboundHopFatalUpgradeError = crate::protocol::inbound_hop::FatalUpgradeError; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::InboundStopFatalUpgradeError instead." + )] + pub type InboundStopFatalUpgradeError = crate::protocol::inbound_stop::FatalUpgradeError; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::OutboundHopFatalUpgradeError instead." + )] + pub type OutboundHopFatalUpgradeError = crate::protocol::outbound_hop::FatalUpgradeError; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::OutboundStopFatalUpgradeError instead." + )] + pub type OutboundStopFatalUpgradeError = crate::protocol::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; } + +#[deprecated(since = "0.15.0", note = "Use libp2p_relay::RequestId instead.")] +pub type RequestId = super::RequestId; diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index cfa5ece1917..c9f8087a4b9 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -23,7 +23,7 @@ mod handler; pub mod transport; -use crate::v2::protocol::{self, inbound_stop, outbound_hop}; +use crate::protocol::{self, inbound_stop, outbound_hop}; use bytes::Bytes; use either::Either; use futures::channel::mpsc::Receiver; diff --git a/protocols/relay/src/v2/client/handler.rs b/protocols/relay/src/v2/client/handler.rs index de4970b8240..e7b3fd209db 100644 --- a/protocols/relay/src/v2/client/handler.rs +++ b/protocols/relay/src/v2/client/handler.rs @@ -18,9 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::message_proto::Status; +use crate::protocol::{self, inbound_stop, outbound_hop}; use crate::v2::client::transport; -use crate::v2::message_proto::Status; -use crate::v2::protocol::{self, inbound_stop, outbound_hop}; use either::Either; use futures::channel::{mpsc, oneshot}; use futures::future::{BoxFuture, FutureExt}; diff --git a/protocols/relay/src/v2/client/transport.rs b/protocols/relay/src/v2/client/transport.rs index f491dc16782..e2752e00dfb 100644 --- a/protocols/relay/src/v2/client/transport.rs +++ b/protocols/relay/src/v2/client/transport.rs @@ -20,7 +20,7 @@ // DEALINGS IN THE SOFTWARE. use crate::v2::client::RelayedConnection; -use crate::v2::RequestId; +use crate::RequestId; use futures::channel::mpsc; use futures::channel::oneshot; use futures::future::{ready, BoxFuture, FutureExt, Ready}; diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index 8dc3aa5dd1f..ce6040344f4 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -23,8 +23,8 @@ mod handler; pub mod rate_limiter; -use crate::v2::message_proto; -use crate::v2::protocol::inbound_hop; +use crate::message_proto; +use crate::protocol::{inbound_hop, outbound_stop}; use either::Either; use instant::Instant; use libp2p_core::connection::ConnectionId; @@ -41,8 +41,6 @@ use std::ops::Add; use std::task::{Context, Poll}; use std::time::Duration; -use super::protocol::outbound_stop; - /// Configuration for the relay [`Behaviour`]. /// /// # Panics diff --git a/protocols/relay/src/v2/relay/handler.rs b/protocols/relay/src/v2/relay/handler.rs index ef8b40755b2..6cce932ab27 100644 --- a/protocols/relay/src/v2/relay/handler.rs +++ b/protocols/relay/src/v2/relay/handler.rs @@ -18,9 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::message_proto::Status; +use crate::protocol::{inbound_hop, outbound_stop}; use crate::v2::copy_future::CopyFuture; -use crate::v2::message_proto::Status; -use crate::v2::protocol::{inbound_hop, outbound_stop}; use crate::v2::relay::CircuitId; use bytes::Bytes; use either::Either; From 948f87b80fbf8c9cb9c649757f3f853494be71e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 14 Dec 2022 12:09:38 +0000 Subject: [PATCH 09/25] move relay::v2::client symbols to relay::client and use them across the crate --- protocols/dcutr/examples/dcutr.rs | 2 +- protocols/dcutr/tests/lib.rs | 2 +- protocols/relay/src/{v2 => }/client.rs | 10 +-- .../relay/src/{v2 => }/client/handler.rs | 2 +- .../relay/src/{v2 => }/client/transport.rs | 30 ++------- protocols/relay/src/lib.rs | 1 + protocols/relay/src/v2.rs | 63 ++++++++++++++++++- protocols/relay/tests/v2.rs | 2 +- 8 files changed, 75 insertions(+), 37 deletions(-) rename protocols/relay/src/{v2 => }/client.rs (98%) rename protocols/relay/src/{v2 => }/client/handler.rs (99%) rename protocols/relay/src/{v2 => }/client/transport.rs (96%) diff --git a/protocols/dcutr/examples/dcutr.rs b/protocols/dcutr/examples/dcutr.rs index 728eb86cb2f..1d9c3366642 100644 --- a/protocols/dcutr/examples/dcutr.rs +++ b/protocols/dcutr/examples/dcutr.rs @@ -32,7 +32,7 @@ use libp2p_dns::DnsConfig; use libp2p_identify as identify; use libp2p_noise as noise; use libp2p_ping as ping; -use libp2p_relay::v2::client; +use libp2p_relay::client; use libp2p_swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent}; use libp2p_tcp as tcp; use log::info; diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index fec2d1c80ca..a376598bea0 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -31,8 +31,8 @@ use libp2p_core::PublicKey; use libp2p_core::{identity, PeerId}; use libp2p_dcutr as dcutr; use libp2p_plaintext::PlainText2Config; -use libp2p_relay::v2::client; use libp2p_relay::v2::relay; +use libp2p_relay::client; use libp2p_swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmEvent}; use std::time::Duration; diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/client.rs similarity index 98% rename from protocols/relay/src/v2/client.rs rename to protocols/relay/src/client.rs index c9f8087a4b9..956cf9c900b 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/client.rs @@ -46,6 +46,8 @@ use std::ops::DerefMut; use std::pin::Pin; use std::task::{Context, Poll}; +pub use transport::Transport; + /// The events produced by the client `Behaviour`. #[derive(Debug)] pub enum Event { @@ -88,14 +90,6 @@ pub enum Event { }, } -#[deprecated( - since = "0.15.0", - note = "Use libp2p_relay::v2::client::Behaviour instead." -)] -/// [`NetworkBehaviour`] implementation of the relay client -/// functionality of the circuit relay v2 protocol. -pub type Client = Behaviour; - /// [`NetworkBehaviour`] implementation of the relay client /// functionality of the circuit relay v2 protocol. pub struct Behaviour { diff --git a/protocols/relay/src/v2/client/handler.rs b/protocols/relay/src/client/handler.rs similarity index 99% rename from protocols/relay/src/v2/client/handler.rs rename to protocols/relay/src/client/handler.rs index e7b3fd209db..1eccfb70a9e 100644 --- a/protocols/relay/src/v2/client/handler.rs +++ b/protocols/relay/src/client/handler.rs @@ -18,9 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::client::transport; use crate::message_proto::Status; use crate::protocol::{self, inbound_stop, outbound_hop}; -use crate::v2::client::transport; use either::Either; use futures::channel::{mpsc, oneshot}; use futures::future::{BoxFuture, FutureExt}; diff --git a/protocols/relay/src/v2/client/transport.rs b/protocols/relay/src/client/transport.rs similarity index 96% rename from protocols/relay/src/v2/client/transport.rs rename to protocols/relay/src/client/transport.rs index e2752e00dfb..e69accd298b 100644 --- a/protocols/relay/src/v2/client/transport.rs +++ b/protocols/relay/src/client/transport.rs @@ -19,7 +19,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::client::RelayedConnection; +use crate::client::RelayedConnection; use crate::RequestId; use futures::channel::mpsc; use futures::channel::oneshot; @@ -36,12 +36,6 @@ use std::pin::Pin; use std::task::{Context, Poll}; use thiserror::Error; -#[deprecated( - since = "0.15.0", - note = "Use libp2p_relay::v2::client::Transport instead." -)] -pub type ClientTransport = Transport; - /// A [`Transport`] enabling client relay capabilities. /// /// Note: The transport only handles listening and dialing on relayed [`Multiaddr`], and depends on @@ -56,7 +50,7 @@ pub type ClientTransport = Transport; /// # use libp2p_core::{Multiaddr, multiaddr::{Protocol}, Transport, PeerId}; /// # use libp2p_core::transport::memory::MemoryTransport; /// # use libp2p_core::transport::choice::OrTransport; -/// # use libp2p_relay::v2::client; +/// # use libp2p_relay::client; /// let actual_transport = MemoryTransport::default(); /// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( /// PeerId::random(), @@ -78,7 +72,7 @@ pub type ClientTransport = Transport; /// # use libp2p_core::{Multiaddr, multiaddr::{Protocol}, Transport, PeerId}; /// # use libp2p_core::transport::memory::MemoryTransport; /// # use libp2p_core::transport::choice::OrTransport; -/// # use libp2p_relay::v2::client; +/// # use libp2p_relay::client; /// # let relay_id = PeerId::random(); /// # let local_peer_id = PeerId::random(); /// let actual_transport = MemoryTransport::default(); @@ -109,7 +103,7 @@ impl Transport { /// # use libp2p_core::{Multiaddr, multiaddr::{Protocol}, Transport, PeerId}; /// # use libp2p_core::transport::memory::MemoryTransport; /// # use libp2p_core::transport::choice::OrTransport; - /// # use libp2p_relay::v2::client; + /// # use libp2p_relay::client; /// let actual_transport = MemoryTransport::default(); /// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( /// PeerId::random(), @@ -322,19 +316,13 @@ fn parse_relayed_multiaddr(addr: Multiaddr) -> Result::Item>, /// Channel for messages from the behaviour [`Handler`][super::handler::Handler]. from_behaviour: mpsc::Receiver, - /// The listener can be closed either manually with [`Transport::remove_listener`] or if + /// The listener can be closed either manually with [`Transport::remove_listener`](libp2p_core::Transport) or if /// the sender side of the `from_behaviour` channel is dropped. is_closed: bool, } @@ -416,12 +404,6 @@ impl Stream for Listener { pub type RelayedDial = BoxFuture<'static, Result>; -#[deprecated( - since = "0.15.0", - note = "Use libp2p_relay::v2::client::Error instead." -)] -pub type RelayError = Error; - /// Error that occurred during relay connection setup. #[derive(Debug, Error)] pub enum Error { @@ -455,7 +437,7 @@ impl From for TransportError { } } -/// Message from the [`Transport`] to the [`Behaviour`](crate::v2::relay::Behaviour) +/// Message from the [`Transport`] to the [`Behaviour`](crate::Behaviour) /// [`NetworkBehaviour`](libp2p_swarm::NetworkBehaviour). pub enum TransportToBehaviourMsg { /// Dial destination node via relay node. diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index be258d2a0c2..5cad93b23f7 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -23,6 +23,7 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +pub mod client; mod protocol; pub mod v2; diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index 152795c34b4..b68947e44bb 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -21,10 +21,71 @@ //! Implementation of the [libp2p circuit relay v2 //! specification](https://github.com/libp2p/specs/blob/master/relay/circuit-v2.md). -pub mod client; mod copy_future; pub mod relay; +pub mod client { + #[deprecated(since = "0.15.0", note = "Use libp2p_relay::client::Event instead.")] + pub type Event = crate::client::Event; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::Behaviour instead." + )] + pub type Client = crate::client::Behaviour; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::RelayedConnection instead." + )] + pub type RelayedConnection = crate::client::RelayedConnection; + + pub mod transport { + use futures::future::BoxFuture; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::Transport instead." + )] + pub type ClientTransport = crate::client::Transport; + + #[deprecated(since = "0.15.0", note = "Use libp2p_relay::Listener instead.")] + pub type RelayListener = crate::client::transport::Listener; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::transport::RelayedDial instead." + )] + pub type RelayedDial = BoxFuture< + 'static, + Result, + >; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::transport::Error instead." + )] + pub type RelayError = crate::client::transport::Error; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::transport::TransportToBehaviourMsg instead." + )] + pub type TransportToBehaviourMsg = crate::client::transport::TransportToBehaviourMsg; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::transport::ToListenerMsg instead." + )] + pub type ToListenerMsg = crate::client::transport::ToListenerMsg; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::transport::Reservation instead." + )] + pub type Reservation = crate::client::transport::Reservation; + } +} pub mod protocol { #[deprecated( since = "0.15.0", diff --git a/protocols/relay/tests/v2.rs b/protocols/relay/tests/v2.rs index ded04604349..cadd80f8244 100644 --- a/protocols/relay/tests/v2.rs +++ b/protocols/relay/tests/v2.rs @@ -31,7 +31,7 @@ use libp2p_core::PublicKey; use libp2p_core::{identity, upgrade, PeerId}; use libp2p_ping as ping; use libp2p_plaintext::PlainText2Config; -use libp2p_relay::v2::client; +use libp2p_relay::client; use libp2p_relay::v2::relay; use libp2p_swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmEvent}; use std::time::Duration; From dcbca3a5c58c9aae13a4bcd3f97db86e062cb8c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 14 Dec 2022 12:54:31 +0000 Subject: [PATCH 10/25] move relay::v2::copy_future module to relay::copy_future and use it across the crate --- protocols/relay/src/{v2 => }/copy_future.rs | 0 protocols/relay/src/lib.rs | 1 + protocols/relay/src/v2.rs | 1 - protocols/relay/src/v2/relay/handler.rs | 2 +- 4 files changed, 2 insertions(+), 2 deletions(-) rename protocols/relay/src/{v2 => }/copy_future.rs (100%) diff --git a/protocols/relay/src/v2/copy_future.rs b/protocols/relay/src/copy_future.rs similarity index 100% rename from protocols/relay/src/v2/copy_future.rs rename to protocols/relay/src/copy_future.rs diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index 5cad93b23f7..bc9fa61267a 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -24,6 +24,7 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] pub mod client; +mod copy_future; mod protocol; pub mod v2; diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index b68947e44bb..f1387bba8d6 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -21,7 +21,6 @@ //! Implementation of the [libp2p circuit relay v2 //! specification](https://github.com/libp2p/specs/blob/master/relay/circuit-v2.md). -mod copy_future; pub mod relay; pub mod client { diff --git a/protocols/relay/src/v2/relay/handler.rs b/protocols/relay/src/v2/relay/handler.rs index 6cce932ab27..d62ce738ed0 100644 --- a/protocols/relay/src/v2/relay/handler.rs +++ b/protocols/relay/src/v2/relay/handler.rs @@ -18,9 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::copy_future::CopyFuture; use crate::message_proto::Status; use crate::protocol::{inbound_hop, outbound_stop}; -use crate::v2::copy_future::CopyFuture; use crate::v2::relay::CircuitId; use bytes::Bytes; use either::Either; From db1ff9f657ca261295c4912293581f35d80a6593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 14 Dec 2022 14:17:43 +0000 Subject: [PATCH 11/25] move relay::v2::relay symbols to relay::behaviour, and use them across the crate. Deprecate the v2 ones. --- misc/metrics/src/lib.rs | 4 +- misc/metrics/src/relay.rs | 44 +++++++------------ protocols/dcutr/tests/lib.rs | 2 +- .../relay/examples/{relay_v2.rs => relay.rs} | 2 +- .../relay/src/{v2/relay.rs => behaviour.rs} | 7 --- .../src/{v2/relay => behaviour}/handler.rs | 2 +- .../{v2/relay => behaviour}/rate_limiter.rs | 0 protocols/relay/src/lib.rs | 2 + protocols/relay/src/v2.rs | 43 +++++++++++++++++- protocols/relay/tests/{v2.rs => lib.rs} | 2 +- 10 files changed, 65 insertions(+), 43 deletions(-) rename protocols/relay/examples/{relay_v2.rs => relay.rs} (99%) rename protocols/relay/src/{v2/relay.rs => behaviour.rs} (99%) rename protocols/relay/src/{v2/relay => behaviour}/handler.rs (99%) rename protocols/relay/src/{v2/relay => behaviour}/rate_limiter.rs (100%) rename protocols/relay/tests/{v2.rs => lib.rs} (99%) diff --git a/misc/metrics/src/lib.rs b/misc/metrics/src/lib.rs index 351887260df..3a4bf4bcbc3 100644 --- a/misc/metrics/src/lib.rs +++ b/misc/metrics/src/lib.rs @@ -136,8 +136,8 @@ impl Recorder for Metrics { } #[cfg(feature = "relay")] -impl Recorder for Metrics { - fn record(&self, event: &libp2p_relay::v2::relay::Event) { +impl Recorder for Metrics { + fn record(&self, event: &libp2p_relay::Event) { self.relay.record(event) } } diff --git a/misc/metrics/src/relay.rs b/misc/metrics/src/relay.rs index 9267a975b08..b5892532c7b 100644 --- a/misc/metrics/src/relay.rs +++ b/misc/metrics/src/relay.rs @@ -63,47 +63,35 @@ enum EventType { CircuitClosed, } -impl From<&libp2p_relay::v2::relay::Event> for EventType { - fn from(event: &libp2p_relay::v2::relay::Event) -> Self { +impl From<&libp2p_relay::Event> for EventType { + fn from(event: &libp2p_relay::Event) -> Self { match event { - libp2p_relay::v2::relay::Event::ReservationReqAccepted { .. } => { - EventType::ReservationReqAccepted - } - libp2p_relay::v2::relay::Event::ReservationReqAcceptFailed { .. } => { + libp2p_relay::Event::ReservationReqAccepted { .. } => EventType::ReservationReqAccepted, + libp2p_relay::Event::ReservationReqAcceptFailed { .. } => { EventType::ReservationReqAcceptFailed } - libp2p_relay::v2::relay::Event::ReservationReqDenied { .. } => { - EventType::ReservationReqDenied - } - libp2p_relay::v2::relay::Event::ReservationReqDenyFailed { .. } => { + libp2p_relay::Event::ReservationReqDenied { .. } => EventType::ReservationReqDenied, + libp2p_relay::Event::ReservationReqDenyFailed { .. } => { EventType::ReservationReqDenyFailed } - libp2p_relay::v2::relay::Event::ReservationTimedOut { .. } => { - EventType::ReservationTimedOut - } - libp2p_relay::v2::relay::Event::CircuitReqReceiveFailed { .. } => { + libp2p_relay::Event::ReservationTimedOut { .. } => EventType::ReservationTimedOut, + libp2p_relay::Event::CircuitReqReceiveFailed { .. } => { EventType::CircuitReqReceiveFailed } - libp2p_relay::v2::relay::Event::CircuitReqDenied { .. } => EventType::CircuitReqDenied, - libp2p_relay::v2::relay::Event::CircuitReqOutboundConnectFailed { .. } => { + libp2p_relay::Event::CircuitReqDenied { .. } => EventType::CircuitReqDenied, + libp2p_relay::Event::CircuitReqOutboundConnectFailed { .. } => { EventType::CircuitReqOutboundConnectFailed } - libp2p_relay::v2::relay::Event::CircuitReqDenyFailed { .. } => { - EventType::CircuitReqDenyFailed - } - libp2p_relay::v2::relay::Event::CircuitReqAccepted { .. } => { - EventType::CircuitReqAccepted - } - libp2p_relay::v2::relay::Event::CircuitReqAcceptFailed { .. } => { - EventType::CircuitReqAcceptFailed - } - libp2p_relay::v2::relay::Event::CircuitClosed { .. } => EventType::CircuitClosed, + libp2p_relay::Event::CircuitReqDenyFailed { .. } => EventType::CircuitReqDenyFailed, + libp2p_relay::Event::CircuitReqAccepted { .. } => EventType::CircuitReqAccepted, + libp2p_relay::Event::CircuitReqAcceptFailed { .. } => EventType::CircuitReqAcceptFailed, + libp2p_relay::Event::CircuitClosed { .. } => EventType::CircuitClosed, } } } -impl super::Recorder for Metrics { - fn record(&self, event: &libp2p_relay::v2::relay::Event) { +impl super::Recorder for Metrics { + fn record(&self, event: &libp2p_relay::Event) { self.events .get_or_create(&EventLabels { event: event.into(), diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index a376598bea0..65f5f977388 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -31,7 +31,7 @@ use libp2p_core::PublicKey; use libp2p_core::{identity, PeerId}; use libp2p_dcutr as dcutr; use libp2p_plaintext::PlainText2Config; -use libp2p_relay::v2::relay; +use libp2p_relay as relay; use libp2p_relay::client; use libp2p_swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmEvent}; use std::time::Duration; diff --git a/protocols/relay/examples/relay_v2.rs b/protocols/relay/examples/relay.rs similarity index 99% rename from protocols/relay/examples/relay_v2.rs rename to protocols/relay/examples/relay.rs index abe198d1350..d04060d2b79 100644 --- a/protocols/relay/examples/relay_v2.rs +++ b/protocols/relay/examples/relay.rs @@ -28,7 +28,7 @@ use libp2p_core::{identity, Multiaddr, PeerId, Transport}; use libp2p_identify as identify; use libp2p_noise as noise; use libp2p_ping as ping; -use libp2p_relay::v2::relay; +use libp2p_relay as relay; use libp2p_swarm::{NetworkBehaviour, Swarm, SwarmEvent}; use libp2p_tcp as tcp; use std::error::Error; diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/behaviour.rs similarity index 99% rename from protocols/relay/src/v2/relay.rs rename to protocols/relay/src/behaviour.rs index ce6040344f4..3a10045ad9f 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/behaviour.rs @@ -187,13 +187,6 @@ pub enum Event { }, } -#[deprecated( - since = "0.15.0", - note = "Use libp2p_relay::v2::relay::Behaviour instead." -)] -/// [`Relay`] is a [`NetworkBehaviour`] that implements the relay server. -pub type Relay = Behaviour; - /// [`NetworkBehaviour`] implementation of the relay server /// functionality of the circuit relay v2 protocol. pub struct Behaviour { diff --git a/protocols/relay/src/v2/relay/handler.rs b/protocols/relay/src/behaviour/handler.rs similarity index 99% rename from protocols/relay/src/v2/relay/handler.rs rename to protocols/relay/src/behaviour/handler.rs index d62ce738ed0..120e980c001 100644 --- a/protocols/relay/src/v2/relay/handler.rs +++ b/protocols/relay/src/behaviour/handler.rs @@ -18,10 +18,10 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::behaviour::CircuitId; use crate::copy_future::CopyFuture; use crate::message_proto::Status; use crate::protocol::{inbound_hop, outbound_stop}; -use crate::v2::relay::CircuitId; use bytes::Bytes; use either::Either; use futures::channel::oneshot::{self, Canceled}; diff --git a/protocols/relay/src/v2/relay/rate_limiter.rs b/protocols/relay/src/behaviour/rate_limiter.rs similarity index 100% rename from protocols/relay/src/v2/relay/rate_limiter.rs rename to protocols/relay/src/behaviour/rate_limiter.rs diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index bc9fa61267a..b690aedfb54 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -23,6 +23,7 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +pub mod behaviour; pub mod client; mod copy_future; mod protocol; @@ -33,6 +34,7 @@ mod message_proto { include!(concat!(env!("OUT_DIR"), "/message_v2.pb.rs")); } +pub use behaviour::{Behaviour, Config, Event}; pub use protocol::{ inbound_hop::FatalUpgradeError as InboundHopFatalUpgradeError, inbound_stop::FatalUpgradeError as InboundStopFatalUpgradeError, diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index f1387bba8d6..be5fb4f0b88 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -21,8 +21,6 @@ //! Implementation of the [libp2p circuit relay v2 //! specification](https://github.com/libp2p/specs/blob/master/relay/circuit-v2.md). -pub mod relay; - pub mod client { #[deprecated(since = "0.15.0", note = "Use libp2p_relay::client::Event instead.")] pub type Event = crate::client::Event; @@ -85,6 +83,47 @@ pub mod client { pub type Reservation = crate::client::transport::Reservation; } } + +pub mod relay { + #[deprecated(since = "0.15.0", note = "Use libp2p_relay::Config instead.")] + pub type Config = crate::Config; + + #[deprecated(since = "0.15.0", note = "Use libp2p_relay::Event instead.")] + pub type Event = crate::Event; + + #[deprecated(since = "0.15.0", note = "Use libp2p_relay::Behaviour instead.")] + pub type Relay = crate::Behaviour; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::behaviour::CircuitId instead." + )] + pub type CircuitId = crate::behaviour::CircuitId; + + pub mod rate_limiter { + use instant::Instant; + use libp2p_core::{Multiaddr, PeerId}; + + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::behaviour::rate_limiter::RateLimiter instead." + )] + pub trait RateLimiter: Send { + fn try_next(&mut self, peer: PeerId, addr: &Multiaddr, now: Instant) -> bool; + } + + #[allow(deprecated)] + impl RateLimiter for T + where + T: crate::behaviour::rate_limiter::RateLimiter, + { + fn try_next(&mut self, peer: PeerId, addr: &Multiaddr, now: Instant) -> bool { + self.try_next(peer, addr, now) + } + } + } +} + pub mod protocol { #[deprecated( since = "0.15.0", diff --git a/protocols/relay/tests/v2.rs b/protocols/relay/tests/lib.rs similarity index 99% rename from protocols/relay/tests/v2.rs rename to protocols/relay/tests/lib.rs index cadd80f8244..c6363f3d3b9 100644 --- a/protocols/relay/tests/v2.rs +++ b/protocols/relay/tests/lib.rs @@ -31,8 +31,8 @@ use libp2p_core::PublicKey; use libp2p_core::{identity, upgrade, PeerId}; use libp2p_ping as ping; use libp2p_plaintext::PlainText2Config; +use libp2p_relay as relay; use libp2p_relay::client; -use libp2p_relay::v2::relay; use libp2p_swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmEvent}; use std::time::Duration; From 2171c366142f1da505c19c86dfb28a703c6cc831 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 13 Dec 2022 13:57:08 +0100 Subject: [PATCH 12/25] chore(ROADMAP): Mark Kademlia efficient querying as done (#3233) With https://github.com/libp2p/rust-libp2p/pull/2712 merged, this can be marked as done. --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 2a0e6651f83..61a3c876a89 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -123,7 +123,7 @@ First draft is in https://github.com/libp2p/rust-libp2p/pull/2828 | Category | Status | Target Completion | Tracking | Dependencies | Dependents | |--------------|-------------|-------------------|-------------------------------------------------|--------------|------------| -| Optimization | in progress | Q1/2023 | https://github.com/libp2p/rust-libp2p/pull/2712 | | | +| Optimization | done | Q1/2023 | https://github.com/libp2p/rust-libp2p/pull/2712 | | | Users of rust-libp2p like [iroh](https://github.com/n0-computer/iroh) need this for low latency usage of `libp2p-kad`. The rust-libp2p maintainers can pick this up unless iroh folks finish the From e6e40050b5f5bfb735f06aad9ae8133f20c89b31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 13 Dec 2022 20:24:31 +0000 Subject: [PATCH 13/25] feat: move Identify I/O from NetworkBehaviour to ConnectionHandler (#3208) Addresses #2885 --- protocols/identify/CHANGELOG.md | 5 + protocols/identify/src/behaviour.rs | 237 +++++++++++----------------- protocols/identify/src/handler.rs | 196 ++++++++++++++++++----- protocols/identify/src/protocol.rs | 80 ++++------ 4 files changed, 292 insertions(+), 226 deletions(-) diff --git a/protocols/identify/CHANGELOG.md b/protocols/identify/CHANGELOG.md index f85477d8434..61032f9b6a6 100644 --- a/protocols/identify/CHANGELOG.md +++ b/protocols/identify/CHANGELOG.md @@ -1,7 +1,12 @@ # 0.42.0 [unreleased] +- Move I/O from `Behaviour` to `Handler`. Handle `Behaviour`'s Identify and Push requests independently by incoming order, + previously Push requests were prioritized. see [PR 3208]. + - Update to `libp2p-swarm` `v0.42.0`. +[PR 3208]: https://github.com/libp2p/rust-libp2p/pull/3208 + # 0.41.0 - Change default `cache_size` of `Config` to 100. See [PR 2995]. diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index 0e53470fd40..f37abfc0da7 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -18,24 +18,21 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::handler::{self, Proto, Push}; -use crate::protocol::{Info, ReplySubstream, UpgradeError}; -use futures::prelude::*; +use crate::handler::{self, InEvent, Proto}; +use crate::protocol::{Info, Protocol, UpgradeError}; use libp2p_core::{ - connection::ConnectionId, multiaddr::Protocol, ConnectedPoint, Multiaddr, PeerId, PublicKey, + connection::ConnectionId, multiaddr, ConnectedPoint, Multiaddr, PeerId, PublicKey, }; use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}; use libp2p_swarm::{ dial_opts::DialOpts, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError, - IntoConnectionHandler, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, - NotifyHandler, PollParameters, + IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use lru::LruCache; use std::num::NonZeroUsize; use std::{ collections::{HashMap, HashSet, VecDeque}, iter::FromIterator, - pin::Pin, task::Context, task::Poll, time::Duration, @@ -51,30 +48,23 @@ pub struct Behaviour { config: Config, /// For each peer we're connected to, the observed address to send back to it. connected: HashMap>, - /// Pending replies to send. - pending_replies: VecDeque, + /// Pending requests to be fulfilled, either `Handler` requests for `Behaviour` info + /// to address identification requests, or push requests to peers + /// with current information about the local peer. + requests: Vec, /// Pending events to be emitted when polled. events: VecDeque>, - /// Peers to which an active push with current information about - /// the local peer should be sent. - pending_push: HashSet, /// The addresses of all peers that we have discovered. discovered_peers: PeerCache, } -/// A pending reply to an inbound identification request. -enum Reply { - /// The reply is queued for sending. - Queued { - peer: PeerId, - io: ReplySubstream, - observed: Multiaddr, - }, - /// The reply is being sent. - Sending { - peer: PeerId, - io: Pin> + Send>>, - }, +/// A `Behaviour` request to be fulfilled, either `Handler` requests for `Behaviour` info +/// to address identification requests, or push requests to peers +/// with current information about the local peer. +#[derive(Debug, PartialEq, Eq)] +struct Request { + peer_id: PeerId, + protocol: Protocol, } /// Configuration for the [`identify::Behaviour`](Behaviour). @@ -184,9 +174,8 @@ impl Behaviour { Self { config, connected: HashMap::new(), - pending_replies: VecDeque::new(), + requests: Vec::new(), events: VecDeque::new(), - pending_push: HashSet::new(), discovered_peers, } } @@ -197,7 +186,13 @@ impl Behaviour { I: IntoIterator, { for p in peers { - if self.pending_push.insert(p) && !self.connected.contains_key(&p) { + let request = Request { + peer_id: p, + protocol: Protocol::Push, + }; + if !self.requests.contains(&request) { + self.requests.push(request); + let handler = self.new_handler(); self.events.push_back(NetworkBehaviourAction::Dial { opts: DialOpts::peer_id(p).build(), @@ -240,13 +235,19 @@ impl NetworkBehaviour for Behaviour { type OutEvent = Event; fn new_handler(&mut self) -> Self::ConnectionHandler { - Proto::new(self.config.initial_delay, self.config.interval) + Proto::new( + self.config.initial_delay, + self.config.interval, + self.config.local_public_key.clone(), + self.config.protocol_version.clone(), + self.config.agent_version.clone(), + ) } fn on_connection_handler_event( &mut self, peer_id: PeerId, - connection: ConnectionId, + connection_id: ConnectionId, event: <::Handler as ConnectionHandler>::OutEvent, ) { match event { @@ -271,26 +272,22 @@ impl NetworkBehaviour for Behaviour { score: AddressScore::Finite(1), }); } + handler::Event::Identification(peer) => { + self.events + .push_back(NetworkBehaviourAction::GenerateEvent(Event::Sent { + peer_id: peer, + })); + } handler::Event::IdentificationPushed => { self.events .push_back(NetworkBehaviourAction::GenerateEvent(Event::Pushed { peer_id, })); } - handler::Event::Identify(sender) => { - let observed = self - .connected - .get(&peer_id) - .and_then(|addrs| addrs.get(&connection)) - .expect( - "`on_connection_handler_event` is only called \ - with an established connection and calling `NetworkBehaviour::on_event` \ - with `FromSwarm::ConnectionEstablished ensures there is an entry; qed", - ); - self.pending_replies.push_back(Reply::Queued { - peer: peer_id, - io: sender, - observed: observed.clone(), + handler::Event::Identify => { + self.requests.push(Request { + peer_id, + protocol: Protocol::Identify(connection_id), }); } handler::Event::IdentificationError(error) => { @@ -305,99 +302,41 @@ impl NetworkBehaviour for Behaviour { fn poll( &mut self, - cx: &mut Context<'_>, + _cx: &mut Context<'_>, params: &mut impl PollParameters, ) -> Poll> { if let Some(event) = self.events.pop_front() { return Poll::Ready(event); } - // Check for a pending active push to perform. - let peer_push = self.pending_push.iter().find_map(|peer| { - self.connected.get(peer).map(|conns| { - let observed_addr = conns - .values() - .next() - .expect("connected peer has a connection") - .clone(); - - let listen_addrs = listen_addrs(params); - let protocols = supported_protocols(params); - - let info = Info { - public_key: self.config.local_public_key.clone(), - protocol_version: self.config.protocol_version.clone(), - agent_version: self.config.agent_version.clone(), - listen_addrs, - protocols, - observed_addr, - }; - - (*peer, Push(info)) - }) - }); - - if let Some((peer_id, push)) = peer_push { - self.pending_push.remove(&peer_id); - return Poll::Ready(NetworkBehaviourAction::NotifyHandler { + // Check for pending requests. + match self.requests.pop() { + Some(Request { + peer_id, + protocol: Protocol::Push, + }) => Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, - event: push, handler: NotifyHandler::Any, - }); - } - - // Check for pending replies to send. - if let Some(r) = self.pending_replies.pop_front() { - let mut sending = 0; - let to_send = self.pending_replies.len() + 1; - let mut reply = Some(r); - loop { - match reply { - Some(Reply::Queued { peer, io, observed }) => { - let info = Info { - listen_addrs: listen_addrs(params), - protocols: supported_protocols(params), - public_key: self.config.local_public_key.clone(), - protocol_version: self.config.protocol_version.clone(), - agent_version: self.config.agent_version.clone(), - observed_addr: observed, - }; - let io = Box::pin(io.send(info)); - reply = Some(Reply::Sending { peer, io }); - } - Some(Reply::Sending { peer, mut io }) => { - sending += 1; - match Future::poll(Pin::new(&mut io), cx) { - Poll::Ready(Ok(())) => { - let event = Event::Sent { peer_id: peer }; - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - Poll::Pending => { - self.pending_replies.push_back(Reply::Sending { peer, io }); - if sending == to_send { - // All remaining futures are NotReady - break; - } else { - reply = self.pending_replies.pop_front(); - } - } - Poll::Ready(Err(err)) => { - let event = Event::Error { - peer_id: peer, - error: ConnectionHandlerUpgrErr::Upgrade( - libp2p_core::upgrade::UpgradeError::Apply(err), - ), - }; - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - } - } - None => unreachable!(), - } - } + event: InEvent { + listen_addrs: listen_addrs(params), + supported_protocols: supported_protocols(params), + protocol: Protocol::Push, + }, + }), + Some(Request { + peer_id, + protocol: Protocol::Identify(connection_id), + }) => Poll::Ready(NetworkBehaviourAction::NotifyHandler { + peer_id, + handler: NotifyHandler::One(connection_id), + event: InEvent { + listen_addrs: listen_addrs(params), + supported_protocols: supported_protocols(params), + protocol: Protocol::Identify(connection_id), + }, + }), + None => Poll::Pending, } - - Poll::Pending } fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec { @@ -417,7 +356,13 @@ impl NetworkBehaviour for Behaviour { }) => { if remaining_established == 0 { self.connected.remove(&peer_id); - self.pending_push.remove(&peer_id); + self.requests.retain(|request| { + request + != &Request { + peer_id, + protocol: Protocol::Push, + } + }); } else if let Some(addrs) = self.connected.get_mut(&peer_id) { addrs.remove(&connection_id); } @@ -425,7 +370,13 @@ impl NetworkBehaviour for Behaviour { FromSwarm::DialFailure(DialFailure { peer_id, error, .. }) => { if let Some(peer_id) = peer_id { if !self.connected.contains_key(&peer_id) { - self.pending_push.remove(&peer_id); + self.requests.retain(|request| { + request + != &Request { + peer_id, + protocol: Protocol::Push, + } + }); } } @@ -437,14 +388,17 @@ impl NetworkBehaviour for Behaviour { } } } - FromSwarm::NewListenAddr(_) => { - if self.config.push_listen_addr_updates { - self.pending_push.extend(self.connected.keys()); - } - } - FromSwarm::ExpiredListenAddr(_) => { + FromSwarm::NewListenAddr(_) | FromSwarm::ExpiredListenAddr(_) => { if self.config.push_listen_addr_updates { - self.pending_push.extend(self.connected.keys()); + for p in self.connected.keys() { + let request = Request { + peer_id: *p, + protocol: Protocol::Push, + }; + if !self.requests.contains(&request) { + self.requests.push(request); + } + } } } FromSwarm::AddressChange(_) @@ -509,7 +463,7 @@ fn listen_addrs(params: &impl PollParameters) -> Vec { /// the given peer_id. If there is no peer_id for the peer in the mutiaddr, this returns true. fn multiaddr_matches_peer_id(addr: &Multiaddr, peer_id: &PeerId) -> bool { let last_component = addr.iter().last(); - if let Some(Protocol::P2p(multi_addr_peer_id)) = last_component { + if let Some(multiaddr::Protocol::P2p(multi_addr_peer_id)) = last_component { return multi_addr_peer_id == *peer_id.as_ref(); } true @@ -557,6 +511,7 @@ impl PeerCache { mod tests { use super::*; use futures::pin_mut; + use futures::prelude::*; use libp2p_core::{identity, muxing::StreamMuxerBox, transport, upgrade, PeerId, Transport}; use libp2p_mplex::MplexConfig; use libp2p_noise as noise; @@ -618,7 +573,7 @@ mod tests { // nb. Either swarm may receive the `Identified` event first, upon which // it will permit the connection to be closed, as defined by - // `IdentifyHandler::connection_keep_alive`. Hence the test succeeds if + // `Handler::connection_keep_alive`. Hence the test succeeds if // either `Identified` event arrives correctly. async_std::task::block_on(async move { loop { @@ -835,8 +790,8 @@ mod tests { let addr_without_peer_id: Multiaddr = addr.clone(); let mut addr_with_other_peer_id = addr.clone(); - addr.push(Protocol::P2p(peer_id.into())); - addr_with_other_peer_id.push(Protocol::P2p(other_peer_id.into())); + addr.push(multiaddr::Protocol::P2p(peer_id.into())); + addr_with_other_peer_id.push(multiaddr::Protocol::P2p(other_peer_id.into())); assert!(multiaddr_matches_peer_id(&addr, &peer_id)); assert!(!multiaddr_matches_peer_id( diff --git a/protocols/identify/src/handler.rs b/protocols/identify/src/handler.rs index 0de54f0a006..21063acc661 100644 --- a/protocols/identify/src/handler.rs +++ b/protocols/identify/src/handler.rs @@ -19,14 +19,15 @@ // DEALINGS IN THE SOFTWARE. use crate::protocol::{ - InboundPush, Info, OutboundPush, Protocol, PushProtocol, ReplySubstream, UpgradeError, + self, Identify, InboundPush, Info, OutboundPush, Protocol, Push, UpgradeError, }; use futures::future::BoxFuture; use futures::prelude::*; +use futures::stream::FuturesUnordered; use futures_timer::Delay; use libp2p_core::either::{EitherError, EitherOutput}; use libp2p_core::upgrade::{EitherUpgrade, SelectUpgrade}; -use libp2p_core::{ConnectedPoint, PeerId}; +use libp2p_core::{ConnectedPoint, Multiaddr, PeerId, PublicKey}; use libp2p_swarm::handler::{ ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, }; @@ -36,18 +37,31 @@ use libp2p_swarm::{ }; use log::warn; use smallvec::SmallVec; +use std::collections::VecDeque; use std::{io, pin::Pin, task::Context, task::Poll, time::Duration}; pub struct Proto { initial_delay: Duration, interval: Duration, + public_key: PublicKey, + protocol_version: String, + agent_version: String, } impl Proto { - pub fn new(initial_delay: Duration, interval: Duration) -> Self { + pub fn new( + initial_delay: Duration, + interval: Duration, + public_key: PublicKey, + protocol_version: String, + agent_version: String, + ) -> Self { Proto { initial_delay, interval, + public_key, + protocol_version, + agent_version, } } } @@ -55,12 +69,25 @@ impl Proto { impl IntoConnectionHandler for Proto { type Handler = Handler; - fn into_handler(self, remote_peer_id: &PeerId, _endpoint: &ConnectedPoint) -> Self::Handler { - Handler::new(self.initial_delay, self.interval, *remote_peer_id) + fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { + let observed_addr = match endpoint { + ConnectedPoint::Dialer { address, .. } => address, + ConnectedPoint::Listener { send_back_addr, .. } => send_back_addr, + }; + + Handler::new( + self.initial_delay, + self.interval, + *remote_peer_id, + self.public_key, + self.protocol_version, + self.agent_version, + observed_addr.clone(), + ) } fn inbound_protocol(&self) -> ::InboundProtocol { - SelectUpgrade::new(Protocol, PushProtocol::inbound()) + SelectUpgrade::new(Identify, Push::inbound()) } } @@ -74,14 +101,16 @@ pub struct Handler { inbound_identify_push: Option>>, /// Pending events to yield. events: SmallVec< - [ConnectionHandlerEvent< - EitherUpgrade>, - (), - Event, - io::Error, - >; 4], + [ConnectionHandlerEvent>, (), Event, io::Error>; + 4], >, + /// Streams awaiting `BehaviourInfo` to then send identify requests. + reply_streams: VecDeque, + + /// Pending identification replies, awaiting being sent. + pending_replies: FuturesUnordered>>, + /// Future that fires when we need to identify the node again. trigger_next_identify: Delay, @@ -90,36 +119,75 @@ pub struct Handler { /// The interval of `trigger_next_identify`, i.e. the recurrent delay. interval: Duration, + + /// The public key of the local peer. + public_key: PublicKey, + + /// Application-specific version of the protocol family used by the peer, + /// e.g. `ipfs/1.0.0` or `polkadot/1.0.0`. + protocol_version: String, + + /// Name and version of the peer, similar to the `User-Agent` header in + /// the HTTP protocol. + agent_version: String, + + /// Address observed by or for the remote. + observed_addr: Multiaddr, } -/// Event produced by the `IdentifyHandler`. +/// An event from `Behaviour` with the information requested by the `Handler`. +#[derive(Debug)] +pub struct InEvent { + /// The addresses that the peer is listening on. + pub listen_addrs: Vec, + + /// The list of protocols supported by the peer, e.g. `/ipfs/ping/1.0.0`. + pub supported_protocols: Vec, + + /// The protocol w.r.t. the information requested. + pub protocol: Protocol, +} + +/// Event produced by the `Handler`. #[derive(Debug)] #[allow(clippy::large_enum_variant)] pub enum Event { /// We obtained identification information from the remote. Identified(Info), + /// We replied to an identification request from the remote. + Identification(PeerId), /// We actively pushed our identification information to the remote. IdentificationPushed, /// We received a request for identification. - Identify(ReplySubstream), - /// Failed to identify the remote. + Identify, + /// Failed to identify the remote, or to reply to an identification request. IdentificationError(ConnectionHandlerUpgrErr), } -/// Identifying information of the local node that is pushed to a remote. -#[derive(Debug)] -pub struct Push(pub Info); - impl Handler { - /// Creates a new `IdentifyHandler`. - pub fn new(initial_delay: Duration, interval: Duration, remote_peer_id: PeerId) -> Self { + /// Creates a new `Handler`. + pub fn new( + initial_delay: Duration, + interval: Duration, + remote_peer_id: PeerId, + public_key: PublicKey, + protocol_version: String, + agent_version: String, + observed_addr: Multiaddr, + ) -> Self { Self { remote_peer_id, inbound_identify_push: Default::default(), events: SmallVec::new(), + reply_streams: VecDeque::new(), + pending_replies: FuturesUnordered::new(), trigger_next_identify: Delay::new(initial_delay), keep_alive: KeepAlive::Yes, interval, + public_key, + protocol_version, + agent_version, + observed_addr, } } @@ -133,9 +201,18 @@ impl Handler { >, ) { match output { - EitherOutput::First(substream) => self - .events - .push(ConnectionHandlerEvent::Custom(Event::Identify(substream))), + EitherOutput::First(substream) => { + self.events + .push(ConnectionHandlerEvent::Custom(Event::Identify)); + if !self.reply_streams.is_empty() { + warn!( + "New inbound identify request from {} while a previous one \ + is still pending. Queueing the new one.", + self.remote_peer_id, + ); + } + self.reply_streams.push_back(substream); + } EitherOutput::Second(fut) => { if self.inbound_identify_push.replace(fut).is_some() { warn!( @@ -195,26 +272,58 @@ impl Handler { } impl ConnectionHandler for Handler { - type InEvent = Push; + type InEvent = InEvent; type OutEvent = Event; type Error = io::Error; - type InboundProtocol = SelectUpgrade>; - type OutboundProtocol = EitherUpgrade>; + type InboundProtocol = SelectUpgrade>; + type OutboundProtocol = EitherUpgrade>; type OutboundOpenInfo = (); type InboundOpenInfo = (); fn listen_protocol(&self) -> SubstreamProtocol { - SubstreamProtocol::new(SelectUpgrade::new(Protocol, PushProtocol::inbound()), ()) + SubstreamProtocol::new(SelectUpgrade::new(Identify, Push::inbound()), ()) } - fn on_behaviour_event(&mut self, Push(push): Self::InEvent) { - self.events - .push(ConnectionHandlerEvent::OutboundSubstreamRequest { - protocol: SubstreamProtocol::new( - EitherUpgrade::B(PushProtocol::outbound(push)), - (), - ), - }); + fn on_behaviour_event( + &mut self, + InEvent { + listen_addrs, + supported_protocols, + protocol, + }: Self::InEvent, + ) { + let info = Info { + public_key: self.public_key.clone(), + protocol_version: self.protocol_version.clone(), + agent_version: self.agent_version.clone(), + listen_addrs, + protocols: supported_protocols, + observed_addr: self.observed_addr.clone(), + }; + + match protocol { + Protocol::Push => { + self.events + .push(ConnectionHandlerEvent::OutboundSubstreamRequest { + protocol: SubstreamProtocol::new( + EitherUpgrade::B(Push::outbound(info)), + (), + ), + }); + } + Protocol::Identify(_) => { + let substream = self + .reply_streams + .pop_front() + .expect("A BehaviourInfo reply should have a matching substream."); + let peer = self.remote_peer_id; + let fut = Box::pin(async move { + protocol::send(substream, info).await?; + Ok(peer) + }); + self.pending_replies.push(fut); + } + } } fn connection_keep_alive(&self) -> KeepAlive { @@ -237,7 +346,7 @@ impl ConnectionHandler for Handler { Poll::Ready(()) => { self.trigger_next_identify.reset(self.interval); let ev = ConnectionHandlerEvent::OutboundSubstreamRequest { - protocol: SubstreamProtocol::new(EitherUpgrade::A(Protocol), ()), + protocol: SubstreamProtocol::new(EitherUpgrade::A(Identify), ()), }; return Poll::Ready(ev); } @@ -255,7 +364,18 @@ impl ConnectionHandler for Handler { } } - Poll::Pending + // Check for pending replies to send. + match self.pending_replies.poll_next_unpin(cx) { + Poll::Ready(Some(Ok(peer_id))) => Poll::Ready(ConnectionHandlerEvent::Custom( + Event::Identification(peer_id), + )), + Poll::Ready(Some(Err(err))) => Poll::Ready(ConnectionHandlerEvent::Custom( + Event::IdentificationError(ConnectionHandlerUpgrErr::Upgrade( + libp2p_core::upgrade::UpgradeError::Apply(err), + )), + )), + Poll::Ready(None) | Poll::Pending => Poll::Pending, + } } fn on_connection_event( diff --git a/protocols/identify/src/protocol.rs b/protocols/identify/src/protocol.rs index f30622561e3..12e6de3f302 100644 --- a/protocols/identify/src/protocol.rs +++ b/protocols/identify/src/protocol.rs @@ -22,13 +22,14 @@ use crate::structs_proto; use asynchronous_codec::{FramedRead, FramedWrite}; use futures::{future::BoxFuture, prelude::*}; use libp2p_core::{ + connection::ConnectionId, identity, multiaddr, upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}, Multiaddr, PublicKey, }; use log::trace; use std::convert::TryFrom; -use std::{fmt, io, iter, pin::Pin}; +use std::{io, iter, pin::Pin}; use thiserror::Error; use void::Void; @@ -38,25 +39,32 @@ pub const PROTOCOL_NAME: &[u8; 14] = b"/ipfs/id/1.0.0"; pub const PUSH_PROTOCOL_NAME: &[u8; 19] = b"/ipfs/id/push/1.0.0"; +/// The type of the Substream protocol. +#[derive(Debug, PartialEq, Eq)] +pub enum Protocol { + Identify(ConnectionId), + Push, +} + /// Substream upgrade protocol for `/ipfs/id/1.0.0`. #[derive(Debug, Clone)] -pub struct Protocol; +pub struct Identify; /// Substream upgrade protocol for `/ipfs/id/push/1.0.0`. #[derive(Debug, Clone)] -pub struct PushProtocol(T); +pub struct Push(T); pub struct InboundPush(); pub struct OutboundPush(Info); -impl PushProtocol { +impl Push { pub fn inbound() -> Self { - PushProtocol(InboundPush()) + Push(InboundPush()) } } -impl PushProtocol { +impl Push { pub fn outbound(info: Info) -> Self { - PushProtocol(OutboundPush(info)) + Push(OutboundPush(info)) } } @@ -79,31 +87,7 @@ pub struct Info { pub observed_addr: Multiaddr, } -/// The substream on which a reply is expected to be sent. -pub struct ReplySubstream { - inner: T, -} - -impl fmt::Debug for ReplySubstream { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("ReplySubstream").finish() - } -} - -impl ReplySubstream -where - T: AsyncWrite + Unpin, -{ - /// Sends back the requested information on the substream. - /// - /// Consumes the substream, returning a future that resolves - /// when the reply has been sent on the underlying connection. - pub async fn send(self, info: Info) -> Result<(), UpgradeError> { - send(self.inner, info).await.map_err(Into::into) - } -} - -impl UpgradeInfo for Protocol { +impl UpgradeInfo for Identify { type Info = &'static [u8]; type InfoIter = iter::Once; @@ -112,17 +96,17 @@ impl UpgradeInfo for Protocol { } } -impl InboundUpgrade for Protocol { - type Output = ReplySubstream; +impl InboundUpgrade for Identify { + type Output = C; type Error = UpgradeError; type Future = future::Ready>; fn upgrade_inbound(self, socket: C, _: Self::Info) -> Self::Future { - future::ok(ReplySubstream { inner: socket }) + future::ok(socket) } } -impl OutboundUpgrade for Protocol +impl OutboundUpgrade for Identify where C: AsyncRead + AsyncWrite + Unpin + Send + 'static, { @@ -135,7 +119,7 @@ where } } -impl UpgradeInfo for PushProtocol { +impl UpgradeInfo for Push { type Info = &'static [u8]; type InfoIter = iter::Once; @@ -144,7 +128,7 @@ impl UpgradeInfo for PushProtocol { } } -impl InboundUpgrade for PushProtocol +impl InboundUpgrade for Push where C: AsyncRead + AsyncWrite + Unpin + Send + 'static, { @@ -158,7 +142,7 @@ where } } -impl OutboundUpgrade for PushProtocol +impl OutboundUpgrade for Push where C: AsyncWrite + Unpin + Send + 'static, { @@ -171,7 +155,7 @@ where } } -async fn send(io: T, info: Info) -> Result<(), UpgradeError> +pub(crate) async fn send(io: T, info: Info) -> Result<(), UpgradeError> where T: AsyncWrite + Unpin, { @@ -316,10 +300,11 @@ mod tests { .await .unwrap(); - let sender = apply_inbound(socket, Protocol).await.unwrap(); + let sender = apply_inbound(socket, Identify).await.unwrap(); - sender - .send(Info { + send( + sender, + Info { public_key: send_pubkey, protocol_version: "proto_version".to_owned(), agent_version: "agent_version".to_owned(), @@ -329,16 +314,17 @@ mod tests { ], protocols: vec!["proto1".to_string(), "proto2".to_string()], observed_addr: "/ip4/100.101.102.103/tcp/5000".parse().unwrap(), - }) - .await - .unwrap(); + }, + ) + .await + .unwrap(); }); async_std::task::block_on(async move { let mut transport = tcp::async_io::Transport::default(); let socket = transport.dial(rx.await.unwrap()).unwrap().await.unwrap(); - let info = apply_outbound(socket, Protocol, upgrade::Version::V1) + let info = apply_outbound(socket, Identify, upgrade::Version::V1) .await .unwrap(); assert_eq!( From f15d82aad08297f4ca22cecb5a10ca3658649471 Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Wed, 14 Dec 2022 09:37:19 +1100 Subject: [PATCH 14/25] ci(caching): make caching more effective (#3215) Currently, we create a new cache for each workflow run for each crate. That ends up blowing the maximum allowed cache size of 10GB and GitHub deletes the least-recently used cache again. Effectively, this means we don't have any caching. This patch introduces a cache factory workflow that only runs on master and always _saves_ a new cache. The CI workflow run for pull-requests on the other hand only restore these caches but don't save them. --- .github/workflows/cache-factory.yml | 78 +++++++++++++++++++++++++++++ .github/workflows/ci.yml | 29 +++++------ 2 files changed, 93 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/cache-factory.yml diff --git a/.github/workflows/cache-factory.yml b/.github/workflows/cache-factory.yml new file mode 100644 index 00000000000..f63e8ad7247 --- /dev/null +++ b/.github/workflows/cache-factory.yml @@ -0,0 +1,78 @@ +# This workflow _produces_ caches which are used to speed up pull request builds. +# The caches are split by Rust version (stable vs MSRV per crate) because those caches cannot share any artifacts. + +name: Cache factory + +on: + push: + branches: + - master # Caches are only created on master branch. + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + gather_msrv_versions: + runs-on: ubuntu-latest + outputs: + versions: ${{ steps.find-rust-versions.outputs.versions }} + steps: + - uses: actions/checkout@v3 + + - id: find-rust-versions + run: | + RUST_VERSIONS=$(cargo metadata --format-version=1 --no-deps | jq -c '.packages | map(.rust_version) | unique | del(..|nulls)') + echo "versions=${RUST_VERSIONS}" >> $GITHUB_OUTPUT + + make_msrv_cache: + runs-on: ubuntu-latest + needs: gather_msrv_versions + strategy: + fail-fast: false + matrix: + rust: ${{ fromJSON(needs.gather_msrv_versions.outputs.versions) }} + steps: + - name: Install Protoc + uses: arduino/setup-protoc@64c0c85d18e984422218383b81c52f8b077404d3 # v1.1.2 + + - uses: actions/checkout@v3 + + - uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 + with: + toolchain: ${{ matrix.rust }} + + - uses: Swatinem/rust-cache@359a70e43a0bb8a13953b04a90f76428b4959bb6 # v2.2.0 + with: + shared-key: msrv-cache + + - name: Compile all crates which have MSRV ${{ matrix.rust }} + run: | + cargo metadata --format-version=1 --no-deps | \ + jq -r '.packages[] | select(.rust_version == "${{ matrix.rust }}") | "+\(.rust_version) build --all-features --package \(.name)"' | + xargs --verbose -L 1 cargo + + make_stable_rust_cache: + runs-on: ubuntu-latest + steps: + - name: Install Protoc + uses: arduino/setup-protoc@64c0c85d18e984422218383b81c52f8b077404d3 # v1.1.2 + + - uses: actions/checkout@v3 + + - uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 + with: + toolchain: stable + + - uses: Swatinem/rust-cache@359a70e43a0bb8a13953b04a90f76428b4959bb6 # v2.2.0 + with: + shared-key: stable-cache + + - name: Compile workspace with stable Rust + run: cargo test --all-features --all-targets --workspace --no-run + + - name: Render docs + run: cargo doc --all-features --workspace + + - name: Install tools + run: cargo install cargo-semver-checks --locked diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d764ccd0ed..bfce5917a16 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,30 +38,33 @@ jobs: with: profile: minimal toolchain: ${{ steps.parse-msrv.outputs.version }} + override: true - - name: Update to latest stable Rust - uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 + - uses: Swatinem/rust-cache@359a70e43a0bb8a13953b04a90f76428b4959bb6 # v2.2.0 + with: + shared-key: msrv-cache + save-if: false + + - name: Check if ${{ matrix.crate }} compiles on MSRV (Rust ${{ steps.parse-msrv.outputs.version }}) + run: cargo +${{ steps.parse-msrv.outputs.version }} build --package ${{ matrix.crate }} --all-features + + - uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 with: profile: minimal toolchain: stable override: true - # By default, this action already includes the active Rust toolchain in the cache key. - # We also install a separate toolchain for the MSRV check so all we need to do is add that to the key to make sure it invalidates when we update the MSRV. - # cargo separates build artifacts by Rust compiler version, meaning we can compile with different versions but cache all artifacts. - uses: Swatinem/rust-cache@359a70e43a0bb8a13953b04a90f76428b4959bb6 # v2.2.0 with: - key: ${{ matrix.crate }}-msrv-${{ steps.parse-msrv.outputs.version }} - - - name: Check if ${{ matrix.crate }} compiles on MSRV (Rust ${{ steps.parse-msrv.outputs.version }}) - run: cargo +${{ steps.parse-msrv.outputs.version }} check --package ${{ matrix.crate }} --all-features - - - name: Check if we compile without any features activated - run: cargo check --package ${{ matrix.crate }} --no-default-features + shared-key: stable-cache + save-if: false - name: Run all tests run: cargo test --package ${{ matrix.crate }} --all-features + - name: Check if we compile without any features activated + run: cargo build --package ${{ matrix.crate }} --no-default-features + - name: Check if crate has been released id: check-released run: | @@ -138,8 +141,6 @@ jobs: override: true - uses: Swatinem/rust-cache@359a70e43a0bb8a13953b04a90f76428b4959bb6 # v2.2.0 - with: - key: ${{ matrix.runtime }} - run: cargo check --package libp2p --features="${{ matrix.features }}" From 63f03bee1916782f32c8ee7a28433596900259bd Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Wed, 14 Dec 2022 11:50:08 +1100 Subject: [PATCH 15/25] refactor(swarm)!: deprecate `PollParameters` where possible (#3153) This patch deprecates 3 out of 4 functions on `PollParameters`: - `local_peer_id` - `listened_addresses` - `external_addresses` The addresses can be obtained by inspecting the `FromSwarm` event. To make this easier, we introduce two utility structs in `libp2p-swarm`: - `ExternalAddresses` - `ListenAddresses` A node's `PeerId` is always known to the caller, thus we can require them to pass it in. Related: #3124. --- examples/chat-tokio.rs | 2 +- examples/chat.rs | 2 +- examples/distributed-key-value-store.rs | 2 +- examples/gossipsub-chat.rs | 2 +- examples/mdns-passive-discovery.rs | 2 +- protocols/autonat/CHANGELOG.md | 4 ++ protocols/autonat/src/behaviour.rs | 16 ++++- protocols/autonat/src/behaviour/as_client.rs | 23 ++++--- protocols/dcutr/CHANGELOG.md | 3 + protocols/dcutr/examples/dcutr.rs | 2 +- protocols/dcutr/src/behaviour.rs | 34 ++++++---- protocols/dcutr/tests/lib.rs | 2 +- protocols/identify/src/behaviour.rs | 31 ++++++--- protocols/kad/src/behaviour.rs | 67 ++++++++++---------- protocols/mdns/CHANGELOG.md | 4 ++ protocols/mdns/src/behaviour.rs | 21 ++++-- protocols/mdns/src/behaviour/iface.rs | 18 +++--- protocols/mdns/src/behaviour/iface/dns.rs | 6 +- protocols/mdns/src/behaviour/iface/query.rs | 2 +- protocols/mdns/tests/use-async-std.rs | 2 +- protocols/mdns/tests/use-tokio.rs | 2 +- protocols/relay/src/behaviour.rs | 26 ++++---- protocols/rendezvous/src/client.rs | 16 +++-- swarm/CHANGELOG.md | 2 + swarm/src/behaviour.rs | 17 +++++ swarm/src/behaviour/external_addresses.rs | 50 +++++++++++++++ swarm/src/behaviour/listen_addresses.rs | 33 ++++++++++ swarm/src/lib.rs | 3 +- 28 files changed, 282 insertions(+), 112 deletions(-) create mode 100644 swarm/src/behaviour/external_addresses.rs create mode 100644 swarm/src/behaviour/listen_addresses.rs diff --git a/examples/chat-tokio.rs b/examples/chat-tokio.rs index 240a52fb0c9..2d644b0f360 100644 --- a/examples/chat-tokio.rs +++ b/examples/chat-tokio.rs @@ -91,7 +91,7 @@ async fn main() -> Result<(), Box> { } // Create a Swarm to manage peers and events. - let mdns_behaviour = mdns::Behaviour::new(Default::default())?; + let mdns_behaviour = mdns::Behaviour::new(Default::default(), peer_id)?; let behaviour = MyBehaviour { floodsub: Floodsub::new(peer_id), mdns: mdns_behaviour, diff --git a/examples/chat.rs b/examples/chat.rs index 0c57f90c8ff..6d6825125df 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -107,7 +107,7 @@ async fn main() -> Result<(), Box> { // Create a Swarm to manage peers and events let mut swarm = { - let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?; + let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?; let mut behaviour = MyBehaviour { floodsub: Floodsub::new(local_peer_id), mdns, diff --git a/examples/distributed-key-value-store.rs b/examples/distributed-key-value-store.rs index bd5f4be916b..18d74270e7e 100644 --- a/examples/distributed-key-value-store.rs +++ b/examples/distributed-key-value-store.rs @@ -97,7 +97,7 @@ async fn main() -> Result<(), Box> { // Create a Kademlia behaviour. let store = MemoryStore::new(local_peer_id); let kademlia = Kademlia::new(local_peer_id, store); - let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?; + let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?; let behaviour = MyBehaviour { kademlia, mdns }; Swarm::with_async_std_executor(transport, behaviour, local_peer_id) }; diff --git a/examples/gossipsub-chat.rs b/examples/gossipsub-chat.rs index 07c04e472e5..9150aa64624 100644 --- a/examples/gossipsub-chat.rs +++ b/examples/gossipsub-chat.rs @@ -104,7 +104,7 @@ async fn main() -> Result<(), Box> { // Create a Swarm to manage peers and events let mut swarm = { - let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?; + let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?; let behaviour = MyBehaviour { gossipsub, mdns }; Swarm::with_async_std_executor(transport, behaviour, local_peer_id) }; diff --git a/examples/mdns-passive-discovery.rs b/examples/mdns-passive-discovery.rs index fc84b7972bb..587d268d0e2 100644 --- a/examples/mdns-passive-discovery.rs +++ b/examples/mdns-passive-discovery.rs @@ -39,7 +39,7 @@ async fn main() -> Result<(), Box> { let transport = libp2p::development_transport(id_keys).await?; // Create an MDNS network behaviour. - let behaviour = mdns::async_io::Behaviour::new(mdns::Config::default())?; + let behaviour = mdns::async_io::Behaviour::new(mdns::Config::default(), peer_id)?; // Create a Swarm that establishes connections through the given transport. // Note that the MDNS behaviour itself will not actually inititiate any connections, diff --git a/protocols/autonat/CHANGELOG.md b/protocols/autonat/CHANGELOG.md index 4c4efd79bf2..3da1cedb2aa 100644 --- a/protocols/autonat/CHANGELOG.md +++ b/protocols/autonat/CHANGELOG.md @@ -1,9 +1,13 @@ # 0.10.0 [unreleased] +- Require the node's local `PeerId` to be passed into the constructor of `libp2p_autonat::Behaviour`. See [PR 3153]. + - Update to `libp2p-request-response` `v0.24.0`. - Update to `libp2p-swarm` `v0.42.0`. +[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153 + # 0.9.0 - Update to `libp2p-core` `v0.38.0`. diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index a0d5ad4fedc..d9980f16dbb 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -39,8 +39,8 @@ use libp2p_swarm::{ AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, ExpiredListenAddr, FromSwarm, }, - ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, - PollParameters, + ConnectionHandler, ExternalAddresses, IntoConnectionHandler, ListenAddresses, NetworkBehaviour, + NetworkBehaviourAction, PollParameters, }; use std::{ collections::{HashMap, VecDeque}, @@ -212,6 +212,9 @@ pub struct Behaviour { pending_out_events: VecDeque<::OutEvent>, probe_id: ProbeId, + + listen_addresses: ListenAddresses, + external_addresses: ExternalAddresses, } impl Behaviour { @@ -236,6 +239,8 @@ impl Behaviour { last_probe: None, pending_out_events: VecDeque::new(), probe_id: ProbeId(0), + listen_addresses: Default::default(), + external_addresses: Default::default(), } } @@ -288,6 +293,8 @@ impl Behaviour { ongoing_outbound: &mut self.ongoing_outbound, last_probe: &mut self.last_probe, schedule_probe: &mut self.schedule_probe, + listen_addresses: &self.listen_addresses, + external_addresses: &self.external_addresses, } } @@ -457,7 +464,7 @@ impl NetworkBehaviour for Behaviour { Poll::Pending => is_inner_pending = true, } - match self.as_client().poll_auto_probe(params, cx) { + match self.as_client().poll_auto_probe(cx) { Poll::Ready(event) => self .pending_out_events .push_back(Event::OutboundProbe(event)), @@ -476,6 +483,9 @@ impl NetworkBehaviour for Behaviour { } fn on_swarm_event(&mut self, event: FromSwarm) { + self.listen_addresses.on_swarm_event(&event); + self.external_addresses.on_swarn_event(&event); + match event { FromSwarm::ConnectionEstablished(connection_established) => { self.inner diff --git a/protocols/autonat/src/behaviour/as_client.rs b/protocols/autonat/src/behaviour/as_client.rs index 43763029f65..76ddebce2dc 100644 --- a/protocols/autonat/src/behaviour/as_client.rs +++ b/protocols/autonat/src/behaviour/as_client.rs @@ -29,7 +29,9 @@ use futures_timer::Delay; use instant::Instant; use libp2p_core::{connection::ConnectionId, Multiaddr, PeerId}; use libp2p_request_response::{self as request_response, OutboundFailure, RequestId}; -use libp2p_swarm::{AddressScore, NetworkBehaviourAction, PollParameters}; +use libp2p_swarm::{ + AddressScore, ExternalAddresses, ListenAddresses, NetworkBehaviourAction, PollParameters, +}; use rand::{seq::SliceRandom, thread_rng}; use std::{ collections::{HashMap, VecDeque}, @@ -97,6 +99,9 @@ pub struct AsClient<'a> { pub last_probe: &'a mut Option, pub schedule_probe: &'a mut Delay, + + pub listen_addresses: &'a ListenAddresses, + pub external_addresses: &'a ExternalAddresses, } impl<'a> HandleInnerEvent for AsClient<'a> { @@ -146,6 +151,8 @@ impl<'a> HandleInnerEvent for AsClient<'a> { if let Ok(address) = response.result { // Update observed address score if it is finite. + #[allow(deprecated)] + // TODO: Fix once we report `AddressScore` through `FromSwarm` event. let score = params .external_addresses() .find_map(|r| (r.addr == address).then_some(r.score)) @@ -188,17 +195,17 @@ impl<'a> HandleInnerEvent for AsClient<'a> { } impl<'a> AsClient<'a> { - pub fn poll_auto_probe( - &mut self, - params: &mut impl PollParameters, - cx: &mut Context<'_>, - ) -> Poll { + pub fn poll_auto_probe(&mut self, cx: &mut Context<'_>) -> Poll { match self.schedule_probe.poll_unpin(cx) { Poll::Ready(()) => { self.schedule_probe.reset(self.config.retry_interval); - let mut addresses: Vec<_> = params.external_addresses().map(|r| r.addr).collect(); - addresses.extend(params.listened_addresses()); + let addresses = self + .external_addresses + .iter() + .chain(self.listen_addresses.iter()) + .cloned() + .collect(); let probe_id = self.probe_id.next(); let event = match self.do_probe(probe_id, addresses) { diff --git a/protocols/dcutr/CHANGELOG.md b/protocols/dcutr/CHANGELOG.md index 6c45f4cc9d4..23c9b616541 100644 --- a/protocols/dcutr/CHANGELOG.md +++ b/protocols/dcutr/CHANGELOG.md @@ -5,7 +5,10 @@ - Declare `InboundUpgradeError` and `OutboundUpgradeError` as type aliases instead of renames. This is a workaround for a missing feature in `cargo semver-checks`. See [PR 3213]. +- Require the node's local `PeerId` to be passed into the constructor of `libp2p_dcutr::Behaviour`. See [PR 3153]. + [PR 3213]: https://github.com/libp2p/rust-libp2p/pull/3213 +[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153 # 0.8.0 diff --git a/protocols/dcutr/examples/dcutr.rs b/protocols/dcutr/examples/dcutr.rs index 1d9c3366642..6356ef6647f 100644 --- a/protocols/dcutr/examples/dcutr.rs +++ b/protocols/dcutr/examples/dcutr.rs @@ -157,7 +157,7 @@ fn main() -> Result<(), Box> { "/TODO/0.0.1".to_string(), local_key.public(), )), - dcutr: dcutr::behaviour::Behaviour::new(), + dcutr: dcutr::behaviour::Behaviour::new(local_peer_id), }; let mut swarm = match ThreadPool::new() { diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 78b22c89ac1..15dfe078bfe 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -29,8 +29,8 @@ use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}; use libp2p_swarm::dial_opts::{self, DialOpts}; use libp2p_swarm::{ - ConnectionHandler, ConnectionHandlerUpgrErr, IntoConnectionHandler, NetworkBehaviour, - NetworkBehaviourAction, NotifyHandler, PollParameters, + ConnectionHandler, ConnectionHandlerUpgrErr, ExternalAddresses, IntoConnectionHandler, + NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use std::collections::{HashMap, HashSet, VecDeque}; use std::task::{Context, Poll}; @@ -66,20 +66,25 @@ pub enum UpgradeError { Handler(ConnectionHandlerUpgrErr), } -#[derive(Default)] pub struct Behaviour { /// Queue of actions to return when polled. queued_actions: VecDeque, /// All direct (non-relayed) connections. direct_connections: HashMap>, + + external_addresses: ExternalAddresses, + + local_peer_id: PeerId, } impl Behaviour { - pub fn new() -> Self { + pub fn new(local_peer_id: PeerId) -> Self { Behaviour { queued_actions: Default::default(), direct_connections: Default::default(), + external_addresses: Default::default(), + local_peer_id, } } @@ -308,16 +313,18 @@ impl NetworkBehaviour for Behaviour { fn poll( &mut self, _cx: &mut Context<'_>, - poll_parameters: &mut impl PollParameters, + _: &mut impl PollParameters, ) -> Poll> { if let Some(action) = self.queued_actions.pop_front() { - return Poll::Ready(action.build(poll_parameters)); + return Poll::Ready(action.build(self.local_peer_id, &self.external_addresses)); } Poll::Pending } fn on_swarm_event(&mut self, event: FromSwarm) { + self.external_addresses.on_swarn_event(&event); + match event { FromSwarm::ConnectionEstablished(connection_established) => { self.on_connection_established(connection_established) @@ -364,16 +371,15 @@ impl From> for ActionBuilder { impl ActionBuilder { fn build( self, - poll_parameters: &mut impl PollParameters, + local_peer_id: PeerId, + external_addresses: &ExternalAddresses, ) -> NetworkBehaviourAction { let obs_addrs = || { - poll_parameters - .external_addresses() - .filter(|a| !a.addr.iter().any(|p| p == Protocol::P2pCircuit)) - .map(|a| { - a.addr - .with(Protocol::P2p((*poll_parameters.local_peer_id()).into())) - }) + external_addresses + .iter() + .cloned() + .filter(|a| !a.iter().any(|p| p == Protocol::P2pCircuit)) + .map(|a| a.with(Protocol::P2p(local_peer_id.into()))) .collect() }; diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index 65f5f977388..27885aa574c 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -127,7 +127,7 @@ fn build_client() -> Swarm { transport, Client { relay: behaviour, - dcutr: dcutr::behaviour::Behaviour::new(), + dcutr: dcutr::behaviour::Behaviour::new(local_peer_id), }, local_peer_id, ) diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index f37abfc0da7..beb264da789 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -26,7 +26,8 @@ use libp2p_core::{ use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}; use libp2p_swarm::{ dial_opts::DialOpts, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError, - IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, + ExternalAddresses, IntoConnectionHandler, ListenAddresses, NetworkBehaviour, + NetworkBehaviourAction, NotifyHandler, PollParameters, }; use lru::LruCache; use std::num::NonZeroUsize; @@ -56,6 +57,9 @@ pub struct Behaviour { events: VecDeque>, /// The addresses of all peers that we have discovered. discovered_peers: PeerCache, + + listen_addresses: ListenAddresses, + external_addresses: ExternalAddresses, } /// A `Behaviour` request to be fulfilled, either `Handler` requests for `Behaviour` info @@ -177,6 +181,8 @@ impl Behaviour { requests: Vec::new(), events: VecDeque::new(), discovered_peers, + listen_addresses: Default::default(), + external_addresses: Default::default(), } } @@ -318,7 +324,12 @@ impl NetworkBehaviour for Behaviour { peer_id, handler: NotifyHandler::Any, event: InEvent { - listen_addrs: listen_addrs(params), + listen_addrs: self + .listen_addresses + .iter() + .chain(self.external_addresses.iter()) + .cloned() + .collect(), supported_protocols: supported_protocols(params), protocol: Protocol::Push, }, @@ -330,7 +341,12 @@ impl NetworkBehaviour for Behaviour { peer_id, handler: NotifyHandler::One(connection_id), event: InEvent { - listen_addrs: listen_addrs(params), + listen_addrs: self + .listen_addresses + .iter() + .chain(self.external_addresses.iter()) + .cloned() + .collect(), supported_protocols: supported_protocols(params), protocol: Protocol::Identify(connection_id), }, @@ -344,6 +360,9 @@ impl NetworkBehaviour for Behaviour { } fn on_swarm_event(&mut self, event: FromSwarm) { + self.listen_addresses.on_swarm_event(&event); + self.external_addresses.on_swarn_event(&event); + match event { FromSwarm::ConnectionEstablished(connection_established) => { self.on_connection_established(connection_established) @@ -453,12 +472,6 @@ fn supported_protocols(params: &impl PollParameters) -> Vec { .collect() } -fn listen_addrs(params: &impl PollParameters) -> Vec { - let mut listen_addrs: Vec<_> = params.external_addresses().map(|r| r.addr).collect(); - listen_addrs.extend(params.listened_addresses()); - listen_addrs -} - /// If there is a given peer_id in the multiaddr, make sure it is the same as /// the given peer_id. If there is no peer_id for the peer in the mutiaddr, this returns true. fn multiaddr_matches_peer_id(addr: &Multiaddr, peer_id: &PeerId) -> bool { diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index 643f618567c..42081b22108 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -41,12 +41,12 @@ use fnv::{FnvHashMap, FnvHashSet}; use instant::Instant; use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; use libp2p_swarm::behaviour::{ - AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredListenAddr, - FromSwarm, NewExternalAddr, NewListenAddr, + AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm, }; use libp2p_swarm::{ dial_opts::{self, DialOpts}, - DialError, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, + DialError, ExternalAddresses, ListenAddresses, NetworkBehaviour, NetworkBehaviourAction, + NotifyHandler, PollParameters, }; use log::{debug, info, warn}; use smallvec::SmallVec; @@ -103,12 +103,15 @@ pub struct Kademlia { /// Queued events to return when the behaviour is being polled. queued_events: VecDeque>>, - /// The currently known addresses of the local node. - local_addrs: HashSet, + listen_addresses: ListenAddresses, + + external_addresses: ExternalAddresses, /// See [`KademliaConfig::caching`]. caching: KademliaCaching, + local_peer_id: PeerId, + /// The record storage. store: TStore, } @@ -439,6 +442,7 @@ where protocol_config: config.protocol_config, record_filtering: config.record_filtering, queued_events: VecDeque::with_capacity(config.query_config.replication_factor.get()), + listen_addresses: Default::default(), queries: QueryPool::new(config.query_config), connected_peers: Default::default(), add_provider_job, @@ -446,7 +450,8 @@ where record_ttl: config.record_ttl, provider_record_ttl: config.provider_record_ttl, connection_idle_timeout: config.connection_idle_timeout, - local_addrs: HashSet::new(), + external_addresses: Default::default(), + local_peer_id: id, } } @@ -1034,7 +1039,9 @@ where fn provider_peers(&mut self, key: &record::Key, source: &PeerId) -> Vec { let kbuckets = &mut self.kbuckets; let connected = &mut self.connected_peers; - let local_addrs = &self.local_addrs; + let listen_addresses = &self.listen_addresses; + let external_addresses = &self.external_addresses; + self.store .providers(key) .into_iter() @@ -1055,7 +1062,13 @@ where // done before provider records were stored along with // their addresses. if &node_id == kbuckets.local_key().preimage() { - Some(local_addrs.iter().cloned().collect::>()) + Some( + listen_addresses + .iter() + .chain(external_addresses.iter()) + .cloned() + .collect::>(), + ) } else { let key = kbucket::Key::from(node_id); kbuckets @@ -1226,11 +1239,7 @@ where } /// Handles a finished (i.e. successful) query. - fn query_finished( - &mut self, - q: Query, - params: &mut impl PollParameters, - ) -> Option { + fn query_finished(&mut self, q: Query) -> Option { let query_id = q.id(); log::trace!("Query {:?} finished.", query_id); let result = q.into_result(); @@ -1340,8 +1349,8 @@ where key, phase: AddProviderPhase::GetClosestPeers, } => { - let provider_id = *params.local_peer_id(); - let external_addresses = params.external_addresses().map(|r| r.addr).collect(); + let provider_id = self.local_peer_id; + let external_addresses = self.external_addresses.iter().cloned().collect(); let inner = QueryInner::new(QueryInfo::AddProvider { context, key, @@ -2285,7 +2294,7 @@ where fn poll( &mut self, cx: &mut Context<'_>, - parameters: &mut impl PollParameters, + _: &mut impl PollParameters, ) -> Poll> { let now = Instant::now(); @@ -2352,7 +2361,7 @@ where loop { match self.queries.poll(now) { QueryPoolState::Finished(q) => { - if let Some(event) = self.query_finished(q, parameters) { + if let Some(event) = self.query_finished(q) { return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); } } @@ -2406,6 +2415,9 @@ where } fn on_swarm_event(&mut self, event: FromSwarm) { + self.listen_addresses.on_swarm_event(&event); + self.external_addresses.on_swarn_event(&event); + match event { FromSwarm::ConnectionEstablished(connection_established) => { self.on_connection_established(connection_established) @@ -2415,18 +2427,10 @@ where } FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), - FromSwarm::ExpiredListenAddr(ExpiredListenAddr { addr, .. }) => { - self.local_addrs.remove(addr); - } - FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => { - if self.local_addrs.len() < MAX_LOCAL_EXTERNAL_ADDRS { - self.local_addrs.insert(addr.clone()); - } - } - FromSwarm::NewListenAddr(NewListenAddr { addr, .. }) => { - self.local_addrs.insert(addr.clone()); - } - FromSwarm::ListenFailure(_) + FromSwarm::ExpiredListenAddr(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ListenFailure(_) | FromSwarm::NewListener(_) | FromSwarm::ListenerClosed(_) | FromSwarm::ListenerError(_) @@ -3179,8 +3183,3 @@ pub enum RoutingUpdate { /// peer ID). Failed, } - -/// The maximum number of local external addresses. When reached any -/// further externally reported addresses are ignored. The behaviour always -/// tracks all its listen addresses. -const MAX_LOCAL_EXTERNAL_ADDRS: usize = 20; diff --git a/protocols/mdns/CHANGELOG.md b/protocols/mdns/CHANGELOG.md index c997b9d5d8b..4ebe5674b6c 100644 --- a/protocols/mdns/CHANGELOG.md +++ b/protocols/mdns/CHANGELOG.md @@ -1,7 +1,11 @@ # 0.43.0 [unreleased] +- Require the node's local `PeerId` to be passed into the constructor of `libp2p_mdns::Behaviour`. See [PR 3153]. + - Update to `libp2p-swarm` `v0.42.0`. +[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153 + # 0.42.0 - Update to `libp2p-core` `v0.38.0`. diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index ef9ac50addf..815a23c9bdc 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -30,7 +30,8 @@ use if_watch::IfEvent; use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::behaviour::{ConnectionClosed, FromSwarm}; use libp2p_swarm::{ - dummy, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, + dummy, ConnectionHandler, ListenAddresses, NetworkBehaviour, NetworkBehaviourAction, + PollParameters, }; use smallvec::SmallVec; use std::collections::hash_map::{Entry, HashMap}; @@ -121,6 +122,10 @@ where /// /// `None` if `discovered_nodes` is empty. closest_expiration: Option, + + listen_addresses: ListenAddresses, + + local_peer_id: PeerId, } impl

Behaviour

@@ -128,13 +133,15 @@ where P: Provider, { /// Builds a new `Mdns` behaviour. - pub fn new(config: Config) -> io::Result { + pub fn new(config: Config, local_peer_id: PeerId) -> io::Result { Ok(Self { config, if_watch: P::new_watcher()?, iface_states: Default::default(), discovered_nodes: Default::default(), closest_expiration: Default::default(), + listen_addresses: Default::default(), + local_peer_id, }) } @@ -189,6 +196,8 @@ where } fn on_swarm_event(&mut self, event: FromSwarm) { + self.listen_addresses.on_swarm_event(&event); + match event { FromSwarm::ConnectionClosed(ConnectionClosed { peer_id, @@ -221,7 +230,7 @@ where fn poll( &mut self, cx: &mut Context<'_>, - params: &mut impl PollParameters, + _: &mut impl PollParameters, ) -> Poll> { // Poll ifwatch. while let Poll::Ready(Some(event)) = Pin::new(&mut self.if_watch).poll_next(cx) { @@ -237,7 +246,7 @@ where continue; } if let Entry::Vacant(e) = self.iface_states.entry(addr) { - match InterfaceState::new(addr, self.config.clone()) { + match InterfaceState::new(addr, self.config.clone(), self.local_peer_id) { Ok(iface_state) => { e.insert(iface_state); } @@ -257,7 +266,9 @@ where // Emit discovered event. let mut discovered = SmallVec::<[(PeerId, Multiaddr); 4]>::new(); for iface_state in self.iface_states.values_mut() { - while let Poll::Ready((peer, addr, expiration)) = iface_state.poll(cx, params) { + while let Poll::Ready((peer, addr, expiration)) = + iface_state.poll(cx, &self.listen_addresses) + { if let Some((_, _, cur_expires)) = self .discovered_nodes .iter_mut() diff --git a/protocols/mdns/src/behaviour/iface.rs b/protocols/mdns/src/behaviour/iface.rs index 0985f3cdc82..f07e6564a4c 100644 --- a/protocols/mdns/src/behaviour/iface.rs +++ b/protocols/mdns/src/behaviour/iface.rs @@ -26,7 +26,7 @@ use self::query::MdnsPacket; use crate::behaviour::{socket::AsyncSocket, timer::Builder}; use crate::Config; use libp2p_core::{Multiaddr, PeerId}; -use libp2p_swarm::PollParameters; +use libp2p_swarm::ListenAddresses; use socket2::{Domain, Socket, Type}; use std::{ collections::VecDeque, @@ -66,6 +66,8 @@ pub struct InterfaceState { discovered: VecDeque<(PeerId, Multiaddr, Instant)>, /// TTL ttl: Duration, + + local_peer_id: PeerId, } impl InterfaceState @@ -74,7 +76,7 @@ where T: Builder + futures::Stream, { /// Builds a new [`InterfaceState`]. - pub fn new(addr: IpAddr, config: Config) -> io::Result { + pub fn new(addr: IpAddr, config: Config, local_peer_id: PeerId) -> io::Result { log::info!("creating instance on iface {}", addr); let recv_socket = match addr { IpAddr::V4(addr) => { @@ -134,6 +136,7 @@ where timeout: T::interval_at(Instant::now(), query_interval), multicast_addr, ttl: config.ttl, + local_peer_id, }) } @@ -148,7 +151,7 @@ where pub fn poll( &mut self, cx: &mut Context, - params: &impl PollParameters, + listen_addresses: &ListenAddresses, ) -> Poll<(PeerId, Multiaddr, Instant)> { loop { // 1st priority: Low latency: Create packet ASAP after timeout. @@ -198,8 +201,8 @@ where self.send_buffer.extend(build_query_response( query.query_id(), - *params.local_peer_id(), - params.listened_addresses(), + self.local_peer_id, + listen_addresses.iter(), self.ttl, )); continue; @@ -211,9 +214,8 @@ where self.addr ); - self.discovered.extend( - response.extract_discovered(Instant::now(), *params.local_peer_id()), - ); + self.discovered + .extend(response.extract_discovered(Instant::now(), self.local_peer_id)); continue; } Poll::Ready(Ok(Ok(Some(MdnsPacket::ServiceDiscovery(disc))))) => { diff --git a/protocols/mdns/src/behaviour/iface/dns.rs b/protocols/mdns/src/behaviour/iface/dns.rs index 1f0825727a2..8ea4db49f2d 100644 --- a/protocols/mdns/src/behaviour/iface/dns.rs +++ b/protocols/mdns/src/behaviour/iface/dns.rs @@ -103,10 +103,10 @@ pub fn build_query() -> MdnsPacket { /// Builds the response to an address discovery DNS query. /// /// If there are more than 2^16-1 addresses, ignores the rest. -pub fn build_query_response( +pub fn build_query_response<'a>( id: u16, peer_id: PeerId, - addresses: impl ExactSizeIterator, + addresses: impl ExactSizeIterator, ttl: Duration, ) -> Vec { // Convert the TTL into seconds. @@ -413,7 +413,7 @@ mod tests { let packets = build_query_response( 0xf8f8, my_peer_id, - vec![addr1, addr2].into_iter(), + vec![&addr1, &addr2].into_iter(), Duration::from_secs(60), ); for packet in packets { diff --git a/protocols/mdns/src/behaviour/iface/query.rs b/protocols/mdns/src/behaviour/iface/query.rs index 50b86bd888f..7cf22223c41 100644 --- a/protocols/mdns/src/behaviour/iface/query.rs +++ b/protocols/mdns/src/behaviour/iface/query.rs @@ -335,7 +335,7 @@ mod tests { let packets = build_query_response( 0xf8f8, peer_id, - vec![addr1, addr2].into_iter(), + vec![&addr1, &addr2].into_iter(), Duration::from_secs(60), ); diff --git a/protocols/mdns/tests/use-async-std.rs b/protocols/mdns/tests/use-async-std.rs index 736371a50a4..e12eeb09299 100644 --- a/protocols/mdns/tests/use-async-std.rs +++ b/protocols/mdns/tests/use-async-std.rs @@ -63,7 +63,7 @@ async fn create_swarm(config: Config) -> Result, Box .authenticate(libp2p_noise::NoiseAuthenticated::xx(&id_keys).unwrap()) .multiplex(libp2p_yamux::YamuxConfig::default()) .boxed(); - let behaviour = Behaviour::new(config)?; + let behaviour = Behaviour::new(config, peer_id)?; let mut swarm = Swarm::with_async_std_executor(transport, behaviour, peer_id); swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?; Ok(swarm) diff --git a/protocols/mdns/tests/use-tokio.rs b/protocols/mdns/tests/use-tokio.rs index 1a48e8c7361..77deae55412 100644 --- a/protocols/mdns/tests/use-tokio.rs +++ b/protocols/mdns/tests/use-tokio.rs @@ -59,7 +59,7 @@ async fn create_swarm(config: Config) -> Result, Box .authenticate(libp2p_noise::NoiseAuthenticated::xx(&id_keys).unwrap()) .multiplex(libp2p_yamux::YamuxConfig::default()) .boxed(); - let behaviour = Behaviour::new(config)?; + let behaviour = Behaviour::new(config, peer_id)?; let mut swarm = Swarm::with_tokio_executor(transport, behaviour, peer_id); swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?; Ok(swarm) diff --git a/protocols/relay/src/behaviour.rs b/protocols/relay/src/behaviour.rs index 3a10045ad9f..32150f884a0 100644 --- a/protocols/relay/src/behaviour.rs +++ b/protocols/relay/src/behaviour.rs @@ -32,8 +32,8 @@ use libp2p_core::multiaddr::Protocol; use libp2p_core::PeerId; use libp2p_swarm::behaviour::{ConnectionClosed, FromSwarm}; use libp2p_swarm::{ - ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, - PollParameters, + ConnectionHandlerUpgrErr, ExternalAddresses, NetworkBehaviour, NetworkBehaviourAction, + NotifyHandler, PollParameters, }; use std::collections::{hash_map, HashMap, HashSet, VecDeque}; use std::num::NonZeroU32; @@ -199,6 +199,8 @@ pub struct Behaviour { /// Queue of actions to return when polled. queued_actions: VecDeque, + + external_addresses: ExternalAddresses, } impl Behaviour { @@ -209,6 +211,7 @@ impl Behaviour { reservations: Default::default(), circuits: Default::default(), queued_actions: Default::default(), + external_addresses: Default::default(), } } @@ -261,6 +264,8 @@ impl NetworkBehaviour for Behaviour { } fn on_swarm_event(&mut self, event: FromSwarm) { + self.external_addresses.on_swarn_event(&event); + match event { FromSwarm::ConnectionClosed(connection_closed) => { self.on_connection_closed(connection_closed) @@ -637,10 +642,10 @@ impl NetworkBehaviour for Behaviour { fn poll( &mut self, _cx: &mut Context<'_>, - poll_parameters: &mut impl PollParameters, + _: &mut impl PollParameters, ) -> Poll> { if let Some(action) = self.queued_actions.pop_front() { - return Poll::Ready(action.build(poll_parameters)); + return Poll::Ready(action.build(self.local_peer_id, &self.external_addresses)); } Poll::Pending @@ -758,7 +763,8 @@ impl From> for Action { impl Action { fn build( self, - poll_parameters: &mut impl PollParameters, + local_peer_id: PeerId, + external_addresses: &ExternalAddresses, ) -> NetworkBehaviourAction { match self { Action::Done(action) => action, @@ -771,15 +777,13 @@ impl Action { peer_id, event: Either::Left(handler::In::AcceptReservationReq { inbound_reservation_req, - addrs: poll_parameters - .external_addresses() - .map(|a| a.addr) + addrs: external_addresses + .iter() + .cloned() // Add local peer ID in case it isn't present yet. .filter_map(|a| match a.iter().last()? { Protocol::P2p(_) => Some(a), - _ => Some( - a.with(Protocol::P2p(*poll_parameters.local_peer_id().as_ref())), - ), + _ => Some(a.with(Protocol::P2p(local_peer_id.into()))), }) .collect(), }), diff --git a/protocols/rendezvous/src/client.rs b/protocols/rendezvous/src/client.rs index 173831d95d6..599fc8f508f 100644 --- a/protocols/rendezvous/src/client.rs +++ b/protocols/rendezvous/src/client.rs @@ -34,7 +34,8 @@ use libp2p_core::identity::Keypair; use libp2p_core::{Multiaddr, PeerId, PeerRecord}; use libp2p_swarm::behaviour::FromSwarm; use libp2p_swarm::{ - CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, + CloseConnection, ExternalAddresses, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + PollParameters, }; use std::collections::{HashMap, VecDeque}; use std::iter::FromIterator; @@ -57,6 +58,8 @@ pub struct Behaviour { /// Tracks the expiry of registrations that we have discovered and stored in `discovered_peers` otherwise we have a memory leak. expiring_registrations: FuturesUnordered>, + + external_addresses: ExternalAddresses, } impl Behaviour { @@ -70,6 +73,7 @@ impl Behaviour { expiring_registrations: FuturesUnordered::from_iter(vec![ futures::future::pending().boxed() ]), + external_addresses: Default::default(), } } @@ -215,7 +219,7 @@ impl NetworkBehaviour for Behaviour { fn poll( &mut self, cx: &mut Context<'_>, - poll_params: &mut impl PollParameters, + _: &mut impl PollParameters, ) -> Poll> { if let Some(event) = self.events.pop_front() { return Poll::Ready(event); @@ -224,10 +228,8 @@ impl NetworkBehaviour for Behaviour { if let Some((namespace, rendezvous_node, ttl)) = self.pending_register_requests.pop() { // Update our external addresses based on the Swarm's current knowledge. // It doesn't make sense to register addresses on which we are not reachable, hence this should not be configurable from the outside. - let external_addresses = poll_params - .external_addresses() - .map(|r| r.addr) - .collect::>(); + + let external_addresses = self.external_addresses.iter().cloned().collect::>(); if external_addresses.is_empty() { return Poll::Ready(NetworkBehaviourAction::GenerateEvent( @@ -268,6 +270,8 @@ impl NetworkBehaviour for Behaviour { } fn on_swarm_event(&mut self, event: FromSwarm) { + self.external_addresses.on_swarn_event(&event); + match event { FromSwarm::ConnectionEstablished(_) | FromSwarm::ConnectionClosed(_) diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index e111ea099c0..e6f0a92c8ec 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -1,11 +1,13 @@ # 0.42.0 [unreleased] - Removed deprecated Swarm constructors. For transition notes see [0.41.0](#0.41.0). See [PR 3170]. +- Deprecate functions on `PollParameters` in preparation for `PollParameters` to be removed entirely eventually. See [PR 3153]. - Add `estblished_in` to `SwarmEvent::ConnectionEstablished`. See [PR 3134]. [PR 3170]: https://github.com/libp2p/rust-libp2p/pull/3170 [PR 3134]: https://github.com/libp2p/rust-libp2p/pull/3134 +[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153 # 0.41.1 diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index cbd2a4381c4..141d6c3efbd 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -19,8 +19,13 @@ // DEALINGS IN THE SOFTWARE. mod either; +mod external_addresses; +mod listen_addresses; pub mod toggle; +pub use external_addresses::ExternalAddresses; +pub use listen_addresses::ListenAddresses; + use crate::dial_opts::DialOpts; use crate::handler::{ConnectionHandler, IntoConnectionHandler}; use crate::{AddressRecord, AddressScore, DialError}; @@ -402,12 +407,24 @@ pub trait PollParameters { fn supported_protocols(&self) -> Self::SupportedProtocolsIter; /// Returns the list of the addresses we're listening on. + #[deprecated( + since = "0.42.0", + note = "Use `libp2p_swarm::ListenAddresses` instead." + )] fn listened_addresses(&self) -> Self::ListenedAddressesIter; /// Returns the list of the addresses nodes can use to reach us. + #[deprecated( + since = "0.42.0", + note = "Use `libp2p_swarm::ExternalAddresses` instead." + )] fn external_addresses(&self) -> Self::ExternalAddressesIter; /// Returns the peer id of the local node. + #[deprecated( + since = "0.42.0", + note = "Pass the node's `PeerId` into the behaviour instead." + )] fn local_peer_id(&self) -> &PeerId; } diff --git a/swarm/src/behaviour/external_addresses.rs b/swarm/src/behaviour/external_addresses.rs new file mode 100644 index 00000000000..0ce07962e7e --- /dev/null +++ b/swarm/src/behaviour/external_addresses.rs @@ -0,0 +1,50 @@ +use crate::behaviour::{ExpiredExternalAddr, FromSwarm, NewExternalAddr}; +use crate::IntoConnectionHandler; +use libp2p_core::Multiaddr; +use std::collections::HashSet; + +/// The maximum number of local external addresses. When reached any +/// further externally reported addresses are ignored. The behaviour always +/// tracks all its listen addresses. +const MAX_LOCAL_EXTERNAL_ADDRS: usize = 20; + +/// Utility struct for tracking the external addresses of a [`Swarm`](crate::Swarm). +#[derive(Debug, Clone)] +pub struct ExternalAddresses { + addresses: HashSet, + limit: usize, +} + +impl Default for ExternalAddresses { + fn default() -> Self { + Self { + addresses: Default::default(), + limit: MAX_LOCAL_EXTERNAL_ADDRS, + } + } +} + +impl ExternalAddresses { + /// Returns an [`Iterator`] over all external addresses. + pub fn iter(&self) -> impl ExactSizeIterator { + self.addresses.iter() + } + + /// Feed a [`FromSwarm`] event to this struct. + pub fn on_swarn_event(&mut self, event: &FromSwarm) + where + THandler: IntoConnectionHandler, + { + match event { + FromSwarm::NewExternalAddr(NewExternalAddr { addr, .. }) => { + if self.addresses.len() < self.limit { + self.addresses.insert((*addr).clone()); + } + } + FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr, .. }) => { + self.addresses.insert((*addr).clone()); + } + _ => {} + } + } +} diff --git a/swarm/src/behaviour/listen_addresses.rs b/swarm/src/behaviour/listen_addresses.rs new file mode 100644 index 00000000000..37a7d05d12c --- /dev/null +++ b/swarm/src/behaviour/listen_addresses.rs @@ -0,0 +1,33 @@ +use crate::behaviour::{ExpiredListenAddr, FromSwarm, NewListenAddr}; +use crate::IntoConnectionHandler; +use libp2p_core::Multiaddr; +use std::collections::HashSet; + +/// Utility struct for tracking the addresses a [`Swarm`](crate::Swarm) is listening on. +#[derive(Debug, Default, Clone)] +pub struct ListenAddresses { + addresses: HashSet, +} + +impl ListenAddresses { + /// Returns an [`Iterator`] over all listen addresses. + pub fn iter(&self) -> impl ExactSizeIterator { + self.addresses.iter() + } + + /// Feed a [`FromSwarm`] event to this struct. + pub fn on_swarm_event(&mut self, event: &FromSwarm) + where + THandler: IntoConnectionHandler, + { + match event { + FromSwarm::NewListenAddr(NewListenAddr { addr, .. }) => { + self.addresses.insert((*addr).clone()); + } + FromSwarm::ExpiredListenAddr(ExpiredListenAddr { addr, .. }) => { + self.addresses.insert((*addr).clone()); + } + _ => {} + } + } +} diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 68ac8009884..a2ef648d6e6 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -101,7 +101,8 @@ pub mod derive_prelude { } pub use behaviour::{ - CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, + CloseConnection, ExternalAddresses, ListenAddresses, NetworkBehaviour, NetworkBehaviourAction, + NotifyHandler, PollParameters, }; pub use connection::pool::{ConnectionCounters, ConnectionLimits}; pub use connection::{ From 009aadc71edf11f7a285b3f23847b8fcce8fe5cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 14 Dec 2022 15:09:43 +0000 Subject: [PATCH 16/25] fix typo on client deprecation message. --- protocols/relay/src/v2.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index be5fb4f0b88..24ad31ff6a5 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -46,7 +46,10 @@ pub mod client { )] pub type ClientTransport = crate::client::Transport; - #[deprecated(since = "0.15.0", note = "Use libp2p_relay::Listener instead.")] + #[deprecated( + since = "0.15.0", + note = "Use libp2p_relay::client::transport::Listener instead." + )] pub type RelayListener = crate::client::transport::Listener; #[deprecated( From b4bb9175a43772166fd853c2e1fab46e1d63de4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 14 Dec 2022 15:24:24 +0000 Subject: [PATCH 17/25] Update CHANGELOG.md. --- protocols/relay/CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index 5f9a49a5329..ea11248c29b 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -3,8 +3,8 @@ - Rename types as per [discussion 2174]. `Relay` has been renamed to `Behaviour`. The `Relay`, and `Client` prefixes have been removed from various types like `ClientTransport`. - Users should prefer importing the relay protocol as a module (`use libp2p::relay::v2::relay;`), - and refer to its types via `relay::`. For example: `relay::v2::relay::Behaviour` or `relay::v2::client::Behaviour`. + the `v2` namespace has also been removed, users should prefer importing the relay protocol as a module (`use libp2p::relay;`), + and refer to its types via `relay::`. For example: `relay::Behaviour` or `relay::client::Behaviour`. See [PR 3235]. [PR 3235]: https://github.com/libp2p/rust-libp2p/pull/3235 From 4134363951b565c38149646b0d501949ef5de466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 14 Dec 2022 23:17:37 +0000 Subject: [PATCH 18/25] multiple updates: - rename RelayTransport in client doc to transport - make behaviour mod private re-exporting CircuitId - make client mod private re-exporting pub types. --- protocols/relay/src/lib.rs | 17 ++++++++++++++--- .../relay/src/{client.rs => priv_client.rs} | 2 +- .../src/{client => priv_client}/handler.rs | 2 +- .../src/{client => priv_client}/transport.rs | 2 +- protocols/relay/src/v2.rs | 7 ++----- 5 files changed, 19 insertions(+), 11 deletions(-) rename protocols/relay/src/{client.rs => priv_client.rs} (99%) rename protocols/relay/src/{client => priv_client}/handler.rs (99%) rename protocols/relay/src/{client => priv_client}/transport.rs (99%) diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index b690aedfb54..30f72c34ec7 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -23,9 +23,9 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] -pub mod behaviour; -pub mod client; +mod behaviour; mod copy_future; +mod priv_client; mod protocol; pub mod v2; @@ -34,7 +34,7 @@ mod message_proto { include!(concat!(env!("OUT_DIR"), "/message_v2.pb.rs")); } -pub use behaviour::{Behaviour, Config, Event}; +pub use behaviour::{Behaviour, CircuitId, Config, Event}; pub use protocol::{ inbound_hop::FatalUpgradeError as InboundHopFatalUpgradeError, inbound_stop::FatalUpgradeError as InboundStopFatalUpgradeError, @@ -43,6 +43,17 @@ pub use protocol::{ STOP_PROTOCOL_NAME, }; +// explicitly pub'ed client types. +pub mod client { + pub use crate::priv_client::{Behaviour, Event, RelayedConnection, Transport}; + + pub mod transport { + pub use crate::priv_client::transport::{ + Error, Listener, Reservation, ToListenerMsg, TransportToBehaviourMsg, + }; + } +} + // Check that we can safely cast a `usize` to a `u64`. static_assertions::const_assert! { std::mem::size_of::() <= std::mem::size_of::() diff --git a/protocols/relay/src/client.rs b/protocols/relay/src/priv_client.rs similarity index 99% rename from protocols/relay/src/client.rs rename to protocols/relay/src/priv_client.rs index 956cf9c900b..1f1a9ee8a3f 100644 --- a/protocols/relay/src/client.rs +++ b/protocols/relay/src/priv_client.rs @@ -325,7 +325,7 @@ impl NetworkBehaviour for Behaviour { } None => unreachable!( "`relay::Behaviour` polled after channel from \ - `RelayTransport` has been closed. Unreachable under \ + `Transport` has been closed. Unreachable under \ the assumption that the `client::Behaviour` is never polled after \ `client::Transport` is dropped.", ), diff --git a/protocols/relay/src/client/handler.rs b/protocols/relay/src/priv_client/handler.rs similarity index 99% rename from protocols/relay/src/client/handler.rs rename to protocols/relay/src/priv_client/handler.rs index 1eccfb70a9e..564d48d2db5 100644 --- a/protocols/relay/src/client/handler.rs +++ b/protocols/relay/src/priv_client/handler.rs @@ -18,8 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::client::transport; use crate::message_proto::Status; +use crate::priv_client::transport; use crate::protocol::{self, inbound_stop, outbound_hop}; use either::Either; use futures::channel::{mpsc, oneshot}; diff --git a/protocols/relay/src/client/transport.rs b/protocols/relay/src/priv_client/transport.rs similarity index 99% rename from protocols/relay/src/client/transport.rs rename to protocols/relay/src/priv_client/transport.rs index e69accd298b..84f55afccb9 100644 --- a/protocols/relay/src/client/transport.rs +++ b/protocols/relay/src/priv_client/transport.rs @@ -19,7 +19,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::client::RelayedConnection; +use crate::priv_client::RelayedConnection; use crate::RequestId; use futures::channel::mpsc; use futures::channel::oneshot; diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index 24ad31ff6a5..a8c1d85293c 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -97,11 +97,8 @@ pub mod relay { #[deprecated(since = "0.15.0", note = "Use libp2p_relay::Behaviour instead.")] pub type Relay = crate::Behaviour; - #[deprecated( - since = "0.15.0", - note = "Use libp2p_relay::behaviour::CircuitId instead." - )] - pub type CircuitId = crate::behaviour::CircuitId; + #[deprecated(since = "0.15.0", note = "Use libp2p_relay::CircuitId instead.")] + pub type CircuitId = crate::CircuitId; pub mod rate_limiter { use instant::Instant; From 9eb0e2151bf4d6c327d09b97498e812c1d229cb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 15 Dec 2022 11:24:10 +0000 Subject: [PATCH 19/25] deprecate client::Behaviour::new_transport_and_behaviour, use client::new instead. Update client module doc. --- protocols/dcutr/examples/dcutr.rs | 2 +- protocols/dcutr/tests/lib.rs | 3 +-- protocols/relay/src/lib.rs | 4 ++-- protocols/relay/src/priv_client.rs | 22 ++++++++++++++-------- protocols/relay/tests/lib.rs | 3 +-- 5 files changed, 19 insertions(+), 15 deletions(-) diff --git a/protocols/dcutr/examples/dcutr.rs b/protocols/dcutr/examples/dcutr.rs index f302c07806b..553dffc4864 100644 --- a/protocols/dcutr/examples/dcutr.rs +++ b/protocols/dcutr/examples/dcutr.rs @@ -87,7 +87,7 @@ fn main() -> Result<(), Box> { let local_peer_id = PeerId::from(local_key.public()); info!("Local peer id: {:?}", local_peer_id); - let (relay_transport, client) = client::Behaviour::new_transport_and_behaviour(local_peer_id); + let (relay_transport, client) = client::new(local_peer_id); let transport = OrTransport::new( relay_transport, diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index af900f36b0e..770593f13d3 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -116,8 +116,7 @@ fn build_client() -> Swarm { let local_public_key = local_key.public(); let local_peer_id = local_public_key.to_peer_id(); - let (relay_transport, behaviour) = - client::Behaviour::new_transport_and_behaviour(local_peer_id); + let (relay_transport, behaviour) = client::new(local_peer_id); let transport = build_transport( OrTransport::new(relay_transport, MemoryTransport::default()).boxed(), local_public_key, diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index 30f72c34ec7..de9f50a8697 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -43,9 +43,9 @@ pub use protocol::{ STOP_PROTOCOL_NAME, }; -// explicitly pub'ed client types. +/// Everything related to the relay protocol from a client's perspective. pub mod client { - pub use crate::priv_client::{Behaviour, Event, RelayedConnection, Transport}; + pub use crate::priv_client::{new, Behaviour, Event, RelayedConnection, Transport}; pub mod transport { pub use crate::priv_client::transport::{ diff --git a/protocols/relay/src/priv_client.rs b/protocols/relay/src/priv_client.rs index 1f1a9ee8a3f..fbb4c7f3c3e 100644 --- a/protocols/relay/src/priv_client.rs +++ b/protocols/relay/src/priv_client.rs @@ -104,16 +104,22 @@ pub struct Behaviour { queued_actions: VecDeque, } +/// Create a new client relay [`Behaviour`] with it's corresponding [`Transport`]. +pub fn new(local_peer_id: PeerId) -> (transport::Transport, Behaviour) { + let (transport, from_transport) = transport::Transport::new(); + let behaviour = Behaviour { + local_peer_id, + from_transport, + directly_connected_peers: Default::default(), + queued_actions: Default::default(), + }; + (transport, behaviour) +} + impl Behaviour { + #[deprecated(since = "0.15.0", note = "Use libp2p_relay::client::new instead.")] pub fn new_transport_and_behaviour(local_peer_id: PeerId) -> (transport::Transport, Self) { - let (transport, from_transport) = transport::Transport::new(); - let behaviour = Behaviour { - local_peer_id, - from_transport, - directly_connected_peers: Default::default(), - queued_actions: Default::default(), - }; - (transport, behaviour) + new(local_peer_id) } fn on_connection_closed( diff --git a/protocols/relay/tests/lib.rs b/protocols/relay/tests/lib.rs index 2b1b6843aed..df73bb8d524 100644 --- a/protocols/relay/tests/lib.rs +++ b/protocols/relay/tests/lib.rs @@ -312,8 +312,7 @@ fn build_client() -> Swarm { let local_public_key = local_key.public(); let local_peer_id = local_public_key.to_peer_id(); - let (relay_transport, behaviour) = - client::Behaviour::new_transport_and_behaviour(local_peer_id); + let (relay_transport, behaviour) = client::new(local_peer_id); let transport = upgrade_transport( OrTransport::new(relay_transport, MemoryTransport::default()).boxed(), local_public_key, From 238c779f92e6bd98835dd5d8e6b83a185f437c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 15 Dec 2022 11:25:47 +0000 Subject: [PATCH 20/25] move UpgradeErrors to inbound or outbound modules. --- protocols/relay/src/lib.rs | 28 +++++++++++++++++++++------- protocols/relay/src/v2.rs | 16 ++++++++-------- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index de9f50a8697..9f68c998f74 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -35,13 +35,27 @@ mod message_proto { } pub use behaviour::{Behaviour, CircuitId, Config, Event}; -pub use protocol::{ - inbound_hop::FatalUpgradeError as InboundHopFatalUpgradeError, - inbound_stop::FatalUpgradeError as InboundStopFatalUpgradeError, - outbound_hop::FatalUpgradeError as OutboundHopFatalUpgradeError, - outbound_stop::FatalUpgradeError as OutboundStopFatalUpgradeError, HOP_PROTOCOL_NAME, - STOP_PROTOCOL_NAME, -}; +pub use protocol::{HOP_PROTOCOL_NAME, STOP_PROTOCOL_NAME}; + +/// Types related to the relay protocol inbound. +pub mod inbound { + pub mod hop { + pub use crate::protocol::inbound_hop::FatalUpgradeError; + } + pub mod stop { + pub use crate::protocol::inbound_stop::FatalUpgradeError; + } +} + +/// Types related to the relay protocol outbound. +pub mod outbound { + pub mod hop { + pub use crate::protocol::outbound_hop::FatalUpgradeError; + } + pub mod stop { + pub use crate::protocol::outbound_stop::FatalUpgradeError; + } +} /// Everything related to the relay protocol from a client's perspective. pub mod client { diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index a8c1d85293c..8abb39da6b2 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -127,27 +127,27 @@ pub mod relay { pub mod protocol { #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::InboundHopFatalUpgradeError instead." + note = "Use libp2p_relay::inbound::hop::FatalUpgradeError instead." )] - pub type InboundHopFatalUpgradeError = crate::protocol::inbound_hop::FatalUpgradeError; + pub type InboundHopFatalUpgradeError = crate::inbound::hop::FatalUpgradeError; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::InboundStopFatalUpgradeError instead." + note = "Use libp2p_relay::inbound::stop::FatalUpgradeError instead." )] - pub type InboundStopFatalUpgradeError = crate::protocol::inbound_stop::FatalUpgradeError; + pub type InboundStopFatalUpgradeError = crate::inbound::stop::FatalUpgradeError; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::OutboundHopFatalUpgradeError instead." + note = "Use libp2p_relay::outbound::hop::FatalUpgradeError instead." )] - pub type OutboundHopFatalUpgradeError = crate::protocol::outbound_hop::FatalUpgradeError; + pub type OutboundHopFatalUpgradeError = crate::outbound::hop::FatalUpgradeError; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::OutboundStopFatalUpgradeError instead." + note = "Use libp2p_relay::outbound::stop::FatalUpgradeError instead." )] - pub type OutboundStopFatalUpgradeError = crate::protocol::outbound_stop::FatalUpgradeError; + pub type OutboundStopFatalUpgradeError = crate::outbound::stop::FatalUpgradeError; #[deprecated( since = "0.15.0", From 43ea4a8fde7947ebc2fcf4976d583e8736a3b891 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 15 Dec 2022 23:44:09 +0000 Subject: [PATCH 21/25] make client::Transport types private. --- protocols/relay/src/lib.rs | 6 ------ protocols/relay/src/v2.rs | 33 +++++++++++++++++++-------------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index 9f68c998f74..8db1ca2f59e 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -60,12 +60,6 @@ pub mod outbound { /// Everything related to the relay protocol from a client's perspective. pub mod client { pub use crate::priv_client::{new, Behaviour, Event, RelayedConnection, Transport}; - - pub mod transport { - pub use crate::priv_client::transport::{ - Error, Listener, Reservation, ToListenerMsg, TransportToBehaviourMsg, - }; - } } // Check that we can safely cast a `usize` to a `u64`. diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index 8abb39da6b2..3c6306d8aaa 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -42,48 +42,53 @@ pub mod client { #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::client::Transport instead." + note = "ClientTransport has been renamed to Transport + and is now private as it shouldn't be required by end users." )] - pub type ClientTransport = crate::client::Transport; + pub type ClientTransport = crate::priv_client::transport::Transport; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::client::transport::Listener instead." + note = "RelayListener has been renamed to Listener + and is now private as it shouldn't be required by end users." )] - pub type RelayListener = crate::client::transport::Listener; + pub type RelayListener = crate::priv_client::transport::Listener; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::transport::RelayedDial instead." + note = "RelayedDial is now private as it shouldn't be required by end users." )] pub type RelayedDial = BoxFuture< 'static, - Result, + Result, >; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::client::transport::Error instead." + note = "RelayError has been renamed to Error + and is now private as it shouldn't be required by end users." )] - pub type RelayError = crate::client::transport::Error; + pub type RelayError = crate::priv_client::transport::Error; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::client::transport::TransportToBehaviourMsg instead." + note = "TransportToBehaviourMsg is now private + as it shouldn't be required by end users." )] - pub type TransportToBehaviourMsg = crate::client::transport::TransportToBehaviourMsg; + pub type TransportToBehaviourMsg = crate::priv_client::transport::TransportToBehaviourMsg; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::client::transport::ToListenerMsg instead." + note = "ToListenerMsg is now private + as it shouldn't be required by end users." )] - pub type ToListenerMsg = crate::client::transport::ToListenerMsg; + pub type ToListenerMsg = crate::priv_client::transport::ToListenerMsg; #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::client::transport::Reservation instead." + note = "Reservation is now private as it shouldn't be required by end users." )] - pub type Reservation = crate::client::transport::Reservation; + pub type Reservation = crate::priv_client::transport::Reservation; } } From 64e6dd95423e01a19ec401bc080b0253f1834adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 16 Dec 2022 15:08:58 +0000 Subject: [PATCH 22/25] review: apply multiple suggestions: - dcutr tests use relay::client instead of just client:: - rename RelayedConnection to RelayedConnection - improve deprcated wording for types, remove the renamed references. --- protocols/dcutr/tests/lib.rs | 25 ++++++------- protocols/relay/src/lib.rs | 6 +++- protocols/relay/src/priv_client.rs | 38 ++++++++++---------- protocols/relay/src/priv_client/handler.rs | 8 ++--- protocols/relay/src/priv_client/transport.rs | 10 +++--- protocols/relay/src/v2.rs | 28 +++++++-------- 6 files changed, 60 insertions(+), 55 deletions(-) diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index 770593f13d3..15f37bdb6a3 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -32,7 +32,6 @@ use libp2p_core::{identity, PeerId}; use libp2p_dcutr as dcutr; use libp2p_plaintext::PlainText2Config; use libp2p_relay as relay; -use libp2p_relay::client; use libp2p_swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmEvent}; use std::time::Duration; @@ -116,7 +115,7 @@ fn build_client() -> Swarm { let local_public_key = local_key.public(); let local_peer_id = local_public_key.to_peer_id(); - let (relay_transport, behaviour) = client::new(local_peer_id); + let (relay_transport, behaviour) = relay::client::new(local_peer_id); let transport = build_transport( OrTransport::new(relay_transport, MemoryTransport::default()).boxed(), local_public_key, @@ -153,18 +152,18 @@ where prelude = "libp2p_swarm::derive_prelude" )] struct Client { - relay: client::Behaviour, + relay: relay::client::Behaviour, dcutr: dcutr::behaviour::Behaviour, } #[derive(Debug)] enum ClientEvent { - Relay(client::Event), + Relay(relay::client::Event), Dcutr(dcutr::behaviour::Event), } -impl From for ClientEvent { - fn from(event: client::Event) -> Self { +impl From for ClientEvent { + fn from(event: relay::client::Event) -> Self { ClientEvent::Relay(event) } } @@ -198,11 +197,13 @@ async fn wait_for_reservation( break; } } - SwarmEvent::Behaviour(ClientEvent::Relay(client::Event::ReservationReqAccepted { - relay_peer_id: peer_id, - renewal, - .. - })) if relay_peer_id == peer_id && renewal == is_renewal => { + SwarmEvent::Behaviour(ClientEvent::Relay( + relay::client::Event::ReservationReqAccepted { + relay_peer_id: peer_id, + renewal, + .. + }, + )) if relay_peer_id == peer_id && renewal == is_renewal => { reservation_req_accepted = true; if new_listen_addr_for_relayed_addr { break; @@ -226,7 +227,7 @@ async fn wait_for_connection_established(client: &mut Swarm, addr: &Mult } SwarmEvent::Dialing(_) => {} SwarmEvent::Behaviour(ClientEvent::Relay( - client::Event::OutboundCircuitEstablished { .. }, + relay::client::Event::OutboundCircuitEstablished { .. }, )) => {} SwarmEvent::ConnectionEstablished { .. } => {} e => panic!("{e:?}"), diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index 8db1ca2f59e..2b81940919e 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -59,7 +59,11 @@ pub mod outbound { /// Everything related to the relay protocol from a client's perspective. pub mod client { - pub use crate::priv_client::{new, Behaviour, Event, RelayedConnection, Transport}; + pub use crate::priv_client::{new, Behaviour, Connection, Event, Transport}; + + pub mod transport { + pub use crate::priv_client::transport::Error; + } } // Check that we can safely cast a `usize` to a `u64`. diff --git a/protocols/relay/src/priv_client.rs b/protocols/relay/src/priv_client.rs index fbb4c7f3c3e..70808bdc8dd 100644 --- a/protocols/relay/src/priv_client.rs +++ b/protocols/relay/src/priv_client.rs @@ -342,9 +342,9 @@ impl NetworkBehaviour for Behaviour { } /// A [`NegotiatedSubstream`] acting as a [`RelayedConnection`]. -pub enum RelayedConnection { +pub enum Connection { InboundAccepting { - accept: BoxFuture<'static, Result>, + accept: BoxFuture<'static, Result>, }, Operational { read_buffer: Bytes, @@ -353,20 +353,20 @@ pub enum RelayedConnection { }, } -impl Unpin for RelayedConnection {} +impl Unpin for Connection {} -impl RelayedConnection { +impl Connection { pub(crate) fn new_inbound( circuit: inbound_stop::Circuit, drop_notifier: oneshot::Sender, ) -> Self { - RelayedConnection::InboundAccepting { + Connection::InboundAccepting { accept: async { let (substream, read_buffer) = circuit .accept() .await .map_err(|e| Error::new(ErrorKind::Other, e))?; - Ok(RelayedConnection::Operational { + Ok(Connection::Operational { read_buffer, substream, drop_notifier, @@ -381,7 +381,7 @@ impl RelayedConnection { read_buffer: Bytes, drop_notifier: oneshot::Sender, ) -> Self { - RelayedConnection::Operational { + Connection::Operational { substream, read_buffer, drop_notifier, @@ -389,7 +389,7 @@ impl RelayedConnection { } } -impl AsyncWrite for RelayedConnection { +impl AsyncWrite for Connection { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context, @@ -397,10 +397,10 @@ impl AsyncWrite for RelayedConnection { ) -> Poll> { loop { match self.deref_mut() { - RelayedConnection::InboundAccepting { accept } => { + Connection::InboundAccepting { accept } => { *self = ready!(accept.poll_unpin(cx))?; } - RelayedConnection::Operational { substream, .. } => { + Connection::Operational { substream, .. } => { return Pin::new(substream).poll_write(cx, buf); } } @@ -409,10 +409,10 @@ impl AsyncWrite for RelayedConnection { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { loop { match self.deref_mut() { - RelayedConnection::InboundAccepting { accept } => { + Connection::InboundAccepting { accept } => { *self = ready!(accept.poll_unpin(cx))?; } - RelayedConnection::Operational { substream, .. } => { + Connection::Operational { substream, .. } => { return Pin::new(substream).poll_flush(cx); } } @@ -421,10 +421,10 @@ impl AsyncWrite for RelayedConnection { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { loop { match self.deref_mut() { - RelayedConnection::InboundAccepting { accept } => { + Connection::InboundAccepting { accept } => { *self = ready!(accept.poll_unpin(cx))?; } - RelayedConnection::Operational { substream, .. } => { + Connection::Operational { substream, .. } => { return Pin::new(substream).poll_close(cx); } } @@ -438,10 +438,10 @@ impl AsyncWrite for RelayedConnection { ) -> Poll> { loop { match self.deref_mut() { - RelayedConnection::InboundAccepting { accept } => { + Connection::InboundAccepting { accept } => { *self = ready!(accept.poll_unpin(cx))?; } - RelayedConnection::Operational { substream, .. } => { + Connection::Operational { substream, .. } => { return Pin::new(substream).poll_write_vectored(cx, bufs); } } @@ -449,7 +449,7 @@ impl AsyncWrite for RelayedConnection { } } -impl AsyncRead for RelayedConnection { +impl AsyncRead for Connection { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, @@ -457,10 +457,10 @@ impl AsyncRead for RelayedConnection { ) -> Poll> { loop { match self.deref_mut() { - RelayedConnection::InboundAccepting { accept } => { + Connection::InboundAccepting { accept } => { *self = ready!(accept.poll_unpin(cx))?; } - RelayedConnection::Operational { + Connection::Operational { read_buffer, substream, .. diff --git a/protocols/relay/src/priv_client/handler.rs b/protocols/relay/src/priv_client/handler.rs index 564d48d2db5..ca95852696a 100644 --- a/protocols/relay/src/priv_client/handler.rs +++ b/protocols/relay/src/priv_client/handler.rs @@ -56,7 +56,7 @@ pub enum In { }, EstablishCircuit { dst_peer_id: PeerId, - send_back: oneshot::Sender>, + send_back: oneshot::Sender>, }, } @@ -231,7 +231,7 @@ impl Handler { let (tx, rx) = oneshot::channel(); self.alive_lend_out_substreams.push(rx); - let connection = super::RelayedConnection::new_inbound(inbound_circuit, tx); + let connection = super::Connection::new_inbound(inbound_circuit, tx); pending_msgs.push_back(transport::ToListenerMsg::IncomingRelayedConnection { stream: connection, @@ -316,7 +316,7 @@ impl Handler { OutboundOpenInfo::Connect { send_back }, ) => { let (tx, rx) = oneshot::channel(); - match send_back.send(Ok(super::RelayedConnection::new_outbound( + match send_back.send(Ok(super::Connection::new_outbound( substream, read_buffer, tx, @@ -795,6 +795,6 @@ pub enum OutboundOpenInfo { to_listener: mpsc::Sender, }, Connect { - send_back: oneshot::Sender>, + send_back: oneshot::Sender>, }, } diff --git a/protocols/relay/src/priv_client/transport.rs b/protocols/relay/src/priv_client/transport.rs index 84f55afccb9..35200bc3142 100644 --- a/protocols/relay/src/priv_client/transport.rs +++ b/protocols/relay/src/priv_client/transport.rs @@ -19,7 +19,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::priv_client::RelayedConnection; +use crate::priv_client::Connection; use crate::RequestId; use futures::channel::mpsc; use futures::channel::oneshot; @@ -124,7 +124,7 @@ impl Transport { } impl libp2p_core::Transport for Transport { - type Output = RelayedConnection; + type Output = Connection; type Error = Error; type ListenerUpgrade = Ready>; type Dial = RelayedDial; @@ -402,7 +402,7 @@ impl Stream for Listener { } } -pub type RelayedDial = BoxFuture<'static, Result>; +pub type RelayedDial = BoxFuture<'static, Result>; /// Error that occurred during relay connection setup. #[derive(Debug, Error)] @@ -447,7 +447,7 @@ pub enum TransportToBehaviourMsg { relay_peer_id: PeerId, dst_addr: Option, dst_peer_id: PeerId, - send_back: oneshot::Sender>, + send_back: oneshot::Sender>, }, /// Listen for incoming relayed connections via relay node. ListenReq { @@ -461,7 +461,7 @@ pub enum TransportToBehaviourMsg { pub enum ToListenerMsg { Reservation(Result), IncomingRelayedConnection { - stream: RelayedConnection, + stream: Connection, src_peer_id: PeerId, relay_peer_id: PeerId, relay_addr: Multiaddr, diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index 3c6306d8aaa..fe2488d4c4b 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -35,58 +35,58 @@ pub mod client { since = "0.15.0", note = "Use libp2p_relay::client::RelayedConnection instead." )] - pub type RelayedConnection = crate::client::RelayedConnection; + pub type RelayedConnection = crate::client::Connection; pub mod transport { use futures::future::BoxFuture; #[deprecated( since = "0.15.0", - note = "ClientTransport has been renamed to Transport - and is now private as it shouldn't be required by end users." + note = "Use libp2p_relay::client::Transport instead." )] - pub type ClientTransport = crate::priv_client::transport::Transport; + pub type ClientTransport = crate::client::Transport; #[deprecated( since = "0.15.0", - note = "RelayListener has been renamed to Listener - and is now private as it shouldn't be required by end users." + note = "RelayListener will become crate-private in the future + as it shouldn't be required by end users." )] pub type RelayListener = crate::priv_client::transport::Listener; #[deprecated( since = "0.15.0", - note = "RelayedDial is now private as it shouldn't be required by end users." + note = "RelayedDial type alias will be deprecated, + users should create the alias themselves if needed." )] pub type RelayedDial = BoxFuture< 'static, - Result, + Result, >; #[deprecated( since = "0.15.0", - note = "RelayError has been renamed to Error - and is now private as it shouldn't be required by end users." + note = "Use libp2p_relay::client::transport::Error instead." )] - pub type RelayError = crate::priv_client::transport::Error; + pub type RelayError = crate::client::transport::Error; #[deprecated( since = "0.15.0", - note = "TransportToBehaviourMsg is now private + note = "TransportToBehaviourMsg will become crate-private in the future as it shouldn't be required by end users." )] pub type TransportToBehaviourMsg = crate::priv_client::transport::TransportToBehaviourMsg; #[deprecated( since = "0.15.0", - note = "ToListenerMsg is now private + note = "ToListenerMsg will become crate-private in the future as it shouldn't be required by end users." )] pub type ToListenerMsg = crate::priv_client::transport::ToListenerMsg; #[deprecated( since = "0.15.0", - note = "Reservation is now private as it shouldn't be required by end users." + note = "Reservation will become crate-private in the future + as it shouldn't be required by end users." )] pub type Reservation = crate::priv_client::transport::Reservation; } From bc66c5bcdc404402f187f8e72fdb1f05fed4c655 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 17 Dec 2022 18:11:32 +0000 Subject: [PATCH 23/25] review: address left deprecation messages, rename RelayedDial to Dial. --- protocols/relay/src/priv_client.rs | 2 +- protocols/relay/src/priv_client/handler.rs | 2 +- protocols/relay/src/priv_client/transport.rs | 4 ++-- protocols/relay/src/v2.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/protocols/relay/src/priv_client.rs b/protocols/relay/src/priv_client.rs index 70808bdc8dd..69f33bd6e20 100644 --- a/protocols/relay/src/priv_client.rs +++ b/protocols/relay/src/priv_client.rs @@ -341,7 +341,7 @@ impl NetworkBehaviour for Behaviour { } } -/// A [`NegotiatedSubstream`] acting as a [`RelayedConnection`]. +/// A [`NegotiatedSubstream`] acting as a [`Connection`]. pub enum Connection { InboundAccepting { accept: BoxFuture<'static, Result>, diff --git a/protocols/relay/src/priv_client/handler.rs b/protocols/relay/src/priv_client/handler.rs index ca95852696a..c9f7c18adbb 100644 --- a/protocols/relay/src/priv_client/handler.rs +++ b/protocols/relay/src/priv_client/handler.rs @@ -328,7 +328,7 @@ impl Handler { )); } Err(_) => debug!( - "Oneshot to `RelayedDial` future dropped. \ + "Oneshot to `client::transport::Dial` future dropped. \ Dropping established relayed connection to {:?}.", self.remote_peer_id, ), diff --git a/protocols/relay/src/priv_client/transport.rs b/protocols/relay/src/priv_client/transport.rs index 35200bc3142..ea344423c4c 100644 --- a/protocols/relay/src/priv_client/transport.rs +++ b/protocols/relay/src/priv_client/transport.rs @@ -127,7 +127,7 @@ impl libp2p_core::Transport for Transport { type Output = Connection; type Error = Error; type ListenerUpgrade = Ready>; - type Dial = RelayedDial; + type Dial = Dial; fn listen_on(&mut self, addr: Multiaddr) -> Result> { let (relay_peer_id, relay_addr) = match parse_relayed_multiaddr(addr)? { @@ -402,7 +402,7 @@ impl Stream for Listener { } } -pub type RelayedDial = BoxFuture<'static, Result>; +pub type Dial = BoxFuture<'static, Result>; /// Error that occurred during relay connection setup. #[derive(Debug, Error)] diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index fe2488d4c4b..8491e455f79 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -33,7 +33,7 @@ pub mod client { #[deprecated( since = "0.15.0", - note = "Use libp2p_relay::client::RelayedConnection instead." + note = "Use libp2p_relay::client::Connection instead." )] pub type RelayedConnection = crate::client::Connection; From e3a8f0a66a889cb6730e7bb8d0117487bb0d8b09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 21 Dec 2022 13:08:05 +0000 Subject: [PATCH 24/25] adress Thomas multiple review suggestions. --- protocols/dcutr/examples/dcutr.rs | 18 ++++++------- protocols/relay/CHANGELOG.md | 4 +-- protocols/relay/src/lib.rs | 2 +- protocols/relay/src/priv_client.rs | 9 +++---- protocols/relay/src/priv_client/transport.rs | 27 +++----------------- protocols/relay/tests/lib.rs | 27 ++++++++++---------- 6 files changed, 33 insertions(+), 54 deletions(-) diff --git a/protocols/dcutr/examples/dcutr.rs b/protocols/dcutr/examples/dcutr.rs index c574b0e9469..63a55c0dc2f 100644 --- a/protocols/dcutr/examples/dcutr.rs +++ b/protocols/dcutr/examples/dcutr.rs @@ -32,7 +32,7 @@ use libp2p_dns::DnsConfig; use libp2p_identify as identify; use libp2p_noise as noise; use libp2p_ping as ping; -use libp2p_relay::client; +use libp2p_relay as relay; use libp2p_swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent}; use libp2p_tcp as tcp; use log::info; @@ -87,7 +87,7 @@ fn main() -> Result<(), Box> { let local_peer_id = PeerId::from(local_key.public()); info!("Local peer id: {:?}", local_peer_id); - let (relay_transport, client) = client::new(local_peer_id); + let (relay_transport, client) = relay::client::new(local_peer_id); let transport = OrTransport::new( relay_transport, @@ -111,7 +111,7 @@ fn main() -> Result<(), Box> { prelude = "libp2p_swarm::derive_prelude" )] struct Behaviour { - relay_client: client::Behaviour, + relay_client: relay::client::Behaviour, ping: ping::Behaviour, identify: identify::Behaviour, dcutr: dcutr::Behaviour, @@ -122,7 +122,7 @@ fn main() -> Result<(), Box> { enum Event { Ping(ping::Event), Identify(identify::Event), - Relay(client::Event), + Relay(relay::client::Event), Dcutr(dcutr::Event), } @@ -138,8 +138,8 @@ fn main() -> Result<(), Box> { } } - impl From for Event { - fn from(e: client::Event) -> Self { + impl From for Event { + fn from(e: relay::client::Event) -> Self { Event::Relay(e) } } @@ -252,9 +252,9 @@ fn main() -> Result<(), Box> { SwarmEvent::NewListenAddr { address, .. } => { info!("Listening on {:?}", address); } - SwarmEvent::Behaviour(Event::Relay(client::Event::ReservationReqAccepted { - .. - })) => { + SwarmEvent::Behaviour(Event::Relay( + relay::client::Event::ReservationReqAccepted { .. }, + )) => { assert!(opts.mode == Mode::Listen); info!("Relay accepted our reservation request."); } diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index 4482b1f198c..082f829657e 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -5,13 +5,13 @@ The `Relay`, and `Client` prefixes have been removed from various types like `ClientTransport`. the `v2` namespace has also been removed, users should prefer importing the relay protocol as a module (`use libp2p::relay;`), and refer to its types via `relay::`. For example: `relay::Behaviour` or `relay::client::Behaviour`. - See [PR 3235]. + See [PR 3238]. - Update to `libp2p-core` `v0.39.0`. - Update to `libp2p-swarm` `v0.42.0`. -[PR 3235]: https://github.com/libp2p/rust-libp2p/pull/3235 +[PR 3238]: https://github.com/libp2p/rust-libp2p/pull/3238 [discussion 2174]: https://github.com/libp2p/rust-libp2p/issues/2174 # 0.14.0 diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index 2b81940919e..22f7edd0498 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -59,7 +59,7 @@ pub mod outbound { /// Everything related to the relay protocol from a client's perspective. pub mod client { - pub use crate::priv_client::{new, Behaviour, Connection, Event, Transport}; + pub use crate::priv_client::{new, transport::Transport, Behaviour, Connection, Event}; pub mod transport { pub use crate::priv_client::transport::Error; diff --git a/protocols/relay/src/priv_client.rs b/protocols/relay/src/priv_client.rs index 69f33bd6e20..0469254cfd3 100644 --- a/protocols/relay/src/priv_client.rs +++ b/protocols/relay/src/priv_client.rs @@ -21,7 +21,7 @@ //! [`NetworkBehaviour`] to act as a circuit relay v2 **client**. mod handler; -pub mod transport; +pub(crate) mod transport; use crate::protocol::{self, inbound_stop, outbound_hop}; use bytes::Bytes; @@ -45,8 +45,7 @@ use std::io::{Error, ErrorKind, IoSlice}; use std::ops::DerefMut; use std::pin::Pin; use std::task::{Context, Poll}; - -pub use transport::Transport; +use transport::Transport; /// The events produced by the client `Behaviour`. #[derive(Debug)] @@ -105,8 +104,8 @@ pub struct Behaviour { } /// Create a new client relay [`Behaviour`] with it's corresponding [`Transport`]. -pub fn new(local_peer_id: PeerId) -> (transport::Transport, Behaviour) { - let (transport, from_transport) = transport::Transport::new(); +pub fn new(local_peer_id: PeerId) -> (Transport, Behaviour) { + let (transport, from_transport) = Transport::new(); let behaviour = Behaviour { local_peer_id, from_transport, diff --git a/protocols/relay/src/priv_client/transport.rs b/protocols/relay/src/priv_client/transport.rs index ea344423c4c..772ad34dfcd 100644 --- a/protocols/relay/src/priv_client/transport.rs +++ b/protocols/relay/src/priv_client/transport.rs @@ -50,9 +50,9 @@ use thiserror::Error; /// # use libp2p_core::{Multiaddr, multiaddr::{Protocol}, Transport, PeerId}; /// # use libp2p_core::transport::memory::MemoryTransport; /// # use libp2p_core::transport::choice::OrTransport; -/// # use libp2p_relay::client; +/// # use libp2p_relay as relay; /// let actual_transport = MemoryTransport::default(); -/// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( +/// let (relay_transport, behaviour) = relay::client::new( /// PeerId::random(), /// ); /// let mut transport = OrTransport::new(relay_transport, actual_transport); @@ -93,25 +93,6 @@ pub struct Transport { } impl Transport { - /// Create a new [`Transport`]. - /// - /// Note: The transport only handles listening and dialing on relayed [`Multiaddr`], and depends on - /// an other transport to do the actual transmission of data. They should be combined through the - /// [`OrTransport`](libp2p_core::transport::choice::OrTransport). - /// - /// ``` - /// # use libp2p_core::{Multiaddr, multiaddr::{Protocol}, Transport, PeerId}; - /// # use libp2p_core::transport::memory::MemoryTransport; - /// # use libp2p_core::transport::choice::OrTransport; - /// # use libp2p_relay::client; - /// let actual_transport = MemoryTransport::default(); - /// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( - /// PeerId::random(), - /// ); - /// - /// // To reduce unnecessary connection attempts, put `relay_transport` first. - /// let mut transport = OrTransport::new(relay_transport, actual_transport); - /// ``` pub(crate) fn new() -> (Self, mpsc::Receiver) { let (to_behaviour, from_transport) = mpsc::channel(0); let transport = Transport { @@ -127,7 +108,7 @@ impl libp2p_core::Transport for Transport { type Output = Connection; type Error = Error; type ListenerUpgrade = Ready>; - type Dial = Dial; + type Dial = BoxFuture<'static, Result>; fn listen_on(&mut self, addr: Multiaddr) -> Result> { let (relay_peer_id, relay_addr) = match parse_relayed_multiaddr(addr)? { @@ -402,8 +383,6 @@ impl Stream for Listener { } } -pub type Dial = BoxFuture<'static, Result>; - /// Error that occurred during relay connection setup. #[derive(Debug, Error)] pub enum Error { diff --git a/protocols/relay/tests/lib.rs b/protocols/relay/tests/lib.rs index df73bb8d524..df5e0b0315e 100644 --- a/protocols/relay/tests/lib.rs +++ b/protocols/relay/tests/lib.rs @@ -32,7 +32,6 @@ use libp2p_core::{identity, upgrade, PeerId}; use libp2p_ping as ping; use libp2p_plaintext::PlainText2Config; use libp2p_relay as relay; -use libp2p_relay::client; use libp2p_swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmEvent}; use std::time::Duration; @@ -141,7 +140,7 @@ fn new_reservation_to_same_relay_replaces_old() { } } SwarmEvent::Behaviour(ClientEvent::Relay( - client::Event::ReservationReqAccepted { + relay::client::Event::ReservationReqAccepted { relay_peer_id: peer_id, .. }, @@ -219,7 +218,7 @@ fn connect() { break } SwarmEvent::Behaviour(ClientEvent::Relay( - client::Event::OutboundCircuitEstablished { .. }, + relay::client::Event::OutboundCircuitEstablished { .. }, )) => {} SwarmEvent::Behaviour(ClientEvent::Ping(ping::Event { peer, .. })) if peer == relay_peer_id => {} @@ -312,7 +311,7 @@ fn build_client() -> Swarm { let local_public_key = local_key.public(); let local_peer_id = local_public_key.to_peer_id(); - let (relay_transport, behaviour) = client::new(local_peer_id); + let (relay_transport, behaviour) = relay::client::new(local_peer_id); let transport = upgrade_transport( OrTransport::new(relay_transport, MemoryTransport::default()).boxed(), local_public_key, @@ -378,18 +377,18 @@ impl From for RelayEvent { prelude = "libp2p_swarm::derive_prelude" )] struct Client { - relay: client::Behaviour, + relay: relay::client::Behaviour, ping: ping::Behaviour, } #[derive(Debug)] enum ClientEvent { - Relay(client::Event), + Relay(relay::client::Event), Ping(ping::Event), } -impl From for ClientEvent { - fn from(event: client::Event) -> Self { +impl From for ClientEvent { + fn from(event: relay::client::Event) -> Self { ClientEvent::Relay(event) } } @@ -417,11 +416,13 @@ async fn wait_for_reservation( loop { match client.select_next_some().await { - SwarmEvent::Behaviour(ClientEvent::Relay(client::Event::ReservationReqAccepted { - relay_peer_id: peer_id, - renewal, - .. - })) if relay_peer_id == peer_id && renewal == is_renewal => { + SwarmEvent::Behaviour(ClientEvent::Relay( + relay::client::Event::ReservationReqAccepted { + relay_peer_id: peer_id, + renewal, + .. + }, + )) if relay_peer_id == peer_id && renewal == is_renewal => { reservation_req_accepted = true; if new_listen_addr { break; From 09512711e7e8bb510364995e6b35a94d25cab0c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 23 Dec 2022 19:27:18 +0000 Subject: [PATCH 25/25] review: apply suggestions. --- protocols/relay/examples/relay.rs | 33 +------------- protocols/relay/src/lib.rs | 2 + protocols/relay/src/priv_client/transport.rs | 4 +- protocols/relay/src/v2.rs | 5 +- protocols/relay/tests/lib.rs | 48 +------------------- 5 files changed, 12 insertions(+), 80 deletions(-) diff --git a/protocols/relay/examples/relay.rs b/protocols/relay/examples/relay.rs index 4b755269e36..5d88f1739df 100644 --- a/protocols/relay/examples/relay.rs +++ b/protocols/relay/examples/relay.rs @@ -79,7 +79,7 @@ fn main() -> Result<(), Box> { block_on(async { loop { match swarm.next().await.expect("Infinite Stream.") { - SwarmEvent::Behaviour(Event::Relay(event)) => { + SwarmEvent::Behaviour(event) => { println!("{event:?}") } SwarmEvent::NewListenAddr { address, .. } => { @@ -92,42 +92,13 @@ fn main() -> Result<(), Box> { } #[derive(NetworkBehaviour)] -#[behaviour( - out_event = "Event", - event_process = false, - prelude = "libp2p_swarm::derive_prelude" -)] +#[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct Behaviour { relay: relay::Behaviour, ping: ping::Behaviour, identify: identify::Behaviour, } -#[derive(Debug)] -enum Event { - Ping(ping::Event), - Identify(identify::Event), - Relay(relay::Event), -} - -impl From for Event { - fn from(e: ping::Event) -> Self { - Event::Ping(e) - } -} - -impl From for Event { - fn from(e: identify::Event) -> Self { - Event::Identify(e) - } -} - -impl From for Event { - fn from(e: relay::Event) -> Self { - Event::Relay(e) - } -} - fn generate_ed25519(secret_key_seed: u8) -> identity::Keypair { let mut bytes = [0u8; 32]; bytes[0] = secret_key_seed; diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index 22f7edd0498..aa5a82043f5 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -72,6 +72,8 @@ static_assertions::const_assert! { } /// The ID of an outgoing / incoming, relay / destination request. +// TODO remove this type and it's usage on `TransportToBehaviourMsg::DialReq` +// when removed from `v2`. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct RequestId(u64); diff --git a/protocols/relay/src/priv_client/transport.rs b/protocols/relay/src/priv_client/transport.rs index 772ad34dfcd..264eb3abcd5 100644 --- a/protocols/relay/src/priv_client/transport.rs +++ b/protocols/relay/src/priv_client/transport.rs @@ -72,11 +72,11 @@ use thiserror::Error; /// # use libp2p_core::{Multiaddr, multiaddr::{Protocol}, Transport, PeerId}; /// # use libp2p_core::transport::memory::MemoryTransport; /// # use libp2p_core::transport::choice::OrTransport; -/// # use libp2p_relay::client; +/// # use libp2p_relay as relay; /// # let relay_id = PeerId::random(); /// # let local_peer_id = PeerId::random(); /// let actual_transport = MemoryTransport::default(); -/// let (relay_transport, behaviour) = client::Behaviour::new_transport_and_behaviour( +/// let (relay_transport, behaviour) = relay::client::new( /// local_peer_id, /// ); /// let mut transport = OrTransport::new(relay_transport, actual_transport); diff --git a/protocols/relay/src/v2.rs b/protocols/relay/src/v2.rs index 8491e455f79..bf428684bbc 100644 --- a/protocols/relay/src/v2.rs +++ b/protocols/relay/src/v2.rs @@ -167,5 +167,8 @@ pub mod protocol { pub const STOP_PROTOCOL_NAME: &[u8; 32] = crate::STOP_PROTOCOL_NAME; } -#[deprecated(since = "0.15.0", note = "Use libp2p_relay::RequestId instead.")] +#[deprecated( + since = "0.15.0", + note = "RequestId will be deprecated as it isn't used" +)] pub type RequestId = super::RequestId; diff --git a/protocols/relay/tests/lib.rs b/protocols/relay/tests/lib.rs index df5e0b0315e..a26d09e6e3b 100644 --- a/protocols/relay/tests/lib.rs +++ b/protocols/relay/tests/lib.rs @@ -342,63 +342,19 @@ where } #[derive(NetworkBehaviour)] -#[behaviour( - out_event = "RelayEvent", - event_process = false, - prelude = "libp2p_swarm::derive_prelude" -)] +#[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct Relay { relay: relay::Behaviour, ping: ping::Behaviour, } -#[derive(Debug)] -enum RelayEvent { - Relay(relay::Event), - Ping(ping::Event), -} - -impl From for RelayEvent { - fn from(event: relay::Event) -> Self { - RelayEvent::Relay(event) - } -} - -impl From for RelayEvent { - fn from(event: ping::Event) -> Self { - RelayEvent::Ping(event) - } -} - #[derive(NetworkBehaviour)] -#[behaviour( - out_event = "ClientEvent", - event_process = false, - prelude = "libp2p_swarm::derive_prelude" -)] +#[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct Client { relay: relay::client::Behaviour, ping: ping::Behaviour, } -#[derive(Debug)] -enum ClientEvent { - Relay(relay::client::Event), - Ping(ping::Event), -} - -impl From for ClientEvent { - fn from(event: relay::client::Event) -> Self { - ClientEvent::Relay(event) - } -} - -impl From for ClientEvent { - fn from(event: ping::Event) -> Self { - ClientEvent::Ping(event) - } -} - fn spawn_swarm_on_pool(pool: &LocalPool, swarm: Swarm) { pool.spawner() .spawn_obj(swarm.collect::>().map(|_| ()).boxed().into())