commonware-p2p 2026.4.0

Communicate with authenticated peers over encrypted connections.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use super::{Error, Receiver, Sender};
use crate::{
    authenticated::UnboundedMailbox, Address, AddressableTrackedPeers, Channel,
    PeerSetSubscription, TrackedPeers,
};
use commonware_cryptography::PublicKey;
use commonware_runtime::{Clock, Quota};
use commonware_utils::{
    channel::{fallible::FallibleExt, mpsc, oneshot, ring},
    ordered::Map,
};
use rand_distr::Normal;
use std::time::Duration;

pub enum Message<P: PublicKey, E: Clock> {
    Register {
        channel: Channel,
        public_key: P,
        quota: Quota,
        #[allow(clippy::type_complexity)]
        result: oneshot::Sender<Result<(Sender<P, E>, Receiver<P>), Error>>,
    },
    Track {
        id: u64,
        peers: TrackedPeers<P>,
    },
    PeerSet {
        id: u64,
        response: oneshot::Sender<Option<TrackedPeers<P>>>,
    },
    Subscribe {
        response: oneshot::Sender<PeerSetSubscription<P>>,
    },
    SubscribeConnected {
        response: oneshot::Sender<ring::Receiver<Vec<P>>>,
    },
    LimitBandwidth {
        public_key: P,
        egress_cap: Option<usize>,
        ingress_cap: Option<usize>,
        result: oneshot::Sender<()>,
    },
    AddLink {
        sender: P,
        receiver: P,
        sampler: Normal<f64>,
        success_rate: f64,
        result: oneshot::Sender<Result<(), Error>>,
    },
    RemoveLink {
        sender: P,
        receiver: P,
        result: oneshot::Sender<Result<(), Error>>,
    },
    Block {
        /// The public key of the peer sending the block request.
        from: P,
        /// The public key of the peer to block.
        to: P,
    },
    Blocked {
        result: oneshot::Sender<Result<Vec<(P, P)>, Error>>,
    },
}

impl<P: PublicKey, E: Clock> std::fmt::Debug for Message<P, E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Register { .. } => f.debug_struct("Register").finish_non_exhaustive(),
            Self::Track { id, .. } => f
                .debug_struct("Track")
                .field("id", id)
                .finish_non_exhaustive(),
            Self::PeerSet { id, .. } => f
                .debug_struct("PeerSet")
                .field("id", id)
                .finish_non_exhaustive(),
            Self::Subscribe { .. } => f.debug_struct("Subscribe").finish_non_exhaustive(),
            Self::SubscribeConnected { .. } => {
                f.debug_struct("SubscribeConnected").finish_non_exhaustive()
            }
            Self::LimitBandwidth { .. } => f.debug_struct("LimitBandwidth").finish_non_exhaustive(),
            Self::AddLink { .. } => f.debug_struct("AddLink").finish_non_exhaustive(),
            Self::RemoveLink { .. } => f.debug_struct("RemoveLink").finish_non_exhaustive(),
            Self::Block { from, to } => f
                .debug_struct("Block")
                .field("from", from)
                .field("to", to)
                .finish(),
            Self::Blocked { .. } => f.debug_struct("Blocked").finish_non_exhaustive(),
        }
    }
}

/// Describes a connection between two peers.
///
/// Links are unidirectional (and must be set up in both directions
/// for a bidirectional connection).
#[derive(Clone)]
pub struct Link {
    /// Mean latency for the delivery of a message.
    pub latency: Duration,

    /// Standard deviation of the latency for the delivery of a message.
    pub jitter: Duration,

    /// Probability of a message being delivered successfully (in range \[0,1\]).
    pub success_rate: f64,
}

/// Interface for modifying the simulated network.
///
/// At any point, peers can be added/removed and links
/// between said peers can be modified.
#[derive(Debug)]
pub struct Oracle<P: PublicKey, E: Clock> {
    sender: UnboundedMailbox<Message<P, E>>,
}

impl<P: PublicKey, E: Clock> Clone for Oracle<P, E> {
    fn clone(&self) -> Self {
        Self {
            sender: self.sender.clone(),
        }
    }
}

impl<P: PublicKey, E: Clock> Oracle<P, E> {
    /// Create a new instance of the oracle.
    pub(crate) const fn new(sender: UnboundedMailbox<Message<P, E>>) -> Self {
        Self { sender }
    }

