snarkos_node_tcp/
tcp.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::{
17    collections::HashSet,
18    fmt,
19    io,
20    net::{IpAddr, SocketAddr},
21    ops::Deref,
22    sync::{
23        Arc,
24        atomic::{AtomicUsize, Ordering::*},
25    },
26    time::{Duration, Instant},
27};
28
29#[cfg(feature = "locktick")]
30use locktick::parking_lot::Mutex;
31use once_cell::sync::OnceCell;
32#[cfg(not(feature = "locktick"))]
33use parking_lot::Mutex;
34use tokio::{
35    io::split,
36    net::{TcpListener, TcpStream},
37    sync::oneshot,
38    task::JoinHandle,
39    time::timeout,
40};
41use tracing::*;
42
43use crate::{
44    BannedPeers,
45    Config,
46    KnownPeers,
47    Stats,
48    connections::{Connection, ConnectionSide, Connections},
49    protocols::{Protocol, Protocols},
50};
51
52// A sequential numeric identifier assigned to `Tcp`s that were not provided with a name.
53static SEQUENTIAL_NODE_ID: AtomicUsize = AtomicUsize::new(0);
54
55/// The central object responsible for handling connections.
56#[derive(Clone)]
57pub struct Tcp(Arc<InnerTcp>);
58
59impl Deref for Tcp {
60    type Target = Arc<InnerTcp>;
61
62    fn deref(&self) -> &Self::Target {
63        &self.0
64    }
65}
66
67/// Error types for the `Tcp::connect` function.
68#[allow(missing_docs)]
69#[derive(thiserror::Error, Debug)]
70pub enum ConnectError {
71    #[error("already reached the maximum number of {limit} connections")]
72    MaximumConnectionsReached { limit: u16 },
73    #[error("already connecting to node at {address:?}")]
74    AlreadyConnecting { address: SocketAddr },
75    #[error("already connected to node at {address:?}")]
76    AlreadyConnected { address: SocketAddr },
77    #[error("attempt to self-connect (at address {address:?}")]
78    SelfConnect { address: SocketAddr },
79    #[error("I/O error: {0}")]
80    IoError(std::io::Error),
81}
82
83impl From<std::io::Error> for ConnectError {
84    fn from(inner: std::io::Error) -> Self {
85        Self::IoError(inner)
86    }
87}
88
89#[doc(hidden)]
90pub struct InnerTcp {
91    /// The tracing span.
92    span: Span,
93    /// The node's configuration.
94    config: Config,
95    /// The node's listening address.
96    listening_addr: OnceCell<SocketAddr>,
97    /// Contains objects used by the protocols implemented by the node.
98    pub(crate) protocols: Protocols,
99    /// A set of connections that have not been finalized yet.
100    connecting: Mutex<HashSet<SocketAddr>>,
101    /// Contains objects related to the node's active connections.
102    connections: Connections,
103    /// Collects statistics related to the node's peers.
104    known_peers: KnownPeers,
105    /// Contains the set of currently banned peers.
106    banned_peers: BannedPeers,
107    /// Collects statistics related to the node itself.
108    stats: Stats,
109    /// The node's tasks.
110    pub(crate) tasks: Mutex<Vec<JoinHandle<()>>>,
111}
112
113impl Tcp {
114    /// Creates a new [`Tcp`] using the given [`Config`].
115    pub fn new(mut config: Config) -> Self {
116        // If there is no pre-configured name, assign a sequential numeric identifier.
117        if config.name.is_none() {
118            config.name = Some(SEQUENTIAL_NODE_ID.fetch_add(1, Relaxed).to_string());
119        }
120
121        // Create a tracing span containing the node's name.
122        let span = crate::helpers::create_span(config.name.as_deref().unwrap());
123
124        // Initialize the Tcp stack.
125        let tcp = Tcp(Arc::new(InnerTcp {
126            span,
127            config,
128            listening_addr: Default::default(),
129            protocols: Default::default(),
130            connecting: Default::default(),
131            connections: Default::default(),
132            known_peers: Default::default(),
133            banned_peers: Default::default(),
134            stats: Stats::new(Instant::now()),
135            tasks: Default::default(),
136        }));
137
138        debug!(parent: tcp.span(), "The node is ready");
139
140        tcp
141    }
142
143    /// Returns the name assigned.
144    #[inline]
145    pub fn name(&self) -> &str {
146        // safe; can be set as None in Config, but receives a default value on Tcp creation
147        self.config.name.as_deref().unwrap()
148    }
149
150    /// Returns a reference to the configuration.
151    #[inline]
152    pub fn config(&self) -> &Config {
153        &self.config
154    }
155
156    /// Returns the listening address; returns an error if Tcp was not configured
157    /// to listen for inbound connections.
158    pub fn listening_addr(&self) -> io::Result<SocketAddr> {
159        self.listening_addr.get().copied().ok_or_else(|| io::ErrorKind::AddrNotAvailable.into())
160    }
161
162    /// Checks whether the provided address is connected.
163    pub fn is_connected(&self, addr: SocketAddr) -> bool {
164        self.connections.is_connected(addr)
165    }
166
167    /// Checks if Tcp is currently setting up a connection with the provided address.
168    pub fn is_connecting(&self, addr: SocketAddr) -> bool {
169        self.connecting.lock().contains(&addr)
170    }
171
172    /// Returns the number of active connections.
173    pub fn num_connected(&self) -> usize {
174        self.connections.num_connected()
175    }
176
177    /// Returns the number of connections that are currently being set up.
178    pub fn num_connecting(&self) -> usize {
179        self.connecting.lock().len()
180    }
181
182    /// Returns a list containing addresses of active connections.
183    pub fn connected_addrs(&self) -> Vec<SocketAddr> {
184        self.connections.addrs()
185    }
186
187    /// Returns a list containing addresses of pending connections.
188    pub fn connecting_addrs(&self) -> Vec<SocketAddr> {
189        self.connecting.lock().iter().copied().collect()
190    }
191
192    /// Returns a reference to the collection of statistics of known peers.
193    #[inline]
194    pub fn known_peers(&self) -> &KnownPeers {
195        &self.known_peers
196    }
197
198    /// Returns a reference to the set of currently banned peers.
199    #[inline]
200    pub fn banned_peers(&self) -> &BannedPeers {
201        &self.banned_peers
202    }
203
204    /// Returns a reference to the statistics.
205    #[inline]
206    pub fn stats(&self) -> &Stats {
207        &self.stats
208    }
209
210    /// Returns the tracing [`Span`] associated with Tcp.
211    #[inline]
212    pub fn span(&self) -> &Span {
213        &self.span
214    }
215
216    /// Gracefully shuts down the stack.
217    pub async fn shut_down(&self) {
218        debug!(parent: self.span(), "Shutting down the TCP stack");
219
220        // Retrieve all tasks.
221        let mut tasks = std::mem::take(&mut *self.tasks.lock()).into_iter();
222
223        // Abort the listening task first.
224        if let Some(listening_task) = tasks.next() {
225            listening_task.abort(); // abort the listening task first
226        }
227        // Disconnect from all connected peers.
228        for addr in self.connected_addrs() {
229            self.disconnect(addr).await;
230        }
231        // Abort all remaining tasks.
232        for handle in tasks {
233            handle.abort();
234        }
235    }
236}
237
238impl Tcp {
239    /// Connects to the provided `SocketAddr`.
240    pub async fn connect(&self, addr: SocketAddr) -> Result<(), ConnectError> {
241        if let Ok(listening_addr) = self.listening_addr() {
242            // TODO(nkls): maybe this first check can be dropped; though it might be best to keep just in case.
243            if addr == listening_addr || self.is_self_connect(addr) {
244                error!(parent: self.span(), "Attempted to self-connect ({addr})");
245                return Err(ConnectError::SelfConnect { address: addr });
246            }
247        }
248
249        if !self.can_add_connection() {
250            error!(parent: self.span(), "Too many connections; refusing to connect to {addr}");
251            return Err(ConnectError::MaximumConnectionsReached { limit: self.config.max_connections });
252        }
253
254        if self.is_connected(addr) {
255            warn!(parent: self.span(), "Already connected to {addr}");
256            return Err(ConnectError::AlreadyConnected { address: addr });
257        }
258
259        if !self.connecting.lock().insert(addr) {
260            warn!(parent: self.span(), "Already connecting to {addr}");
261            return Err(ConnectError::AlreadyConnecting { address: addr });
262        }
263
264        let timeout_duration = Duration::from_millis(self.config().connection_timeout_ms.into());
265
266        // Bind the tcp socket to the configured listener ip if it's set.
267        // Otherwise default to the system's default interface.
268        let res = if let Some(listen_ip) = self.config().listener_ip {
269            let sock =
270                if listen_ip.is_ipv4() { tokio::net::TcpSocket::new_v4()? } else { tokio::net::TcpSocket::new_v6()? };
271            sock.bind(SocketAddr::new(listen_ip, 0))?;
272            timeout(timeout_duration, sock.connect(addr)).await
273        } else {
274            timeout(timeout_duration, TcpStream::connect(addr)).await
275        };
276
277        let stream = match res {
278            Ok(Ok(stream)) => Ok(stream),
279            Ok(err) => {
280                self.connecting.lock().remove(&addr);
281                err
282            }
283            Err(err) => {
284                self.connecting.lock().remove(&addr);
285                error!("connection timeout error: {}", err);
286                Err(io::ErrorKind::TimedOut.into())
287            }
288        }?;
289
290        let ret = self.adapt_stream(stream, addr, ConnectionSide::Initiator).await;
291
292        if let Err(ref e) = ret {
293            self.connecting.lock().remove(&addr);
294            self.known_peers().register_failure(addr.ip());
295            error!(parent: self.span(), "Unable to initiate a connection with {addr}: {e}");
296        }
297
298        ret.map_err(|err| err.into())
299    }
300
301    /// Disconnects from the provided `SocketAddr`.
302    ///
303    /// Returns true if the we were connected to the given address.
304    pub async fn disconnect(&self, addr: SocketAddr) -> bool {
305        if let Some(handler) = self.protocols.disconnect.get() {
306            if self.is_connected(addr) {
307                let (sender, receiver) = oneshot::channel();
308                handler.trigger((addr, sender));
309                let _ = receiver.await; // can't really fail
310            }
311        }
312
313        let conn = self.connections.remove(addr);
314
315        if let Some(ref conn) = conn {
316            debug!(parent: self.span(), "Disconnecting from {}", conn.addr());
317
318            // Shut down the associated tasks of the peer.
319            for task in conn.tasks.iter().rev() {
320                task.abort();
321            }
322
323            debug!(parent: self.span(), "Disconnected from {}", conn.addr());
324        } else {
325            warn!(parent: self.span(), "Failed to disconnect, was not connected to {addr}");
326        }
327
328        conn.is_some()
329    }
330}
331
332impl Tcp {
333    /// Spawns a task that listens for incoming connections.
334    pub async fn enable_listener(&self) -> io::Result<SocketAddr> {
335        // Retrieve the listening IP address, which must be set.
336        let listener_ip =
337            self.config().listener_ip.expect("Tcp::enable_listener was called, but Config::listener_ip is not set");
338
339        // Initialize the TCP listener.
340        let listener = self.create_listener(listener_ip).await?;
341
342        // Discover the port, if it was unspecified.
343        let port = listener.local_addr()?.port();
344
345        // Set the listening IP address.
346        let listening_addr = (listener_ip, port).into();
347        self.listening_addr.set(listening_addr).expect("The node's listener was started more than once");
348
349        // Use a channel to know when the listening task is ready.
350        let (tx, rx) = oneshot::channel();
351
352        let tcp = self.clone();
353        let listening_task = tokio::spawn(async move {
354            trace!(parent: tcp.span(), "Spawned the listening task");
355            tx.send(()).unwrap(); // safe; the channel was just opened
356
357            loop {
358                // Await for a new connection.
359                match listener.accept().await {
360                    Ok((stream, addr)) => tcp.handle_connection(stream, addr),
361                    Err(e) => error!(parent: tcp.span(), "Failed to accept a connection: {e}"),
362                }
363            }
364        });
365        self.tasks.lock().push(listening_task);
366        let _ = rx.await;
367        debug!(parent: self.span(), "Listening on {listening_addr}");
368
369        Ok(listening_addr)
370    }
371
372    /// Creates an instance of `TcpListener` based on the node's configuration.
373    async fn create_listener(&self, listener_ip: IpAddr) -> io::Result<TcpListener> {
374        debug!("Creating a TCP listener on {listener_ip}...");
375        let listener = if let Some(port) = self.config().desired_listening_port {
376            // Construct the desired listening IP address.
377            let desired_listening_addr = SocketAddr::new(listener_ip, port);
378            // If a desired listening port is set, try to bind to it.
379            match TcpListener::bind(desired_listening_addr).await {
380                Ok(listener) => listener,
381                Err(e) => {
382                    if self.config().allow_random_port {
383                        warn!(
384                            parent: self.span(),
385                            "Trying any listening port, as the desired port is unavailable: {e}"
386                        );
387                        let random_available_addr = SocketAddr::new(listener_ip, 0);
388                        TcpListener::bind(random_available_addr).await?
389                    } else {
390                        error!(parent: self.span(), "The desired listening port is unavailable: {e}");
391                        return Err(e);
392                    }
393                }
394            }
395        } else if self.config().allow_random_port {
396            let random_available_addr = SocketAddr::new(listener_ip, 0);
397            TcpListener::bind(random_available_addr).await?
398        } else {
399            panic!("As 'listener_ip' is set, either 'desired_listening_port' or 'allow_random_port' must be set");
400        };
401
402        Ok(listener)
403    }
404
405    /// Handles a new inbound connection.
406    fn handle_connection(&self, stream: TcpStream, addr: SocketAddr) {
407        debug!(parent: self.span(), "Received a connection from {addr}");
408
409        if !self.can_add_connection() || self.is_self_connect(addr) {
410            debug!(parent: self.span(), "Rejecting the connection from {addr}");
411            return;
412        }
413
414        self.connecting.lock().insert(addr);
415
416        let tcp = self.clone();
417        tokio::spawn(async move {
418            if let Err(e) = tcp.adapt_stream(stream, addr, ConnectionSide::Responder).await {
419                tcp.connecting.lock().remove(&addr);
420                tcp.known_peers().register_failure(addr.ip());
421                error!(parent: tcp.span(), "Failed to connect with {addr}: {e}");
422            }
423        });
424    }
425
426    /// Checks if the given IP address is the same as the listening address of this `Tcp`.
427    fn is_self_connect(&self, addr: SocketAddr) -> bool {
428        // SAFETY: if we're opening connections, this should never fail.
429        let listening_addr = self.listening_addr().unwrap();
430
431        match listening_addr.ip().is_loopback() {
432            // If localhost, check the ports, this only works on outbound connections, since we
433            // don't know the ephemeral port a peer might be using if they initiate the connection.
434            true => listening_addr.port() == addr.port(),
435            // If it's not localhost, matching IPs indicate a self-connect in both directions.
436            false => listening_addr.ip() == addr.ip(),
437        }
438    }
439
440    /// Checks whether the `Tcp` can handle an additional connection.
441    fn can_add_connection(&self) -> bool {
442        // Retrieve the number of connected peers.
443        let num_connected = self.num_connected();
444        // Retrieve the maximum number of connected peers.
445        let limit = self.config.max_connections as usize;
446
447        if num_connected >= limit {
448            warn!(parent: self.span(), "Maximum number of active connections ({limit}) reached");
449            false
450        } else if num_connected + self.num_connecting() >= limit {
451            warn!(parent: self.span(), "Maximum number of active & pending connections ({limit}) reached");
452            false
453        } else {
454            true
455        }
456    }
457
458    /// Prepares the freshly acquired connection to handle the protocols the Tcp implements.
459    async fn adapt_stream(&self, stream: TcpStream, peer_addr: SocketAddr, own_side: ConnectionSide) -> io::Result<()> {
460        self.known_peers.add(peer_addr.ip());
461
462        // Register the port seen by the peer.
463        if own_side == ConnectionSide::Initiator {
464            if let Ok(addr) = stream.local_addr() {
465                debug!(
466                    parent: self.span(), "establishing connection with {}; the peer is connected on port {}",
467                    peer_addr, addr.port()
468                );
469            } else {
470                warn!(parent: self.span(), "couldn't determine the peer's port");
471            }
472        }
473
474        let connection = Connection::new(peer_addr, stream, !own_side);
475
476        // Enact the enabled protocols.
477        let mut connection = self.enable_protocols(connection).await?;
478
479        // if Reading is enabled, we'll notify the related task when the connection is fully ready.
480        let conn_ready_tx = connection.readiness_notifier.take();
481
482        self.connections.add(connection);
483        self.connecting.lock().remove(&peer_addr);
484
485        // Send the aforementioned notification so that reading from the socket can commence.
486        if let Some(tx) = conn_ready_tx {
487            let _ = tx.send(());
488        }
489
490        // If enabled, enact OnConnect.
491        if let Some(handler) = self.protocols.on_connect.get() {
492            let (sender, receiver) = oneshot::channel();
493            handler.trigger((peer_addr, sender));
494            let _ = receiver.await; // can't really fail
495        }
496
497        Ok(())
498    }
499
500    /// Enacts the enabled protocols on the provided connection.
501    async fn enable_protocols(&self, conn: Connection) -> io::Result<Connection> {
502        /// A helper macro to enable a protocol on a connection.
503        macro_rules! enable_protocol {
504            ($handler_type: ident, $node:expr, $conn: expr) => {
505                if let Some(handler) = $node.protocols.$handler_type.get() {
506                    let (conn_returner, conn_retriever) = oneshot::channel();
507
508                    handler.trigger(($conn, conn_returner));
509
510                    match conn_retriever.await {
511                        Ok(Ok(conn)) => conn,
512                        Err(_) => return Err(io::ErrorKind::BrokenPipe.into()),
513                        Ok(e) => return e,
514                    }
515                } else {
516                    $conn
517                }
518            };
519        }
520
521        let mut conn = enable_protocol!(handshake, self, conn);
522
523        // Split the stream after the handshake (if not done before).
524        if let Some(stream) = conn.stream.take() {
525            let (reader, writer) = split(stream);
526            conn.reader = Some(Box::new(reader));
527            conn.writer = Some(Box::new(writer));
528        }
529
530        let conn = enable_protocol!(reading, self, conn);
531        let conn = enable_protocol!(writing, self, conn);
532
533        Ok(conn)
534    }
535}
536
537impl fmt::Debug for Tcp {
538    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539        write!(f, "The TCP stack config: {:?}", self.config)
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    use std::{
548        net::{IpAddr, Ipv4Addr},
549        str::FromStr,
550    };
551
552    #[tokio::test]
553    async fn test_new() {
554        let tcp = Tcp::new(Config {
555            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
556            max_connections: 200,
557            ..Default::default()
558        });
559
560        assert_eq!(tcp.config.max_connections, 200);
561        assert_eq!(tcp.config.listener_ip, Some(IpAddr::V4(Ipv4Addr::LOCALHOST)));
562        assert_eq!(tcp.enable_listener().await.unwrap().ip(), IpAddr::V4(Ipv4Addr::LOCALHOST));
563
564        assert_eq!(tcp.num_connected(), 0);
565        assert_eq!(tcp.num_connecting(), 0);
566    }
567
568    #[tokio::test]
569    async fn test_connect() {
570        let tcp = Tcp::new(Config::default());
571        let node_ip = tcp.enable_listener().await.unwrap();
572
573        // Ensure self-connecting is not possible.
574        let result = tcp.connect(node_ip).await;
575        assert!(matches!(result, Err(ConnectError::SelfConnect { .. })));
576
577        assert_eq!(tcp.num_connected(), 0);
578        assert_eq!(tcp.num_connecting(), 0);
579        assert!(!tcp.is_connected(node_ip));
580        assert!(!tcp.is_connecting(node_ip));
581
582        // Initialize the peer.
583        let peer = Tcp::new(Config {
584            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
585            desired_listening_port: Some(0),
586            max_connections: 1,
587            ..Default::default()
588        });
589        let peer_ip = peer.enable_listener().await.unwrap();
590
591        // Connect to the peer.
592        tcp.connect(peer_ip).await.unwrap();
593        assert_eq!(tcp.num_connected(), 1);
594        assert_eq!(tcp.num_connecting(), 0);
595        assert!(tcp.is_connected(peer_ip));
596        assert!(!tcp.is_connecting(peer_ip));
597    }
598
599    #[tokio::test]
600    async fn test_disconnect() {
601        let tcp = Tcp::new(Config::default());
602        let _node_ip = tcp.enable_listener().await.unwrap();
603
604        // Initialize the peer.
605        let peer = Tcp::new(Config {
606            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
607            desired_listening_port: Some(0),
608            max_connections: 1,
609            ..Default::default()
610        });
611        let peer_ip = peer.enable_listener().await.unwrap();
612
613        // Connect to the peer.
614        tcp.connect(peer_ip).await.unwrap();
615        assert_eq!(tcp.num_connected(), 1);
616        assert_eq!(tcp.num_connecting(), 0);
617        assert!(tcp.is_connected(peer_ip));
618        assert!(!tcp.is_connecting(peer_ip));
619
620        // Disconnect from the peer.
621        let has_disconnected = tcp.disconnect(peer_ip).await;
622        assert!(has_disconnected);
623        assert_eq!(tcp.num_connected(), 0);
624        assert_eq!(tcp.num_connecting(), 0);
625        assert!(!tcp.is_connected(peer_ip));
626        assert!(!tcp.is_connecting(peer_ip));
627
628        // Ensure disconnecting from the peer a second time is okay.
629        let has_disconnected = tcp.disconnect(peer_ip).await;
630        assert!(!has_disconnected);
631        assert_eq!(tcp.num_connected(), 0);
632        assert_eq!(tcp.num_connecting(), 0);
633        assert!(!tcp.is_connected(peer_ip));
634        assert!(!tcp.is_connecting(peer_ip));
635    }
636
637    #[tokio::test]
638    async fn test_can_add_connection() {
639        let tcp = Tcp::new(Config { max_connections: 1, ..Default::default() });
640
641        // Initialize the peer.
642        let peer = Tcp::new(Config {
643            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
644            desired_listening_port: Some(0),
645            max_connections: 1,
646            ..Default::default()
647        });
648        let peer_ip = peer.enable_listener().await.unwrap();
649
650        assert!(tcp.can_add_connection());
651
652        // Simulate an active connection.
653        let stream = TcpStream::connect(peer_ip).await.unwrap();
654        tcp.connections.add(Connection::new(peer_ip, stream, ConnectionSide::Initiator));
655        assert!(!tcp.can_add_connection());
656
657        // Ensure that we cannot invoke connect() successfully in this case.
658        // Use a non-local IP, to ensure it is never qual to peer IP.
659        let another_ip = SocketAddr::from_str("1.2.3.4:4242").unwrap();
660        let result = tcp.connect(another_ip).await;
661        assert!(matches!(result, Err(ConnectError::MaximumConnectionsReached { .. })));
662
663        // Remove the active connection.
664        tcp.connections.remove(peer_ip);
665        assert!(tcp.can_add_connection());
666
667        // Simulate a pending connection.
668        tcp.connecting.lock().insert(peer_ip);
669        assert!(!tcp.can_add_connection());
670
671        // Ensure that we cannot invoke connect() successfully in this case either.
672        let another_ip = SocketAddr::from_str("1.2.3.4:4242").unwrap();
673        let result = tcp.connect(another_ip).await;
674        assert!(matches!(result, Err(ConnectError::MaximumConnectionsReached { .. })));
675
676        // Remove the pending connection.
677        tcp.connecting.lock().remove(&peer_ip);
678        assert!(tcp.can_add_connection());
679
680        // Simulate an active and a pending connection (this case should never occur).
681        let stream = TcpStream::connect(peer_ip).await.unwrap();
682        tcp.connections.add(Connection::new(peer_ip, stream, ConnectionSide::Responder));
683        tcp.connecting.lock().insert(peer_ip);
684        assert!(!tcp.can_add_connection());
685
686        // Remove the active and pending connection.
687        tcp.connections.remove(peer_ip);
688        tcp.connecting.lock().remove(&peer_ip);
689        assert!(tcp.can_add_connection());
690    }
691
692    #[tokio::test]
693    async fn test_handle_connection() {
694        let tcp = Tcp::new(Config {
695            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
696            max_connections: 1,
697            ..Default::default()
698        });
699
700        // Initialize peer 1.
701        let peer1 = Tcp::new(Config {
702            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
703            desired_listening_port: Some(0),
704            max_connections: 1,
705            ..Default::default()
706        });
707        let peer1_ip = peer1.enable_listener().await.unwrap();
708
709        // Simulate an active connection.
710        let stream = TcpStream::connect(peer1_ip).await.unwrap();
711        tcp.connections.add(Connection::new(peer1_ip, stream, ConnectionSide::Responder));
712        assert!(!tcp.can_add_connection());
713        assert_eq!(tcp.num_connected(), 1);
714        assert_eq!(tcp.num_connecting(), 0);
715        assert!(tcp.is_connected(peer1_ip));
716        assert!(!tcp.is_connecting(peer1_ip));
717
718        // Initialize peer 2.
719        let peer2 = Tcp::new(Config {
720            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
721            desired_listening_port: Some(0),
722            max_connections: 1,
723            ..Default::default()
724        });
725        let peer2_ip = peer2.enable_listener().await.unwrap();
726
727        // Handle the connection.
728        let stream = TcpStream::connect(peer2_ip).await.unwrap();
729        tcp.handle_connection(stream, peer2_ip);
730        assert!(!tcp.can_add_connection());
731        assert_eq!(tcp.num_connected(), 1);
732        assert_eq!(tcp.num_connecting(), 0);
733        assert!(tcp.is_connected(peer1_ip));
734        assert!(!tcp.is_connected(peer2_ip));
735        assert!(!tcp.is_connecting(peer1_ip));
736        assert!(!tcp.is_connecting(peer2_ip));
737    }
738
739    #[tokio::test]
740    async fn test_adapt_stream() {
741        let tcp = Tcp::new(Config { max_connections: 1, ..Default::default() });
742
743        // Initialize the peer.
744        let peer = Tcp::new(Config {
745            listener_ip: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
746            desired_listening_port: Some(0),
747            max_connections: 1,
748            ..Default::default()
749        });
750        let peer_ip = peer.enable_listener().await.unwrap();
751
752        // Simulate a pending connection.
753        tcp.connecting.lock().insert(peer_ip);
754        assert_eq!(tcp.num_connected(), 0);
755        assert_eq!(tcp.num_connecting(), 1);
756        assert!(!tcp.is_connected(peer_ip));
757        assert!(tcp.is_connecting(peer_ip));
758
759        // Simulate a new connection.
760        let stream = TcpStream::connect(peer_ip).await.unwrap();
761        tcp.adapt_stream(stream, peer_ip, ConnectionSide::Responder).await.unwrap();
762        assert_eq!(tcp.num_connected(), 1);
763        assert_eq!(tcp.num_connecting(), 0);
764        assert!(tcp.is_connected(peer_ip));
765        assert!(!tcp.is_connecting(peer_ip));
766    }
767}