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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
|
use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
use base64::engine::{Engine, general_purpose::STANDARD as BASE64};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use thiserror::Error;
use url::Url;
use crate::transport::wire;
use crate::transport::{
Addressed, EncodedMessage, HandlerFn, MessageHandler, ParsedMessage, Transport, hand_on_probe,
is_probe,
};
pub(crate) mod daemon;
#[cfg(test)]
mod fake_daemon;
#[cfg(test)]
mod real_daemons;
pub(crate) use daemon::{MyceliumSetup, MyceliumSpawnConfig};
/// The scheme of this transport's addresses (`transport::paths`).
pub(crate) const SCHEME: &str = "mycelium";
/// How long a request for the inbox waits in the daemon for a message (`poll_inbox`).
const MYCELIUM_POLL_TIMEOUT_SECS: u64 = 300;
/// How long Mycelium tries to deliver a message before dropping it.
const DELIVERY_LIMIT: Duration = Duration::from_secs(300);
/// The largest inbound message read (its JSON, base64 payload included: about 190 MiB of
/// payload). Anyone can send us anything; this bounds what one message costs before it
/// is even parsed. Generous, because a sync message can carry a whole history until
/// large deltas travel as blobs.
const MAX_INBOUND_BYTES: usize = 256 << 20;
/// How long a request to our Mycelium may take, before what its body adds
/// (`post_timeout`).
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
/// The slowest our Mycelium is expected to take a message body, in bytes per second:
/// a large sync message gets more time than a STATUS, instead of failing (and being
/// generated and sent whole again) at a fixed limit.
const POST_MIN_RATE: u64 = 1 << 20;
/// The one Mycelium topic all of continuum's messages travel on; what a message is, its
/// payload says (`wire`).
const TOPIC: &str = "continuum";
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct InboundMessage {
id: String,
src_pk: String,
topic: String,
payload: String,
}
// Deserialize only for debugging
#[derive(Debug, Serialize, Deserialize)]
struct OutboundMessage {
dst: Destination,
topic: String,
payload: String,
}
// Deserialize only for debugging
#[derive(Debug, Serialize, Deserialize)]
struct Destination {
pk: String,
}
/// The part of Mycelium's `/api/v1/admin` answer we use.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub(crate) struct MyceliumAdminInfo {
pub(crate) node_pubkey: String,
}
fn is_pubkey(s: &str) -> bool {
s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())
}
pub(crate) struct MyceliumTransport {
/// The daemon, kept to wait for its exit.
setup: tokio::sync::Mutex<MyceliumSetup>,
client: reqwest::Client,
/// For the long-polling inbox (its timeout is longer).
poll_client: reqwest::Client,
messages_endpoint: Url,
pubkey_basepath: Url,
local_id: String,
/// Whose messages may be large (`transport::Admission`).
admission: std::sync::OnceLock<crate::transport::Admission>,
/// Requests to the daemon under way besides the inbox's (`Turn`): while any is, the
/// inbox's poller doesn't wait in the daemon (`poll_inbox`).
others: tokio::sync::watch::Sender<usize>,
}
/// A request to the daemon besides the inbox's, under way while this lives (`others`).
struct Turn<'a>(&'a tokio::sync::watch::Sender<usize>);
impl<'a> Turn<'a> {
fn taken(others: &'a tokio::sync::watch::Sender<usize>) -> Self {
others.send_modify(|n| *n += 1);
Turn(others)
}
}
impl Drop for Turn<'_> {
fn drop(&mut self) {
self.0.send_modify(|n| *n -= 1);
}
}
/// This transport's options, checked when the configuration is loaded
/// (`config::Settings::check`): a daemon elsewhere (`mycelium-rest-url`) by a URL, and
/// none of the options only a supervised one takes with it; a private network with
/// both its key and its name.
pub(crate) fn check(settings: &crate::config::Settings) -> Result<()> {
if let Some(url) = &settings.mycelium_rest_url {
Url::parse(url).with_context(|| format!("mycelium-rest-url {url:?}"))?;
if let Some((name, _)) = supervised_only(settings).iter().find(|(_, set)| *set) {
anyhow::bail!(
"{name} is for a supervised Mycelium daemon and can't be combined with mycelium-rest-url"
);
}
}
if settings.mycelium_key_create && settings.mycelium_key_file.is_none() {
anyhow::bail!("mycelium-key-create creates the key at mycelium-key-file; set that too");
}
// A private network has both; one alone would be ignored or invented.
if settings.mycelium_network_key_file.is_some() != settings.mycelium_network_name.is_some() {
anyhow::bail!("mycelium-network-key-file and mycelium-network-name go together");
}
Ok(())
}
/// The options only a supervised Mycelium daemon takes, and whether each is set: the
/// other side of `config::CONFLICTS`' `mycelium-rest-url` (a test keeps them the same).
pub(crate) fn supervised_only(settings: &crate::config::Settings) -> [(&'static str, bool); 5] {
[
("mycelium-key-file", settings.mycelium_key_file.is_some()),
("mycelium-key-create", settings.mycelium_key_create),
(
"mycelium-network-key-file",
settings.mycelium_network_key_file.is_some(),
),
(
"mycelium-network-name",
settings.mycelium_network_name.is_some(),
),
(
"mycelium-tcp-listen-port",
settings.mycelium_tcp_listen_port.is_some(),
),
]
}
/// The transport as `settings` configure it (`transport::start`): its daemon supervised
/// (started, which can take a while) or one running elsewhere. None if `stop` came
/// first.
pub(crate) async fn start(
settings: &crate::config::Settings,
mut stop: tokio::sync::watch::Receiver<bool>,
) -> Result<Option<MyceliumTransport>> {
// The daemon's key, 32 raw bytes (as `daemon` hands it an ephemeral one): read,
// or made, here, so a missing file fails before the daemon starts.
if let Some(path) = &settings.mycelium_key_file {
let (bytes, created) = crate::files::key_file(
path,
"Mycelium key",
settings.mycelium_key_create,
"mycelium-key-create",
"a new Mycelium address",
32,
)?;
if bytes.len() != 32 {
anyhow::bail!(
"The Mycelium key in {} has {} bytes; it has 32",
path.display(),
bytes.len()
);
}
if created {
tracing::info!(path = %path.display(), "Created a new Mycelium key");
}
}
let spawn_config = MyceliumSpawnConfig {
rest_url_opt: settings
.mycelium_rest_url
.as_deref()
.and_then(|url| Url::parse(url).ok()),
key_file_opt: settings.mycelium_key_file.clone(),
network_key_file: settings.mycelium_network_key_file.clone(),
network_name: settings.mycelium_network_name.clone(),
tcp_port: settings.mycelium_tcp_listen_port,
peers: settings.mycelium_peers.clone(),
};
let setup = tokio::select! {
setup = MyceliumSetup::bootstrap(spawn_config) => setup?,
_ = stop.wait_for(|stop| *stop) => return Ok(None),
};
// Without a password it may carry (the option is secret).
let mut shown_url = setup.rest_url.clone();
let _ = shown_url.set_password(None);
tracing::debug!(url = shown_url.to_string(), "Using Mycelium REST API");
tokio::select! {
transport = MyceliumTransport::connect(setup) => Ok(Some(transport?)),
_ = stop.wait_for(|stop| *stop) => Ok(None),
}
}
/// How long the daemon's API may take to come up: a daemon just started listens a
/// moment later (`admin_info`).
const API_READY_WITHIN: Duration = Duration::from_secs(30);
/// The daemon's identity, from its API at `url` (`/api/v1/admin`), once the API answers:
/// a daemon we just started doesn't listen yet, so refused connections are tried again
/// (50 ms, doubling up to a second) for `API_READY_WITHIN`; anything else is an error.
async fn admin_info(client: &reqwest::Client, url: Url) -> Result<MyceliumAdminInfo> {
let deadline = tokio::time::Instant::now() + API_READY_WITHIN;
let mut wait = Duration::from_millis(50);
loop {
match client.get(url.clone()).send().await {
Ok(response) => {
return response
.error_for_status()?
.json()
.await
.context("Querying local Mycelium identity");
}
Err(error) if error.is_connect() && tokio::time::Instant::now() + wait < deadline => {
tracing::debug!(url = %url, error = %error, "Mycelium's API doesn't answer yet; trying again");
tokio::time::sleep(wait).await;
wait = (wait * 2).min(Duration::from_secs(1));
}
Err(error) => {
return Err(error).with_context(|| {
format!(
"Querying local Mycelium identity (no answer within {API_READY_WITHIN:?})"
)
});
}
}
}
}
impl MyceliumTransport {
pub(crate) async fn connect(setup: MyceliumSetup) -> Result<Self> {
let rest_url = setup.rest_url.clone();
// reqwest's TLS has no crypto provider of its own (`Cargo.toml`): ring, for the
// whole process, unless one is installed already.
let _ = rustls::crypto::ring::default_provider().install_default();
let client = reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.build()?;
let poll_client = reqwest::Client::builder()
.timeout(Duration::from_secs(MYCELIUM_POLL_TIMEOUT_SECS + 30))
.build()?;
let admin = admin_info(&client, rest_url.join("/api/v1/admin")?).await?;
let transport = Self {
setup: tokio::sync::Mutex::new(setup),
client,
poll_client,
messages_endpoint: rest_url.join("/api/v1/messages")?,
pubkey_basepath: rest_url.join("/api/v1/pubkey/")?,
local_id: admin.node_pubkey,
admission: std::sync::OnceLock::new(),
others: tokio::sync::watch::channel(0).0,
};
transport.discard_backlog().await;
Ok(transport)
}
/// Drops what Mycelium queued for us before we started. A Mycelium that outlives us
/// (an external one, or across our restart) keeps accepting messages meant for us:
/// HELLO retries, keepalives, sync messages of sessions that ended with our previous
/// run. Processing them would only replay stale handshakes. Everything that still
/// matters is resent: peers retry their HELLOs, and sync starts over after the
/// handshake. Runs before we send anything, so no answer to us is dropped.
///
/// Bounded in time, not count: the backlog is whatever piled up while we were away,
/// which a local loop drains in well under a second even for large swarms. Whatever
/// is still arriving after that is current traffic (peers that don't know we're
/// back), and it is processed normally, exactly as without this step.
async fn discard_backlog(&self) {
const DRAIN_FOR: Duration = Duration::from_secs(2);
let deadline = std::time::Instant::now() + DRAIN_FOR;
let mut discarded = 0u64;
while std::time::Instant::now() < deadline {
let response = self
.client
.get(self.messages_endpoint.clone())
.query(&[("timeout", 0)])
.query(&[("topic", encode_topic(TOPIC))])
.send()
.await;
match response {
Ok(response) if response.status() == StatusCode::NO_CONTENT => break,
Ok(response) if response.status().is_success() => discarded += 1,
Ok(response) => {
tracing::warn!(status = %response.status(), "Couldn't drain the inbox");
break;
}
Err(error) => {
tracing::warn!(error = %with_causes(error), "Couldn't drain the inbox");
break;
}
}
}
if discarded > 0 {
tracing::info!(
discarded,
"Discarded messages Mycelium queued for us before we started"
);
}
}
async fn lookup_pubkey(&self, ip: &std::net::Ipv6Addr) -> Result<String> {
#[derive(Deserialize)]
struct PublicKeyResponse {
#[serde(rename = "publicKey")]
public_key: String,
}
let _turn = Turn::taken(&self.others);
let response: PublicKeyResponse = self
.client
.get(self.pubkey_basepath.join(&ip.to_string())?)
.send()
.await?
.error_for_status()?
.json()
.await?;
Ok(response.public_key)
}
}
#[async_trait]
impl Transport for MyceliumTransport {
fn set_admission(&self, admission: crate::transport::Admission) {
let _ = self.admission.set(admission);
}
fn local_id(&self) -> &str {
&self.local_id
}
fn is_peer_id(&self, id: &str) -> bool {
is_pubkey(id)
}
fn delivery_limit(&self) -> Duration {
DELIVERY_LIMIT
}
async fn resolve_seed(&self, hint: &str) -> Result<String> {
if is_pubkey(hint) {
return Ok(hint.to_owned());
}
if let Ok(ip) = hint.parse::<std::net::Ipv6Addr>() {
return self.lookup_pubkey(&ip).await;
}
let ip = tokio::time::timeout(Duration::from_secs(10), tokio::net::lookup_host((hint, 0)))
.await
.context("DNS lookup timed out")??
.find_map(|addr| match addr.ip() {
std::net::IpAddr::V6(ip) => Some(ip),
_ => None,
})
.ok_or_else(|| anyhow!("{hint}: no AAAA record found"))?;
self.lookup_pubkey(&ip).await
}
fn encode_in(
&self,
peer: &str,
message: &ParsedMessage,
version: u8,
) -> Result<EncodedMessage> {
encode_message(peer, message, version)
}
async fn send_encoded(&self, message: &EncodedMessage) -> Result<()> {
tracing::trace!(payload_bytes = message.body.len(), "Sending message");
let _turn = Turn::taken(&self.others);
let response = self
.client
.post(self.messages_endpoint.clone())
.header(reqwest::header::CONTENT_TYPE, "application/json")
.timeout(post_timeout(message.body.len()))
.body(message.body.clone())
.send()
.await?;
let status = response.status();
if !status.is_success() {
tracing::error!(status = %status, "Mycelium rejected outbound message");
return Err(TransportError::MyceliumRejected {
peer: message.peer.clone(),
status,
}
.into());
}
// Mycelium's message ID, for GET /api/v1/messages/status/{id} when chasing a
// message that never arrived. The message itself is logged above, in the paths
// layer (`transport::paths`).
if tracing::enabled!(tracing::Level::TRACE) {
let id = response
.bytes()
.await
.ok()
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
.and_then(|body| body.get("id")?.as_str().map(str::to_owned));
tracing::trace!(to = %Addressed(SCHEME, &message.peer), id = ?id, "Mycelium took the message");
}
Ok(())
}
async fn start_consumer(&self, handler: MessageHandler) -> Result<()> {
let other_versions = wire::OtherVersions::default();
tracing::info!(
endpoint = self.messages_endpoint.as_str(),
"Starting the consumer"
);
// The poller takes the next message while the handler takes the one before.
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
tokio::spawn(poll_inbox(
self.poll_client.clone(),
self.messages_endpoint.clone(),
self.others.subscribe(),
tx,
));
// PINGs and PONGs aren't handled after the message before them (`is_probe`).
let handler: std::sync::Arc<HandlerFn> = std::sync::Arc::from(handler);
while let Some(inbound_message) = rx.recv().await {
// Mycelium has taken it whole already; a stranger's large one isn't decoded.
let limit = crate::transport::Admission::limit(
self.admission.get(),
SCHEME,
&inbound_message.src_pk,
MAX_INBOUND_BYTES,
);
if base64_decoded_len(&inbound_message.payload) > limit {
tracing::debug!(
from = %Addressed(SCHEME, &inbound_message.src_pk),
limit,
"Dropping a large message from a peer not admitted"
);
continue;
}
match parse_message(&inbound_message) {
Ok((sender, parsed)) => {
// The message itself is logged above, in the paths layer.
tracing::trace!(
from = %Addressed(SCHEME, &inbound_message.src_pk),
id = %inbound_message.id,
"Mycelium delivered a message"
);
let payload_len = base64_decoded_len(&inbound_message.payload);
if is_probe(&parsed) {
hand_on_probe(SCHEME, &handler, sender, parsed, payload_len);
} else if let Err(error) = handler(sender, parsed, payload_len).await {
tracing::warn!(error = %format!("{error:#}"), "Failed to process inbound message");
}
}
Err(TransportError::Wire(wire::WireError::Version(version))) => {
other_versions.note(SCHEME, &inbound_message.src_pk, version);
}
Err(transport_error) => {
// Who sent it and what it claims to be.
let kind = BASE64
.decode(&inbound_message.payload)
.ok()
.and_then(|payload| payload.get(1).copied());
tracing::error!(
error = %transport_error,
from = %Addressed(SCHEME, &inbound_message.src_pk),
kind = ?kind,
payload_bytes = base64_decoded_len(&inbound_message.payload),
topic = %inbound_message.topic,
"Dropping poisoned packet: parsing failed gracefully"
);
}
}
}
Ok(())
}
async fn wait_for_exit(&self) -> std::io::Result<std::process::ExitStatus> {
let mut guard = self.setup.lock().await;
guard.wait_for_exit().await
}
}
/// Takes what comes into the inbox and passes it to `tx` (`start_consumer`). Mycelium holds
/// its node's lock for as long as a request for the inbox waits for a message, and every
/// other request waits for that lock, the messages we send among them. So the poller waits
/// there only while nothing else is asked of the daemon (`others`): a request that begins
/// drops the waiting one, which frees the lock, as the daemon's API drops a request whose
/// client went away. While others are under way, it takes what is there without waiting,
/// again as each begins or ends. It waits peeking (`peek`), leaving the message in the
/// inbox, and pops it after without waiting: a request dropped while it waited takes
/// nothing with it.
async fn poll_inbox(
client: reqwest::Client,
endpoint: Url,
mut others: tokio::sync::watch::Receiver<usize>,
tx: tokio::sync::mpsc::Sender<InboundMessage>,
) {
loop {
let popped = if *others.borrow() == 0 {
tokio::select! {
biased;
begun = others.wait_for(|n| *n > 0) => {
if begun.is_err() {
return; // the transport is gone
}
continue;
}
peeked = ask(&client, &endpoint, MYCELIUM_POLL_TIMEOUT_SECS, true) => {
if peeked.is_none() {
continue;
}
}
}
ask(&client, &endpoint, 0, false).await
} else {
match ask(&client, &endpoint, 0, false).await {
Some(response) => Some(response),
None => {
if others.changed().await.is_err() {
return;
}
continue;
}
}
};
let Some(response) = popped else {
continue;
};
let Some(message) = message_of(response).await else {
continue;
};
if tx.send(message).await.is_err() {
return; // the consumer stopped
}
}
}
/// Asks the daemon for the inbox's next message, waiting up to `timeout` seconds for one,
/// and leaving it there with `peek`: the answer carrying it, where one came; none where
/// none did, or where the request failed, which is said, and waited a moment after.
async fn ask(
client: &reqwest::Client,
endpoint: &Url,
timeout: u64,
peek: bool,
) -> Option<reqwest::Response> {
tracing::trace!(timeout, peek, "Asking for the inbox");
let mut request = client
.get(endpoint.clone())
.query(&[("timeout", timeout)])
.query(&[("topic", encode_topic(TOPIC))]);
if peek {
request = request.query(&[("peek", true)]);
}
match request.send().await {
Ok(response) if response.status() == StatusCode::NO_CONTENT => {
tracing::trace!("The inbox is empty");
None
}
Ok(response) if response.status().is_success() => Some(response),
Ok(response) => {
tracing::warn!(status = %response.status(), "Polling the inbox failed");
tokio::time::sleep(Duration::from_millis(500)).await;
None
}
Err(error) => {
tracing::warn!(error = %with_causes(error), "Polling the inbox failed");
tokio::time::sleep(Duration::from_millis(250)).await;
None
}
}
}
/// The message `response` carries, where it is no larger than `MAX_INBOUND_BYTES` and
/// decodes; else none, said.
async fn message_of(response: reqwest::Response) -> Option<InboundMessage> {
let raw_bytes = match read_capped(response, MAX_INBOUND_BYTES).await {
Ok(Some(bytes)) => bytes,
Ok(None) => {
tracing::warn!(
limit_bytes = MAX_INBOUND_BYTES,
"Dropping an inbound message larger than the limit"
);
return None;
}
Err(error) => {
tracing::warn!(error = %with_causes(error), "Couldn't read a message from the inbox");
tokio::time::sleep(Duration::from_millis(100)).await;
return None;
}
};
match serde_json::from_slice::<InboundMessage>(&raw_bytes) {
Ok(message) => Some(message),
Err(error) => {
tracing::error!(
error = %error,
raw_payload = %String::from_utf8_lossy(&raw_bytes),
"Dropping a message that doesn't decode"
);
tokio::time::sleep(Duration::from_millis(500)).await;
None
}
}
}
/// A request's error and its causes, as people read them: reqwest's own says only which
/// request failed, its causes why.
fn with_causes(error: reqwest::Error) -> String {
format!("{:#}", anyhow::Error::from(error))
}
/// The body of `response`, unless it is larger than `limit` bytes (None): read no
/// further than that, whatever the sender claims.
async fn read_capped(
mut response: reqwest::Response,
limit: usize,
) -> reqwest::Result<Option<bytes::Bytes>> {
if response
.content_length()
.is_some_and(|length| length > limit as u64)
{
return Ok(None);
}
let mut body = bytes::BytesMut::new();
while let Some(chunk) = response.chunk().await? {
if body.len() + chunk.len() > limit {
return Ok(None);
}
body.extend_from_slice(&chunk);
}
Ok(Some(body.freeze()))
}
/// A message as the Mycelium REST API takes it (the JSON body of an outbound message).
/// Also the simulator's wire format (`transport::sim`), so tests go through the same
/// encoding. Its payload is in wire `version`.
pub(crate) fn encode_message(
peer: &str,
message: &ParsedMessage,
version: u8,
) -> Result<EncodedMessage> {
let (outbound, payload_len) = format_message(peer, message, version)?;
Ok(EncodedMessage {
peer: peer.to_owned(),
address: peer.to_owned(),
body: serde_json::to_vec(&outbound)?.into(),
kind: message.kind(),
payload_len,
message: None,
})
}
/// Mycelium's envelope, for simulations that run on it (`transport::sim::Codec`).
#[cfg(test)]
pub(crate) const CODEC: crate::transport::sim::Codec = crate::transport::sim::Codec {
encode: encode_message,
decode: decode_message,
};
/// The message in a body made by [`encode_message`].
#[cfg(test)]
pub(crate) fn decode_message(body: &[u8]) -> Result<ParsedMessage> {
let outbound: OutboundMessage = serde_json::from_slice(body)?;
Ok(decode_payload(&outbound.topic, &outbound.payload)?)
}
fn encode_topic(topic: &str) -> String {
BASE64.encode(topic.as_bytes())
}
fn decode_topic(topic: &str) -> Result<String, TransportError> {
let bytes = BASE64.decode(topic)?;
Ok(String::from_utf8(bytes)?)
}
fn encode_payload(payload: &Vec<u8>) -> String {
BASE64.encode(payload)
}
/// How long posting a body of `bytes` may take: `REQUEST_TIMEOUT`, plus the body at
/// `POST_MIN_RATE`.
fn post_timeout(bytes: usize) -> Duration {
REQUEST_TIMEOUT + Duration::from_millis(bytes as u64 * 1000 / POST_MIN_RATE)
}
/// Length of what padded base64 `encoded` decodes to.
fn base64_decoded_len(encoded: &str) -> usize {
let padding = encoded.bytes().rev().take_while(|&b| b == b'=').count();
(encoded.len() / 4 * 3).saturating_sub(padding)
}
fn decode_payload(topic_encoded: &str, payload: &str) -> Result<ParsedMessage, TransportError> {
let topic = decode_topic(topic_encoded)?;
if topic != TOPIC {
return Err(TransportError::UnknownTopic(topic));
}
Ok(wire::decode(&BASE64.decode(payload)?)?)
}
fn parse_message(message: &InboundMessage) -> Result<(String, ParsedMessage), TransportError> {
let sender = message.src_pk.clone();
if sender.is_empty() {
return Err(TransportError::NoSender);
}
let parsed = decode_payload(&message.topic, &message.payload)?;
Ok((sender, parsed))
}
/// The message for Mycelium's API, its payload in wire `version`, and the payload's length.
fn format_message(
recipient: &str,
message: &ParsedMessage,
version: u8,
) -> Result<(OutboundMessage, usize), TransportError> {
let payload_bytes = wire::encode_in(message, version)?;
let outbound = OutboundMessage {
dst: Destination {
pk: recipient.to_owned(),
},
topic: encode_topic(TOPIC),
payload: encode_payload(&payload_bytes),
};
Ok((outbound, payload_bytes.len()))
}
#[derive(Error, Debug)]
pub(crate) enum TransportError {
#[error("Mycelium delivered a message without a sender public key")]
NoSender,
#[error("Base64 decoding failed: {0}")]
Base64Decode(#[from] base64::DecodeError),
#[error("UTF-8 decoding failed: {0}")]
Utf8Decode(#[from] std::string::FromUtf8Error),
#[error(transparent)]
Wire(#[from] wire::WireError),
#[error("Unknown topic: {0}")]
UnknownTopic(String),
#[error("Network HTTP request failed: {0}")]
Http(#[from] reqwest::Error),
#[error("Mycelium server rejected outbound message to {peer} (HTTP {status})")]
MyceliumRejected {
peer: String,
status: reqwest::StatusCode,
},
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::ChangeHash;
use crate::transport::{
BlobBody, BlobId, BlobMessage, Epoch, HeadsSummary, MAX_LISTED_HEADS, Status,
};
/// Mycelium splits messages into chunks of this size.
const MYCELIUM_CHUNK: usize = 1300;
#[test]
fn post_timeout_grows_with_the_body() {
assert_eq!(post_timeout(0), REQUEST_TIMEOUT);
assert_eq!(
post_timeout(64 << 20),
REQUEST_TIMEOUT + Duration::from_secs(64)
);
}
#[test]
fn largest_keepalive_fits_in_one_chunk() {
// A digest with a full sample: the most a keepalive carries.
let status = Status {
heads: HeadsSummary::of(
(0..=MAX_LISTED_HEADS as u8)
.map(|n| ChangeHash([n; 32]))
.collect(),
),
epoch: Epoch {
generation: u64::MAX,
id: [0xff; 32],
},
epoch_seq: u32::MAX,
ready: true,
syncs_with_you: true,
leaving: false,
announcing: false,
reaches: None,
round_trips: None,
};
let payload = wire::encode(&ParsedMessage::StatusReply(status.clone())).unwrap();
// Mycelium's message data: a length byte, the topic, then our payload.
let size = 1 + TOPIC.len() + payload.len();
assert!(
size + 50 <= MYCELIUM_CHUNK,
"STATUS with {MAX_LISTED_HEADS} heads takes {size} bytes"
);
let ParsedMessage::StatusReply(decoded) = wire::decode(&payload).unwrap() else {
panic!("not a STATUS_REPLY");
};
assert_eq!(decoded.heads, status.heads);
}
#[test]
fn blob_messages_round_trip() {
let epoch = Epoch {
generation: 3,
id: [7; 32],
};
let id = BlobId::Change(ChangeHash([9; 32]));
let decode_blob = |payload: &[u8]| match wire::decode(payload).unwrap() {
ParsedMessage::Blob(blob) => blob,
other => panic!("not a blob: {other:?}"),
};
let chunk = ParsedMessage::Blob(BlobMessage {
epoch,
epoch_seq: 4,
id,
body: BlobBody::Chunk {
index: 5,
data: vec![1u8; 64 * 1024].into(),
},
sent: crate::clock::UnixMillis(6),
});
let bytes = wire::encode(&chunk).unwrap();
// A 64 KiB chunk costs only a few bytes of framing.
assert!(bytes.len() < 64 * 1024 + 128, "{} bytes", bytes.len());
let decoded = decode_blob(&bytes);
assert_eq!(decoded.id, id);
assert_eq!(decoded.epoch, epoch);
assert_eq!(decoded.epoch_seq, 4);
assert!(
matches!(decoded.body, BlobBody::Chunk { index: 5, ref data } if data.len() == 64 * 1024)
);
let manifest = ParsedMessage::Blob(BlobMessage {
epoch,
epoch_seq: 4,
id,
body: BlobBody::Manifest {
size: 100,
chunk_size: 64,
hashes: vec![[1; 32], [2; 32]],
},
sent: crate::clock::UnixMillis(6),
});
let decoded = decode_blob(&wire::encode(&manifest).unwrap());
assert!(matches!(
decoded.body,
BlobBody::Manifest { size: 100, chunk_size: 64, ref hashes } if hashes.len() == 2
));
}
/// Every kind decodes from Mycelium's API body (its envelope: the topic, the payload
/// in base64) to what was encoded.
#[test]
fn every_kind_round_trips_through_the_api_body() {
for message in wire::samples() {
let encoded = encode_message("peer", &message, wire::VERSION).unwrap();
assert_eq!(encoded.kind, message.kind());
let decoded = decode_message(&encoded.body).unwrap();
assert_eq!(
wire::encode(&decoded).unwrap(),
wire::encode(&message).unwrap(),
"{message:?}"
);
assert_eq!(encoded.payload_len, wire::encode(&message).unwrap().len());
}
}
/// A swarm whose every message goes through Mycelium's envelope: joining, writes
/// reaching everyone, and concurrent writes merging, as the simulations do with the
/// wire encoding alone.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_swarm_converges_over_the_envelope() {
use crate::simtest::{Sim, read, write};
use crate::swarm::bootstrap::Start;
use serde_json::json;
const SOON: Duration = Duration::from_secs(10);
let sim = Sim::with_codec(11, CODEC);
let a = sim.start("a", &[], Start::Genesis);
let b = sim.start("b", &["a"], Start::Join);
let c = sim.start("c", &["a"], Start::Join);
let (a, b, c) = (&a, &b, &c);
sim.wait_ready(&[a, b, c], SOON).await;
write(b, "users/bob", json!({"name": "Bob"})).await;
sim.wait_until("c has b's write", SOON, move || async move {
read(c, "users/bob/name").await == Some(json!("Bob"))
})
.await;
write(a, "users/alice", json!(1)).await;
write(c, "users/carol", json!(3)).await;
sim.wait_converged(&[a, b, c], SOON).await;
for node in [a, b, c] {
assert_eq!(read(node, "users/alice").await, Some(json!(1)));
assert_eq!(read(node, "users/carol").await, Some(json!(3)));
}
}
#[test]
fn listed_heads_equal_their_digest() {
let heads: Vec<_> = (0..3u8).map(|n| ChangeHash([n; 32])).collect();
let listed = HeadsSummary::of(heads.clone());
let digest = HeadsSummary::Digest {
digest: listed.digest(),
sample: Vec::new(),
};
assert_eq!(listed, digest);
assert_ne!(listed, HeadsSummary::of(heads[..2].to_vec()));
}
}
|