    /// Create a new [Control] interface for some peer.
    pub fn control(&self, me: P) -> Control<P, E> {
        Control {
            me,
            sender: self.sender.clone(),
        }
    }

    /// Create a new [Manager].
    ///
    /// Useful for mocking [crate::authenticated::discovery].
    pub fn manager(&self) -> Manager<P, E> {
        Manager {
            oracle: self.clone(),
        }
    }

    /// Create a new [SocketManager].
    ///
    /// Useful for mocking [crate::authenticated::lookup].
    pub fn socket_manager(&self) -> SocketManager<P, E> {
        SocketManager {
            oracle: self.clone(),
        }
    }

    /// Return a list of all blocked peers.
    pub async fn blocked(&self) -> Result<Vec<(P, P)>, Error> {
        self.sender
            .0
            .request(|result| Message::Blocked { result })
            .await
            .ok_or(Error::NetworkClosed)?
    }

    /// Set bandwidth limits for a peer.
    ///
    /// Bandwidth is specified for the peer's egress (upload) and ingress (download)
    /// rates in bytes per second. Use `None` for unlimited bandwidth.
    ///
    /// Bandwidth can be specified before a peer is registered or linked.
    pub async fn limit_bandwidth(
        &self,
        public_key: P,
        egress_cap: Option<usize>,
        ingress_cap: Option<usize>,
    ) -> Result<(), Error> {
        self.sender
            .0
            .request(|result| Message::LimitBandwidth {
                public_key,
                egress_cap,
                ingress_cap,
                result,
            })
            .await
            .ok_or(Error::NetworkClosed)
    }

    /// Create a unidirectional link between two peers.
    ///
    /// Link can be called multiple times for the same sender/receiver. The latest
    /// setting will be used.
    ///
    /// Link can be called before a peer is registered or bandwidth is specified.
    pub async fn add_link(&self, sender: P, receiver: P, config: Link) -> Result<(), Error> {
        // Sanity checks
        if sender == receiver {
            return Err(Error::LinkingSelf);
        }
        if config.success_rate < 0.0 || config.success_rate > 1.0 {
            return Err(Error::InvalidSuccessRate(config.success_rate));
        }

        // Convert Duration to milliseconds as f64 for the Normal distribution
        let latency_ms = config.latency.as_secs_f64() * 1000.0;
        let jitter_ms = config.jitter.as_secs_f64() * 1000.0;

        // Create distribution
        let sampler = Normal::new(latency_ms, jitter_ms).unwrap();

        self.sender
            .0
            .request(|result| Message::AddLink {
                sender,
                receiver,
                sampler,
                success_rate: config.success_rate,
                result,
            })
            .await
            .ok_or(Error::NetworkClosed)?
    }

    /// Remove a unidirectional link between two peers.
    ///
    /// If no link exists, this will return an error.
    pub async fn remove_link(&self, sender: P, receiver: P) -> Result<(), Error> {
        // Sanity checks
        if sender == receiver {
            return Err(Error::LinkingSelf);
        }

        self.sender
            .0
            .request(|result| Message::RemoveLink {
                sender,
                receiver,
                result,
            })
            .await
            .ok_or(Error::NetworkClosed)?
    }

    /// Set the peers for a given id.
    fn track(&self, id: u64, peers: TrackedPeers<P>) {
        self.sender.0.send_lossy(Message::Track { id, peers });
    }

    /// Get the primary and secondary peers for a given ID.
    async fn peer_set(&self, id: u64) -> Option<TrackedPeers<P>> {
        self.sender
            .0
            .request(|response| Message::PeerSet { id, response })
            .await
            .flatten()
    }

    /// Subscribe to notifications when new peer sets are added.
    async fn subscribe(&self) -> PeerSetSubscription<P> {
        self.sender
            .0
            .request(|response| Message::Subscribe { response })
            .await
            .unwrap_or_else(|| {
                let (_, rx) = mpsc::unbounded_channel();
                rx
            })
    }
}

/// Implementation of [crate::Manager] for peers.
///
/// Useful for mocking [crate::authenticated::discovery].
pub struct Manager<P: PublicKey, E: Clock> {
    /// The oracle to send messages to.
    oracle: Oracle<P, E>,
}

