fedimint_core/net/
peers.rs1use std::ops::{Deref, DerefMut};
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use fedimint_core::PeerId;
6use serde::de::DeserializeOwned;
7use serde::Serialize;
8
9use crate::task::Cancellable;
10
11#[cfg(not(target_family = "wasm"))]
12pub mod fake;
13
14pub struct PeerConnections<Msg>(Box<dyn IPeerConnections<Msg> + Send + Unpin + 'static>);
16
17impl<Msg> Deref for PeerConnections<Msg> {
18 type Target = dyn IPeerConnections<Msg> + Send + Unpin + 'static;
19
20 fn deref(&self) -> &Self::Target {
21 &*self.0
22 }
23}
24
25impl<Msg> DerefMut for PeerConnections<Msg> {
26 fn deref_mut(&mut self) -> &mut Self::Target {
27 &mut *self.0
28 }
29}
30
31#[async_trait]
45pub trait IPeerConnections<Msg>
46where
47 Msg: Serialize + DeserializeOwned + Unpin + Send,
48{
49 async fn send(&mut self, peers: &[PeerId], msg: Msg) -> Cancellable<()>;
54
55 async fn receive(&mut self) -> Cancellable<(PeerId, Msg)>;
57
58 async fn ban_peer(&mut self, peer: PeerId);
60
61 fn into_dyn(self) -> PeerConnections<Msg>
63 where
64 Self: Sized + Send + Unpin + 'static,
65 {
66 PeerConnections(Box::new(self))
67 }
68}
69
70#[derive(Clone)]
72pub struct MuxPeerConnections<MuxKey, Msg>(
73 Arc<dyn IMuxPeerConnections<MuxKey, Msg> + Send + Sync + Unpin + 'static>,
74);
75
76impl<MuxKey, Msg> Deref for MuxPeerConnections<MuxKey, Msg> {
77 type Target = dyn IMuxPeerConnections<MuxKey, Msg> + Send + Sync + Unpin + 'static;
78
79 fn deref(&self) -> &Self::Target {
80 &*self.0
81 }
82}
83
84#[async_trait]
85pub trait IMuxPeerConnections<MuxKey, Msg>
92where
93 Msg: Serialize + DeserializeOwned + Unpin + Send,
94 MuxKey: Serialize + DeserializeOwned + Unpin + Send,
95{
96 async fn send(&self, peers: &[PeerId], mux_key: MuxKey, msg: Msg) -> Cancellable<()>;
98
99 async fn receive(&self, mux_key: MuxKey) -> Cancellable<(PeerId, Msg)>;
101
102 async fn ban_peer(&self, peer: PeerId);
104
105 fn into_dyn(self) -> MuxPeerConnections<MuxKey, Msg>
107 where
108 Self: Sized + Send + Sync + Unpin + 'static,
109 {
110 MuxPeerConnections(Arc::new(self))
111 }
112}