sl_mpc_mate/
coord.rs

1// Copyright (c) Silence Laboratories Pte. Ltd. All Rights Reserved.
2// This software is licensed under the Silence Laboratories License Agreement.
3
4use std::{
5    future::Future,
6    pin::Pin,
7    task::{Context, Poll},
8};
9
10pub use futures_util::{sink::Feed, Sink, SinkExt, Stream, StreamExt};
11
12use crate::message::*;
13
14mod buffered;
15
16pub mod stats;
17
18#[cfg(feature = "simple-relay")]
19pub mod adversary;
20#[cfg(feature = "simple-relay")]
21pub mod simple;
22#[cfg(feature = "simple-relay")]
23pub use simple::SimpleMessageRelay;
24
25pub use buffered::BufferedMsgRelay;
26
27#[derive(Debug, Copy, Clone)]
28pub struct MessageSendError;
29
30pub struct MaybeFeed<'a, S: ?Sized>(Option<Feed<'a, S, Vec<u8>>>);
31
32impl<'a, Si: Sink<Vec<u8>> + Unpin> MaybeFeed<'a, Si> {
33    pub fn new(feed: Feed<'a, Si, Vec<u8>>) -> Self {
34        Self(Some(feed))
35    }
36
37    pub fn skip() -> Self {
38        Self(None)
39    }
40}
41
42impl<Si: Sink<Vec<u8>> + Unpin> Future for MaybeFeed<'_, Si> {
43    type Output = Result<(), Si::Error>;
44
45    fn poll(
46        self: Pin<&mut Self>,
47        cx: &mut Context<'_>,
48    ) -> Poll<Self::Output> {
49        match &mut self.get_mut().0 {
50            None => Poll::Ready(Ok(())),
51            Some(feed) => Pin::new(feed).poll(cx),
52        }
53    }
54}
55
56pub trait Relay:
57    Stream<Item = Vec<u8>> + Sink<Vec<u8>, Error = MessageSendError> + Unpin
58{
59    fn ask(&mut self, id: &MsgId, ttl: u32) -> MaybeFeed<'_, Self> {
60        MaybeFeed(Some(self.feed(AskMsg::allocate(id, ttl))))
61    }
62}
63
64pub trait MessageRelayService {
65    type MessageRelay: Relay;
66
67    fn connect(&self) -> impl Future<Output = Option<Self::MessageRelay>>;
68}