From 14b1eda2e90aeb79f5267714fda737df9283a8be Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Fri, 5 May 2023 14:22:05 +0200 Subject: [PATCH 1/2] Remove deprecated connection limits --- misc/metrics/src/swarm.rs | 10 -- protocols/kad/src/behaviour.rs | 2 - swarm/CHANGELOG.md | 2 + swarm/src/connection.rs | 25 --- swarm/src/connection/error.rs | 21 --- swarm/src/connection/pool.rs | 211 +++--------------------- swarm/src/lib.rs | 284 +++------------------------------ 7 files changed, 45 insertions(+), 510 deletions(-) diff --git a/misc/metrics/src/swarm.rs b/misc/metrics/src/swarm.rs index d04fd028a00..dcf055a6e60 100644 --- a/misc/metrics/src/swarm.rs +++ b/misc/metrics/src/swarm.rs @@ -225,10 +225,6 @@ impl super::Recorder record(OutgoingConnectionError::Banned), - #[allow(deprecated)] - libp2p_swarm::DialError::ConnectionLimit(_) => { - record(OutgoingConnectionError::ConnectionLimit) - } libp2p_swarm::DialError::LocalPeerId { .. } => { record(OutgoingConnectionError::LocalPeerId) } @@ -340,7 +336,6 @@ enum PeerStatus { #[derive(EncodeLabelValue, Hash, Clone, Eq, PartialEq, Debug)] enum OutgoingConnectionError { Banned, - ConnectionLimit, LocalPeerId, NoAddresses, DialPeerConditionFalse, @@ -365,7 +360,6 @@ enum IncomingConnectionError { TransportErrorMultiaddrNotSupported, TransportErrorOther, Aborted, - ConnectionLimit, Denied, } @@ -373,10 +367,6 @@ impl From<&libp2p_swarm::ListenError> for IncomingConnectionError { fn from(error: &libp2p_swarm::ListenError) -> Self { match error { libp2p_swarm::ListenError::WrongPeerId { .. } => IncomingConnectionError::WrongPeerId, - #[allow(deprecated)] - libp2p_swarm::ListenError::ConnectionLimit(_) => { - IncomingConnectionError::ConnectionLimit - } libp2p_swarm::ListenError::LocalPeerId { .. } => IncomingConnectionError::LocalPeerId, libp2p_swarm::ListenError::Transport( libp2p_core::transport::TransportError::MultiaddrNotSupported(_), diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index ed161d7a6ce..f264bd2e5b8 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -1933,8 +1933,6 @@ where DialError::DialPeerConditionFalse(dial_opts::PeerCondition::Always) => { unreachable!("DialPeerCondition::Always can not trigger DialPeerConditionFalse."); } - #[allow(deprecated)] - DialError::ConnectionLimit(_) => {} } } diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 365c0e771c2..57efb92b05b 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -10,6 +10,8 @@ - Return a bool from `ExternalAddresses::on_swarm_event` and `ListenAddresses::on_swarm_event` indicating whether any state was changed. See [PR 3865]. +- Remove deprecated `ConnectionLimits`. + [PR 3715]: https://github.com/libp2p/rust-libp2p/pull/3715 [PR 3746]: https://github.com/libp2p/rust-libp2p/pull/3746 [PR 3865]: https://github.com/libp2p/rust-libp2p/pull/3865 diff --git a/swarm/src/connection.rs b/swarm/src/connection.rs index e813ad0c66d..f016f443825 100644 --- a/swarm/src/connection.rs +++ b/swarm/src/connection.rs @@ -386,31 +386,6 @@ impl<'a> IncomingInfo<'a> { } } -/// Information about a connection limit. -#[deprecated(note = "Use `libp2p::connection_limits` instead.", since = "0.42.1")] -#[derive(Debug, Clone, Copy)] -pub struct ConnectionLimit { - /// The maximum number of connections. - pub limit: u32, - /// The current number of connections. - pub current: u32, -} - -#[allow(deprecated)] -impl fmt::Display for ConnectionLimit { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "connection limit exceeded ({}/{})", - self.current, self.limit - ) - } -} - -/// A `ConnectionLimit` can represent an error if it has been exceeded. -#[allow(deprecated)] -impl std::error::Error for ConnectionLimit {} - struct SubstreamUpgrade { user_data: Option, timeout: Delay, diff --git a/swarm/src/connection/error.rs b/swarm/src/connection/error.rs index 9e0c58a4e7d..5d5dda57868 100644 --- a/swarm/src/connection/error.rs +++ b/swarm/src/connection/error.rs @@ -18,8 +18,6 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -#[allow(deprecated)] -use crate::connection::ConnectionLimit; use crate::transport::TransportError; use crate::Multiaddr; use crate::{ConnectedPoint, PeerId}; @@ -90,15 +88,6 @@ pub enum PendingConnectionError { /// An error occurred while negotiating the transport protocol(s) on a connection. Transport(TTransErr), - /// The connection was dropped because the connection limit - /// for a peer has been reached. - #[deprecated( - note = "Use `libp2p::connection_limits` instead and handle `{Dial,Listen}Error::Denied::cause`.", - since = "0.42.1" - )] - #[allow(deprecated)] - ConnectionLimit(ConnectionLimit), - /// Pending connection attempt has been aborted. Aborted, @@ -117,10 +106,6 @@ impl PendingConnectionError { pub fn map(self, f: impl FnOnce(T) -> U) -> PendingConnectionError { match self { PendingConnectionError::Transport(t) => PendingConnectionError::Transport(f(t)), - #[allow(deprecated)] - PendingConnectionError::ConnectionLimit(l) => { - PendingConnectionError::ConnectionLimit(l) - } PendingConnectionError::Aborted => PendingConnectionError::Aborted, PendingConnectionError::WrongPeerId { obtained, endpoint } => { PendingConnectionError::WrongPeerId { obtained, endpoint } @@ -145,10 +130,6 @@ where "Pending connection: Transport error on connection: {err}" ) } - #[allow(deprecated)] - PendingConnectionError::ConnectionLimit(l) => { - write!(f, "Connection error: Connection limit: {l}.") - } PendingConnectionError::WrongPeerId { obtained, endpoint } => { write!( f, @@ -172,8 +153,6 @@ where PendingConnectionError::WrongPeerId { .. } => None, PendingConnectionError::LocalPeerId { .. } => None, PendingConnectionError::Aborted => None, - #[allow(deprecated)] - PendingConnectionError::ConnectionLimit(..) => None, } } } diff --git a/swarm/src/connection/pool.rs b/swarm/src/connection/pool.rs index 68ad16ad36a..fbfc3424dd3 100644 --- a/swarm/src/connection/pool.rs +++ b/swarm/src/connection/pool.rs @@ -18,8 +18,7 @@ // 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. -#[allow(deprecated)] -use crate::connection::{Connection, ConnectionId, ConnectionLimit, PendingPoint}; +use crate::connection::{Connection, ConnectionId, PendingPoint}; #[allow(deprecated)] use crate::IntoConnectionHandler; use crate::{ @@ -46,7 +45,6 @@ use libp2p_core::muxing::{StreamMuxerBox, StreamMuxerExt}; use std::task::Waker; use std::{ collections::{hash_map, HashMap}, - convert::TryFrom as _, fmt, num::{NonZeroU8, NonZeroUsize}, pin::Pin, @@ -308,8 +306,7 @@ where THandler: ConnectionHandler, { /// Creates a new empty `Pool`. - #[allow(deprecated)] - pub(crate) fn new(local_id: PeerId, config: PoolConfig, limits: ConnectionLimits) -> Self { + pub(crate) fn new(local_id: PeerId, config: PoolConfig) -> Self { let (pending_connection_events_tx, pending_connection_events_rx) = mpsc::channel(0); let executor = match config.executor { Some(exec) => ExecSwitch::Executor(exec), @@ -317,7 +314,7 @@ where }; Pool { local_id, - counters: ConnectionCounters::new(limits), + counters: ConnectionCounters::new(), established: Default::default(), pending: Default::default(), task_command_buffer_size: config.task_command_buffer_size, @@ -409,9 +406,6 @@ where /// Adds a pending outgoing connection to the pool in the form of a `Future` /// that establishes and negotiates the connection. - /// - /// Returns an error if the limit of pending outgoing connections - /// has been reached. #[allow(deprecated)] pub(crate) fn add_outgoing( &mut self, @@ -428,9 +422,7 @@ where role_override: Endpoint, dial_concurrency_factor_override: Option, connection_id: ConnectionId, - ) -> Result<(), ConnectionLimit> { - self.counters.check_max_pending_outgoing()?; - + ) { let dial = ConcurrentDial::new( dials, dial_concurrency_factor_override.unwrap_or(self.dial_concurrency_factor), @@ -458,29 +450,20 @@ where accepted_at: Instant::now(), }, ); - - Ok(()) } /// Adds a pending incoming connection to the pool in the form of a /// `Future` that establishes and negotiates the connection. - /// - /// Returns an error if the limit of pending incoming connections - /// has been reached. - #[allow(deprecated)] pub(crate) fn add_incoming( &mut self, future: TFut, info: IncomingInfo<'_>, connection_id: ConnectionId, - ) -> Result<(), ConnectionLimit> - where + ) where TFut: Future> + Send + 'static, { let endpoint = info.create_connected_point(); - self.counters.check_max_pending_incoming()?; - let (abort_notifier, abort_receiver) = oneshot::channel(); self.executor @@ -501,8 +484,6 @@ where accepted_at: Instant::now(), }, ); - - Ok(()) } #[allow(deprecated)] @@ -686,49 +667,26 @@ where ), }; - #[allow(deprecated)] - // Remove once `PendingConnectionError::ConnectionLimit` is gone. - let error = self - .counters - // Check general established connection limit. - .check_max_established(&endpoint) - .map_err(PendingConnectionError::ConnectionLimit) - // Check per-peer established connection limit. - .and_then(|()| { - self.counters - .check_max_established_per_peer(num_peer_established( - &self.established, - obtained_peer_id, - )) - .map_err(PendingConnectionError::ConnectionLimit) - }) - // Check expected peer id matches. - .and_then(|()| { - if let Some(peer) = expected_peer_id { - if peer != obtained_peer_id { - Err(PendingConnectionError::WrongPeerId { - obtained: obtained_peer_id, - endpoint: endpoint.clone(), - }) - } else { - Ok(()) - } - } else { - Ok(()) - } - }) - // Check peer is not local peer. - .and_then(|()| { - if self.local_id == obtained_peer_id { - Err(PendingConnectionError::LocalPeerId { + let check_peer_id = || { + if let Some(peer) = expected_peer_id { + if peer != obtained_peer_id { + return Err(PendingConnectionError::WrongPeerId { + obtained: obtained_peer_id, endpoint: endpoint.clone(), - }) - } else { - Ok(()) + }); } - }); + } + + if self.local_id == obtained_peer_id { + return Err(PendingConnectionError::LocalPeerId { + endpoint: endpoint.clone(), + }); + } - if let Err(error) = error { + Ok(()) + }; + + if let Err(error) = check_peer_id() { self.executor.spawn(poll_fn(move |cx| { if let Err(e) = ready!(muxer.poll_close_unpin(cx)) { log::debug!( @@ -873,9 +831,6 @@ impl Drop for NewConnection { /// Network connection information. #[derive(Debug, Clone)] pub struct ConnectionCounters { - /// The effective connection limits. - #[allow(deprecated)] - limits: ConnectionLimits, /// The current number of incoming connections. pending_incoming: u32, /// The current number of outgoing connections. @@ -887,10 +842,8 @@ pub struct ConnectionCounters { } impl ConnectionCounters { - #[allow(deprecated)] - fn new(limits: ConnectionLimits) -> Self { + fn new() -> Self { Self { - limits, pending_incoming: 0, pending_outgoing: 0, established_incoming: 0, @@ -898,13 +851,6 @@ impl ConnectionCounters { } } - /// The effective connection limits. - #[deprecated(note = "Use the `libp2p::connection_limits` instead.")] - #[allow(deprecated)] - pub fn limits(&self) -> &ConnectionLimits { - &self.limits - } - /// The total number of connections, both pending and established. pub fn num_connections(&self) -> u32 { self.num_pending() + self.num_established() @@ -987,117 +933,6 @@ impl ConnectionCounters { } } } - - #[allow(deprecated)] - fn check_max_pending_outgoing(&self) -> Result<(), ConnectionLimit> { - Self::check(self.pending_outgoing, self.limits.max_pending_outgoing) - } - - #[allow(deprecated)] - fn check_max_pending_incoming(&self) -> Result<(), ConnectionLimit> { - Self::check(self.pending_incoming, self.limits.max_pending_incoming) - } - - #[allow(deprecated)] - fn check_max_established(&self, endpoint: &ConnectedPoint) -> Result<(), ConnectionLimit> { - // Check total connection limit. - Self::check(self.num_established(), self.limits.max_established_total)?; - // Check incoming/outgoing connection limits - match endpoint { - ConnectedPoint::Dialer { .. } => Self::check( - self.established_outgoing, - self.limits.max_established_outgoing, - ), - ConnectedPoint::Listener { .. } => Self::check( - self.established_incoming, - self.limits.max_established_incoming, - ), - } - } - - #[allow(deprecated)] - fn check_max_established_per_peer(&self, current: u32) -> Result<(), ConnectionLimit> { - Self::check(current, self.limits.max_established_per_peer) - } - - #[allow(deprecated)] - fn check(current: u32, limit: Option) -> Result<(), ConnectionLimit> { - if let Some(limit) = limit { - if current >= limit { - return Err(ConnectionLimit { limit, current }); - } - } - Ok(()) - } -} - -/// Counts the number of established connections to the given peer. -fn num_peer_established( - established: &FnvHashMap>>, - peer: PeerId, -) -> u32 { - established.get(&peer).map_or(0, |conns| { - u32::try_from(conns.len()).expect("Unexpectedly large number of connections for a peer.") - }) -} - -/// The configurable connection limits. -/// -/// By default no connection limits apply. -#[derive(Debug, Clone, Default)] -#[deprecated(note = "Use `libp2p::connection_limits` instead.", since = "0.42.1")] -pub struct ConnectionLimits { - max_pending_incoming: Option, - max_pending_outgoing: Option, - max_established_incoming: Option, - max_established_outgoing: Option, - max_established_per_peer: Option, - max_established_total: Option, -} - -#[allow(deprecated)] -impl ConnectionLimits { - /// Configures the maximum number of concurrently incoming connections being established. - pub fn with_max_pending_incoming(mut self, limit: Option) -> Self { - self.max_pending_incoming = limit; - self - } - - /// Configures the maximum number of concurrently outgoing connections being established. - pub fn with_max_pending_outgoing(mut self, limit: Option) -> Self { - self.max_pending_outgoing = limit; - self - } - - /// Configures the maximum number of concurrent established inbound connections. - pub fn with_max_established_incoming(mut self, limit: Option) -> Self { - self.max_established_incoming = limit; - self - } - - /// Configures the maximum number of concurrent established outbound connections. - pub fn with_max_established_outgoing(mut self, limit: Option) -> Self { - self.max_established_outgoing = limit; - self - } - - /// Configures the maximum number of concurrent established connections (both - /// inbound and outbound). - /// - /// Note: This should be used in conjunction with - /// [`ConnectionLimits::with_max_established_incoming`] to prevent possible - /// eclipse attacks (all connections being inbound). - pub fn with_max_established(mut self, limit: Option) -> Self { - self.max_established_total = limit; - self - } - - /// Configures the maximum number of concurrent established connections per peer, - /// regardless of direction (incoming or outgoing). - pub fn with_max_established_per_peer(mut self, limit: Option) -> Self { - self.max_established_per_peer = limit; - self - } } /// Configuration options when creating a [`Pool`]. diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 9c87389334e..30371994a65 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -107,8 +107,6 @@ pub mod derive_prelude { pub use libp2p_identity::PeerId; } -#[allow(deprecated)] -pub use crate::connection::ConnectionLimit; #[allow(deprecated)] pub use behaviour::NetworkBehaviourAction; pub use behaviour::{ @@ -117,8 +115,7 @@ pub use behaviour::{ ListenerClosed, ListenerError, NetworkBehaviour, NewExternalAddr, NewListenAddr, NotifyHandler, PollParameters, ToSwarm, }; -#[allow(deprecated)] -pub use connection::pool::{ConnectionCounters, ConnectionLimits}; +pub use connection::pool::ConnectionCounters; pub use connection::{ConnectionError, ConnectionId}; pub use executor::Executor; #[allow(deprecated)] @@ -653,27 +650,15 @@ where }) .collect(); - match self.pool.add_outgoing( + self.pool.add_outgoing( dials, peer_id, dial_opts.role_override(), dial_opts.dial_concurrency_override(), connection_id, - ) { - Ok(()) => Ok(()), - Err(connection_limit) => { - #[allow(deprecated)] - let error = DialError::ConnectionLimit(connection_limit); - self.behaviour - .on_swarm_event(FromSwarm::DialFailure(DialFailure { - peer_id, - error: &error, - connection_id, - })); + ); - Err(error) - } - } + Ok(()) } /// Returns an iterator that produces the list of addresses we're listening on. @@ -1089,33 +1074,19 @@ where } } - match self.pool.add_incoming( + self.pool.add_incoming( upgrade, IncomingInfo { local_addr: &local_addr, send_back_addr: &send_back_addr, }, connection_id, - ) { - Ok(()) => { - return Some(SwarmEvent::IncomingConnection { - local_addr, - send_back_addr, - }); - } - Err(connection_limit) => { - #[allow(deprecated)] - let error = ListenError::ConnectionLimit(connection_limit); - self.behaviour - .on_swarm_event(FromSwarm::ListenFailure(ListenFailure { - local_addr: &local_addr, - send_back_addr: &send_back_addr, - error: &error, - connection_id, - })); - log::debug!("Incoming connection rejected: {:?}", connection_limit); - } - }; + ); + + Some(SwarmEvent::IncomingConnection { + local_addr, + send_back_addr, + }) } TransportEvent::NewAddress { listener_id, @@ -1131,10 +1102,10 @@ where listener_id, addr: &listen_addr, })); - return Some(SwarmEvent::NewListenAddr { + Some(SwarmEvent::NewListenAddr { listener_id, address: listen_addr, - }); + }) } TransportEvent::AddressExpired { listener_id, @@ -1153,10 +1124,10 @@ where listener_id, addr: &listen_addr, })); - return Some(SwarmEvent::ExpiredListenAddr { + Some(SwarmEvent::ExpiredListenAddr { listener_id, address: listen_addr, - }); + }) } TransportEvent::ListenerClosed { listener_id, @@ -1174,11 +1145,11 @@ where listener_id, reason: reason.as_ref().copied(), })); - return Some(SwarmEvent::ListenerClosed { + Some(SwarmEvent::ListenerClosed { listener_id, addresses: addrs.to_vec(), reason, - }); + }) } TransportEvent::ListenerError { listener_id, error } => { self.behaviour @@ -1186,10 +1157,9 @@ where listener_id, err: &error, })); - return Some(SwarmEvent::ListenerError { listener_id, error }); + Some(SwarmEvent::ListenerError { listener_id, error }) } } - None } fn handle_behaviour_event( @@ -1525,8 +1495,6 @@ pub struct SwarmBuilder { transport: transport::Boxed<(PeerId, StreamMuxerBox)>, behaviour: TBehaviour, pool_config: PoolConfig, - #[allow(deprecated)] - connection_limits: ConnectionLimits, } impl SwarmBuilder @@ -1547,7 +1515,6 @@ where transport, behaviour, pool_config: PoolConfig::new(Some(Box::new(executor))), - connection_limits: Default::default(), } } @@ -1629,7 +1596,6 @@ where transport, behaviour, pool_config: PoolConfig::new(None), - connection_limits: Default::default(), } } @@ -1669,13 +1635,6 @@ where self } - /// Configures the connection limits. - #[allow(deprecated)] - pub fn connection_limits(mut self, limits: ConnectionLimits) -> Self { - self.connection_limits = limits; - self - } - /// Configures an override for the substream upgrade protocol to use. /// /// The subtream upgrade protocol is the multistream-select protocol @@ -1710,7 +1669,7 @@ where Swarm { local_peer_id: self.local_peer_id, transport: self.transport, - pool: Pool::new(self.local_peer_id, self.pool_config, self.connection_limits), + pool: Pool::new(self.local_peer_id, self.pool_config), behaviour: self.behaviour, supported_protocols: Default::default(), listened_addrs: HashMap::new(), @@ -1727,14 +1686,6 @@ pub enum DialError { /// The peer is currently banned. #[deprecated(note = "Use `libp2p::allow_block_list` instead.", since = "0.42.1")] Banned, - /// The configured limit for simultaneous outgoing connections - /// has been reached. - #[deprecated( - note = "Use `libp2p::connection_limits` instead and handle `{Dial,Listen}Error::Denied::cause`.", - since = "0.42.1" - )] - #[allow(deprecated)] - ConnectionLimit(ConnectionLimit), /// The peer identity obtained on the connection matches the local peer. LocalPeerId { endpoint: ConnectedPoint, @@ -1764,8 +1715,6 @@ pub enum DialError { impl From for DialError { fn from(error: PendingOutboundConnectionError) -> Self { match error { - #[allow(deprecated)] - PendingConnectionError::ConnectionLimit(limit) => DialError::ConnectionLimit(limit), PendingConnectionError::Aborted => DialError::Aborted, PendingConnectionError::WrongPeerId { obtained, endpoint } => { DialError::WrongPeerId { obtained, endpoint } @@ -1779,8 +1728,6 @@ impl From for DialError { impl fmt::Display for DialError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - #[allow(deprecated)] - DialError::ConnectionLimit(err) => write!(f, "Dial error: {err}"), DialError::NoAddresses => write!(f, "Dial error: no addresses for peer."), DialError::LocalPeerId { endpoint } => write!( f, @@ -1834,8 +1781,6 @@ fn print_error_chain(f: &mut fmt::Formatter<'_>, e: &dyn error::Error) -> fmt::R impl error::Error for DialError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { - #[allow(deprecated)] - DialError::ConnectionLimit(err) => Some(err), DialError::LocalPeerId { .. } => None, DialError::NoAddresses => None, #[allow(deprecated)] @@ -1853,14 +1798,6 @@ impl error::Error for DialError { /// Possible errors when upgrading an inbound connection. #[derive(Debug)] pub enum ListenError { - /// The configured limit for simultaneous outgoing connections - /// has been reached. - #[deprecated( - note = "Use `libp2p::connection_limits` instead and handle `{Dial,Listen}Error::Denied::cause`.", - since = "0.42.1" - )] - #[allow(deprecated)] - ConnectionLimit(ConnectionLimit), /// Pending connection attempt has been aborted. Aborted, /// The peer identity obtained on the connection did not match the one that was expected. @@ -1883,10 +1820,6 @@ impl From for ListenError { fn from(error: PendingInboundConnectionError) -> Self { match error { PendingInboundConnectionError::Transport(inner) => ListenError::Transport(inner), - #[allow(deprecated)] - PendingInboundConnectionError::ConnectionLimit(inner) => { - ListenError::ConnectionLimit(inner) - } PendingInboundConnectionError::Aborted => ListenError::Aborted, PendingInboundConnectionError::WrongPeerId { obtained, endpoint } => { ListenError::WrongPeerId { obtained, endpoint } @@ -1901,8 +1834,6 @@ impl From for ListenError { impl fmt::Display for ListenError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - #[allow(deprecated)] - ListenError::ConnectionLimit(_) => write!(f, "Listen error"), ListenError::Aborted => write!( f, "Listen error: Pending connection attempt has been aborted." @@ -1927,8 +1858,6 @@ impl fmt::Display for ListenError { impl error::Error for ListenError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { - #[allow(deprecated)] - ListenError::ConnectionLimit(err) => Some(err), ListenError::WrongPeerId { .. } => None, ListenError::Transport(err) => Some(err), ListenError::Aborted => None, @@ -2034,8 +1963,7 @@ mod tests { use either::Either; use futures::executor::block_on; use futures::executor::ThreadPool; - use futures::future::poll_fn; - use futures::{executor, future, ready}; + use futures::{executor, future}; use libp2p_core::multiaddr::multiaddr; use libp2p_core::transport::memory::MemoryTransportError; use libp2p_core::transport::TransportEvent; @@ -2538,178 +2466,6 @@ mod tests { QuickCheck::new().tests(10).quickcheck(prop as fn(_) -> _); } - #[test] - #[allow(deprecated)] - fn max_outgoing() { - use rand::Rng; - - let outgoing_limit = rand::thread_rng().gen_range(1..10); - - let limits = ConnectionLimits::default().with_max_pending_outgoing(Some(outgoing_limit)); - let mut network = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler) - .connection_limits(limits) - .build(); - - let addr: Multiaddr = "/memory/1234".parse().unwrap(); - - let target = PeerId::random(); - for _ in 0..outgoing_limit { - network - .dial( - DialOpts::peer_id(target) - .addresses(vec![addr.clone()]) - .build(), - ) - .expect("Unexpected connection limit."); - } - - match network - .dial(DialOpts::peer_id(target).addresses(vec![addr]).build()) - .expect_err("Unexpected dialing success.") - { - #[allow(deprecated)] - DialError::ConnectionLimit(limit) => { - assert_eq!(limit.current, outgoing_limit); - assert_eq!(limit.limit, outgoing_limit); - } - e => panic!("Unexpected error: {e:?}"), - } - - let info = network.network_info(); - assert_eq!(info.num_peers(), 0); - assert_eq!( - info.connection_counters().num_pending_outgoing(), - outgoing_limit - ); - } - - #[test] - fn max_established_incoming() { - #[derive(Debug, Clone)] - struct Limit(u32); - - impl Arbitrary for Limit { - fn arbitrary(g: &mut Gen) -> Self { - Self(g.gen_range(1..10)) - } - } - - #[allow(deprecated)] - fn limits(limit: u32) -> ConnectionLimits { - ConnectionLimits::default().with_max_established_incoming(Some(limit)) - } - - fn prop(limit: Limit) { - let limit = limit.0; - - #[allow(deprecated)] - let mut network1 = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler) - .connection_limits(limits(limit)) - .build(); - #[allow(deprecated)] - let mut network2 = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler) - .connection_limits(limits(limit)) - .build(); - - let _ = network1.listen_on(multiaddr![Memory(0u64)]).unwrap(); - let listen_addr = async_std::task::block_on(poll_fn(|cx| { - match ready!(network1.poll_next_unpin(cx)).unwrap() { - SwarmEvent::NewListenAddr { address, .. } => Poll::Ready(address), - e => panic!("Unexpected network event: {e:?}"), - } - })); - - // Spawn and block on the dialer. - async_std::task::block_on({ - let mut n = 0; - network2.dial(listen_addr.clone()).unwrap(); - - let mut expected_closed = false; - let mut network_1_established = false; - let mut network_2_established = false; - let mut network_1_limit_reached = false; - let mut network_2_limit_reached = false; - poll_fn(move |cx| { - loop { - let mut network_1_pending = false; - let mut network_2_pending = false; - - match network1.poll_next_unpin(cx) { - Poll::Ready(Some(SwarmEvent::IncomingConnection { .. })) => {} - Poll::Ready(Some(SwarmEvent::ConnectionEstablished { .. })) => { - network_1_established = true; - } - #[allow(deprecated)] - Poll::Ready(Some(SwarmEvent::IncomingConnectionError { - error: ListenError::ConnectionLimit(err), - .. - })) => { - assert_eq!(err.limit, limit); - assert_eq!(err.limit, err.current); - let info = network1.network_info(); - let counters = info.connection_counters(); - assert_eq!(counters.num_established_incoming(), limit); - assert_eq!(counters.num_established(), limit); - network_1_limit_reached = true; - } - Poll::Pending => { - network_1_pending = true; - } - e => panic!("Unexpected network event: {e:?}"), - } - - match network2.poll_next_unpin(cx) { - Poll::Ready(Some(SwarmEvent::ConnectionEstablished { .. })) => { - network_2_established = true; - } - Poll::Ready(Some(SwarmEvent::ConnectionClosed { .. })) => { - assert!(expected_closed); - let info = network2.network_info(); - let counters = info.connection_counters(); - assert_eq!(counters.num_established_outgoing(), limit); - assert_eq!(counters.num_established(), limit); - network_2_limit_reached = true; - } - Poll::Pending => { - network_2_pending = true; - } - e => panic!("Unexpected network event: {e:?}"), - } - - if network_1_pending && network_2_pending { - return Poll::Pending; - } - - if network_1_established && network_2_established { - network_1_established = false; - network_2_established = false; - - if n <= limit { - // Dial again until the limit is exceeded. - n += 1; - network2.dial(listen_addr.clone()).unwrap(); - - if n == limit { - // The the next dialing attempt exceeds the limit, this - // is the connection we expected to get closed. - expected_closed = true; - } - } else { - panic!("Expect networks not to establish connections beyond the limit.") - } - } - - if network_1_limit_reached && network_2_limit_reached { - return Poll::Ready(()); - } - } - }) - }); - } - - quickcheck(prop as fn(_)); - } - #[test] fn invalid_peer_id() { // Checks whether dialing an address containing the wrong peer id raises an error From c98f9879a380995b2b25576c7b46136091b10002 Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Fri, 5 May 2023 22:28:51 +1000 Subject: [PATCH 2/2] Update swarm/CHANGELOG.md --- swarm/CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 57efb92b05b..70b1bb8de0d 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -11,10 +11,13 @@ See [PR 3865]. - Remove deprecated `ConnectionLimits`. + Users should migrate to `libp2p::connection_limits::Behaviour`. + See [PR 3885]. [PR 3715]: https://github.com/libp2p/rust-libp2p/pull/3715 [PR 3746]: https://github.com/libp2p/rust-libp2p/pull/3746 [PR 3865]: https://github.com/libp2p/rust-libp2p/pull/3865 +[PR 3885]: https://github.com/libp2p/rust-libp2p/pull/3885 ## 0.42.2