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::peers::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::peers::{IP2PConnections, Recipient};
19use fedimint_core::task::{TaskGroup, sleep};
20use fedimint_core::util::FmtCompactAnyhow;
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::watch;
27use tokio::time::{Instant, sleep_until};
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_anyhow(), "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    /// Drop a connection once it exceeds this age so it is re-established;
258    /// disabled if `None`.
259    max_connection_age: Option<Duration>,
260    /// Point in time at which the current connection exceeds the maximum
261    /// age; set whenever a new connection is established.
262    connection_deadline: Option<Instant>,
263}
264
265enum P2PConnectionSMState<M> {
266    Disconnected {
267        backoff: FibonacciBackoff,
268        last_error: Option<String>,
269    },
270    Connected(DynP2PConnection<M>),
271}
272
273impl<M: Send + 'static> P2PConnectionStateMachine<M> {
274    async fn state_transition(mut self) -> Option<Self> {
275        match self.state {
276            P2PConnectionSMState::Disconnected {
277                backoff,
278                last_error,
279            } => {
280                self.common.status_sender.send_replace(P2PConnectionState {
281                    connected: None,
282                    last_error,
283                });
284
285                self.common.transition_disconnected(backoff).await
286            }
287            P2PConnectionSMState::Connected(connection) => {
288                // Subscribe before taking the snapshot so an update racing with
289                // the snapshot remains queued for the connected transition.
290                let status_updates = connection.connection_status_updates();
291                let status = P2PConnectionStatus {
292                    conn_type: connection
293                        .connection_type()
294                        .or_else(|| self.common.connector.connection_type(self.common.peer_id)),
295                    rtt: connection.rtt(),
296                };
297
298                self.common.status_sender.send_replace(P2PConnectionState {
299                    connected: Some(status),
300                    last_error: None,
301                });
302
303                self.common
304                    .transition_connected(connection, status_updates)
305                    .await
306            }
307        }
308        .map(|state| P2PConnectionStateMachine {
309            common: self.common,
310            state,
311        })
312    }
313}
314
315impl<M: Send + 'static> P2PConnectionSMCommon<M> {
316    async fn transition_connected(
317        &mut self,
318        mut connection: DynP2PConnection<M>,
319        mut status_updates: Option<DynConnectionStatusUpdates>,
320    ) -> Option<P2PConnectionSMState<M>> {
321        tokio::select! {
322            Some(()) = async {
323                match status_updates.as_mut() {
324                    Some(status_updates) => status_updates.next().await,
325                    None => std::future::pending().await,
326                }
327            } => {
328                Some(P2PConnectionSMState::Connected(connection))
329            },
330            () = async {
331                match self.connection_deadline {
332                    Some(deadline) => sleep_until(deadline).await,
333                    None => std::future::pending().await,
334                }
335            } => {
336                Some(self.disconnect(anyhow!("Connection exceeded the maximum age")))
337            },
338            message = self.outgoing_receiver.recv() => {
339                Some(self.send_message(connection, message.ok()?).await)
340            },
341            connection = self.incoming_connections.recv() => {
342                info!(target: LOG_NET_PEER, "Connected to peer");
343
344                self.connection_deadline = self.max_connection_age.map(|age| Instant::now() + age);
345
346                Some(P2PConnectionSMState::Connected(connection.ok()?))
347            },
348            message = connection.receive() => {
349                let mut message = match message {
350                    Ok(message) => message,
351                    Err(e) => return Some(self.disconnect(e)),
352                };
353
354                match message.read_to_end().await {
355                    Ok(message) => {
356                        PEER_MESSAGES_COUNT
357                            .with_label_values(&[self.our_id_str.as_str(), self.peer_id_str.as_str(), "incoming"])
358                            .inc();
359
360                        if self.incoming_sender.try_send(message).is_err() {
361                            debug!(target: LOG_NET_PEER, "Incoming message channel is full");
362                        }
363                    },
364                    Err(e) => return Some(self.disconnect(e)),
365                }
366
367                Some(P2PConnectionSMState::Connected(connection))
368            },
369        }
370    }
371
372    fn disconnect(&self, error: anyhow::Error) -> P2PConnectionSMState<M> {
373        let last_error = error.fmt_compact_anyhow().to_string();
374
375        info!(
376            target: LOG_NET_PEER,
377            error = %last_error,
378            "Disconnected from peer"
379        );
380
381        PEER_DISCONNECT_COUNT
382            .with_label_values(&[&self.our_id_str, &self.peer_id_str])
383            .inc();
384
385        P2PConnectionSMState::Disconnected {
386            backoff: api_networking_backoff(),
387            last_error: Some(last_error),
388        }
389    }
390
391    async fn send_message(
392        &mut self,
393        mut connection: DynP2PConnection<M>,
394        peer_message: M,
395    ) -> P2PConnectionSMState<M> {
396        PEER_MESSAGES_COUNT
397            .with_label_values(&[
398                self.our_id_str.as_str(),
399                self.peer_id_str.as_str(),
400                "outgoing",
401            ])
402            .inc();
403
404        if let Err(e) = connection.send(peer_message).await {
405            return self.disconnect(e);
406        }
407
408        P2PConnectionSMState::Connected(connection)
409    }
410
411    async fn transition_disconnected(
412        &mut self,
413        mut backoff: FibonacciBackoff,
414    ) -> Option<P2PConnectionSMState<M>> {
415        tokio::select! {
416            connection = self.incoming_connections.recv() => {
417                PEER_CONNECT_COUNT
418                    .with_label_values(&[self.our_id_str.as_str(), self.peer_id_str.as_str(), "incoming"])
419                    .inc();
420
421                info!(target: LOG_NET_PEER, "Connected to peer");
422
423                self.connection_deadline = self.max_connection_age.map(|age| Instant::now() + age);
424
425                Some(P2PConnectionSMState::Connected(connection.ok()?))
426            },
427            // to prevent "reconnection ping-pongs", only the side with lower PeerId reconnects
428            () = sleep(backoff.next().expect("Unlimited retries")), if self.our_id < self.peer_id => {
429                info!(target: LOG_NET_PEER, "Attempting to reconnect to peer");
430
431                match self.connector.connect(self.peer_id).await {
432                    Ok(connection) => {
433                        PEER_CONNECT_COUNT
434                            .with_label_values(&[self.our_id_str.as_str(), self.peer_id_str.as_str(), "outgoing"])
435                            .inc();
436
437                        info!(target: LOG_NET_PEER, "Connected to peer");
438
439                        self.connection_deadline = self.max_connection_age.map(|age| Instant::now() + age);
440
441                        Some(P2PConnectionSMState::Connected(connection))
442                    }
443                    Err(e) => {
444                        let last_error = e.fmt_compact_anyhow().to_string();
445
446                        warn!(
447                            target: LOG_CONSENSUS,
448                            error = %last_error,
449                            "Failed to connect to peer"
450                        );
451
452                        Some(P2PConnectionSMState::Disconnected {
453                            backoff,
454                            last_error: Some(last_error),
455                        })
456                    }
457                }
458            },
459        }
460    }
461}