From 2fd729c8ab854495579e7f5e4bfc531e1dff2240 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Wed, 13 Oct 2021 14:23:53 +0200 Subject: [PATCH 01/27] swarm/: Enable advanced dialing requests Enable advanced dialing requests both on `Swarm` and via `NetworkBehaviourAction`. Users can now trigger a dial with a specific set of addresses, optionally extended via `NetworkBehaviour::addresses_of_peer`. In addition the whole process is now modelled in a type safe way via the builder pattern. Example of a `NetworkBehaviour` requesting a dial to a specific peer with a set of addresses additionally extended through `NetworkBehaviour::addresses_of_peer`: ```rust NetworkBehaviourAction::Dial { opts: DialOpts::peer_id(peer_id) .condition(PeerCondition::Always) .addresses(addresses) .extend_addresses_through_behaviour() .build(), handler, } ``` Example of a user requesting a dial to an unknown peer with a single address via `Swarm`: ```rust swarm1.dial( DialOpts::unknown_peer_id() .address(addr2.clone()) .build() ) ``` --- swarm/src/behaviour.rs | 110 ++---------- swarm/src/lib.rs | 399 +++++++++++++++++++++++++++++++---------- 2 files changed, 319 insertions(+), 190 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index a8217eda066..4541bc27fca 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -18,6 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::dial_opts::DialOpts; use crate::protocols_handler::{IntoProtocolsHandler, ProtocolsHandler}; use crate::{AddressRecord, AddressScore, DialError}; use libp2p_core::{ @@ -269,31 +270,7 @@ pub enum NetworkBehaviourAction< /// Instructs the `Swarm` to return an event when it is being polled. GenerateEvent(TOutEvent), - /// Instructs the swarm to dial the given multiaddress optionally including a [`PeerId`]. - /// - /// On success, [`NetworkBehaviour::inject_connection_established`] is invoked. - /// On failure, [`NetworkBehaviour::inject_dial_failure`] is invoked. - /// - /// Note that the provided handler is returned to the [`NetworkBehaviour`] on connection failure - /// and connection closing. Thus it can be used to carry state, which otherwise would have to be - /// tracked in the [`NetworkBehaviour`] itself. E.g. a message destined to an unconnected peer - /// can be included in the handler, and thus directly send on connection success or extracted by - /// the [`NetworkBehaviour`] on connection failure. See [`NetworkBehaviourAction::DialPeer`] for - /// example. - DialAddress { - /// The address to dial. - address: Multiaddr, - /// The handler to be used to handle the connection to the peer. - handler: THandler, - }, - - /// Instructs the swarm to dial a known `PeerId`. - /// - /// The [`NetworkBehaviour::addresses_of_peer`] method is called to determine which addresses to - /// attempt to reach. - /// - /// If we were already trying to dial this node, the addresses that are not yet in the queue of - /// addresses to try are added back to this queue. + /// Instructs the swarm to start a dial. /// /// On success, [`NetworkBehaviour::inject_connection_established`] is invoked. /// On failure, [`NetworkBehaviour::inject_dial_failure`] is invoked. @@ -316,10 +293,11 @@ pub enum NetworkBehaviourAction< /// # use libp2p::core::PeerId; /// # use libp2p::plaintext::PlainText2Config; /// # use libp2p::swarm::{ - /// # DialError, DialPeerCondition, IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, + /// # DialError, IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, /// # NetworkBehaviour, NetworkBehaviourAction, PollParameters, ProtocolsHandler, /// # ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, Swarm, SwarmEvent, /// # }; + /// # use libp2p::swarm::dial_opts::{DialOpts, PeerCondition}; /// # use libp2p::yamux; /// # use std::collections::VecDeque; /// # use std::task::{Context, Poll}; @@ -362,9 +340,10 @@ pub enum NetworkBehaviourAction< /// # impl MyBehaviour { /// # fn send(&mut self, peer_id: PeerId, msg: PreciousMessage) { /// # self.outbox_to_swarm - /// # .push_back(NetworkBehaviourAction::DialPeer { - /// # peer_id, - /// # condition: DialPeerCondition::Always, + /// # .push_back(NetworkBehaviourAction::Dial { + /// # opts: DialOpts::peer_id(peer_id) + /// # .condition(PeerCondition::Always) + /// # .build(), /// # handler: MyHandler { message: Some(msg) }, /// # }); /// # } @@ -476,14 +455,7 @@ pub enum NetworkBehaviourAction< /// # #[derive(Debug, PartialEq, Eq)] /// # struct PreciousMessage(String); /// ``` - DialPeer { - /// The peer to try reach. - peer_id: PeerId, - /// The condition for initiating a new dialing attempt. - condition: DialPeerCondition, - /// The handler to be used to handle the connection to the peer. - handler: THandler, - }, + Dial { opts: DialOpts, handler: THandler }, /// Instructs the `Swarm` to send an event to the handler dedicated to a /// connection with a peer. @@ -553,18 +525,9 @@ impl ) -> NetworkBehaviourAction { match self { NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e), - NetworkBehaviourAction::DialAddress { address, handler } => { - NetworkBehaviourAction::DialAddress { address, handler } + NetworkBehaviourAction::Dial { opts, handler } => { + NetworkBehaviourAction::Dial { opts, handler } } - NetworkBehaviourAction::DialPeer { - peer_id, - condition, - handler, - } => NetworkBehaviourAction::DialPeer { - peer_id, - condition, - handler, - }, NetworkBehaviourAction::NotifyHandler { peer_id, handler, @@ -593,18 +556,9 @@ impl NetworkBehaviourAction(self, f: impl FnOnce(TOutEvent) -> E) -> NetworkBehaviourAction { match self { NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(f(e)), - NetworkBehaviourAction::DialAddress { address, handler } => { - NetworkBehaviourAction::DialAddress { address, handler } + NetworkBehaviourAction::Dial { opts, handler } => { + NetworkBehaviourAction::Dial { opts, handler } } - NetworkBehaviourAction::DialPeer { - peer_id, - condition, - handler, - } => NetworkBehaviourAction::DialPeer { - peer_id, - condition, - handler, - }, NetworkBehaviourAction::NotifyHandler { peer_id, handler, @@ -644,19 +598,8 @@ where { match self { NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e), - NetworkBehaviourAction::DialAddress { address, handler } => { - NetworkBehaviourAction::DialAddress { - address, - handler: f(handler), - } - } - NetworkBehaviourAction::DialPeer { - peer_id, - condition, - handler, - } => NetworkBehaviourAction::DialPeer { - peer_id, - condition, + NetworkBehaviourAction::Dial { opts, handler } => NetworkBehaviourAction::Dial { + opts, handler: f(handler), }, NetworkBehaviourAction::NotifyHandler { @@ -691,29 +634,6 @@ pub enum NotifyHandler { Any, } -/// The available conditions under which a new dialing attempt to -/// a peer is initiated when requested by [`NetworkBehaviourAction::DialPeer`]. -#[derive(Debug, Copy, Clone)] -pub enum DialPeerCondition { - /// A new dialing attempt is initiated _only if_ the peer is currently - /// considered disconnected, i.e. there is no established connection - /// and no ongoing dialing attempt. - Disconnected, - /// A new dialing attempt is initiated _only if_ there is currently - /// no ongoing dialing attempt, i.e. the peer is either considered - /// disconnected or connected but without an ongoing dialing attempt. - NotDialing, - /// A new dialing attempt is always initiated, only subject to the - /// configured connection limits. - Always, -} - -impl Default for DialPeerCondition { - fn default() -> Self { - DialPeerCondition::Disconnected - } -} - /// The options which connections to close. #[derive(Debug, Clone)] pub enum CloseConnection { diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 4dd894d1094..cbb9e62a39d 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -63,8 +63,8 @@ pub mod protocols_handler; pub mod toggle; pub use behaviour::{ - CloseConnection, DialPeerCondition, NetworkBehaviour, NetworkBehaviourAction, - NetworkBehaviourEventProcess, NotifyHandler, PollParameters, + CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, + NotifyHandler, PollParameters, }; pub use protocols_handler::{ IntoProtocolsHandler, IntoProtocolsHandlerSelect, KeepAlive, OneShotHandler, @@ -73,6 +73,7 @@ pub use protocols_handler::{ }; pub use registry::{AddAddressResult, AddressRecord, AddressScore}; +use dial_opts::DialOpts; use futures::{executor::ThreadPoolBuilder, prelude::*, stream::FusedStream}; use libp2p_core::{ connection::{ @@ -321,72 +322,124 @@ where self.network.remove_listener(id) } - /// Initiates a new dialing attempt to the given address. - pub fn dial_addr(&mut self, addr: Multiaddr) -> Result<(), DialError> { + pub fn dial(&mut self, opts: DialOpts) -> Result<(), DialError> { let handler = self.behaviour.new_handler(); - self.dial_addr_with_handler(addr, handler) - .map_err(DialError::from_network_dial_error) - .map_err(|(e, _)| e) - } - - fn dial_addr_with_handler( - &mut self, - addr: Multiaddr, - handler: ::ProtocolsHandler, - ) -> Result<(), network::DialError>>> { - let handler = handler - .into_node_handler_builder() - .with_substream_upgrade_protocol_override(self.substream_upgrade_protocol_override); - - self.network.dial(&addr, handler).map(|_id| ()) - } - - /// Initiates a new dialing attempt to the given peer. - pub fn dial(&mut self, peer_id: &PeerId) -> Result<(), DialError> { - let handler = self.behaviour.new_handler(); - self.dial_with_handler(peer_id, handler) + self.dial_with_handler(opts, handler) } fn dial_with_handler( &mut self, - peer_id: &PeerId, + opts: DialOpts, handler: ::ProtocolsHandler, ) -> Result<(), DialError> { - if self.banned_peers.contains(peer_id) { - let error = DialError::Banned; - self.behaviour - .inject_dial_failure(Some(*peer_id), handler, &error); - return Err(error); + // TODO: Remove Import + use dial_opts::PeerCondition; + + match opts { + DialOpts::WithPeerId(dial_opts::WithPeerId { peer_id, condition }) + | DialOpts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { + peer_id, + condition, + .. + }) => { + let condition_matched = match condition { + PeerCondition::Disconnected => self.network.is_disconnected(&peer_id), + PeerCondition::NotDialing => !self.network.is_dialing(&peer_id), + PeerCondition::Always => true, + }; + + if !condition_matched { + self.behaviour.inject_dial_failure( + Some(peer_id), + handler, + &DialError::DialPeerConditionFalse(condition), + ); + + return Err(DialError::DialPeerConditionFalse(condition)); + } + } + DialOpts::WithoutPeerIdWithAddress { .. } => {} } - let self_listening = self.listened_addrs.clone(); - let mut addrs = self - .behaviour - .addresses_of_peer(peer_id) - .into_iter() - .filter(move |a| !self_listening.contains(a)) - .peekable(); - - if addrs.peek().is_none() { - let error = DialError::NoAddresses; - self.behaviour - .inject_dial_failure(Some(*peer_id), handler, &error); - return Err(error); - }; + match opts { + DialOpts::WithPeerId(dial_opts::WithPeerId { peer_id, .. }) + | DialOpts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { + peer_id, + .. + }) => { + if self.banned_peers.contains(&peer_id) { + let error = DialError::Banned; + self.behaviour + .inject_dial_failure(Some(peer_id), handler, &error); + return Err(error); + } + + let addresses = match opts { + DialOpts::WithPeerId(dial_opts::WithPeerId { .. }) => { + self.behaviour.addresses_of_peer(&peer_id) + } + DialOpts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { + peer_id, + mut addresses, + extend_addresses_through_behaviour, + .. + }) => { + if extend_addresses_through_behaviour { + addresses.extend(self.behaviour.addresses_of_peer(&peer_id)) + } + addresses + } + DialOpts::WithoutPeerIdWithAddress { .. } => { + unreachable!("Due to outer match.") + } + }; + + if addresses.is_empty() { + let error = DialError::NoAddresses; + self.behaviour + .inject_dial_failure(Some(peer_id), handler, &error); + return Err(error); + }; + + let handler = handler + .into_node_handler_builder() + .with_substream_upgrade_protocol_override( + self.substream_upgrade_protocol_override, + ); - let handler = handler - .into_node_handler_builder() - .with_substream_upgrade_protocol_override(self.substream_upgrade_protocol_override); - match self.network.peer(*peer_id).dial(addrs, handler) { - Ok(_connection_id) => Ok(()), - Err(error) => { - let (error, handler) = DialError::from_network_dial_error(error); - self.behaviour.inject_dial_failure( - Some(*peer_id), - handler.into_protocols_handler(), - &error, - ); - Err(error) + match self.network.peer(peer_id).dial(addresses, handler) { + Ok(_connection_id) => Ok(()), + Err(error) => { + let (error, handler) = DialError::from_network_dial_error(error); + self.behaviour.inject_dial_failure( + Some(peer_id), + handler.into_protocols_handler(), + &error, + ); + return Err(error); + } + } + } + DialOpts::WithoutPeerIdWithAddress(dial_opts::WithoutPeerIdWithAddress { address }) => { + let handler = handler + .into_node_handler_builder() + .with_substream_upgrade_protocol_override( + self.substream_upgrade_protocol_override, + ); + + match self.network.dial(&address, handler).map(|_id| ()) { + Ok(_connection_id) => Ok(()), + Err(error) => { + // TODO: Deduplicate with the above? + let (error, handler) = DialError::from_network_dial_error(error); + self.behaviour.inject_dial_failure( + None, + handler.into_protocols_handler(), + &error, + ); + return Err(error); + } + } } } } @@ -808,37 +861,56 @@ where Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)) => { return Poll::Ready(SwarmEvent::Behaviour(event)) } - Poll::Ready(NetworkBehaviourAction::DialAddress { address, handler }) => { - let _ = Swarm::dial_addr_with_handler(&mut *this, address, handler); - } - Poll::Ready(NetworkBehaviourAction::DialPeer { - peer_id, - condition, - handler, - }) => { - let condition_matched = match condition { - DialPeerCondition::Disconnected => this.network.is_disconnected(&peer_id), - DialPeerCondition::NotDialing => !this.network.is_dialing(&peer_id), - DialPeerCondition::Always => true, - }; - if condition_matched { - if Swarm::dial_with_handler(this, &peer_id, handler).is_ok() { - return Poll::Ready(SwarmEvent::Dialing(peer_id)); - } - } else { - log::trace!( - "Condition for new dialing attempt to {:?} not met: {:?}", - peer_id, - condition - ); - - this.behaviour.inject_dial_failure( - Some(peer_id), - handler, - &DialError::DialPeerConditionFalse(condition), - ); + // Poll::Ready(NetworkBehaviourAction::DialAddress { address, handler }) => { + // let _ = Swarm::dial_addr_with_handler(&mut *this, address, handler); + // } + Poll::Ready(NetworkBehaviourAction::Dial { opts, handler }) => { + if let Ok(()) = this.dial_with_handler(opts, handler) { + // TODO + // return Poll::Ready(SwarmEvent::Dialing(peer_id)); } } + // Poll::Ready(NetworkBehaviourAction::DialPeer { + // peer_id, + // condition, + // handler, + // }) => { + // let condition_matched = match condition { + // DialPeerCondition::Disconnected => this.network.is_disconnected(&peer_id), + // DialPeerCondition::NotDialing => !this.network.is_dialing(&peer_id), + // DialPeerCondition::Always => true, + // }; + // if condition_matched { + // if Swarm::dial_with_handler(this, &peer_id, handler).is_ok() { + // return Poll::Ready(SwarmEvent::Dialing(peer_id)); + // } + // } else { + // // Even if the condition for a _new_ dialing attempt is not met, + // // we always add any potentially new addresses of the peer to an + // // ongoing dialing attempt, if there is one. + // log::trace!( + // "Condition for new dialing attempt to {:?} not met: {:?}", + // peer_id, + // condition + // ); + // let self_listening = &this.listened_addrs; + // if let Some(mut peer) = this.network.peer(peer_id).into_dialing() { + // let addrs = this.behaviour.addresses_of_peer(peer.id()); + // let mut attempt = peer.some_attempt(); + // for a in addrs { + // if !self_listening.contains(&a) { + // attempt.add_address(a); + // } + // } + // } + + // this.behaviour.inject_dial_failure( + // &peer_id, + // handler, + // DialError::DialPeerConditionFalse(condition), + // ); + // } + // } Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, handler, @@ -1215,7 +1287,7 @@ pub enum DialError { /// for the peer to dial. NoAddresses, /// The provided [`DialPeerCondition`] evaluated to false and thus the dial was aborted. - DialPeerConditionFalse(DialPeerCondition), + DialPeerConditionFalse(dial_opts::PeerCondition), /// Pending connection attempt has been aborted. Aborted, /// The peer identity obtained on the connection did not @@ -1457,7 +1529,9 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1.dial_addr(addr2.clone()).unwrap(); + swarm1 + .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) + .unwrap(); } let mut state = State::Connecting; @@ -1489,7 +1563,11 @@ mod tests { swarm2.behaviour.reset(); unbanned = true; for _ in 0..num_connections { - swarm2.dial_addr(addr1.clone()).unwrap(); + swarm2 + .dial( + DialOpts::unknown_peer_id().address(addr1.clone()).build(), + ) + .unwrap(); } state = State::Connecting; } @@ -1532,7 +1610,9 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1.dial_addr(addr2.clone()).unwrap(); + swarm1 + .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) + .unwrap(); } let mut state = State::Connecting; @@ -1562,7 +1642,9 @@ mod tests { swarm1.behaviour.reset(); swarm2.behaviour.reset(); for _ in 0..num_connections { - swarm2.dial_addr(addr1.clone()).unwrap(); + swarm2 + .dial(DialOpts::unknown_peer_id().address(addr1.clone()).build()) + .unwrap(); } state = State::Connecting; } @@ -1605,7 +1687,9 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1.dial_addr(addr2.clone()).unwrap(); + swarm1 + .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) + .unwrap(); } let mut state = State::Connecting; @@ -1638,7 +1722,9 @@ mod tests { swarm1.behaviour.reset(); swarm2.behaviour.reset(); for _ in 0..num_connections { - swarm2.dial_addr(addr1.clone()).unwrap(); + swarm2 + .dial(DialOpts::unknown_peer_id().address(addr1.clone()).build()) + .unwrap(); } state = State::Connecting; } @@ -1680,7 +1766,9 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1.dial_addr(addr2.clone()).unwrap(); + swarm1 + .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) + .unwrap(); } let mut state = State::Connecting; let mut disconnected_conn_id = None; @@ -1731,3 +1819,124 @@ mod tests { })) } } + +pub mod dial_opts { + use libp2p_core::{Multiaddr, PeerId}; + + #[derive(Debug)] + pub enum DialOpts { + // TODO: How about folding these structs into the enum variants? + WithPeerId(WithPeerId), + WithPeerIdWithAddresses(WithPeerIdWithAddresses), + WithoutPeerIdWithAddress(WithoutPeerIdWithAddress), + } + + impl DialOpts { + pub fn peer_id(peer_id: PeerId) -> WithPeerId { + WithPeerId { + peer_id, + condition: Default::default(), + } + } + + pub fn unknown_peer_id() -> WithoutPeerId { + WithoutPeerId {} + } + } + + #[derive(Debug)] + pub struct WithPeerId { + pub(crate) peer_id: PeerId, + pub(crate) condition: PeerCondition, + } + + impl WithPeerId { + pub fn condition(mut self, condition: PeerCondition) -> Self { + self.condition = condition; + self + } + + pub fn addresses(self, addresses: Vec) -> WithPeerIdWithAddresses { + WithPeerIdWithAddresses { + peer_id: self.peer_id, + condition: self.condition, + addresses, + extend_addresses_through_behaviour: false, + } + } + + pub fn build(self) -> DialOpts { + DialOpts::WithPeerId(self) + } + } + + #[derive(Debug)] + pub struct WithPeerIdWithAddresses { + pub(crate) peer_id: PeerId, + pub(crate) condition: PeerCondition, + pub(crate) addresses: Vec, + pub(crate) extend_addresses_through_behaviour: bool, + } + + impl WithPeerIdWithAddresses { + pub fn extend_addresses_through_behaviour(mut self) -> Self { + self.extend_addresses_through_behaviour = true; + self + } + + pub fn build(self) -> DialOpts { + DialOpts::WithPeerIdWithAddresses(self) + } + } + + #[derive(Debug)] + pub struct WithoutPeerId {} + + impl WithoutPeerId { + pub fn address(self, address: Multiaddr) -> WithoutPeerIdWithAddress { + WithoutPeerIdWithAddress { address } + } + } + + #[derive(Debug)] + pub struct WithoutPeerIdWithAddress { + pub(crate) address: Multiaddr, + } + + impl WithoutPeerIdWithAddress { + pub fn build(self) -> DialOpts { + DialOpts::WithoutPeerIdWithAddress(self) + } + } + + /// The available conditions under which a new dialing attempt to + /// a peer is initiated when requested by [`NetworkBehaviourAction::DialPeer`]. + #[derive(Debug, Copy, Clone)] + pub enum PeerCondition { + /// A new dialing attempt is initiated _only if_ the peer is currently + /// considered disconnected, i.e. there is no established connection + /// and no ongoing dialing attempt. + /// + /// If there is an ongoing dialing attempt, the addresses reported by + /// [`NetworkBehaviour::addresses_of_peer`] are added to the ongoing + /// dialing attempt, ignoring duplicates. + Disconnected, + /// A new dialing attempt is initiated _only if_ there is currently + /// no ongoing dialing attempt, i.e. the peer is either considered + /// disconnected or connected but without an ongoing dialing attempt. + /// + /// If there is an ongoing dialing attempt, the addresses reported by + /// [`NetworkBehaviour::addresses_of_peer`] are added to the ongoing + /// dialing attempt, ignoring duplicates. + NotDialing, + /// A new dialing attempt is always initiated, only subject to the + /// configured connection limits. + Always, + } + + impl Default for PeerCondition { + fn default() -> Self { + PeerCondition::Disconnected + } + } +} From 09688c7772aa116214e4552bd9d7cf4f2e5093ca Mon Sep 17 00:00:00 2001 From: Max Inden Date: Fri, 29 Oct 2021 18:28:24 +0200 Subject: [PATCH 02/27] swarm/src/lib: Emit SwarmEvent::Dialing --- swarm/src/lib.rs | 60 +++++++++++------------------------------------- 1 file changed, 14 insertions(+), 46 deletions(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index cbb9e62a39d..2eee488a33d 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -861,56 +861,14 @@ where Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)) => { return Poll::Ready(SwarmEvent::Behaviour(event)) } - // Poll::Ready(NetworkBehaviourAction::DialAddress { address, handler }) => { - // let _ = Swarm::dial_addr_with_handler(&mut *this, address, handler); - // } Poll::Ready(NetworkBehaviourAction::Dial { opts, handler }) => { + let peer_id = opts.get_peer_id(); if let Ok(()) = this.dial_with_handler(opts, handler) { - // TODO - // return Poll::Ready(SwarmEvent::Dialing(peer_id)); + if Some(peer_id) = peer_id { + return Poll::Ready(SwarmEvent::Dialing(peer_id)); + } } } - // Poll::Ready(NetworkBehaviourAction::DialPeer { - // peer_id, - // condition, - // handler, - // }) => { - // let condition_matched = match condition { - // DialPeerCondition::Disconnected => this.network.is_disconnected(&peer_id), - // DialPeerCondition::NotDialing => !this.network.is_dialing(&peer_id), - // DialPeerCondition::Always => true, - // }; - // if condition_matched { - // if Swarm::dial_with_handler(this, &peer_id, handler).is_ok() { - // return Poll::Ready(SwarmEvent::Dialing(peer_id)); - // } - // } else { - // // Even if the condition for a _new_ dialing attempt is not met, - // // we always add any potentially new addresses of the peer to an - // // ongoing dialing attempt, if there is one. - // log::trace!( - // "Condition for new dialing attempt to {:?} not met: {:?}", - // peer_id, - // condition - // ); - // let self_listening = &this.listened_addrs; - // if let Some(mut peer) = this.network.peer(peer_id).into_dialing() { - // let addrs = this.behaviour.addresses_of_peer(peer.id()); - // let mut attempt = peer.some_attempt(); - // for a in addrs { - // if !self_listening.contains(&a) { - // attempt.add_address(a); - // } - // } - // } - - // this.behaviour.inject_dial_failure( - // &peer_id, - // handler, - // DialError::DialPeerConditionFalse(condition), - // ); - // } - // } Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, handler, @@ -1842,6 +1800,16 @@ pub mod dial_opts { pub fn unknown_peer_id() -> WithoutPeerId { WithoutPeerId {} } + + pub fn get_peer_id(&self) -> Option { + match self { + DialOpts::WithPeerId(WithPeerId { peer_id, .. }) => Some(peer_id), + DialOpts::WithPeerIdWithAddresses(WithPeerIdWithAddresses { peer_id, .. }) => { + Some(peer_id) + } + DialOpts::WithoutPeerIdWithAddress(_) => None, + } + } } #[derive(Debug)] From 147c5332faa6fb603a2a3184b87103c08ba9c1b9 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Wed, 3 Nov 2021 13:02:39 +0100 Subject: [PATCH 03/27] swarm/src/lib: Fold condition check into first match --- swarm/src/lib.rs | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 2eee488a33d..f81b6e5042f 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -73,7 +73,7 @@ pub use protocols_handler::{ }; pub use registry::{AddAddressResult, AddressRecord, AddressScore}; -use dial_opts::DialOpts; +use dial_opts::{DialOpts, PeerCondition}; use futures::{executor::ThreadPoolBuilder, prelude::*, stream::FusedStream}; use libp2p_core::{ connection::{ @@ -332,9 +332,6 @@ where opts: DialOpts, handler: ::ProtocolsHandler, ) -> Result<(), DialError> { - // TODO: Remove Import - use dial_opts::PeerCondition; - match opts { DialOpts::WithPeerId(dial_opts::WithPeerId { peer_id, condition }) | DialOpts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { @@ -342,12 +339,12 @@ where condition, .. }) => { + // Check [`PeerCondition`] if provided. let condition_matched = match condition { PeerCondition::Disconnected => self.network.is_disconnected(&peer_id), PeerCondition::NotDialing => !self.network.is_dialing(&peer_id), PeerCondition::Always => true, }; - if !condition_matched { self.behaviour.inject_dial_failure( Some(peer_id), @@ -357,16 +354,8 @@ where return Err(DialError::DialPeerConditionFalse(condition)); } - } - DialOpts::WithoutPeerIdWithAddress { .. } => {} - } - match opts { - DialOpts::WithPeerId(dial_opts::WithPeerId { peer_id, .. }) - | DialOpts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { - peer_id, - .. - }) => { + // Check if peer is banned. if self.banned_peers.contains(&peer_id) { let error = DialError::Banned; self.behaviour @@ -374,6 +363,7 @@ where return Err(error); } + // Retrieve the addresses to dial. let addresses = match opts { DialOpts::WithPeerId(dial_opts::WithPeerId { .. }) => { self.behaviour.addresses_of_peer(&peer_id) @@ -393,7 +383,6 @@ where unreachable!("Due to outer match.") } }; - if addresses.is_empty() { let error = DialError::NoAddresses; self.behaviour @@ -430,7 +419,6 @@ where match self.network.dial(&address, handler).map(|_id| ()) { Ok(_connection_id) => Ok(()), Err(error) => { - // TODO: Deduplicate with the above? let (error, handler) = DialError::from_network_dial_error(error); self.behaviour.inject_dial_failure( None, @@ -864,7 +852,7 @@ where Poll::Ready(NetworkBehaviourAction::Dial { opts, handler }) => { let peer_id = opts.get_peer_id(); if let Ok(()) = this.dial_with_handler(opts, handler) { - if Some(peer_id) = peer_id { + if let Some(peer_id) = peer_id { return Poll::Ready(SwarmEvent::Dialing(peer_id)); } } @@ -1803,9 +1791,9 @@ pub mod dial_opts { pub fn get_peer_id(&self) -> Option { match self { - DialOpts::WithPeerId(WithPeerId { peer_id, .. }) => Some(peer_id), + DialOpts::WithPeerId(WithPeerId { peer_id, .. }) => Some(*peer_id), DialOpts::WithPeerIdWithAddresses(WithPeerIdWithAddresses { peer_id, .. }) => { - Some(peer_id) + Some(*peer_id) } DialOpts::WithoutPeerIdWithAddress(_) => None, } From 2bda3b311a7a980ffe4e70d4eba161d47daa8e3b Mon Sep 17 00:00:00 2001 From: Max Inden Date: Wed, 3 Nov 2021 13:27:07 +0100 Subject: [PATCH 04/27] protocols/kad: Adjust to API changes --- protocols/kad/src/behaviour.rs | 44 +++++++++++++++++----------------- swarm/src/lib.rs | 12 ++++++++++ 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index b785fdb09bd..f9f9f2437d5 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -44,8 +44,8 @@ use libp2p_core::{ ConnectedPoint, Multiaddr, PeerId, }; use libp2p_swarm::{ - DialError, DialPeerCondition, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, - PollParameters, + dial_opts::{self, DialOpts}, + DialError, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use log::{debug, info, warn}; use smallvec::SmallVec; @@ -564,12 +564,12 @@ where } kbucket::InsertResult::Pending { disconnected } => { let handler = self.new_handler(); - self.queued_events - .push_back(NetworkBehaviourAction::DialPeer { - peer_id: disconnected.into_preimage(), - condition: DialPeerCondition::Disconnected, - handler, - }); + self.queued_events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(disconnected.into_preimage()) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), + handler, + }); RoutingUpdate::Pending } } @@ -1152,12 +1152,12 @@ where // Only try dialing peer if not currently connected. if !self.connected_peers.contains(disconnected.preimage()) { let handler = self.new_handler(); - self.queued_events - .push_back(NetworkBehaviourAction::DialPeer { - peer_id: disconnected.into_preimage(), - condition: DialPeerCondition::Disconnected, - handler, - }) + self.queued_events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(disconnected.into_preimage()) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), + handler, + }) } } } @@ -1934,12 +1934,12 @@ where } } DialError::DialPeerConditionFalse( - DialPeerCondition::Disconnected | DialPeerCondition::NotDialing, + dial_opts::PeerCondition::Disconnected | dial_opts::PeerCondition::NotDialing, ) => { // We might (still) be connected, or about to be connected, thus do not report the // failure to the queries. } - DialError::DialPeerConditionFalse(DialPeerCondition::Always) => { + DialError::DialPeerConditionFalse(dial_opts::PeerCondition::Always) => { unreachable!("DialPeerCondition::Always can not trigger DialPeerConditionFalse."); } } @@ -2321,12 +2321,12 @@ where } else if &peer_id != self.kbuckets.local_key().preimage() { query.inner.pending_rpcs.push((peer_id, event)); let handler = self.new_handler(); - self.queued_events - .push_back(NetworkBehaviourAction::DialPeer { - peer_id, - condition: DialPeerCondition::Disconnected, - handler, - }); + self.queued_events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(peer_id) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), + handler, + }); } } QueryPoolState::Waiting(None) | QueryPoolState::Idle => break, diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index f81b6e5042f..5f0993b2204 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -390,6 +390,17 @@ where return Err(error); }; + // TODO: Filter out addresses we are listening on ourself. + // let self_listening = self.listened_addrs.clone(); + // let mut addrs = self + // .behaviour + // .addresses_of_peer(peer_id) + // .into_iter() + // .filter(move |a| !self_listening.contains(a)) + // .peekable(); + + // TODO: Deduplicate the addresses? + let handler = handler .into_node_handler_builder() .with_substream_upgrade_protocol_override( @@ -1766,6 +1777,7 @@ mod tests { } } +// TODO: Move above tests or into separate module. pub mod dial_opts { use libp2p_core::{Multiaddr, PeerId}; From ad083e933a567f1f498e590f22a4022f0d09cfee Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 17:50:26 +0000 Subject: [PATCH 05/27] swarm/src/lib: Wrap Opts in DialOpts --- swarm/src/lib.rs | 72 +++++++++++++++++++++++++++++------------------- 1 file changed, 43 insertions(+), 29 deletions(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 5f0993b2204..23bd9cb1759 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -332,9 +332,9 @@ where opts: DialOpts, handler: ::ProtocolsHandler, ) -> Result<(), DialError> { - match opts { - DialOpts::WithPeerId(dial_opts::WithPeerId { peer_id, condition }) - | DialOpts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { + match opts.0 { + dial_opts::Opts::WithPeerId(dial_opts::WithPeerId { peer_id, condition }) + | dial_opts::Opts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { peer_id, condition, .. @@ -364,22 +364,24 @@ where } // Retrieve the addresses to dial. - let addresses = match opts { - DialOpts::WithPeerId(dial_opts::WithPeerId { .. }) => { + let addresses = match opts.0 { + dial_opts::Opts::WithPeerId(dial_opts::WithPeerId { .. }) => { self.behaviour.addresses_of_peer(&peer_id) } - DialOpts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { - peer_id, - mut addresses, - extend_addresses_through_behaviour, - .. - }) => { + dial_opts::Opts::WithPeerIdWithAddresses( + dial_opts::WithPeerIdWithAddresses { + peer_id, + mut addresses, + extend_addresses_through_behaviour, + .. + }, + ) => { if extend_addresses_through_behaviour { addresses.extend(self.behaviour.addresses_of_peer(&peer_id)) } addresses } - DialOpts::WithoutPeerIdWithAddress { .. } => { + dial_opts::Opts::WithoutPeerIdWithAddress { .. } => { unreachable!("Due to outer match.") } }; @@ -420,7 +422,9 @@ where } } } - DialOpts::WithoutPeerIdWithAddress(dial_opts::WithoutPeerIdWithAddress { address }) => { + dial_opts::Opts::WithoutPeerIdWithAddress(dial_opts::WithoutPeerIdWithAddress { + address, + }) => { let handler = handler .into_node_handler_builder() .with_substream_upgrade_protocol_override( @@ -1487,7 +1491,11 @@ mod tests { for _ in 0..num_connections { swarm1 - .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) + .dial( + dial_opts::Opts::unknown_peer_id() + .address(addr2.clone()) + .build(), + ) .unwrap(); } let mut state = State::Connecting; @@ -1522,7 +1530,9 @@ mod tests { for _ in 0..num_connections { swarm2 .dial( - DialOpts::unknown_peer_id().address(addr1.clone()).build(), + dialDialOpts::unknown_peer_id() + .address(addr1.clone()) + .build(), ) .unwrap(); } @@ -1782,12 +1792,7 @@ pub mod dial_opts { use libp2p_core::{Multiaddr, PeerId}; #[derive(Debug)] - pub enum DialOpts { - // TODO: How about folding these structs into the enum variants? - WithPeerId(WithPeerId), - WithPeerIdWithAddresses(WithPeerIdWithAddresses), - WithoutPeerIdWithAddress(WithoutPeerIdWithAddress), - } + pub struct DialOpts(pub(super) Opts); impl DialOpts { pub fn peer_id(peer_id: PeerId) -> WithPeerId { @@ -1803,15 +1808,24 @@ pub mod dial_opts { pub fn get_peer_id(&self) -> Option { match self { - DialOpts::WithPeerId(WithPeerId { peer_id, .. }) => Some(*peer_id), - DialOpts::WithPeerIdWithAddresses(WithPeerIdWithAddresses { peer_id, .. }) => { - Some(*peer_id) - } - DialOpts::WithoutPeerIdWithAddress(_) => None, + DialOpts(Opts::WithPeerId(WithPeerId { peer_id, .. })) => Some(*peer_id), + DialOpts(Opts::WithPeerIdWithAddresses(WithPeerIdWithAddresses { + peer_id, + .. + })) => Some(*peer_id), + DialOpts(Opts::WithoutPeerIdWithAddress(_)) => None, } } } + #[derive(Debug)] + pub(super) enum Opts { + // TODO: How about folding these structs into the enum variants? + WithPeerId(WithPeerId), + WithPeerIdWithAddresses(WithPeerIdWithAddresses), + WithoutPeerIdWithAddress(WithoutPeerIdWithAddress), + } + #[derive(Debug)] pub struct WithPeerId { pub(crate) peer_id: PeerId, @@ -1834,7 +1848,7 @@ pub mod dial_opts { } pub fn build(self) -> DialOpts { - DialOpts::WithPeerId(self) + DialOpts(Opts::WithPeerId(self)) } } @@ -1853,7 +1867,7 @@ pub mod dial_opts { } pub fn build(self) -> DialOpts { - DialOpts::WithPeerIdWithAddresses(self) + DialOpts(Opts::WithPeerIdWithAddresses(self)) } } @@ -1873,7 +1887,7 @@ pub mod dial_opts { impl WithoutPeerIdWithAddress { pub fn build(self) -> DialOpts { - DialOpts::WithoutPeerIdWithAddress(self) + DialOpts(Opts::WithoutPeerIdWithAddress(self)) } } From eea9e12536ca019ac8c621a21082d45605f5cb28 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 17:52:01 +0000 Subject: [PATCH 06/27] protocols/identify: Update to latest changes --- protocols/identify/src/identify.rs | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/protocols/identify/src/identify.rs b/protocols/identify/src/identify.rs index 7db89d589bf..74c9eb2f4ed 100644 --- a/protocols/identify/src/identify.rs +++ b/protocols/identify/src/identify.rs @@ -27,8 +27,9 @@ use libp2p_core::{ ConnectedPoint, Multiaddr, PeerId, PublicKey, }; use libp2p_swarm::{ - AddressScore, DialError, DialPeerCondition, IntoProtocolsHandler, NegotiatedSubstream, - NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, ProtocolsHandler, + dial_opts::{self, DialOpts}, + AddressScore, DialError, IntoProtocolsHandler, NegotiatedSubstream, NetworkBehaviour, + NetworkBehaviourAction, NotifyHandler, PollParameters, ProtocolsHandler, ProtocolsHandlerUpgrErr, }; use lru::LruCache; @@ -198,9 +199,10 @@ impl Identify { if self.pending_push.insert(p) { if !self.connected.contains_key(&p) { let handler = self.new_handler(); - self.events.push_back(NetworkBehaviourAction::DialPeer { - peer_id: p, - condition: DialPeerCondition::Disconnected, + self.events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(p) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), handler, }); } @@ -561,7 +563,9 @@ mod tests { } } }); - swarm2.dial_addr(listen_addr).unwrap(); + swarm2 + .dial(DialOpts::unknown_peer_id().address(listen_addr).build()) + .unwrap(); // nb. Either swarm may receive the `Identified` event first, upon which // it will permit the connection to be closed, as defined by @@ -641,7 +645,9 @@ mod tests { } }); - Swarm::dial_addr(&mut swarm2, listen_addr).unwrap(); + swarm2 + .dial(DialOpts::unknown_peer_id().address(listen_addr).build()) + .unwrap(); async_std::task::block_on(async move { loop { @@ -728,7 +734,9 @@ mod tests { } }); - swarm2.dial_addr(listen_addr).unwrap(); + swarm2 + .dial(DialOpts::unknown_peer_id().address(listen_addr).build()) + .unwrap(); // wait until we identified async_std::task::block_on(async { @@ -744,7 +752,9 @@ mod tests { swarm2.disconnect_peer_id(swarm1_peer_id).unwrap(); // we should still be able to dial now! - swarm2.dial(&swarm1_peer_id).unwrap(); + swarm2 + .dial(DialOpts::peer_id(swarm1_peer_id).build()) + .unwrap(); let connected_peer = async_std::task::block_on(async { loop { From 26dedbec870842a5b3f9299894db14790b759777 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 17:53:26 +0000 Subject: [PATCH 07/27] swarm/src/lib: Allow WithPeerIdWithAddresses::condition --- swarm/src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 23bd9cb1759..b59d1c3dd6d 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -1861,6 +1861,11 @@ pub mod dial_opts { } impl WithPeerIdWithAddresses { + pub fn condition(mut self, condition: PeerCondition) -> Self { + self.condition = condition; + self + } + pub fn extend_addresses_through_behaviour(mut self) -> Self { self.extend_addresses_through_behaviour = true; self From eb67288934a051018a185f4f39b92329e16f57fa Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 17:56:16 +0000 Subject: [PATCH 08/27] protocols/floodsub: Adjust to latest changes --- protocols/floodsub/src/layer.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index 25b235e3364..73b8edb97fa 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -28,8 +28,8 @@ use cuckoofilter::{CuckooError, CuckooFilter}; use fnv::FnvHashSet; use libp2p_core::{connection::ConnectionId, PeerId}; use libp2p_swarm::{ - DialPeerCondition, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, OneShotHandler, - PollParameters, + dial_opts::{self, DialOpts}, + NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, OneShotHandler, PollParameters, }; use log::warn; use smallvec::SmallVec; @@ -107,9 +107,10 @@ impl Floodsub { if self.target_peers.insert(peer_id) { let handler = self.new_handler(); - self.events.push_back(NetworkBehaviourAction::DialPeer { - peer_id, - condition: DialPeerCondition::Disconnected, + self.events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(peer_id) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), handler, }); } @@ -310,9 +311,10 @@ impl NetworkBehaviour for Floodsub { // try to reconnect. if self.target_peers.contains(id) { let handler = self.new_handler(); - self.events.push_back(NetworkBehaviourAction::DialPeer { - peer_id: *id, - condition: DialPeerCondition::Disconnected, + self.events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(*id) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), handler, }); } From a04eaa3c225e33773a29109f0c19f98ea6e18e14 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 18:01:24 +0000 Subject: [PATCH 09/27] protocols/req-resp: Adjust to latest changes --- protocols/request-response/src/lib.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index c04f229b64e..bae9652d3ed 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -66,8 +66,9 @@ use futures::channel::oneshot; use handler::{RequestProtocol, RequestResponseHandler, RequestResponseHandlerEvent}; use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; use libp2p_swarm::{ - DialError, DialPeerCondition, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, - NotifyHandler, PollParameters, + dial_opts::{self, DialOpts}, + DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + PollParameters, }; use smallvec::SmallVec; use std::{ @@ -385,12 +386,12 @@ where if let Some(request) = self.try_send_request(peer, request) { let handler = self.new_handler(); - self.pending_events - .push_back(NetworkBehaviourAction::DialPeer { - peer_id: *peer, - condition: DialPeerCondition::Disconnected, - handler, - }); + self.pending_events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(*peer) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), + handler, + }); self.pending_outbound_requests .entry(*peer) .or_default() From 57f0648d6ae5e96b876a1353dff29b8f9035a59c Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 18:06:42 +0000 Subject: [PATCH 10/27] protocols/relay/src/behaviour: Update to recent changes --- protocols/relay/src/behaviour.rs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/protocols/relay/src/behaviour.rs b/protocols/relay/src/behaviour.rs index d69de981590..2ad2023fbcf 100644 --- a/protocols/relay/src/behaviour.rs +++ b/protocols/relay/src/behaviour.rs @@ -29,8 +29,9 @@ use libp2p_core::connection::{ConnectedPoint, ConnectionId, ListenerId}; use libp2p_core::multiaddr::Multiaddr; use libp2p_core::PeerId; use libp2p_swarm::{ - DialError, DialPeerCondition, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, - NotifyHandler, PollParameters, + dial_opts::{self, DialOpts}, + DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + PollParameters, }; use std::collections::{hash_map::Entry, HashMap, HashSet, VecDeque}; use std::task::{Context, Poll}; @@ -310,7 +311,7 @@ impl NetworkBehaviour for Relay { error: &DialError, ) { if let DialError::DialPeerConditionFalse( - DialPeerCondition::Disconnected | DialPeerCondition::NotDialing, + dial_opts::PeerCondition::Disconnected | dial_opts::PeerCondition::NotDialing, ) = error { // Return early. The dial, that this dial was canceled for, might still succeed. @@ -483,9 +484,10 @@ impl NetworkBehaviour for Relay { ); let handler = self.new_handler(); self.outbox_to_swarm - .push_back(NetworkBehaviourAction::DialPeer { - peer_id: dest_id, - condition: DialPeerCondition::NotDialing, + .push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(dest_id) + .condition(dial_opts::PeerCondition::NotDialing) + .build(), handler, }); } else { @@ -676,9 +678,10 @@ impl NetworkBehaviour for Relay { dst_peer_id, send_back, }); - return Poll::Ready(NetworkBehaviourAction::DialPeer { - peer_id: relay_peer_id, - condition: DialPeerCondition::Disconnected, + return Poll::Ready(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(relay_peer_id) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), handler: self.new_handler(), }); } @@ -743,9 +746,10 @@ impl NetworkBehaviour for Relay { to_listener, }, ); - return Poll::Ready(NetworkBehaviourAction::DialPeer { - peer_id: relay_peer_id, - condition: DialPeerCondition::Disconnected, + return Poll::Ready(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(relay_peer_id) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), handler: self.new_handler(), }); } From 770e3afbe5dfe0488b3db5c31c7a6247153f8b7c Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 18:21:19 +0000 Subject: [PATCH 11/27] protocols/gossipsub: Adjust to latest changes --- protocols/gossipsub/src/behaviour.rs | 18 +++++++----- protocols/gossipsub/src/behaviour/tests.rs | 34 +++++++--------------- protocols/gossipsub/tests/smoke.rs | 10 +++++-- 3 files changed, 29 insertions(+), 33 deletions(-) diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index d9682791f20..c8d7691b1a1 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -41,8 +41,8 @@ use libp2p_core::{ multiaddr::Protocol::Ip6, ConnectedPoint, Multiaddr, PeerId, }; use libp2p_swarm::{ - DialPeerCondition, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, - NotifyHandler, PollParameters, + dial_opts::{self, DialOpts}, + IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use crate::config::{GossipsubConfig, ValidationMode}; @@ -1046,9 +1046,10 @@ where // Connect to peer debug!("Connecting to explicit peer {:?}", peer_id); let handler = self.new_handler(); - self.events.push_back(NetworkBehaviourAction::DialPeer { - peer_id: *peer_id, - condition: DialPeerCondition::Disconnected, + self.events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(*peer_id) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), handler, }); } @@ -1498,9 +1499,10 @@ where // dial peer let handler = self.new_handler(); - self.events.push_back(NetworkBehaviourAction::DialPeer { - peer_id, - condition: DialPeerCondition::Disconnected, + self.events.push_back(NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(peer_id) + .condition(dial_opts::PeerCondition::Disconnected) + .build(), handler, }); } diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index d22ce8a3e6d..55d5284aa3a 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -1342,11 +1342,9 @@ mod tests { .events .iter() .filter(|e| match e { - NetworkBehaviourAction::DialPeer { - peer_id, - condition: DialPeerCondition::Disconnected, - handler: _, - } => peer_id == &peer, + NetworkBehaviourAction::Dial { opts, handler: _ } => { + opts.get_peer_id() == Some(peer) + } _ => false, }) .collect(); @@ -1388,11 +1386,8 @@ mod tests { gs.events .iter() .filter(|e| match e { - NetworkBehaviourAction::DialPeer { - peer_id, - condition: DialPeerCondition::Disconnected, - handler: _, - } => peer_id == peer, + NetworkBehaviourAction::Dial { opts, handler: _ } => + opts.get_peer_id() == Some(*peer), _ => false, }) .count(), @@ -1407,11 +1402,8 @@ mod tests { gs.events .iter() .filter(|e| match e { - NetworkBehaviourAction::DialPeer { - peer_id, - condition: DialPeerCondition::Disconnected, - handler: _, - } => peer_id == peer, + NetworkBehaviourAction::Dial { opts, handler: _ } => + opts.get_peer_id() == Some(*peer), _ => false, }) .count() @@ -1821,11 +1813,7 @@ mod tests { .events .iter() .filter_map(|e| match e { - NetworkBehaviourAction::DialPeer { - peer_id, - condition: DialPeerCondition::Disconnected, - handler: _, - } => Some(peer_id.clone()), + NetworkBehaviourAction::Dial { opts, handler: _ } => opts.get_peer_id(), _ => None, }) .collect(); @@ -2444,7 +2432,7 @@ mod tests { gs.events .iter() .filter(|e| match e { - NetworkBehaviourAction::DialPeer { .. } => true, + NetworkBehaviourAction::Dial { .. } => true, _ => false, }) .count(), @@ -3047,7 +3035,7 @@ mod tests { gs.events .iter() .filter(|e| match e { - NetworkBehaviourAction::DialPeer { .. } => true, + NetworkBehaviourAction::Dial { .. } => true, _ => false, }) .count(), @@ -3072,7 +3060,7 @@ mod tests { gs.events .iter() .filter(|e| match e { - NetworkBehaviourAction::DialPeer { .. } => true, + NetworkBehaviourAction::Dial { .. } => true, _ => false, }) .count() diff --git a/protocols/gossipsub/tests/smoke.rs b/protocols/gossipsub/tests/smoke.rs index 3cf3f882427..4bebb3865d2 100644 --- a/protocols/gossipsub/tests/smoke.rs +++ b/protocols/gossipsub/tests/smoke.rs @@ -37,7 +37,7 @@ use libp2p_gossipsub::{ ValidationMode, }; use libp2p_plaintext::PlainText2Config; -use libp2p_swarm::{Swarm, SwarmEvent}; +use libp2p_swarm::{dial_opts::DialOpts, Swarm, SwarmEvent}; use libp2p_yamux as yamux; struct Graph { @@ -98,7 +98,13 @@ impl Graph { p2p_suffix_connected.unwrap() ); - Swarm::dial_addr(&mut next.1, connected_addr_no_p2p).unwrap(); + next.1 + .dial( + DialOpts::unknown_peer_id() + .address(connected_addr_no_p2p) + .build(), + ) + .unwrap(); connected_nodes.push(next); } From 96ac37efa3a1f04e8873e569419402ca01d13edd Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 8 Nov 2021 18:47:44 +0000 Subject: [PATCH 12/27] *: Adjust to latest changes --- Cargo.toml | 2 +- examples/chat-tokio.rs | 4 +- examples/chat.rs | 4 +- examples/file-sharing.rs | 11 +- examples/gossipsub-chat.rs | 8 +- examples/ipfs-private.rs | 4 +- examples/ping.rs | 4 +- misc/metrics/examples/metrics.rs | 4 +- protocols/ping/tests/ping.rs | 26 +++- protocols/relay/examples/relay.rs | 8 +- protocols/relay/src/lib.rs | 4 +- protocols/relay/tests/lib.rs | 114 +++++++++++++++--- protocols/rendezvous/examples/discover.rs | 12 +- protocols/rendezvous/examples/register.rs | 11 +- .../examples/register_with_identify.rs | 11 +- protocols/rendezvous/tests/harness/mod.rs | 11 +- protocols/rendezvous/tests/rendezvous.rs | 9 +- src/tutorial.rs | 8 +- swarm-derive/Cargo.toml | 2 +- swarm-derive/src/lib.rs | 15 +-- swarm/src/lib.rs | 10 +- 21 files changed, 203 insertions(+), 79 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 52d6d80eeb5..6c4ab8dc283 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -86,7 +86,7 @@ libp2p-relay = { version = "0.4.0", path = "protocols/relay", optional = true } libp2p-rendezvous = { version = "0.1.0", path = "protocols/rendezvous", optional = true } libp2p-request-response = { version = "0.13.0", path = "protocols/request-response", optional = true } libp2p-swarm = { version = "0.31.0", path = "swarm" } -libp2p-swarm-derive = { version = "0.25.0", path = "swarm-derive" } +libp2p-swarm-derive = { version = "0.26.0", path = "swarm-derive" } libp2p-uds = { version = "0.30.0", path = "transports/uds", optional = true } libp2p-wasm-ext = { version = "0.30.0", path = "transports/wasm-ext", default-features = false, optional = true } libp2p-yamux = { version = "0.34.0", path = "muxers/yamux", optional = true } diff --git a/examples/chat-tokio.rs b/examples/chat-tokio.rs index e5238e785e8..2e4b5158a80 100644 --- a/examples/chat-tokio.rs +++ b/examples/chat-tokio.rs @@ -44,7 +44,7 @@ use libp2p::{ mdns::{Mdns, MdnsEvent}, mplex, noise, - swarm::{NetworkBehaviourEventProcess, SwarmBuilder, SwarmEvent}, + swarm::{dial_opts::DialOpts, NetworkBehaviourEventProcess, SwarmBuilder, SwarmEvent}, // `TokioTcpConfig` is available through the `tcp-tokio` feature. tcp::TokioTcpConfig, Multiaddr, @@ -148,7 +148,7 @@ async fn main() -> Result<(), Box> { // Reach out to another node if specified if let Some(to_dial) = std::env::args().nth(1) { let addr: Multiaddr = to_dial.parse()?; - swarm.dial_addr(addr)?; + swarm.dial(DialOpts::unknown_peer_id().address(addr).build())?; println!("Dialed {:?}", to_dial) } diff --git a/examples/chat.rs b/examples/chat.rs index 7343732f8c4..cd0be5a573a 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -55,7 +55,7 @@ use libp2p::{ floodsub::{self, Floodsub, FloodsubEvent}, identity, mdns::{Mdns, MdnsConfig, MdnsEvent}, - swarm::SwarmEvent, + swarm::{dial_opts::DialOpts, SwarmEvent}, Multiaddr, NetworkBehaviour, PeerId, Swarm, }; use std::{ @@ -128,7 +128,7 @@ async fn main() -> Result<(), Box> { // Reach out to another node if specified if let Some(to_dial) = std::env::args().nth(1) { let addr: Multiaddr = to_dial.parse()?; - swarm.dial_addr(addr)?; + swarm.dial(DialOpts::unknown_peer_id().address(addr).build())?; println!("Dialed {:?}", to_dial) } diff --git a/examples/file-sharing.rs b/examples/file-sharing.rs index f7d7abb8356..482792517d4 100644 --- a/examples/file-sharing.rs +++ b/examples/file-sharing.rs @@ -217,7 +217,7 @@ mod network { ProtocolSupport, RequestId, RequestResponse, RequestResponseCodec, RequestResponseEvent, RequestResponseMessage, ResponseChannel, }; - use libp2p::swarm::{ProtocolsHandlerUpgrErr, SwarmBuilder, SwarmEvent}; + use libp2p::swarm::{dial_opts::DialOpts, ProtocolsHandlerUpgrErr, SwarmBuilder, SwarmEvent}; use libp2p::{NetworkBehaviour, Swarm}; use std::collections::{HashMap, HashSet}; use std::iter; @@ -523,10 +523,11 @@ mod network { .behaviour_mut() .kademlia .add_address(&peer_id, peer_addr.clone()); - match self - .swarm - .dial_addr(peer_addr.with(Protocol::P2p(peer_id.into()))) - { + match self.swarm.dial( + DialOpts::unknown_peer_id() + .address(peer_addr.with(Protocol::P2p(peer_id.into()))) + .build(), + ) { Ok(()) => { self.pending_dial.insert(peer_id, sender); } diff --git a/examples/gossipsub-chat.rs b/examples/gossipsub-chat.rs index bbf1190f8c3..9e4415facf9 100644 --- a/examples/gossipsub-chat.rs +++ b/examples/gossipsub-chat.rs @@ -53,7 +53,11 @@ use libp2p::gossipsub::MessageId; use libp2p::gossipsub::{ GossipsubEvent, GossipsubMessage, IdentTopic as Topic, MessageAuthenticity, ValidationMode, }; -use libp2p::{gossipsub, identity, swarm::SwarmEvent, PeerId}; +use libp2p::{ + gossipsub, identity, + swarm::{dial_opts::DialOpts, SwarmEvent}, + PeerId, +}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; @@ -124,7 +128,7 @@ async fn main() -> Result<(), Box> { if let Some(to_dial) = std::env::args().nth(1) { let dialing = to_dial.clone(); match to_dial.parse() { - Ok(to_dial) => match swarm.dial_addr(to_dial) { + Ok(to_dial) => match swarm.dial(DialOpts::unknown_peer_id().address(to_dial).build()) { Ok(_) => println!("Dialed {:?}", dialing), Err(e) => println!("Dial {:?} failed: {:?}", dialing, e), }, diff --git a/examples/ipfs-private.rs b/examples/ipfs-private.rs index 2bf7811186b..8d79e91bb46 100644 --- a/examples/ipfs-private.rs +++ b/examples/ipfs-private.rs @@ -43,7 +43,7 @@ use libp2p::{ multiaddr::Protocol, noise, ping, pnet::{PnetConfig, PreSharedKey}, - swarm::{NetworkBehaviourEventProcess, SwarmEvent}, + swarm::{dial_opts::DialOpts, NetworkBehaviourEventProcess, SwarmEvent}, tcp::TcpConfig, yamux::YamuxConfig, Multiaddr, NetworkBehaviour, PeerId, Swarm, Transport, @@ -265,7 +265,7 @@ fn main() -> Result<(), Box> { // Reach out to other nodes if specified for to_dial in std::env::args().skip(1) { let addr: Multiaddr = parse_legacy_multiaddr(&to_dial)?; - swarm.dial_addr(addr)?; + swarm.dial(DialOpts::unknown_peer_id().address(addr).build())?; println!("Dialed {:?}", to_dial) } diff --git a/examples/ping.rs b/examples/ping.rs index ef5f538ed9d..63bd628a2da 100644 --- a/examples/ping.rs +++ b/examples/ping.rs @@ -42,7 +42,7 @@ use futures::executor::block_on; use futures::prelude::*; -use libp2p::swarm::{Swarm, SwarmEvent}; +use libp2p::swarm::{dial_opts::DialOpts, Swarm, SwarmEvent}; use libp2p::{identity, ping, PeerId}; use std::error::Error; use std::task::Poll; @@ -71,7 +71,7 @@ fn main() -> Result<(), Box> { // command-line argument, if any. if let Some(addr) = std::env::args().nth(1) { let remote = addr.parse()?; - swarm.dial_addr(remote)?; + swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; println!("Dialed {}", addr) } diff --git a/misc/metrics/examples/metrics.rs b/misc/metrics/examples/metrics.rs index 3671664a826..cec6578c2a3 100644 --- a/misc/metrics/examples/metrics.rs +++ b/misc/metrics/examples/metrics.rs @@ -52,7 +52,7 @@ use futures::executor::block_on; use futures::stream::StreamExt; use libp2p::metrics::{Metrics, Recorder}; use libp2p::ping::{Ping, PingConfig}; -use libp2p::swarm::SwarmEvent; +use libp2p::swarm::{dial_opts::DialOpts, SwarmEvent}; use libp2p::{identity, PeerId, Swarm}; use open_metrics_client::encoding::text::encode; use open_metrics_client::registry::Registry; @@ -75,7 +75,7 @@ fn main() -> Result<(), Box> { swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?; if let Some(addr) = std::env::args().nth(1) { let remote = addr.parse()?; - swarm.dial_addr(remote)?; + swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; tide::log::info!("Dialed {}", addr) } diff --git a/protocols/ping/tests/ping.rs b/protocols/ping/tests/ping.rs index e0d876bf512..d9c74711b4b 100644 --- a/protocols/ping/tests/ping.rs +++ b/protocols/ping/tests/ping.rs @@ -30,7 +30,7 @@ use libp2p_core::{ use libp2p_mplex as mplex; use libp2p_noise as noise; use libp2p_ping as ping; -use libp2p_swarm::{DummyBehaviour, KeepAlive, Swarm, SwarmEvent}; +use libp2p_swarm::{dial_opts::DialOpts, DummyBehaviour, KeepAlive, Swarm, SwarmEvent}; use libp2p_tcp::TcpConfig; use libp2p_yamux as yamux; use quickcheck::*; @@ -82,7 +82,13 @@ fn ping_pong() { let pid2 = peer2_id.clone(); let peer2 = async move { - swarm2.dial_addr(rx.next().await.unwrap()).unwrap(); + swarm2 + .dial( + DialOpts::unknown_peer_id() + .address(rx.next().await.unwrap()) + .build(), + ) + .unwrap(); loop { match swarm2.select_next_some().await { @@ -156,7 +162,13 @@ fn max_failures() { }; let peer2 = async move { - swarm2.dial_addr(rx.next().await.unwrap()).unwrap(); + swarm2 + .dial( + DialOpts::unknown_peer_id() + .address(rx.next().await.unwrap()) + .build(), + ) + .unwrap(); let mut count2: u8 = 0; @@ -216,7 +228,13 @@ fn unsupported_doesnt_fail() { }); let result = async_std::task::block_on(async move { - swarm2.dial_addr(rx.next().await.unwrap()).unwrap(); + swarm2 + .dial( + DialOpts::unknown_peer_id() + .address(rx.next().await.unwrap()) + .build(), + ) + .unwrap(); loop { match swarm2.select_next_some().await { diff --git a/protocols/relay/examples/relay.rs b/protocols/relay/examples/relay.rs index 52506ce3d3f..8961d5a43d5 100644 --- a/protocols/relay/examples/relay.rs +++ b/protocols/relay/examples/relay.rs @@ -62,7 +62,7 @@ use futures::stream::StreamExt; use libp2p::dns::DnsConfig; use libp2p::plaintext; use libp2p::relay::{Relay, RelayConfig}; -use libp2p::swarm::SwarmEvent; +use libp2p::swarm::{dial_opts::DialOpts, SwarmEvent}; use libp2p::tcp::TcpConfig; use libp2p::Transport; use libp2p::{core::upgrade, identity::ed25519, ping}; @@ -130,7 +130,11 @@ fn main() -> Result<(), Box> { } Mode::ClientDial => { let client_listen_address = get_client_listen_address(&opt); - swarm.dial_addr(client_listen_address.parse()?)?; + swarm.dial( + DialOpts::unknown_peer_id() + .address(client_listen_address.parse()?) + .build(), + )?; println!("starting as client dialer on {}", client_listen_address); } } diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index c092f494ed6..a344df69b3a 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -26,7 +26,7 @@ //! ```rust //! # use libp2p_core::transport::memory::MemoryTransport; //! # use libp2p_relay::{RelayConfig, new_transport_and_behaviour}; -//! # use libp2p_swarm::Swarm; +//! # use libp2p_swarm::{Swarm, dial_opts::DialOpts}; //! # use libp2p_core::{identity, Multiaddr, multiaddr::Protocol, PeerId, upgrade, Transport}; //! # use libp2p_yamux::YamuxConfig; //! # use libp2p_plaintext::PlainText2Config; @@ -62,7 +62,7 @@ //! swarm.listen_on(relay_addr).unwrap(); //! //! // Dial node (5678) via relay node (1234). -//! swarm.dial_addr(dst_addr).unwrap(); +//! swarm.dial(DialOpts::unknown_peer_id().address(dst_addr).build()).unwrap(); //! ``` //! //! ## Terminology diff --git a/protocols/relay/tests/lib.rs b/protocols/relay/tests/lib.rs index 427d83f970a..f4613b8e729 100644 --- a/protocols/relay/tests/lib.rs +++ b/protocols/relay/tests/lib.rs @@ -36,7 +36,7 @@ use libp2p_plaintext::PlainText2Config; use libp2p_relay::{Relay, RelayConfig}; use libp2p_swarm::protocols_handler::KeepAlive; use libp2p_swarm::{ - DialError, DummyBehaviour, NetworkBehaviour, NetworkBehaviourAction, + dial_opts::DialOpts, DialError, DummyBehaviour, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters, Swarm, SwarmEvent, }; use std::task::{Context, Poll}; @@ -146,7 +146,13 @@ fn src_connect_to_dst_listening_via_relay() { } }; - src_swarm.dial_addr(dst_addr_via_relay).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay) + .build(), + ) + .unwrap(); let src = async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -221,7 +227,13 @@ fn src_connect_to_dst_not_listening_via_active_relay() { dst_swarm.listen_on(Protocol::P2pCircuit.into()).unwrap(); spawn_swarm_on_pool(&pool, dst_swarm); - src_swarm.dial_addr(dst_addr_via_relay).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay) + .build(), + ) + .unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -307,7 +319,9 @@ fn src_connect_to_dst_via_established_connection_to_relay() { spawn_swarm_on_pool(&pool, dst_swarm); pool.run_until(async move { - src_swarm.dial_addr(relay_addr).unwrap(); + src_swarm + .dial(DialOpts::unknown_peer_id().address(relay_addr).build()) + .unwrap(); // Source Node establishing connection to Relay. loop { @@ -321,7 +335,13 @@ fn src_connect_to_dst_via_established_connection_to_relay() { } } - src_swarm.dial_addr(dst_addr_via_relay).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay) + .build(), + ) + .unwrap(); // Source Node establishing connection to destination node via Relay. loop { @@ -375,7 +395,13 @@ fn src_try_connect_to_offline_dst() { relay_swarm.listen_on(relay_addr.clone()).unwrap(); spawn_swarm_on_pool(&pool, relay_swarm); - src_swarm.dial_addr(dst_addr_via_relay.clone()).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay.clone()) + .build(), + ) + .unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -433,7 +459,13 @@ fn src_try_connect_to_unsupported_dst() { dst_swarm.listen_on(dst_addr.clone()).unwrap(); spawn_swarm_on_pool(&pool, dst_swarm); - src_swarm.dial_addr(dst_addr_via_relay.clone()).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay.clone()) + .build(), + ) + .unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -484,7 +516,13 @@ fn src_try_connect_to_offline_dst_via_offline_relay() { .with(dst_addr.into_iter().next().unwrap()) .with(Protocol::P2p(dst_peer_id.clone().into())); - src_swarm.dial_addr(dst_addr_via_relay.clone()).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay.clone()) + .build(), + ) + .unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -761,7 +799,9 @@ fn inactive_connection_timeout() { spawn_swarm_on_pool(&pool, dst_swarm); pool.run_until(async move { - src_swarm.dial_addr(relay_addr).unwrap(); + src_swarm + .dial(DialOpts::unknown_peer_id().address(relay_addr).build()) + .unwrap(); // Source Node dialing Relay. loop { match src_swarm.select_next_some().await { @@ -773,7 +813,13 @@ fn inactive_connection_timeout() { } } - src_swarm.dial_addr(dst_addr_via_relay).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay) + .build(), + ) + .unwrap(); // Source Node establishing connection to destination node via Relay. match src_swarm.select_next_some().await { @@ -841,8 +887,20 @@ fn concurrent_connection_same_relay_same_dst() { spawn_swarm_on_pool(&pool, dst_swarm); pool.run_until(async move { - src_swarm.dial_addr(dst_addr_via_relay.clone()).unwrap(); - src_swarm.dial_addr(dst_addr_via_relay).unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay.clone()) + .build(), + ) + .unwrap(); + src_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay) + .build(), + ) + .unwrap(); // Source Node establishing two connections to destination node via Relay. let mut num_established = 0; @@ -987,8 +1045,20 @@ fn yield_incoming_connection_through_correct_listener() { } }); - src_1_swarm.dial_addr(dst_addr_via_relay_1.clone()).unwrap(); - src_2_swarm.dial_addr(dst_addr_via_relay_2.clone()).unwrap(); + src_1_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay_1.clone()) + .build(), + ) + .unwrap(); + src_2_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay_2.clone()) + .build(), + ) + .unwrap(); spawn_swarm_on_pool(&pool, src_1_swarm); spawn_swarm_on_pool(&pool, src_2_swarm); @@ -1047,7 +1117,13 @@ fn yield_incoming_connection_through_correct_listener() { // Expect destination node to reject incoming connection from unknown relay given that // destination node is not listening for such connections. - src_3_swarm.dial_addr(dst_addr_via_relay_3.clone()).unwrap(); + src_3_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay_3.clone()) + .build(), + ) + .unwrap(); pool.run_until(async { loop { futures::select! { @@ -1117,7 +1193,13 @@ fn yield_incoming_connection_through_correct_listener() { // Expect destination node to accept incoming connection from "unknown" relay, i.e. the // connection from source node 3 via relay 3. - src_3_swarm.dial_addr(dst_addr_via_relay_3.clone()).unwrap(); + src_3_swarm + .dial( + DialOpts::unknown_peer_id() + .address(dst_addr_via_relay_3.clone()) + .build(), + ) + .unwrap(); pool.run_until(async move { loop { match src_3_swarm.select_next_some().await { diff --git a/protocols/rendezvous/examples/discover.rs b/protocols/rendezvous/examples/discover.rs index 4466e1caaa0..2a9709f42c4 100644 --- a/protocols/rendezvous/examples/discover.rs +++ b/protocols/rendezvous/examples/discover.rs @@ -23,7 +23,7 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::multiaddr::Protocol; use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess}; -use libp2p::swarm::SwarmEvent; +use libp2p::swarm::{dial_opts::DialOpts, SwarmEvent}; use libp2p::Swarm; use libp2p::{development_transport, rendezvous, Multiaddr}; use std::time::Duration; @@ -55,7 +55,13 @@ async fn main() { log::info!("Local peer id: {}", swarm.local_peer_id()); - let _ = swarm.dial_addr(rendezvous_point_address.clone()); + let _ = swarm + .dial( + DialOpts::unknown_peer_id() + .address(rendezvous_point_address.clone()) + .build(), + ) + .unwrap(); let mut discover_tick = tokio::time::interval(Duration::from_secs(30)); let mut cookie = None; @@ -96,7 +102,7 @@ async fn main() { address.clone() }; - swarm.dial_addr(address_with_p2p).unwrap() + swarm.dial(DialOpts::unknown_peer_id().address(address_with_p2p).build()).unwrap() } } } diff --git a/protocols/rendezvous/examples/register.rs b/protocols/rendezvous/examples/register.rs index 856cc480731..f6b38c14405 100644 --- a/protocols/rendezvous/examples/register.rs +++ b/protocols/rendezvous/examples/register.rs @@ -22,8 +22,7 @@ use futures::StreamExt; use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess}; -use libp2p::swarm::Swarm; -use libp2p::swarm::SwarmEvent; +use libp2p::swarm::{dial_opts::DialOpts, Swarm, SwarmEvent}; use libp2p::{development_transport, rendezvous}; use libp2p::{Multiaddr, NetworkBehaviour}; use libp2p_swarm::AddressScore; @@ -58,7 +57,13 @@ async fn main() { let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap()); - swarm.dial_addr(rendezvous_point_address).unwrap(); + swarm + .dial( + DialOpts::unknown_peer_id() + .address(rendezvous_point_address) + .build(), + ) + .unwrap(); while let Some(event) = swarm.next().await { match event { diff --git a/protocols/rendezvous/examples/register_with_identify.rs b/protocols/rendezvous/examples/register_with_identify.rs index 92aeb88ba05..5ab746a41bd 100644 --- a/protocols/rendezvous/examples/register_with_identify.rs +++ b/protocols/rendezvous/examples/register_with_identify.rs @@ -23,8 +23,7 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent}; use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess}; -use libp2p::swarm::Swarm; -use libp2p::swarm::SwarmEvent; +use libp2p::swarm::{dial_opts::DialOpts, Swarm, SwarmEvent}; use libp2p::{development_transport, rendezvous}; use libp2p::{Multiaddr, NetworkBehaviour}; use std::time::Duration; @@ -61,7 +60,13 @@ async fn main() { let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap()); - swarm.dial_addr(rendezvous_point_address).unwrap(); + swarm + .dial( + DialOpts::unknown_peer_id() + .address(rendezvous_point_address) + .build(), + ) + .unwrap(); while let Some(event) = swarm.next().await { match event { diff --git a/protocols/rendezvous/tests/harness/mod.rs b/protocols/rendezvous/tests/harness/mod.rs index 7b37fb740ca..204f0f0e7eb 100644 --- a/protocols/rendezvous/tests/harness/mod.rs +++ b/protocols/rendezvous/tests/harness/mod.rs @@ -29,7 +29,9 @@ use libp2p::core::upgrade::SelectUpgrade; use libp2p::core::{identity, Multiaddr, PeerId, Transport}; use libp2p::mplex::MplexConfig; use libp2p::noise::{Keypair, NoiseConfig, X25519Spec}; -use libp2p::swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmBuilder, SwarmEvent}; +use libp2p::swarm::{ + dial_opts::DialOpts, AddressScore, NetworkBehaviour, Swarm, SwarmBuilder, SwarmEvent, +}; use libp2p::yamux::YamuxConfig; use std::fmt::Debug; use std::time::Duration; @@ -163,7 +165,12 @@ where { let addr_to_dial = other.external_addresses().next().unwrap().addr.clone(); - self.dial_addr(addr_to_dial.clone()).unwrap(); + self.dial( + DialOpts::unknown_peer_id() + .address(addr_to_dial.clone()) + .build(), + ) + .unwrap(); let mut dialer_done = false; let mut listener_done = false; diff --git a/protocols/rendezvous/tests/rendezvous.rs b/protocols/rendezvous/tests/rendezvous.rs index cdec79a4ce4..7c5cbedb2c6 100644 --- a/protocols/rendezvous/tests/rendezvous.rs +++ b/protocols/rendezvous/tests/rendezvous.rs @@ -26,8 +26,7 @@ use futures::stream::FuturesUnordered; use futures::StreamExt; use libp2p_core::identity; use libp2p_rendezvous as rendezvous; -use libp2p_swarm::DialError; -use libp2p_swarm::{Swarm, SwarmEvent}; +use libp2p_swarm::{dial_opts::DialOpts, DialError, Swarm, SwarmEvent}; use std::convert::TryInto; use std::time::Duration; @@ -187,7 +186,7 @@ async fn discover_allows_for_dial_by_peer_id() { let alices_peer_id = *alice.local_peer_id(); let bobs_peer_id = *bob.local_peer_id(); - bob.dial(&alices_peer_id).unwrap(); + bob.dial(DialOpts::peer_id(alices_peer_id).build()).unwrap(); let alice_connected_to = tokio::spawn(async move { loop { @@ -296,7 +295,9 @@ async fn registration_on_clients_expire() { tokio::time::sleep(Duration::from_secs(registration_ttl + 5)).await; let event = bob.select_next_some().await; - let error = bob.dial(alice.local_peer_id()).unwrap_err(); + let error = bob + .dial(DialOpts::peer_id(*alice.local_peer_id()).build()) + .unwrap_err(); assert!(matches!( event, diff --git a/src/tutorial.rs b/src/tutorial.rs index 844bb145699..6d2961abd53 100644 --- a/src/tutorial.rs +++ b/src/tutorial.rs @@ -224,7 +224,7 @@ //! use futures::executor::block_on; //! use libp2p::{identity, PeerId}; //! use libp2p::ping::{Ping, PingConfig}; -//! use libp2p::swarm::Swarm; +//! use libp2p::swarm::{Swarm, dial_opts::DialOpts}; //! use std::error::Error; //! //! fn main() -> Result<(), Box> { @@ -251,7 +251,7 @@ //! // command-line argument, if any. //! if let Some(addr) = std::env::args().nth(1) { //! let remote = addr.parse()?; -//! swarm.dial_addr(remote)?; +//! swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; //! println!("Dialed {}", addr) //! } //! @@ -269,7 +269,7 @@ //! use futures::executor::block_on; //! use futures::prelude::*; //! use libp2p::ping::{Ping, PingConfig}; -//! use libp2p::swarm::{Swarm, SwarmEvent}; +//! use libp2p::swarm::{Swarm, SwarmEvent, dial_opts::DialOpts}; //! use libp2p::{identity, PeerId}; //! use std::error::Error; //! use std::task::Poll; @@ -298,7 +298,7 @@ //! // command-line argument, if any. //! if let Some(addr) = std::env::args().nth(1) { //! let remote = addr.parse()?; -//! swarm.dial_addr(remote)?; +//! swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; //! println!("Dialed {}", addr) //! } //! diff --git a/swarm-derive/Cargo.toml b/swarm-derive/Cargo.toml index 2da7fc8a34b..01ca2087f6d 100644 --- a/swarm-derive/Cargo.toml +++ b/swarm-derive/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-swarm-derive" edition = "2018" description = "Procedural macros of libp2p-core" -version = "0.25.0" +version = "0.26.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 512e0923670..5cab0f131d0 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -554,10 +554,10 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { wrapped_event = quote!{ #either_ident::First(#wrapped_event) }; } - // `DialPeer` and `DialAddress` each provide a handler of the specific - // behaviour triggering the event. Though in order for the final handler - // to be able to handle protocols of all behaviours, the provided - // handler needs to be combined with handlers of all other behaviours. + // `Dial` provides a handler of the specific behaviour triggering the + // event. Though in order for the final handler to be able to handle + // protocols of all behaviours, the provided handler needs to be + // combined with handlers of all other behaviours. let provided_handler_and_new_handlers = { let mut out_handler = None; @@ -608,11 +608,8 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { loop { match #trait_to_impl::poll(&mut #field_name, cx, poll_params) { #generate_event_match_arm - std::task::Poll::Ready(#network_behaviour_action::DialAddress { address, handler: provided_handler }) => { - return std::task::Poll::Ready(#network_behaviour_action::DialAddress { address, handler: #provided_handler_and_new_handlers }); - } - std::task::Poll::Ready(#network_behaviour_action::DialPeer { peer_id, condition, handler: provided_handler }) => { - return std::task::Poll::Ready(#network_behaviour_action::DialPeer { peer_id, condition, handler: #provided_handler_and_new_handlers }); + std::task::Poll::Ready(#network_behaviour_action::Dial { opts, handler: provided_handler }) => { + return std::task::Poll::Ready(#network_behaviour_action::Dial { opts, handler: #provided_handler_and_new_handlers }); } std::task::Poll::Ready(#network_behaviour_action::NotifyHandler { peer_id, handler, event }) => { return std::task::Poll::Ready(#network_behaviour_action::NotifyHandler { diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index b59d1c3dd6d..6550e517fe6 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -1491,11 +1491,7 @@ mod tests { for _ in 0..num_connections { swarm1 - .dial( - dial_opts::Opts::unknown_peer_id() - .address(addr2.clone()) - .build(), - ) + .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) .unwrap(); } let mut state = State::Connecting; @@ -1530,9 +1526,7 @@ mod tests { for _ in 0..num_connections { swarm2 .dial( - dialDialOpts::unknown_peer_id() - .address(addr1.clone()) - .build(), + DialOpts::unknown_peer_id().address(addr1.clone()).build(), ) .unwrap(); } From 9f941fd146e98ee765bf2c7e8d88c48dd488f446 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 9 Nov 2021 12:07:00 +0000 Subject: [PATCH 13/27] protocols/identify: Wait for connection to close before redialing --- protocols/identify/src/identify.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/protocols/identify/src/identify.rs b/protocols/identify/src/identify.rs index 74c9eb2f4ed..b7619379573 100644 --- a/protocols/identify/src/identify.rs +++ b/protocols/identify/src/identify.rs @@ -738,7 +738,7 @@ mod tests { .dial(DialOpts::unknown_peer_id().address(listen_addr).build()) .unwrap(); - // wait until we identified + // Wait until we identified. async_std::task::block_on(async { loop { if let SwarmEvent::Behaviour(IdentifyEvent::Received { .. }) = @@ -751,7 +751,18 @@ mod tests { swarm2.disconnect_peer_id(swarm1_peer_id).unwrap(); - // we should still be able to dial now! + // Wait for connection to close. + async_std::task::block_on(async { + loop { + if let SwarmEvent::ConnectionClosed { peer_id, .. } = + swarm2.select_next_some().await + { + break peer_id; + } + } + }); + + // We should still be able to dial now! swarm2 .dial(DialOpts::peer_id(swarm1_peer_id).build()) .unwrap(); From d4410bbcebc7aa361328adee131ae29f186e5bdc Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 9 Nov 2021 12:48:52 +0000 Subject: [PATCH 14/27] swarm/: Add documentation --- swarm/src/behaviour.rs | 34 +++++++------- swarm/src/lib.rs | 101 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 111 insertions(+), 24 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 8a02465ca54..f50b0250f6f 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -277,7 +277,7 @@ pub enum NetworkBehaviourAction< /// can be included in the handler, and thus directly send on connection success or extracted by /// the [`NetworkBehaviour`] on connection failure. /// - /// # Example + /// # Example carrying state in the handler /// /// ```rust /// # use futures::executor::block_on; @@ -328,22 +328,22 @@ pub enum NetworkBehaviourAction< /// ); /// }); /// - /// # #[derive(Default)] - /// # struct MyBehaviour { - /// # outbox_to_swarm: VecDeque>, - /// # } - /// # - /// # impl MyBehaviour { - /// # fn send(&mut self, peer_id: PeerId, msg: PreciousMessage) { - /// # self.outbox_to_swarm - /// # .push_back(NetworkBehaviourAction::Dial { - /// # opts: DialOpts::peer_id(peer_id) - /// # .condition(PeerCondition::Always) - /// # .build(), - /// # handler: MyHandler { message: Some(msg) }, - /// # }); - /// # } - /// # } + /// #[derive(Default)] + /// struct MyBehaviour { + /// outbox_to_swarm: VecDeque>, + /// } + /// + /// impl MyBehaviour { + /// fn send(&mut self, peer_id: PeerId, msg: PreciousMessage) { + /// self.outbox_to_swarm + /// .push_back(NetworkBehaviourAction::Dial { + /// opts: DialOpts::peer_id(peer_id) + /// .condition(PeerCondition::Always) + /// .build(), + /// handler: MyHandler { message: Some(msg) }, + /// }); + /// } + /// } /// # /// impl NetworkBehaviour for MyBehaviour { /// # type ProtocolsHandler = MyHandler; diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 6550e517fe6..963f84c9c9e 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -322,6 +322,36 @@ where self.network.remove_listener(id) } + /// Dial a known or unknown peer. + /// + /// See also [`DialOpts`]. + /// + /// ``` + /// # use libp2p_swarm::Swarm; + /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; + /// # use libp2p_core::{PeerId, Transport}; + /// # use libp2p_core::transport::dummy::DummyTransport; + /// # use libp2p_swarm::DummyBehaviour; + /// # + /// let mut swarm = Swarm::new( + /// DummyTransport::new().boxed(), + /// DummyBehaviour::default(), + /// PeerId::random(), + /// ); + /// + /// // Dial a known peer. + /// swarm.dial( + /// DialOpts::peer_id(PeerId::random()) + /// .build() + /// ); + /// + /// // Dial an unknown peer. + /// swarm.dial( + /// DialOpts::unknown_peer_id() + /// .address("/ip6/::1/tcp/12345".parse().unwrap()) + /// .build() + /// ); + /// ``` pub fn dial(&mut self, opts: DialOpts) -> Result<(), DialError> { let handler = self.behaviour.new_handler(); self.dial_with_handler(opts, handler) @@ -1247,7 +1277,8 @@ pub enum DialError { /// [`NetworkBehaviour::addresses_of_peer`] returned no addresses /// for the peer to dial. NoAddresses, - /// The provided [`DialPeerCondition`] evaluated to false and thus the dial was aborted. + /// The provided [`dial_opts::PeerCondition`] evaluated to false and thus + /// the dial was aborted. DialPeerConditionFalse(dial_opts::PeerCondition), /// Pending connection attempt has been aborted. Aborted, @@ -1785,10 +1816,31 @@ mod tests { pub mod dial_opts { use libp2p_core::{Multiaddr, PeerId}; + /// Options to configure a dial to a known or unknown peer. + /// + /// Used in [`Swarm::dial`](crate::Swarm::dial) and + /// [`NetworkBehaviourAction::Dial`](crate::behaviour::NetworkBehaviourAction::Dial). + /// + /// To construct use either of: + /// + /// - [`DialOpts::peer_id`] dialing a known peer + /// + /// - [`DialOpts::unknown_peer_id`] dialing an unknown peer #[derive(Debug)] pub struct DialOpts(pub(super) Opts); impl DialOpts { + /// Dial a known peer. + /// + /// ``` + /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; + /// # use libp2p_core::PeerId; + /// DialOpts::peer_id(PeerId::random()) + /// .condition(PeerCondition::Disconnected) + /// .addresses(vec!["/ip6/::1/tcp/12345".parse().unwrap()]) + /// .extend_addresses_through_behaviour() + /// .build(); + /// ``` pub fn peer_id(peer_id: PeerId) -> WithPeerId { WithPeerId { peer_id, @@ -1796,10 +1848,19 @@ pub mod dial_opts { } } + /// Dial an unknown peer. + /// + /// ``` + /// # use libp2p_swarm::dial_opts::DialOpts; + /// DialOpts::unknown_peer_id() + /// .address("/ip6/::1/tcp/12345".parse().unwrap()) + /// .build(); + /// ``` pub fn unknown_peer_id() -> WithoutPeerId { WithoutPeerId {} } + /// Get the [`PeerId`] specified in a [`DialOpts`] if any. pub fn get_peer_id(&self) -> Option { match self { DialOpts(Opts::WithPeerId(WithPeerId { peer_id, .. })) => Some(*peer_id), @@ -1812,9 +1873,14 @@ pub mod dial_opts { } } + /// Internal options type. + /// + /// Not to be constructed manually. Use either of the below instead: + /// + /// - [`DialOpts::peer_id`] dialing a known peer + /// - [`DialOpts::unknown_peer_id`] dialing an unknown peer #[derive(Debug)] pub(super) enum Opts { - // TODO: How about folding these structs into the enum variants? WithPeerId(WithPeerId), WithPeerIdWithAddresses(WithPeerIdWithAddresses), WithoutPeerIdWithAddress(WithoutPeerIdWithAddress), @@ -1827,11 +1893,13 @@ pub mod dial_opts { } impl WithPeerId { + /// Specify a [`PeerCondition`] for the dial. pub fn condition(mut self, condition: PeerCondition) -> Self { self.condition = condition; self } + /// Specify a set of addresses to be used to dial the known peer. pub fn addresses(self, addresses: Vec) -> WithPeerIdWithAddresses { WithPeerIdWithAddresses { peer_id: self.peer_id, @@ -1841,6 +1909,10 @@ pub mod dial_opts { } } + /// Build the final [`DialOpts`]. + /// + /// Addresses to dial the peer are retrieved via + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer). pub fn build(self) -> DialOpts { DialOpts(Opts::WithPeerId(self)) } @@ -1855,16 +1927,20 @@ pub mod dial_opts { } impl WithPeerIdWithAddresses { + /// Specify a [`PeerCondition`] for the dial. pub fn condition(mut self, condition: PeerCondition) -> Self { self.condition = condition; self } + /// In addition to the provided addresses, extend the set via + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer). pub fn extend_addresses_through_behaviour(mut self) -> Self { self.extend_addresses_through_behaviour = true; self } + /// Build the final [`DialOpts`]. pub fn build(self) -> DialOpts { DialOpts(Opts::WithPeerIdWithAddresses(self)) } @@ -1874,6 +1950,7 @@ pub mod dial_opts { pub struct WithoutPeerId {} impl WithoutPeerId { + /// Specify a single address to dial the unknown peer. pub fn address(self, address: Multiaddr) -> WithoutPeerIdWithAddress { WithoutPeerIdWithAddress { address } } @@ -1885,13 +1962,23 @@ pub mod dial_opts { } impl WithoutPeerIdWithAddress { + /// Build the final [`DialOpts`]. pub fn build(self) -> DialOpts { DialOpts(Opts::WithoutPeerIdWithAddress(self)) } } /// The available conditions under which a new dialing attempt to - /// a peer is initiated when requested by [`NetworkBehaviourAction::DialPeer`]. + /// a known peer is initiated. + /// + /// ``` + /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; + /// # use libp2p_core::PeerId; + /// # + /// DialOpts::peer_id(PeerId::random()) + /// .condition(PeerCondition::Disconnected) + /// .build(); + /// ``` #[derive(Debug, Copy, Clone)] pub enum PeerCondition { /// A new dialing attempt is initiated _only if_ the peer is currently @@ -1899,16 +1986,16 @@ pub mod dial_opts { /// and no ongoing dialing attempt. /// /// If there is an ongoing dialing attempt, the addresses reported by - /// [`NetworkBehaviour::addresses_of_peer`] are added to the ongoing - /// dialing attempt, ignoring duplicates. + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) + /// are added to the ongoing dialing attempt, ignoring duplicates. Disconnected, /// A new dialing attempt is initiated _only if_ there is currently /// no ongoing dialing attempt, i.e. the peer is either considered /// disconnected or connected but without an ongoing dialing attempt. /// /// If there is an ongoing dialing attempt, the addresses reported by - /// [`NetworkBehaviour::addresses_of_peer`] are added to the ongoing - /// dialing attempt, ignoring duplicates. + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) + /// are added to the ongoing dialing attempt, ignoring duplicates. NotDialing, /// A new dialing attempt is always initiated, only subject to the /// configured connection limits. From 163229c66b573b2565772e7f8001c46f8d66dba3 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 9 Nov 2021 13:04:05 +0000 Subject: [PATCH 15/27] swarm/src/lib: Deduplicate addresses --- swarm/src/lib.rs | 71 ++++++++++++++++++++++++------------------------ 1 file changed, 36 insertions(+), 35 deletions(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 963f84c9c9e..93a1b4606d9 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -363,6 +363,7 @@ where handler: ::ProtocolsHandler, ) -> Result<(), DialError> { match opts.0 { + // Dial a known peer. dial_opts::Opts::WithPeerId(dial_opts::WithPeerId { peer_id, condition }) | dial_opts::Opts::WithPeerIdWithAddresses(dial_opts::WithPeerIdWithAddresses { peer_id, @@ -394,44 +395,43 @@ where } // Retrieve the addresses to dial. - let addresses = match opts.0 { - dial_opts::Opts::WithPeerId(dial_opts::WithPeerId { .. }) => { - self.behaviour.addresses_of_peer(&peer_id) - } - dial_opts::Opts::WithPeerIdWithAddresses( - dial_opts::WithPeerIdWithAddresses { - peer_id, - mut addresses, - extend_addresses_through_behaviour, - .. - }, - ) => { - if extend_addresses_through_behaviour { - addresses.extend(self.behaviour.addresses_of_peer(&peer_id)) + let addresses = { + let mut addresses = match opts.0 { + dial_opts::Opts::WithPeerId(dial_opts::WithPeerId { .. }) => { + self.behaviour.addresses_of_peer(&peer_id) } - addresses - } - dial_opts::Opts::WithoutPeerIdWithAddress { .. } => { - unreachable!("Due to outer match.") - } - }; - if addresses.is_empty() { - let error = DialError::NoAddresses; - self.behaviour - .inject_dial_failure(Some(peer_id), handler, &error); - return Err(error); - }; + dial_opts::Opts::WithPeerIdWithAddresses( + dial_opts::WithPeerIdWithAddresses { + peer_id, + mut addresses, + extend_addresses_through_behaviour, + .. + }, + ) => { + if extend_addresses_through_behaviour { + addresses.extend(self.behaviour.addresses_of_peer(&peer_id)) + } + addresses + } + dial_opts::Opts::WithoutPeerIdWithAddress { .. } => { + unreachable!("Due to outer match.") + } + }; - // TODO: Filter out addresses we are listening on ourself. - // let self_listening = self.listened_addrs.clone(); - // let mut addrs = self - // .behaviour - // .addresses_of_peer(peer_id) - // .into_iter() - // .filter(move |a| !self_listening.contains(a)) - // .peekable(); + let mut unique_addresses = HashSet::new(); + addresses.retain(|a| { + !self.listened_addrs.contains(a) && unique_addresses.insert(a.clone()) + }); + + if addresses.is_empty() { + let error = DialError::NoAddresses; + self.behaviour + .inject_dial_failure(Some(peer_id), handler, &error); + return Err(error); + }; - // TODO: Deduplicate the addresses? + addresses + }; let handler = handler .into_node_handler_builder() @@ -452,6 +452,7 @@ where } } } + // Dial an unknown peer. dial_opts::Opts::WithoutPeerIdWithAddress(dial_opts::WithoutPeerIdWithAddress { address, }) => { From 8334f3610b5298d988fee4d28aaca579a1c85033 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 9 Nov 2021 13:17:04 +0000 Subject: [PATCH 16/27] swarm/CHANGELOG: Add entry --- swarm/CHANGELOG.md | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 0124b5bff93..1c0d2ed2662 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -1,8 +1,46 @@ -# 0.31.1 [unreleased] +# 0.32.0 [unreleased] - Use `instant` and `futures-timer` instead of `wasm-timer` (see [PR 2245]). +- Enable advanced dialing requests both on `Swarm::dial` and via + `NetworkBehaviourAction::Dial`. Users can now trigger a dial with a specific + set of addresses, optionally extended via + `NetworkBehaviour::addresses_of_peer`. + + Changes required to maintain status quo: + + - Previously `swarm.dial(peer_id)` + Now `swarm.dial(DialOpts::peer_id(swarm1_peer_id).build())` + + - Previously `swarm.dial_addr(addr)` + Now `swarm.dial(DialOpts::unknown_peer_id().address(addr).build())` + + - Previously `NetworkBehaviourAction::DialPeer { peer_id, condition, handler }` + Now + ```rust + NetworkBehaviourAction::Dial { + opts: DialOpts::peer_id(peer_id) + .condition(condition) + .build(), + handler, + } + ``` + + - Previously `NetworkBehaviourAction::DialAddress { address, handler }` + Now + ```rust + NetworkBehaviourAction::Dial { + opts: DialOpts::unknown_peer_id() + .address(address) + .build(), + handler, + } + ``` + + See [PR 2317]. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 +[PR 2317]: https://github.com/libp2p/rust-libp2p/pull/2317 # 0.31.0 [2021-11-01] From 1e561e82a9485b70000687d191fa8f6ce22d6dbf Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 9 Nov 2021 13:27:31 +0000 Subject: [PATCH 17/27] *: Bump versions --- Cargo.toml | 20 ++++++++++---------- misc/metrics/CHANGELOG.md | 4 ++++ misc/metrics/Cargo.toml | 12 ++++++------ protocols/floodsub/CHANGELOG.md | 4 ++++ protocols/floodsub/Cargo.toml | 4 ++-- protocols/gossipsub/CHANGELOG.md | 4 +++- protocols/gossipsub/Cargo.toml | 4 ++-- protocols/identify/CHANGELOG.md | 4 +++- protocols/identify/Cargo.toml | 4 ++-- protocols/kad/CHANGELOG.md | 2 ++ protocols/kad/Cargo.toml | 2 +- protocols/mdns/CHANGELOG.md | 4 ++++ protocols/mdns/Cargo.toml | 4 ++-- protocols/ping/CHANGELOG.md | 4 +++- protocols/ping/Cargo.toml | 4 ++-- protocols/relay/CHANGELOG.md | 4 +++- protocols/relay/Cargo.toml | 4 ++-- protocols/rendezvous/CHANGELOG.md | 4 +++- protocols/rendezvous/Cargo.toml | 4 ++-- protocols/request-response/CHANGELOG.md | 4 +++- protocols/request-response/Cargo.toml | 4 ++-- swarm/Cargo.toml | 2 +- 22 files changed, 66 insertions(+), 40 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6c4ab8dc283..806e92ae9cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,20 +72,20 @@ getrandom = "0.2.3" # Explicit dependency to be used in `wasm-bindgen` feature instant = "0.1.11" # Explicit dependency to be used in `wasm-bindgen` feature lazy_static = "1.2" libp2p-core = { version = "0.30.0", path = "core", default-features = false } -libp2p-floodsub = { version = "0.31.0", path = "protocols/floodsub", optional = true } -libp2p-gossipsub = { version = "0.33.0", path = "./protocols/gossipsub", optional = true } -libp2p-identify = { version = "0.31.0", path = "protocols/identify", optional = true } +libp2p-floodsub = { version = "0.32.0", path = "protocols/floodsub", optional = true } +libp2p-gossipsub = { version = "0.34.0", path = "./protocols/gossipsub", optional = true } +libp2p-identify = { version = "0.32.0", path = "protocols/identify", optional = true } libp2p-kad = { version = "0.33.0", path = "protocols/kad", optional = true } -libp2p-metrics = { version = "0.1.0", path = "misc/metrics", optional = true } +libp2p-metrics = { version = "0.2.0", path = "misc/metrics", optional = true } libp2p-mplex = { version = "0.30.0", path = "muxers/mplex", optional = true } libp2p-noise = { version = "0.33.0", path = "transports/noise", optional = true } -libp2p-ping = { version = "0.31.0", path = "protocols/ping", optional = true } +libp2p-ping = { version = "0.32.0", path = "protocols/ping", optional = true } libp2p-plaintext = { version = "0.30.0", path = "transports/plaintext", optional = true } libp2p-pnet = { version = "0.22.0", path = "transports/pnet", optional = true } -libp2p-relay = { version = "0.4.0", path = "protocols/relay", optional = true } -libp2p-rendezvous = { version = "0.1.0", path = "protocols/rendezvous", optional = true } -libp2p-request-response = { version = "0.13.0", path = "protocols/request-response", optional = true } -libp2p-swarm = { version = "0.31.0", path = "swarm" } +libp2p-relay = { version = "0.5.0", path = "protocols/relay", optional = true } +libp2p-rendezvous = { version = "0.2.0", path = "protocols/rendezvous", optional = true } +libp2p-request-response = { version = "0.14.0", path = "protocols/request-response", optional = true } +libp2p-swarm = { version = "0.32.0", path = "swarm" } libp2p-swarm-derive = { version = "0.26.0", path = "swarm-derive" } libp2p-uds = { version = "0.30.0", path = "transports/uds", optional = true } libp2p-wasm-ext = { version = "0.30.0", path = "transports/wasm-ext", default-features = false, optional = true } @@ -99,7 +99,7 @@ smallvec = "1.6.1" [target.'cfg(not(any(target_os = "emscripten", target_os = "wasi", target_os = "unknown")))'.dependencies] libp2p-deflate = { version = "0.30.0", path = "transports/deflate", optional = true } libp2p-dns = { version = "0.30.0", path = "transports/dns", optional = true, default-features = false } -libp2p-mdns = { version = "0.32.0", path = "protocols/mdns", optional = true } +libp2p-mdns = { version = "0.33.0", path = "protocols/mdns", optional = true } libp2p-tcp = { version = "0.30.0", path = "transports/tcp", default-features = false, optional = true } libp2p-websocket = { version = "0.32.0", path = "transports/websocket", optional = true } diff --git a/misc/metrics/CHANGELOG.md b/misc/metrics/CHANGELOG.md index 91693e4579a..f25070eecf8 100644 --- a/misc/metrics/CHANGELOG.md +++ b/misc/metrics/CHANGELOG.md @@ -1,3 +1,7 @@ +## Version 0.2.0 [unreleased] + +- Update dependencies. + ## Version 0.1.0 [2021-11-01] - Add initial version. \ No newline at end of file diff --git a/misc/metrics/Cargo.toml b/misc/metrics/Cargo.toml index f09aaf757d4..a2674de592b 100644 --- a/misc/metrics/Cargo.toml +++ b/misc/metrics/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-metrics" edition = "2018" description = "Metrics for libp2p" -version = "0.1.0" +version = "0.2.0" authors = ["Max Inden "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -15,11 +15,11 @@ kad = ["libp2p-kad"] ping = ["libp2p-ping"] [dependencies] -libp2p-core= { version = "0.30.0", path = "../../core" } -libp2p-identify = { version = "0.31.0", path = "../../protocols/identify", optional = true } -libp2p-kad = { version = "0.33.0", path = "../../protocols/kad", optional = true } -libp2p-ping = { version = "0.31.0", path = "../../protocols/ping", optional = true } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-core = { version = "0.30.0", path = "../../core" } +libp2p-identify = { version = "0.32.0", path = "../../protocols/identify", optional = true } +libp2p-kad = { version = "0.33.0", path = "../../protocols/kad", optional = true } +libp2p-ping = { version = "0.32.0", path = "../../protocols/ping", optional = true } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } open-metrics-client = "0.12.0" [dev-dependencies] diff --git a/protocols/floodsub/CHANGELOG.md b/protocols/floodsub/CHANGELOG.md index ca05810d9b9..7e18468e4a0 100644 --- a/protocols/floodsub/CHANGELOG.md +++ b/protocols/floodsub/CHANGELOG.md @@ -1,3 +1,7 @@ +# 0.32.0 [unreleased] + +- Update dependencies. + # 0.31.0 [2021-11-01] - Make default features of `libp2p-core` optional. diff --git a/protocols/floodsub/Cargo.toml b/protocols/floodsub/Cargo.toml index a08fcc49bcf..1679e6133d5 100644 --- a/protocols/floodsub/Cargo.toml +++ b/protocols/floodsub/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-floodsub" edition = "2018" description = "Floodsub protocol for libp2p" -version = "0.31.0" +version = "0.32.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -14,7 +14,7 @@ cuckoofilter = "0.5.0" fnv = "1.0" futures = "0.3.1" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } log = "0.4" prost = "0.9" rand = "0.7" diff --git a/protocols/gossipsub/CHANGELOG.md b/protocols/gossipsub/CHANGELOG.md index 8a0b2ca55f4..480d57959e5 100644 --- a/protocols/gossipsub/CHANGELOG.md +++ b/protocols/gossipsub/CHANGELOG.md @@ -1,7 +1,9 @@ -# 0.33.1 [unreleased] +# 0.34.0 [unreleased] - Use `instant` and `futures-timer` instead of `wasm-timer` (see [PR 2245]). +- Update dependencies. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 # 0.33.0 [2021-11-01] diff --git a/protocols/gossipsub/Cargo.toml b/protocols/gossipsub/Cargo.toml index 8622be50305..66c00067195 100644 --- a/protocols/gossipsub/Cargo.toml +++ b/protocols/gossipsub/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-gossipsub" edition = "2018" description = "Gossipsub protocol for libp2p" -version = "0.33.1" +version = "0.34.0" authors = ["Age Manning "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -10,7 +10,7 @@ keywords = ["peer-to-peer", "libp2p", "networking"] categories = ["network-programming", "asynchronous"] [dependencies] -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } bytes = "1.0" byteorder = "1.3.4" diff --git a/protocols/identify/CHANGELOG.md b/protocols/identify/CHANGELOG.md index 20eb855174a..b6cb0762e5d 100644 --- a/protocols/identify/CHANGELOG.md +++ b/protocols/identify/CHANGELOG.md @@ -1,7 +1,9 @@ -# 0.31.1 [unreleased] +# 0.32.0 [unreleased] - Use `futures-timer` instead of `wasm-timer` (see [PR 2245]). +- Update dependencies. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 # 0.31.0 [2021-11-01] diff --git a/protocols/identify/Cargo.toml b/protocols/identify/Cargo.toml index 8b8a2bb4404..53bca1ff489 100644 --- a/protocols/identify/Cargo.toml +++ b/protocols/identify/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-identify" edition = "2018" description = "Nodes identifcation protocol for libp2p" -version = "0.31.1" +version = "0.32.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -13,7 +13,7 @@ categories = ["network-programming", "asynchronous"] futures = "0.3.1" futures-timer = "3.0.2" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } log = "0.4.1" lru = "0.6" prost = "0.9" diff --git a/protocols/kad/CHANGELOG.md b/protocols/kad/CHANGELOG.md index 4f1c06f368d..59137705d76 100644 --- a/protocols/kad/CHANGELOG.md +++ b/protocols/kad/CHANGELOG.md @@ -8,6 +8,8 @@ - Populate the `key` field when converting `KadRequestMsg::PutValue` to `proto::Message` (see [PR 2309]). +- Update dependencies. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 [PR 2297]: https://github.com/libp2p/rust-libp2p/pull/2297 [PR 2309]: https://github.com/libp2p/rust-libp2p/pull/2309 diff --git a/protocols/kad/Cargo.toml b/protocols/kad/Cargo.toml index c0a04fc7ccb..76b4084eb4d 100644 --- a/protocols/kad/Cargo.toml +++ b/protocols/kad/Cargo.toml @@ -18,7 +18,7 @@ asynchronous-codec = "0.6" futures = "0.3.1" log = "0.4" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } prost = "0.9" rand = "0.7.2" sha2 = "0.9.1" diff --git a/protocols/mdns/CHANGELOG.md b/protocols/mdns/CHANGELOG.md index f3287379ded..b7b66e278af 100644 --- a/protocols/mdns/CHANGELOG.md +++ b/protocols/mdns/CHANGELOG.md @@ -1,3 +1,7 @@ +# 0.33.0 [unreleased] + +- Update dependencies. + # 0.32.0 [2021-11-01] - Make default features of `libp2p-core` optional. diff --git a/protocols/mdns/Cargo.toml b/protocols/mdns/Cargo.toml index 43370a9bffd..4fb7eaf08bf 100644 --- a/protocols/mdns/Cargo.toml +++ b/protocols/mdns/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "libp2p-mdns" edition = "2018" -version = "0.32.0" +version = "0.33.0" description = "Implementation of the libp2p mDNS discovery method" authors = ["Parity Technologies "] license = "MIT" @@ -17,7 +17,7 @@ futures = "0.3.13" if-watch = "0.2.0" lazy_static = "1.4.0" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } log = "0.4.14" rand = "0.8.3" smallvec = "1.6.1" diff --git a/protocols/ping/CHANGELOG.md b/protocols/ping/CHANGELOG.md index 3b80aa9ee60..a3d7fe678d4 100644 --- a/protocols/ping/CHANGELOG.md +++ b/protocols/ping/CHANGELOG.md @@ -1,7 +1,9 @@ -# 0.31.1 [unreleased] +# 0.32.0 [unreleased] - Use `instant` and `futures-timer` instead of `wasm-timer` (see [PR 2245]). +- Update dependencies. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 # 0.31.0 [2021-11-01] diff --git a/protocols/ping/Cargo.toml b/protocols/ping/Cargo.toml index 8c11866cb0c..4bbd70f9324 100644 --- a/protocols/ping/Cargo.toml +++ b/protocols/ping/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-ping" edition = "2018" description = "Ping protocol for libp2p" -version = "0.31.1" +version = "0.32.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -14,7 +14,7 @@ futures = "0.3.1" futures-timer = "3.0.2" instant = "0.1.11" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } log = "0.4.1" rand = "0.7.2" void = "1.0" diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index 6a3d38c6401..24833b1ee49 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -1,7 +1,9 @@ -# 0.4.1 [unreleased] +# 0.5.0 [unreleased] - Use `instant` instead of `wasm-timer` (see [PR 2245]). +- Update dependencies. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 # 0.4.0 [2021-11-01] diff --git a/protocols/relay/Cargo.toml b/protocols/relay/Cargo.toml index 051c97e06d8..d9d618a61e2 100644 --- a/protocols/relay/Cargo.toml +++ b/protocols/relay/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-relay" edition = "2018" description = "Communications relaying for libp2p" -version = "0.4.1" +version = "0.5.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -16,7 +16,7 @@ futures = "0.3.1" futures-timer = "3" instant = "0.1.11" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } log = "0.4" pin-project = "1" prost = "0.9" diff --git a/protocols/rendezvous/CHANGELOG.md b/protocols/rendezvous/CHANGELOG.md index 5bfe1b576a2..b7af7a07917 100644 --- a/protocols/rendezvous/CHANGELOG.md +++ b/protocols/rendezvous/CHANGELOG.md @@ -1,7 +1,9 @@ -# 0.1.1 [unreleased] +# 0.2.0 [unreleased] - Use `instant` and `futures-timer` instead of `wasm-timer` (see [PR 2245]). +- Update dependencies. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 # 0.1.0 [2021-11-01] diff --git a/protocols/rendezvous/Cargo.toml b/protocols/rendezvous/Cargo.toml index ba20329b084..c0cba9cd709 100644 --- a/protocols/rendezvous/Cargo.toml +++ b/protocols/rendezvous/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-rendezvous" edition = "2018" description = "Rendezvous protocol for libp2p" -version = "0.1.1" +version = "0.2.0" authors = ["The COMIT guys "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -12,7 +12,7 @@ categories = ["network-programming", "asynchronous"] [dependencies] asynchronous-codec = "0.6" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } prost = "0.9" void = "1" log = "0.4" diff --git a/protocols/request-response/CHANGELOG.md b/protocols/request-response/CHANGELOG.md index b87bcf2ecf7..73db7a30e0d 100644 --- a/protocols/request-response/CHANGELOG.md +++ b/protocols/request-response/CHANGELOG.md @@ -1,7 +1,9 @@ -# 0.13.1 [unreleased] +# 0.14.0 [unreleased] - Use `instant` instead of `wasm-timer` (see [PR 2245]). +- Update dependencies. + [PR 2245]: https://github.com/libp2p/rust-libp2p/pull/2245 # 0.13.0 [2021-11-01] diff --git a/protocols/request-response/Cargo.toml b/protocols/request-response/Cargo.toml index afd36754720..9d18836fd91 100644 --- a/protocols/request-response/Cargo.toml +++ b/protocols/request-response/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-request-response" edition = "2018" description = "Generic Request/Response Protocols" -version = "0.13.1" +version = "0.14.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -15,7 +15,7 @@ bytes = "1" futures = "0.3.1" instant = "0.1.11" libp2p-core = { version = "0.30.0", path = "../../core", default-features = false } -libp2p-swarm = { version = "0.31.0", path = "../../swarm" } +libp2p-swarm = { version = "0.32.0", path = "../../swarm" } log = "0.4.11" lru = "0.7" rand = "0.7" diff --git a/swarm/Cargo.toml b/swarm/Cargo.toml index ec028270604..2c5da850070 100644 --- a/swarm/Cargo.toml +++ b/swarm/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-swarm" edition = "2018" description = "The libp2p swarm" -version = "0.31.1" +version = "0.32.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" From 036cf2497d3269897b71d251f3a5d4ff8258745b Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 9 Nov 2021 13:33:06 +0000 Subject: [PATCH 18/27] swarm/src/lib: Move dial_opts to separate file --- swarm/src/dial_opts.rs | 213 +++++++++++++++++++++++++++++++++++++++++ swarm/src/lib.rs | 198 +------------------------------------- 2 files changed, 214 insertions(+), 197 deletions(-) create mode 100644 swarm/src/dial_opts.rs diff --git a/swarm/src/dial_opts.rs b/swarm/src/dial_opts.rs new file mode 100644 index 00000000000..97e204151ed --- /dev/null +++ b/swarm/src/dial_opts.rs @@ -0,0 +1,213 @@ +// Copyright 2019 Parity Technologies (UK) Ltd. +// Copyright 2021 Protocol Labs. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +use libp2p_core::{Multiaddr, PeerId}; + +/// Options to configure a dial to a known or unknown peer. +/// +/// Used in [`Swarm::dial`](crate::Swarm::dial) and +/// [`NetworkBehaviourAction::Dial`](crate::behaviour::NetworkBehaviourAction::Dial). +/// +/// To construct use either of: +/// +/// - [`DialOpts::peer_id`] dialing a known peer +/// +/// - [`DialOpts::unknown_peer_id`] dialing an unknown peer +#[derive(Debug)] +pub struct DialOpts(pub(super) Opts); + +impl DialOpts { + /// Dial a known peer. + /// + /// ``` + /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; + /// # use libp2p_core::PeerId; + /// DialOpts::peer_id(PeerId::random()) + /// .condition(PeerCondition::Disconnected) + /// .addresses(vec!["/ip6/::1/tcp/12345".parse().unwrap()]) + /// .extend_addresses_through_behaviour() + /// .build(); + /// ``` + pub fn peer_id(peer_id: PeerId) -> WithPeerId { + WithPeerId { + peer_id, + condition: Default::default(), + } + } + + /// Dial an unknown peer. + /// + /// ``` + /// # use libp2p_swarm::dial_opts::DialOpts; + /// DialOpts::unknown_peer_id() + /// .address("/ip6/::1/tcp/12345".parse().unwrap()) + /// .build(); + /// ``` + pub fn unknown_peer_id() -> WithoutPeerId { + WithoutPeerId {} + } + + /// Get the [`PeerId`] specified in a [`DialOpts`] if any. + pub fn get_peer_id(&self) -> Option { + match self { + DialOpts(Opts::WithPeerId(WithPeerId { peer_id, .. })) => Some(*peer_id), + DialOpts(Opts::WithPeerIdWithAddresses(WithPeerIdWithAddresses { + peer_id, .. + })) => Some(*peer_id), + DialOpts(Opts::WithoutPeerIdWithAddress(_)) => None, + } + } +} + +/// Internal options type. +/// +/// Not to be constructed manually. Use either of the below instead: +/// +/// - [`DialOpts::peer_id`] dialing a known peer +/// - [`DialOpts::unknown_peer_id`] dialing an unknown peer +#[derive(Debug)] +pub(super) enum Opts { + WithPeerId(WithPeerId), + WithPeerIdWithAddresses(WithPeerIdWithAddresses), + WithoutPeerIdWithAddress(WithoutPeerIdWithAddress), +} + +#[derive(Debug)] +pub struct WithPeerId { + pub(crate) peer_id: PeerId, + pub(crate) condition: PeerCondition, +} + +impl WithPeerId { + /// Specify a [`PeerCondition`] for the dial. + pub fn condition(mut self, condition: PeerCondition) -> Self { + self.condition = condition; + self + } + + /// Specify a set of addresses to be used to dial the known peer. + pub fn addresses(self, addresses: Vec) -> WithPeerIdWithAddresses { + WithPeerIdWithAddresses { + peer_id: self.peer_id, + condition: self.condition, + addresses, + extend_addresses_through_behaviour: false, + } + } + + /// Build the final [`DialOpts`]. + /// + /// Addresses to dial the peer are retrieved via + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer). + pub fn build(self) -> DialOpts { + DialOpts(Opts::WithPeerId(self)) + } +} + +#[derive(Debug)] +pub struct WithPeerIdWithAddresses { + pub(crate) peer_id: PeerId, + pub(crate) condition: PeerCondition, + pub(crate) addresses: Vec, + pub(crate) extend_addresses_through_behaviour: bool, +} + +impl WithPeerIdWithAddresses { + /// Specify a [`PeerCondition`] for the dial. + pub fn condition(mut self, condition: PeerCondition) -> Self { + self.condition = condition; + self + } + + /// In addition to the provided addresses, extend the set via + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer). + pub fn extend_addresses_through_behaviour(mut self) -> Self { + self.extend_addresses_through_behaviour = true; + self + } + + /// Build the final [`DialOpts`]. + pub fn build(self) -> DialOpts { + DialOpts(Opts::WithPeerIdWithAddresses(self)) + } +} + +#[derive(Debug)] +pub struct WithoutPeerId {} + +impl WithoutPeerId { + /// Specify a single address to dial the unknown peer. + pub fn address(self, address: Multiaddr) -> WithoutPeerIdWithAddress { + WithoutPeerIdWithAddress { address } + } +} + +#[derive(Debug)] +pub struct WithoutPeerIdWithAddress { + pub(crate) address: Multiaddr, +} + +impl WithoutPeerIdWithAddress { + /// Build the final [`DialOpts`]. + pub fn build(self) -> DialOpts { + DialOpts(Opts::WithoutPeerIdWithAddress(self)) + } +} + +/// The available conditions under which a new dialing attempt to +/// a known peer is initiated. +/// +/// ``` +/// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; +/// # use libp2p_core::PeerId; +/// # +/// DialOpts::peer_id(PeerId::random()) +/// .condition(PeerCondition::Disconnected) +/// .build(); +/// ``` +#[derive(Debug, Copy, Clone)] +pub enum PeerCondition { + /// A new dialing attempt is initiated _only if_ the peer is currently + /// considered disconnected, i.e. there is no established connection + /// and no ongoing dialing attempt. + /// + /// If there is an ongoing dialing attempt, the addresses reported by + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) + /// are added to the ongoing dialing attempt, ignoring duplicates. + Disconnected, + /// A new dialing attempt is initiated _only if_ there is currently + /// no ongoing dialing attempt, i.e. the peer is either considered + /// disconnected or connected but without an ongoing dialing attempt. + /// + /// If there is an ongoing dialing attempt, the addresses reported by + /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) + /// are added to the ongoing dialing attempt, ignoring duplicates. + NotDialing, + /// A new dialing attempt is always initiated, only subject to the + /// configured connection limits. + Always, +} + +impl Default for PeerCondition { + fn default() -> Self { + PeerCondition::Disconnected + } +} diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 93a1b4606d9..1eed46eb0a8 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -59,6 +59,7 @@ mod registry; mod test; mod upgrade; +pub mod dial_opts; pub mod protocols_handler; pub mod toggle; @@ -1812,200 +1813,3 @@ mod tests { })) } } - -// TODO: Move above tests or into separate module. -pub mod dial_opts { - use libp2p_core::{Multiaddr, PeerId}; - - /// Options to configure a dial to a known or unknown peer. - /// - /// Used in [`Swarm::dial`](crate::Swarm::dial) and - /// [`NetworkBehaviourAction::Dial`](crate::behaviour::NetworkBehaviourAction::Dial). - /// - /// To construct use either of: - /// - /// - [`DialOpts::peer_id`] dialing a known peer - /// - /// - [`DialOpts::unknown_peer_id`] dialing an unknown peer - #[derive(Debug)] - pub struct DialOpts(pub(super) Opts); - - impl DialOpts { - /// Dial a known peer. - /// - /// ``` - /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; - /// # use libp2p_core::PeerId; - /// DialOpts::peer_id(PeerId::random()) - /// .condition(PeerCondition::Disconnected) - /// .addresses(vec!["/ip6/::1/tcp/12345".parse().unwrap()]) - /// .extend_addresses_through_behaviour() - /// .build(); - /// ``` - pub fn peer_id(peer_id: PeerId) -> WithPeerId { - WithPeerId { - peer_id, - condition: Default::default(), - } - } - - /// Dial an unknown peer. - /// - /// ``` - /// # use libp2p_swarm::dial_opts::DialOpts; - /// DialOpts::unknown_peer_id() - /// .address("/ip6/::1/tcp/12345".parse().unwrap()) - /// .build(); - /// ``` - pub fn unknown_peer_id() -> WithoutPeerId { - WithoutPeerId {} - } - - /// Get the [`PeerId`] specified in a [`DialOpts`] if any. - pub fn get_peer_id(&self) -> Option { - match self { - DialOpts(Opts::WithPeerId(WithPeerId { peer_id, .. })) => Some(*peer_id), - DialOpts(Opts::WithPeerIdWithAddresses(WithPeerIdWithAddresses { - peer_id, - .. - })) => Some(*peer_id), - DialOpts(Opts::WithoutPeerIdWithAddress(_)) => None, - } - } - } - - /// Internal options type. - /// - /// Not to be constructed manually. Use either of the below instead: - /// - /// - [`DialOpts::peer_id`] dialing a known peer - /// - [`DialOpts::unknown_peer_id`] dialing an unknown peer - #[derive(Debug)] - pub(super) enum Opts { - WithPeerId(WithPeerId), - WithPeerIdWithAddresses(WithPeerIdWithAddresses), - WithoutPeerIdWithAddress(WithoutPeerIdWithAddress), - } - - #[derive(Debug)] - pub struct WithPeerId { - pub(crate) peer_id: PeerId, - pub(crate) condition: PeerCondition, - } - - impl WithPeerId { - /// Specify a [`PeerCondition`] for the dial. - pub fn condition(mut self, condition: PeerCondition) -> Self { - self.condition = condition; - self - } - - /// Specify a set of addresses to be used to dial the known peer. - pub fn addresses(self, addresses: Vec) -> WithPeerIdWithAddresses { - WithPeerIdWithAddresses { - peer_id: self.peer_id, - condition: self.condition, - addresses, - extend_addresses_through_behaviour: false, - } - } - - /// Build the final [`DialOpts`]. - /// - /// Addresses to dial the peer are retrieved via - /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer). - pub fn build(self) -> DialOpts { - DialOpts(Opts::WithPeerId(self)) - } - } - - #[derive(Debug)] - pub struct WithPeerIdWithAddresses { - pub(crate) peer_id: PeerId, - pub(crate) condition: PeerCondition, - pub(crate) addresses: Vec, - pub(crate) extend_addresses_through_behaviour: bool, - } - - impl WithPeerIdWithAddresses { - /// Specify a [`PeerCondition`] for the dial. - pub fn condition(mut self, condition: PeerCondition) -> Self { - self.condition = condition; - self - } - - /// In addition to the provided addresses, extend the set via - /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer). - pub fn extend_addresses_through_behaviour(mut self) -> Self { - self.extend_addresses_through_behaviour = true; - self - } - - /// Build the final [`DialOpts`]. - pub fn build(self) -> DialOpts { - DialOpts(Opts::WithPeerIdWithAddresses(self)) - } - } - - #[derive(Debug)] - pub struct WithoutPeerId {} - - impl WithoutPeerId { - /// Specify a single address to dial the unknown peer. - pub fn address(self, address: Multiaddr) -> WithoutPeerIdWithAddress { - WithoutPeerIdWithAddress { address } - } - } - - #[derive(Debug)] - pub struct WithoutPeerIdWithAddress { - pub(crate) address: Multiaddr, - } - - impl WithoutPeerIdWithAddress { - /// Build the final [`DialOpts`]. - pub fn build(self) -> DialOpts { - DialOpts(Opts::WithoutPeerIdWithAddress(self)) - } - } - - /// The available conditions under which a new dialing attempt to - /// a known peer is initiated. - /// - /// ``` - /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; - /// # use libp2p_core::PeerId; - /// # - /// DialOpts::peer_id(PeerId::random()) - /// .condition(PeerCondition::Disconnected) - /// .build(); - /// ``` - #[derive(Debug, Copy, Clone)] - pub enum PeerCondition { - /// A new dialing attempt is initiated _only if_ the peer is currently - /// considered disconnected, i.e. there is no established connection - /// and no ongoing dialing attempt. - /// - /// If there is an ongoing dialing attempt, the addresses reported by - /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) - /// are added to the ongoing dialing attempt, ignoring duplicates. - Disconnected, - /// A new dialing attempt is initiated _only if_ there is currently - /// no ongoing dialing attempt, i.e. the peer is either considered - /// disconnected or connected but without an ongoing dialing attempt. - /// - /// If there is an ongoing dialing attempt, the addresses reported by - /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) - /// are added to the ongoing dialing attempt, ignoring duplicates. - NotDialing, - /// A new dialing attempt is always initiated, only subject to the - /// configured connection limits. - Always, - } - - impl Default for PeerCondition { - fn default() -> Self { - PeerCondition::Disconnected - } - } -} From eab21a6f34713dd218cc0567126e6c07fc39ce73 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Tue, 9 Nov 2021 13:36:32 +0000 Subject: [PATCH 19/27] swarm/src/dial_opts: Remove outdated comment --- swarm/src/dial_opts.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/swarm/src/dial_opts.rs b/swarm/src/dial_opts.rs index 97e204151ed..79e05c213d1 100644 --- a/swarm/src/dial_opts.rs +++ b/swarm/src/dial_opts.rs @@ -188,18 +188,10 @@ pub enum PeerCondition { /// A new dialing attempt is initiated _only if_ the peer is currently /// considered disconnected, i.e. there is no established connection /// and no ongoing dialing attempt. - /// - /// If there is an ongoing dialing attempt, the addresses reported by - /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) - /// are added to the ongoing dialing attempt, ignoring duplicates. Disconnected, /// A new dialing attempt is initiated _only if_ there is currently /// no ongoing dialing attempt, i.e. the peer is either considered /// disconnected or connected but without an ongoing dialing attempt. - /// - /// If there is an ongoing dialing attempt, the addresses reported by - /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer) - /// are added to the ongoing dialing attempt, ignoring duplicates. NotDialing, /// A new dialing attempt is always initiated, only subject to the /// configured connection limits. From 5e3edb3bf4c9dcbd5fb5fac8ecfd0b14b956d82b Mon Sep 17 00:00:00 2001 From: Max Inden Date: Sun, 14 Nov 2021 22:02:37 +0000 Subject: [PATCH 20/27] swarm/src/dial_opts: Implement From for DialOpts --- examples/chat-tokio.rs | 2 +- examples/chat.rs | 2 +- examples/file-sharing.rs | 9 +- examples/gossipsub-chat.rs | 2 +- examples/ipfs-private.rs | 2 +- examples/ping.rs | 2 +- misc/metrics/examples/metrics.rs | 2 +- protocols/gossipsub/tests/smoke.rs | 8 +- protocols/identify/src/identify.rs | 12 +- protocols/ping/tests/ping.rs | 24 +--- protocols/relay/examples/relay.rs | 6 +- protocols/relay/src/lib.rs | 2 +- protocols/relay/tests/lib.rs | 112 +++--------------- protocols/rendezvous/examples/discover.rs | 10 +- protocols/rendezvous/examples/register.rs | 8 +- .../examples/register_with_identify.rs | 8 +- protocols/rendezvous/tests/harness/mod.rs | 7 +- src/tutorial.rs | 4 +- swarm/CHANGELOG.md | 9 +- swarm/src/dial_opts.rs | 6 + swarm/src/lib.rs | 40 ++----- 21 files changed, 62 insertions(+), 215 deletions(-) diff --git a/examples/chat-tokio.rs b/examples/chat-tokio.rs index 2e4b5158a80..47dbb4341ba 100644 --- a/examples/chat-tokio.rs +++ b/examples/chat-tokio.rs @@ -148,7 +148,7 @@ async fn main() -> Result<(), Box> { // Reach out to another node if specified if let Some(to_dial) = std::env::args().nth(1) { let addr: Multiaddr = to_dial.parse()?; - swarm.dial(DialOpts::unknown_peer_id().address(addr).build())?; + swarm.dial(addr)?; println!("Dialed {:?}", to_dial) } diff --git a/examples/chat.rs b/examples/chat.rs index cd0be5a573a..8113d78dbcf 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -128,7 +128,7 @@ async fn main() -> Result<(), Box> { // Reach out to another node if specified if let Some(to_dial) = std::env::args().nth(1) { let addr: Multiaddr = to_dial.parse()?; - swarm.dial(DialOpts::unknown_peer_id().address(addr).build())?; + swarm.dial(addr)?; println!("Dialed {:?}", to_dial) } diff --git a/examples/file-sharing.rs b/examples/file-sharing.rs index 482792517d4..8798eaa5539 100644 --- a/examples/file-sharing.rs +++ b/examples/file-sharing.rs @@ -523,11 +523,10 @@ mod network { .behaviour_mut() .kademlia .add_address(&peer_id, peer_addr.clone()); - match self.swarm.dial( - DialOpts::unknown_peer_id() - .address(peer_addr.with(Protocol::P2p(peer_id.into()))) - .build(), - ) { + match self + .swarm + .dial(peer_addr.with(Protocol::P2p(peer_id.into()))) + { Ok(()) => { self.pending_dial.insert(peer_id, sender); } diff --git a/examples/gossipsub-chat.rs b/examples/gossipsub-chat.rs index 9e4415facf9..21d6ae440a1 100644 --- a/examples/gossipsub-chat.rs +++ b/examples/gossipsub-chat.rs @@ -128,7 +128,7 @@ async fn main() -> Result<(), Box> { if let Some(to_dial) = std::env::args().nth(1) { let dialing = to_dial.clone(); match to_dial.parse() { - Ok(to_dial) => match swarm.dial(DialOpts::unknown_peer_id().address(to_dial).build()) { + Ok(to_dial) => match swarm.dial(to_dial) { Ok(_) => println!("Dialed {:?}", dialing), Err(e) => println!("Dial {:?} failed: {:?}", dialing, e), }, diff --git a/examples/ipfs-private.rs b/examples/ipfs-private.rs index 8d79e91bb46..15f34d1c9db 100644 --- a/examples/ipfs-private.rs +++ b/examples/ipfs-private.rs @@ -265,7 +265,7 @@ fn main() -> Result<(), Box> { // Reach out to other nodes if specified for to_dial in std::env::args().skip(1) { let addr: Multiaddr = parse_legacy_multiaddr(&to_dial)?; - swarm.dial(DialOpts::unknown_peer_id().address(addr).build())?; + swarm.dial(addr)?; println!("Dialed {:?}", to_dial) } diff --git a/examples/ping.rs b/examples/ping.rs index 63bd628a2da..73afc17dabe 100644 --- a/examples/ping.rs +++ b/examples/ping.rs @@ -71,7 +71,7 @@ fn main() -> Result<(), Box> { // command-line argument, if any. if let Some(addr) = std::env::args().nth(1) { let remote = addr.parse()?; - swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; + swarm.dial(remote)?; println!("Dialed {}", addr) } diff --git a/misc/metrics/examples/metrics.rs b/misc/metrics/examples/metrics.rs index cec6578c2a3..dec81f1e0ed 100644 --- a/misc/metrics/examples/metrics.rs +++ b/misc/metrics/examples/metrics.rs @@ -75,7 +75,7 @@ fn main() -> Result<(), Box> { swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?; if let Some(addr) = std::env::args().nth(1) { let remote = addr.parse()?; - swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; + swarm.dial(remote)?; tide::log::info!("Dialed {}", addr) } diff --git a/protocols/gossipsub/tests/smoke.rs b/protocols/gossipsub/tests/smoke.rs index 4bebb3865d2..f4345ed3160 100644 --- a/protocols/gossipsub/tests/smoke.rs +++ b/protocols/gossipsub/tests/smoke.rs @@ -98,13 +98,7 @@ impl Graph { p2p_suffix_connected.unwrap() ); - next.1 - .dial( - DialOpts::unknown_peer_id() - .address(connected_addr_no_p2p) - .build(), - ) - .unwrap(); + next.1.dial(connected_addr_no_p2p).unwrap(); connected_nodes.push(next); } diff --git a/protocols/identify/src/identify.rs b/protocols/identify/src/identify.rs index b7619379573..50d07ad2c83 100644 --- a/protocols/identify/src/identify.rs +++ b/protocols/identify/src/identify.rs @@ -563,9 +563,7 @@ mod tests { } } }); - swarm2 - .dial(DialOpts::unknown_peer_id().address(listen_addr).build()) - .unwrap(); + swarm2.dial(listen_addr).unwrap(); // nb. Either swarm may receive the `Identified` event first, upon which // it will permit the connection to be closed, as defined by @@ -645,9 +643,7 @@ mod tests { } }); - swarm2 - .dial(DialOpts::unknown_peer_id().address(listen_addr).build()) - .unwrap(); + swarm2.dial(listen_addr).unwrap(); async_std::task::block_on(async move { loop { @@ -734,9 +730,7 @@ mod tests { } }); - swarm2 - .dial(DialOpts::unknown_peer_id().address(listen_addr).build()) - .unwrap(); + swarm2.dial(listen_addr).unwrap(); // Wait until we identified. async_std::task::block_on(async { diff --git a/protocols/ping/tests/ping.rs b/protocols/ping/tests/ping.rs index d9c74711b4b..3a7acd72fb1 100644 --- a/protocols/ping/tests/ping.rs +++ b/protocols/ping/tests/ping.rs @@ -82,13 +82,7 @@ fn ping_pong() { let pid2 = peer2_id.clone(); let peer2 = async move { - swarm2 - .dial( - DialOpts::unknown_peer_id() - .address(rx.next().await.unwrap()) - .build(), - ) - .unwrap(); + swarm2.dial(rx.next().await.unwrap()).unwrap(); loop { match swarm2.select_next_some().await { @@ -162,13 +156,7 @@ fn max_failures() { }; let peer2 = async move { - swarm2 - .dial( - DialOpts::unknown_peer_id() - .address(rx.next().await.unwrap()) - .build(), - ) - .unwrap(); + swarm2.dial(rx.next().await.unwrap()).unwrap(); let mut count2: u8 = 0; @@ -228,13 +216,7 @@ fn unsupported_doesnt_fail() { }); let result = async_std::task::block_on(async move { - swarm2 - .dial( - DialOpts::unknown_peer_id() - .address(rx.next().await.unwrap()) - .build(), - ) - .unwrap(); + swarm2.dial(rx.next().await.unwrap()).unwrap(); loop { match swarm2.select_next_some().await { diff --git a/protocols/relay/examples/relay.rs b/protocols/relay/examples/relay.rs index 8961d5a43d5..216ab7f86bb 100644 --- a/protocols/relay/examples/relay.rs +++ b/protocols/relay/examples/relay.rs @@ -130,11 +130,7 @@ fn main() -> Result<(), Box> { } Mode::ClientDial => { let client_listen_address = get_client_listen_address(&opt); - swarm.dial( - DialOpts::unknown_peer_id() - .address(client_listen_address.parse()?) - .build(), - )?; + swarm.dial(client_listen_address.parse()?)?; println!("starting as client dialer on {}", client_listen_address); } } diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index a344df69b3a..1b40b52f4fd 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -62,7 +62,7 @@ //! swarm.listen_on(relay_addr).unwrap(); //! //! // Dial node (5678) via relay node (1234). -//! swarm.dial(DialOpts::unknown_peer_id().address(dst_addr).build()).unwrap(); +//! swarm.dial(dst_addr).unwrap(); //! ``` //! //! ## Terminology diff --git a/protocols/relay/tests/lib.rs b/protocols/relay/tests/lib.rs index f4613b8e729..c316f06a8fc 100644 --- a/protocols/relay/tests/lib.rs +++ b/protocols/relay/tests/lib.rs @@ -146,13 +146,7 @@ fn src_connect_to_dst_listening_via_relay() { } }; - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay).unwrap(); let src = async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -227,13 +221,7 @@ fn src_connect_to_dst_not_listening_via_active_relay() { dst_swarm.listen_on(Protocol::P2pCircuit.into()).unwrap(); spawn_swarm_on_pool(&pool, dst_swarm); - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay).unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -319,9 +307,7 @@ fn src_connect_to_dst_via_established_connection_to_relay() { spawn_swarm_on_pool(&pool, dst_swarm); pool.run_until(async move { - src_swarm - .dial(DialOpts::unknown_peer_id().address(relay_addr).build()) - .unwrap(); + src_swarm.dial(relay_addr).unwrap(); // Source Node establishing connection to Relay. loop { @@ -335,13 +321,7 @@ fn src_connect_to_dst_via_established_connection_to_relay() { } } - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay).unwrap(); // Source Node establishing connection to destination node via Relay. loop { @@ -395,13 +375,7 @@ fn src_try_connect_to_offline_dst() { relay_swarm.listen_on(relay_addr.clone()).unwrap(); spawn_swarm_on_pool(&pool, relay_swarm); - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay.clone()) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay.clone()).unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -459,13 +433,7 @@ fn src_try_connect_to_unsupported_dst() { dst_swarm.listen_on(dst_addr.clone()).unwrap(); spawn_swarm_on_pool(&pool, dst_swarm); - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay.clone()) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay.clone()).unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -516,13 +484,7 @@ fn src_try_connect_to_offline_dst_via_offline_relay() { .with(dst_addr.into_iter().next().unwrap()) .with(Protocol::P2p(dst_peer_id.clone().into())); - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay.clone()) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay.clone()).unwrap(); pool.run_until(async move { // Source Node dialing Relay to connect to Destination Node. match src_swarm.select_next_some().await { @@ -799,9 +761,7 @@ fn inactive_connection_timeout() { spawn_swarm_on_pool(&pool, dst_swarm); pool.run_until(async move { - src_swarm - .dial(DialOpts::unknown_peer_id().address(relay_addr).build()) - .unwrap(); + src_swarm.dial(relay_addr).unwrap(); // Source Node dialing Relay. loop { match src_swarm.select_next_some().await { @@ -813,13 +773,7 @@ fn inactive_connection_timeout() { } } - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay).unwrap(); // Source Node establishing connection to destination node via Relay. match src_swarm.select_next_some().await { @@ -887,20 +841,8 @@ fn concurrent_connection_same_relay_same_dst() { spawn_swarm_on_pool(&pool, dst_swarm); pool.run_until(async move { - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay.clone()) - .build(), - ) - .unwrap(); - src_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay) - .build(), - ) - .unwrap(); + src_swarm.dial(dst_addr_via_relay.clone()).unwrap(); + src_swarm.dial(dst_addr_via_relay).unwrap(); // Source Node establishing two connections to destination node via Relay. let mut num_established = 0; @@ -1045,20 +987,8 @@ fn yield_incoming_connection_through_correct_listener() { } }); - src_1_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay_1.clone()) - .build(), - ) - .unwrap(); - src_2_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay_2.clone()) - .build(), - ) - .unwrap(); + src_1_swarm.dial(dst_addr_via_relay_1.clone()).unwrap(); + src_2_swarm.dial(dst_addr_via_relay_2.clone()).unwrap(); spawn_swarm_on_pool(&pool, src_1_swarm); spawn_swarm_on_pool(&pool, src_2_swarm); @@ -1117,13 +1047,7 @@ fn yield_incoming_connection_through_correct_listener() { // Expect destination node to reject incoming connection from unknown relay given that // destination node is not listening for such connections. - src_3_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay_3.clone()) - .build(), - ) - .unwrap(); + src_3_swarm.dial(dst_addr_via_relay_3.clone()).unwrap(); pool.run_until(async { loop { futures::select! { @@ -1193,13 +1117,7 @@ fn yield_incoming_connection_through_correct_listener() { // Expect destination node to accept incoming connection from "unknown" relay, i.e. the // connection from source node 3 via relay 3. - src_3_swarm - .dial( - DialOpts::unknown_peer_id() - .address(dst_addr_via_relay_3.clone()) - .build(), - ) - .unwrap(); + src_3_swarm.dial(dst_addr_via_relay_3.clone()).unwrap(); pool.run_until(async move { loop { match src_3_swarm.select_next_some().await { diff --git a/protocols/rendezvous/examples/discover.rs b/protocols/rendezvous/examples/discover.rs index 2a9709f42c4..687c5f253ca 100644 --- a/protocols/rendezvous/examples/discover.rs +++ b/protocols/rendezvous/examples/discover.rs @@ -55,13 +55,7 @@ async fn main() { log::info!("Local peer id: {}", swarm.local_peer_id()); - let _ = swarm - .dial( - DialOpts::unknown_peer_id() - .address(rendezvous_point_address.clone()) - .build(), - ) - .unwrap(); + let _ = swarm.dial(rendezvous_point_address.clone()).unwrap(); let mut discover_tick = tokio::time::interval(Duration::from_secs(30)); let mut cookie = None; @@ -102,7 +96,7 @@ async fn main() { address.clone() }; - swarm.dial(DialOpts::unknown_peer_id().address(address_with_p2p).build()).unwrap() + swarm.dial(address_with_p2p).unwrap() } } } diff --git a/protocols/rendezvous/examples/register.rs b/protocols/rendezvous/examples/register.rs index f6b38c14405..d83f9ccc486 100644 --- a/protocols/rendezvous/examples/register.rs +++ b/protocols/rendezvous/examples/register.rs @@ -57,13 +57,7 @@ async fn main() { let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap()); - swarm - .dial( - DialOpts::unknown_peer_id() - .address(rendezvous_point_address) - .build(), - ) - .unwrap(); + swarm.dial(rendezvous_point_address).unwrap(); while let Some(event) = swarm.next().await { match event { diff --git a/protocols/rendezvous/examples/register_with_identify.rs b/protocols/rendezvous/examples/register_with_identify.rs index 5ab746a41bd..5e781a455ce 100644 --- a/protocols/rendezvous/examples/register_with_identify.rs +++ b/protocols/rendezvous/examples/register_with_identify.rs @@ -60,13 +60,7 @@ async fn main() { let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap()); - swarm - .dial( - DialOpts::unknown_peer_id() - .address(rendezvous_point_address) - .build(), - ) - .unwrap(); + swarm.dial(rendezvous_point_address).unwrap(); while let Some(event) = swarm.next().await { match event { diff --git a/protocols/rendezvous/tests/harness/mod.rs b/protocols/rendezvous/tests/harness/mod.rs index 204f0f0e7eb..6b5a202b476 100644 --- a/protocols/rendezvous/tests/harness/mod.rs +++ b/protocols/rendezvous/tests/harness/mod.rs @@ -165,12 +165,7 @@ where { let addr_to_dial = other.external_addresses().next().unwrap().addr.clone(); - self.dial( - DialOpts::unknown_peer_id() - .address(addr_to_dial.clone()) - .build(), - ) - .unwrap(); + self.dial(addr_to_dial.clone()).unwrap(); let mut dialer_done = false; let mut listener_done = false; diff --git a/src/tutorial.rs b/src/tutorial.rs index 6d2961abd53..8f7e9cb1ad9 100644 --- a/src/tutorial.rs +++ b/src/tutorial.rs @@ -251,7 +251,7 @@ //! // command-line argument, if any. //! if let Some(addr) = std::env::args().nth(1) { //! let remote = addr.parse()?; -//! swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; +//! swarm.dial(remote)?; //! println!("Dialed {}", addr) //! } //! @@ -298,7 +298,7 @@ //! // command-line argument, if any. //! if let Some(addr) = std::env::args().nth(1) { //! let remote = addr.parse()?; -//! swarm.dial(DialOpts::unknown_peer_id().address(remote).build())?; +//! swarm.dial(remote)?; //! println!("Dialed {}", addr) //! } //! diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 1c0d2ed2662..b74607b52c3 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -10,13 +10,14 @@ Changes required to maintain status quo: - Previously `swarm.dial(peer_id)` - Now `swarm.dial(DialOpts::peer_id(swarm1_peer_id).build())` + now `swarm.dial(DialOpts::peer_id(swarm1_peer_id).build())` - Previously `swarm.dial_addr(addr)` - Now `swarm.dial(DialOpts::unknown_peer_id().address(addr).build())` + now `swarm.dial(DialOpts::unknown_peer_id().address(addr).build())` + or `swarm.dial(addr)` given that `DialOpts` implements `From`. - Previously `NetworkBehaviourAction::DialPeer { peer_id, condition, handler }` - Now + now ```rust NetworkBehaviourAction::Dial { opts: DialOpts::peer_id(peer_id) @@ -27,7 +28,7 @@ ``` - Previously `NetworkBehaviourAction::DialAddress { address, handler }` - Now + now ```rust NetworkBehaviourAction::Dial { opts: DialOpts::unknown_peer_id() diff --git a/swarm/src/dial_opts.rs b/swarm/src/dial_opts.rs index 79e05c213d1..2bc190ee48e 100644 --- a/swarm/src/dial_opts.rs +++ b/swarm/src/dial_opts.rs @@ -77,6 +77,12 @@ impl DialOpts { } } +impl From for DialOpts { + fn from(address: Multiaddr) -> Self { + DialOpts::unknown_peer_id().address(address).build() + } +} + /// Internal options type. /// /// Not to be constructed manually. Use either of the below instead: diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 1eed46eb0a8..bead5be83ce 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -347,15 +347,11 @@ where /// ); /// /// // Dial an unknown peer. - /// swarm.dial( - /// DialOpts::unknown_peer_id() - /// .address("/ip6/::1/tcp/12345".parse().unwrap()) - /// .build() - /// ); + /// swarm.dial("/ip6/::1/tcp/12345".parse().unwrap()); /// ``` - pub fn dial(&mut self, opts: DialOpts) -> Result<(), DialError> { + pub fn dial(&mut self, opts: impl Into) -> Result<(), DialError> { let handler = self.behaviour.new_handler(); - self.dial_with_handler(opts, handler) + self.dial_with_handler(opts.into(), handler) } fn dial_with_handler( @@ -1523,9 +1519,7 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1 - .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) - .unwrap(); + swarm1.dial(addr2.clone()).unwrap(); } let mut state = State::Connecting; @@ -1557,11 +1551,7 @@ mod tests { swarm2.behaviour.reset(); unbanned = true; for _ in 0..num_connections { - swarm2 - .dial( - DialOpts::unknown_peer_id().address(addr1.clone()).build(), - ) - .unwrap(); + swarm2.dial(addr1.clone()).unwrap(); } state = State::Connecting; } @@ -1604,9 +1594,7 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1 - .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) - .unwrap(); + swarm1.dial(addr2.clone()).unwrap(); } let mut state = State::Connecting; @@ -1636,9 +1624,7 @@ mod tests { swarm1.behaviour.reset(); swarm2.behaviour.reset(); for _ in 0..num_connections { - swarm2 - .dial(DialOpts::unknown_peer_id().address(addr1.clone()).build()) - .unwrap(); + swarm2.dial(addr1.clone()).unwrap(); } state = State::Connecting; } @@ -1681,9 +1667,7 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1 - .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) - .unwrap(); + swarm1.dial(addr2.clone()).unwrap(); } let mut state = State::Connecting; @@ -1716,9 +1700,7 @@ mod tests { swarm1.behaviour.reset(); swarm2.behaviour.reset(); for _ in 0..num_connections { - swarm2 - .dial(DialOpts::unknown_peer_id().address(addr1.clone()).build()) - .unwrap(); + swarm2.dial(addr1.clone()).unwrap(); } state = State::Connecting; } @@ -1760,9 +1742,7 @@ mod tests { let num_connections = 10; for _ in 0..num_connections { - swarm1 - .dial(DialOpts::unknown_peer_id().address(addr2.clone()).build()) - .unwrap(); + swarm1.dial(addr2.clone()).unwrap(); } let mut state = State::Connecting; let mut disconnected_conn_id = None; From 09293c4d9697d1d883dd69d935c481c2c8a2337c Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 15 Nov 2021 11:27:17 +0000 Subject: [PATCH 21/27] swarm/src/dial_opts: Implement From for DialOpts --- protocols/identify/src/identify.rs | 4 +--- protocols/rendezvous/tests/rendezvous.rs | 6 ++---- swarm/CHANGELOG.md | 3 ++- swarm/src/dial_opts.rs | 6 ++++++ swarm/src/lib.rs | 5 +---- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/protocols/identify/src/identify.rs b/protocols/identify/src/identify.rs index 50d07ad2c83..09859216d41 100644 --- a/protocols/identify/src/identify.rs +++ b/protocols/identify/src/identify.rs @@ -757,9 +757,7 @@ mod tests { }); // We should still be able to dial now! - swarm2 - .dial(DialOpts::peer_id(swarm1_peer_id).build()) - .unwrap(); + swarm2.dial(swarm1_peer_id).unwrap(); let connected_peer = async_std::task::block_on(async { loop { diff --git a/protocols/rendezvous/tests/rendezvous.rs b/protocols/rendezvous/tests/rendezvous.rs index 7c5cbedb2c6..7d02610a5af 100644 --- a/protocols/rendezvous/tests/rendezvous.rs +++ b/protocols/rendezvous/tests/rendezvous.rs @@ -186,7 +186,7 @@ async fn discover_allows_for_dial_by_peer_id() { let alices_peer_id = *alice.local_peer_id(); let bobs_peer_id = *bob.local_peer_id(); - bob.dial(DialOpts::peer_id(alices_peer_id).build()).unwrap(); + bob.dial(alices_peer_id).unwrap(); let alice_connected_to = tokio::spawn(async move { loop { @@ -295,9 +295,7 @@ async fn registration_on_clients_expire() { tokio::time::sleep(Duration::from_secs(registration_ttl + 5)).await; let event = bob.select_next_some().await; - let error = bob - .dial(DialOpts::peer_id(*alice.local_peer_id()).build()) - .unwrap_err(); + let error = bob.dial(*alice.local_peer_id()).unwrap_err(); assert!(matches!( event, diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index b74607b52c3..3bd29c1bf51 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -10,7 +10,8 @@ Changes required to maintain status quo: - Previously `swarm.dial(peer_id)` - now `swarm.dial(DialOpts::peer_id(swarm1_peer_id).build())` + now `swarm.dial(DialOpts::peer_id(peer_id).build())` + or `swarm.dial(peer_id)` given that `DialOpts` implements `From`. - Previously `swarm.dial_addr(addr)` now `swarm.dial(DialOpts::unknown_peer_id().address(addr).build())` diff --git a/swarm/src/dial_opts.rs b/swarm/src/dial_opts.rs index 2bc190ee48e..ae41be17ef9 100644 --- a/swarm/src/dial_opts.rs +++ b/swarm/src/dial_opts.rs @@ -83,6 +83,12 @@ impl From for DialOpts { } } +impl From for DialOpts { + fn from(peer_id: PeerId) -> Self { + DialOpts::peer_id(peer_id).build() + } +} + /// Internal options type. /// /// Not to be constructed manually. Use either of the below instead: diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index bead5be83ce..7f00bd8d395 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -341,10 +341,7 @@ where /// ); /// /// // Dial a known peer. - /// swarm.dial( - /// DialOpts::peer_id(PeerId::random()) - /// .build() - /// ); + /// swarm.dial(PeerId::random()); /// /// // Dial an unknown peer. /// swarm.dial("/ip6/::1/tcp/12345".parse().unwrap()); From 8d9b5485f8ffaeeeda51d70354394f3ed3ddb41d Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 15 Nov 2021 11:58:06 +0000 Subject: [PATCH 22/27] misc/metrics: Fix type inference --- misc/metrics/examples/metrics.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/misc/metrics/examples/metrics.rs b/misc/metrics/examples/metrics.rs index dec81f1e0ed..a8bdb0a270a 100644 --- a/misc/metrics/examples/metrics.rs +++ b/misc/metrics/examples/metrics.rs @@ -50,9 +50,10 @@ use futures::executor::block_on; use futures::stream::StreamExt; +use libp2p::core::Multiaddr; use libp2p::metrics::{Metrics, Recorder}; use libp2p::ping::{Ping, PingConfig}; -use libp2p::swarm::{dial_opts::DialOpts, SwarmEvent}; +use libp2p::swarm::SwarmEvent; use libp2p::{identity, PeerId, Swarm}; use open_metrics_client::encoding::text::encode; use open_metrics_client::registry::Registry; @@ -74,7 +75,7 @@ fn main() -> Result<(), Box> { ); swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?; if let Some(addr) = std::env::args().nth(1) { - let remote = addr.parse()?; + let remote: Multiaddr = addr.parse()?; swarm.dial(remote)?; tide::log::info!("Dialed {}", addr) } From 1562159566b29166d39be85bb37ea479c4156ce5 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 15 Nov 2021 12:06:40 +0000 Subject: [PATCH 23/27] examples: Help type inference --- examples/chat.rs | 2 +- examples/file-sharing.rs | 2 +- examples/gossipsub-chat.rs | 17 +++++++---------- examples/ipfs-private.rs | 2 +- examples/ping.rs | 6 +++--- 5 files changed, 13 insertions(+), 16 deletions(-) diff --git a/examples/chat.rs b/examples/chat.rs index 8113d78dbcf..a343bc862a0 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -55,7 +55,7 @@ use libp2p::{ floodsub::{self, Floodsub, FloodsubEvent}, identity, mdns::{Mdns, MdnsConfig, MdnsEvent}, - swarm::{dial_opts::DialOpts, SwarmEvent}, + swarm::{SwarmEvent}, Multiaddr, NetworkBehaviour, PeerId, Swarm, }; use std::{ diff --git a/examples/file-sharing.rs b/examples/file-sharing.rs index 8798eaa5539..c1d203aac84 100644 --- a/examples/file-sharing.rs +++ b/examples/file-sharing.rs @@ -217,7 +217,7 @@ mod network { ProtocolSupport, RequestId, RequestResponse, RequestResponseCodec, RequestResponseEvent, RequestResponseMessage, ResponseChannel, }; - use libp2p::swarm::{dial_opts::DialOpts, ProtocolsHandlerUpgrErr, SwarmBuilder, SwarmEvent}; + use libp2p::swarm::{ProtocolsHandlerUpgrErr, SwarmBuilder, SwarmEvent}; use libp2p::{NetworkBehaviour, Swarm}; use std::collections::{HashMap, HashSet}; use std::iter; diff --git a/examples/gossipsub-chat.rs b/examples/gossipsub-chat.rs index 21d6ae440a1..b102c546398 100644 --- a/examples/gossipsub-chat.rs +++ b/examples/gossipsub-chat.rs @@ -55,8 +55,8 @@ use libp2p::gossipsub::{ }; use libp2p::{ gossipsub, identity, - swarm::{dial_opts::DialOpts, SwarmEvent}, - PeerId, + swarm::{SwarmEvent}, + Multiaddr, PeerId, }; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -126,14 +126,11 @@ async fn main() -> Result<(), Box> { // Reach out to another node if specified if let Some(to_dial) = std::env::args().nth(1) { - let dialing = to_dial.clone(); - match to_dial.parse() { - Ok(to_dial) => match swarm.dial(to_dial) { - Ok(_) => println!("Dialed {:?}", dialing), - Err(e) => println!("Dial {:?} failed: {:?}", dialing, e), - }, - Err(err) => println!("Failed to parse address to dial: {:?}", err), - } + let address: Multiaddr = to_dial.parse().expect("User to provide valid address."); + match swarm.dial(address.clone()) { + Ok(_) => println!("Dialed {:?}", address), + Err(e) => println!("Dial {:?} failed: {:?}", address, e), + }; } // Read full lines from stdin diff --git a/examples/ipfs-private.rs b/examples/ipfs-private.rs index 15f34d1c9db..4b44ad3f40a 100644 --- a/examples/ipfs-private.rs +++ b/examples/ipfs-private.rs @@ -43,7 +43,7 @@ use libp2p::{ multiaddr::Protocol, noise, ping, pnet::{PnetConfig, PreSharedKey}, - swarm::{dial_opts::DialOpts, NetworkBehaviourEventProcess, SwarmEvent}, + swarm::{NetworkBehaviourEventProcess, SwarmEvent}, tcp::TcpConfig, yamux::YamuxConfig, Multiaddr, NetworkBehaviour, PeerId, Swarm, Transport, diff --git a/examples/ping.rs b/examples/ping.rs index 73afc17dabe..6a4523b4d77 100644 --- a/examples/ping.rs +++ b/examples/ping.rs @@ -42,8 +42,8 @@ use futures::executor::block_on; use futures::prelude::*; -use libp2p::swarm::{dial_opts::DialOpts, Swarm, SwarmEvent}; -use libp2p::{identity, ping, PeerId}; +use libp2p::swarm::{Swarm, SwarmEvent}; +use libp2p::{identity, ping, Multiaddr, PeerId}; use std::error::Error; use std::task::Poll; @@ -70,7 +70,7 @@ fn main() -> Result<(), Box> { // Dial the peer identified by the multi-address given as the second // command-line argument, if any. if let Some(addr) = std::env::args().nth(1) { - let remote = addr.parse()?; + let remote: Multiaddr = addr.parse()?; swarm.dial(remote)?; println!("Dialed {}", addr) } From d11a4edf832a7ea03d3446099e8baf11b59fb80c Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 15 Nov 2021 12:23:14 +0000 Subject: [PATCH 24/27] protocols/.*/examples: Run cargo fix --- protocols/relay/examples/relay.rs | 8 ++++---- protocols/rendezvous/examples/discover.rs | 2 +- protocols/rendezvous/examples/register.rs | 2 +- protocols/rendezvous/examples/register_with_identify.rs | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/protocols/relay/examples/relay.rs b/protocols/relay/examples/relay.rs index 216ab7f86bb..04517f7a066 100644 --- a/protocols/relay/examples/relay.rs +++ b/protocols/relay/examples/relay.rs @@ -62,10 +62,10 @@ use futures::stream::StreamExt; use libp2p::dns::DnsConfig; use libp2p::plaintext; use libp2p::relay::{Relay, RelayConfig}; -use libp2p::swarm::{dial_opts::DialOpts, SwarmEvent}; +use libp2p::swarm::{SwarmEvent}; use libp2p::tcp::TcpConfig; use libp2p::Transport; -use libp2p::{core::upgrade, identity::ed25519, ping}; +use libp2p::{core::upgrade, identity::ed25519, ping, Multiaddr}; use libp2p::{identity, NetworkBehaviour, PeerId, Swarm}; use std::error::Error; use std::task::{Context, Poll}; @@ -129,8 +129,8 @@ fn main() -> Result<(), Box> { println!("starting client listener via relay on {}", &relay_address); } Mode::ClientDial => { - let client_listen_address = get_client_listen_address(&opt); - swarm.dial(client_listen_address.parse()?)?; + let client_listen_address: Multiaddr = get_client_listen_address(&opt).parse()?; + swarm.dial(client_listen_address.clone())?; println!("starting as client dialer on {}", client_listen_address); } } diff --git a/protocols/rendezvous/examples/discover.rs b/protocols/rendezvous/examples/discover.rs index 687c5f253ca..8d147cba3d3 100644 --- a/protocols/rendezvous/examples/discover.rs +++ b/protocols/rendezvous/examples/discover.rs @@ -23,7 +23,7 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::multiaddr::Protocol; use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess}; -use libp2p::swarm::{dial_opts::DialOpts, SwarmEvent}; +use libp2p::swarm::{SwarmEvent}; use libp2p::Swarm; use libp2p::{development_transport, rendezvous, Multiaddr}; use std::time::Duration; diff --git a/protocols/rendezvous/examples/register.rs b/protocols/rendezvous/examples/register.rs index d83f9ccc486..9c21874d50c 100644 --- a/protocols/rendezvous/examples/register.rs +++ b/protocols/rendezvous/examples/register.rs @@ -22,7 +22,7 @@ use futures::StreamExt; use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess}; -use libp2p::swarm::{dial_opts::DialOpts, Swarm, SwarmEvent}; +use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::{development_transport, rendezvous}; use libp2p::{Multiaddr, NetworkBehaviour}; use libp2p_swarm::AddressScore; diff --git a/protocols/rendezvous/examples/register_with_identify.rs b/protocols/rendezvous/examples/register_with_identify.rs index 5e781a455ce..3896db3e3d1 100644 --- a/protocols/rendezvous/examples/register_with_identify.rs +++ b/protocols/rendezvous/examples/register_with_identify.rs @@ -23,7 +23,7 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent}; use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess}; -use libp2p::swarm::{dial_opts::DialOpts, Swarm, SwarmEvent}; +use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::{development_transport, rendezvous}; use libp2p::{Multiaddr, NetworkBehaviour}; use std::time::Duration; From 03ef106c0d36b4701c51e2e48e93ade7ca7fc1ac Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 15 Nov 2021 12:24:51 +0000 Subject: [PATCH 25/27] *: Run cargo fmt --- examples/chat.rs | 2 +- examples/gossipsub-chat.rs | 6 +----- protocols/relay/examples/relay.rs | 2 +- protocols/rendezvous/examples/discover.rs | 2 +- 4 files changed, 4 insertions(+), 8 deletions(-) diff --git a/examples/chat.rs b/examples/chat.rs index a343bc862a0..bdafde20a19 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -55,7 +55,7 @@ use libp2p::{ floodsub::{self, Floodsub, FloodsubEvent}, identity, mdns::{Mdns, MdnsConfig, MdnsEvent}, - swarm::{SwarmEvent}, + swarm::SwarmEvent, Multiaddr, NetworkBehaviour, PeerId, Swarm, }; use std::{ diff --git a/examples/gossipsub-chat.rs b/examples/gossipsub-chat.rs index b102c546398..fdd477bfe4b 100644 --- a/examples/gossipsub-chat.rs +++ b/examples/gossipsub-chat.rs @@ -53,11 +53,7 @@ use libp2p::gossipsub::MessageId; use libp2p::gossipsub::{ GossipsubEvent, GossipsubMessage, IdentTopic as Topic, MessageAuthenticity, ValidationMode, }; -use libp2p::{ - gossipsub, identity, - swarm::{SwarmEvent}, - Multiaddr, PeerId, -}; +use libp2p::{gossipsub, identity, swarm::SwarmEvent, Multiaddr, PeerId}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; diff --git a/protocols/relay/examples/relay.rs b/protocols/relay/examples/relay.rs index 04517f7a066..0cd421959f8 100644 --- a/protocols/relay/examples/relay.rs +++ b/protocols/relay/examples/relay.rs @@ -62,7 +62,7 @@ use futures::stream::StreamExt; use libp2p::dns::DnsConfig; use libp2p::plaintext; use libp2p::relay::{Relay, RelayConfig}; -use libp2p::swarm::{SwarmEvent}; +use libp2p::swarm::SwarmEvent; use libp2p::tcp::TcpConfig; use libp2p::Transport; use libp2p::{core::upgrade, identity::ed25519, ping, Multiaddr}; diff --git a/protocols/rendezvous/examples/discover.rs b/protocols/rendezvous/examples/discover.rs index 8d147cba3d3..ceca71c6c4c 100644 --- a/protocols/rendezvous/examples/discover.rs +++ b/protocols/rendezvous/examples/discover.rs @@ -23,7 +23,7 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::multiaddr::Protocol; use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess}; -use libp2p::swarm::{SwarmEvent}; +use libp2p::swarm::SwarmEvent; use libp2p::Swarm; use libp2p::{development_transport, rendezvous, Multiaddr}; use std::time::Duration; From 8415ba2a9f363ad4314bdd937e7ccc0ca9ec25e9 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 15 Nov 2021 12:53:32 +0000 Subject: [PATCH 26/27] src/tutorial: Fix type inference --- src/tutorial.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tutorial.rs b/src/tutorial.rs index 8f7e9cb1ad9..966bc6d39f2 100644 --- a/src/tutorial.rs +++ b/src/tutorial.rs @@ -222,7 +222,7 @@ //! //! ```rust //! use futures::executor::block_on; -//! use libp2p::{identity, PeerId}; +//! use libp2p::{identity, Multiaddr, PeerId}; //! use libp2p::ping::{Ping, PingConfig}; //! use libp2p::swarm::{Swarm, dial_opts::DialOpts}; //! use std::error::Error; @@ -250,7 +250,7 @@ //! // Dial the peer identified by the multi-address given as the second //! // command-line argument, if any. //! if let Some(addr) = std::env::args().nth(1) { -//! let remote = addr.parse()?; +//! let remote: Multiaddr = addr.parse()?; //! swarm.dial(remote)?; //! println!("Dialed {}", addr) //! } @@ -270,7 +270,7 @@ //! use futures::prelude::*; //! use libp2p::ping::{Ping, PingConfig}; //! use libp2p::swarm::{Swarm, SwarmEvent, dial_opts::DialOpts}; -//! use libp2p::{identity, PeerId}; +//! use libp2p::{identity, Multiaddr, PeerId}; //! use std::error::Error; //! use std::task::Poll; //! @@ -297,7 +297,7 @@ //! // Dial the peer identified by the multi-address given as the second //! // command-line argument, if any. //! if let Some(addr) = std::env::args().nth(1) { -//! let remote = addr.parse()?; +//! let remote: Multiaddr = addr.parse()?; //! swarm.dial(remote)?; //! println!("Dialed {}", addr) //! } From 9ada8688780e1768c2b2d8d2649df3d5bf7fc26a Mon Sep 17 00:00:00 2001 From: Max Inden Date: Mon, 15 Nov 2021 12:58:40 +0000 Subject: [PATCH 27/27] swarm/src/lib: Help type inference --- swarm/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 7f00bd8d395..0059a21a0cb 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -330,7 +330,7 @@ where /// ``` /// # use libp2p_swarm::Swarm; /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; - /// # use libp2p_core::{PeerId, Transport}; + /// # use libp2p_core::{Multiaddr, PeerId, Transport}; /// # use libp2p_core::transport::dummy::DummyTransport; /// # use libp2p_swarm::DummyBehaviour; /// # @@ -344,7 +344,7 @@ where /// swarm.dial(PeerId::random()); /// /// // Dial an unknown peer. - /// swarm.dial("/ip6/::1/tcp/12345".parse().unwrap()); + /// swarm.dial("/ip6/::1/tcp/12345".parse::().unwrap()); /// ``` pub fn dial(&mut self, opts: impl Into) -> Result<(), DialError> { let handler = self.behaviour.new_handler();