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
use async_trait::async_trait;
use mpc_protocol::SessionId;
use serde::Serialize;

use crate::{Client, ClientOptions, EventLoop, Result};

/// Enumeration of available transports.
#[derive(Clone)]
pub enum Transport {
    /// Relay websocket client.
    Relay(Client),
    // NOTE: later we will add a Peer variant using
    // NOTE: a WebRTC data channel for communication
}

impl From<Client> for Transport {
    fn from(value: Client) -> Self {
        Self::Relay(value)
    }
}

#[async_trait]
impl NetworkTransport for Transport {
    fn public_key(&self) -> &[u8] {
        match self {
            Transport::Relay(client) => client.public_key(),
        }
    }

    async fn connect(&mut self) -> Result<()> {
        match self {
            Transport::Relay(client) => client.connect().await,
        }
    }

    async fn connect_peer(
        &mut self,
        public_key: &[u8],
    ) -> Result<()> {
        match self {
            Transport::Relay(client) => {
                client.connect_peer(public_key).await
            }
        }
    }

    async fn send_json<S>(
        &mut self,
        public_key: &[u8],
        payload: &S,
        session_id: Option<SessionId>,
    ) -> Result<()>
    where
        S: Serialize + Send + Sync + ?Sized,
    {
        match self {
            Transport::Relay(client) => {
                client
                    .send_json(public_key, payload, session_id)
                    .await
            }
        }
    }

    async fn send_blob(
        &mut self,
        public_key: &[u8],
        payload: Vec<u8>,
        session_id: Option<SessionId>,
    ) -> Result<()> {
        match self {
            Transport::Relay(client) => {
                client
                    .send_blob(public_key, payload, session_id)
                    .await
            }
        }
    }

    async fn new_session(
        &mut self,
        participant_keys: Vec<Vec<u8>>,
        session_id: Option<SessionId>,
    ) -> Result<()> {
        match self {
            Transport::Relay(client) => {
                client.new_session(participant_keys, session_id).await
            }
        }
    }

    async fn register_connection(
        &mut self,
        session_id: &SessionId,
        peer_key: &[u8],
    ) -> Result<()> {
        match self {
            Transport::Relay(client) => {
                client.register_connection(session_id, peer_key).await
            }
        }
    }

    async fn close_session(
        &mut self,
        session_id: SessionId,
    ) -> Result<()> {
        match self {
            Transport::Relay(client) => {
                client.close_session(session_id).await
            }
        }
    }

    async fn broadcast_json<S>(
        &mut self,
        session_id: &SessionId,
        recipient_public_keys: &[Vec<u8>],
        payload: &S,
    ) -> Result<()>
    where
        S: Serialize + Send + Sync + ?Sized,
    {
        match self {
            Transport::Relay(client) => {
                client
                    .broadcast_json(
                        session_id,
                        recipient_public_keys,
                        payload,
                    )
                    .await
            }
        }
    }

    async fn broadcast_blob(
        &mut self,
        session_id: &SessionId,
        recipient_public_keys: &[Vec<u8>],
        payload: Vec<u8>,
    ) -> Result<()> {
        match self {
            Transport::Relay(client) => {
                client
                    .broadcast_blob(
                        session_id,
                        recipient_public_keys,
                        payload,
                    )
                    .await
            }
        }
    }

    async fn close(&self) -> Result<()> {
        match self {
            Transport::Relay(client) => client.close().await,
        }
    }
}

impl Transport {
    /// Create a new relay client.
    pub async fn new_relay(
        server: &str,
        options: ClientOptions,
    ) -> Result<(Self, EventLoop)> {
        let (client, event_loop) =
            Client::new(server, options).await?;
        Ok((Self::Relay(client), event_loop))
    }
}

/// Trait for network clients.
#[async_trait]
pub trait NetworkTransport {
    /// Public key for this client.
    fn public_key(&self) -> &[u8];

    /// Perform initial handshake with the server.
    async fn connect(&mut self) -> Result<()>;

    /// Handshake with a peer.
    ///
    /// Peer already exists error is returned if this
    /// client is already connecting to the peer.
    async fn connect_peer(&mut self, public_key: &[u8])
        -> Result<()>;

    /// Send a JSON message to a peer.
    async fn send_json<S>(
        &mut self,
        public_key: &[u8],
        payload: &S,
        session_id: Option<SessionId>,
    ) -> Result<()>
    where
        S: Serialize + Send + Sync + ?Sized;

    /// Send a binary message to a peer.
    async fn send_blob(
        &mut self,
        public_key: &[u8],
        payload: Vec<u8>,
        session_id: Option<SessionId>,
    ) -> Result<()>;

    /// Create a new session.
    ///
    /// Do not include the public key of the initiator for the new
    /// session; it is automatically included as the session owner.
    async fn new_session(
        &mut self,
        participant_keys: Vec<Vec<u8>>,
        session_id: Option<SessionId>,
    ) -> Result<()>;

    /// Register a peer connection in a session.
    async fn register_connection(
        &mut self,
        session_id: &SessionId,
        peer_key: &[u8],
    ) -> Result<()>;

    /// Close a session.
    async fn close_session(
        &mut self,
        session_id: SessionId,
    ) -> Result<()>;

    /// Broadcast a JSON message in the context of a session.
    async fn broadcast_json<S>(
        &mut self,
        session_id: &SessionId,
        recipient_public_keys: &[Vec<u8>],
        payload: &S,
    ) -> Result<()>
    where
        S: Serialize + Send + Sync + ?Sized;

    /// Broadcast a binary message in the context of a session.
    async fn broadcast_blob(
        &mut self,
        session_id: &SessionId,
        recipient_public_keys: &[Vec<u8>],
        payload: Vec<u8>,
    ) -> Result<()>;

    /// Close the socket connection.
    async fn close(&self) -> Result<()>;
}