fedimint_core/net/peers/
fake.rs

1use async_channel::bounded;
2/// Fake (channel-based) implementation of [`super::DynP2PConnections`].
3use async_trait::async_trait;
4use fedimint_core::PeerId;
5use fedimint_core::net::peers::{DynP2PConnections, IP2PConnections};
6
7use crate::net::peers::Recipient;
8
9#[derive(Clone)]
10struct FakePeerConnections<M> {
11    tx: async_channel::Sender<M>,
12    rx: async_channel::Receiver<M>,
13    peer: PeerId,
14}
15
16#[async_trait]
17impl<M: Clone + Send + 'static> IP2PConnections<M> for FakePeerConnections<M> {
18    fn send(&self, recipient: Recipient, msg: M) {
19        assert_eq!(recipient, Recipient::Peer(self.peer));
20
21        // If the peer is gone, just pretend we are going to resend
22        // the msg eventually, even if it will never happen.
23        self.tx.try_send(msg).ok();
24    }
25
26    async fn receive(&self) -> Option<(PeerId, M)> {
27        self.rx.recv().await.map(|msg| (self.peer, msg)).ok()
28    }
29
30    async fn receive_from_peer(&self, _peer: PeerId) -> Option<M> {
31        self.rx.recv().await.ok()
32    }
33}
34
35/// Create a fake link between `peer1` and `peer2` for test purposes
36///
37/// `buf_size` controls the size of the `tokio::mpsc::channel` used
38/// under the hood (both ways).
39pub fn make_fake_peer_connection<M: Clone + Send + 'static>(
40    peer_1: PeerId,
41    peer_2: PeerId,
42    buf_size: usize,
43) -> (DynP2PConnections<M>, DynP2PConnections<M>) {
44    let (tx1, rx1) = bounded(buf_size);
45    let (tx2, rx2) = bounded(buf_size);
46
47    let c_1 = FakePeerConnections {
48        tx: tx1,
49        rx: rx2,
50        peer: peer_2,
51    };
52
53    let c_2 = FakePeerConnections {
54        tx: tx2,
55        rx: rx1,
56        peer: peer_1,
57    };
58
59    (c_1.into_dyn(), c_2.into_dyn())
60}