1#[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::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 pub connected: Option<P2PConnectionStatus>,
38 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 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 max_connection_age: Option<Duration>,
260 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
273const METADATA_REFRESH_INTERVAL: Duration = Duration::from_secs(10);
276
277enum SendHalt<M> {
279 Shutdown,
281 Failed(anyhow::Error),
283 Replaced(DynP2PConnection<M>),
285 MaxAge,
287}
288
289impl<M: Send + 'static> P2PConnectionStateMachine<M> {
290 async fn state_transition(mut self) -> Option<Self> {
291 match self.state {
292 P2PConnectionSMState::Disconnected {
293 backoff,
294 last_error,
295 } => {
296 self.common.status_sender.send_replace(P2PConnectionState {
297 connected: None,
298 last_error,
299 });
300
301 self.common.transition_disconnected(backoff).await
302 }
303 P2PConnectionSMState::Connected(connection) => {
304 let status_updates = connection.connection_status_updates();
307
308 self.common.refresh_status(&connection);
309
310 self.common
311 .transition_connected(connection, status_updates)
312 .await
313 }
314 }
315 .map(|state| P2PConnectionStateMachine {
316 common: self.common,
317 state,
318 })
319 }
320}
321
322impl<M: Send + 'static> P2PConnectionSMCommon<M> {
323 async fn transition_connected(
324 &mut self,
325 connection: DynP2PConnection<M>,
326 mut status_updates: Option<DynConnectionStatusUpdates>,
327 ) -> Option<P2PConnectionSMState<M>> {
328 let send_loop = Self::send_loop(
343 &connection,
344 &self.outgoing_receiver,
345 &self.incoming_connections,
346 self.connection_deadline,
347 &self.our_id_str,
348 &self.peer_id_str,
349 );
350 let receive_loop = Self::receive_loop(
351 &connection,
352 &self.incoming_sender,
353 &self.our_id_str,
354 &self.peer_id_str,
355 );
356
357 tokio::pin!(send_loop, receive_loop);
358
359 loop {
360 tokio::select! {
361 halt = &mut send_loop => {
362 return match halt {
363 SendHalt::Shutdown => None,
364 SendHalt::Failed(e) => Some(self.disconnect(e)),
365 SendHalt::MaxAge => {
366 Some(self.disconnect(anyhow!("Connection exceeded the maximum age")))
367 }
368 SendHalt::Replaced(connection) => {
369 info!(target: LOG_NET_PEER, "Connected to peer");
370
371 self.connection_deadline =
372 self.max_connection_age.map(|age| Instant::now() + age);
373
374 Some(P2PConnectionSMState::Connected(connection))
375 }
376 };
377 },
378 e = &mut receive_loop => {
379 return Some(self.disconnect(e));
380 },
381 Some(()) = async {
382 match status_updates.as_mut() {
383 Some(status_updates) => status_updates.next().await,
384 None => std::future::pending().await,
385 }
386 } => {
387 self.refresh_status(&connection);
388 },
389 () = sleep(METADATA_REFRESH_INTERVAL) => {
390 self.refresh_status(&connection);
395 },
396 }
397 }
398 }
399
400 async fn send_loop(
407 connection: &DynP2PConnection<M>,
408 outgoing_receiver: &Receiver<M>,
409 incoming_connections: &Receiver<DynP2PConnection<M>>,
410 connection_deadline: Option<Instant>,
411 our_id_str: &str,
412 peer_id_str: &str,
413 ) -> SendHalt<M> {
414 loop {
415 let message = tokio::select! {
418 message = outgoing_receiver.recv() => match message {
419 Ok(message) => message,
420 Err(..) => return SendHalt::Shutdown,
421 },
422 connection = incoming_connections.recv() => return match connection {
423 Ok(connection) => SendHalt::Replaced(connection),
424 Err(..) => SendHalt::Shutdown,
425 },
426 () = async {
427 match connection_deadline {
428 Some(deadline) => sleep_until(deadline).await,
429 None => std::future::pending().await,
430 }
431 } => return SendHalt::MaxAge,
432 };
433
434 PEER_MESSAGES_COUNT
435 .with_label_values(&[our_id_str, peer_id_str, "outgoing"])
436 .inc();
437
438 if let Err(e) = connection.send(message).await {
439 return SendHalt::Failed(e);
440 }
441 }
442 }
443
444 async fn receive_loop(
447 connection: &DynP2PConnection<M>,
448 incoming_sender: &Sender<M>,
449 our_id_str: &str,
450 peer_id_str: &str,
451 ) -> anyhow::Error {
452 loop {
453 let mut frame = match connection.receive().await {
454 Ok(frame) => frame,
455 Err(e) => return e,
456 };
457
458 match frame.read_to_end().await {
459 Ok(message) => {
460 PEER_MESSAGES_COUNT
461 .with_label_values(&[our_id_str, peer_id_str, "incoming"])
462 .inc();
463
464 if incoming_sender.try_send(message).is_err() {
465 debug!(target: LOG_NET_PEER, "Incoming message channel is full");
466 }
467 }
468 Err(e) => return e,
469 }
470 }
471 }
472
473 fn refresh_status(&self, connection: &DynP2PConnection<M>) {
478 let status = P2PConnectionStatus {
479 conn_type: connection
480 .connection_type()
481 .or_else(|| self.connector.connection_type(self.peer_id)),
482 rtt: connection.rtt(),
483 };
484
485 self.status_sender.send_replace(P2PConnectionState {
486 connected: Some(status),
487 last_error: None,
488 });
489 }
490
491 fn disconnect(&self, error: anyhow::Error) -> P2PConnectionSMState<M> {
492 let last_error = error.fmt_compact_anyhow().to_string();
493
494 info!(
495 target: LOG_NET_PEER,
496 error = %last_error,
497 "Disconnected from peer"
498 );
499
500 PEER_DISCONNECT_COUNT
501 .with_label_values(&[&self.our_id_str, &self.peer_id_str])
502 .inc();
503
504 P2PConnectionSMState::Disconnected {
505 backoff: api_networking_backoff(),
506 last_error: Some(last_error),
507 }
508 }
509
510 async fn transition_disconnected(
511 &mut self,
512 mut backoff: FibonacciBackoff,
513 ) -> Option<P2PConnectionSMState<M>> {
514 tokio::select! {
515 connection = self.incoming_connections.recv() => {
516 PEER_CONNECT_COUNT
517 .with_label_values(&[self.our_id_str.as_str(), self.peer_id_str.as_str(), "incoming"])
518 .inc();
519
520 info!(target: LOG_NET_PEER, "Connected to peer");
521
522 self.connection_deadline = self.max_connection_age.map(|age| Instant::now() + age);
523
524 Some(P2PConnectionSMState::Connected(connection.ok()?))
525 },
526 () = sleep(backoff.next().expect("Unlimited retries")), if self.our_id < self.peer_id => {
528 info!(target: LOG_NET_PEER, "Attempting to reconnect to peer");
529
530 match self.connector.connect(self.peer_id).await {
531 Ok(connection) => {
532 PEER_CONNECT_COUNT
533 .with_label_values(&[self.our_id_str.as_str(), self.peer_id_str.as_str(), "outgoing"])
534 .inc();
535
536 info!(target: LOG_NET_PEER, "Connected to peer");
537
538 self.connection_deadline = self.max_connection_age.map(|age| Instant::now() + age);
539
540 Some(P2PConnectionSMState::Connected(connection))
541 }
542 Err(e) => {
543 let last_error = e.fmt_compact_anyhow().to_string();
544
545 warn!(
546 target: LOG_CONSENSUS,
547 error = %last_error,
548 "Failed to connect to peer"
549 );
550
551 Some(P2PConnectionSMState::Disconnected {
552 backoff,
553 last_error: Some(last_error),
554 })
555 }
556 }
557 },
558 }
559 }
560}