impl<P: PublicKey, E: Clock> std::fmt::Debug for Manager<P, E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Manager").finish_non_exhaustive()
    }
}

impl<P: PublicKey, E: Clock> Clone for Manager<P, E> {
    fn clone(&self) -> Self {
        Self {
            oracle: self.oracle.clone(),
        }
    }
}

impl<P: PublicKey, E: Clock> crate::Provider for Manager<P, E> {
    type PublicKey = P;

    async fn peer_set(&mut self, id: u64) -> Option<TrackedPeers<Self::PublicKey>> {
        self.oracle.peer_set(id).await
    }

    async fn subscribe(&mut self) -> PeerSetSubscription<Self::PublicKey> {
        self.oracle.subscribe().await
    }
}

impl<P: PublicKey, E: Clock> crate::Manager for Manager<P, E> {
    async fn track<R>(&mut self, id: u64, peers: R)
    where
        R: Into<TrackedPeers<Self::PublicKey>> + Send,
    {
        self.oracle.track(id, peers.into());
    }
}

/// Implementation of [crate::AddressableManager] for peers with [Address]es.
///
/// Useful for mocking [crate::authenticated::lookup].
///
/// # Note on [Address]
///
/// Because addresses are never exposed in [crate::simulated],
/// there is nothing to assert submitted data against. We thus consider
/// all addresses to be valid.
pub struct SocketManager<P: PublicKey, E: Clock> {
    /// The oracle to send messages to.
    oracle: Oracle<P, E>,
}

impl<P: PublicKey, E: Clock> std::fmt::Debug for SocketManager<P, E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SocketManager").finish_non_exhaustive()
    }
}

impl<P: PublicKey, E: Clock> Clone for SocketManager<P, E> {
    fn clone(&self) -> Self {
        Self {
            oracle: self.oracle.clone(),
        }
    }
}

impl<P: PublicKey, E: Clock> crate::Provider for SocketManager<P, E> {
    type PublicKey = P;

    async fn peer_set(&mut self, id: u64) -> Option<TrackedPeers<Self::PublicKey>> {
        self.oracle.peer_set(id).await
    }

    async fn subscribe(&mut self) -> PeerSetSubscription<P> {
        self.oracle.subscribe().await
    }
}

impl<P: PublicKey, E: Clock> crate::AddressableManager for SocketManager<P, E> {
    async fn track<R>(&mut self, id: u64, peers: R)
    where
        R: Into<AddressableTrackedPeers<Self::PublicKey>> + Send,
    {
        // Ignore all addresses (simulated network doesn't use them)
        let peers = peers.into();
        self.oracle.track(
            id,
            TrackedPeers::new(peers.primary.into_keys(), peers.secondary.into_keys()),
        );
    }

    async fn overwrite(&mut self, _peers: Map<Self::PublicKey, Address>) {
        // We consider all addresses to be valid, so this is a no-op
    }
}

/// Individual control interface for a peer in the simulated network.
#[derive(Debug)]
pub struct Control<P: PublicKey, E: Clock> {
    /// The public key of the peer this control interface is for.
    me: P,

    /// Sender for messages to the oracle.
    sender: UnboundedMailbox<Message<P, E>>,
}

impl<P: PublicKey, E: Clock> Clone for Control<P, E> {
    fn clone(&self) -> Self {
        Self {
            me: self.me.clone(),
            sender: self.sender.clone(),
        }
    }
}

impl<P: PublicKey, E: Clock> Control<P, E> {
    /// Register the communication interfaces for the peer over a given [Channel].
    ///
    /// # Rate Limiting
    ///
    /// The `quota` parameter specifies the rate limit for outbound messages to each peer.
    /// Recipients that exceed their rate limit will be skipped when sending.
    pub async fn register(
        &self,
        channel: Channel,
        quota: Quota,
    ) -> Result<(Sender<P, E>, Receiver<P>), Error> {
        let public_key = self.me.clone();
        self.sender
            .0
            .request(|result| Message::Register {
                channel,
                public_key,
                quota,
                result,
            })
            .await
            .ok_or(Error::NetworkClosed)?
    }
}

impl<P: PublicKey, E: Clock> crate::Blocker for Control<P, E> {
    type PublicKey = P;

    async fn block(&mut self, public_key: P) {
        self.sender.0.send_lossy(Message::Block {
            from: self.me.clone(),
            to: public_key,
        });
    }
}