From 8502645381372a919f0814a5f80a9afc7ac9bf32 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 20 Aug 2024 18:35:28 +0300 Subject: [PATCH 01/30] identify: Expose API to inject listen addresses Signed-off-by: Alexandru Vasile --- src/protocol/libp2p/identify.rs | 69 ++++++++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 10 deletions(-) diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 30117e87..203a3a77 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -33,12 +33,14 @@ use crate::{ use futures::{future::BoxFuture, stream::FuturesUnordered, Stream, StreamExt}; use multiaddr::Multiaddr; +use parking_lot::RwLock; use prost::Message; use tokio::sync::mpsc::{channel, Sender}; use tokio_stream::wrappers::ReceiverStream; use std::{ collections::{HashMap, HashSet}, + sync::Arc, time::Duration, }; @@ -62,6 +64,48 @@ mod identify_schema { include!(concat!(env!("OUT_DIR"), "/identify.rs")); } +/// Set of the public addresses of the local node. +/// +/// These addresses are reported to the identify protocol. +#[derive(Debug, Clone)] +pub struct IdentifyPublicAddresses { + inner: Arc>>, +} + +impl IdentifyPublicAddresses { + /// Create new [`IdentifyPublicAddresses`]. + fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(HashSet::new())), + } + } + + /// Add public address. + pub fn add(&self, address: Multiaddr) { + self.inner.write().insert(address); + } + + /// Remove public address. + pub fn remove(&self, address: &Multiaddr) { + self.inner.write().remove(address); + } + + /// Get public addresses. + pub fn get_addresses(&self) -> Vec { + self.inner.read().iter().cloned().collect() + } + + /// Get public addresses in the identify raw format. + fn get_raw_addresses(&self) -> Vec> { + self.inner.read().iter().map(|address| address.to_vec()).collect() + } + + /// Extend public addresses. + pub fn extend(&self, addresses: impl IntoIterator) { + self.inner.write().extend(addresses); + } +} + /// Identify configuration. pub struct Config { /// Protocol name. @@ -80,7 +124,7 @@ pub struct Config { pub(crate) protocols: Vec, /// Public addresses. - pub(crate) public_addresses: Vec, + pub(crate) public_addresses: IdentifyPublicAddresses, /// Protocol version. pub(crate) protocol_version: String, @@ -98,20 +142,27 @@ impl Config { protocol_version: String, user_agent: Option, public_addresses: Vec, - ) -> (Self, Box + Send + Unpin>) { + ) -> ( + Self, + IdentifyPublicAddresses, + Box + Send + Unpin>, + ) { let (tx_event, rx_event) = channel(DEFAULT_CHANNEL_SIZE); + let identify_public_addresses = IdentifyPublicAddresses::new(); + identify_public_addresses.extend(public_addresses); ( Self { tx_event, public: None, - public_addresses, + public_addresses: identify_public_addresses.clone(), protocol_version, user_agent, codec: ProtocolCodec::UnsignedVarint(Some(IDENTIFY_PAYLOAD_SIZE)), protocols: Vec::new(), protocol: ProtocolName::from(PROTOCOL_NAME), }, + identify_public_addresses, Box::new(ReceiverStream::new(rx_event)), ) } @@ -183,7 +234,7 @@ pub(crate) struct Identify { user_agent: String, /// Public addresses. - listen_addresses: HashSet, + listen_addresses: IdentifyPublicAddresses, /// Protocols supported by the local node, filled by `Litep2p`. protocols: Vec, @@ -205,11 +256,13 @@ impl Identify { config: Config, listen_addresses: Vec, ) -> Self { + config.public_addresses.extend(listen_addresses); + Self { service, tx: config.tx_event, peers: HashMap::new(), - listen_addresses: config.public_addresses.into_iter().chain(listen_addresses).collect(), + listen_addresses: config.public_addresses, public: config.public.expect("public key to be supplied"), protocol_version: config.protocol_version, user_agent: config.user_agent.unwrap_or(DEFAULT_AGENT.to_string()), @@ -269,11 +322,7 @@ impl Identify { protocol_version: Some(self.protocol_version.clone()), agent_version: Some(self.user_agent.clone()), public_key: Some(self.public.to_protobuf_encoding()), - listen_addrs: self - .listen_addresses - .iter() - .map(|address| address.to_vec()) - .collect::>(), + listen_addrs: self.listen_addresses.get_raw_addresses(), observed_addr, protocols: self.protocols.clone(), }; From e4527456a699648cf06617e1ff8d39de41080d0e Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 20 Aug 2024 18:35:42 +0300 Subject: [PATCH 02/30] tests: Check identify public addresses are propagated Signed-off-by: Alexandru Vasile --- src/protocol/libp2p/identify.rs | 79 +++++++++++++++++++++++++++++- tests/conformance/rust/identify.rs | 2 +- tests/protocol/identify.rs | 6 +-- 3 files changed, 82 insertions(+), 5 deletions(-) diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 203a3a77..c1d51e8e 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -82,6 +82,10 @@ impl IdentifyPublicAddresses { /// Add public address. pub fn add(&self, address: Multiaddr) { + if address.is_empty() { + return; + } + self.inner.write().insert(address); } @@ -102,7 +106,9 @@ impl IdentifyPublicAddresses { /// Extend public addresses. pub fn extend(&self, addresses: impl IntoIterator) { - self.inner.write().extend(addresses); + self.inner + .write() + .extend(addresses.into_iter().filter(|address| !address.is_empty())); } } @@ -462,3 +468,74 @@ impl Identify { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{config::ConfigBuilder, transport::tcp::config::Config as TcpConfig, Litep2p}; + use multiaddr::Multiaddr; + + fn create_litep2p() -> ( + Litep2p, + IdentifyPublicAddresses, + Box + Send + Unpin>, + ) { + let (identify_config, pub_addr, identify) = Config::new( + "1.0.0".to_string(), + Some("litep2p/1.0.0".to_string()), + vec![Multiaddr::empty()], + ); + + let config = ConfigBuilder::new() + .with_tcp(TcpConfig { + listen_addresses: vec!["/ip6/::1/tcp/0".parse().unwrap()], + ..Default::default() + }) + .with_libp2p_identify(identify_config) + .build(); + + (Litep2p::new(config).unwrap(), pub_addr, identify) + } + + #[tokio::test] + async fn update_identify_addresses() { + // Create two instances of litep2p + let (mut litep2p1, addr1, mut event_stream1) = create_litep2p(); + let (mut litep2p2, _addr2, mut event_stream2) = create_litep2p(); + + let multiaddr: Multiaddr = "/ip6/::9/tcp/111".parse().unwrap(); + // Litep2p1 is now listening on the new address. + addr1.add(multiaddr.clone()); + + // Dial `litep2p1` + litep2p2 + .dial_address(litep2p1.listen_addresses().next().unwrap().clone()) + .await + .unwrap(); + + tokio::spawn(async move { + loop { + tokio::select! { + _ = litep2p1.next_event() => {} + _event = event_stream1.next() => {} + } + } + }); + + loop { + tokio::select! { + _ = litep2p2.next_event() => {} + event = event_stream2.next() => match event { + Some(IdentifyEvent::PeerIdentified { + listen_addresses, + .. + }) => { + assert!(listen_addresses.iter().any(|address| address == &multiaddr)); + break; + } + _ => {} + } + } + } + } +} diff --git a/tests/conformance/rust/identify.rs b/tests/conformance/rust/identify.rs index c29ca882..b2c82c98 100644 --- a/tests/conformance/rust/identify.rs +++ b/tests/conformance/rust/identify.rs @@ -71,7 +71,7 @@ fn initialize_litep2p() -> ( ) { let keypair = Keypair::generate(); let (ping_config, ping_event_stream) = PingConfig::default(); - let (identify_config, identify_event_stream) = + let (identify_config, _, identify_event_stream) = IdentifyConfig::new("proto v1".to_string(), None, Vec::new()); let litep2p = Litep2p::new( diff --git a/tests/protocol/identify.rs b/tests/protocol/identify.rs index efb3da28..4c232991 100644 --- a/tests/protocol/identify.rs +++ b/tests/protocol/identify.rs @@ -65,7 +65,7 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .try_init(); - let (identify_config1, mut identify_event_stream1) = Config::new( + let (identify_config1, _, mut identify_event_stream1) = Config::new( "/proto/1".to_string(), Some("agent v1".to_string()), Vec::new(), @@ -75,7 +75,7 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { .with_libp2p_identify(identify_config1); let config1 = add_transport(config_builder1, transport1).build(); - let (identify_config2, mut identify_event_stream2) = Config::new( + let (identify_config2, _, mut identify_event_stream2) = Config::new( "/proto/2".to_string(), Some("agent v2".to_string()), Vec::new(), @@ -193,7 +193,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { .with_libp2p_ping(ping_config); let config1 = add_transport(config_builder1, transport1).build(); - let (identify_config2, mut identify_event_stream2) = + let (identify_config2, _, mut identify_event_stream2) = Config::new("litep2p".to_string(), None, Vec::new()); let config_builder2 = ConfigBuilder::new() .with_keypair(Keypair::generate()) From 0e42027d8e651166e4c93d699b4a9b3afaab4b9d Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 14:27:42 +0300 Subject: [PATCH 03/30] listen-addr: Add listen address struct to a separate module Signed-off-by: Alexandru Vasile --- src/lib.rs | 1 + src/listen_addresses.rs | 72 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 src/listen_addresses.rs diff --git a/src/lib.rs b/src/lib.rs index 6222c241..1dbd188c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,6 +69,7 @@ pub mod config; pub mod crypto; pub mod error; pub mod executor; +pub mod listen_addresses; pub mod protocol; pub mod substream; pub mod transport; diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs new file mode 100644 index 00000000..3028737e --- /dev/null +++ b/src/listen_addresses.rs @@ -0,0 +1,72 @@ +// Copyright 2024 litep2p developers +// +// 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 std::{collections::HashSet, sync::Arc}; + +use multiaddr::Multiaddr; +use parking_lot::RwLock; + +/// Set of the public addresses of the local node. +/// +/// These addresses are reported to the identify protocol. +#[derive(Debug, Clone)] +pub struct IdentifyPublicAddresses { + inner: Arc>>, +} + +impl IdentifyPublicAddresses { + /// Create new [`IdentifyPublicAddresses`]. + fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(HashSet::new())), + } + } + + /// Add public address. + pub fn add(&self, address: Multiaddr) { + if address.is_empty() { + return; + } + + self.inner.write().insert(address); + } + + /// Remove public address. + pub fn remove(&self, address: &Multiaddr) { + self.inner.write().remove(address); + } + + /// Get public addresses. + pub fn get_addresses(&self) -> Vec { + self.inner.read().iter().cloned().collect() + } + + /// Get public addresses in the identify raw format. + fn get_raw_addresses(&self) -> Vec> { + self.inner.read().iter().map(|address| address.to_vec()).collect() + } + + /// Extend public addresses. + pub fn extend(&self, addresses: impl IntoIterator) { + self.inner + .write() + .extend(addresses.into_iter().filter(|address| !address.is_empty())); + } +} From 890df795efb7e349ffbe9d09757627f59f1c32f3 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 14:39:17 +0300 Subject: [PATCH 04/30] listen-addr/tests: Check listen addr interface functionality Signed-off-by: Alexandru Vasile --- src/listen_addresses.rs | 84 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index 3028737e..f6e165f9 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -27,19 +27,25 @@ use parking_lot::RwLock; /// /// These addresses are reported to the identify protocol. #[derive(Debug, Clone)] -pub struct IdentifyPublicAddresses { +pub struct ListenAddresses { inner: Arc>>, } -impl IdentifyPublicAddresses { - /// Create new [`IdentifyPublicAddresses`]. +impl ListenAddresses { + /// Create new [`ListenAddresses`]. fn new() -> Self { Self { inner: Arc::new(RwLock::new(HashSet::new())), } } - /// Add public address. + /// Add a public address to the list of listen addresses. + /// + /// # Note + /// + /// Users must ensure that the address is public. + /// + /// Empty addresses are ignored. pub fn add(&self, address: Multiaddr) { if address.is_empty() { return; @@ -53,12 +59,17 @@ impl IdentifyPublicAddresses { self.inner.write().remove(address); } + /// Returns `true` if the set contains the given address. + pub fn contains(&self, address: &Multiaddr) -> bool { + self.inner.read().contains(address) + } + /// Get public addresses. pub fn get_addresses(&self) -> Vec { self.inner.read().iter().cloned().collect() } - /// Get public addresses in the identify raw format. + /// Get public addresses in the raw (bytes) format. fn get_raw_addresses(&self) -> Vec> { self.inner.read().iter().map(|address| address.to_vec()).collect() } @@ -70,3 +81,66 @@ impl IdentifyPublicAddresses { .extend(addresses.into_iter().filter(|address| !address.is_empty())); } } + +#[cfg(test)] +mod tests { + use super::*; + use std::str::FromStr; + + #[test] + fn add_remove_contains() { + let addresses = ListenAddresses::new(); + let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + + assert!(!addresses.contains(&address)); + addresses.add(address.clone()); + assert!(addresses.contains(&address)); + + addresses.remove(&address); + assert!(!addresses.contains(&address)); + } + + #[test] + fn get_addresses() { + let addresses = ListenAddresses::new(); + let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); + + addresses.add(address1.clone()); + addresses.add(address2.clone()); + + let addresses = addresses.get_addresses(); + assert_eq!(addresses.len(), 2); + assert!(addresses.contains(&address1)); + assert!(addresses.contains(&address2)); + } + + #[test] + fn get_raw_addresses() { + let addresses = ListenAddresses::new(); + let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); + + addresses.add(address1.clone()); + addresses.add(address2.clone()); + + let addresses = addresses.get_raw_addresses(); + assert_eq!(addresses.len(), 2); + assert!(addresses.contains(&address1.to_vec())); + assert!(addresses.contains(&address2.to_vec())); + } + + #[test] + fn extend() { + let addresses = ListenAddresses::new(); + let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); + + addresses.extend(vec![address1.clone(), address2.clone()]); + + let addresses = addresses.get_addresses(); + assert_eq!(addresses.len(), 2); + assert!(addresses.contains(&address1)); + assert!(addresses.contains(&address2)); + } +} From 59668c9055d77622e73c8ef5d1763b7f6a0be14e Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 14:53:20 +0300 Subject: [PATCH 05/30] listen-addr: Use a lock guard for custom iteration over the addresses Signed-off-by: Alexandru Vasile --- src/listen_addresses.rs | 45 +++++++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 8 deletions(-) diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index f6e165f9..43aca3a1 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -32,8 +32,8 @@ pub struct ListenAddresses { } impl ListenAddresses { - /// Create new [`ListenAddresses`]. - fn new() -> Self { + /// Creates new [`ListenAddresses`]. + pub fn new() -> Self { Self { inner: Arc::new(RwLock::new(HashSet::new())), } @@ -64,14 +64,28 @@ impl ListenAddresses { self.inner.read().contains(address) } - /// Get public addresses. + /// Returns a vector of the available listen addresses. pub fn get_addresses(&self) -> Vec { self.inner.read().iter().cloned().collect() } - /// Get public addresses in the raw (bytes) format. - fn get_raw_addresses(&self) -> Vec> { - self.inner.read().iter().map(|address| address.to_vec()).collect() + /// Returns an immutable reference to the set of listen addresses. + /// + /// This method can be used when `get_addresses` is not sufficient. + /// + /// # Example + /// + /// ```rust + /// # use litep2p::listen_addresses::ListenAddresses; + /// # + /// # fn listen_addresses(addresses: ListenAddresses) { + /// let string_addresses = addresses.locked().iter().map(|address| address.to_string()).collect::>(); + /// # } + /// ``` + pub fn locked(&self) -> LockedListenAddresses { + LockedListenAddresses { + inner: self.inner.read(), + } } /// Extend public addresses. @@ -82,6 +96,20 @@ impl ListenAddresses { } } +/// A short lived instance of the locked listen addresses. +pub struct LockedListenAddresses<'a> { + inner: parking_lot::RwLockReadGuard<'a, HashSet>, +} + +impl<'a> LockedListenAddresses<'a> { + /// Iterate over the listen addresses. + /// + /// This exposes all the functionality of the standard iterator. + pub fn iter(&self) -> impl Iterator { + self.inner.iter() + } +} + #[cfg(test)] mod tests { use super::*; @@ -116,7 +144,7 @@ mod tests { } #[test] - fn get_raw_addresses() { + fn locked() { let addresses = ListenAddresses::new(); let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); @@ -124,7 +152,8 @@ mod tests { addresses.add(address1.clone()); addresses.add(address2.clone()); - let addresses = addresses.get_raw_addresses(); + let addresses = addresses.locked(); + let addresses = addresses.iter().map(|address| address.to_vec()).collect::>(); assert_eq!(addresses.len(), 2); assert!(addresses.contains(&address1.to_vec())); assert!(addresses.contains(&address2.to_vec())); From 56ed02a89e01173233b0373ac0d41764cb1abcb9 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 15:06:10 +0300 Subject: [PATCH 06/30] litep2p: Store shared listenAddresses on Litep2p object Signed-off-by: Alexandru Vasile --- src/lib.rs | 11 ++++++----- src/listen_addresses.rs | 7 ++++++- src/protocol/transport_service.rs | 6 ++++++ src/transport/manager/handle.rs | 6 ++++++ src/transport/manager/mod.rs | 6 ++++++ 5 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1dbd188c..fa29d6a2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,6 +30,7 @@ use crate::{ config::Litep2pConfig, + listen_addresses::ListenAddresses, protocol::{ libp2p::{bitswap::Bitswap, identify::Identify, kademlia::Kademlia, ping::Ping}, mdns::Mdns, @@ -128,7 +129,7 @@ pub struct Litep2p { local_peer_id: PeerId, /// Listen addresses. - listen_addresses: Vec, + listen_addresses: ListenAddresses, /// Transport manager. transport_manager: TransportManager, @@ -399,7 +400,7 @@ impl Litep2p { Ok(Self { local_peer_id, bandwidth_sink, - listen_addresses, + listen_addresses: transport_manager.listen_addresses(), transport_manager, }) } @@ -440,9 +441,9 @@ impl Litep2p { &self.local_peer_id } - /// Get listen address of litep2p. - pub fn listen_addresses(&self) -> impl Iterator { - self.listen_addresses.iter() + /// Get the listen address of litep2p. + pub fn listen_addresses(&self) -> ListenAddresses { + self.listen_addresses.clone() } /// Get handle to bandwidth sink. diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index 43aca3a1..14331aa4 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -33,12 +33,17 @@ pub struct ListenAddresses { impl ListenAddresses { /// Creates new [`ListenAddresses`]. - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self { inner: Arc::new(RwLock::new(HashSet::new())), } } + /// Creates new [`ListenAddresses`] from the inner set. + pub(crate) fn from_inner(inner: Arc>>) -> Self { + Self { inner } + } + /// Add a public address to the list of listen addresses. /// /// # Note diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 63d5a117..067327bf 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -20,6 +20,7 @@ use crate::{ error::Error, + listen_addresses::ListenAddresses, protocol::{connection::ConnectionHandle, InnerTransportEvent, TransportEvent}, transport::{manager::TransportManagerHandle, Endpoint}, types::{protocol::ProtocolName, ConnectionId, SubstreamId}, @@ -157,6 +158,11 @@ impl TransportService { ) } + /// Get the listen address of litep2p. + pub fn listen_addresses(&self) -> ListenAddresses { + self.transport_handle.listen_addresses() + } + /// Handle connection established event. fn on_connection_established( &mut self, diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index ece77f02..fa5a7bdc 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -22,6 +22,7 @@ use crate::{ crypto::ed25519::Keypair, error::{AddressError, Error}, executor::Executor, + listen_addresses::ListenAddresses, protocol::ProtocolSet, transport::manager::{ address::{AddressRecord, AddressStore}, @@ -102,6 +103,11 @@ impl TransportManagerHandle { self.supported_transport.insert(transport); } + /// Get listen addresses. + pub(crate) fn listen_addresses(&self) -> ListenAddresses { + ListenAddresses::from_inner(self.listen_addresses.clone()) + } + /// Check if `address` is supported by one of the enabled transports. pub fn supported_transport(&self, address: &Multiaddr) -> bool { let mut iter = address.iter(); diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index 33cc8f5b..64884926 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -23,6 +23,7 @@ use crate::{ crypto::ed25519::Keypair, error::{AddressError, Error}, executor::Executor, + listen_addresses::ListenAddresses, protocol::{InnerTransportEvent, TransportService}, transport::{ manager::{ @@ -377,6 +378,11 @@ impl TransportManager { self.transport_manager_handle.register_transport(name); } + /// Get listen addresses. + pub(crate) fn listen_addresses(&self) -> ListenAddresses { + ListenAddresses::from_inner(self.listen_addresses.clone()) + } + /// Register local listen address. pub fn register_listen_address(&mut self, address: Multiaddr) { assert!(!address.iter().any(|protocol| std::matches!(protocol, Protocol::P2p(_)))); From a4bbf063a2262bf295d0aa2e49ea86bd416fce76 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 15:14:49 +0300 Subject: [PATCH 07/30] identify: Use the new interface of public addresses Signed-off-by: Alexandru Vasile --- src/lib.rs | 2 +- src/listen_addresses.rs | 7 --- src/protocol/libp2p/identify.rs | 79 +++++---------------------------- 3 files changed, 11 insertions(+), 77 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index fa29d6a2..2dcc313c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -378,7 +378,7 @@ impl Litep2p { // if identify was enabled, give it the enabled protocols and listen addresses and start it if let Some((service, mut identify_config)) = identify_info.take() { identify_config.protocols = transport_manager.protocols().cloned().collect(); - let identify = Identify::new(service, identify_config, listen_addresses.clone()); + let identify = Identify::new(service, identify_config); litep2p_config.executor.run(Box::pin(async move { let _ = identify.run().await; diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index 14331aa4..070cff67 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -32,13 +32,6 @@ pub struct ListenAddresses { } impl ListenAddresses { - /// Creates new [`ListenAddresses`]. - pub(crate) fn new() -> Self { - Self { - inner: Arc::new(RwLock::new(HashSet::new())), - } - } - /// Creates new [`ListenAddresses`] from the inner set. pub(crate) fn from_inner(inner: Arc>>) -> Self { Self { inner } diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index c1d51e8e..1f0cbfff 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -24,6 +24,7 @@ use crate::{ codec::ProtocolCodec, crypto::PublicKey, error::{Error, SubstreamError}, + listen_addresses::ListenAddresses, protocol::{Direction, TransportEvent, TransportService}, substream::Substream, transport::Endpoint, @@ -33,14 +34,12 @@ use crate::{ use futures::{future::BoxFuture, stream::FuturesUnordered, Stream, StreamExt}; use multiaddr::Multiaddr; -use parking_lot::RwLock; use prost::Message; use tokio::sync::mpsc::{channel, Sender}; use tokio_stream::wrappers::ReceiverStream; use std::{ collections::{HashMap, HashSet}, - sync::Arc, time::Duration, }; @@ -64,54 +63,6 @@ mod identify_schema { include!(concat!(env!("OUT_DIR"), "/identify.rs")); } -/// Set of the public addresses of the local node. -/// -/// These addresses are reported to the identify protocol. -#[derive(Debug, Clone)] -pub struct IdentifyPublicAddresses { - inner: Arc>>, -} - -impl IdentifyPublicAddresses { - /// Create new [`IdentifyPublicAddresses`]. - fn new() -> Self { - Self { - inner: Arc::new(RwLock::new(HashSet::new())), - } - } - - /// Add public address. - pub fn add(&self, address: Multiaddr) { - if address.is_empty() { - return; - } - - self.inner.write().insert(address); - } - - /// Remove public address. - pub fn remove(&self, address: &Multiaddr) { - self.inner.write().remove(address); - } - - /// Get public addresses. - pub fn get_addresses(&self) -> Vec { - self.inner.read().iter().cloned().collect() - } - - /// Get public addresses in the identify raw format. - fn get_raw_addresses(&self) -> Vec> { - self.inner.read().iter().map(|address| address.to_vec()).collect() - } - - /// Extend public addresses. - pub fn extend(&self, addresses: impl IntoIterator) { - self.inner - .write() - .extend(addresses.into_iter().filter(|address| !address.is_empty())); - } -} - /// Identify configuration. pub struct Config { /// Protocol name. @@ -130,7 +81,7 @@ pub struct Config { pub(crate) protocols: Vec, /// Public addresses. - pub(crate) public_addresses: IdentifyPublicAddresses, + pub(crate) public_addresses: Vec, /// Protocol version. pub(crate) protocol_version: String, @@ -148,27 +99,20 @@ impl Config { protocol_version: String, user_agent: Option, public_addresses: Vec, - ) -> ( - Self, - IdentifyPublicAddresses, - Box + Send + Unpin>, - ) { + ) -> (Self, Box + Send + Unpin>) { let (tx_event, rx_event) = channel(DEFAULT_CHANNEL_SIZE); - let identify_public_addresses = IdentifyPublicAddresses::new(); - identify_public_addresses.extend(public_addresses); ( Self { tx_event, public: None, - public_addresses: identify_public_addresses.clone(), + public_addresses, protocol_version, user_agent, codec: ProtocolCodec::UnsignedVarint(Some(IDENTIFY_PAYLOAD_SIZE)), protocols: Vec::new(), protocol: ProtocolName::from(PROTOCOL_NAME), }, - identify_public_addresses, Box::new(ReceiverStream::new(rx_event)), ) } @@ -240,7 +184,7 @@ pub(crate) struct Identify { user_agent: String, /// Public addresses. - listen_addresses: IdentifyPublicAddresses, + listen_addresses: ListenAddresses, /// Protocols supported by the local node, filled by `Litep2p`. protocols: Vec, @@ -257,18 +201,15 @@ pub(crate) struct Identify { impl Identify { /// Create new [`Identify`] protocol. - pub(crate) fn new( - service: TransportService, - config: Config, - listen_addresses: Vec, - ) -> Self { - config.public_addresses.extend(listen_addresses); + pub(crate) fn new(service: TransportService, config: Config) -> Self { + let listen_addresses = service.listen_addresses(); + listen_addresses.extend(config.public_addresses.into_iter()); Self { service, tx: config.tx_event, peers: HashMap::new(), - listen_addresses: config.public_addresses, + listen_addresses, public: config.public.expect("public key to be supplied"), protocol_version: config.protocol_version, user_agent: config.user_agent.unwrap_or(DEFAULT_AGENT.to_string()), @@ -328,7 +269,7 @@ impl Identify { protocol_version: Some(self.protocol_version.clone()), agent_version: Some(self.user_agent.clone()), public_key: Some(self.public.to_protobuf_encoding()), - listen_addrs: self.listen_addresses.get_raw_addresses(), + listen_addrs: self.listen_addresses.locked().iter().map(|addr| addr.to_vec()).collect(), observed_addr, protocols: self.protocols.clone(), }; From f2a1c5114b12219df544de5a8a4f161a00c856de Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 15:25:00 +0300 Subject: [PATCH 08/30] listen-addr: Check listen address contains p2p protocol Signed-off-by: Alexandru Vasile --- src/listen_addresses.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index 070cff67..9d44b708 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -20,7 +20,7 @@ use std::{collections::HashSet, sync::Arc}; -use multiaddr::Multiaddr; +use multiaddr::{Multiaddr, Protocol}; use parking_lot::RwLock; /// Set of the public addresses of the local node. @@ -44,11 +44,10 @@ impl ListenAddresses { /// Users must ensure that the address is public. /// /// Empty addresses are ignored. - pub fn add(&self, address: Multiaddr) { - if address.is_empty() { + pub fn register_listen_address(&self, address: Multiaddr) { + if !address.iter().any(|protocol| std::matches!(protocol, Protocol::P2p(_))) { return; } - self.inner.write().insert(address); } From 67b617d51f6c49a4615913b7a476cc42deb11539 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 15:29:39 +0300 Subject: [PATCH 09/30] Polish up the API Signed-off-by: Alexandru Vasile --- src/lib.rs | 22 +++++----------------- src/listen_addresses.rs | 10 ++++++++++ 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 2dcc313c..07ab51e3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,8 +51,7 @@ use crate::transport::webrtc::WebRtcTransport; #[cfg(feature = "websocket")] use crate::transport::websocket::WebSocketTransport; -use multiaddr::{Multiaddr, Protocol}; -use multihash::Multihash; +use multiaddr::Multiaddr; use transport::Endpoint; use types::ConnectionId; @@ -143,7 +142,6 @@ impl Litep2p { pub fn new(mut litep2p_config: Litep2pConfig) -> crate::Result { let local_peer_id = PeerId::from_public_key(&litep2p_config.keypair.public().into()); let bandwidth_sink = BandwidthSink::new(); - let mut listen_addresses = vec![]; let supported_transports = Self::supported_transports(&litep2p_config); let (mut transport_manager, transport_handle) = TransportManager::new( @@ -306,9 +304,6 @@ impl Litep2p { for address in transport_listen_addresses { transport_manager.register_listen_address(address.clone()); - listen_addresses.push(address.with(Protocol::P2p( - Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), - ))); } transport_manager.register_transport(SupportedTransport::Tcp, Box::new(transport)); @@ -323,9 +318,6 @@ impl Litep2p { for address in transport_listen_addresses { transport_manager.register_listen_address(address.clone()); - listen_addresses.push(address.with(Protocol::P2p( - Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), - ))); } transport_manager.register_transport(SupportedTransport::Quic, Box::new(transport)); @@ -340,9 +332,6 @@ impl Litep2p { for address in transport_listen_addresses { transport_manager.register_listen_address(address.clone()); - listen_addresses.push(address.with(Protocol::P2p( - Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), - ))); } transport_manager.register_transport(SupportedTransport::WebRtc, Box::new(transport)); @@ -357,18 +346,17 @@ impl Litep2p { for address in transport_listen_addresses { transport_manager.register_listen_address(address.clone()); - listen_addresses.push(address.with(Protocol::P2p( - Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), - ))); } transport_manager .register_transport(SupportedTransport::WebSocket, Box::new(transport)); } + let listen_addresses = transport_manager.listen_addresses(); + // enable mdns if the config exists if let Some(config) = litep2p_config.mdns.take() { - let mdns = Mdns::new(transport_handle, config, listen_addresses.clone())?; + let mdns = Mdns::new(transport_handle, config, listen_addresses.get_addresses())?; litep2p_config.executor.run(Box::pin(async move { let _ = mdns.start().await; @@ -400,7 +388,7 @@ impl Litep2p { Ok(Self { local_peer_id, bandwidth_sink, - listen_addresses: transport_manager.listen_addresses(), + listen_addresses, transport_manager, }) } diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index 9d44b708..58a62176 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -91,6 +91,16 @@ impl ListenAddresses { .write() .extend(addresses.into_iter().filter(|address| !address.is_empty())); } + + /// Returns the number of listen addresses. + pub fn len(&self) -> usize { + self.inner.read().len() + } + + /// Returns `true` if the set of listen addresses is empty. + pub fn is_empty(&self) -> bool { + self.inner.read().is_empty() + } } /// A short lived instance of the locked listen addresses. From 38d8ca3285783a485ca55bcf45b62d6a5175ee09 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 18:23:22 +0300 Subject: [PATCH 10/30] listen-addr: Register lsiten addresses with adding the local peerID Signed-off-by: Alexandru Vasile --- src/listen_addresses.rs | 109 ++++++++++++++++++++++++++++------------ 1 file changed, 78 insertions(+), 31 deletions(-) diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index 58a62176..52c44e48 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -23,37 +23,54 @@ use std::{collections::HashSet, sync::Arc}; use multiaddr::{Multiaddr, Protocol}; use parking_lot::RwLock; +use crate::PeerId; + /// Set of the public addresses of the local node. /// /// These addresses are reported to the identify protocol. #[derive(Debug, Clone)] pub struct ListenAddresses { inner: Arc>>, + local_peer_id: PeerId, } impl ListenAddresses { /// Creates new [`ListenAddresses`] from the inner set. - pub(crate) fn from_inner(inner: Arc>>) -> Self { - Self { inner } + pub(crate) fn from_inner( + inner: Arc>>, + local_peer_id: PeerId, + ) -> Self { + Self { + inner, + local_peer_id, + } } /// Add a public address to the list of listen addresses. /// - /// # Note - /// - /// Users must ensure that the address is public. + /// The address must contain the local peer ID, otherwise it will be added. /// - /// Empty addresses are ignored. - pub fn register_listen_address(&self, address: Multiaddr) { - if !address.iter().any(|protocol| std::matches!(protocol, Protocol::P2p(_))) { - return; + /// Returns true if the address was added, false if it was already present. + pub fn register_listen_address(&self, mut address: Multiaddr) -> Result { + if address.is_empty() { + return Err(address); + } + + // Verify the peer ID from the address corresponds to the local peer ID. + if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { + if peer_id != self.local_peer_id { + return Err(address); + } + } else { + address.push(Protocol::P2p(self.local_peer_id.into())); } - self.inner.write().insert(address); + + Ok(self.inner.write().insert(address)) } /// Remove public address. - pub fn remove(&self, address: &Multiaddr) { - self.inner.write().remove(address); + pub fn remove(&self, address: &Multiaddr) -> bool { + self.inner.write().remove(address) } /// Returns `true` if the set contains the given address. @@ -124,25 +141,41 @@ mod tests { #[test] fn add_remove_contains() { - let addresses = ListenAddresses::new(); + let peer_id = PeerId::random(); + let addresses = ListenAddresses::from_inner(Default::default(), peer_id); let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") + .unwrap() + .with(Protocol::P2p(peer_id.into())); assert!(!addresses.contains(&address)); - addresses.add(address.clone()); - assert!(addresses.contains(&address)); - addresses.remove(&address); + assert!(addresses.register_listen_address(address.clone()).unwrap()); + // Adding the address a second time returns Ok(false). + assert!(!addresses.register_listen_address(address.clone()).unwrap()); + assert!(!addresses.contains(&address)); + assert!(addresses.contains(&peer_address)); + + addresses.remove(&peer_address); + assert!(!addresses.contains(&peer_address)); } #[test] fn get_addresses() { - let addresses = ListenAddresses::new(); - let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); - - addresses.add(address1.clone()); - addresses.add(address2.clone()); + let peer_id = PeerId::random(); + let addresses = ListenAddresses::from_inner(Default::default(), peer_id); + let address1 = Multiaddr::from_str( + "/dns/domain1.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", + ) + .unwrap(); + let address2 = Multiaddr::from_str( + "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", + ) + .unwrap(); + + assert!(addresses.register_listen_address(address1.clone()).unwrap()); + assert!(addresses.register_listen_address(address2.clone()).unwrap()); let addresses = addresses.get_addresses(); assert_eq!(addresses.len(), 2); @@ -152,12 +185,19 @@ mod tests { #[test] fn locked() { - let addresses = ListenAddresses::new(); - let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); - - addresses.add(address1.clone()); - addresses.add(address2.clone()); + let peer_id = PeerId::random(); + let addresses = ListenAddresses::from_inner(Default::default(), peer_id); + let address1 = Multiaddr::from_str( + "/dns/domain1.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", + ) + .unwrap(); + let address2 = Multiaddr::from_str( + "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", + ) + .unwrap(); + + assert!(addresses.register_listen_address(address1.clone()).unwrap()); + assert!(addresses.register_listen_address(address2.clone()).unwrap()); let addresses = addresses.locked(); let addresses = addresses.iter().map(|address| address.to_vec()).collect::>(); @@ -168,9 +208,16 @@ mod tests { #[test] fn extend() { - let addresses = ListenAddresses::new(); - let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); + let peer_id = PeerId::random(); + let addresses = ListenAddresses::from_inner(Default::default(), peer_id); + let address1 = Multiaddr::from_str( + "/dns/domain1.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", + ) + .unwrap(); + let address2 = Multiaddr::from_str( + "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", + ) + .unwrap(); addresses.extend(vec![address1.clone(), address2.clone()]); From 2a454226ea85bf9705c0ae91cc9bec9451441060 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 18:23:51 +0300 Subject: [PATCH 11/30] Adjust testing to the new interface Signed-off-by: Alexandru Vasile --- examples/custom_executor.rs | 2 +- examples/custom_protocol.rs | 2 +- examples/echo_notification.rs | 2 +- examples/gossiping.rs | 2 +- src/protocol/libp2p/identify.rs | 24 +++++---- src/transport/manager/handle.rs | 2 +- src/transport/manager/mod.rs | 2 +- tests/conformance/rust/identify.rs | 4 +- tests/conformance/rust/kademlia.rs | 6 +-- tests/conformance/rust/ping.rs | 2 +- tests/conformance/substrate/connection.rs | 2 +- tests/conformance/substrate/notifications.rs | 14 ++--- .../conformance/substrate/request_response.rs | 10 ++-- tests/connection/mod.rs | 53 ++++++++++--------- tests/custom_executor.rs | 2 +- tests/protocol/identify.rs | 12 ++--- tests/protocol/kademlia.rs | 8 +-- tests/protocol/notification.rs | 22 ++++---- tests/protocol/ping.rs | 2 +- tests/protocol/request_response.rs | 4 +- tests/substream.rs | 2 +- tests/user_protocol.rs | 2 +- tests/user_protocol_2.rs | 2 +- tests/webrtc.rs | 2 +- 24 files changed, 95 insertions(+), 90 deletions(-) diff --git a/examples/custom_executor.rs b/examples/custom_executor.rs index 34ab4748..5a5cbd98 100644 --- a/examples/custom_executor.rs +++ b/examples/custom_executor.rs @@ -122,7 +122,7 @@ async fn main() { // dial `litep2p1` litep2p2 - .dial_address(litep2p1.listen_addresses().next().unwrap().clone()) + .dial_address(litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone()) .await .unwrap(); diff --git a/examples/custom_protocol.rs b/examples/custom_protocol.rs index b69ede2d..7eead39f 100644 --- a/examples/custom_protocol.rs +++ b/examples/custom_protocol.rs @@ -277,7 +277,7 @@ async fn main() { let (mut litep2p2, mut handle2) = make_litep2p(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(listen_address)); tokio::spawn(async move { diff --git a/examples/echo_notification.rs b/examples/echo_notification.rs index 11842257..4521c934 100644 --- a/examples/echo_notification.rs +++ b/examples/echo_notification.rs @@ -125,7 +125,7 @@ async fn main() { // get the first (and only) listen address for the second peer // and add it as a known address for `litep2p1` - let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let peer = *litep2p2.local_peer_id(); litep2p1.add_known_address(peer, vec![listen_address].into_iter()); diff --git a/examples/gossiping.rs b/examples/gossiping.rs index ca01d978..730d23db 100644 --- a/examples/gossiping.rs +++ b/examples/gossiping.rs @@ -237,7 +237,7 @@ async fn main() { // establish connection to litep2p for all other litep2ps let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address.clone()].into_iter()); litep2p3.add_known_address(peer2, vec![listen_address.clone()].into_iter()); diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 1f0cbfff..e0f77261 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -418,10 +418,9 @@ mod tests { fn create_litep2p() -> ( Litep2p, - IdentifyPublicAddresses, Box + Send + Unpin>, ) { - let (identify_config, pub_addr, identify) = Config::new( + let (identify_config, identify) = Config::new( "1.0.0".to_string(), Some("litep2p/1.0.0".to_string()), vec![Multiaddr::empty()], @@ -435,24 +434,26 @@ mod tests { .with_libp2p_identify(identify_config) .build(); - (Litep2p::new(config).unwrap(), pub_addr, identify) + (Litep2p::new(config).unwrap(), identify) } #[tokio::test] async fn update_identify_addresses() { // Create two instances of litep2p - let (mut litep2p1, addr1, mut event_stream1) = create_litep2p(); - let (mut litep2p2, _addr2, mut event_stream2) = create_litep2p(); + let (mut litep2p1, mut event_stream1) = create_litep2p(); + let (mut litep2p2, mut event_stream2) = create_litep2p(); let multiaddr: Multiaddr = "/ip6/::9/tcp/111".parse().unwrap(); - // Litep2p1 is now listening on the new address. - addr1.add(multiaddr.clone()); + // Litep2p1 is now reporting the new address. + assert!(litep2p1.listen_addresses().register_listen_address(multiaddr.clone()).unwrap()); + + let litep2p1_address = + litep2p1.listen_addresses().get_addresses().into_iter().next().unwrap(); + + println!(" listen_addresses: {:?}", litep2p1_address); // Dial `litep2p1` - litep2p2 - .dial_address(litep2p1.listen_addresses().next().unwrap().clone()) - .await - .unwrap(); + litep2p2.dial_address(litep2p1_address).await.unwrap(); tokio::spawn(async move { loop { @@ -471,6 +472,7 @@ mod tests { listen_addresses, .. }) => { + println!(" listen_addresses: {:?}", listen_addresses); assert!(listen_addresses.iter().any(|address| address == &multiaddr)); break; } diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index fa5a7bdc..d4c427fc 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -105,7 +105,7 @@ impl TransportManagerHandle { /// Get listen addresses. pub(crate) fn listen_addresses(&self) -> ListenAddresses { - ListenAddresses::from_inner(self.listen_addresses.clone()) + ListenAddresses::from_inner(self.listen_addresses.clone(), self.local_peer_id) } /// Check if `address` is supported by one of the enabled transports. diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index 64884926..bf39a770 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -380,7 +380,7 @@ impl TransportManager { /// Get listen addresses. pub(crate) fn listen_addresses(&self) -> ListenAddresses { - ListenAddresses::from_inner(self.listen_addresses.clone()) + ListenAddresses::from_inner(self.listen_addresses.clone(), self.local_peer_id) } /// Register local listen address. diff --git a/tests/conformance/rust/identify.rs b/tests/conformance/rust/identify.rs index b2c82c98..66d0ccd5 100644 --- a/tests/conformance/rust/identify.rs +++ b/tests/conformance/rust/identify.rs @@ -71,7 +71,7 @@ fn initialize_litep2p() -> ( ) { let keypair = Keypair::generate(); let (ping_config, ping_event_stream) = PingConfig::default(); - let (identify_config, _, identify_event_stream) = + let (identify_config, identify_event_stream) = IdentifyConfig::new("proto v1".to_string(), None, Vec::new()); let litep2p = Litep2p::new( @@ -119,7 +119,7 @@ async fn identify_works() { let mut libp2p = initialize_libp2p(); let (mut litep2p, _ping_event_stream, mut identify_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/rust/kademlia.rs b/tests/conformance/rust/kademlia.rs index a501b581..eebc539d 100644 --- a/tests/conformance/rust/kademlia.rs +++ b/tests/conformance/rust/kademlia.rs @@ -119,7 +119,7 @@ async fn find_node() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -223,7 +223,7 @@ async fn put_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -335,7 +335,7 @@ async fn get_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); diff --git a/tests/conformance/rust/ping.rs b/tests/conformance/rust/ping.rs index bf398bdb..5e4213aa 100644 --- a/tests/conformance/rust/ping.rs +++ b/tests/conformance/rust/ping.rs @@ -81,7 +81,7 @@ async fn libp2p_dials() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut ping_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/substrate/connection.rs b/tests/conformance/substrate/connection.rs index fd8c28cf..ff4c318c 100644 --- a/tests/conformance/substrate/connection.rs +++ b/tests/conformance/substrate/connection.rs @@ -110,7 +110,7 @@ async fn substrate_keep_alive_timeout() { let (mut libp2p, _peer_store_handle) = initialize_libp2p(1u32, 1u32); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_connection_open = false; diff --git a/tests/conformance/substrate/notifications.rs b/tests/conformance/substrate/notifications.rs index 9d5df646..ada5915f 100644 --- a/tests/conformance/substrate/notifications.rs +++ b/tests/conformance/substrate/notifications.rs @@ -119,7 +119,7 @@ async fn substrate_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -214,7 +214,7 @@ async fn litep2p_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -311,7 +311,7 @@ async fn substrate_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -360,7 +360,7 @@ async fn litep2p_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -412,7 +412,7 @@ async fn substrate_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_notification_count = 0; @@ -504,7 +504,7 @@ async fn litep2p_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut notif_count = 0; @@ -584,7 +584,7 @@ async fn both_nodes_open_substreams() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; diff --git a/tests/conformance/substrate/request_response.rs b/tests/conformance/substrate/request_response.rs index 437dd49d..39d2cbe5 100644 --- a/tests/conformance/substrate/request_response.rs +++ b/tests/conformance/substrate/request_response.rs @@ -101,7 +101,7 @@ async fn request_works() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let libp2p_peer = *libp2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -197,7 +197,7 @@ async fn substrate_reject_request() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); tokio::spawn(peer_store.run()); @@ -254,7 +254,7 @@ async fn litep2p_reject_request() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -321,7 +321,7 @@ async fn substrate_request_timeout() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); let mut _timeout_request = None; @@ -379,7 +379,7 @@ async fn litep2p_request_timeout() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); diff --git a/tests/connection/mod.rs b/tests/connection/mod.rs index 769a161f..fedbbdc9 100644 --- a/tests/connection/mod.rs +++ b/tests/connection/mod.rs @@ -108,7 +108,7 @@ async fn two_litep2ps_work(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let (res1, res2) = tokio::join!(litep2p1.next_event(), litep2p2.next_event()); @@ -255,7 +255,7 @@ async fn connect_over_dns() { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let mut new_address = Multiaddr::empty(); @@ -436,7 +436,7 @@ async fn dial_self(transport: Transport) { let litep2p_config = add_transport(litep2p_config, transport).build(); let mut litep2p = Litep2p::new(litep2p_config).unwrap(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); // dial without peer id attached assert!(std::matches!( @@ -563,7 +563,7 @@ async fn keep_alive_timeout(transport1: Transport, transport2: Transport) { let config2 = add_transport(config2, transport2).build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().next().unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p2.dial_address(address1).await.unwrap(); let mut litep2p1_ping = false; let mut litep2p2_ping = false; @@ -622,8 +622,8 @@ async fn simultaneous_dial_tcp() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().next().unwrap().clone(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -675,8 +675,8 @@ async fn simultaneous_dial_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().next().unwrap().clone(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -728,8 +728,8 @@ async fn simultaneous_dial_ipv6_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().next().unwrap().clone(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -787,7 +787,7 @@ async fn websocket_over_ipv6() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address2).await.unwrap(); let mut ping_received1 = false; @@ -839,7 +839,7 @@ async fn tcp_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -901,7 +901,7 @@ async fn websocket_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -1036,10 +1036,9 @@ async fn multiple_listen_addresses( let (mut litep2p2, _event_stream) = make_dummy_litep2p(transport2).await; let (mut litep2p3, _event_stream) = make_dummy_litep2p(transport3).await; - let mut address_iter = litep2p1.listen_addresses(); - let address1 = address_iter.next().unwrap().clone(); - let address2 = address_iter.next().unwrap().clone(); - drop(address_iter); + let addresses = litep2p1.listen_addresses().get_addresses(); + let address1 = addresses.get(0).unwrap().clone(); + let address2 = addresses.get(1).unwrap().clone(); tokio::spawn(async move { loop { @@ -1172,11 +1171,10 @@ async fn unspecified_listen_address_tcp() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - for address in litep2p1.listen_addresses() { + for address in litep2p1.listen_addresses().locked().iter() { tracing::info!("address: {address:?}"); } - - let listen_address = litep2p1.listen_addresses().collect::>(); + let listen_address = litep2p1.listen_addresses().get_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1277,11 +1275,10 @@ async fn unspecified_listen_address_websocket() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - for address in litep2p1.listen_addresses() { + for address in litep2p1.listen_addresses().locked().iter() { tracing::info!("address: {address:?}"); } - - let listen_address = litep2p1.listen_addresses().collect::>(); + let listen_address = litep2p1.listen_addresses().get_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1426,8 +1423,14 @@ async fn simultaneous_dial_then_redial(transport1: Transport, transport2: Transp let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - litep2p1.add_known_address(peer2, litep2p2.listen_addresses().cloned()); - litep2p2.add_known_address(peer1, litep2p1.listen_addresses().cloned()); + litep2p1.add_known_address( + peer2, + litep2p2.listen_addresses().get_addresses().into_iter(), + ); + litep2p2.add_known_address( + peer1, + litep2p1.listen_addresses().get_addresses().into_iter(), + ); let (_, _) = tokio::join!(litep2p1.dial(&peer2), litep2p2.dial(&peer1)); diff --git a/tests/custom_executor.rs b/tests/custom_executor.rs index 171219c5..bddc78ed 100644 --- a/tests/custom_executor.rs +++ b/tests/custom_executor.rs @@ -158,7 +158,7 @@ async fn custom_executor() { let peer2 = *litep2p2.local_peer_id(); // wait until peers have connected and spawn the litep2p objects in the background - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; diff --git a/tests/protocol/identify.rs b/tests/protocol/identify.rs index 4c232991..58ace3b1 100644 --- a/tests/protocol/identify.rs +++ b/tests/protocol/identify.rs @@ -65,7 +65,7 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .try_init(); - let (identify_config1, _, mut identify_event_stream1) = Config::new( + let (identify_config1, mut identify_event_stream1) = Config::new( "/proto/1".to_string(), Some("agent v1".to_string()), Vec::new(), @@ -75,7 +75,7 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { .with_libp2p_identify(identify_config1); let config1 = add_transport(config_builder1, transport1).build(); - let (identify_config2, _, mut identify_event_stream2) = Config::new( + let (identify_config2, mut identify_event_stream2) = Config::new( "/proto/2".to_string(), Some("agent v2".to_string()), Vec::new(), @@ -88,8 +88,8 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().next().unwrap().clone(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("listen address of peer1: {address1}"); tracing::info!("listen address of peer2: {address2}"); @@ -193,7 +193,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { .with_libp2p_ping(ping_config); let config1 = add_transport(config_builder1, transport1).build(); - let (identify_config2, _, mut identify_event_stream2) = + let (identify_config2, mut identify_event_stream2) = Config::new("litep2p".to_string(), None, Vec::new()); let config_builder2 = ConfigBuilder::new() .with_keypair(Keypair::generate()) @@ -202,7 +202,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/kademlia.rs b/tests/protocol/kademlia.rs index 893871e9..39cd354a 100644 --- a/tests/protocol/kademlia.rs +++ b/tests/protocol/kademlia.rs @@ -153,7 +153,7 @@ async fn records_are_stored_automatically() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.listen_addresses().cloned().collect(), + litep2p2.listen_addresses().get_addresses(), ) .await; @@ -234,7 +234,7 @@ async fn records_are_stored_manually() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.listen_addresses().cloned().collect(), + litep2p2.listen_addresses().get_addresses(), ) .await; @@ -317,7 +317,7 @@ async fn not_validated_records_are_not_stored() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.listen_addresses().cloned().collect(), + litep2p2.listen_addresses().get_addresses(), ) .await; @@ -419,7 +419,7 @@ async fn get_record_retrieves_remote_records() { kad_handle2 .add_known_peer( *litep2p1.local_peer_id(), - litep2p1.listen_addresses().cloned().collect(), + litep2p1.listen_addresses().get_addresses(), ) .await; diff --git a/tests/protocol/notification.rs b/tests/protocol/notification.rs index ae034d49..409c2071 100644 --- a/tests/protocol/notification.rs +++ b/tests/protocol/notification.rs @@ -46,7 +46,7 @@ use std::{net::Ipv6Addr, task::Poll, time::Duration}; use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; @@ -2550,7 +2550,7 @@ async fn dial_peer_when_opening_substream(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address)); // add `peer2` known address for `peer1` and spawn the litep2p objects in the background @@ -2708,8 +2708,8 @@ async fn open_and_close_batched( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); - let address3 = litep2p3.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -2913,8 +2913,8 @@ async fn open_and_close_batched_duplicate_peer( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); - let address3 = litep2p3.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -3150,7 +3150,7 @@ async fn no_listener_address_for_one_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); tokio::spawn(async move { @@ -3550,7 +3550,7 @@ async fn dialing_disabled(transport1: Transport, transport2: Transport) { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3641,7 +3641,7 @@ async fn validation_takes_too_long(transport1: Transport, transport2: Transport) let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3748,7 +3748,7 @@ async fn ignored_validation_open_substream(transport1: Transport, transport2: Tr let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3893,7 +3893,7 @@ async fn clogged_channel_disconnects_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); diff --git a/tests/protocol/ping.rs b/tests/protocol/ping.rs index 5a6fecbc..f460b157 100644 --- a/tests/protocol/ping.rs +++ b/tests/protocol/ping.rs @@ -70,7 +70,7 @@ async fn ping_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/request_response.rs b/tests/protocol/request_response.rs index 39d7e046..306f4e8f 100644 --- a/tests/protocol/request_response.rs +++ b/tests/protocol/request_response.rs @@ -52,7 +52,7 @@ use std::{ use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("address: {address}"); litep2p1.dial_address(address).await.unwrap(); @@ -1435,7 +1435,7 @@ async fn dial_peer_when_sending_request(transport1: Transport, transport2: Trans let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); // add known address for `peer2` and start event loop for both litep2ps litep2p1.add_known_address(peer2, std::iter::once(address)); diff --git a/tests/substream.rs b/tests/substream.rs index efcf5011..a222bd54 100644 --- a/tests/substream.rs +++ b/tests/substream.rs @@ -218,7 +218,7 @@ impl UserProtocol for CustomProtocol { } async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let listen_address = litep2p1.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p2.dial_address(listen_address).await.unwrap(); let mut litep2p1_ready = false; diff --git a/tests/user_protocol.rs b/tests/user_protocol.rs index afd05e5a..5d767d80 100644 --- a/tests/user_protocol.rs +++ b/tests/user_protocol.rs @@ -99,7 +99,7 @@ async fn user_protocol() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses().next().unwrap().clone(); + let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); let custom_protocol2 = Box::new(CustomProtocol::new()); let config2 = ConfigBuilder::new() diff --git a/tests/user_protocol_2.rs b/tests/user_protocol_2.rs index 1c7e6910..d4b3e9ec 100644 --- a/tests/user_protocol_2.rs +++ b/tests/user_protocol_2.rs @@ -122,7 +122,7 @@ async fn user_protocol_2() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().next().unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); sender1.send(address).await.unwrap(); diff --git a/tests/webrtc.rs b/tests/webrtc.rs index fd0651f8..acacb5a4 100644 --- a/tests/webrtc.rs +++ b/tests/webrtc.rs @@ -58,7 +58,7 @@ async fn webrtc_test() { .build(); let mut litep2p = Litep2p::new(config).unwrap(); - let address = litep2p.listen_addresses().next().unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("listen address: {address:?}"); From fc0c70089bd7c3134c1fa20d9913c1a1eb3ffdc3 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 19:14:32 +0300 Subject: [PATCH 12/30] Use ListenAddresses everywhere Signed-off-by: Alexandru Vasile --- src/lib.rs | 2 +- src/listen_addresses.rs | 99 ++++++++++++++++--------------- src/protocol/libp2p/identify.rs | 23 +++---- src/protocol/transport_service.rs | 2 +- src/transport/manager/handle.rs | 35 +++++------ src/transport/manager/mod.rs | 26 ++++---- 6 files changed, 95 insertions(+), 92 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 07ab51e3..6f8452ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -452,7 +452,7 @@ impl Litep2p { /// Add one ore more known addresses for peer. /// /// Return value denotes how many addresses were added for the peer. - // Addresses belonging to disabled/unsupported transports will be ignored. + /// Addresses belonging to disabled/unsupported transports will be ignored. pub fn add_known_address( &mut self, peer: PeerId, diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index 52c44e48..b7c1a4f2 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -35,36 +35,22 @@ pub struct ListenAddresses { } impl ListenAddresses { - /// Creates new [`ListenAddresses`] from the inner set. - pub(crate) fn from_inner( - inner: Arc>>, - local_peer_id: PeerId, - ) -> Self { + /// Creates new [`ListenAddresses`] from the given peer ID. + pub(crate) fn new(local_peer_id: PeerId) -> Self { Self { - inner, + inner: Arc::new(RwLock::new(HashSet::new())), local_peer_id, } } /// Add a public address to the list of listen addresses. /// - /// The address must contain the local peer ID, otherwise it will be added. + /// The address must contain the local peer ID, otherwise the address will be modified to + /// include the local peer ID. /// /// Returns true if the address was added, false if it was already present. - pub fn register_listen_address(&self, mut address: Multiaddr) -> Result { - if address.is_empty() { - return Err(address); - } - - // Verify the peer ID from the address corresponds to the local peer ID. - if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { - if peer_id != self.local_peer_id { - return Err(address); - } - } else { - address.push(Protocol::P2p(self.local_peer_id.into())); - } - + pub fn register_listen_address(&self, address: Multiaddr) -> Result { + let address = self.add_local_peer(address)?; Ok(self.inner.write().insert(address)) } @@ -74,6 +60,8 @@ impl ListenAddresses { } /// Returns `true` if the set contains the given address. + /// + /// The address must contain the local peer ID. pub fn contains(&self, address: &Multiaddr) -> bool { self.inner.read().contains(address) } @@ -106,7 +94,7 @@ impl ListenAddresses { pub fn extend(&self, addresses: impl IntoIterator) { self.inner .write() - .extend(addresses.into_iter().filter(|address| !address.is_empty())); + .extend(addresses.into_iter().filter_map(|address| self.add_local_peer(address).ok())); } /// Returns the number of listen addresses. @@ -118,6 +106,24 @@ impl ListenAddresses { pub fn is_empty(&self) -> bool { self.inner.read().is_empty() } + + /// Modify the provided address to contain the local peer ID. + fn add_local_peer(&self, mut address: Multiaddr) -> Result { + if address.is_empty() { + return Err(address); + } + + // Verify the peer ID from the address corresponds to the local peer ID. + if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { + if peer_id != self.local_peer_id { + return Err(address); + } + } else { + address.push(Protocol::P2p(self.local_peer_id.into())); + } + + Ok(address) + } } /// A short lived instance of the locked listen addresses. @@ -142,7 +148,7 @@ mod tests { #[test] fn add_remove_contains() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::from_inner(Default::default(), peer_id); + let addresses = ListenAddresses::new(peer_id); let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") .unwrap() @@ -164,66 +170,63 @@ mod tests { #[test] fn get_addresses() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::from_inner(Default::default(), peer_id); - let address1 = Multiaddr::from_str( - "/dns/domain1.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", - ) - .unwrap(); - let address2 = Multiaddr::from_str( + let addresses = ListenAddresses::new(peer_id); + let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); + // Addresses different than the local peer ID are ignored. + let address3 = Multiaddr::from_str( "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", ) .unwrap(); assert!(addresses.register_listen_address(address1.clone()).unwrap()); assert!(addresses.register_listen_address(address2.clone()).unwrap()); + addresses.register_listen_address(address3.clone()).unwrap_err(); let addresses = addresses.get_addresses(); assert_eq!(addresses.len(), 2); - assert!(addresses.contains(&address1)); - assert!(addresses.contains(&address2)); + assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())))); + assert!(addresses.contains(&address2.with(Protocol::P2p(peer_id.into())))); } #[test] fn locked() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::from_inner(Default::default(), peer_id); - let address1 = Multiaddr::from_str( - "/dns/domain1.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", - ) - .unwrap(); + let addresses = ListenAddresses::new(peer_id); + let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let address2 = Multiaddr::from_str( "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", ) .unwrap(); assert!(addresses.register_listen_address(address1.clone()).unwrap()); - assert!(addresses.register_listen_address(address2.clone()).unwrap()); + addresses.register_listen_address(address2.clone()).unwrap_err(); let addresses = addresses.locked(); let addresses = addresses.iter().map(|address| address.to_vec()).collect::>(); - assert_eq!(addresses.len(), 2); - assert!(addresses.contains(&address1.to_vec())); - assert!(addresses.contains(&address2.to_vec())); + assert_eq!(addresses.len(), 1); + assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())).to_vec())); } #[test] fn extend() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::from_inner(Default::default(), peer_id); - let address1 = Multiaddr::from_str( - "/dns/domain1.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", - ) - .unwrap(); - let address2 = Multiaddr::from_str( + let addresses = ListenAddresses::new(peer_id); + let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333") + .unwrap() + .with(Protocol::P2p(peer_id.into())); + // Addresses different than the local peer ID are ignored. + let address3 = Multiaddr::from_str( "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", ) .unwrap(); - addresses.extend(vec![address1.clone(), address2.clone()]); + addresses.extend(vec![address1.clone(), address2.clone(), address3]); let addresses = addresses.get_addresses(); assert_eq!(addresses.len(), 2); - assert!(addresses.contains(&address1)); + assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())))); assert!(addresses.contains(&address2)); } } diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index e0f77261..29612974 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -414,11 +414,12 @@ impl Identify { mod tests { use super::*; use crate::{config::ConfigBuilder, transport::tcp::config::Config as TcpConfig, Litep2p}; - use multiaddr::Multiaddr; + use multiaddr::{Multiaddr, Protocol}; fn create_litep2p() -> ( Litep2p, Box + Send + Unpin>, + PeerId, ) { let (identify_config, identify) = Config::new( "1.0.0".to_string(), @@ -426,7 +427,10 @@ mod tests { vec![Multiaddr::empty()], ); + let keypair = crate::crypto::ed25519::Keypair::generate(); + let peer = PeerId::from_public_key(&crate::crypto::PublicKey::Ed25519(keypair.public())); let config = ConfigBuilder::new() + .with_keypair(keypair) .with_tcp(TcpConfig { listen_addresses: vec!["/ip6/::1/tcp/0".parse().unwrap()], ..Default::default() @@ -434,27 +438,26 @@ mod tests { .with_libp2p_identify(identify_config) .build(); - (Litep2p::new(config).unwrap(), identify) + (Litep2p::new(config).unwrap(), identify, peer) } #[tokio::test] async fn update_identify_addresses() { // Create two instances of litep2p - let (mut litep2p1, mut event_stream1) = create_litep2p(); - let (mut litep2p2, mut event_stream2) = create_litep2p(); + let (mut litep2p1, mut event_stream1, peer1) = create_litep2p(); + let (mut litep2p2, mut event_stream2, _peer2) = create_litep2p(); + let litep2p1_address = + litep2p1.listen_addresses().get_addresses().into_iter().next().unwrap(); let multiaddr: Multiaddr = "/ip6/::9/tcp/111".parse().unwrap(); // Litep2p1 is now reporting the new address. assert!(litep2p1.listen_addresses().register_listen_address(multiaddr.clone()).unwrap()); - let litep2p1_address = - litep2p1.listen_addresses().get_addresses().into_iter().next().unwrap(); - - println!(" listen_addresses: {:?}", litep2p1_address); - // Dial `litep2p1` litep2p2.dial_address(litep2p1_address).await.unwrap(); + let expected_multiaddr = multiaddr.with(Protocol::P2p(peer1.into())); + tokio::spawn(async move { loop { tokio::select! { @@ -473,7 +476,7 @@ mod tests { .. }) => { println!(" listen_addresses: {:?}", listen_addresses); - assert!(listen_addresses.iter().any(|address| address == &multiaddr)); + assert!(listen_addresses.iter().any(|address| address == &expected_multiaddr)); break; } _ => {} diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 067327bf..4ea4c030 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -445,7 +445,7 @@ mod tests { Arc::new(RwLock::new(HashMap::new())), cmd_tx, HashSet::new(), - Default::default(), + ListenAddresses::new(peer), ); let (service, sender) = TransportService::new( diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index d4c427fc..af6f123b 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -77,7 +77,7 @@ pub struct TransportManagerHandle { supported_transport: HashSet, /// Local listen addresess. - listen_addresses: Arc>>, + listen_addresses: ListenAddresses, } impl TransportManagerHandle { @@ -87,7 +87,7 @@ impl TransportManagerHandle { peers: Arc>>, cmd_tx: Sender, supported_transport: HashSet, - listen_addresses: Arc>>, + listen_addresses: ListenAddresses, ) -> Self { Self { peers, @@ -105,7 +105,7 @@ impl TransportManagerHandle { /// Get listen addresses. pub(crate) fn listen_addresses(&self) -> ListenAddresses { - ListenAddresses::from_inner(self.listen_addresses.clone(), self.local_peer_id) + self.listen_addresses.clone() } /// Check if `address` is supported by one of the enabled transports. @@ -157,7 +157,8 @@ impl TransportManagerHandle { .take_while(|protocol| !std::matches!(protocol, Protocol::P2p(_))) .collect(); - self.listen_addresses.read().contains(&address) + self.listen_addresses + .contains(&address.with(Protocol::P2p(self.local_peer_id.into()))) } /// Add one or more known addresses for peer. @@ -327,13 +328,14 @@ mod tests { ) { let (cmd_tx, cmd_rx) = channel(64); + let local_peer_id = PeerId::random(); ( TransportManagerHandle { - local_peer_id: PeerId::random(), + local_peer_id, cmd_tx, peers: Default::default(), supported_transport: HashSet::new(), - listen_addresses: Default::default(), + listen_addresses: ListenAddresses::new(local_peer_id), }, cmd_rx, ) @@ -593,21 +595,20 @@ mod tests { fn is_local_address() { let (cmd_tx, _cmd_rx) = channel(64); + let local_peer_id = PeerId::random(); + let first_addr: Multiaddr = "/ip6/::1/tcp/8888".parse().expect("valid multiaddress"); + let second_addr: Multiaddr = "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress"); + + let listen_addresses = ListenAddresses::new(local_peer_id); + listen_addresses.extend([first_addr.clone(), second_addr.clone()]); + println!("{:?}", listen_addresses); + let handle = TransportManagerHandle { - local_peer_id: PeerId::random(), + local_peer_id, cmd_tx, peers: Default::default(), supported_transport: HashSet::new(), - listen_addresses: Arc::new(RwLock::new(HashSet::from_iter([ - "/ip6/::1/tcp/8888".parse().expect("valid multiaddress"), - "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress"), - "/ip6/::1/tcp/8888/p2p/12D3KooWT2ouvz5uMmCvHJGzAGRHiqDts5hzXR7NdoQ27pGdzp9Q" - .parse() - .expect("valid multiaddress"), - "/ip4/127.0.0.1/tcp/8888/p2p/12D3KooWT2ouvz5uMmCvHJGzAGRHiqDts5hzXR7NdoQ27pGdzp9Q" - .parse() - .expect("valid multiaddress"), - ]))), + listen_addresses, }; // local addresses diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index bf39a770..d75c3913 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -40,7 +40,6 @@ use crate::{ use futures::{Stream, StreamExt}; use indexmap::IndexMap; use multiaddr::{Multiaddr, Protocol}; -use multihash::Multihash; use parking_lot::RwLock; use tokio::sync::mpsc::{channel, Receiver, Sender}; @@ -218,7 +217,7 @@ pub struct TransportManager { protocol_names: HashSet, /// Listen addresses. - listen_addresses: Arc>>, + listen_addresses: ListenAddresses, /// Next connection ID. next_connection_id: Arc, @@ -265,13 +264,13 @@ impl TransportManager { let peers = Arc::new(RwLock::new(HashMap::new())); let (cmd_tx, cmd_rx) = channel(256); let (event_tx, event_rx) = channel(256); - let listen_addresses = Arc::new(RwLock::new(HashSet::new())); + let listen_addresses = ListenAddresses::new(local_peer_id); let handle = TransportManagerHandle::new( local_peer_id, peers.clone(), cmd_tx, supported_transports, - Arc::clone(&listen_addresses), + listen_addresses.clone(), ); ( @@ -380,19 +379,14 @@ impl TransportManager { /// Get listen addresses. pub(crate) fn listen_addresses(&self) -> ListenAddresses { - ListenAddresses::from_inner(self.listen_addresses.clone(), self.local_peer_id) + self.listen_addresses.clone() } /// Register local listen address. pub fn register_listen_address(&mut self, address: Multiaddr) { - assert!(!address.iter().any(|protocol| std::matches!(protocol, Protocol::P2p(_)))); - - let mut listen_addresses = self.listen_addresses.write(); - - listen_addresses.insert(address.clone()); - listen_addresses.insert(address.with(Protocol::P2p( - Multihash::from_bytes(&self.local_peer_id.to_bytes()).unwrap(), - ))); + if let Err(address) = self.listen_addresses.register_listen_address(address) { + tracing::warn!(target: LOG_TARGET, ?address, "failed to register listen address"); + } } /// Add one or more known addresses for `peer`. @@ -482,7 +476,7 @@ impl TransportManager { } for record in records.values() { - if self.listen_addresses.read().contains(record.as_ref()) { + if self.listen_addresses.contains(record.as_ref()) { tracing::warn!( target: LOG_TARGET, ?peer, @@ -584,7 +578,7 @@ impl TransportManager { let mut record = AddressRecord::from_multiaddr(address) .ok_or(Error::AddressError(AddressError::PeerIdMissing))?; - if self.listen_addresses.read().contains(record.as_ref()) { + if self.listen_addresses.contains(record.as_ref()) { return Err(Error::TriedToDialSelf); } @@ -1763,6 +1757,8 @@ impl TransportManager { mod tests { use limits::ConnectionLimitsConfig; + use multihash::Multihash; + use super::*; use crate::{ crypto::ed25519::Keypair, From 7f07e9d926838faa9883852109ff059fd74887b4 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 28 Aug 2024 19:18:29 +0300 Subject: [PATCH 13/30] listen-addr: Add better documentation Signed-off-by: Alexandru Vasile --- src/listen_addresses.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index b7c1a4f2..d90bf91a 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -27,7 +27,14 @@ use crate::PeerId; /// Set of the public addresses of the local node. /// -/// These addresses are reported to the identify protocol. +/// The format of the addresses stored in the set contain the local peer ID. +/// This requirement is enforced by the [`ListenAddresses::register_listen_address`] method, +/// that will add the local peer ID to the address if it is missing. +/// +/// # Note +/// +/// - The addresses are reported to the identify protocol and are used to establish connections. +/// - Users must ensure that the addresses are reachable from the network. #[derive(Debug, Clone)] pub struct ListenAddresses { inner: Arc>>, From 794eba50fbd63ebe53eeb6c2732add200b665832 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Thu, 29 Aug 2024 11:38:27 +0300 Subject: [PATCH 14/30] listen-addr: Add contains and remove partial methods Signed-off-by: Alexandru Vasile --- src/listen_addresses.rs | 76 +++++++++++++++++++++++++++++++-- src/transport/manager/handle.rs | 8 +--- 2 files changed, 74 insertions(+), 10 deletions(-) diff --git a/src/listen_addresses.rs b/src/listen_addresses.rs index d90bf91a..41ebdfd9 100644 --- a/src/listen_addresses.rs +++ b/src/listen_addresses.rs @@ -61,18 +61,36 @@ impl ListenAddresses { Ok(self.inner.write().insert(address)) } - /// Remove public address. + /// Remove the exact public address. + /// + /// The provided address must contain the local peer ID. pub fn remove(&self, address: &Multiaddr) -> bool { self.inner.write().remove(address) } - /// Returns `true` if the set contains the given address. + /// Similar to [`ListenAddresses::remove`], but removes the address ignoring the peer ID. + pub fn remove_partial(&self, address: &Multiaddr) -> bool { + self.inner.write().remove(&self.replace_local_peer(address.clone())) + } + + /// Returns `true` if the set contains the exact address. /// - /// The address must contain the local peer ID. + /// The provided address must contain the local peer ID. + /// + /// If you want to check if the address is a local listen address, use + /// [`ListenAddresses::contains_partial`]. pub fn contains(&self, address: &Multiaddr) -> bool { self.inner.read().contains(address) } + /// Similar to [`ListenAddresses::contains`], but checks if the address ignoring the peer ID + /// is a local listen address. + /// + /// If you want to match the exact address, use [`ListenAddresses::contains`]. + pub fn contains_partial(&self, address: &Multiaddr) -> bool { + self.inner.read().contains(&self.replace_local_peer(address.clone())) + } + /// Returns a vector of the available listen addresses. pub fn get_addresses(&self) -> Vec { self.inner.read().iter().cloned().collect() @@ -114,6 +132,19 @@ impl ListenAddresses { self.inner.read().is_empty() } + /// Modify the provided address to contain the local peer ID. + /// + /// This method replaces any existing peer ID with the local peer ID. + fn replace_local_peer(&self, address: Multiaddr) -> Multiaddr { + let mut address: Multiaddr = address + .iter() + .take_while(|protocol| !std::matches!(protocol, Protocol::P2p(_))) + .collect(); + address.push(Protocol::P2p(self.local_peer_id.into())); + + address + } + /// Modify the provided address to contain the local peer ID. fn add_local_peer(&self, mut address: Multiaddr) -> Result { if address.is_empty() { @@ -236,4 +267,43 @@ mod tests { assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())))); assert!(addresses.contains(&address2)); } + + #[test] + fn contains_partial() { + let peer_id = PeerId::random(); + let addresses = ListenAddresses::new(peer_id); + let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") + .unwrap() + .with(Protocol::P2p(peer_id.into())); + + assert!(!addresses.contains_partial(&peer_address)); + assert!(!addresses.contains_partial(&address)); + + addresses.register_listen_address(peer_address.clone()).unwrap(); + assert!(addresses.contains_partial(&address)); + assert!(addresses.contains_partial(&peer_address)); + + assert!(!addresses.contains(&address)); + assert!(addresses.contains(&peer_address)); + } + + #[test] + fn remove_partial() { + let peer_id = PeerId::random(); + let addresses = ListenAddresses::new(peer_id); + let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") + .unwrap() + .with(Protocol::P2p(peer_id.into())); + + addresses.register_listen_address(peer_address.clone()).unwrap(); + assert!(addresses.contains(&peer_address)); + + assert!(addresses.remove_partial(&address)); + assert!(!addresses.contains(&peer_address)); + + // Already removed. + assert!(!addresses.remove(&peer_address)); + } } diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index af6f123b..dbd58736 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -152,13 +152,7 @@ impl TransportManagerHandle { /// Check if the address is a local listen address and if so, discard it. fn is_local_address(&self, address: &Multiaddr) -> bool { - let address: Multiaddr = address - .iter() - .take_while(|protocol| !std::matches!(protocol, Protocol::P2p(_))) - .collect(); - - self.listen_addresses - .contains(&address.with(Protocol::P2p(self.local_peer_id.into()))) + self.listen_addresses.contains_partial(&address) } /// Add one or more known addresses for peer. From e11a99630bb9df9170605da00a569ac36efdcefd Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Fri, 30 Aug 2024 14:11:34 +0000 Subject: [PATCH 15/30] Rename to ExternalAddresses for clarity Signed-off-by: Alexandru Vasile --- ...ten_addresses.rs => external_addresses.rs} | 40 +++++++++---------- src/lib.rs | 8 ++-- src/protocol/libp2p/identify.rs | 4 +- src/protocol/transport_service.rs | 6 +-- src/transport/manager/handle.rs | 12 +++--- src/transport/manager/mod.rs | 8 ++-- 6 files changed, 39 insertions(+), 39 deletions(-) rename src/{listen_addresses.rs => external_addresses.rs} (89%) diff --git a/src/listen_addresses.rs b/src/external_addresses.rs similarity index 89% rename from src/listen_addresses.rs rename to src/external_addresses.rs index 41ebdfd9..8bbf671b 100644 --- a/src/listen_addresses.rs +++ b/src/external_addresses.rs @@ -28,7 +28,7 @@ use crate::PeerId; /// Set of the public addresses of the local node. /// /// The format of the addresses stored in the set contain the local peer ID. -/// This requirement is enforced by the [`ListenAddresses::register_listen_address`] method, +/// This requirement is enforced by the [`ExternalAddresses::register_listen_address`] method, /// that will add the local peer ID to the address if it is missing. /// /// # Note @@ -36,13 +36,13 @@ use crate::PeerId; /// - The addresses are reported to the identify protocol and are used to establish connections. /// - Users must ensure that the addresses are reachable from the network. #[derive(Debug, Clone)] -pub struct ListenAddresses { +pub struct ExternalAddresses { inner: Arc>>, local_peer_id: PeerId, } -impl ListenAddresses { - /// Creates new [`ListenAddresses`] from the given peer ID. +impl ExternalAddresses { + /// Creates new [`ExternalAddresses`] from the given peer ID. pub(crate) fn new(local_peer_id: PeerId) -> Self { Self { inner: Arc::new(RwLock::new(HashSet::new())), @@ -68,7 +68,7 @@ impl ListenAddresses { self.inner.write().remove(address) } - /// Similar to [`ListenAddresses::remove`], but removes the address ignoring the peer ID. + /// Similar to [`ExternalAddresses::remove`], but removes the address ignoring the peer ID. pub fn remove_partial(&self, address: &Multiaddr) -> bool { self.inner.write().remove(&self.replace_local_peer(address.clone())) } @@ -78,15 +78,15 @@ impl ListenAddresses { /// The provided address must contain the local peer ID. /// /// If you want to check if the address is a local listen address, use - /// [`ListenAddresses::contains_partial`]. + /// [`ExternalAddresses::contains_partial`]. pub fn contains(&self, address: &Multiaddr) -> bool { self.inner.read().contains(address) } - /// Similar to [`ListenAddresses::contains`], but checks if the address ignoring the peer ID + /// Similar to [`ExternalAddresses::contains`], but checks if the address ignoring the peer ID /// is a local listen address. /// - /// If you want to match the exact address, use [`ListenAddresses::contains`]. + /// If you want to match the exact address, use [`ExternalAddresses::contains`]. pub fn contains_partial(&self, address: &Multiaddr) -> bool { self.inner.read().contains(&self.replace_local_peer(address.clone())) } @@ -103,14 +103,14 @@ impl ListenAddresses { /// # Example /// /// ```rust - /// # use litep2p::listen_addresses::ListenAddresses; + /// # use litep2p::listen_addresses::ExternalAddresses; /// # - /// # fn listen_addresses(addresses: ListenAddresses) { + /// # fn external_addresses(addresses: ExternalAddresses) { /// let string_addresses = addresses.locked().iter().map(|address| address.to_string()).collect::>(); /// # } /// ``` - pub fn locked(&self) -> LockedListenAddresses { - LockedListenAddresses { + pub fn locked(&self) -> LockedExternalAddresses { + LockedExternalAddresses { inner: self.inner.read(), } } @@ -165,11 +165,11 @@ impl ListenAddresses { } /// A short lived instance of the locked listen addresses. -pub struct LockedListenAddresses<'a> { +pub struct LockedExternalAddresses<'a> { inner: parking_lot::RwLockReadGuard<'a, HashSet>, } -impl<'a> LockedListenAddresses<'a> { +impl<'a> LockedExternalAddresses<'a> { /// Iterate over the listen addresses. /// /// This exposes all the functionality of the standard iterator. @@ -186,7 +186,7 @@ mod tests { #[test] fn add_remove_contains() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::new(peer_id); + let addresses = ExternalAddresses::new(peer_id); let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") .unwrap() @@ -208,7 +208,7 @@ mod tests { #[test] fn get_addresses() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::new(peer_id); + let addresses = ExternalAddresses::new(peer_id); let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); // Addresses different than the local peer ID are ignored. @@ -230,7 +230,7 @@ mod tests { #[test] fn locked() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::new(peer_id); + let addresses = ExternalAddresses::new(peer_id); let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let address2 = Multiaddr::from_str( "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", @@ -249,7 +249,7 @@ mod tests { #[test] fn extend() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::new(peer_id); + let addresses = ExternalAddresses::new(peer_id); let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333") .unwrap() @@ -271,7 +271,7 @@ mod tests { #[test] fn contains_partial() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::new(peer_id); + let addresses = ExternalAddresses::new(peer_id); let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") .unwrap() @@ -291,7 +291,7 @@ mod tests { #[test] fn remove_partial() { let peer_id = PeerId::random(); - let addresses = ListenAddresses::new(peer_id); + let addresses = ExternalAddresses::new(peer_id); let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") .unwrap() diff --git a/src/lib.rs b/src/lib.rs index 43de2f92..a1bc6e21 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,7 +31,7 @@ use crate::{ config::Litep2pConfig, error::DialError, - listen_addresses::ListenAddresses, + external_addresses::ExternalAddresses, protocol::{ libp2p::{bitswap::Bitswap, identify::Identify, kademlia::Kademlia, ping::Ping}, mdns::Mdns, @@ -70,7 +70,7 @@ pub mod config; pub mod crypto; pub mod error; pub mod executor; -pub mod listen_addresses; +pub mod external_addresses; pub mod protocol; pub mod substream; pub mod transport; @@ -139,7 +139,7 @@ pub struct Litep2p { local_peer_id: PeerId, /// Listen addresses. - listen_addresses: ListenAddresses, + listen_addresses: ExternalAddresses, /// Transport manager. transport_manager: TransportManager, @@ -441,7 +441,7 @@ impl Litep2p { } /// Get the listen address of litep2p. - pub fn listen_addresses(&self) -> ListenAddresses { + pub fn external_addresses(&self) -> ExternalAddresses { self.listen_addresses.clone() } diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 29612974..d3f24b43 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -24,7 +24,7 @@ use crate::{ codec::ProtocolCodec, crypto::PublicKey, error::{Error, SubstreamError}, - listen_addresses::ListenAddresses, + external_addresses::ExternalAddresses, protocol::{Direction, TransportEvent, TransportService}, substream::Substream, transport::Endpoint, @@ -184,7 +184,7 @@ pub(crate) struct Identify { user_agent: String, /// Public addresses. - listen_addresses: ListenAddresses, + listen_addresses: ExternalAddresses, /// Protocols supported by the local node, filled by `Litep2p`. protocols: Vec, diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 4ea4c030..173a4834 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -20,7 +20,7 @@ use crate::{ error::Error, - listen_addresses::ListenAddresses, + external_addresses::ExternalAddresses, protocol::{connection::ConnectionHandle, InnerTransportEvent, TransportEvent}, transport::{manager::TransportManagerHandle, Endpoint}, types::{protocol::ProtocolName, ConnectionId, SubstreamId}, @@ -159,7 +159,7 @@ impl TransportService { } /// Get the listen address of litep2p. - pub fn listen_addresses(&self) -> ListenAddresses { + pub fn external_addresses(&self) -> ExternalAddresses { self.transport_handle.listen_addresses() } @@ -445,7 +445,7 @@ mod tests { Arc::new(RwLock::new(HashMap::new())), cmd_tx, HashSet::new(), - ListenAddresses::new(peer), + ExternalAddresses::new(peer), ); let (service, sender) = TransportService::new( diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index dbd58736..8bd413e7 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -22,7 +22,7 @@ use crate::{ crypto::ed25519::Keypair, error::{AddressError, Error}, executor::Executor, - listen_addresses::ListenAddresses, + external_addresses::ExternalAddresses, protocol::ProtocolSet, transport::manager::{ address::{AddressRecord, AddressStore}, @@ -77,7 +77,7 @@ pub struct TransportManagerHandle { supported_transport: HashSet, /// Local listen addresess. - listen_addresses: ListenAddresses, + listen_addresses: ExternalAddresses, } impl TransportManagerHandle { @@ -87,7 +87,7 @@ impl TransportManagerHandle { peers: Arc>>, cmd_tx: Sender, supported_transport: HashSet, - listen_addresses: ListenAddresses, + listen_addresses: ExternalAddresses, ) -> Self { Self { peers, @@ -104,7 +104,7 @@ impl TransportManagerHandle { } /// Get listen addresses. - pub(crate) fn listen_addresses(&self) -> ListenAddresses { + pub(crate) fn external_addresses(&self) -> ExternalAddresses { self.listen_addresses.clone() } @@ -329,7 +329,7 @@ mod tests { cmd_tx, peers: Default::default(), supported_transport: HashSet::new(), - listen_addresses: ListenAddresses::new(local_peer_id), + listen_addresses: ExternalAddresses::new(local_peer_id), }, cmd_rx, ) @@ -593,7 +593,7 @@ mod tests { let first_addr: Multiaddr = "/ip6/::1/tcp/8888".parse().expect("valid multiaddress"); let second_addr: Multiaddr = "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress"); - let listen_addresses = ListenAddresses::new(local_peer_id); + let listen_addresses = ExternalAddresses::new(local_peer_id); listen_addresses.extend([first_addr.clone(), second_addr.clone()]); println!("{:?}", listen_addresses); diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index ce1d4bf5..de11ca94 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -23,7 +23,7 @@ use crate::{ crypto::ed25519::Keypair, error::{AddressError, DialError, Error}, executor::Executor, - listen_addresses::ListenAddresses, + external_addresses::ExternalAddresses, protocol::{InnerTransportEvent, TransportService}, transport::{ manager::{ @@ -217,7 +217,7 @@ pub struct TransportManager { protocol_names: HashSet, /// Listen addresses. - listen_addresses: ListenAddresses, + listen_addresses: ExternalAddresses, /// Next connection ID. next_connection_id: Arc, @@ -267,7 +267,7 @@ impl TransportManager { let peers = Arc::new(RwLock::new(HashMap::new())); let (cmd_tx, cmd_rx) = channel(256); let (event_tx, event_rx) = channel(256); - let listen_addresses = ListenAddresses::new(local_peer_id); + let listen_addresses = ExternalAddresses::new(local_peer_id); let handle = TransportManagerHandle::new( local_peer_id, peers.clone(), @@ -382,7 +382,7 @@ impl TransportManager { } /// Get listen addresses. - pub(crate) fn listen_addresses(&self) -> ListenAddresses { + pub(crate) fn external_addresses(&self) -> ExternalAddresses { self.listen_addresses.clone() } From 09b6feee0a8fcbd0bd297d90837e21b4cb735386 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Mon, 2 Sep 2024 11:31:39 +0000 Subject: [PATCH 16/30] Refactor and adjust testing Signed-off-by: Alexandru Vasile --- examples/custom_executor.rs | 2 +- examples/custom_protocol.rs | 2 +- examples/echo_notification.rs | 2 +- examples/gossiping.rs | 2 +- src/external_addresses.rs | 309 ------------------ src/lib.rs | 14 +- src/protocol/libp2p/identify.rs | 34 +- src/protocol/transport_service.rs | 10 +- src/public_addresses.rs | 145 ++++++++ src/transport/manager/handle.rs | 25 +- src/transport/manager/mod.rs | 18 +- tests/conformance/rust/identify.rs | 2 +- tests/conformance/rust/kademlia.rs | 6 +- tests/conformance/rust/ping.rs | 2 +- tests/conformance/substrate/connection.rs | 2 +- tests/conformance/substrate/notifications.rs | 14 +- .../conformance/substrate/request_response.rs | 10 +- tests/connection/mod.rs | 44 ++- tests/custom_executor.rs | 2 +- tests/protocol/identify.rs | 6 +- tests/protocol/kademlia.rs | 8 +- tests/protocol/notification.rs | 22 +- tests/protocol/ping.rs | 2 +- tests/protocol/request_response.rs | 4 +- tests/substream.rs | 2 +- tests/user_protocol.rs | 2 +- tests/user_protocol_2.rs | 2 +- tests/webrtc.rs | 2 +- 28 files changed, 276 insertions(+), 419 deletions(-) delete mode 100644 src/external_addresses.rs create mode 100644 src/public_addresses.rs diff --git a/examples/custom_executor.rs b/examples/custom_executor.rs index 5a5cbd98..90084d99 100644 --- a/examples/custom_executor.rs +++ b/examples/custom_executor.rs @@ -122,7 +122,7 @@ async fn main() { // dial `litep2p1` litep2p2 - .dial_address(litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone()) + .dial_address(litep2p1.public_addresses().get_addresses().get(0).unwrap().clone()) .await .unwrap(); diff --git a/examples/custom_protocol.rs b/examples/custom_protocol.rs index 7eead39f..a39cc425 100644 --- a/examples/custom_protocol.rs +++ b/examples/custom_protocol.rs @@ -277,7 +277,7 @@ async fn main() { let (mut litep2p2, mut handle2) = make_litep2p(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(listen_address)); tokio::spawn(async move { diff --git a/examples/echo_notification.rs b/examples/echo_notification.rs index 4521c934..d2e324a8 100644 --- a/examples/echo_notification.rs +++ b/examples/echo_notification.rs @@ -125,7 +125,7 @@ async fn main() { // get the first (and only) listen address for the second peer // and add it as a known address for `litep2p1` - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); let peer = *litep2p2.local_peer_id(); litep2p1.add_known_address(peer, vec![listen_address].into_iter()); diff --git a/examples/gossiping.rs b/examples/gossiping.rs index 730d23db..a24c7a2f 100644 --- a/examples/gossiping.rs +++ b/examples/gossiping.rs @@ -237,7 +237,7 @@ async fn main() { // establish connection to litep2p for all other litep2ps let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address.clone()].into_iter()); litep2p3.add_known_address(peer2, vec![listen_address.clone()].into_iter()); diff --git a/src/external_addresses.rs b/src/external_addresses.rs deleted file mode 100644 index 8bbf671b..00000000 --- a/src/external_addresses.rs +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright 2024 litep2p developers -// -// 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 std::{collections::HashSet, sync::Arc}; - -use multiaddr::{Multiaddr, Protocol}; -use parking_lot::RwLock; - -use crate::PeerId; - -/// Set of the public addresses of the local node. -/// -/// The format of the addresses stored in the set contain the local peer ID. -/// This requirement is enforced by the [`ExternalAddresses::register_listen_address`] method, -/// that will add the local peer ID to the address if it is missing. -/// -/// # Note -/// -/// - The addresses are reported to the identify protocol and are used to establish connections. -/// - Users must ensure that the addresses are reachable from the network. -#[derive(Debug, Clone)] -pub struct ExternalAddresses { - inner: Arc>>, - local_peer_id: PeerId, -} - -impl ExternalAddresses { - /// Creates new [`ExternalAddresses`] from the given peer ID. - pub(crate) fn new(local_peer_id: PeerId) -> Self { - Self { - inner: Arc::new(RwLock::new(HashSet::new())), - local_peer_id, - } - } - - /// Add a public address to the list of listen addresses. - /// - /// The address must contain the local peer ID, otherwise the address will be modified to - /// include the local peer ID. - /// - /// Returns true if the address was added, false if it was already present. - pub fn register_listen_address(&self, address: Multiaddr) -> Result { - let address = self.add_local_peer(address)?; - Ok(self.inner.write().insert(address)) - } - - /// Remove the exact public address. - /// - /// The provided address must contain the local peer ID. - pub fn remove(&self, address: &Multiaddr) -> bool { - self.inner.write().remove(address) - } - - /// Similar to [`ExternalAddresses::remove`], but removes the address ignoring the peer ID. - pub fn remove_partial(&self, address: &Multiaddr) -> bool { - self.inner.write().remove(&self.replace_local_peer(address.clone())) - } - - /// Returns `true` if the set contains the exact address. - /// - /// The provided address must contain the local peer ID. - /// - /// If you want to check if the address is a local listen address, use - /// [`ExternalAddresses::contains_partial`]. - pub fn contains(&self, address: &Multiaddr) -> bool { - self.inner.read().contains(address) - } - - /// Similar to [`ExternalAddresses::contains`], but checks if the address ignoring the peer ID - /// is a local listen address. - /// - /// If you want to match the exact address, use [`ExternalAddresses::contains`]. - pub fn contains_partial(&self, address: &Multiaddr) -> bool { - self.inner.read().contains(&self.replace_local_peer(address.clone())) - } - - /// Returns a vector of the available listen addresses. - pub fn get_addresses(&self) -> Vec { - self.inner.read().iter().cloned().collect() - } - - /// Returns an immutable reference to the set of listen addresses. - /// - /// This method can be used when `get_addresses` is not sufficient. - /// - /// # Example - /// - /// ```rust - /// # use litep2p::listen_addresses::ExternalAddresses; - /// # - /// # fn external_addresses(addresses: ExternalAddresses) { - /// let string_addresses = addresses.locked().iter().map(|address| address.to_string()).collect::>(); - /// # } - /// ``` - pub fn locked(&self) -> LockedExternalAddresses { - LockedExternalAddresses { - inner: self.inner.read(), - } - } - - /// Extend public addresses. - pub fn extend(&self, addresses: impl IntoIterator) { - self.inner - .write() - .extend(addresses.into_iter().filter_map(|address| self.add_local_peer(address).ok())); - } - - /// Returns the number of listen addresses. - pub fn len(&self) -> usize { - self.inner.read().len() - } - - /// Returns `true` if the set of listen addresses is empty. - pub fn is_empty(&self) -> bool { - self.inner.read().is_empty() - } - - /// Modify the provided address to contain the local peer ID. - /// - /// This method replaces any existing peer ID with the local peer ID. - fn replace_local_peer(&self, address: Multiaddr) -> Multiaddr { - let mut address: Multiaddr = address - .iter() - .take_while(|protocol| !std::matches!(protocol, Protocol::P2p(_))) - .collect(); - address.push(Protocol::P2p(self.local_peer_id.into())); - - address - } - - /// Modify the provided address to contain the local peer ID. - fn add_local_peer(&self, mut address: Multiaddr) -> Result { - if address.is_empty() { - return Err(address); - } - - // Verify the peer ID from the address corresponds to the local peer ID. - if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { - if peer_id != self.local_peer_id { - return Err(address); - } - } else { - address.push(Protocol::P2p(self.local_peer_id.into())); - } - - Ok(address) - } -} - -/// A short lived instance of the locked listen addresses. -pub struct LockedExternalAddresses<'a> { - inner: parking_lot::RwLockReadGuard<'a, HashSet>, -} - -impl<'a> LockedExternalAddresses<'a> { - /// Iterate over the listen addresses. - /// - /// This exposes all the functionality of the standard iterator. - pub fn iter(&self) -> impl Iterator { - self.inner.iter() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::str::FromStr; - - #[test] - fn add_remove_contains() { - let peer_id = PeerId::random(); - let addresses = ExternalAddresses::new(peer_id); - let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") - .unwrap() - .with(Protocol::P2p(peer_id.into())); - - assert!(!addresses.contains(&address)); - - assert!(addresses.register_listen_address(address.clone()).unwrap()); - // Adding the address a second time returns Ok(false). - assert!(!addresses.register_listen_address(address.clone()).unwrap()); - - assert!(!addresses.contains(&address)); - assert!(addresses.contains(&peer_address)); - - addresses.remove(&peer_address); - assert!(!addresses.contains(&peer_address)); - } - - #[test] - fn get_addresses() { - let peer_id = PeerId::random(); - let addresses = ExternalAddresses::new(peer_id); - let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); - // Addresses different than the local peer ID are ignored. - let address3 = Multiaddr::from_str( - "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", - ) - .unwrap(); - - assert!(addresses.register_listen_address(address1.clone()).unwrap()); - assert!(addresses.register_listen_address(address2.clone()).unwrap()); - addresses.register_listen_address(address3.clone()).unwrap_err(); - - let addresses = addresses.get_addresses(); - assert_eq!(addresses.len(), 2); - assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())))); - assert!(addresses.contains(&address2.with(Protocol::P2p(peer_id.into())))); - } - - #[test] - fn locked() { - let peer_id = PeerId::random(); - let addresses = ExternalAddresses::new(peer_id); - let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let address2 = Multiaddr::from_str( - "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", - ) - .unwrap(); - - assert!(addresses.register_listen_address(address1.clone()).unwrap()); - addresses.register_listen_address(address2.clone()).unwrap_err(); - - let addresses = addresses.locked(); - let addresses = addresses.iter().map(|address| address.to_vec()).collect::>(); - assert_eq!(addresses.len(), 1); - assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())).to_vec())); - } - - #[test] - fn extend() { - let peer_id = PeerId::random(); - let addresses = ExternalAddresses::new(peer_id); - let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333") - .unwrap() - .with(Protocol::P2p(peer_id.into())); - // Addresses different than the local peer ID are ignored. - let address3 = Multiaddr::from_str( - "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", - ) - .unwrap(); - - addresses.extend(vec![address1.clone(), address2.clone(), address3]); - - let addresses = addresses.get_addresses(); - assert_eq!(addresses.len(), 2); - assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())))); - assert!(addresses.contains(&address2)); - } - - #[test] - fn contains_partial() { - let peer_id = PeerId::random(); - let addresses = ExternalAddresses::new(peer_id); - let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") - .unwrap() - .with(Protocol::P2p(peer_id.into())); - - assert!(!addresses.contains_partial(&peer_address)); - assert!(!addresses.contains_partial(&address)); - - addresses.register_listen_address(peer_address.clone()).unwrap(); - assert!(addresses.contains_partial(&address)); - assert!(addresses.contains_partial(&peer_address)); - - assert!(!addresses.contains(&address)); - assert!(addresses.contains(&peer_address)); - } - - #[test] - fn remove_partial() { - let peer_id = PeerId::random(); - let addresses = ExternalAddresses::new(peer_id); - let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); - let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") - .unwrap() - .with(Protocol::P2p(peer_id.into())); - - addresses.register_listen_address(peer_address.clone()).unwrap(); - assert!(addresses.contains(&peer_address)); - - assert!(addresses.remove_partial(&address)); - assert!(!addresses.contains(&peer_address)); - - // Already removed. - assert!(!addresses.remove(&peer_address)); - } -} diff --git a/src/lib.rs b/src/lib.rs index a1bc6e21..e46714d3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,13 +31,13 @@ use crate::{ config::Litep2pConfig, error::DialError, - external_addresses::ExternalAddresses, protocol::{ libp2p::{bitswap::Bitswap, identify::Identify, kademlia::Kademlia, ping::Ping}, mdns::Mdns, notification::NotificationProtocol, request_response::RequestResponseProtocol, }, + public_addresses::PublicAddresses, transport::{ manager::{SupportedTransport, TransportManager}, tcp::TcpTransport, @@ -70,8 +70,8 @@ pub mod config; pub mod crypto; pub mod error; pub mod executor; -pub mod external_addresses; pub mod protocol; +pub mod public_addresses; pub mod substream; pub mod transport; pub mod types; @@ -139,7 +139,7 @@ pub struct Litep2p { local_peer_id: PeerId, /// Listen addresses. - listen_addresses: ExternalAddresses, + listen_addresses: PublicAddresses, /// Transport manager. transport_manager: TransportManager, @@ -363,7 +363,7 @@ impl Litep2p { .register_transport(SupportedTransport::WebSocket, Box::new(transport)); } - let listen_addresses = transport_manager.listen_addresses(); + let listen_addresses = transport_manager.public_addresses(); // enable mdns if the config exists if let Some(config) = litep2p_config.mdns.take() { @@ -389,7 +389,7 @@ impl Litep2p { } // verify that at least one transport is specified - if listen_addresses.is_empty() { + if listen_addresses.inner.read().is_empty() { tracing::warn!( target: LOG_TARGET, "litep2p started with no listen addresses, cannot accept inbound connections", @@ -440,8 +440,8 @@ impl Litep2p { &self.local_peer_id } - /// Get the listen address of litep2p. - pub fn external_addresses(&self) -> ExternalAddresses { + /// Get the list of public addresses of the node. + pub fn public_addresses(&self) -> PublicAddresses { self.listen_addresses.clone() } diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index d3f24b43..695991ca 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -24,8 +24,8 @@ use crate::{ codec::ProtocolCodec, crypto::PublicKey, error::{Error, SubstreamError}, - external_addresses::ExternalAddresses, protocol::{Direction, TransportEvent, TransportService}, + public_addresses::PublicAddresses, substream::Substream, transport::Endpoint, types::{protocol::ProtocolName, SubstreamId}, @@ -33,7 +33,7 @@ use crate::{ }; use futures::{future::BoxFuture, stream::FuturesUnordered, Stream, StreamExt}; -use multiaddr::Multiaddr; +use multiaddr::{Multiaddr, Protocol}; use prost::Message; use tokio::sync::mpsc::{channel, Sender}; use tokio_stream::wrappers::ReceiverStream; @@ -184,7 +184,7 @@ pub(crate) struct Identify { user_agent: String, /// Public addresses. - listen_addresses: ExternalAddresses, + listen_addresses: PublicAddresses, /// Protocols supported by the local node, filled by `Litep2p`. protocols: Vec, @@ -202,8 +202,24 @@ pub(crate) struct Identify { impl Identify { /// Create new [`Identify`] protocol. pub(crate) fn new(service: TransportService, config: Config) -> Self { - let listen_addresses = service.listen_addresses(); - listen_addresses.extend(config.public_addresses.into_iter()); + let listen_addresses = service.public_addresses(); + + let local_peer_id = service.local_peer_id; + let filtered_public_addr = config.public_addresses.into_iter().filter_map(|address| { + if address.is_empty() { + return None; + } + if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { + if peer_id != local_peer_id { + return None; + } + + return Some(address); + } + + Some(address.with(Protocol::P2p(local_peer_id.into()))) + }); + listen_addresses.inner.write().extend(filtered_public_addr); Self { service, @@ -265,11 +281,13 @@ impl Identify { } }; + let listen_addrs = + self.listen_addresses.inner.read().iter().map(|addr| addr.to_vec()).collect(); let identify = identify_schema::Identify { protocol_version: Some(self.protocol_version.clone()), agent_version: Some(self.user_agent.clone()), public_key: Some(self.public.to_protobuf_encoding()), - listen_addrs: self.listen_addresses.locked().iter().map(|addr| addr.to_vec()).collect(), + listen_addrs, observed_addr, protocols: self.protocols.clone(), }; @@ -447,11 +465,11 @@ mod tests { let (mut litep2p1, mut event_stream1, peer1) = create_litep2p(); let (mut litep2p2, mut event_stream2, _peer2) = create_litep2p(); let litep2p1_address = - litep2p1.listen_addresses().get_addresses().into_iter().next().unwrap(); + litep2p1.public_addresses().get_addresses().into_iter().next().unwrap(); let multiaddr: Multiaddr = "/ip6/::9/tcp/111".parse().unwrap(); // Litep2p1 is now reporting the new address. - assert!(litep2p1.listen_addresses().register_listen_address(multiaddr.clone()).unwrap()); + assert!(litep2p1.public_addresses().add_public_address(multiaddr.clone()).unwrap()); // Dial `litep2p1` litep2p2.dial_address(litep2p1_address).await.unwrap(); diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 173a4834..e17a2732 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -20,7 +20,7 @@ use crate::{ error::Error, - external_addresses::ExternalAddresses, + public_addresses::PublicAddresses, protocol::{connection::ConnectionHandle, InnerTransportEvent, TransportEvent}, transport::{manager::TransportManagerHandle, Endpoint}, types::{protocol::ProtocolName, ConnectionId, SubstreamId}, @@ -158,9 +158,9 @@ impl TransportService { ) } - /// Get the listen address of litep2p. - pub fn external_addresses(&self) -> ExternalAddresses { - self.transport_handle.listen_addresses() + /// Get the list of public addresses of the node. + pub fn public_addresses(&self) -> PublicAddresses { + self.transport_handle.public_addresses() } /// Handle connection established event. @@ -445,7 +445,7 @@ mod tests { Arc::new(RwLock::new(HashMap::new())), cmd_tx, HashSet::new(), - ExternalAddresses::new(peer), + PublicAddresses::new(peer), ); let (service, sender) = TransportService::new( diff --git a/src/public_addresses.rs b/src/public_addresses.rs new file mode 100644 index 00000000..bebb6b2e --- /dev/null +++ b/src/public_addresses.rs @@ -0,0 +1,145 @@ +// Copyright 2024 litep2p developers +// +// 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 std::{collections::HashSet, sync::Arc}; + +use multiaddr::{Multiaddr, Protocol}; +use parking_lot::RwLock; + +use crate::PeerId; + +/// Set of the public addresses of the local node. +/// +/// The format of the addresses stored in the set contain the local peer ID. +/// This requirement is enforced by the [`PublicAddresses::register_listen_address`] method, +/// that will add the local peer ID to the address if it is missing. +/// +/// # Note +/// +/// - The addresses are reported to the identify protocol and are used by other nodes +/// to establish a connection with the local node. +/// +/// - Users must ensure that the addresses are reachable from the network. +#[derive(Debug, Clone)] +pub struct PublicAddresses { + pub(crate) inner: Arc>>, + local_peer_id: PeerId, +} + +impl PublicAddresses { + /// Creates new [`PublicAddresses`] from the given peer ID. + pub(crate) fn new(local_peer_id: PeerId) -> Self { + Self { + inner: Arc::new(RwLock::new(HashSet::new())), + local_peer_id, + } + } + + /// Add a public address to the list of addresses. + /// + /// The address must contain the local peer ID, otherwise an error is returned. + /// In case the address does not contain any peer ID, it will be added. + /// + /// Returns true if the address was added, false if it was already present. + pub fn add_public_address(&self, address: Multiaddr) -> Result { + let address = self.check_local_peer(address)?; + Ok(self.inner.write().insert(address)) + } + + /// Remove the exact public address. + /// + /// The provided address must contain the local peer ID. + pub fn remove_public_address(&self, address: &Multiaddr) -> bool { + self.inner.write().remove(address) + } + + /// Returns a vector of the available listen addresses. + pub fn get_addresses(&self) -> Vec { + self.inner.read().iter().cloned().collect() + } + + /// Checks if the address contains the local peer ID. + fn check_local_peer(&self, mut address: Multiaddr) -> Result { + if address.is_empty() { + return Err(address); + } + + // Verify the peer ID from the address corresponds to the local peer ID. + if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { + if peer_id != self.local_peer_id { + return Err(address); + } + } else { + address.push(Protocol::P2p(self.local_peer_id.into())); + } + + Ok(address) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::str::FromStr; + + #[test] + fn add_remove_contains() { + let peer_id = PeerId::random(); + let addresses = PublicAddresses::new(peer_id); + let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") + .unwrap() + .with(Protocol::P2p(peer_id.into())); + + assert!(!addresses.get_addresses().contains(&address)); + + assert!(addresses.add_public_address(address.clone()).unwrap()); + // Adding the address a second time returns Ok(false). + assert!(!addresses.add_public_address(address.clone()).unwrap()); + + assert!(!addresses.get_addresses().contains(&address)); + assert!(addresses.get_addresses().contains(&peer_address)); + + addresses.remove_public_address(&peer_address); + assert!(!addresses.get_addresses().contains(&peer_address)); + } + + #[test] + fn get_addresses() { + let peer_id = PeerId::random(); + let addresses = PublicAddresses::new(peer_id); + let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); + let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); + // Addresses different than the local peer ID are ignored. + let address3 = Multiaddr::from_str( + "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", + ) + .unwrap(); + + assert!(addresses.add_public_address(address1.clone()).unwrap()); + assert!(addresses.add_public_address(address2.clone()).unwrap()); + addresses.add_public_address(address3.clone()).unwrap_err(); + + let addresses = addresses.get_addresses(); + assert_eq!(addresses.len(), 2); + assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())))); + assert!(addresses.contains(&address2.with(Protocol::P2p(peer_id.into())))); + } +} diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index 8bd413e7..9553ad9a 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -22,8 +22,8 @@ use crate::{ crypto::ed25519::Keypair, error::{AddressError, Error}, executor::Executor, - external_addresses::ExternalAddresses, protocol::ProtocolSet, + public_addresses::PublicAddresses, transport::manager::{ address::{AddressRecord, AddressStore}, types::{PeerContext, PeerState, SupportedTransport}, @@ -77,7 +77,7 @@ pub struct TransportManagerHandle { supported_transport: HashSet, /// Local listen addresess. - listen_addresses: ExternalAddresses, + listen_addresses: PublicAddresses, } impl TransportManagerHandle { @@ -87,7 +87,7 @@ impl TransportManagerHandle { peers: Arc>>, cmd_tx: Sender, supported_transport: HashSet, - listen_addresses: ExternalAddresses, + listen_addresses: PublicAddresses, ) -> Self { Self { peers, @@ -103,8 +103,8 @@ impl TransportManagerHandle { self.supported_transport.insert(transport); } - /// Get listen addresses. - pub(crate) fn external_addresses(&self) -> ExternalAddresses { + /// Get the list of public addresses of the node. + pub(crate) fn public_addresses(&self) -> PublicAddresses { self.listen_addresses.clone() } @@ -152,7 +152,13 @@ impl TransportManagerHandle { /// Check if the address is a local listen address and if so, discard it. fn is_local_address(&self, address: &Multiaddr) -> bool { - self.listen_addresses.contains_partial(&address) + let mut address: Multiaddr = address + .iter() + .take_while(|protocol| !std::matches!(protocol, Protocol::P2p(_))) + .collect(); + address.push(Protocol::P2p(self.local_peer_id.into())); + + self.listen_addresses.inner.read().contains(&address) } /// Add one or more known addresses for peer. @@ -329,7 +335,7 @@ mod tests { cmd_tx, peers: Default::default(), supported_transport: HashSet::new(), - listen_addresses: ExternalAddresses::new(local_peer_id), + listen_addresses: PublicAddresses::new(local_peer_id), }, cmd_rx, ) @@ -593,8 +599,9 @@ mod tests { let first_addr: Multiaddr = "/ip6/::1/tcp/8888".parse().expect("valid multiaddress"); let second_addr: Multiaddr = "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress"); - let listen_addresses = ExternalAddresses::new(local_peer_id); - listen_addresses.extend([first_addr.clone(), second_addr.clone()]); + let listen_addresses = PublicAddresses::new(local_peer_id); + listen_addresses.add_public_address(first_addr.clone()).unwrap(); + listen_addresses.add_public_address(second_addr.clone()).unwrap(); println!("{:?}", listen_addresses); let handle = TransportManagerHandle { diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index de11ca94..719bb864 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -23,8 +23,8 @@ use crate::{ crypto::ed25519::Keypair, error::{AddressError, DialError, Error}, executor::Executor, - external_addresses::ExternalAddresses, protocol::{InnerTransportEvent, TransportService}, + public_addresses::PublicAddresses, transport::{ manager::{ address::{AddressRecord, AddressStore}, @@ -217,7 +217,7 @@ pub struct TransportManager { protocol_names: HashSet, /// Listen addresses. - listen_addresses: ExternalAddresses, + listen_addresses: PublicAddresses, /// Next connection ID. next_connection_id: Arc, @@ -267,7 +267,7 @@ impl TransportManager { let peers = Arc::new(RwLock::new(HashMap::new())); let (cmd_tx, cmd_rx) = channel(256); let (event_tx, event_rx) = channel(256); - let listen_addresses = ExternalAddresses::new(local_peer_id); + let listen_addresses = PublicAddresses::new(local_peer_id); let handle = TransportManagerHandle::new( local_peer_id, peers.clone(), @@ -381,14 +381,14 @@ impl TransportManager { self.transport_manager_handle.register_transport(name); } - /// Get listen addresses. - pub(crate) fn external_addresses(&self) -> ExternalAddresses { + /// Get the list of public addresses of the node. + pub(crate) fn public_addresses(&self) -> PublicAddresses { self.listen_addresses.clone() } /// Register local listen address. pub fn register_listen_address(&mut self, address: Multiaddr) { - if let Err(address) = self.listen_addresses.register_listen_address(address) { + if let Err(address) = self.listen_addresses.add_public_address(address) { tracing::warn!(target: LOG_TARGET, ?address, "failed to register listen address"); } } @@ -479,8 +479,9 @@ impl TransportManager { return Err(Error::NoAddressAvailable(peer)); } + let locked_addresses = self.listen_addresses.inner.read(); for record in records.values() { - if self.listen_addresses.contains(record.as_ref()) { + if locked_addresses.contains(record.as_ref()) { tracing::warn!( target: LOG_TARGET, ?peer, @@ -492,6 +493,7 @@ impl TransportManager { return Err(Error::TriedToDialSelf); } } + drop(locked_addresses); // set connection id for the address record and put peer into `Opening` state let connection_id = @@ -582,7 +584,7 @@ impl TransportManager { let mut record = AddressRecord::from_multiaddr(address) .ok_or(Error::AddressError(AddressError::PeerIdMissing))?; - if self.listen_addresses.contains(record.as_ref()) { + if self.listen_addresses.inner.read().contains(record.as_ref()) { return Err(Error::TriedToDialSelf); } diff --git a/tests/conformance/rust/identify.rs b/tests/conformance/rust/identify.rs index 66d0ccd5..50891d34 100644 --- a/tests/conformance/rust/identify.rs +++ b/tests/conformance/rust/identify.rs @@ -119,7 +119,7 @@ async fn identify_works() { let mut libp2p = initialize_libp2p(); let (mut litep2p, _ping_event_stream, mut identify_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/rust/kademlia.rs b/tests/conformance/rust/kademlia.rs index eebc539d..5d9caf5e 100644 --- a/tests/conformance/rust/kademlia.rs +++ b/tests/conformance/rust/kademlia.rs @@ -119,7 +119,7 @@ async fn find_node() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -223,7 +223,7 @@ async fn put_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -335,7 +335,7 @@ async fn get_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); diff --git a/tests/conformance/rust/ping.rs b/tests/conformance/rust/ping.rs index 5e4213aa..35734570 100644 --- a/tests/conformance/rust/ping.rs +++ b/tests/conformance/rust/ping.rs @@ -81,7 +81,7 @@ async fn libp2p_dials() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut ping_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/substrate/connection.rs b/tests/conformance/substrate/connection.rs index ff4c318c..52ae1611 100644 --- a/tests/conformance/substrate/connection.rs +++ b/tests/conformance/substrate/connection.rs @@ -110,7 +110,7 @@ async fn substrate_keep_alive_timeout() { let (mut libp2p, _peer_store_handle) = initialize_libp2p(1u32, 1u32); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_connection_open = false; diff --git a/tests/conformance/substrate/notifications.rs b/tests/conformance/substrate/notifications.rs index ada5915f..3e47ba18 100644 --- a/tests/conformance/substrate/notifications.rs +++ b/tests/conformance/substrate/notifications.rs @@ -119,7 +119,7 @@ async fn substrate_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -214,7 +214,7 @@ async fn litep2p_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -311,7 +311,7 @@ async fn substrate_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -360,7 +360,7 @@ async fn litep2p_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -412,7 +412,7 @@ async fn substrate_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_notification_count = 0; @@ -504,7 +504,7 @@ async fn litep2p_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut notif_count = 0; @@ -584,7 +584,7 @@ async fn both_nodes_open_substreams() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; diff --git a/tests/conformance/substrate/request_response.rs b/tests/conformance/substrate/request_response.rs index 39d2cbe5..a09914b3 100644 --- a/tests/conformance/substrate/request_response.rs +++ b/tests/conformance/substrate/request_response.rs @@ -101,7 +101,7 @@ async fn request_works() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let libp2p_peer = *libp2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -197,7 +197,7 @@ async fn substrate_reject_request() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); tokio::spawn(peer_store.run()); @@ -254,7 +254,7 @@ async fn litep2p_reject_request() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -321,7 +321,7 @@ async fn substrate_request_timeout() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); let mut _timeout_request = None; @@ -379,7 +379,7 @@ async fn litep2p_request_timeout() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); diff --git a/tests/connection/mod.rs b/tests/connection/mod.rs index 5bb68bc4..115d4d5a 100644 --- a/tests/connection/mod.rs +++ b/tests/connection/mod.rs @@ -108,7 +108,7 @@ async fn two_litep2ps_work(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let (res1, res2) = tokio::join!(litep2p1.next_event(), litep2p2.next_event()); @@ -255,7 +255,7 @@ async fn connect_over_dns() { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let mut new_address = Multiaddr::empty(); @@ -440,7 +440,7 @@ async fn dial_self(transport: Transport) { let litep2p_config = add_transport(litep2p_config, transport).build(); let mut litep2p = Litep2p::new(litep2p_config).unwrap(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); // dial without peer id attached assert!(std::matches!( @@ -567,7 +567,7 @@ async fn keep_alive_timeout(transport1: Transport, transport2: Transport) { let config2 = add_transport(config2, transport2).build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p2.dial_address(address1).await.unwrap(); let mut litep2p1_ping = false; let mut litep2p2_ping = false; @@ -626,8 +626,8 @@ async fn simultaneous_dial_tcp() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -679,8 +679,8 @@ async fn simultaneous_dial_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -732,8 +732,8 @@ async fn simultaneous_dial_ipv6_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -791,7 +791,7 @@ async fn websocket_over_ipv6() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address2).await.unwrap(); let mut ping_received1 = false; @@ -843,7 +843,7 @@ async fn tcp_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -905,7 +905,7 @@ async fn websocket_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -1040,7 +1040,7 @@ async fn multiple_listen_addresses( let (mut litep2p2, _event_stream) = make_dummy_litep2p(transport2).await; let (mut litep2p3, _event_stream) = make_dummy_litep2p(transport3).await; - let addresses = litep2p1.listen_addresses().get_addresses(); + let addresses = litep2p1.public_addresses().get_addresses(); let address1 = addresses.get(0).unwrap().clone(); let address2 = addresses.get(1).unwrap().clone(); @@ -1124,7 +1124,7 @@ async fn dial_over_multiple_addresses() { // let (mut litep2p2, _event_stream) = make_dummy_litep2p(transport2).await; // let (mut litep2p3, _event_stream) = make_dummy_litep2p(transport3).await; - // let mut address_iter = litep2p1.listen_addresses(); + // let mut address_iter = litep2p1.public_addresses(); // let address1 = address_iter.next().unwrap().clone(); // let address2 = address_iter.next().unwrap().clone(); // drop(address_iter); @@ -1175,10 +1175,7 @@ async fn unspecified_listen_address_tcp() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - for address in litep2p1.listen_addresses().locked().iter() { - tracing::info!("address: {address:?}"); - } - let listen_address = litep2p1.listen_addresses().get_addresses(); + let listen_address = litep2p1.public_addresses().get_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1279,10 +1276,7 @@ async fn unspecified_listen_address_websocket() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - for address in litep2p1.listen_addresses().locked().iter() { - tracing::info!("address: {address:?}"); - } - let listen_address = litep2p1.listen_addresses().get_addresses(); + let listen_address = litep2p1.public_addresses().get_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1429,11 +1423,11 @@ async fn simultaneous_dial_then_redial(transport1: Transport, transport2: Transp litep2p1.add_known_address( peer2, - litep2p2.listen_addresses().get_addresses().into_iter(), + litep2p2.public_addresses().get_addresses().into_iter(), ); litep2p2.add_known_address( peer1, - litep2p1.listen_addresses().get_addresses().into_iter(), + litep2p1.public_addresses().get_addresses().into_iter(), ); let (_, _) = tokio::join!(litep2p1.dial(&peer2), litep2p2.dial(&peer1)); diff --git a/tests/custom_executor.rs b/tests/custom_executor.rs index bddc78ed..2d8b833b 100644 --- a/tests/custom_executor.rs +++ b/tests/custom_executor.rs @@ -158,7 +158,7 @@ async fn custom_executor() { let peer2 = *litep2p2.local_peer_id(); // wait until peers have connected and spawn the litep2p objects in the background - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; diff --git a/tests/protocol/identify.rs b/tests/protocol/identify.rs index 58ace3b1..99e34bed 100644 --- a/tests/protocol/identify.rs +++ b/tests/protocol/identify.rs @@ -88,8 +88,8 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("listen address of peer1: {address1}"); tracing::info!("listen address of peer2: {address2}"); @@ -202,7 +202,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/kademlia.rs b/tests/protocol/kademlia.rs index 39cd354a..ea578833 100644 --- a/tests/protocol/kademlia.rs +++ b/tests/protocol/kademlia.rs @@ -153,7 +153,7 @@ async fn records_are_stored_automatically() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.listen_addresses().get_addresses(), + litep2p2.public_addresses().get_addresses(), ) .await; @@ -234,7 +234,7 @@ async fn records_are_stored_manually() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.listen_addresses().get_addresses(), + litep2p2.public_addresses().get_addresses(), ) .await; @@ -317,7 +317,7 @@ async fn not_validated_records_are_not_stored() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.listen_addresses().get_addresses(), + litep2p2.public_addresses().get_addresses(), ) .await; @@ -419,7 +419,7 @@ async fn get_record_retrieves_remote_records() { kad_handle2 .add_known_peer( *litep2p1.local_peer_id(), - litep2p1.listen_addresses().get_addresses(), + litep2p1.public_addresses().get_addresses(), ) .await; diff --git a/tests/protocol/notification.rs b/tests/protocol/notification.rs index 409c2071..416571ee 100644 --- a/tests/protocol/notification.rs +++ b/tests/protocol/notification.rs @@ -46,7 +46,7 @@ use std::{net::Ipv6Addr, task::Poll, time::Duration}; use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; @@ -2550,7 +2550,7 @@ async fn dial_peer_when_opening_substream(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address)); // add `peer2` known address for `peer1` and spawn the litep2p objects in the background @@ -2708,8 +2708,8 @@ async fn open_and_close_batched( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -2913,8 +2913,8 @@ async fn open_and_close_batched_duplicate_peer( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -3150,7 +3150,7 @@ async fn no_listener_address_for_one_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); tokio::spawn(async move { @@ -3550,7 +3550,7 @@ async fn dialing_disabled(transport1: Transport, transport2: Transport) { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3641,7 +3641,7 @@ async fn validation_takes_too_long(transport1: Transport, transport2: Transport) let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3748,7 +3748,7 @@ async fn ignored_validation_open_substream(transport1: Transport, transport2: Tr let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3893,7 +3893,7 @@ async fn clogged_channel_disconnects_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); diff --git a/tests/protocol/ping.rs b/tests/protocol/ping.rs index f460b157..327844f7 100644 --- a/tests/protocol/ping.rs +++ b/tests/protocol/ping.rs @@ -70,7 +70,7 @@ async fn ping_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/request_response.rs b/tests/protocol/request_response.rs index 306f4e8f..276d63a6 100644 --- a/tests/protocol/request_response.rs +++ b/tests/protocol/request_response.rs @@ -52,7 +52,7 @@ use std::{ use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("address: {address}"); litep2p1.dial_address(address).await.unwrap(); @@ -1435,7 +1435,7 @@ async fn dial_peer_when_sending_request(transport1: Transport, transport2: Trans let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); // add known address for `peer2` and start event loop for both litep2ps litep2p1.add_known_address(peer2, std::iter::once(address)); diff --git a/tests/substream.rs b/tests/substream.rs index a222bd54..3186cf81 100644 --- a/tests/substream.rs +++ b/tests/substream.rs @@ -218,7 +218,7 @@ impl UserProtocol for CustomProtocol { } async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); litep2p2.dial_address(listen_address).await.unwrap(); let mut litep2p1_ready = false; diff --git a/tests/user_protocol.rs b/tests/user_protocol.rs index 5d767d80..102b2a1c 100644 --- a/tests/user_protocol.rs +++ b/tests/user_protocol.rs @@ -99,7 +99,7 @@ async fn user_protocol() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); let custom_protocol2 = Box::new(CustomProtocol::new()); let config2 = ConfigBuilder::new() diff --git a/tests/user_protocol_2.rs b/tests/user_protocol_2.rs index d4b3e9ec..c48af02b 100644 --- a/tests/user_protocol_2.rs +++ b/tests/user_protocol_2.rs @@ -122,7 +122,7 @@ async fn user_protocol_2() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); sender1.send(address).await.unwrap(); diff --git a/tests/webrtc.rs b/tests/webrtc.rs index acacb5a4..d2c40406 100644 --- a/tests/webrtc.rs +++ b/tests/webrtc.rs @@ -58,7 +58,7 @@ async fn webrtc_test() { .build(); let mut litep2p = Litep2p::new(config).unwrap(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("listen address: {address:?}"); From 68c76d268c3639f140c56f2c71e7cd09e061f5f2 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Mon, 2 Sep 2024 12:58:21 +0000 Subject: [PATCH 17/30] Apply fmt Signed-off-by: Alexandru Vasile --- src/protocol/transport_service.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index a5a6b0e1..94e6832c 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -20,8 +20,8 @@ use crate::{ error::Error, - public_addresses::PublicAddresses, protocol::{connection::ConnectionHandle, InnerTransportEvent, TransportEvent}, + public_addresses::PublicAddresses, transport::{manager::TransportManagerHandle, Endpoint}, types::{protocol::ProtocolName, ConnectionId, SubstreamId}, PeerId, DEFAULT_CHANNEL_SIZE, From 6161233c2be2a0e16daa6a93c6b50677907b1d87 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Mon, 2 Sep 2024 12:59:31 +0000 Subject: [PATCH 18/30] Fix cargo doc and clippy Signed-off-by: Alexandru Vasile --- src/protocol/libp2p/identify.rs | 2 +- src/protocol/transport_service.rs | 2 +- src/public_addresses.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 695991ca..ff60e388 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -204,7 +204,7 @@ impl Identify { pub(crate) fn new(service: TransportService, config: Config) -> Self { let listen_addresses = service.public_addresses(); - let local_peer_id = service.local_peer_id; + let local_peer_id = service.local_peer_id(); let filtered_public_addr = config.public_addresses.into_iter().filter_map(|address| { if address.is_empty() { return None; diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 94e6832c..932d7d42 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -151,7 +151,7 @@ impl TransportService { transport_handle, next_substream_id, connections: HashMap::new(), - keep_alive_timeout: keep_alive_timeout, + keep_alive_timeout, pending_keep_alive_timeouts: FuturesUnordered::new(), }, tx, diff --git a/src/public_addresses.rs b/src/public_addresses.rs index bebb6b2e..e6c8f506 100644 --- a/src/public_addresses.rs +++ b/src/public_addresses.rs @@ -28,7 +28,7 @@ use crate::PeerId; /// Set of the public addresses of the local node. /// /// The format of the addresses stored in the set contain the local peer ID. -/// This requirement is enforced by the [`PublicAddresses::register_listen_address`] method, +/// This requirement is enforced by the [`PublicAddresses::add_public_address`] method, /// that will add the local peer ID to the address if it is missing. /// /// # Note From dacd6653bd52a94482ff2e7fd0e4bae65a399b37 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 10:41:56 +0300 Subject: [PATCH 19/30] pub-addr: Rename API methods Signed-off-by: Alexandru Vasile --- src/protocol/libp2p/identify.rs | 2 +- src/public_addresses.rs | 20 ++++++++++---------- src/transport/manager/handle.rs | 4 ++-- src/transport/manager/mod.rs | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index ff60e388..458f3cc1 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -469,7 +469,7 @@ mod tests { let multiaddr: Multiaddr = "/ip6/::9/tcp/111".parse().unwrap(); // Litep2p1 is now reporting the new address. - assert!(litep2p1.public_addresses().add_public_address(multiaddr.clone()).unwrap()); + assert!(litep2p1.public_addresses().add_address(multiaddr.clone()).unwrap()); // Dial `litep2p1` litep2p2.dial_address(litep2p1_address).await.unwrap(); diff --git a/src/public_addresses.rs b/src/public_addresses.rs index e6c8f506..ffcb3866 100644 --- a/src/public_addresses.rs +++ b/src/public_addresses.rs @@ -58,15 +58,15 @@ impl PublicAddresses { /// In case the address does not contain any peer ID, it will be added. /// /// Returns true if the address was added, false if it was already present. - pub fn add_public_address(&self, address: Multiaddr) -> Result { - let address = self.check_local_peer(address)?; + pub fn add_address(&self, address: Multiaddr) -> Result { + let address = self.ensure_local_peer(address)?; Ok(self.inner.write().insert(address)) } /// Remove the exact public address. /// /// The provided address must contain the local peer ID. - pub fn remove_public_address(&self, address: &Multiaddr) -> bool { + pub fn remove_address(&self, address: &Multiaddr) -> bool { self.inner.write().remove(address) } @@ -76,7 +76,7 @@ impl PublicAddresses { } /// Checks if the address contains the local peer ID. - fn check_local_peer(&self, mut address: Multiaddr) -> Result { + fn ensure_local_peer(&self, mut address: Multiaddr) -> Result { if address.is_empty() { return Err(address); } @@ -110,14 +110,14 @@ mod tests { assert!(!addresses.get_addresses().contains(&address)); - assert!(addresses.add_public_address(address.clone()).unwrap()); + assert!(addresses.add_address(address.clone()).unwrap()); // Adding the address a second time returns Ok(false). - assert!(!addresses.add_public_address(address.clone()).unwrap()); + assert!(!addresses.add_address(address.clone()).unwrap()); assert!(!addresses.get_addresses().contains(&address)); assert!(addresses.get_addresses().contains(&peer_address)); - addresses.remove_public_address(&peer_address); + addresses.remove_address(&peer_address); assert!(!addresses.get_addresses().contains(&peer_address)); } @@ -133,9 +133,9 @@ mod tests { ) .unwrap(); - assert!(addresses.add_public_address(address1.clone()).unwrap()); - assert!(addresses.add_public_address(address2.clone()).unwrap()); - addresses.add_public_address(address3.clone()).unwrap_err(); + assert!(addresses.add_address(address1.clone()).unwrap()); + assert!(addresses.add_address(address2.clone()).unwrap()); + addresses.add_address(address3.clone()).unwrap_err(); let addresses = addresses.get_addresses(); assert_eq!(addresses.len(), 2); diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index 9553ad9a..1f617fcb 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -600,8 +600,8 @@ mod tests { let second_addr: Multiaddr = "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress"); let listen_addresses = PublicAddresses::new(local_peer_id); - listen_addresses.add_public_address(first_addr.clone()).unwrap(); - listen_addresses.add_public_address(second_addr.clone()).unwrap(); + listen_addresses.add_address(first_addr.clone()).unwrap(); + listen_addresses.add_address(second_addr.clone()).unwrap(); println!("{:?}", listen_addresses); let handle = TransportManagerHandle { diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index 719bb864..00450da8 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -388,7 +388,7 @@ impl TransportManager { /// Register local listen address. pub fn register_listen_address(&mut self, address: Multiaddr) { - if let Err(address) = self.listen_addresses.add_public_address(address) { + if let Err(address) = self.listen_addresses.add_address(address) { tracing::warn!(target: LOG_TARGET, ?address, "failed to register listen address"); } } From 1194a29a2245a5930124a7fba23fa43acde9672a Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 11:15:00 +0300 Subject: [PATCH 20/30] Introduce ListenAddresses object Signed-off-by: Alexandru Vasile --- src/{public_addresses.rs => addresses.rs} | 60 +++++++++++++++++------ src/lib.rs | 4 +- src/protocol/libp2p/identify.rs | 2 +- src/protocol/transport_service.rs | 2 +- src/transport/manager/handle.rs | 2 +- src/transport/manager/mod.rs | 2 +- 6 files changed, 52 insertions(+), 20 deletions(-) rename src/{public_addresses.rs => addresses.rs} (78%) diff --git a/src/public_addresses.rs b/src/addresses.rs similarity index 78% rename from src/public_addresses.rs rename to src/addresses.rs index ffcb3866..57cf390b 100644 --- a/src/public_addresses.rs +++ b/src/addresses.rs @@ -59,7 +59,7 @@ impl PublicAddresses { /// /// Returns true if the address was added, false if it was already present. pub fn add_address(&self, address: Multiaddr) -> Result { - let address = self.ensure_local_peer(address)?; + let address = ensure_local_peer(address, self.local_peer_id)?; Ok(self.inner.write().insert(address)) } @@ -74,24 +74,56 @@ impl PublicAddresses { pub fn get_addresses(&self) -> Vec { self.inner.read().iter().cloned().collect() } +} - /// Checks if the address contains the local peer ID. - fn ensure_local_peer(&self, mut address: Multiaddr) -> Result { - if address.is_empty() { - return Err(address); - } +pub struct ListenAddresses { + pub(crate) inner: Arc>>, +} - // Verify the peer ID from the address corresponds to the local peer ID. - if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { - if peer_id != self.local_peer_id { - return Err(address); - } - } else { - address.push(Protocol::P2p(self.local_peer_id.into())); +impl ListenAddresses { + pub(crate) fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(HashSet::new())), } + } + + /// Add a listen address to the list of addresses. + /// + /// Returns true if the address was added, false if it was already present. + pub fn add_address(&self, address: Multiaddr) -> bool { + self.inner.write().insert(address) + } + + /// Remove the listen address. + pub fn remove_address(&self, address: &Multiaddr) -> bool { + self.inner.write().remove(address) + } + + /// Returns a vector of the available listen addresses. + pub fn get_addresses(&self) -> Vec { + self.inner.read().iter().cloned().collect() + } +} - Ok(address) +/// Check if the address contains the local peer ID. +fn ensure_local_peer( + mut address: Multiaddr, + local_peer_id: PeerId, +) -> Result { + if address.is_empty() { + return Err(address); } + + // Verify the peer ID from the address corresponds to the local peer ID. + if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { + if peer_id != local_peer_id { + return Err(address); + } + } else { + address.push(Protocol::P2p(local_peer_id.into())); + } + + Ok(address) } #[cfg(test)] diff --git a/src/lib.rs b/src/lib.rs index e46714d3..96970c68 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -37,7 +37,7 @@ use crate::{ notification::NotificationProtocol, request_response::RequestResponseProtocol, }, - public_addresses::PublicAddresses, + addresses::PublicAddresses, transport::{ manager::{SupportedTransport, TransportManager}, tcp::TcpTransport, @@ -71,7 +71,7 @@ pub mod crypto; pub mod error; pub mod executor; pub mod protocol; -pub mod public_addresses; +pub mod addresses; pub mod substream; pub mod transport; pub mod types; diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 458f3cc1..e9586c3e 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -25,7 +25,7 @@ use crate::{ crypto::PublicKey, error::{Error, SubstreamError}, protocol::{Direction, TransportEvent, TransportService}, - public_addresses::PublicAddresses, + addresses::PublicAddresses, substream::Substream, transport::Endpoint, types::{protocol::ProtocolName, SubstreamId}, diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 932d7d42..764dc044 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -21,7 +21,7 @@ use crate::{ error::Error, protocol::{connection::ConnectionHandle, InnerTransportEvent, TransportEvent}, - public_addresses::PublicAddresses, + addresses::PublicAddresses, transport::{manager::TransportManagerHandle, Endpoint}, types::{protocol::ProtocolName, ConnectionId, SubstreamId}, PeerId, DEFAULT_CHANNEL_SIZE, diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index 1f617fcb..5d530558 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -23,7 +23,7 @@ use crate::{ error::{AddressError, Error}, executor::Executor, protocol::ProtocolSet, - public_addresses::PublicAddresses, + addresses::PublicAddresses, transport::manager::{ address::{AddressRecord, AddressStore}, types::{PeerContext, PeerState, SupportedTransport}, diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index 00450da8..7235ef0e 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -24,7 +24,7 @@ use crate::{ error::{AddressError, DialError, Error}, executor::Executor, protocol::{InnerTransportEvent, TransportService}, - public_addresses::PublicAddresses, + addresses::PublicAddresses, transport::{ manager::{ address::{AddressRecord, AddressStore}, From ba6e1985e1565ee8eadb7bc4c78cf80298a79669 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 11:26:10 +0300 Subject: [PATCH 21/30] Use listenAddresses added interface Signed-off-by: Alexandru Vasile --- src/addresses.rs | 12 ++++++++---- src/lib.rs | 20 +++++++++++++++----- src/protocol/transport_service.rs | 7 ++++++- src/transport/manager/handle.rs | 18 ++++++++++++++---- src/transport/manager/mod.rs | 17 ++++++++++++++--- 5 files changed, 57 insertions(+), 17 deletions(-) diff --git a/src/addresses.rs b/src/addresses.rs index 57cf390b..63a40061 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -76,22 +76,26 @@ impl PublicAddresses { } } +#[derive(Debug, Clone)] pub struct ListenAddresses { pub(crate) inner: Arc>>, + local_peer_id: PeerId, } impl ListenAddresses { - pub(crate) fn new() -> Self { + /// Creates new [`ListenAddresses`] from the given peer ID. + pub(crate) fn new(local_peer_id: PeerId) -> Self { Self { inner: Arc::new(RwLock::new(HashSet::new())), + local_peer_id, } } - /// Add a listen address to the list of addresses. /// /// Returns true if the address was added, false if it was already present. - pub fn add_address(&self, address: Multiaddr) -> bool { - self.inner.write().insert(address) + pub fn add_address(&self, address: Multiaddr) -> Result { + let address = ensure_local_peer(address, self.local_peer_id)?; + Ok(self.inner.write().insert(address)) } /// Remove the listen address. diff --git a/src/lib.rs b/src/lib.rs index 96970c68..5ab0462e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,6 +29,7 @@ #![allow(clippy::match_like_matches_macro)] use crate::{ + addresses::PublicAddresses, config::Litep2pConfig, error::DialError, protocol::{ @@ -37,7 +38,6 @@ use crate::{ notification::NotificationProtocol, request_response::RequestResponseProtocol, }, - addresses::PublicAddresses, transport::{ manager::{SupportedTransport, TransportManager}, tcp::TcpTransport, @@ -52,6 +52,7 @@ use crate::transport::webrtc::WebRtcTransport; #[cfg(feature = "websocket")] use crate::transport::websocket::WebSocketTransport; +use addresses::ListenAddresses; use multiaddr::Multiaddr; use transport::Endpoint; use types::ConnectionId; @@ -65,13 +66,13 @@ pub use types::protocol::ProtocolName; pub(crate) mod peer_id; +pub mod addresses; pub mod codec; pub mod config; pub mod crypto; pub mod error; pub mod executor; pub mod protocol; -pub mod addresses; pub mod substream; pub mod transport; pub mod types; @@ -139,7 +140,10 @@ pub struct Litep2p { local_peer_id: PeerId, /// Listen addresses. - listen_addresses: PublicAddresses, + listen_addresses: ListenAddresses, + + /// Listen addresses. + public_addresses: PublicAddresses, /// Transport manager. transport_manager: TransportManager, @@ -363,7 +367,7 @@ impl Litep2p { .register_transport(SupportedTransport::WebSocket, Box::new(transport)); } - let listen_addresses = transport_manager.public_addresses(); + let listen_addresses = transport_manager.listen_addresses(); // enable mdns if the config exists if let Some(config) = litep2p_config.mdns.take() { @@ -400,6 +404,7 @@ impl Litep2p { local_peer_id, bandwidth_sink, listen_addresses, + public_addresses: transport_manager.public_addresses(), transport_manager, }) } @@ -440,9 +445,14 @@ impl Litep2p { &self.local_peer_id } + /// Get the list of listen addresses of the node. + pub fn listen_addresses(&self) -> ListenAddresses { + self.listen_addresses.clone() + } + /// Get the list of public addresses of the node. pub fn public_addresses(&self) -> PublicAddresses { - self.listen_addresses.clone() + self.public_addresses.clone() } /// Get handle to bandwidth sink. diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 764dc044..a48c37e6 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -19,9 +19,9 @@ // DEALINGS IN THE SOFTWARE. use crate::{ + addresses::{ListenAddresses, PublicAddresses}, error::Error, protocol::{connection::ConnectionHandle, InnerTransportEvent, TransportEvent}, - addresses::PublicAddresses, transport::{manager::TransportManagerHandle, Endpoint}, types::{protocol::ProtocolName, ConnectionId, SubstreamId}, PeerId, DEFAULT_CHANNEL_SIZE, @@ -163,6 +163,11 @@ impl TransportService { self.transport_handle.public_addresses() } + /// Get the list of listen addresses of the node. + pub fn listen_addresses(&self) -> ListenAddresses { + self.transport_handle.listen_addresses() + } + /// Handle connection established event. fn on_connection_established( &mut self, diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index 5d530558..4364c2ab 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -19,11 +19,11 @@ // DEALINGS IN THE SOFTWARE. use crate::{ + addresses::{ListenAddresses, PublicAddresses}, crypto::ed25519::Keypair, error::{AddressError, Error}, executor::Executor, protocol::ProtocolSet, - addresses::PublicAddresses, transport::manager::{ address::{AddressRecord, AddressStore}, types::{PeerContext, PeerState, SupportedTransport}, @@ -77,7 +77,10 @@ pub struct TransportManagerHandle { supported_transport: HashSet, /// Local listen addresess. - listen_addresses: PublicAddresses, + listen_addresses: ListenAddresses, + + /// Public addresses. + public_addresses: PublicAddresses, } impl TransportManagerHandle { @@ -87,14 +90,16 @@ impl TransportManagerHandle { peers: Arc>>, cmd_tx: Sender, supported_transport: HashSet, - listen_addresses: PublicAddresses, + listen_addresses: ListenAddresses, + public_addresses: PublicAddresses, ) -> Self { Self { peers, cmd_tx, local_peer_id, - listen_addresses, supported_transport, + listen_addresses, + public_addresses, } } @@ -105,6 +110,11 @@ impl TransportManagerHandle { /// Get the list of public addresses of the node. pub(crate) fn public_addresses(&self) -> PublicAddresses { + self.public_addresses.clone() + } + + /// Get the list of listen addresses of the node. + pub(crate) fn listen_addresses(&self) -> ListenAddresses { self.listen_addresses.clone() } diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index 7235ef0e..de800a2b 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -19,12 +19,12 @@ // DEALINGS IN THE SOFTWARE. use crate::{ + addresses::{ListenAddresses, PublicAddresses}, codec::ProtocolCodec, crypto::ed25519::Keypair, error::{AddressError, DialError, Error}, executor::Executor, protocol::{InnerTransportEvent, TransportService}, - addresses::PublicAddresses, transport::{ manager::{ address::{AddressRecord, AddressStore}, @@ -217,7 +217,10 @@ pub struct TransportManager { protocol_names: HashSet, /// Listen addresses. - listen_addresses: PublicAddresses, + listen_addresses: ListenAddresses, + + /// Listen addresses. + public_addresses: PublicAddresses, /// Next connection ID. next_connection_id: Arc, @@ -267,13 +270,15 @@ impl TransportManager { let peers = Arc::new(RwLock::new(HashMap::new())); let (cmd_tx, cmd_rx) = channel(256); let (event_tx, event_rx) = channel(256); - let listen_addresses = PublicAddresses::new(local_peer_id); + let listen_addresses = ListenAddresses::new(local_peer_id); + let public_addresses = PublicAddresses::new(local_peer_id); let handle = TransportManagerHandle::new( local_peer_id, peers.clone(), cmd_tx, supported_transports, listen_addresses.clone(), + public_addresses.clone(), ); ( @@ -286,6 +291,7 @@ impl TransportManager { local_peer_id, bandwidth_sink, listen_addresses, + public_addresses, max_parallel_dials, protocols: HashMap::new(), transports: TransportContext::new(), @@ -383,6 +389,11 @@ impl TransportManager { /// Get the list of public addresses of the node. pub(crate) fn public_addresses(&self) -> PublicAddresses { + self.public_addresses.clone() + } + + /// Get the list of listen addresses of the node. + pub(crate) fn listen_addresses(&self) -> ListenAddresses { self.listen_addresses.clone() } From e7a7d805b656598a5bc37b9fc1ef2898f6f5a5da Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 11:34:39 +0300 Subject: [PATCH 22/30] identify: Use user-provided, listen and public addresses Signed-off-by: Alexandru Vasile --- src/protocol/libp2p/identify.rs | 44 +++++++++++++++------------------ 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index e9586c3e..eee83113 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -21,11 +21,11 @@ //! [`/ipfs/identify/1.0.0`](https://github.com/libp2p/specs/blob/master/identify/README.md) implementation. use crate::{ + addresses::{ListenAddresses, PublicAddresses}, codec::ProtocolCodec, crypto::PublicKey, error::{Error, SubstreamError}, protocol::{Direction, TransportEvent, TransportService}, - addresses::PublicAddresses, substream::Substream, transport::Endpoint, types::{protocol::ProtocolName, SubstreamId}, @@ -33,7 +33,7 @@ use crate::{ }; use futures::{future::BoxFuture, stream::FuturesUnordered, Stream, StreamExt}; -use multiaddr::{Multiaddr, Protocol}; +use multiaddr::Multiaddr; use prost::Message; use tokio::sync::mpsc::{channel, Sender}; use tokio_stream::wrappers::ReceiverStream; @@ -183,8 +183,14 @@ pub(crate) struct Identify { /// User agent. user_agent: String, + /// Listen addresses. + listen_addresses: ListenAddresses, + /// Public addresses. - listen_addresses: PublicAddresses, + public_addresses: PublicAddresses, + + /// User provided list of addresses. + user_addresses: Vec>, /// Protocols supported by the local node, filled by `Litep2p`. protocols: Vec, @@ -202,30 +208,18 @@ pub(crate) struct Identify { impl Identify { /// Create new [`Identify`] protocol. pub(crate) fn new(service: TransportService, config: Config) -> Self { - let listen_addresses = service.public_addresses(); - - let local_peer_id = service.local_peer_id(); - let filtered_public_addr = config.public_addresses.into_iter().filter_map(|address| { - if address.is_empty() { - return None; - } - if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { - if peer_id != local_peer_id { - return None; - } - - return Some(address); - } - - Some(address.with(Protocol::P2p(local_peer_id.into()))) - }); - listen_addresses.inner.write().extend(filtered_public_addr); + let listen_addresses = service.listen_addresses(); + let public_addresses = service.public_addresses(); + let user_addresses = + config.public_addresses.into_iter().map(|addr| addr.to_vec()).collect(); Self { service, tx: config.tx_event, peers: HashMap::new(), listen_addresses, + public_addresses, + user_addresses, public: config.public.expect("public key to be supplied"), protocol_version: config.protocol_version, user_agent: config.user_agent.unwrap_or(DEFAULT_AGENT.to_string()), @@ -281,13 +275,15 @@ impl Identify { } }; - let listen_addrs = - self.listen_addresses.inner.read().iter().map(|addr| addr.to_vec()).collect(); + let mut listen_addr: HashSet<_> = self.user_addresses.iter().cloned().collect(); + listen_addr.extend(self.listen_addresses.inner.read().iter().map(|addr| addr.to_vec())); + listen_addr.extend(self.public_addresses.inner.read().iter().map(|addr| addr.to_vec())); + let identify = identify_schema::Identify { protocol_version: Some(self.protocol_version.clone()), agent_version: Some(self.user_agent.clone()), public_key: Some(self.public.to_protobuf_encoding()), - listen_addrs, + listen_addrs: listen_addr.into_iter().collect(), observed_addr, protocols: self.protocols.clone(), }; From 9ad762bc4a49e5867094da44c438cfa71c9a7045 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 11:37:08 +0300 Subject: [PATCH 23/30] manager: Remove transport_manager::register_listen_address Signed-off-by: Alexandru Vasile --- src/lib.rs | 19 +++++++++++++------ src/transport/manager/mod.rs | 7 ------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5ab0462e..78b73e92 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -166,6 +166,7 @@ impl Litep2p { litep2p_config.max_parallel_dials, litep2p_config.connection_limits, ); + let listen_addresses = transport_manager.listen_addresses(); // add known addresses to `TransportManager`, if any exist if !litep2p_config.known_addresses.is_empty() { @@ -318,7 +319,9 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - transport_manager.register_listen_address(address.clone()); + if let Err(err) = listen_addresses.add_address(address.clone()) { + tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); + } } transport_manager.register_transport(SupportedTransport::Tcp, Box::new(transport)); @@ -332,7 +335,9 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - transport_manager.register_listen_address(address.clone()); + if let Err(err) = listen_addresses.add_address(address.clone()) { + tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); + } } transport_manager.register_transport(SupportedTransport::Quic, Box::new(transport)); @@ -346,7 +351,9 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - transport_manager.register_listen_address(address.clone()); + if let Err(err) = listen_addresses.add_address(address.clone()) { + tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); + } } transport_manager.register_transport(SupportedTransport::WebRtc, Box::new(transport)); @@ -360,15 +367,15 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - transport_manager.register_listen_address(address.clone()); + if let Err(err) = listen_addresses.add_address(address.clone()) { + tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); + } } transport_manager .register_transport(SupportedTransport::WebSocket, Box::new(transport)); } - let listen_addresses = transport_manager.listen_addresses(); - // enable mdns if the config exists if let Some(config) = litep2p_config.mdns.take() { let mdns = Mdns::new(transport_handle, config, listen_addresses.get_addresses())?; diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index de800a2b..4105e92c 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -397,13 +397,6 @@ impl TransportManager { self.listen_addresses.clone() } - /// Register local listen address. - pub fn register_listen_address(&mut self, address: Multiaddr) { - if let Err(address) = self.listen_addresses.add_address(address) { - tracing::warn!(target: LOG_TARGET, ?address, "failed to register listen address"); - } - } - /// Add one or more known addresses for `peer`. pub fn add_known_address( &mut self, From d0ebcd2a34a27ac5336bddbf92fae35d93ac7311 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 11:51:05 +0300 Subject: [PATCH 24/30] Adjust testing Signed-off-by: Alexandru Vasile --- examples/custom_executor.rs | 2 +- examples/custom_protocol.rs | 2 +- examples/echo_notification.rs | 2 +- examples/gossiping.rs | 2 +- src/protocol/libp2p/identify.rs | 5 +-- src/protocol/transport_service.rs | 1 + src/transport/manager/handle.rs | 6 ++- tests/conformance/rust/identify.rs | 2 +- tests/conformance/rust/kademlia.rs | 6 +-- tests/conformance/rust/ping.rs | 2 +- tests/conformance/substrate/connection.rs | 2 +- tests/conformance/substrate/notifications.rs | 14 +++---- .../conformance/substrate/request_response.rs | 10 ++--- tests/connection/mod.rs | 38 +++++++++---------- tests/custom_executor.rs | 2 +- tests/protocol/identify.rs | 6 +-- tests/protocol/kademlia.rs | 8 ++-- tests/protocol/notification.rs | 22 +++++------ tests/protocol/ping.rs | 2 +- tests/protocol/request_response.rs | 4 +- tests/substream.rs | 2 +- tests/user_protocol.rs | 2 +- tests/user_protocol_2.rs | 2 +- tests/webrtc.rs | 2 +- 24 files changed, 74 insertions(+), 72 deletions(-) diff --git a/examples/custom_executor.rs b/examples/custom_executor.rs index 90084d99..5a5cbd98 100644 --- a/examples/custom_executor.rs +++ b/examples/custom_executor.rs @@ -122,7 +122,7 @@ async fn main() { // dial `litep2p1` litep2p2 - .dial_address(litep2p1.public_addresses().get_addresses().get(0).unwrap().clone()) + .dial_address(litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone()) .await .unwrap(); diff --git a/examples/custom_protocol.rs b/examples/custom_protocol.rs index a39cc425..7eead39f 100644 --- a/examples/custom_protocol.rs +++ b/examples/custom_protocol.rs @@ -277,7 +277,7 @@ async fn main() { let (mut litep2p2, mut handle2) = make_litep2p(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(listen_address)); tokio::spawn(async move { diff --git a/examples/echo_notification.rs b/examples/echo_notification.rs index d2e324a8..4521c934 100644 --- a/examples/echo_notification.rs +++ b/examples/echo_notification.rs @@ -125,7 +125,7 @@ async fn main() { // get the first (and only) listen address for the second peer // and add it as a known address for `litep2p1` - let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let peer = *litep2p2.local_peer_id(); litep2p1.add_known_address(peer, vec![listen_address].into_iter()); diff --git a/examples/gossiping.rs b/examples/gossiping.rs index a24c7a2f..730d23db 100644 --- a/examples/gossiping.rs +++ b/examples/gossiping.rs @@ -237,7 +237,7 @@ async fn main() { // establish connection to litep2p for all other litep2ps let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address.clone()].into_iter()); litep2p3.add_known_address(peer2, vec![listen_address.clone()].into_iter()); diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index eee83113..0ead262f 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -461,11 +461,11 @@ mod tests { let (mut litep2p1, mut event_stream1, peer1) = create_litep2p(); let (mut litep2p2, mut event_stream2, _peer2) = create_litep2p(); let litep2p1_address = - litep2p1.public_addresses().get_addresses().into_iter().next().unwrap(); + litep2p1.listen_addresses().get_addresses().into_iter().next().unwrap(); let multiaddr: Multiaddr = "/ip6/::9/tcp/111".parse().unwrap(); // Litep2p1 is now reporting the new address. - assert!(litep2p1.public_addresses().add_address(multiaddr.clone()).unwrap()); + assert!(litep2p1.listen_addresses().add_address(multiaddr.clone()).unwrap()); // Dial `litep2p1` litep2p2.dial_address(litep2p1_address).await.unwrap(); @@ -489,7 +489,6 @@ mod tests { listen_addresses, .. }) => { - println!(" listen_addresses: {:?}", listen_addresses); assert!(listen_addresses.iter().any(|address| address == &expected_multiaddr)); break; } diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index a48c37e6..c3450b83 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -455,6 +455,7 @@ mod tests { Arc::new(RwLock::new(HashMap::new())), cmd_tx, HashSet::new(), + ListenAddresses::new(peer), PublicAddresses::new(peer), ); diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index 4364c2ab..8e51b8d2 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -345,7 +345,8 @@ mod tests { cmd_tx, peers: Default::default(), supported_transport: HashSet::new(), - listen_addresses: PublicAddresses::new(local_peer_id), + listen_addresses: ListenAddresses::new(local_peer_id), + public_addresses: PublicAddresses::new(local_peer_id), }, cmd_rx, ) @@ -609,7 +610,7 @@ mod tests { let first_addr: Multiaddr = "/ip6/::1/tcp/8888".parse().expect("valid multiaddress"); let second_addr: Multiaddr = "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress"); - let listen_addresses = PublicAddresses::new(local_peer_id); + let listen_addresses = ListenAddresses::new(local_peer_id); listen_addresses.add_address(first_addr.clone()).unwrap(); listen_addresses.add_address(second_addr.clone()).unwrap(); println!("{:?}", listen_addresses); @@ -620,6 +621,7 @@ mod tests { peers: Default::default(), supported_transport: HashSet::new(), listen_addresses, + public_addresses: PublicAddresses::new(local_peer_id), }; // local addresses diff --git a/tests/conformance/rust/identify.rs b/tests/conformance/rust/identify.rs index 50891d34..66d0ccd5 100644 --- a/tests/conformance/rust/identify.rs +++ b/tests/conformance/rust/identify.rs @@ -119,7 +119,7 @@ async fn identify_works() { let mut libp2p = initialize_libp2p(); let (mut litep2p, _ping_event_stream, mut identify_event_stream) = initialize_litep2p(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/rust/kademlia.rs b/tests/conformance/rust/kademlia.rs index 5d9caf5e..eebc539d 100644 --- a/tests/conformance/rust/kademlia.rs +++ b/tests/conformance/rust/kademlia.rs @@ -119,7 +119,7 @@ async fn find_node() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -223,7 +223,7 @@ async fn put_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -335,7 +335,7 @@ async fn get_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); diff --git a/tests/conformance/rust/ping.rs b/tests/conformance/rust/ping.rs index 35734570..5e4213aa 100644 --- a/tests/conformance/rust/ping.rs +++ b/tests/conformance/rust/ping.rs @@ -81,7 +81,7 @@ async fn libp2p_dials() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut ping_event_stream) = initialize_litep2p(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/substrate/connection.rs b/tests/conformance/substrate/connection.rs index 52ae1611..ff4c318c 100644 --- a/tests/conformance/substrate/connection.rs +++ b/tests/conformance/substrate/connection.rs @@ -110,7 +110,7 @@ async fn substrate_keep_alive_timeout() { let (mut libp2p, _peer_store_handle) = initialize_libp2p(1u32, 1u32); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_connection_open = false; diff --git a/tests/conformance/substrate/notifications.rs b/tests/conformance/substrate/notifications.rs index 3e47ba18..ada5915f 100644 --- a/tests/conformance/substrate/notifications.rs +++ b/tests/conformance/substrate/notifications.rs @@ -119,7 +119,7 @@ async fn substrate_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -214,7 +214,7 @@ async fn litep2p_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -311,7 +311,7 @@ async fn substrate_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -360,7 +360,7 @@ async fn litep2p_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -412,7 +412,7 @@ async fn substrate_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_notification_count = 0; @@ -504,7 +504,7 @@ async fn litep2p_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut notif_count = 0; @@ -584,7 +584,7 @@ async fn both_nodes_open_substreams() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; diff --git a/tests/conformance/substrate/request_response.rs b/tests/conformance/substrate/request_response.rs index a09914b3..39d2cbe5 100644 --- a/tests/conformance/substrate/request_response.rs +++ b/tests/conformance/substrate/request_response.rs @@ -101,7 +101,7 @@ async fn request_works() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let libp2p_peer = *libp2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -197,7 +197,7 @@ async fn substrate_reject_request() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); tokio::spawn(peer_store.run()); @@ -254,7 +254,7 @@ async fn litep2p_reject_request() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -321,7 +321,7 @@ async fn substrate_request_timeout() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); let mut _timeout_request = None; @@ -379,7 +379,7 @@ async fn litep2p_request_timeout() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); diff --git a/tests/connection/mod.rs b/tests/connection/mod.rs index 115d4d5a..a74ff7b7 100644 --- a/tests/connection/mod.rs +++ b/tests/connection/mod.rs @@ -108,7 +108,7 @@ async fn two_litep2ps_work(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let (res1, res2) = tokio::join!(litep2p1.next_event(), litep2p2.next_event()); @@ -255,7 +255,7 @@ async fn connect_over_dns() { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let mut new_address = Multiaddr::empty(); @@ -440,7 +440,7 @@ async fn dial_self(transport: Transport) { let litep2p_config = add_transport(litep2p_config, transport).build(); let mut litep2p = Litep2p::new(litep2p_config).unwrap(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); // dial without peer id attached assert!(std::matches!( @@ -567,7 +567,7 @@ async fn keep_alive_timeout(transport1: Transport, transport2: Transport) { let config2 = add_transport(config2, transport2).build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p2.dial_address(address1).await.unwrap(); let mut litep2p1_ping = false; let mut litep2p2_ping = false; @@ -626,8 +626,8 @@ async fn simultaneous_dial_tcp() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -679,8 +679,8 @@ async fn simultaneous_dial_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -732,8 +732,8 @@ async fn simultaneous_dial_ipv6_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -791,7 +791,7 @@ async fn websocket_over_ipv6() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address2).await.unwrap(); let mut ping_received1 = false; @@ -843,7 +843,7 @@ async fn tcp_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -905,7 +905,7 @@ async fn websocket_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -1040,7 +1040,7 @@ async fn multiple_listen_addresses( let (mut litep2p2, _event_stream) = make_dummy_litep2p(transport2).await; let (mut litep2p3, _event_stream) = make_dummy_litep2p(transport3).await; - let addresses = litep2p1.public_addresses().get_addresses(); + let addresses = litep2p1.listen_addresses().get_addresses(); let address1 = addresses.get(0).unwrap().clone(); let address2 = addresses.get(1).unwrap().clone(); @@ -1124,7 +1124,7 @@ async fn dial_over_multiple_addresses() { // let (mut litep2p2, _event_stream) = make_dummy_litep2p(transport2).await; // let (mut litep2p3, _event_stream) = make_dummy_litep2p(transport3).await; - // let mut address_iter = litep2p1.public_addresses(); + // let mut address_iter = litep2p1.listen_addresses(); // let address1 = address_iter.next().unwrap().clone(); // let address2 = address_iter.next().unwrap().clone(); // drop(address_iter); @@ -1175,7 +1175,7 @@ async fn unspecified_listen_address_tcp() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.public_addresses().get_addresses(); + let listen_address = litep2p1.listen_addresses().get_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1276,7 +1276,7 @@ async fn unspecified_listen_address_websocket() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.public_addresses().get_addresses(); + let listen_address = litep2p1.listen_addresses().get_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1423,11 +1423,11 @@ async fn simultaneous_dial_then_redial(transport1: Transport, transport2: Transp litep2p1.add_known_address( peer2, - litep2p2.public_addresses().get_addresses().into_iter(), + litep2p2.listen_addresses().get_addresses().into_iter(), ); litep2p2.add_known_address( peer1, - litep2p1.public_addresses().get_addresses().into_iter(), + litep2p1.listen_addresses().get_addresses().into_iter(), ); let (_, _) = tokio::join!(litep2p1.dial(&peer2), litep2p2.dial(&peer1)); diff --git a/tests/custom_executor.rs b/tests/custom_executor.rs index 2d8b833b..bddc78ed 100644 --- a/tests/custom_executor.rs +++ b/tests/custom_executor.rs @@ -158,7 +158,7 @@ async fn custom_executor() { let peer2 = *litep2p2.local_peer_id(); // wait until peers have connected and spawn the litep2p objects in the background - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; diff --git a/tests/protocol/identify.rs b/tests/protocol/identify.rs index 99e34bed..58ace3b1 100644 --- a/tests/protocol/identify.rs +++ b/tests/protocol/identify.rs @@ -88,8 +88,8 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("listen address of peer1: {address1}"); tracing::info!("listen address of peer2: {address2}"); @@ -202,7 +202,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/kademlia.rs b/tests/protocol/kademlia.rs index ea578833..39cd354a 100644 --- a/tests/protocol/kademlia.rs +++ b/tests/protocol/kademlia.rs @@ -153,7 +153,7 @@ async fn records_are_stored_automatically() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.public_addresses().get_addresses(), + litep2p2.listen_addresses().get_addresses(), ) .await; @@ -234,7 +234,7 @@ async fn records_are_stored_manually() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.public_addresses().get_addresses(), + litep2p2.listen_addresses().get_addresses(), ) .await; @@ -317,7 +317,7 @@ async fn not_validated_records_are_not_stored() { kad_handle1 .add_known_peer( *litep2p2.local_peer_id(), - litep2p2.public_addresses().get_addresses(), + litep2p2.listen_addresses().get_addresses(), ) .await; @@ -419,7 +419,7 @@ async fn get_record_retrieves_remote_records() { kad_handle2 .add_known_peer( *litep2p1.local_peer_id(), - litep2p1.public_addresses().get_addresses(), + litep2p1.listen_addresses().get_addresses(), ) .await; diff --git a/tests/protocol/notification.rs b/tests/protocol/notification.rs index 416571ee..409c2071 100644 --- a/tests/protocol/notification.rs +++ b/tests/protocol/notification.rs @@ -46,7 +46,7 @@ use std::{net::Ipv6Addr, task::Poll, time::Duration}; use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; @@ -2550,7 +2550,7 @@ async fn dial_peer_when_opening_substream(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address)); // add `peer2` known address for `peer1` and spawn the litep2p objects in the background @@ -2708,8 +2708,8 @@ async fn open_and_close_batched( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -2913,8 +2913,8 @@ async fn open_and_close_batched_duplicate_peer( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -3150,7 +3150,7 @@ async fn no_listener_address_for_one_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address2 = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); tokio::spawn(async move { @@ -3550,7 +3550,7 @@ async fn dialing_disabled(transport1: Transport, transport2: Transport) { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3641,7 +3641,7 @@ async fn validation_takes_too_long(transport1: Transport, transport2: Transport) let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3748,7 +3748,7 @@ async fn ignored_validation_open_substream(transport1: Transport, transport2: Tr let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3893,7 +3893,7 @@ async fn clogged_channel_disconnects_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); diff --git a/tests/protocol/ping.rs b/tests/protocol/ping.rs index 327844f7..f460b157 100644 --- a/tests/protocol/ping.rs +++ b/tests/protocol/ping.rs @@ -70,7 +70,7 @@ async fn ping_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/request_response.rs b/tests/protocol/request_response.rs index 276d63a6..306f4e8f 100644 --- a/tests/protocol/request_response.rs +++ b/tests/protocol/request_response.rs @@ -52,7 +52,7 @@ use std::{ use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("address: {address}"); litep2p1.dial_address(address).await.unwrap(); @@ -1435,7 +1435,7 @@ async fn dial_peer_when_sending_request(transport1: Transport, transport2: Trans let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); // add known address for `peer2` and start event loop for both litep2ps litep2p1.add_known_address(peer2, std::iter::once(address)); diff --git a/tests/substream.rs b/tests/substream.rs index 3186cf81..a222bd54 100644 --- a/tests/substream.rs +++ b/tests/substream.rs @@ -218,7 +218,7 @@ impl UserProtocol for CustomProtocol { } async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let listen_address = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); litep2p2.dial_address(listen_address).await.unwrap(); let mut litep2p1_ready = false; diff --git a/tests/user_protocol.rs b/tests/user_protocol.rs index 102b2a1c..5d767d80 100644 --- a/tests/user_protocol.rs +++ b/tests/user_protocol.rs @@ -99,7 +99,7 @@ async fn user_protocol() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.public_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); let custom_protocol2 = Box::new(CustomProtocol::new()); let config2 = ConfigBuilder::new() diff --git a/tests/user_protocol_2.rs b/tests/user_protocol_2.rs index c48af02b..d4b3e9ec 100644 --- a/tests/user_protocol_2.rs +++ b/tests/user_protocol_2.rs @@ -122,7 +122,7 @@ async fn user_protocol_2() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); sender1.send(address).await.unwrap(); diff --git a/tests/webrtc.rs b/tests/webrtc.rs index d2c40406..acacb5a4 100644 --- a/tests/webrtc.rs +++ b/tests/webrtc.rs @@ -58,7 +58,7 @@ async fn webrtc_test() { .build(); let mut litep2p = Litep2p::new(config).unwrap(); - let address = litep2p.public_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); tracing::info!("listen address: {address:?}"); From 41c1e23a7221b6efc04467370c5fdb465ce49ec5 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 12:28:24 +0300 Subject: [PATCH 25/30] Fix documentation Signed-off-by: Alexandru Vasile --- src/addresses.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/addresses.rs b/src/addresses.rs index 63a40061..fc7420af 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -28,7 +28,7 @@ use crate::PeerId; /// Set of the public addresses of the local node. /// /// The format of the addresses stored in the set contain the local peer ID. -/// This requirement is enforced by the [`PublicAddresses::add_public_address`] method, +/// This requirement is enforced by the [`PublicAddresses::add_address`] method, /// that will add the local peer ID to the address if it is missing. /// /// # Note @@ -76,6 +76,12 @@ impl PublicAddresses { } } +/// Set of the addresses the local node listens on. +/// +/// The format of the addresses stored in the set contain the local peer ID. +/// This requirement is enforced by the [`ListenAddresses::add_address`] method. +/// +/// The listen addresses are populated during the construction of the Litep2p object. #[derive(Debug, Clone)] pub struct ListenAddresses { pub(crate) inner: Arc>>, From fd23d156f01d84975e26b05e6f4a08d76dfffa40 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 12:31:50 +0300 Subject: [PATCH 26/30] address: Introduce insertion error for better reporting Signed-off-by: Alexandru Vasile --- src/addresses.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/addresses.rs b/src/addresses.rs index fc7420af..2074c152 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -58,7 +58,7 @@ impl PublicAddresses { /// In case the address does not contain any peer ID, it will be added. /// /// Returns true if the address was added, false if it was already present. - pub fn add_address(&self, address: Multiaddr) -> Result { + pub fn add_address(&self, address: Multiaddr) -> Result { let address = ensure_local_peer(address, self.local_peer_id)?; Ok(self.inner.write().insert(address)) } @@ -99,7 +99,7 @@ impl ListenAddresses { /// Add a listen address to the list of addresses. /// /// Returns true if the address was added, false if it was already present. - pub fn add_address(&self, address: Multiaddr) -> Result { + pub fn add_address(&self, address: Multiaddr) -> Result { let address = ensure_local_peer(address, self.local_peer_id)?; Ok(self.inner.write().insert(address)) } @@ -116,18 +116,20 @@ impl ListenAddresses { } /// Check if the address contains the local peer ID. +/// +/// If the address does not contain any peer ID, it will be added. fn ensure_local_peer( mut address: Multiaddr, local_peer_id: PeerId, -) -> Result { +) -> Result { if address.is_empty() { - return Err(address); + return Err(InsertionError::EmptyAddress); } // Verify the peer ID from the address corresponds to the local peer ID. if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { if peer_id != local_peer_id { - return Err(address); + return Err(InsertionError::DifferentPeerId); } } else { address.push(Protocol::P2p(local_peer_id.into())); @@ -136,6 +138,15 @@ fn ensure_local_peer( Ok(address) } +/// The error returned when an address cannot be inserted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InsertionError { + /// The address is empty. + EmptyAddress, + /// The address contains a different peer ID than the local peer ID. + DifferentPeerId, +} + #[cfg(test)] mod tests { use super::*; From be8d66366fad70d0a8bed538859c6059edd4ad18 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 18:10:07 +0300 Subject: [PATCH 27/30] Remove ListenAddresses Signed-off-by: Alexandru Vasile --- src/addresses.rs | 39 ------------------------ src/lib.rs | 50 +++++++++++++++++-------------- src/protocol/libp2p/identify.rs | 27 +++++------------ src/protocol/transport_service.rs | 4 +-- src/transport/manager/handle.rs | 15 +++++----- src/transport/manager/mod.rs | 24 ++++++++++----- 6 files changed, 60 insertions(+), 99 deletions(-) diff --git a/src/addresses.rs b/src/addresses.rs index 2074c152..609efbe0 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -76,45 +76,6 @@ impl PublicAddresses { } } -/// Set of the addresses the local node listens on. -/// -/// The format of the addresses stored in the set contain the local peer ID. -/// This requirement is enforced by the [`ListenAddresses::add_address`] method. -/// -/// The listen addresses are populated during the construction of the Litep2p object. -#[derive(Debug, Clone)] -pub struct ListenAddresses { - pub(crate) inner: Arc>>, - local_peer_id: PeerId, -} - -impl ListenAddresses { - /// Creates new [`ListenAddresses`] from the given peer ID. - pub(crate) fn new(local_peer_id: PeerId) -> Self { - Self { - inner: Arc::new(RwLock::new(HashSet::new())), - local_peer_id, - } - } - /// Add a listen address to the list of addresses. - /// - /// Returns true if the address was added, false if it was already present. - pub fn add_address(&self, address: Multiaddr) -> Result { - let address = ensure_local_peer(address, self.local_peer_id)?; - Ok(self.inner.write().insert(address)) - } - - /// Remove the listen address. - pub fn remove_address(&self, address: &Multiaddr) -> bool { - self.inner.write().remove(address) - } - - /// Returns a vector of the available listen addresses. - pub fn get_addresses(&self) -> Vec { - self.inner.read().iter().cloned().collect() - } -} - /// Check if the address contains the local peer ID. /// /// If the address does not contain any peer ID, it will be added. diff --git a/src/lib.rs b/src/lib.rs index 78b73e92..58e5cf9c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -52,8 +52,8 @@ use crate::transport::webrtc::WebRtcTransport; #[cfg(feature = "websocket")] use crate::transport::websocket::WebSocketTransport; -use addresses::ListenAddresses; -use multiaddr::Multiaddr; +use multiaddr::{Multiaddr, Protocol}; +use multihash::Multihash; use transport::Endpoint; use types::ConnectionId; @@ -140,7 +140,7 @@ pub struct Litep2p { local_peer_id: PeerId, /// Listen addresses. - listen_addresses: ListenAddresses, + listen_addresses: Vec, /// Listen addresses. public_addresses: PublicAddresses, @@ -157,6 +157,7 @@ impl Litep2p { pub fn new(mut litep2p_config: Litep2pConfig) -> crate::Result { let local_peer_id = PeerId::from_public_key(&litep2p_config.keypair.public().into()); let bandwidth_sink = BandwidthSink::new(); + let mut listen_addresses = vec![]; let supported_transports = Self::supported_transports(&litep2p_config); let (mut transport_manager, transport_handle) = TransportManager::new( @@ -166,7 +167,6 @@ impl Litep2p { litep2p_config.max_parallel_dials, litep2p_config.connection_limits, ); - let listen_addresses = transport_manager.listen_addresses(); // add known addresses to `TransportManager`, if any exist if !litep2p_config.known_addresses.is_empty() { @@ -319,9 +319,10 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - if let Err(err) = listen_addresses.add_address(address.clone()) { - tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); - } + transport_manager.register_listen_address(address.clone()); + listen_addresses.push(address.with(Protocol::P2p( + Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), + ))); } transport_manager.register_transport(SupportedTransport::Tcp, Box::new(transport)); @@ -335,9 +336,10 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - if let Err(err) = listen_addresses.add_address(address.clone()) { - tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); - } + transport_manager.register_listen_address(address.clone()); + listen_addresses.push(address.with(Protocol::P2p( + Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), + ))); } transport_manager.register_transport(SupportedTransport::Quic, Box::new(transport)); @@ -351,9 +353,10 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - if let Err(err) = listen_addresses.add_address(address.clone()) { - tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); - } + transport_manager.register_listen_address(address.clone()); + listen_addresses.push(address.with(Protocol::P2p( + Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), + ))); } transport_manager.register_transport(SupportedTransport::WebRtc, Box::new(transport)); @@ -367,9 +370,10 @@ impl Litep2p { ::new(handle, config)?; for address in transport_listen_addresses { - if let Err(err) = listen_addresses.add_address(address.clone()) { - tracing::warn!(target: LOG_TARGET, ?err, "failed to register listen address"); - } + transport_manager.register_listen_address(address.clone()); + listen_addresses.push(address.with(Protocol::P2p( + Multihash::from_bytes(&local_peer_id.to_bytes()).unwrap(), + ))); } transport_manager @@ -378,7 +382,7 @@ impl Litep2p { // enable mdns if the config exists if let Some(config) = litep2p_config.mdns.take() { - let mdns = Mdns::new(transport_handle, config, listen_addresses.get_addresses())?; + let mdns = Mdns::new(transport_handle, config, listen_addresses.clone())?; litep2p_config.executor.run(Box::pin(async move { let _ = mdns.start().await; @@ -400,7 +404,7 @@ impl Litep2p { } // verify that at least one transport is specified - if listen_addresses.inner.read().is_empty() { + if listen_addresses.is_empty() { tracing::warn!( target: LOG_TARGET, "litep2p started with no listen addresses, cannot accept inbound connections", @@ -452,16 +456,16 @@ impl Litep2p { &self.local_peer_id } - /// Get the list of listen addresses of the node. - pub fn listen_addresses(&self) -> ListenAddresses { - self.listen_addresses.clone() - } - /// Get the list of public addresses of the node. pub fn public_addresses(&self) -> PublicAddresses { self.public_addresses.clone() } + /// Get the list of listen addresses of the node. + pub fn listen_addresses(&self) -> Vec { + self.listen_addresses.clone() + } + /// Get handle to bandwidth sink. pub fn bandwidth_sink(&self) -> BandwidthSink { self.bandwidth_sink.clone() diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 0ead262f..0b249fac 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -21,7 +21,6 @@ //! [`/ipfs/identify/1.0.0`](https://github.com/libp2p/specs/blob/master/identify/README.md) implementation. use crate::{ - addresses::{ListenAddresses, PublicAddresses}, codec::ProtocolCodec, crypto::PublicKey, error::{Error, SubstreamError}, @@ -183,14 +182,8 @@ pub(crate) struct Identify { /// User agent. user_agent: String, - /// Listen addresses. - listen_addresses: ListenAddresses, - - /// Public addresses. - public_addresses: PublicAddresses, - - /// User provided list of addresses. - user_addresses: Vec>, + /// User provided list of addresses concatenated with the listen addresses. + addresses: HashSet>, /// Protocols supported by the local node, filled by `Litep2p`. protocols: Vec, @@ -208,18 +201,14 @@ pub(crate) struct Identify { impl Identify { /// Create new [`Identify`] protocol. pub(crate) fn new(service: TransportService, config: Config) -> Self { - let listen_addresses = service.listen_addresses(); - let public_addresses = service.public_addresses(); - let user_addresses = - config.public_addresses.into_iter().map(|addr| addr.to_vec()).collect(); + let mut addresses = service.listen_addresses(); + addresses.extend(config.public_addresses.iter().cloned()); Self { service, tx: config.tx_event, peers: HashMap::new(), - listen_addresses, - public_addresses, - user_addresses, + addresses: addresses.into_iter().map(|addr| addr.to_vec()).collect(), public: config.public.expect("public key to be supplied"), protocol_version: config.protocol_version, user_agent: config.user_agent.unwrap_or(DEFAULT_AGENT.to_string()), @@ -275,9 +264,9 @@ impl Identify { } }; - let mut listen_addr: HashSet<_> = self.user_addresses.iter().cloned().collect(); - listen_addr.extend(self.listen_addresses.inner.read().iter().map(|addr| addr.to_vec())); - listen_addr.extend(self.public_addresses.inner.read().iter().map(|addr| addr.to_vec())); + let mut listen_addr: HashSet<_> = self.addresses.clone(); + listen_addr + .extend(self.service.public_addresses().inner.read().iter().map(|addr| addr.to_vec())); let identify = identify_schema::Identify { protocol_version: Some(self.protocol_version.clone()), diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index c3450b83..8e84269b 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use crate::{ - addresses::{ListenAddresses, PublicAddresses}, + addresses::PublicAddresses, error::Error, protocol::{connection::ConnectionHandle, InnerTransportEvent, TransportEvent}, transport::{manager::TransportManagerHandle, Endpoint}, @@ -164,7 +164,7 @@ impl TransportService { } /// Get the list of listen addresses of the node. - pub fn listen_addresses(&self) -> ListenAddresses { + pub fn listen_addresses(&self) -> HashSet { self.transport_handle.listen_addresses() } diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index 8e51b8d2..89b57468 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use crate::{ - addresses::{ListenAddresses, PublicAddresses}, + addresses::PublicAddresses, crypto::ed25519::Keypair, error::{AddressError, Error}, executor::Executor, @@ -77,7 +77,7 @@ pub struct TransportManagerHandle { supported_transport: HashSet, /// Local listen addresess. - listen_addresses: ListenAddresses, + listen_addresses: Arc>>, /// Public addresses. public_addresses: PublicAddresses, @@ -90,7 +90,7 @@ impl TransportManagerHandle { peers: Arc>>, cmd_tx: Sender, supported_transport: HashSet, - listen_addresses: ListenAddresses, + listen_addresses: Arc>>, public_addresses: PublicAddresses, ) -> Self { Self { @@ -114,8 +114,8 @@ impl TransportManagerHandle { } /// Get the list of listen addresses of the node. - pub(crate) fn listen_addresses(&self) -> ListenAddresses { - self.listen_addresses.clone() + pub(crate) fn listen_addresses(&self) -> HashSet { + self.listen_addresses.read().clone() } /// Check if `address` is supported by one of the enabled transports. @@ -162,13 +162,12 @@ impl TransportManagerHandle { /// Check if the address is a local listen address and if so, discard it. fn is_local_address(&self, address: &Multiaddr) -> bool { - let mut address: Multiaddr = address + let address: Multiaddr = address .iter() .take_while(|protocol| !std::matches!(protocol, Protocol::P2p(_))) .collect(); - address.push(Protocol::P2p(self.local_peer_id.into())); - self.listen_addresses.inner.read().contains(&address) + self.listen_addresses.read().contains(&address) } /// Add one or more known addresses for peer. diff --git a/src/transport/manager/mod.rs b/src/transport/manager/mod.rs index 4105e92c..6816bbf2 100644 --- a/src/transport/manager/mod.rs +++ b/src/transport/manager/mod.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use crate::{ - addresses::{ListenAddresses, PublicAddresses}, + addresses::PublicAddresses, codec::ProtocolCodec, crypto::ed25519::Keypair, error::{AddressError, DialError, Error}, @@ -40,6 +40,7 @@ use crate::{ use futures::{Stream, StreamExt}; use indexmap::IndexMap; use multiaddr::{Multiaddr, Protocol}; +use multihash::Multihash; use parking_lot::RwLock; use tokio::sync::mpsc::{channel, Receiver, Sender}; @@ -217,7 +218,7 @@ pub struct TransportManager { protocol_names: HashSet, /// Listen addresses. - listen_addresses: ListenAddresses, + listen_addresses: Arc>>, /// Listen addresses. public_addresses: PublicAddresses, @@ -270,7 +271,7 @@ impl TransportManager { let peers = Arc::new(RwLock::new(HashMap::new())); let (cmd_tx, cmd_rx) = channel(256); let (event_tx, event_rx) = channel(256); - let listen_addresses = ListenAddresses::new(local_peer_id); + let listen_addresses = Arc::new(RwLock::new(HashSet::new())); let public_addresses = PublicAddresses::new(local_peer_id); let handle = TransportManagerHandle::new( local_peer_id, @@ -392,9 +393,16 @@ impl TransportManager { self.public_addresses.clone() } - /// Get the list of listen addresses of the node. - pub(crate) fn listen_addresses(&self) -> ListenAddresses { - self.listen_addresses.clone() + /// Register local listen address. + pub fn register_listen_address(&mut self, address: Multiaddr) { + assert!(!address.iter().any(|protocol| std::matches!(protocol, Protocol::P2p(_)))); + + let mut listen_addresses = self.listen_addresses.write(); + + listen_addresses.insert(address.clone()); + listen_addresses.insert(address.with(Protocol::P2p( + Multihash::from_bytes(&self.local_peer_id.to_bytes()).unwrap(), + ))); } /// Add one or more known addresses for `peer`. @@ -483,7 +491,7 @@ impl TransportManager { return Err(Error::NoAddressAvailable(peer)); } - let locked_addresses = self.listen_addresses.inner.read(); + let locked_addresses = self.listen_addresses.read(); for record in records.values() { if locked_addresses.contains(record.as_ref()) { tracing::warn!( @@ -588,7 +596,7 @@ impl TransportManager { let mut record = AddressRecord::from_multiaddr(address) .ok_or(Error::AddressError(AddressError::PeerIdMissing))?; - if self.listen_addresses.inner.read().contains(record.as_ref()) { + if self.listen_addresses.read().contains(record.as_ref()) { return Err(Error::TriedToDialSelf); } From af8fe6035bfde0661c39b5feecdf74c935b51faa Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 18:25:29 +0300 Subject: [PATCH 28/30] Adjust testing Signed-off-by: Alexandru Vasile --- examples/custom_executor.rs | 2 +- examples/custom_protocol.rs | 2 +- examples/echo_notification.rs | 2 +- examples/gossiping.rs | 2 +- src/lib.rs | 6 +-- src/protocol/libp2p/identify.rs | 13 +++--- src/protocol/transport_service.rs | 2 +- src/transport/manager/handle.rs | 9 ++-- tests/conformance/rust/identify.rs | 2 +- tests/conformance/rust/kademlia.rs | 6 +-- tests/conformance/rust/ping.rs | 2 +- tests/conformance/substrate/connection.rs | 2 +- tests/conformance/substrate/notifications.rs | 14 +++---- .../conformance/substrate/request_response.rs | 10 ++--- tests/connection/mod.rs | 42 ++++++++----------- tests/custom_executor.rs | 2 +- tests/protocol/identify.rs | 6 +-- tests/protocol/kademlia.rs | 17 ++------ tests/protocol/notification.rs | 22 +++++----- tests/protocol/ping.rs | 2 +- tests/protocol/request_response.rs | 4 +- tests/substream.rs | 2 +- tests/user_protocol.rs | 2 +- tests/user_protocol_2.rs | 2 +- tests/webrtc.rs | 2 +- 25 files changed, 78 insertions(+), 99 deletions(-) diff --git a/examples/custom_executor.rs b/examples/custom_executor.rs index 5a5cbd98..3b765e0e 100644 --- a/examples/custom_executor.rs +++ b/examples/custom_executor.rs @@ -122,7 +122,7 @@ async fn main() { // dial `litep2p1` litep2p2 - .dial_address(litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone()) + .dial_address(litep2p1.listen_addresses().get(0).unwrap().clone()) .await .unwrap(); diff --git a/examples/custom_protocol.rs b/examples/custom_protocol.rs index 7eead39f..a2f6f8d9 100644 --- a/examples/custom_protocol.rs +++ b/examples/custom_protocol.rs @@ -277,7 +277,7 @@ async fn main() { let (mut litep2p2, mut handle2) = make_litep2p(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(listen_address)); tokio::spawn(async move { diff --git a/examples/echo_notification.rs b/examples/echo_notification.rs index 4521c934..af87b23e 100644 --- a/examples/echo_notification.rs +++ b/examples/echo_notification.rs @@ -125,7 +125,7 @@ async fn main() { // get the first (and only) listen address for the second peer // and add it as a known address for `litep2p1` - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); let peer = *litep2p2.local_peer_id(); litep2p1.add_known_address(peer, vec![listen_address].into_iter()); diff --git a/examples/gossiping.rs b/examples/gossiping.rs index 730d23db..ffd5d3f2 100644 --- a/examples/gossiping.rs +++ b/examples/gossiping.rs @@ -237,7 +237,7 @@ async fn main() { // establish connection to litep2p for all other litep2ps let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address.clone()].into_iter()); litep2p3.add_known_address(peer2, vec![listen_address.clone()].into_iter()); diff --git a/src/lib.rs b/src/lib.rs index 58e5cf9c..027cebd9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -142,9 +142,6 @@ pub struct Litep2p { /// Listen addresses. listen_addresses: Vec, - /// Listen addresses. - public_addresses: PublicAddresses, - /// Transport manager. transport_manager: TransportManager, @@ -415,7 +412,6 @@ impl Litep2p { local_peer_id, bandwidth_sink, listen_addresses, - public_addresses: transport_manager.public_addresses(), transport_manager, }) } @@ -458,7 +454,7 @@ impl Litep2p { /// Get the list of public addresses of the node. pub fn public_addresses(&self) -> PublicAddresses { - self.public_addresses.clone() + self.transport_manager.public_addresses() } /// Get the list of listen addresses of the node. diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 0b249fac..90449b60 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -182,7 +182,7 @@ pub(crate) struct Identify { /// User agent. user_agent: String, - /// User provided list of addresses concatenated with the listen addresses. + /// User provided list of addresses. addresses: HashSet>, /// Protocols supported by the local node, filled by `Litep2p`. @@ -201,14 +201,11 @@ pub(crate) struct Identify { impl Identify { /// Create new [`Identify`] protocol. pub(crate) fn new(service: TransportService, config: Config) -> Self { - let mut addresses = service.listen_addresses(); - addresses.extend(config.public_addresses.iter().cloned()); - Self { service, tx: config.tx_event, peers: HashMap::new(), - addresses: addresses.into_iter().map(|addr| addr.to_vec()).collect(), + addresses: config.public_addresses.into_iter().map(|addr| addr.to_vec()).collect(), public: config.public.expect("public key to be supplied"), protocol_version: config.protocol_version, user_agent: config.user_agent.unwrap_or(DEFAULT_AGENT.to_string()), @@ -265,6 +262,7 @@ impl Identify { }; let mut listen_addr: HashSet<_> = self.addresses.clone(); + listen_addr.extend(self.service.listen_addresses().into_iter().map(|addr| addr.to_vec())); listen_addr .extend(self.service.public_addresses().inner.read().iter().map(|addr| addr.to_vec())); @@ -449,12 +447,11 @@ mod tests { // Create two instances of litep2p let (mut litep2p1, mut event_stream1, peer1) = create_litep2p(); let (mut litep2p2, mut event_stream2, _peer2) = create_litep2p(); - let litep2p1_address = - litep2p1.listen_addresses().get_addresses().into_iter().next().unwrap(); + let litep2p1_address = litep2p1.listen_addresses().into_iter().next().unwrap(); let multiaddr: Multiaddr = "/ip6/::9/tcp/111".parse().unwrap(); // Litep2p1 is now reporting the new address. - assert!(litep2p1.listen_addresses().add_address(multiaddr.clone()).unwrap()); + assert!(litep2p1.public_addresses().add_address(multiaddr.clone()).unwrap()); // Dial `litep2p1` litep2p2.dial_address(litep2p1_address).await.unwrap(); diff --git a/src/protocol/transport_service.rs b/src/protocol/transport_service.rs index 8e84269b..1525cb53 100644 --- a/src/protocol/transport_service.rs +++ b/src/protocol/transport_service.rs @@ -455,7 +455,7 @@ mod tests { Arc::new(RwLock::new(HashMap::new())), cmd_tx, HashSet::new(), - ListenAddresses::new(peer), + Default::default(), PublicAddresses::new(peer), ); diff --git a/src/transport/manager/handle.rs b/src/transport/manager/handle.rs index 89b57468..90fe7efc 100644 --- a/src/transport/manager/handle.rs +++ b/src/transport/manager/handle.rs @@ -329,6 +329,7 @@ impl TransportHandle { mod tests { use super::*; use multihash::Multihash; + use parking_lot::lock_api::RwLock; use tokio::sync::mpsc::{channel, Receiver}; fn make_transport_manager_handle() -> ( @@ -344,7 +345,7 @@ mod tests { cmd_tx, peers: Default::default(), supported_transport: HashSet::new(), - listen_addresses: ListenAddresses::new(local_peer_id), + listen_addresses: Default::default(), public_addresses: PublicAddresses::new(local_peer_id), }, cmd_rx, @@ -609,9 +610,9 @@ mod tests { let first_addr: Multiaddr = "/ip6/::1/tcp/8888".parse().expect("valid multiaddress"); let second_addr: Multiaddr = "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress"); - let listen_addresses = ListenAddresses::new(local_peer_id); - listen_addresses.add_address(first_addr.clone()).unwrap(); - listen_addresses.add_address(second_addr.clone()).unwrap(); + let listen_addresses = Arc::new(RwLock::new( + [first_addr.clone(), second_addr.clone()].iter().cloned().collect(), + )); println!("{:?}", listen_addresses); let handle = TransportManagerHandle { diff --git a/tests/conformance/rust/identify.rs b/tests/conformance/rust/identify.rs index 66d0ccd5..6dd21c77 100644 --- a/tests/conformance/rust/identify.rs +++ b/tests/conformance/rust/identify.rs @@ -119,7 +119,7 @@ async fn identify_works() { let mut libp2p = initialize_libp2p(); let (mut litep2p, _ping_event_stream, mut identify_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/rust/kademlia.rs b/tests/conformance/rust/kademlia.rs index eebc539d..a96bba37 100644 --- a/tests/conformance/rust/kademlia.rs +++ b/tests/conformance/rust/kademlia.rs @@ -119,7 +119,7 @@ async fn find_node() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -223,7 +223,7 @@ async fn put_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -335,7 +335,7 @@ async fn get_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); diff --git a/tests/conformance/rust/ping.rs b/tests/conformance/rust/ping.rs index 5e4213aa..9192eaf2 100644 --- a/tests/conformance/rust/ping.rs +++ b/tests/conformance/rust/ping.rs @@ -81,7 +81,7 @@ async fn libp2p_dials() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut ping_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/substrate/connection.rs b/tests/conformance/substrate/connection.rs index ff4c318c..9dba4816 100644 --- a/tests/conformance/substrate/connection.rs +++ b/tests/conformance/substrate/connection.rs @@ -110,7 +110,7 @@ async fn substrate_keep_alive_timeout() { let (mut libp2p, _peer_store_handle) = initialize_libp2p(1u32, 1u32); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_connection_open = false; diff --git a/tests/conformance/substrate/notifications.rs b/tests/conformance/substrate/notifications.rs index ada5915f..6cab988e 100644 --- a/tests/conformance/substrate/notifications.rs +++ b/tests/conformance/substrate/notifications.rs @@ -119,7 +119,7 @@ async fn substrate_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -214,7 +214,7 @@ async fn litep2p_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -311,7 +311,7 @@ async fn substrate_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -360,7 +360,7 @@ async fn litep2p_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -412,7 +412,7 @@ async fn substrate_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_notification_count = 0; @@ -504,7 +504,7 @@ async fn litep2p_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut notif_count = 0; @@ -584,7 +584,7 @@ async fn both_nodes_open_substreams() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; diff --git a/tests/conformance/substrate/request_response.rs b/tests/conformance/substrate/request_response.rs index 39d2cbe5..80a9c41b 100644 --- a/tests/conformance/substrate/request_response.rs +++ b/tests/conformance/substrate/request_response.rs @@ -101,7 +101,7 @@ async fn request_works() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let libp2p_peer = *libp2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -197,7 +197,7 @@ async fn substrate_reject_request() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); tokio::spawn(peer_store.run()); @@ -254,7 +254,7 @@ async fn litep2p_reject_request() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -321,7 +321,7 @@ async fn substrate_request_timeout() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); let mut _timeout_request = None; @@ -379,7 +379,7 @@ async fn litep2p_request_timeout() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); diff --git a/tests/connection/mod.rs b/tests/connection/mod.rs index a74ff7b7..b489a2f1 100644 --- a/tests/connection/mod.rs +++ b/tests/connection/mod.rs @@ -108,7 +108,7 @@ async fn two_litep2ps_work(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let (res1, res2) = tokio::join!(litep2p1.next_event(), litep2p2.next_event()); @@ -255,7 +255,7 @@ async fn connect_over_dns() { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let mut new_address = Multiaddr::empty(); @@ -440,7 +440,7 @@ async fn dial_self(transport: Transport) { let litep2p_config = add_transport(litep2p_config, transport).build(); let mut litep2p = Litep2p::new(litep2p_config).unwrap(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); // dial without peer id attached assert!(std::matches!( @@ -567,7 +567,7 @@ async fn keep_alive_timeout(transport1: Transport, transport2: Transport) { let config2 = add_transport(config2, transport2).build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); litep2p2.dial_address(address1).await.unwrap(); let mut litep2p1_ping = false; let mut litep2p2_ping = false; @@ -626,8 +626,8 @@ async fn simultaneous_dial_tcp() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -679,8 +679,8 @@ async fn simultaneous_dial_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -732,8 +732,8 @@ async fn simultaneous_dial_ipv6_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -791,7 +791,7 @@ async fn websocket_over_ipv6() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address2).await.unwrap(); let mut ping_received1 = false; @@ -843,7 +843,7 @@ async fn tcp_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -905,7 +905,7 @@ async fn websocket_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -1040,7 +1040,7 @@ async fn multiple_listen_addresses( let (mut litep2p2, _event_stream) = make_dummy_litep2p(transport2).await; let (mut litep2p3, _event_stream) = make_dummy_litep2p(transport3).await; - let addresses = litep2p1.listen_addresses().get_addresses(); + let addresses = litep2p1.listen_addresses(); let address1 = addresses.get(0).unwrap().clone(); let address2 = addresses.get(1).unwrap().clone(); @@ -1175,7 +1175,7 @@ async fn unspecified_listen_address_tcp() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses().get_addresses(); + let listen_address = litep2p1.listen_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1276,7 +1276,7 @@ async fn unspecified_listen_address_websocket() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses().get_addresses(); + let listen_address = litep2p1.listen_addresses(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1421,14 +1421,8 @@ async fn simultaneous_dial_then_redial(transport1: Transport, transport2: Transp let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - litep2p1.add_known_address( - peer2, - litep2p2.listen_addresses().get_addresses().into_iter(), - ); - litep2p2.add_known_address( - peer1, - litep2p1.listen_addresses().get_addresses().into_iter(), - ); + litep2p1.add_known_address(peer2, litep2p2.listen_addresses().into_iter()); + litep2p2.add_known_address(peer1, litep2p1.listen_addresses().into_iter()); let (_, _) = tokio::join!(litep2p1.dial(&peer2), litep2p2.dial(&peer1)); diff --git a/tests/custom_executor.rs b/tests/custom_executor.rs index bddc78ed..ede32a98 100644 --- a/tests/custom_executor.rs +++ b/tests/custom_executor.rs @@ -158,7 +158,7 @@ async fn custom_executor() { let peer2 = *litep2p2.local_peer_id(); // wait until peers have connected and spawn the litep2p objects in the background - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; diff --git a/tests/protocol/identify.rs b/tests/protocol/identify.rs index 58ace3b1..57ec4369 100644 --- a/tests/protocol/identify.rs +++ b/tests/protocol/identify.rs @@ -88,8 +88,8 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); tracing::info!("listen address of peer1: {address1}"); tracing::info!("listen address of peer2: {address2}"); @@ -202,7 +202,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/kademlia.rs b/tests/protocol/kademlia.rs index 39cd354a..e9ba2ed3 100644 --- a/tests/protocol/kademlia.rs +++ b/tests/protocol/kademlia.rs @@ -151,10 +151,7 @@ async fn records_are_stored_automatically() { let mut litep2p2 = Litep2p::new(config2).unwrap(); kad_handle1 - .add_known_peer( - *litep2p2.local_peer_id(), - litep2p2.listen_addresses().get_addresses(), - ) + .add_known_peer(*litep2p2.local_peer_id(), litep2p2.listen_addresses()) .await; // Publish the record. @@ -232,10 +229,7 @@ async fn records_are_stored_manually() { let mut litep2p2 = Litep2p::new(config2).unwrap(); kad_handle1 - .add_known_peer( - *litep2p2.local_peer_id(), - litep2p2.listen_addresses().get_addresses(), - ) + .add_known_peer(*litep2p2.local_peer_id(), litep2p2.listen_addresses()) .await; // Publish the record. @@ -315,10 +309,7 @@ async fn not_validated_records_are_not_stored() { let mut litep2p2 = Litep2p::new(config2).unwrap(); kad_handle1 - .add_known_peer( - *litep2p2.local_peer_id(), - litep2p2.listen_addresses().get_addresses(), - ) + .add_known_peer(*litep2p2.local_peer_id(), litep2p2.listen_addresses()) .await; // Publish the record. @@ -419,7 +410,7 @@ async fn get_record_retrieves_remote_records() { kad_handle2 .add_known_peer( *litep2p1.local_peer_id(), - litep2p1.listen_addresses().get_addresses(), + litep2p1.listen_addresses(), ) .await; diff --git a/tests/protocol/notification.rs b/tests/protocol/notification.rs index 409c2071..c8e721be 100644 --- a/tests/protocol/notification.rs +++ b/tests/protocol/notification.rs @@ -46,7 +46,7 @@ use std::{net::Ipv6Addr, task::Poll, time::Duration}; use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; @@ -2550,7 +2550,7 @@ async fn dial_peer_when_opening_substream(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address)); // add `peer2` known address for `peer1` and spawn the litep2p objects in the background @@ -2708,8 +2708,8 @@ async fn open_and_close_batched( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -2913,8 +2913,8 @@ async fn open_and_close_batched_duplicate_peer( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address3 = litep2p3.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -3150,7 +3150,7 @@ async fn no_listener_address_for_one_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address2 = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); tokio::spawn(async move { @@ -3550,7 +3550,7 @@ async fn dialing_disabled(transport1: Transport, transport2: Transport) { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3641,7 +3641,7 @@ async fn validation_takes_too_long(transport1: Transport, transport2: Transport) let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3748,7 +3748,7 @@ async fn ignored_validation_open_substream(transport1: Transport, transport2: Tr let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3893,7 +3893,7 @@ async fn clogged_channel_disconnects_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); diff --git a/tests/protocol/ping.rs b/tests/protocol/ping.rs index f460b157..b74ac08e 100644 --- a/tests/protocol/ping.rs +++ b/tests/protocol/ping.rs @@ -70,7 +70,7 @@ async fn ping_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/request_response.rs b/tests/protocol/request_response.rs index 306f4e8f..2afa29e3 100644 --- a/tests/protocol/request_response.rs +++ b/tests/protocol/request_response.rs @@ -52,7 +52,7 @@ use std::{ use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); tracing::info!("address: {address}"); litep2p1.dial_address(address).await.unwrap(); @@ -1435,7 +1435,7 @@ async fn dial_peer_when_sending_request(transport1: Transport, transport2: Trans let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); // add known address for `peer2` and start event loop for both litep2ps litep2p1.add_known_address(peer2, std::iter::once(address)); diff --git a/tests/substream.rs b/tests/substream.rs index a222bd54..0e7e376f 100644 --- a/tests/substream.rs +++ b/tests/substream.rs @@ -218,7 +218,7 @@ impl UserProtocol for CustomProtocol { } async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.listen_addresses().get(0).unwrap().clone(); litep2p2.dial_address(listen_address).await.unwrap(); let mut litep2p1_ready = false; diff --git a/tests/user_protocol.rs b/tests/user_protocol.rs index 5d767d80..09bc451f 100644 --- a/tests/user_protocol.rs +++ b/tests/user_protocol.rs @@ -99,7 +99,7 @@ async fn user_protocol() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses().get_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.listen_addresses().get(0).unwrap().clone(); let custom_protocol2 = Box::new(CustomProtocol::new()); let config2 = ConfigBuilder::new() diff --git a/tests/user_protocol_2.rs b/tests/user_protocol_2.rs index d4b3e9ec..58011ded 100644 --- a/tests/user_protocol_2.rs +++ b/tests/user_protocol_2.rs @@ -122,7 +122,7 @@ async fn user_protocol_2() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().get(0).unwrap().clone(); sender1.send(address).await.unwrap(); diff --git a/tests/webrtc.rs b/tests/webrtc.rs index acacb5a4..dee0e14f 100644 --- a/tests/webrtc.rs +++ b/tests/webrtc.rs @@ -58,7 +58,7 @@ async fn webrtc_test() { .build(); let mut litep2p = Litep2p::new(config).unwrap(); - let address = litep2p.listen_addresses().get_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().get(0).unwrap().clone(); tracing::info!("listen address: {address:?}"); From 39153f120077601a9aa3854ea815cea4c4513d2b Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Tue, 3 Sep 2024 18:40:35 +0300 Subject: [PATCH 29/30] Adjust testing Signed-off-by: Alexandru Vasile --- examples/custom_executor.rs | 2 +- examples/custom_protocol.rs | 2 +- examples/echo_notification.rs | 2 +- examples/gossiping.rs | 2 +- src/lib.rs | 4 +-- src/protocol/libp2p/identify.rs | 2 +- tests/conformance/rust/identify.rs | 2 +- tests/conformance/rust/kademlia.rs | 6 ++-- tests/conformance/rust/ping.rs | 2 +- tests/conformance/substrate/connection.rs | 2 +- tests/conformance/substrate/notifications.rs | 14 ++++---- .../conformance/substrate/request_response.rs | 10 +++--- tests/connection/mod.rs | 36 +++++++++---------- tests/custom_executor.rs | 2 +- tests/protocol/identify.rs | 6 ++-- tests/protocol/kademlia.rs | 17 ++++++--- tests/protocol/notification.rs | 22 ++++++------ tests/protocol/ping.rs | 2 +- tests/protocol/request_response.rs | 4 +-- tests/substream.rs | 2 +- tests/user_protocol.rs | 2 +- tests/user_protocol_2.rs | 2 +- tests/webrtc.rs | 2 +- 23 files changed, 78 insertions(+), 69 deletions(-) diff --git a/examples/custom_executor.rs b/examples/custom_executor.rs index 3b765e0e..34ab4748 100644 --- a/examples/custom_executor.rs +++ b/examples/custom_executor.rs @@ -122,7 +122,7 @@ async fn main() { // dial `litep2p1` litep2p2 - .dial_address(litep2p1.listen_addresses().get(0).unwrap().clone()) + .dial_address(litep2p1.listen_addresses().next().unwrap().clone()) .await .unwrap(); diff --git a/examples/custom_protocol.rs b/examples/custom_protocol.rs index a2f6f8d9..b69ede2d 100644 --- a/examples/custom_protocol.rs +++ b/examples/custom_protocol.rs @@ -277,7 +277,7 @@ async fn main() { let (mut litep2p2, mut handle2) = make_litep2p(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(listen_address)); tokio::spawn(async move { diff --git a/examples/echo_notification.rs b/examples/echo_notification.rs index af87b23e..11842257 100644 --- a/examples/echo_notification.rs +++ b/examples/echo_notification.rs @@ -125,7 +125,7 @@ async fn main() { // get the first (and only) listen address for the second peer // and add it as a known address for `litep2p1` - let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); let peer = *litep2p2.local_peer_id(); litep2p1.add_known_address(peer, vec![listen_address].into_iter()); diff --git a/examples/gossiping.rs b/examples/gossiping.rs index ffd5d3f2..ca01d978 100644 --- a/examples/gossiping.rs +++ b/examples/gossiping.rs @@ -237,7 +237,7 @@ async fn main() { // establish connection to litep2p for all other litep2ps let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address.clone()].into_iter()); litep2p3.add_known_address(peer2, vec![listen_address.clone()].into_iter()); diff --git a/src/lib.rs b/src/lib.rs index 027cebd9..d28739eb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -458,8 +458,8 @@ impl Litep2p { } /// Get the list of listen addresses of the node. - pub fn listen_addresses(&self) -> Vec { - self.listen_addresses.clone() + pub fn listen_addresses(&self) -> impl Iterator { + self.listen_addresses.iter() } /// Get handle to bandwidth sink. diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index 90449b60..a7edad70 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -454,7 +454,7 @@ mod tests { assert!(litep2p1.public_addresses().add_address(multiaddr.clone()).unwrap()); // Dial `litep2p1` - litep2p2.dial_address(litep2p1_address).await.unwrap(); + litep2p2.dial_address(litep2p1_address.clone()).await.unwrap(); let expected_multiaddr = multiaddr.with(Protocol::P2p(peer1.into())); diff --git a/tests/conformance/rust/identify.rs b/tests/conformance/rust/identify.rs index 6dd21c77..c29ca882 100644 --- a/tests/conformance/rust/identify.rs +++ b/tests/conformance/rust/identify.rs @@ -119,7 +119,7 @@ async fn identify_works() { let mut libp2p = initialize_libp2p(); let (mut litep2p, _ping_event_stream, mut identify_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/rust/kademlia.rs b/tests/conformance/rust/kademlia.rs index a96bba37..a501b581 100644 --- a/tests/conformance/rust/kademlia.rs +++ b/tests/conformance/rust/kademlia.rs @@ -119,7 +119,7 @@ async fn find_node() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -223,7 +223,7 @@ async fn put_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); @@ -335,7 +335,7 @@ async fn get_record() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut kad_handle) = initialize_litep2p(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); for i in 0..addresses.len() { libp2p.dial(addresses[i].clone()).unwrap(); diff --git a/tests/conformance/rust/ping.rs b/tests/conformance/rust/ping.rs index 9192eaf2..bf398bdb 100644 --- a/tests/conformance/rust/ping.rs +++ b/tests/conformance/rust/ping.rs @@ -81,7 +81,7 @@ async fn libp2p_dials() { let mut libp2p = initialize_libp2p(); let (mut litep2p, mut ping_event_stream) = initialize_litep2p(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); diff --git a/tests/conformance/substrate/connection.rs b/tests/conformance/substrate/connection.rs index 9dba4816..fd8c28cf 100644 --- a/tests/conformance/substrate/connection.rs +++ b/tests/conformance/substrate/connection.rs @@ -110,7 +110,7 @@ async fn substrate_keep_alive_timeout() { let (mut libp2p, _peer_store_handle) = initialize_libp2p(1u32, 1u32); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_connection_open = false; diff --git a/tests/conformance/substrate/notifications.rs b/tests/conformance/substrate/notifications.rs index 6cab988e..9d5df646 100644 --- a/tests/conformance/substrate/notifications.rs +++ b/tests/conformance/substrate/notifications.rs @@ -119,7 +119,7 @@ async fn substrate_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -214,7 +214,7 @@ async fn litep2p_open_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; @@ -311,7 +311,7 @@ async fn substrate_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -360,7 +360,7 @@ async fn litep2p_reject_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); loop { @@ -412,7 +412,7 @@ async fn substrate_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_notification_count = 0; @@ -504,7 +504,7 @@ async fn litep2p_close_substream() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); let mut notif_count = 0; @@ -584,7 +584,7 @@ async fn both_nodes_open_substreams() { let libp2p_peer = *libp2p.local_peer_id(); let litep2p_peer = *litep2p.local_peer_id(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); libp2p.dial(address).unwrap(); let mut libp2p_ready = false; diff --git a/tests/conformance/substrate/request_response.rs b/tests/conformance/substrate/request_response.rs index 80a9c41b..437dd49d 100644 --- a/tests/conformance/substrate/request_response.rs +++ b/tests/conformance/substrate/request_response.rs @@ -101,7 +101,7 @@ async fn request_works() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let libp2p_peer = *libp2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -197,7 +197,7 @@ async fn substrate_reject_request() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); tokio::spawn(peer_store.run()); @@ -254,7 +254,7 @@ async fn litep2p_reject_request() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); @@ -321,7 +321,7 @@ async fn substrate_request_timeout() { let (mut libp2p, peer_store, requests) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); let libp2p_peer = *libp2p.local_peer_id(); let mut _timeout_request = None; @@ -379,7 +379,7 @@ async fn litep2p_request_timeout() { let (mut libp2p, peer_store, _) = initialize_libp2p(); let (mut litep2p, mut handle) = initialize_litep2p().await; - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); let litep2p_peer = *litep2p.local_peer_id(); let mut pending_responses = FuturesUnordered::new(); diff --git a/tests/connection/mod.rs b/tests/connection/mod.rs index b489a2f1..0d16d840 100644 --- a/tests/connection/mod.rs +++ b/tests/connection/mod.rs @@ -108,7 +108,7 @@ async fn two_litep2ps_work(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let (res1, res2) = tokio::join!(litep2p1.next_event(), litep2p2.next_event()); @@ -255,7 +255,7 @@ async fn connect_over_dns() { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let mut new_address = Multiaddr::empty(); @@ -440,7 +440,7 @@ async fn dial_self(transport: Transport) { let litep2p_config = add_transport(litep2p_config, transport).build(); let mut litep2p = Litep2p::new(litep2p_config).unwrap(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); // dial without peer id attached assert!(std::matches!( @@ -567,7 +567,7 @@ async fn keep_alive_timeout(transport1: Transport, transport2: Transport) { let config2 = add_transport(config2, transport2).build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().next().unwrap().clone(); litep2p2.dial_address(address1).await.unwrap(); let mut litep2p1_ping = false; let mut litep2p2_ping = false; @@ -626,8 +626,8 @@ async fn simultaneous_dial_tcp() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -679,8 +679,8 @@ async fn simultaneous_dial_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -732,8 +732,8 @@ async fn simultaneous_dial_ipv6_quic() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); let (res1, res2) = tokio::join!( litep2p1.dial_address(address2), @@ -791,7 +791,7 @@ async fn websocket_over_ipv6() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.dial_address(address2).await.unwrap(); let mut ping_received1 = false; @@ -843,7 +843,7 @@ async fn tcp_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -905,7 +905,7 @@ async fn websocket_dns_resolution() { .build(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); let tcp = address.iter().nth(1).unwrap(); let peer2 = *litep2p2.local_peer_id(); @@ -1040,7 +1040,7 @@ async fn multiple_listen_addresses( let (mut litep2p2, _event_stream) = make_dummy_litep2p(transport2).await; let (mut litep2p3, _event_stream) = make_dummy_litep2p(transport3).await; - let addresses = litep2p1.listen_addresses(); + let addresses: Vec<_> = litep2p1.listen_addresses().cloned().collect(); let address1 = addresses.get(0).unwrap().clone(); let address2 = addresses.get(1).unwrap().clone(); @@ -1175,7 +1175,7 @@ async fn unspecified_listen_address_tcp() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses(); + let listen_address: Vec<_> = litep2p1.listen_addresses().cloned().collect(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1276,7 +1276,7 @@ async fn unspecified_listen_address_websocket() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses(); + let listen_address: Vec<_> = litep2p1.listen_addresses().cloned().collect(); let ip4_port = listen_address.iter().find_map(|address| { let mut iter = address.iter(); @@ -1421,8 +1421,8 @@ async fn simultaneous_dial_then_redial(transport1: Transport, transport2: Transp let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - litep2p1.add_known_address(peer2, litep2p2.listen_addresses().into_iter()); - litep2p2.add_known_address(peer1, litep2p1.listen_addresses().into_iter()); + litep2p1.add_known_address(peer2, litep2p2.listen_addresses().into_iter().cloned()); + litep2p2.add_known_address(peer1, litep2p1.listen_addresses().into_iter().cloned()); let (_, _) = tokio::join!(litep2p1.dial(&peer2), litep2p2.dial(&peer1)); diff --git a/tests/custom_executor.rs b/tests/custom_executor.rs index ede32a98..171219c5 100644 --- a/tests/custom_executor.rs +++ b/tests/custom_executor.rs @@ -158,7 +158,7 @@ async fn custom_executor() { let peer2 = *litep2p2.local_peer_id(); // wait until peers have connected and spawn the litep2p objects in the background - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; diff --git a/tests/protocol/identify.rs b/tests/protocol/identify.rs index 57ec4369..efb3da28 100644 --- a/tests/protocol/identify.rs +++ b/tests/protocol/identify.rs @@ -88,8 +88,8 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address1 = litep2p1.listen_addresses().get(0).unwrap().clone(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address1 = litep2p1.listen_addresses().next().unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); tracing::info!("listen address of peer1: {address1}"); tracing::info!("listen address of peer2: {address2}"); @@ -202,7 +202,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/kademlia.rs b/tests/protocol/kademlia.rs index e9ba2ed3..893871e9 100644 --- a/tests/protocol/kademlia.rs +++ b/tests/protocol/kademlia.rs @@ -151,7 +151,10 @@ async fn records_are_stored_automatically() { let mut litep2p2 = Litep2p::new(config2).unwrap(); kad_handle1 - .add_known_peer(*litep2p2.local_peer_id(), litep2p2.listen_addresses()) + .add_known_peer( + *litep2p2.local_peer_id(), + litep2p2.listen_addresses().cloned().collect(), + ) .await; // Publish the record. @@ -229,7 +232,10 @@ async fn records_are_stored_manually() { let mut litep2p2 = Litep2p::new(config2).unwrap(); kad_handle1 - .add_known_peer(*litep2p2.local_peer_id(), litep2p2.listen_addresses()) + .add_known_peer( + *litep2p2.local_peer_id(), + litep2p2.listen_addresses().cloned().collect(), + ) .await; // Publish the record. @@ -309,7 +315,10 @@ async fn not_validated_records_are_not_stored() { let mut litep2p2 = Litep2p::new(config2).unwrap(); kad_handle1 - .add_known_peer(*litep2p2.local_peer_id(), litep2p2.listen_addresses()) + .add_known_peer( + *litep2p2.local_peer_id(), + litep2p2.listen_addresses().cloned().collect(), + ) .await; // Publish the record. @@ -410,7 +419,7 @@ async fn get_record_retrieves_remote_records() { kad_handle2 .add_known_peer( *litep2p1.local_peer_id(), - litep2p1.listen_addresses(), + litep2p1.listen_addresses().cloned().collect(), ) .await; diff --git a/tests/protocol/notification.rs b/tests/protocol/notification.rs index c8e721be..ae034d49 100644 --- a/tests/protocol/notification.rs +++ b/tests/protocol/notification.rs @@ -46,7 +46,7 @@ use std::{net::Ipv6Addr, task::Poll, time::Duration}; use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); let mut litep2p1_connected = false; @@ -2550,7 +2550,7 @@ async fn dial_peer_when_opening_substream(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address)); // add `peer2` known address for `peer1` and spawn the litep2p objects in the background @@ -2708,8 +2708,8 @@ async fn open_and_close_batched( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address3 = litep2p3.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -2913,8 +2913,8 @@ async fn open_and_close_batched_duplicate_peer( let peer2 = *litep2p2.local_peer_id(); let peer3 = *litep2p3.local_peer_id(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); - let address3 = litep2p3.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); + let address3 = litep2p3.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); litep2p1.add_known_address(peer3, std::iter::once(address3)); @@ -3150,7 +3150,7 @@ async fn no_listener_address_for_one_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address2 = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address2 = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, std::iter::once(address2)); tokio::spawn(async move { @@ -3550,7 +3550,7 @@ async fn dialing_disabled(transport1: Transport, transport2: Transport) { let mut litep2p2 = Litep2p::new(config2).unwrap(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3641,7 +3641,7 @@ async fn validation_takes_too_long(transport1: Transport, transport2: Transport) let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3748,7 +3748,7 @@ async fn ignored_validation_open_substream(transport1: Transport, transport2: Tr let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); @@ -3893,7 +3893,7 @@ async fn clogged_channel_disconnects_peer(transport1: Transport, transport2: Tra let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let listen_address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.add_known_address(peer2, vec![listen_address].into_iter()); diff --git a/tests/protocol/ping.rs b/tests/protocol/ping.rs index b74ac08e..5a6fecbc 100644 --- a/tests/protocol/ping.rs +++ b/tests/protocol/ping.rs @@ -70,7 +70,7 @@ async fn ping_supported(transport1: Transport, transport2: Transport) { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); litep2p1.dial_address(address).await.unwrap(); diff --git a/tests/protocol/request_response.rs b/tests/protocol/request_response.rs index 2afa29e3..39d7e046 100644 --- a/tests/protocol/request_response.rs +++ b/tests/protocol/request_response.rs @@ -52,7 +52,7 @@ use std::{ use crate::common::{add_transport, Transport}; async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); tracing::info!("address: {address}"); litep2p1.dial_address(address).await.unwrap(); @@ -1435,7 +1435,7 @@ async fn dial_peer_when_sending_request(transport1: Transport, transport2: Trans let peer1 = *litep2p1.local_peer_id(); let peer2 = *litep2p2.local_peer_id(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); // add known address for `peer2` and start event loop for both litep2ps litep2p1.add_known_address(peer2, std::iter::once(address)); diff --git a/tests/substream.rs b/tests/substream.rs index 0e7e376f..efcf5011 100644 --- a/tests/substream.rs +++ b/tests/substream.rs @@ -218,7 +218,7 @@ impl UserProtocol for CustomProtocol { } async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) { - let listen_address = litep2p1.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.listen_addresses().next().unwrap().clone(); litep2p2.dial_address(listen_address).await.unwrap(); let mut litep2p1_ready = false; diff --git a/tests/user_protocol.rs b/tests/user_protocol.rs index 09bc451f..afd05e5a 100644 --- a/tests/user_protocol.rs +++ b/tests/user_protocol.rs @@ -99,7 +99,7 @@ async fn user_protocol() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let peer1 = *litep2p1.local_peer_id(); - let listen_address = litep2p1.listen_addresses().get(0).unwrap().clone(); + let listen_address = litep2p1.listen_addresses().next().unwrap().clone(); let custom_protocol2 = Box::new(CustomProtocol::new()); let config2 = ConfigBuilder::new() diff --git a/tests/user_protocol_2.rs b/tests/user_protocol_2.rs index 58011ded..1c7e6910 100644 --- a/tests/user_protocol_2.rs +++ b/tests/user_protocol_2.rs @@ -122,7 +122,7 @@ async fn user_protocol_2() { let mut litep2p1 = Litep2p::new(config1).unwrap(); let mut litep2p2 = Litep2p::new(config2).unwrap(); - let address = litep2p2.listen_addresses().get(0).unwrap().clone(); + let address = litep2p2.listen_addresses().next().unwrap().clone(); sender1.send(address).await.unwrap(); diff --git a/tests/webrtc.rs b/tests/webrtc.rs index dee0e14f..fd0651f8 100644 --- a/tests/webrtc.rs +++ b/tests/webrtc.rs @@ -58,7 +58,7 @@ async fn webrtc_test() { .build(); let mut litep2p = Litep2p::new(config).unwrap(); - let address = litep2p.listen_addresses().get(0).unwrap().clone(); + let address = litep2p.listen_addresses().next().unwrap().clone(); tracing::info!("listen address: {address:?}"); From 6b7b7b1cccd27b4bdb7b8b772a9f0bc2fe535edd Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Wed, 4 Sep 2024 12:30:02 +0300 Subject: [PATCH 30/30] identify: Remove public addr from list config Signed-off-by: Alexandru Vasile --- src/protocol/libp2p/identify.rs | 20 ++++---------------- tests/conformance/rust/identify.rs | 2 +- tests/protocol/identify.rs | 17 +++++------------ 3 files changed, 10 insertions(+), 29 deletions(-) diff --git a/src/protocol/libp2p/identify.rs b/src/protocol/libp2p/identify.rs index a7edad70..184f7fb1 100644 --- a/src/protocol/libp2p/identify.rs +++ b/src/protocol/libp2p/identify.rs @@ -79,9 +79,6 @@ pub struct Config { /// Protocols supported by the local node, filled by `Litep2p`. pub(crate) protocols: Vec, - /// Public addresses. - pub(crate) public_addresses: Vec, - /// Protocol version. pub(crate) protocol_version: String, @@ -97,7 +94,6 @@ impl Config { pub fn new( protocol_version: String, user_agent: Option, - public_addresses: Vec, ) -> (Self, Box + Send + Unpin>) { let (tx_event, rx_event) = channel(DEFAULT_CHANNEL_SIZE); @@ -105,7 +101,6 @@ impl Config { Self { tx_event, public: None, - public_addresses, protocol_version, user_agent, codec: ProtocolCodec::UnsignedVarint(Some(IDENTIFY_PAYLOAD_SIZE)), @@ -182,9 +177,6 @@ pub(crate) struct Identify { /// User agent. user_agent: String, - /// User provided list of addresses. - addresses: HashSet>, - /// Protocols supported by the local node, filled by `Litep2p`. protocols: Vec, @@ -205,7 +197,6 @@ impl Identify { service, tx: config.tx_event, peers: HashMap::new(), - addresses: config.public_addresses.into_iter().map(|addr| addr.to_vec()).collect(), public: config.public.expect("public key to be supplied"), protocol_version: config.protocol_version, user_agent: config.user_agent.unwrap_or(DEFAULT_AGENT.to_string()), @@ -261,8 +252,8 @@ impl Identify { } }; - let mut listen_addr: HashSet<_> = self.addresses.clone(); - listen_addr.extend(self.service.listen_addresses().into_iter().map(|addr| addr.to_vec())); + let mut listen_addr: HashSet<_> = + self.service.listen_addresses().into_iter().map(|addr| addr.to_vec()).collect(); listen_addr .extend(self.service.public_addresses().inner.read().iter().map(|addr| addr.to_vec())); @@ -422,11 +413,8 @@ mod tests { Box + Send + Unpin>, PeerId, ) { - let (identify_config, identify) = Config::new( - "1.0.0".to_string(), - Some("litep2p/1.0.0".to_string()), - vec![Multiaddr::empty()], - ); + let (identify_config, identify) = + Config::new("1.0.0".to_string(), Some("litep2p/1.0.0".to_string())); let keypair = crate::crypto::ed25519::Keypair::generate(); let peer = PeerId::from_public_key(&crate::crypto::PublicKey::Ed25519(keypair.public())); diff --git a/tests/conformance/rust/identify.rs b/tests/conformance/rust/identify.rs index c29ca882..24af7e19 100644 --- a/tests/conformance/rust/identify.rs +++ b/tests/conformance/rust/identify.rs @@ -72,7 +72,7 @@ fn initialize_litep2p() -> ( let keypair = Keypair::generate(); let (ping_config, ping_event_stream) = PingConfig::default(); let (identify_config, identify_event_stream) = - IdentifyConfig::new("proto v1".to_string(), None, Vec::new()); + IdentifyConfig::new("proto v1".to_string(), None); let litep2p = Litep2p::new( ConfigBuilder::new() diff --git a/tests/protocol/identify.rs b/tests/protocol/identify.rs index efb3da28..a4ed3b7a 100644 --- a/tests/protocol/identify.rs +++ b/tests/protocol/identify.rs @@ -65,21 +65,15 @@ async fn identify_supported(transport1: Transport, transport2: Transport) { .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .try_init(); - let (identify_config1, mut identify_event_stream1) = Config::new( - "/proto/1".to_string(), - Some("agent v1".to_string()), - Vec::new(), - ); + let (identify_config1, mut identify_event_stream1) = + Config::new("/proto/1".to_string(), Some("agent v1".to_string())); let config_builder1 = ConfigBuilder::new() .with_keypair(Keypair::generate()) .with_libp2p_identify(identify_config1); let config1 = add_transport(config_builder1, transport1).build(); - let (identify_config2, mut identify_event_stream2) = Config::new( - "/proto/2".to_string(), - Some("agent v2".to_string()), - Vec::new(), - ); + let (identify_config2, mut identify_event_stream2) = + Config::new("/proto/2".to_string(), Some("agent v2".to_string())); let config_builder2 = ConfigBuilder::new() .with_keypair(Keypair::generate()) .with_libp2p_identify(identify_config2); @@ -193,8 +187,7 @@ async fn identify_not_supported(transport1: Transport, transport2: Transport) { .with_libp2p_ping(ping_config); let config1 = add_transport(config_builder1, transport1).build(); - let (identify_config2, mut identify_event_stream2) = - Config::new("litep2p".to_string(), None, Vec::new()); + let (identify_config2, mut identify_event_stream2) = Config::new("litep2p".to_string(), None); let config_builder2 = ConfigBuilder::new() .with_keypair(Keypair::generate()) .with_libp2p_identify(identify_config2);