Skip to main content

fedimint_server/net/
p2p.rs

1//! Implements a connection manager for communication with other federation
2//! members
3//!
4//! The main interface is [`fedimint_core::net::IP2PConnections`] and
5//! its main implementation is [`ReconnectP2PConnections`], see these for
6//! details.
7
8#[cfg(test)]
9mod tests;
10
11use std::collections::BTreeMap;
12use std::time::Duration;
13
14use anyhow::anyhow;
15use async_channel::{Receiver, Sender, bounded};
16use async_trait::async_trait;
17use fedimint_core::PeerId;
18use fedimint_core::net::{IP2PConnections, Recipient};
19use fedimint_core::task::{TaskGroup, sleep};
20use fedimint_core::util::FmtCompact;
21use fedimint_core::util::backoff_util::{FibonacciBackoff, api_networking_backoff};
22use fedimint_logging::{LOG_CONSENSUS, LOG_NET_PEER};
23use fedimint_server_core::dashboard_ui::P2PConnectionStatus;
24use futures::future::select_all;
25use futures::{FutureExt, StreamExt};
26use tokio::sync::{Notify, watch};
27use tokio::time::{Instant, sleep_until, timeout};
28use tracing::{Instrument, debug, info, info_span, warn};
29
30use crate::metrics::{PEER_CONNECT_COUNT, PEER_DISCONNECT_COUNT, PEER_MESSAGES_COUNT};
31use crate::net::p2p_connection::{DynConnectionStatusUpdates, DynP2PConnection};
32use crate::net::p2p_connector::DynP2PConnector;
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct P2PConnectionState {
36    /// Current connection metadata, or `None` if disconnected.
37    pub connected: Option<P2PConnectionStatus>,
38    /// Last disconnect/connect error observed while disconnected.
39    pub last_error: Option<String>,
40}
41
42pub type P2PStatusSenders = BTreeMap<PeerId, watch::Sender<P2PConnectionState>>;
43pub type P2PStatusReceivers = BTreeMap<PeerId, watch::Receiver<P2PConnectionState>>;
44
45pub fn p2p_status_channels(peers: Vec<PeerId>) -> (P2PStatusSenders, P2PStatusReceivers) {
46    let mut senders = BTreeMap::new();
47    let mut receivers = BTreeMap::new();
48
49    for peer in peers {
50        let (sender, receiver) = watch::channel(P2PConnectionState {
51            connected: None,
52            last_error: None,
53        });
54
55        senders.insert(peer, sender);
56        receivers.insert(peer, receiver);
57    }
58
59    (senders, receivers)
60}
61
62#[derive(Clone)]
63pub struct ReconnectP2PConnections<M> {
64    connections: BTreeMap<PeerId, P2PConnection<M>>,
65}
66
67impl<M: Send + 'static> ReconnectP2PConnections<M> {
68    pub fn new(
69        identity: PeerId,
70        connector: DynP2PConnector<M>,
71        task_group: &TaskGroup,
72        status_senders: P2PStatusSenders,
73        max_connection_age: Option<Duration>,
74    ) -> Self {
75        let mut connection_senders = BTreeMap::new();
76        let mut connections = BTreeMap::new();
77
78        for peer_id in connector.peers() {
79            assert_ne!(peer_id, identity);
80
81            let (connection_sender, connection_receiver) = bounded(4);
82
83            let connection = P2PConnection::new(
84                identity,
85                peer_id,
86                connector.clone(),
87                connection_receiver,
88                status_senders
89                    .get(&peer_id)
90                    .expect("No p2p status sender for peer")
91                    .clone(),
92                max_connection_age,
93                task_group,
94            );
95
96            connection_senders.insert(peer_id, connection_sender);
97            connections.insert(peer_id, connection);
98        }
99
100        task_group.spawn_cancellable("handle-incoming-p2p-connections", async move {
101            info!(target: LOG_NET_PEER, "Starting listening task for p2p connections");
102
103            loop {
104                match connector.accept().await {
105                    Ok((peer, connection)) => {
106                        if connection_senders
107                            .get_mut(&peer)
108                            .expect("Authenticating connectors dont return unknown peers")
109                            .send(connection)
110                            .await
111                            .is_err()
112                        {
113                            break;
114                        }
115                    },
116                    Err(err) => {
117                        warn!(target: LOG_NET_PEER, our_id = %identity, err = %err.fmt_compact(), "Error while opening incoming connection");
118                    }
119                }
120            }
121
122            info!(target: LOG_NET_PEER, "Shutting down listening task for p2p connections");
123        });
124
125        ReconnectP2PConnections { connections }
126    }
127}
128
129#[async_trait]
130impl<M: Clone + Send + 'static> IP2PConnections<M> for ReconnectP2PConnections<M> {
131    fn send(&self, recipient: Recipient, message: M) {
132        match recipient {
133            Recipient::Everyone => {
134                for connection in self.connections.values() {
135                    connection.try_send(message.clone());
136                }
137            }
138            Recipient::Peer(peer) => match self.connections.get(&peer) {
139                Some(connection) => {
140                    connection.try_send(message);
141                }
142                _ => {
143                    warn!(target: LOG_NET_PEER, "No connection for peer {peer}");
144                }
145            },
146        }
147    }
148
149    async fn receive(&self) -> Option<(PeerId, M)> {
150        select_all(self.connections.iter().map(|(&peer, connection)| {
151            Box::pin(connection.receive().map(move |m| m.map(|m| (peer, m))))
152        }))
153        .await
154        .0
155    }
156
157    async fn receive_from_peer(&self, peer: PeerId) -> Option<M> {
158        self.connections
159            .get(&peer)
160            .expect("No connection found for peer")
161            .receive()
162            .await
163    }
164}
165
166#[derive(Clone)]
167struct P2PConnection<M> {
168    outgoing_sender: Sender<M>,
169    incoming_receiver: Receiver<M>,
170}
171
172impl<M: Send + 'static> P2PConnection<M> {
173    fn new(
174        our_id: PeerId,
175        peer_id: PeerId,
176        connector: DynP2PConnector<M>,
177        incoming_connections: Receiver<DynP2PConnection<M>>,
178        status_sender: watch::Sender<P2PConnectionState>,
179        max_connection_age: Option<Duration>,
180        task_group: &TaskGroup,
181    ) -> P2PConnection<M> {
182        // We use small message queues here to avoid outdated messages such as requests
183        // for signed session outcomes to queue up while a peer is disconnected. The
184        // consensus expects an unreliable networking layer and will resend lost
185        // messages accordingly. Furthermore, during the DKG there will never be more
186        // than two messages in those channels at once, due to its sequential
187        // nature there.
188        let (outgoing_sender, outgoing_receiver) = bounded(5);
189        let (incoming_sender, incoming_receiver) = bounded(5);
190
191        task_group.spawn_cancellable(
192            format!("io-state-machine-{peer_id}"),
193            async move {
194                info!(target: LOG_NET_PEER, "Starting peer connection state machine");
195
196                let mut state_machine = P2PConnectionStateMachine {
197                    common: P2PConnectionSMCommon {
198                        incoming_sender,
199                        outgoing_receiver,
200                        our_id_str: our_id.to_string(),
201                        our_id,
202                        peer_id_str: peer_id.to_string(),
203                        peer_id,
204                        connector,
205                        incoming_connections,
206                        status_sender,
207                        max_connection_age,
208                        connection_deadline: None,
209                    },
210                    state: P2PConnectionSMState::Disconnected {
211                        backoff: api_networking_backoff(),
212                        last_error: None,
213                    },
214                };
215
216                while let Some(sm) = state_machine.state_transition().await {
217                    state_machine = sm;
218                }
219
220                info!(target: LOG_NET_PEER, "Shutting down peer connection state machine");
221            }
222            .instrument(info_span!("io-state-machine", ?peer_id)),
223        );
224
225        P2PConnection {
226            outgoing_sender,
227            incoming_receiver,
228        }
229    }
230
231    fn try_send(&self, message: M) {
232        if self.outgoing_sender.try_send(message).is_err() {
233            debug!(target: LOG_NET_PEER, "Outgoing message channel is full");
234        }
235    }
236
237    async fn receive(&self) -> Option<M> {
238        self.incoming_receiver.recv().await.ok()
239    }
240}
241
242struct P2PConnectionStateMachine<M> {
243    state: P2PConnectionSMState<M>,
244    common: P2PConnectionSMCommon<M>,
245}
246
247struct P2PConnectionSMCommon<M> {
248    incoming_sender: async_channel::Sender<M>,
249    outgoing_receiver: async_channel::Receiver<M>,
250    our_id: PeerId,
251    our_id_str: String,
252    peer_id: PeerId,
253    peer_id_str: String,
254    connector: DynP2PConnector<M>,
255    incoming_connections: Receiver<DynP2PConnection<M>>,
256    status_sender: watch::Sender<P2PConnectionState>,
257    /// Request connection retirement after this age so it is re-established.
258    ///
259    /// The send loop checks the deadline between sends; disabled if `None`.
260    max_connection_age: Option<Duration>,
261    /// Deadline after which the send loop requests max-age retirement; set when
262    /// a new connection is established.
263    connection_deadline: Option<Instant>,
264}
265
266enum P2PConnectionSMState<M> {
267    Disconnected {
268        backoff: FibonacciBackoff,
269        last_error: Option<String>,
270    },
271    Connected(DynP2PConnection<M>),
272}
273
274/// How often live connection metadata (currently only the round-trip time) is
275/// re-published while a connection stays up.
276const METADATA_REFRESH_INTERVAL: Duration = Duration::from_secs(10);
277
278/// How long a halted send half waits for a frame that is already being read.
279/// A peer that stalls part way through a frame must not hold the state machine
280/// forever, so the wait is bounded. The same grace was proposed for both halves
281/// in #9121.
282const RECEIVE_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
283
284/// Upper bound for sending a single message. P2P messages are small compared
285/// to what a live connection moves in this time, so a send that takes longer
286/// means the peer no longer reads the connection.
287const SEND_TIMEOUT: Duration = Duration::from_mins(1);
288
289/// Why the send half of the connection stopped.
290enum SendHalt<M> {
291    /// The state machine is shutting down.
292    Shutdown,
293    /// The connection failed and should be re-established.
294    Failed(anyhow::Error),
295    /// The peer opened a replacement connection that supersedes this one.
296    Replaced(DynP2PConnection<M>),
297    /// The connection exceeded the maximum age and should be re-established.
298    MaxAge,
299}
300
301enum ReceiveHalt {
302    /// The connection failed and should be re-established.
303    Failed(anyhow::Error),
304    /// The send half halted and the receive half stopped between frames.
305    Stopped,
306}
307
308impl<M: Send + 'static> P2PConnectionStateMachine<M> {
309    async fn state_transition(mut self) -> Option<Self> {
310        match self.state {
311            P2PConnectionSMState::Disconnected {
312                backoff,
313                last_error,
314            } => {
315                self.common.status_sender.send_replace(P2PConnectionState {
316                    connected: None,
317                    last_error,
318                });
319
320                self.common.transition_disconnected(backoff).await
321            }
322            P2PConnectionSMState::Connected(connection) => {
323                // Subscribe before taking the snapshot so an update racing with
324                // the snapshot remains queued for the connected transition.
325                let status_updates = connection.connection_status_updates();
326
327                self.common.refresh_status(&connection);
328
329                self.common
330                    .transition_connected(connection, status_updates)
331                    .await
332            }
333        }
334        .map(|state| P2PConnectionStateMachine {
335            common: self.common,
336            state,
337        })
338    }
339}
340
341impl<M: Send + 'static> P2PConnectionSMCommon<M> {
342    async fn transition_connected(
343        &mut self,
344        connection: DynP2PConnection<M>,
345        mut status_updates: Option<DynConnectionStatusUpdates>,
346    ) -> Option<P2PConnectionSMState<M>> {
347        // The send and receive halves are driven as two long-lived futures during
348        // ordinary operation. Multiplexing a single send and a single receive in
349        // one `select!` meant that a send parked on transport flow control could
350        // no longer poll `receive`, so two peers that both started writing a
351        // message larger than the transport window deadlocked permanently and
352        // silently.
353        //
354        // Interleaving reads inside the parked send is *not* sufficient: it just
355        // turns a write/write deadlock into a read/read one. The halves have to
356        // be genuinely concurrent.
357        //
358        // The send half checks for replacement and max-age retirement between
359        // messages, so neither event cancels an active non-cancel-safe send.
360        // A pending send defers retirement until it completes, fails, or exceeds
361        // SEND_TIMEOUT; a send timeout fails the connection.
362        //
363        // When the send half halts, allow the receive half up to
364        // RECEIVE_DRAIN_TIMEOUT to finish its current frame and stop between
365        // frames. Shutdown skips this grace. A timeout or connection failure can
366        // still discard in-flight traffic; this is not a delivery guarantee.
367        // See `SPEC-guardian-p2p-delivery`.
368        let send_loop = Self::send_loop(
369            &connection,
370            &self.outgoing_receiver,
371            &self.incoming_connections,
372            self.connection_deadline,
373            &self.our_id_str,
374            &self.peer_id_str,
375        );
376        let stop_receiving = Notify::new();
377
378        let receive_loop = Self::receive_loop(
379            &connection,
380            &self.incoming_sender,
381            &stop_receiving,
382            &self.our_id_str,
383            &self.peer_id_str,
384        );
385
386        tokio::pin!(send_loop, receive_loop);
387
388        loop {
389            tokio::select! {
390                halt = &mut send_loop => {
391                    // A frame may be part way through `read_to_end`, which is not
392                    // cancel-safe, so give the receive half bounded time to stop
393                    // between frames rather than dropping it immediately.
394                    // Shutdown skips the grace: nothing reads the incoming queue
395                    // after it.
396                    if !matches!(halt, SendHalt::Shutdown) {
397                        stop_receiving.notify_one();
398
399                        let _ = timeout(RECEIVE_DRAIN_TIMEOUT, &mut receive_loop).await;
400                    }
401
402                    return match halt {
403                        SendHalt::Shutdown => None,
404                        SendHalt::Failed(e) => Some(self.disconnect(e)),
405                        SendHalt::MaxAge => {
406                            Some(self.disconnect(anyhow!("Connection exceeded the maximum age")))
407                        }
408                        SendHalt::Replaced(connection) => {
409                            info!(target: LOG_NET_PEER, "Connected to peer");
410
411                            self.connection_deadline =
412                                self.max_connection_age.map(|age| Instant::now() + age);
413
414                            Some(P2PConnectionSMState::Connected(connection))
415                        }
416                    };
417                },
418                halt = &mut receive_loop => {
419                    return Some(self.disconnect(match halt {
420                        ReceiveHalt::Failed(e) => e,
421                        ReceiveHalt::Stopped => anyhow!("Receive half stopped unprompted"),
422                    }));
423                },
424                Some(()) = async {
425                    match status_updates.as_mut() {
426                        Some(status_updates) => status_updates.next().await,
427                        None => std::future::pending().await,
428                    }
429                } => {
430                    self.refresh_status(&connection);
431                },
432                () = sleep(METADATA_REFRESH_INTERVAL) => {
433                    // Connection metadata used to be refreshed as a side effect
434                    // of every message, which the long-lived halves no longer
435                    // provide. Only `rtt` needs this; transport changes still
436                    // arrive on the status update stream above.
437                    self.refresh_status(&connection);
438                },
439            }
440        }
441    }
442
443    /// Drains the outgoing queue onto the connection.
444    ///
445    /// Checks for replacement and max-age retirement between sends, so neither
446    /// event cancels an active non-cancel-safe `send`. Each send has a
447    /// [`SEND_TIMEOUT`] limit; exceeding it fails the connection and can lose
448    /// the message in flight. This loop does not acknowledge delivery or
449    /// recover messages after reconnecting. See
450    /// `SPEC-guardian-p2p-delivery`.
451    async fn send_loop(
452        connection: &DynP2PConnection<M>,
453        outgoing_receiver: &Receiver<M>,
454        incoming_connections: &Receiver<DynP2PConnection<M>>,
455        connection_deadline: Option<Instant>,
456        our_id_str: &str,
457        peer_id_str: &str,
458    ) -> SendHalt<M> {
459        loop {
460            // All branches are cancel-safe: `recv` on an async channel does not
461            // take an item unless it completes and the timer holds no state.
462            let message = tokio::select! {
463                message = outgoing_receiver.recv() => match message {
464                    Ok(message) => message,
465                    Err(..) => return SendHalt::Shutdown,
466                },
467                connection = incoming_connections.recv() => return match connection {
468                    Ok(connection) => SendHalt::Replaced(connection),
469                    Err(..) => SendHalt::Shutdown,
470                },
471                () = async {
472                    match connection_deadline {
473                        Some(deadline) => sleep_until(deadline).await,
474                        None => std::future::pending().await,
475                    }
476                } => return SendHalt::MaxAge,
477            };
478
479            PEER_MESSAGES_COUNT
480                .with_label_values(&[our_id_str, peer_id_str, "outgoing"])
481                .inc();
482
483            // A peer that stops reading this connection, for example because
484            // it moved to a newer connection to us, parks the send for good
485            // while keepalives hold the connection open. Bound it, so the link
486            // is re-established instead of looking connected while every
487            // further message is dropped.
488            match timeout(SEND_TIMEOUT, connection.send(message)).await {
489                Ok(Ok(())) => {}
490                Ok(Err(e)) => return SendHalt::Failed(e),
491                Err(_) => {
492                    return SendHalt::Failed(anyhow!(
493                        "Sending a message did not complete within {SEND_TIMEOUT:?}"
494                    ));
495                }
496            }
497        }
498    }
499
500    /// Drains the connection into the incoming queue until the connection fails
501    /// or the send half requests a stop between frames.
502    async fn receive_loop(
503        connection: &DynP2PConnection<M>,
504        incoming_sender: &Sender<M>,
505        stop: &Notify,
506        our_id_str: &str,
507        peer_id_str: &str,
508    ) -> ReceiveHalt {
509        loop {
510            // `receive` is cancel-safe, `read_to_end` below is not, so this is
511            // the point at which we honor the stop request. The caller can still
512            // cancel this loop on drain timeout or shutdown.
513            let mut frame = tokio::select! {
514                biased;
515                () = stop.notified() => return ReceiveHalt::Stopped,
516                frame = connection.receive() => match frame {
517                    Ok(frame) => frame,
518                    Err(e) => return ReceiveHalt::Failed(e),
519                },
520            };
521
522            match frame.read_to_end().await {
523                Ok(message) => {
524                    PEER_MESSAGES_COUNT
525                        .with_label_values(&[our_id_str, peer_id_str, "incoming"])
526                        .inc();
527
528                    if incoming_sender.try_send(message).is_err() {
529                        debug!(target: LOG_NET_PEER, "Incoming message channel is full");
530                    }
531                }
532                Err(e) => return ReceiveHalt::Failed(e),
533            }
534        }
535    }
536
537    /// Publishes a fresh metadata snapshot for the live connection.
538    ///
539    /// Refreshing in place rather than re-entering the connected state means a
540    /// send already in flight is never cancelled by a status event.
541    fn refresh_status(&self, connection: &DynP2PConnection<M>) {
542        let status = P2PConnectionStatus {
543            conn_type: connection
544                .connection_type()
545                .or_else(|| self.connector.connection_type(self.peer_id)),
546            rtt: connection.rtt(),
547        };
548
549        self.status_sender.send_replace(P2PConnectionState {
550            connected: Some(status),
551            last_error: None,
552        });
553    }
554
555    fn disconnect(&self, error: anyhow::Error) -> P2PConnectionSMState<M> {
556        let last_error = error.fmt_compact().to_string();
557
558        info!(
559            target: LOG_NET_PEER,
560            error = %last_error,
561            "Disconnected from peer"
562        );
563
564        PEER_DISCONNECT_COUNT
565            .with_label_values(&[&self.our_id_str, &self.peer_id_str])
566            .inc();
567
568        P2PConnectionSMState::Disconnected {
569            backoff: api_networking_backoff(),
570            last_error: Some(last_error),
571        }
572    }
573
574    async fn transition_disconnected(
575        &mut self,
576        mut backoff: FibonacciBackoff,
577    ) -> Option<P2PConnectionSMState<M>> {
578        tokio::select! {
579            connection = self.incoming_connections.recv() => {
580                PEER_CONNECT_COUNT
581                    .with_label_values(&[self.our_id_str.as_str(), self.peer_id_str.as_str(), "incoming"])
582                    .inc();
583
584                info!(target: LOG_NET_PEER, "Connected to peer");
585
586                self.connection_deadline = self.max_connection_age.map(|age| Instant::now() + age);
587
588                Some(P2PConnectionSMState::Connected(connection.ok()?))
589            },
590            // to prevent "reconnection ping-pongs", only the side with lower PeerId reconnects
591            () = sleep(backoff.next().expect("Unlimited retries")), if self.our_id < self.peer_id => {
592                info!(target: LOG_NET_PEER, "Attempting to reconnect to peer");
593
594                match self.connector.connect(self.peer_id).await {
595                    Ok(connection) => {
596                        PEER_CONNECT_COUNT
597                            .with_label_values(&[self.our_id_str.as_str(), self.peer_id_str.as_str(), "outgoing"])
598                            .inc();
599
600                        info!(target: LOG_NET_PEER, "Connected to peer");
601
602                        self.connection_deadline = self.max_connection_age.map(|age| Instant::now() + age);
603
604                        Some(P2PConnectionSMState::Connected(connection))
605                    }
606                    Err(e) => {
607                        let last_error = e.fmt_compact().to_string();
608
609                        warn!(
610                            target: LOG_CONSENSUS,
611                            error = %last_error,
612                            "Failed to connect to peer"
613                        );
614
615                        Some(P2PConnectionSMState::Disconnected {
616                            backoff,
617                            last_error: Some(last_error),
618                        })
619                    }
620                }
621            },
622        }
623    }
624}