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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use colored::*;
use futures::{
future::lazy,
sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
Future, Stream,
};
use std::collections::HashMap;
use uuid::Uuid;
use ws::{CloseCode, Handler, Handshake, Message, Request, Response, Result as WsResult, Sender, connect};
use epicboxlib::error::{ErrorKind, Result};
use epicboxlib::types::{EpicboxAddress, EpicboxError, EpicboxRequest, EpicboxResponse};
use epicboxlib::utils::crypto::{verify_signature, Base58, Hex};
use epicboxlib::utils::secp::{PublicKey, Signature};
use crate::broker::{BrokerRequest, BrokerResponse};
static MAX_SUBSCRIPTIONS: usize = 1;
pub struct BrokerResponseHandler {
inner: std::sync::Arc<std::sync::Mutex<Server>>,
response_receiver: UnboundedReceiver<BrokerResponse>,
}
pub struct AsyncServer {
id: String,
inner: std::sync::Arc<std::sync::Mutex<Server>>,
nats_sender: UnboundedSender<BrokerRequest>,
response_handlers_sender: UnboundedSender<BrokerResponseHandler>,
subscriptions: HashMap<String, Subscription>,
epicbox_domain: String,
epicbox_port: u16,
epicbox_protocol_unsecure: bool,
}
pub struct Server {
id: String,
out: Sender,
}
struct Subscription {}
#[derive(Serialize, Deserialize, Debug)]
struct SignedPayload {
str: String,
challenge: String,
signature: String,
}
impl Drop for AsyncServer {
fn drop(&mut self) {
for (subject, _subscription) in &self.subscriptions {
if self
.nats_sender
.unbounded_send(BrokerRequest::Unsubscribe {
id: self.id.clone(),
})
.is_err()
{
error!("failed to unsubscribe while dropping server!");
};
}
}
}
impl AsyncServer {
pub fn new(
out: Sender,
nats_sender: UnboundedSender<BrokerRequest>,
response_handlers_sender: UnboundedSender<BrokerResponseHandler>,
epicbox_domain: &str,
epicbox_port: u16,
epicbox_protocol_unsecure: bool,
) -> AsyncServer {
let id = Uuid::new_v4().to_string();
let server = Server {
id: id.clone(),
out,
};
AsyncServer {
id: id.clone(),
inner: std::sync::Arc::new(std::sync::Mutex::new(server)),
nats_sender,
response_handlers_sender,
subscriptions: HashMap::new(),
epicbox_domain: epicbox_domain.to_string(),
epicbox_port,
epicbox_protocol_unsecure,
}
}
pub fn init() -> UnboundedSender<BrokerResponseHandler> {
let (fut_tx, fut_rx) = unbounded::<BrokerResponseHandler>();
std::thread::spawn(move || {
info!("broker handler started");
let fut_loop = fut_rx
.for_each(move |handler| {
let clone = handler.inner.clone();
let response_loop = handler.response_receiver.for_each(move |m| {
match m {
BrokerResponse::Message {
subject: _,
payload,
reply_to,
} => {
let signed_payload =
serde_json::from_str::<SignedPayload>(&payload);
if signed_payload.is_ok() {
let signed_payload = signed_payload.unwrap();
let response = EpicboxResponse::Slate {
from: reply_to,
str: signed_payload.str,
challenge: signed_payload.challenge,
signature: signed_payload.signature,
};
let guard = clone.lock().unwrap();
let ref server = *guard;
info!("[{}] <- {}", server.id.bright_green(), response);
if server
.out
.send(serde_json::to_string(&response).unwrap())
.is_err()
{
error!("failed sending slate to client!");
};
} else {
error!("invalid payload!");
}
}
}
Ok(())
});
std::thread::spawn(move || {
tokio::run(lazy(|| {
tokio::spawn(response_loop);
Ok(())
}));
});
Ok(())
})
.map_err(|_| {});
tokio::run(lazy(move || tokio::spawn(fut_loop)));
debug!("future thread ended...");
});
fut_tx
}
fn error(kind: EpicboxError) -> EpicboxResponse {
let description = format!("{}", kind);
EpicboxResponse::Error { kind, description }
}
fn ok() -> EpicboxResponse {
EpicboxResponse::Ok
}
fn get_challenge_raw(&self) -> &str {
"7WUDtkSaKyGRUnQ22rE3QUXChV8DmA6NnunDYP4vheTpc"
}
fn get_challenge(&self) -> EpicboxResponse {
EpicboxResponse::Challenge {
str: String::from(self.get_challenge_raw()),
}
}
fn verify_signature(&self, public_key: &str, challenge: &str, signature: &str) -> Result<()> {
let (public_key, _) = PublicKey::from_base58_check_raw(public_key, 2)?;
let signature = Signature::from_hex(signature)?;
verify_signature(challenge, &signature, &public_key)
.map_err(|_| ErrorKind::EpicboxProtocolError(EpicboxError::InvalidSignature))?;
Ok(())
}
fn subscribe(&mut self, address: String, signature: String) -> EpicboxResponse {
let result = self.verify_signature(&address, self.get_challenge_raw(), &signature);
match result {
Ok(()) => {
if self.subscriptions.len() == MAX_SUBSCRIPTIONS {
AsyncServer::error(EpicboxError::TooManySubscriptions)
} else {
let (res_tx, res_rx) = unbounded::<BrokerResponse>();
if self
.nats_sender
.unbounded_send(BrokerRequest::Subscribe {
id: self.id.clone(),
subject: address.clone(),
response_sender: res_tx,
})
.is_err()
{
error!("could not issue subscribe request!");
return AsyncServer::error(EpicboxError::UnknownError);
};
if self
.response_handlers_sender
.unbounded_send(BrokerResponseHandler {
inner: self.inner.clone(),
response_receiver: res_rx,
})
.is_err()
{
error!("could not register subscription handler!");
return AsyncServer::error(EpicboxError::UnknownError);
};
self.subscriptions.insert(address.clone(), Subscription {});
AsyncServer::ok()
}
}
Err(_) => AsyncServer::error(EpicboxError::UnknownError),
}
}
fn unsubscribe(&mut self, address: String) -> EpicboxResponse {
let result = self.subscriptions.remove(&address);
match result {
Some(_subscription) => {
if self
.nats_sender
.unbounded_send(BrokerRequest::Unsubscribe {
id: self.id.clone(),
})
.is_err()
{
error!("could not unsubscribe!");
return AsyncServer::error(EpicboxError::UnknownError);
};
AsyncServer::ok()
}
None => AsyncServer::error(EpicboxError::InvalidRequest),
}
}
fn post_slate(
&self,
from: String,
to: String,
str: String,
signature: String,
message_expiration_in_seconds: Option<u32>,
) -> EpicboxResponse {
let from_address = EpicboxAddress::from_str_raw(&from);
if from_address.is_err() {
return AsyncServer::error(EpicboxError::InvalidRequest);
}
let from_address = from_address.unwrap();
let to_address = EpicboxAddress::from_str_raw(&to);
if to_address.is_err() {
return AsyncServer::error(EpicboxError::InvalidRequest);
}
let to_address = to_address.unwrap();
let mut challenge = String::new();
challenge.push_str(&str);
let mut result =
self.verify_signature(&from_address.public_key, &challenge, &signature);
let mut challenge_raw = "";
if result.is_err() {
challenge.push_str(self.get_challenge_raw());
challenge_raw = self.get_challenge_raw();
result = self.verify_signature(&from_address.public_key, &challenge, &signature);
}
if result.is_err() {
return AsyncServer::error(EpicboxError::InvalidSignature);
}
if to_address.port == self.epicbox_port && to_address.domain == self.epicbox_domain {
let signed_payload = SignedPayload {
str,
challenge: challenge_raw.to_string(),
signature,
};
let signed_payload = serde_json::to_string(&signed_payload).unwrap();
if self
.nats_sender
.unbounded_send(BrokerRequest::PostMessage {
subject: to_address.public_key,
payload: signed_payload,
reply_to: from_address.stripped(),
message_expiration_in_seconds,
})
.is_err()
{
error!("could not post message to broker!");
return AsyncServer::error(EpicboxError::UnknownError);
};
AsyncServer::ok()
} else {
self.post_slate_federated(&from_address, &to_address, str, signature, message_expiration_in_seconds)
}
}
fn post_slate_federated(&self, from_address: &EpicboxAddress, to_address: &EpicboxAddress, str: String, signature: String, message_expiration_in_seconds: Option<u32>) -> EpicboxResponse {
let url = match self.epicbox_protocol_unsecure {
false => format!(
"wss://{}:{}",
to_address.domain,
to_address.port
),
true => format!(
"ws://{}:{}",
to_address.domain,
to_address.port
)
};
let str = str.clone();
let signature = signature.clone();
let result = connect(url, move |sender| {
let str = str.clone();
let signature = signature.clone();
move |msg: Message| {
let response = serde_json::from_str::<EpicboxResponse>(&msg.to_string())
.expect("could not parse response!");
match response {
EpicboxResponse::Challenge { str: _ } => {
let request = EpicboxRequest::PostSlate {
from: from_address.stripped(),
to: to_address.stripped(),
str: str.clone(),
signature: signature.clone(),
message_expiration_in_seconds,
};
sender
.send(serde_json::to_string(&request).unwrap())
.unwrap();
}
EpicboxResponse::Error {
kind: _,
description: _,
} => {
sender.close(CloseCode::Abnormal).is_ok();
}
EpicboxResponse::Ok => {
sender.close(CloseCode::Normal).is_ok();
}
_ => {}
}
Ok(())
}
});
match result {
Ok(()) => AsyncServer::ok(),
Err(_) => AsyncServer::error(EpicboxError::UnknownError),
}
}
}
impl Handler for AsyncServer {
fn on_request(&mut self, req: &Request) -> WsResult<Response> {
let res = Response::from_request(req);
if let Err(_) = res {
let response = Response::new(200, "", vec![]);
Ok(response)
} else {
Ok(res.unwrap())
}
}
fn on_open(&mut self, _: Handshake) -> WsResult<()> {
info!(
"[{}] {}",
self.id.bright_green(),
"connection established".bright_purple()
);
let response = self.get_challenge();
debug!("[{}] <- {}", self.id.bright_green(), response);
let server = self.inner.lock().unwrap();
if server
.out
.send(serde_json::to_string(&response).unwrap())
.is_err()
{
error!("could not send challenge to client!");
};
Ok(())
}
fn on_message(&mut self, msg: Message) -> WsResult<()> {
let request = serde_json::from_str(&msg.to_string());
let response = if request.is_ok() {
let request = request.unwrap();
info!("[{}] -> {}", self.id.bright_green(), request);
match request {
EpicboxRequest::Challenge => self.get_challenge(),
EpicboxRequest::Subscribe { address, signature } => {
self.subscribe(address, signature)
}
EpicboxRequest::PostSlate {
from,
to,
str,
signature,
message_expiration_in_seconds,
} => self.post_slate(from, to, str, signature, message_expiration_in_seconds),
EpicboxRequest::Unsubscribe { address } => self.unsubscribe(address),
}
} else {
debug!(
"[{}] -> {}",
self.id.bright_green(),
"invalid request!".bright_red()
);
AsyncServer::error(EpicboxError::InvalidRequest)
};
info!("[{}] <- {}", self.id.bright_green(), response);
let server = self.inner.lock().unwrap();
server.out.send(serde_json::to_string(&response).unwrap())
}
fn on_close(&mut self, code: CloseCode, _reason: &str) {
let code = format!("{:?}", code);
info!(
"[{}] {} [{}]",
self.id.bright_green(),
"connection dropped".bright_purple(),
code.bright_green()
);
}
fn on_error(&mut self, err: ws::Error) {
error!("the server encountered an error: {:?}", err);
}
}