-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathmod.rs
More file actions
2224 lines (1992 loc) · 91.9 KB
/
mod.rs
File metadata and controls
2224 lines (1992 loc) · 91.9 KB
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Communicate with a fixed set of authenticated peers with known addresses over encrypted connections.
//!
//! `lookup` provides multiplexed communication between fully-connected peers
//! identified by a developer-specified cryptographic identity (i.e. BLS, ed25519, etc.).
//! Unlike `discovery`, peers in `lookup` don't use a discovery mechanism to find each other;
//! each peer's address is supplied by the application layer.
//!
//! # Features
//!
//! - Configurable Cryptography Scheme for Peer Identities (BLS, ed25519, etc.)
//! - Multiplexing With Configurable Rate Limiting Per Channel and Send Prioritization
//!
//! # Design
//!
//! ## Discovery
//!
//! This module operates under the assumption that all peers are aware of and synchronized on
//! the composition of peer sets at specific, user-provided indices (`u64`). Each index maps to a
//! list of peer `PublicKey`/`SocketAddr` pairs (`(u64, Vec<(PublicKey, SocketAddr)>)`).
//!
//! On startup, the application supplies the initial set of peers. The [`Oracle`] implements
//! [`AddressableManager`](crate::AddressableManager) which provides two ways to update peer addresses:
//!
//! - [`AddressableManager::track`](crate::AddressableManager::track): Track a new peer set at a
//! monotonically increasing index. Use this when the peer set composition changes (peers added/removed).
//! This accepts either a list of primary peers or an
//! [`AddressableTrackedPeers`](crate::AddressableTrackedPeers) value containing both primary and
//! secondary peers.
//! - [`AddressableManager::overwrite`](crate::AddressableManager::overwrite): Update multiple
//! peers' addresses in-place without creating a new peer set. Use this when only peer IPs change but
//! the peer set composition stays the same. Peers not in the directory (or unchanged) are silently skipped (so the application doesn't
//! need to remember what their last submitted peer set was).
//!
//! Secondary peers remain visible in [`PeerSetUpdate`](crate::PeerSetUpdate)
//! notifications, are accepted for inbound connections, and may receive
//! `Recipients::All` traffic on established connections, but outbound dialing
//! is restricted to primary peers.
//!
//! Any inbound connection attempts from an IP address that is not in the union of all registered
//! primary or secondary peers will be rejected.
//!
//! ## Messages
//!
//! Application-level data is exchanged using the `Data` message type. This structure contains:
//! - `channel`: A `u32` identifier used to route the message to the correct application handler.
//! - `message`: The arbitrary application payload as `IoBuf`.
//!
//! The size of the `message` bytes must not exceed the configured
//! `max_message_size`. If it does, the sending operation will fail with
//! [Error::MessageTooLarge]. Messages can be sent with `priority`, allowing certain
//! communications to potentially bypass lower-priority messages waiting in send queues across all
//! channels. Each registered channel ([Sender], [Receiver]) handles its own message queuing
//! and rate limiting.
//!
//! ## Compression
//!
//! Stream compression is not provided at the transport layer to avoid inadvertently
//! enabling known attacks such as BREACH and CRIME. These attacks exploit the interaction
//! between compression and encryption by analyzing patterns in the resulting data.
//! By compressing secrets alongside attacker-controlled content, these attacks can infer
//! sensitive information through compression ratio analysis. Applications that choose
//! to compress data should do so with full awareness of these risks and implement
//! appropriate mitigations (such as ensuring no attacker-controlled data is compressed
//! alongside sensitive information).
//!
//! ## Batching
//!
//! Applications seeking higher performance should prefer batching messages
//! above `p2p`. Larger application-level batches amortize per-message
//! encryption overhead and, if the application also compresses its payloads,
//! can improve compression ratio.
//!
//! ## Rate Limiting
//!
//! There are five primary rate limits:
//!
//! - `max_concurrent_handshakes`: The maximum number of concurrent handshake attempts allowed.
//! - `allowed_handshake_rate_per_ip`: The rate limit for handshake attempts originating from a single IP address.
//! - `allowed_handshake_rate_per_subnet`: The rate limit for handshake attempts originating from a single IP subnet.
//! - `peer_connection_cooldown`: The per-peer rate limit for inbound and outbound connection reservations, expressed as a minimum cooldown between attempts.
//! - `rate` (per channel): The rate limit for messages sent on a single channel.
//!
//! _Users should consider these rate limits as best-effort protection against moderate abuse. Targeted abuse (e.g. DDoS)
//! must be mitigated with an external proxy (that limits inbound connection attempts to authorized IPs)._
//!
//! ## IP Poisoning
//!
//! A malicious peer can claim an ingress [std::net::SocketAddr] that collides with an honest
//! peer, drawing invalid dial attempts to
//! the honest peer (where we expect the malicious public key rather than the honest public key).
//!
//! Because we rate limit inbound connection attempts per IP/subnet, this poisoning can lead to us dropping legitimate
//! dial attempts (if quota was already exhausted on useless dial attempts). Recall, an honest dialer doesn't know which public
//! key actually resides at an address and must try all that collide.
//!
//! To mitigate this issue, we shuffle peer dial order on each dial queue refresh. This ensures we eventually dial a poisoned
//! IP with the correct public key before hitting the rate limit imposed by the listener at said IP.
//!
//! _Applications that wish to entirely prevent this class of attack can assert uniqueness of
//! ingress [std::net::SocketAddr] during
//! peer registration._
//!
//! ## Message Delivery
//!
//! Outgoing messages are dropped when a peer's send buffer is full, preventing slow peers
//! from blocking sends to other peers. Incoming messages are dropped when the application's
//! receive buffer is full, ensuring ping messages continue to flow and connections remain
//! healthy.
//!
//! # Example
//!
//! ```rust
//! use commonware_p2p::{authenticated::lookup::{self, Network}, Address, AddressableManager, Sender, Recipients};
//! use commonware_cryptography::{ed25519, Signer, PrivateKey as _, PublicKey as _, };
//! use commonware_runtime::{deterministic, IoBuf, Metrics, Quota, Runner, Spawner};
//! use commonware_utils::{NZU32, ordered::Map};
//! use std::net::{IpAddr, Ipv4Addr, SocketAddr};
//!
//! // Configure context
//! let runtime_cfg = deterministic::Config::default();
//! let runner = deterministic::Runner::new(runtime_cfg);
//!
//! // Generate identity
//! //
//! // In production, the signer should be generated from a secure source of entropy.
//! let my_sk = ed25519::PrivateKey::from_seed(0);
//! let my_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
//!
//! // Generate peers
//! //
//! // In production, peer identities will be provided by some external source of truth
//! // (like the staking set of a blockchain).
//! let peer1 = ed25519::PrivateKey::from_seed(1).public_key();
//! let peer1_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 3001);
//! let peer2 = ed25519::PrivateKey::from_seed(2).public_key();
//! let peer2_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 3002);
//! let peer3 = ed25519::PrivateKey::from_seed(3).public_key();
//! let peer3_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 3003);
//!
//! // Configure namespace
//! //
//! // In production, use a unique application namespace to prevent cryptographic replay attacks.
//! let application_namespace = b"my-app-namespace";
//!
//! // Configure network
//! //
//! // In production, use a more conservative configuration like `Config::recommended`.
//! const MAX_MESSAGE_SIZE: u32 = 1_024; // 1KB
//! let p2p_cfg = lookup::Config::local(
//! my_sk.clone(),
//! application_namespace,
//! my_addr,
//! MAX_MESSAGE_SIZE,
//! );
//!
//! // Start context
//! runner.start(|context| async move {
//! // Initialize network
//! let (mut network, mut oracle) = Network::new(context.with_label("network"), p2p_cfg);
//!
//! // Register authorized peers
//! //
//! // In production, this would be updated as new peer sets are created (like when
//! // the composition of a validator set changes).
//! let peers: Map<_, Address> = [
//! (my_sk.public_key(), my_addr.into()),
//! (peer1, peer1_addr.into()),
//! (peer2, peer2_addr.into()),
//! (peer3, peer3_addr.into()),
//! ].try_into().unwrap();
//! oracle.track(0, peers).await;
//!
//! // Register some channel
//! const MAX_MESSAGE_BACKLOG: usize = 128;
//! let (mut sender, receiver) = network.register(
//! 0,
//! Quota::per_second(NZU32!(1)),
//! MAX_MESSAGE_BACKLOG,
//! );
//!
//! // Run network
//! network.start();
//!
//! // Example: Use sender
//! let _ = sender.send(Recipients::All, IoBuf::from(b"hello"), false).await;
//!
//! // Graceful shutdown (stops all spawned tasks)
//! context.stop(0, None).await.unwrap();
//! });
//! ```
mod actors;
mod channels;
mod config;
mod metrics;
mod network;
mod types;
use thiserror::Error;
/// Errors that can occur when interacting with the network.
#[derive(Error, Debug)]
pub enum Error {
#[error("message too large: {0}")]
MessageTooLarge(usize),
#[error("network closed")]
NetworkClosed,
}
pub use actors::tracker::Oracle;
pub use channels::{Receiver, Sender};
pub use config::Config;
pub use network::Network;
#[cfg(test)]
mod tests {
use super::*;
use crate::{Address, AddressableManager, Ingress, Provider, Receiver, Recipients, Sender};
use commonware_cryptography::{ed25519, Signer as _};
use commonware_macros::{select, test_group, test_traced};
use commonware_runtime::{
count_running_tasks, deterministic, tokio, BufferPooler, Clock, Metrics,
Network as RNetwork, Quota, Resolver, Runner, Spawner,
};
use commonware_utils::{
channel::mpsc,
hostname,
ordered::{Map, Set},
Hostname, TryCollect, NZU32,
};
use rand_core::{CryptoRngCore, RngCore};
use std::{
collections::HashSet,
net::{IpAddr, Ipv4Addr, SocketAddr},
time::Duration,
};
#[derive(Copy, Clone)]
enum Mode {
All,
Some,
One,
}
const MAX_MESSAGE_SIZE: u32 = 1_024 * 1_024; // 1MB
const DEFAULT_MESSAGE_BACKLOG: usize = 128;
/// Ensure no message rate limiting occurred.
///
/// If a message is rate limited, it would be formatted as:
///
/// ```text
/// peer-9_network_spawner_messages_rate_limited_total{peer="e2e8aa145e1ec5cb01ebfaa40e10e12f0230c832fd8135470c001cb86d77de00",message="data_0"} 1
/// peer-9_network_spawner_messages_rate_limited_total{peer="e2e8aa145e1ec5cb01ebfaa40e10e12f0230c832fd8135470c001cb86d77de00",message="ping"} 1
/// ```
fn assert_no_rate_limiting(context: &impl Metrics) {
let metrics = context.encode();
assert!(
!metrics.contains("messages_rate_limited_total{"),
"no messages should be rate limited: {metrics}"
);
}
/// Test connectivity between `n` peers.
///
/// We set a unique `base_port` for each test to avoid "address already in use"
/// errors when tests are run immediately after each other.
async fn run_network(
context: impl Spawner + BufferPooler + Clock + CryptoRngCore + RNetwork + Resolver,
max_message_size: u32,
base_port: u16,
n: usize,
mode: Mode,
) {
// Create peers
let mut peers_and_sks = Vec::new();
for i in 0..n {
let private_key = ed25519::PrivateKey::from_seed(i as u64);
let public_key = private_key.public_key();
let address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port + i as u16);
peers_and_sks.push((private_key, public_key, address));
}
let peers: Vec<(ed25519::PublicKey, Address)> = peers_and_sks
.iter()
.map(|(_, pub_key, addr)| (pub_key.clone(), (*addr).into()))
.collect::<Vec<_>>();
// Create networks
let (complete_sender, mut complete_receiver) = mpsc::channel(peers.len());
for (i, (private_key, public_key, address)) in peers_and_sks.iter().enumerate() {
let public_key = public_key.clone();
// Create peer context
let context = context.with_label(&format!("peer_{i}"));
// Create network
let config = Config::test(private_key.clone(), *address, max_message_size);
let (mut network, mut oracle) = Network::new(context.with_label("network"), config);
// Register peers
oracle.track(0, Map::try_from(peers.clone()).unwrap()).await;
// Register basic application
let (mut sender, mut receiver) =
network.register(0, Quota::per_second(NZU32!(100)), DEFAULT_MESSAGE_BACKLOG);
// Wait to connect to all peers, and then send messages to everyone
network.start();
// Send/Receive messages
context.with_label("agent").spawn({
let complete_sender = complete_sender.clone();
let peers = peers.clone();
move |context| async move {
// Wait for all peers to send their identity
let receiver = context.with_label("receiver").spawn(move |_| async move {
// Wait for all peers to send their identity
let mut received = HashSet::new();
while received.len() < n - 1 {
// Ensure message equals sender identity
let (sender, message) = receiver.recv().await.unwrap();
assert_eq!(message, sender.as_ref());
// Add to received set
received.insert(sender);
}
complete_sender.send(()).await.unwrap();
// Process messages until all finished (or else sender loops could get stuck as a peer may drop)
loop {
receiver.recv().await.unwrap();
}
});
// Send identity to all peers
let sender = context
.with_label("sender")
.spawn(move |context| async move {
// Get all peers not including self
let mut recipients: Vec<_> = peers
.iter()
.enumerate()
.filter(|(j, _)| i != *j)
.map(|(_, (pk, _))| pk.clone())
.collect();
recipients.sort();
// Loop forever to account for unexpected message drops
loop {
match mode {
Mode::One => {
for pub_key in &recipients {
// Loop until success
loop {
let sent = sender
.send(
Recipients::One(pub_key.clone()),
public_key.as_ref().to_vec(),
true,
)
.await
.unwrap();
if sent.len() != 1 {
context.sleep(Duration::from_millis(100)).await;
continue;
}
assert_eq!(&sent[0], pub_key);
break;
}
}
}
Mode::Some | Mode::All => {
// Loop until all peer sends successful
loop {
let mut sent = sender
.send(
match mode {
Mode::Some => {
Recipients::Some(recipients.clone())
}
Mode::All => Recipients::All,
_ => unreachable!(),
},
public_key.as_ref().to_vec(),
true,
)
.await
.unwrap();
if sent.len() != recipients.len() {
context.sleep(Duration::from_millis(100)).await;
continue;
}
// Compare to expected
sent.sort();
assert_eq!(sent, recipients);
break;
}
}
};
// Sleep to avoid busy loop
context.sleep(Duration::from_secs(10)).await;
}
});
// Neither task should exit
select! {
receiver = receiver => {
panic!("receiver exited: {receiver:?}");
},
sender = sender => {
panic!("sender exited: {sender:?}");
},
}
}
});
}
// Wait for all peers to finish
for _ in 0..n {
complete_receiver.recv().await.unwrap();
}
// Ensure no message rate limiting occurred
assert_no_rate_limiting(&context);
}
fn run_deterministic_test(seed: u64, mode: Mode) {
// Configure test
const NUM_PEERS: usize = 25;
const BASE_PORT: u16 = 3000;
// Run first instance
let executor = deterministic::Runner::seeded(seed);
let state = executor.start(|context| async move {
run_network(
context.clone(),
MAX_MESSAGE_SIZE,
BASE_PORT,
NUM_PEERS,
mode,
)
.await;
context.auditor().state()
});
// Compare result to second instance
let executor = deterministic::Runner::seeded(seed);
let state2 = executor.start(|context| async move {
run_network(
context.clone(),
MAX_MESSAGE_SIZE,
BASE_PORT,
NUM_PEERS,
mode,
)
.await;
context.auditor().state()
});
assert_eq!(state, state2);
}
#[test_group("slow")]
#[test_traced]
fn test_determinism_one() {
for i in 0..10 {
run_deterministic_test(i, Mode::One);
}
}
#[test_group("slow")]
#[test_traced]
fn test_determinism_some() {
for i in 0..10 {
run_deterministic_test(i, Mode::Some);
}
}
#[test_group("slow")]
#[test_traced]
fn test_determinism_all() {
for i in 0..10 {
run_deterministic_test(i, Mode::All);
}
}
#[test_traced]
fn test_tokio_connectivity() {
let executor = tokio::Runner::default();
executor.start(|context| async move {
let base_port = 4000;
let n = 10;
run_network(context, MAX_MESSAGE_SIZE, base_port, n, Mode::One).await;
});
}
#[test_traced]
fn test_multi_index_oracle() {
// Configure test
let base_port = 3000;
let n: usize = 10;
// Initialize context
let executor = deterministic::Runner::default();
executor.start(|context| async move {
// Create peers
let mut peers_and_sks = Vec::new();
for i in 0..n {
let sk = ed25519::PrivateKey::from_seed(i as u64);
let pk = sk.public_key();
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port + i as u16);
peers_and_sks.push((sk, pk, addr));
}
let peers = peers_and_sks
.iter()
.map(|(_, pk, addr)| (pk.clone(), (*addr).into()))
.collect::<Vec<_>>();
// Create networks
let mut waiters = Vec::new();
for (i, (peer_sk, peer_pk, peer_addr)) in peers_and_sks.iter().enumerate() {
// Create peer context
let context = context.with_label(&format!("peer_{i}"));
// Create network
let config = Config::test(
peer_sk.clone(),
*peer_addr,
1_024 * 1_024, // 1MB
);
let (mut network, mut oracle) = Network::new(context.with_label("network"), config);
// Register peers at separate indices
oracle
.track(0, Map::try_from([peers[0].clone()]).unwrap())
.await;
oracle
.track(
1,
Map::try_from([peers[1].clone(), peers[2].clone()]).unwrap(),
)
.await;
oracle
.track(
2,
peers
.iter()
.skip(2)
.cloned()
.try_collect::<Map<_, _>>()
.unwrap(),
)
.await;
// Register basic application
let (mut sender, mut receiver) =
network.register(0, Quota::per_second(NZU32!(10)), DEFAULT_MESSAGE_BACKLOG);
// Wait to connect to all peers, and then send messages to everyone
network.start();
// Send/Receive messages
let msg = peer_pk.clone();
let handler = context
.with_label("agent")
.spawn(move |context| async move {
if i == 0 {
// Loop until success
loop {
if sender
.send(Recipients::All, msg.as_ref().to_vec(), true)
.await
.unwrap()
.len()
== n - 1
{
break;
}
// Sleep and try again (avoid busy loop)
context.sleep(Duration::from_millis(100)).await;
}
} else {
// Ensure message equals sender identity
let (sender, message) = receiver.recv().await.unwrap();
assert_eq!(message, sender.as_ref());
}
});
// Add to waiters
waiters.push(handler);
}
// Wait for waiters to finish (receiver before sender)
for waiter in waiters.into_iter().rev() {
waiter.await.unwrap();
}
// Ensure no message rate limiting occurred
assert_no_rate_limiting(&context);
});
}
#[test_traced]
fn test_message_too_large() {
// Configure test
let base_port = 3000;
let n: usize = 2;
// Initialize context
let executor = deterministic::Runner::seeded(0);
executor.start(|mut context| async move {
// Create peers
let mut peers_and_sks = Vec::new();
for i in 0..n {
let peer_sk = ed25519::PrivateKey::from_seed(i as u64);
let peer_pk = peer_sk.public_key();
let peer_addr =
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port + i as u16);
peers_and_sks.push((peer_sk, peer_pk, peer_addr));
}
let peers: Map<_, _> = peers_and_sks
.iter()
.map(|(_, pk, addr)| (pk.clone(), (*addr).into()))
.try_collect()
.unwrap();
// Create network
let (sk, _, addr) = peers_and_sks[0].clone();
let config = Config::test(
sk,
addr,
1_024 * 1_024, // 1MB
);
let (mut network, mut oracle) = Network::new(context.with_label("network"), config);
// Register peers
oracle.track(0, peers.clone()).await;
// Register basic application
let (mut sender, _) =
network.register(0, Quota::per_second(NZU32!(10)), DEFAULT_MESSAGE_BACKLOG);
// Wait to connect to all peers, and then send messages to everyone
network.start();
// Crate random message
let mut msg = vec![0u8; 10 * 1024 * 1024]; // 10MB (greater than frame capacity)
context.fill_bytes(&mut msg[..]);
// Send message
let recipient = Recipients::One(peers[1].clone());
let result = sender.send(recipient, msg, true).await;
assert!(matches!(result, Err(Error::MessageTooLarge(_))));
});
}
#[test_traced]
fn test_rate_limiting() {
// Configure test
let base_port = 3000;
let n: usize = 2;
// Initialize context
let executor = deterministic::Runner::seeded(0);
executor.start(|context| async move {
// Create peers
let mut peers_and_sks = Vec::new();
for i in 0..n {
let sk = ed25519::PrivateKey::from_seed(i as u64);
let pk = sk.public_key();
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port + i as u16);
peers_and_sks.push((sk, pk, addr));
}
let peers: Map<_, _> = peers_and_sks
.iter()
.map(|(_, pk, addr)| (pk.clone(), (*addr).into()))
.try_collect()
.unwrap();
let (sk0, _, addr0) = peers_and_sks[0].clone();
let (sk1, pk1, addr1) = peers_and_sks[1].clone();
// Create network for peer 0
let config0 = Config::test(sk0, addr0, 1_024 * 1_024); // 1MB
let (mut network0, mut oracle0) = Network::new(context.with_label("peer_0"), config0);
oracle0.track(0, peers.clone()).await;
let (mut sender0, _receiver0) =
network0.register(0, Quota::per_minute(NZU32!(1)), DEFAULT_MESSAGE_BACKLOG);
network0.start();
// Create network for peer 1
let config1 = Config::test(sk1, addr1, 1_024 * 1_024); // 1MB
let (mut network1, mut oracle1) = Network::new(context.with_label("peer_1"), config1);
oracle1.track(0, peers.clone()).await;
let (_sender1, _receiver1) =
network1.register(0, Quota::per_minute(NZU32!(1)), DEFAULT_MESSAGE_BACKLOG);
network1.start();
// Send first message, which should be allowed and consume the quota.
let msg = vec![0u8; 1024]; // 1KB
loop {
// Confirm message is sent to peer
let sent = sender0
.send(Recipients::One(pk1.clone()), msg.clone(), true)
.await
.unwrap();
if !sent.is_empty() {
break;
}
// Ensure we don't rate limit outbound sends while
// waiting for peers to connect
context.sleep(Duration::from_mins(1)).await
}
// Immediately send the second message to trigger the rate limit.
// With partial sends, rate-limited recipients return empty vec (not error).
// Outbound rate limiting skips the peer, returns empty vec.
let sent = sender0.send(Recipients::One(pk1), msg, true).await.unwrap();
assert!(sent.is_empty());
// Give the metrics time to reflect the rate-limited message.
for _ in 0..10 {
assert_no_rate_limiting(&context);
context.sleep(Duration::from_millis(100)).await;
}
});
}
#[test_traced]
fn test_unordered_peer_sets() {
let (n, base_port) = (10, 3000);
let executor = deterministic::Runner::default();
executor.start(|context| async move {
// Create peers
let mut peers_and_sks = Vec::new();
for i in 0..n {
let sk = ed25519::PrivateKey::from_seed(i as u64);
let pk = sk.public_key();
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port + i as u16);
peers_and_sks.push((sk, pk, addr));
}
let peer0 = peers_and_sks[0].clone();
let config = Config::test(peer0.0, peer0.2, 1_024 * 1_024);
let (network, mut oracle) = Network::new(context.with_label("network"), config);
network.start();
// Subscribe to peer sets
let mut subscription = oracle.subscribe().await;
// Register initial peer set
let set10: Map<_, _> = peers_and_sks
.iter()
.take(2)
.map(|(_, pk, addr)| (pk.clone(), (*addr).into()))
.try_collect()
.unwrap();
oracle.track(10, set10.clone()).await;
let update = subscription.recv().await.unwrap();
assert_eq!(update.index, 10);
assert_eq!(&update.latest.primary, set10.keys());
assert!(update.latest.secondary.is_empty());
assert_eq!(&update.all.primary, set10.keys());
assert!(update.all.secondary.is_empty());
// Register old peer sets (ignored)
let set9: Map<_, _> = peers_and_sks
.iter()
.skip(2)
.map(|(_, pk, addr)| (pk.clone(), (*addr).into()))
.try_collect()
.unwrap();
oracle.track(9, set9.clone()).await;
// Add new peer set
let set11: Map<_, _> = peers_and_sks
.iter()
.skip(4)
.map(|(_, pk, addr)| (pk.clone(), (*addr).into()))
.try_collect()
.unwrap();
oracle.track(11, set11.clone()).await;
let update = subscription.recv().await.unwrap();
assert_eq!(update.index, 11);
assert_eq!(&update.latest.primary, set11.keys());
assert!(update.latest.secondary.is_empty());
let all_keys: Set<_> = set10
.into_keys()
.into_iter()
.chain(set11.into_keys().into_iter())
.try_collect()
.unwrap();
assert_eq!(update.all.primary, all_keys);
assert!(update.all.secondary.is_empty());
});
}
#[test_traced]
fn test_graceful_shutdown() {
let base_port = 3000;
let n: usize = 5;
let executor = deterministic::Runner::default();
executor.start(|context| async move {
// Create peers
let mut peers_and_sks = Vec::new();
for i in 0..n {
let sk = ed25519::PrivateKey::from_seed(i as u64);
let pk = sk.public_key();
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port + i as u16);
peers_and_sks.push((sk, pk, addr));
}
let peers: Map<_, _> = peers_and_sks
.iter()
.map(|(_, pk, addr)| (pk.clone(), (*addr).into()))
.try_collect()
.unwrap();
// Create networks for all peers
let (complete_sender, mut complete_receiver) = mpsc::channel(n);
for (i, (sk, pk, addr)) in peers_and_sks.iter().enumerate() {
let peer_context = context.with_label(&format!("peer_{i}"));
let config = Config::test(sk.clone(), *addr, 1_024 * 1_024);
let (mut network, mut oracle) =
Network::new(peer_context.with_label("network"), config);
// Register peer set
oracle.track(0, peers.clone()).await;
let (mut sender, mut receiver) =
network.register(0, Quota::per_second(NZU32!(100)), DEFAULT_MESSAGE_BACKLOG);
network.start();
peer_context.with_label("agent").spawn({
let complete_sender = complete_sender.clone();
let pk = pk.clone();
move |context| async move {
// Wait to connect to at least one other peer
let expected_connections = if i == 0 { n - 1 } else { 1 };
// Send a message
loop {
let sent = sender
.send(Recipients::All, pk.as_ref().to_vec(), true)
.await
.unwrap();
if sent.len() >= expected_connections {
break;
}
context.sleep(Duration::from_millis(100)).await;
}
// Signal that this peer is connected
complete_sender.send(()).await.unwrap();
// Keep receiving messages until shutdown
loop {
select! {
result = receiver.recv() => {
if result.is_err() {
// Channel closed due to shutdown
break;
}
},
_ = context.stopped() => {
// Graceful shutdown signal received
break;
},
}
}
}
});
}
// Wait for all peers to establish connectivity
for _ in 0..n {
complete_receiver.recv().await.unwrap();
}
// Verify that network actors started for all peers
let metrics_before = context.encode();
let is_running = |name: &str| -> bool {
metrics_before.lines().any(|line| {
line.starts_with("runtime_tasks_running{")
&& line.contains(&format!("name=\"{name}\""))
&& line.contains("kind=\"Task\"")
&& line.trim_end().ends_with(" 1")
})
};
for i in 0..n {
let prefix = format!("peer_{i}_network");
assert!(
is_running(&format!("{prefix}_tracker")),
"peer_{i} tracker should be running"
);
assert!(
is_running(&format!("{prefix}_router")),
"peer_{i} router should be running"
);
assert!(
is_running(&format!("{prefix}_spawner")),
"peer_{i} spawner should be running"
);
assert!(
is_running(&format!("{prefix}_listener")),
"peer_{i} listener should be running"
);
assert!(
is_running(&format!("{prefix}_dialer")),
"peer_{i} dialer should be running"
);
}
// All peers are connected - now trigger graceful shutdown
let shutdown_context = context.clone();
context.with_label("shutdown").spawn(move |_| async move {
// Trigger graceful shutdown
let result = shutdown_context.stop(0, Some(Duration::from_secs(5))).await;
// Shutdown should complete successfully without timeout
assert!(
result.is_ok(),
"graceful shutdown should complete: {result:?}"
);
});
// Wait for shutdown to complete
context.stopped().await.unwrap();
// Give the runtime a tick to process task completions and update metrics
context.sleep(Duration::from_millis(100)).await;
// Verify that all network actors stopped
let metrics_after = context.encode();
let is_stopped = |name: &str| -> bool {
metrics_after.lines().any(|line| {
line.starts_with("runtime_tasks_running{")
&& line.contains(&format!("name=\"{name}\""))
&& line.contains("kind=\"Task\"")
&& line.trim_end().ends_with(" 0")
})
};
for i in 0..n {
let prefix = format!("peer_{i}_network");
assert!(
is_stopped(&format!("{prefix}_tracker")),
"peer_{i} tracker should be stopped"
);
assert!(
is_stopped(&format!("{prefix}_router")),
"peer_{i} router should be stopped"
);
assert!(
is_stopped(&format!("{prefix}_spawner")),
"peer_{i} spawner should be stopped"
);
assert!(
is_stopped(&format!("{prefix}_listener")),
"peer_{i} listener should be stopped"
);
assert!(
is_stopped(&format!("{prefix}_dialer")),
"peer_{i} dialer should be stopped"
);
}
});
}
#[test_traced]
fn test_subscription_includes_self_when_registered() {
let base_port = 3000;
let executor = deterministic::Runner::default();
executor.start(|context| async move {
// Create self (peer0) and other peers
let self_sk = ed25519::PrivateKey::from_seed(0);
let self_pk = self_sk.public_key();
let self_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port);
let other_pk = ed25519::PrivateKey::from_seed(1).public_key();
let other_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), base_port + 1);
// Create network for peer0 (self)
let config = Config::test(self_sk, self_addr, 1_024 * 1_024);
let (network, mut oracle) = Network::new(context.with_label("network"), config);
network.start();
// Subscribe to peer sets
let mut subscription = oracle.subscribe().await;
// Register a peer set that does NOT include self
let peer_set: Map<_, _> = [(other_pk.clone(), other_addr.into())].try_into().unwrap();
oracle.track(1, peer_set.clone()).await;
// Receive subscription notification
let update = subscription.recv().await.unwrap();
assert_eq!(update.index, 1);
assert_eq!(update.latest.primary.len(), 1);
assert_eq!(update.all.primary.len(), 1);
assert!(update.all.secondary.is_empty());