rings-node 1.0.0-pre.5

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
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
use std::collections::BTreeSet;
use std::collections::VecDeque;
use std::ops::RangeInclusive;

use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::ecc::SecretKey;
use rings_core::measure::PeerQuality;
use rings_core::message::DhtProtocolMode;
use rings_core::message::MessageSigner;

use super::super::*;
use crate::consts::DATA_REDUNDANT;
use crate::descriptor::SignedDescriptor;
use crate::error::Error;
use crate::error::Result;
use crate::onion::OnionExitDescriptor;
use crate::onion::OnionProcessEpoch;
use crate::onion::OnionRouteError;
use crate::onion::OnionServiceName;
use crate::onion::MAX_ONION_LOOP_SYMBOLS;
use crate::online::OnlineNodeCapabilities;
use crate::online::OnlineNodeDescriptor;
use crate::online::OnlineNodeDescriptorBody;
use crate::online::OnlineNodeType;
use crate::tests::exit_descriptor::ExitDescriptorFixture;

/// Network of every fixture unless a test names another.
const TEST_NETWORK_ID: u32 = 1;
/// Current process epoch of every fixture node.
const TEST_PROCESS_EPOCH: OnionProcessEpoch = OnionProcessEpoch::new([29; 16]);
/// Process epoch of an earlier process of a fixture node.
const STALE_PROCESS_EPOCH: OnionProcessEpoch = OnionProcessEpoch::new([31; 16]);
/// Clock reading at which fixtures are live.
const NOW_MS: u128 = 50;
/// Heartbeat of every live fixture descriptor.
const HEARTBEAT_MS: u128 = 20;
/// Expiry of every live fixture descriptor.
const EXPIRES_MS: u128 = 100;

/// The node whose account secret key is `[seed; 32]`: fixed DIDs make every DID-ordered draw
/// reproducible. `seed` is non-zero.
fn node_key(seed: u8) -> Result<DelegateeKey> {
    let secret =
        SecretKey::try_from(format!("{seed:02x}").repeat(32).as_str()).map_err(Error::CoreError)?;
    DelegateeKey::new_with_seckey_at(&secret, u64::MAX, 0).map_err(Error::CoreError)
}

/// The nodes of `seeds`.
fn node_keys(seeds: RangeInclusive<u8>) -> Result<Vec<DelegateeKey>> {
    seeds.map(node_key).collect()
}

/// `keys` in DID order, the order of every weighted draw.
fn in_did_order(keys: &[DelegateeKey]) -> Vec<&DelegateeKey> {
    let mut ordered = keys.iter().collect::<Vec<_>>();
    ordered.sort_by_key(|key| key.delegator_did());
    ordered
}

/// The relay hop of `key` at `epoch`.
fn hop(key: &DelegateeKey, epoch: OnionProcessEpoch) -> OnionRouteHop {
    OnionRouteHop::new(key.delegator_did(), key.delegatee_public_key(), epoch)
}

/// A signed `tcp` registration of `key` at `epoch` on `network_id`, live until `expires_at_ms`.
fn exit_descriptor(
    key: &DelegateeKey,
    epoch: OnionProcessEpoch,
    network_id: u32,
    expires_at_ms: u128,
) -> Result<OnionExitDescriptor> {
    ExitDescriptorFixture {
        network_id,
        ..ExitDescriptorFixture::offline(key, epoch, HEARTBEAT_MS, expires_at_ms)?
    }
    .sign()
}

/// A live `tcp` registration of `key` at the current epoch.
fn live_exit(key: &DelegateeKey) -> Result<OnionExitDescriptor> {
    exit_descriptor(key, TEST_PROCESS_EPOCH, TEST_NETWORK_ID, EXPIRES_MS)
}

/// A signed online-node descriptor of `key` with `capabilities`, live until `expires_at_ms`.
fn online_descriptor(
    key: &DelegateeKey,
    capabilities: OnlineNodeCapabilities,
    network_id: u32,
    expires_at_ms: u128,
) -> Result<OnlineNodeDescriptor> {
    OnlineNodeDescriptor::new_signed(
        OnlineNodeDescriptorBody {
            did: key.delegator_did(),
            public_key: key
                .delegation()
                .delegator_verification_pubkey()
                .map_err(Error::CoreError)?,
            delegatee_public_key: key.delegatee_public_key(),
            node_type: OnlineNodeType::Native,
            network_id,
            storage_redundancy: DATA_REDUNDANT,
            dht_virtual_nodes: 0,
            capabilities,
            endpoint_hint: None,
            started_at_ms: 1,
            fresh_for_ms: u64::try_from(expires_at_ms.saturating_sub(HEARTBEAT_MS))
                .unwrap_or(u64::MAX),
            expires_at_ms,
            version: "test".to_string(),
        },
        MessageSigner::new(key, network_id),
    )
    .map(|descriptor| descriptor.heard_at(HEARTBEAT_MS))
    .map_err(Error::CoreError)
}

/// A live online-node descriptor of `key` registering `relay` at the current epoch.
fn live_relay(key: &DelegateeKey) -> Result<OnlineNodeDescriptor> {
    online_descriptor(
        key,
        OnlineNodeCapabilities::onion_relay(TEST_PROCESS_EPOCH),
        TEST_NETWORK_ID,
        EXPIRES_MS,
    )
}

/// The request for a loop over the `tcp` symbol.
fn tcp_request() -> OnionRouteRequest {
    OnionRouteRequest::from_service_name(OnionServiceName::tcp())
}

/// The local DHT protocol mode of every fixture.
fn test_dht_protocol() -> DhtProtocolMode {
    DhtProtocolMode::new(TEST_NETWORK_ID, DATA_REDUNDANT, 0)
}

/// Admit `online_nodes` and `exits` through the directory boundary for the `tcp` symbol.
fn tcp_candidates(
    local: Did,
    online_nodes: impl IntoIterator<Item = OnlineNodeDescriptor>,
    exits: impl IntoIterator<Item = OnionExitDescriptor>,
) -> OnionRouteCandidates {
    OnionRouteCandidates::from_validated_descriptors(
        local,
        test_dht_protocol(),
        NOW_MS,
        &OnionServiceName::tcp(),
        online_nodes,
        exits,
    )
}

/// Replay a fixed draw sequence, then `0`: every draw past the sequence takes the first
/// candidate by DID order.
struct FixedEntropy {
    values: VecDeque<u64>,
}

impl FixedEntropy {
    /// Replay `values` in order.
    fn new(values: impl IntoIterator<Item = u64>) -> Self {
        Self {
            values: values.into_iter().collect(),
        }
    }
}

impl RouteEntropy for FixedEntropy {
    fn next_u64(&mut self) -> u64 {
        self.values.pop_front().unwrap_or(0)
    }
}

/// Assert the loop laws of a selected route: `H = 5` positions, the guard at `1` and `H` only,
/// the exit at the symbol position, `H − 1` distinct hops, and the Phase 1 view `g, r₀,₂, h₁`.
fn assert_session_loop(route: &OnionRoute) {
    let hops = route.hops();
    let dids = hops.positions().map(|hop| hop.did).collect::<Vec<_>>();
    let guard = hops.guard().did;

    assert_eq!(dids.len(), 5);
    assert_eq!(dids.first(), Some(&guard));
    assert_eq!(dids.last(), Some(&guard));
    assert_eq!(dids.iter().filter(|did| **did == guard).count(), 2);
    assert_eq!(dids.get(2), Some(&route.exit_did()));
    assert_eq!(
        hops.open_path()
            .map(|hop| hop.did)
            .collect::<BTreeSet<_>>()
            .len(),
        4
    );
}

/// Selection places the `tcp` registrant at the symbol position and relay registrants
/// everywhere else, closing the loop through one guard (D4c, D5, L7).
#[test]
fn test_route_is_a_guard_closed_loop_of_registrants() -> Result<()> {
    let local = node_key(1)?.delegator_did();
    let relays = node_keys(2..=4)?;
    let exit = node_key(5)?;
    let online = relays
        .iter()
        .chain([&exit])
        .map(live_relay)
        .collect::<Result<Vec<_>>>()?;
    let registrants = relays
        .iter()
        .chain([&exit])
        .map(|key| key.delegator_did())
        .collect::<BTreeSet<_>>();

    let route = select_onion_route_from_candidates(
        &tcp_request(),
        tcp_candidates(local, online, [live_exit(&exit)?]),
        Vec::new(),
        &mut FixedEntropy::new([]),
        |_| true,
    )?;

    assert_session_loop(&route);
    assert_eq!(route.exit_did(), exit.delegator_did());
    assert_eq!(route.service(), "tcp");
    assert!(route
        .hops()
        .positions()
        .all(|hop| registrants.contains(&hop.did) && hop.process_epoch == TEST_PROCESS_EPOCH));
    assert!(route.hops().positions().all(|hop| hop.did != local));
    Ok(())
}

/// Fail closed (D5): below `H − 1 = 4` distinct relay registrants selection fails and never
/// shortens the loop; a node without the relay capability is not counted.
#[test]
fn test_selection_fails_closed_below_distinct_hop_bound() -> Result<()> {
    let local = node_key(1)?.delegator_did();
    let relays = node_keys(2..=3)?;
    let bystander = node_key(4)?;
    let exit = node_key(5)?;
    let mut online = relays
        .iter()
        .chain([&exit])
        .map(live_relay)
        .collect::<Result<Vec<_>>>()?;
    online.push(online_descriptor(
        &bystander,
        OnlineNodeCapabilities::default(),
        TEST_NETWORK_ID,
        EXPIRES_MS,
    )?);

    let result = select_onion_route_from_candidates(
        &tcp_request(),
        tcp_candidates(local, online, [live_exit(&exit)?]),
        Vec::new(),
        &mut FixedEntropy::new([]),
        |_| true,
    );

    assert!(matches!(
        result,
        Err(Error::OnionRouteError(OnionRouteError::NotEnoughLoopHops {
            required: 4,
            eligible: 3,
        }))
    ));
    Ok(())
}

/// Registration (D2): an exit is selected only while its process registers `relay` at the same
/// epoch. Each rejection names its cause: no relay registration at all, or a relay registration
/// of another process (stale).
#[test]
fn test_exit_requires_its_current_relay_registration() -> Result<()> {
    let local = node_key(1)?.delegator_did();
    let relays = node_keys(2..=4)?;
    let exit = node_key(5)?;
    let relay_less = node_key(6)?;
    let online = relays
        .iter()
        .chain([&exit])
        .map(live_relay)
        .chain([online_descriptor(
            &relay_less,
            OnlineNodeCapabilities::default(),
            TEST_NETWORK_ID,
            EXPIRES_MS,
        )])
        .collect::<Result<Vec<_>>>()?;
    let stale = exit_descriptor(&exit, STALE_PROCESS_EPOCH, TEST_NETWORK_ID, EXPIRES_MS)?;
    let select = |exits: Vec<OnionExitDescriptor>| {
        select_onion_route_from_candidates(
            &tcp_request(),
            tcp_candidates(local, online.clone(), exits),
            Vec::new(),
            &mut FixedEntropy::new([]),
            |_| true,
        )
    };

    assert!(matches!(
        select(vec![stale]),
        Err(Error::OnionRouteError(OnionRouteError::ExitRelayRegistrationMismatch { service }))
            if service == "tcp"
    ));
    assert!(matches!(
        select(vec![live_exit(&relay_less)?, live_exit(&node_key(7)?)?]),
        Err(Error::OnionRouteError(OnionRouteError::ExitWithoutRelayRegistration { service }))
            if service == "tcp"
    ));
    assert_eq!(
        select(vec![live_exit(&relay_less)?, live_exit(&exit)?])?.exit_did(),
        exit.delegator_did()
    );
    Ok(())
}

/// Descriptors past their expiry are not candidates.
#[test]
fn test_directory_candidates_reject_expired_remote_descriptors() -> Result<()> {
    let local = node_key(1)?.delegator_did();
    let relay = node_key(2)?;
    let expired_at = 40;

    let candidates = tcp_candidates(
        local,
        [online_descriptor(
            &relay,
            OnlineNodeCapabilities::onion_relay(TEST_PROCESS_EPOCH),
            TEST_NETWORK_ID,
            expired_at,
        )?],
        [exit_descriptor(
            &relay,
            TEST_PROCESS_EPOCH,
            TEST_NETWORK_ID,
            expired_at,
        )?],
    );

    assert!(candidates.relays.is_empty());
    assert!(candidates.exits.is_empty());
    Ok(())
}

/// Descriptors signed for another network are not candidates.
#[test]
fn test_directory_candidates_reject_foreign_network_descriptors() -> Result<()> {
    let local = node_key(1)?.delegator_did();
    let relay = node_key(2)?;
    let foreign_network = 2;

    let candidates = tcp_candidates(
        local,
        [online_descriptor(
            &relay,
            OnlineNodeCapabilities::onion_relay(TEST_PROCESS_EPOCH),
            foreign_network,
            EXPIRES_MS,
        )?],
        [exit_descriptor(
            &relay,
            TEST_PROCESS_EPOCH,
            foreign_network,
            EXPIRES_MS,
        )?],
    );

    assert!(candidates.relays.is_empty());
    assert!(candidates.exits.is_empty());
    Ok(())
}

/// Without a symbol registrant the route reports the service before any guard policy runs.
#[test]
fn test_route_builder_reports_no_live_exit_before_guard_filter() {
    let candidates = OnionRouteCandidates {
        relays: Vec::new(),
        exits: Vec::new(),
    };

    let result = select_onion_route_from_candidates(
        &tcp_request(),
        candidates,
        Vec::new(),
        &mut FixedEntropy::new([]),
        |_| false,
    );

    assert!(matches!(
        result,
        Err(Error::OnionRouteError(OnionRouteError::NoLiveExit {
            service
        })) if service == "tcp"
    ));
}

/// The candidates of `relays` plus the registrant `exit`, both at the current epoch.
fn candidates_with_exit(
    relays: &[DelegateeKey],
    exit: &DelegateeKey,
) -> Result<OnionRouteCandidates> {
    Ok(OnionRouteCandidates {
        relays: relays
            .iter()
            .chain([exit])
            .map(|key| hop(key, TEST_PROCESS_EPOCH))
            .collect(),
        exits: vec![live_exit(exit)?],
    })
}

/// The loop `g, r, symbol, r′, g` of a one-symbol pipeline, with `relays = [g, r, r′]`.
fn one_symbol_loop(
    relays: [OnionRouteHop; 3],
    symbol: OnionRouteHop,
) -> Result<OnionLoop<OnionRouteHop>> {
    let mut relays = relays.into_iter();
    OnionLoop::try_unfold(Vec::new(), symbol, |_| {
        relays.next().ok_or(Error::InvalidData)
    })
}

/// Draw a loop for the pipeline whose symbols are registered by the hops of `symbols`, and
/// relabel its symbol positions by those hops.
fn draw_loop(
    symbols: &[Vec<OnionRouteHop>],
    relays: &[OnionRouteHop],
    entropy: &mut FixedEntropy,
) -> Result<OnionLoop<OnionRouteHop>> {
    let relays = RelayRegistrants::new(relays.to_vec());
    let admitted = symbols
        .iter()
        .map(|registrants| relays.admit(registrants.iter(), |hop| **hop))
        .collect::<Vec<_>>();
    select_loop(
        OnionPipelineSymbols::new(&admitted).ok_or(Error::InvalidData)?,
        &relays,
        &BTreeMap::new(),
        entropy,
        |_| true,
    )
    .map(|drawn| drawn.project_symbols(|(hop, _)| *hop).0)
}

/// The guard is drawn by quality weight, over the relays in DID order: after the exit's draw, a
/// healthy guard (weight 8) wins a draw of `1` against a degraded one (weight 1) before it.
#[test]
fn test_guard_is_drawn_by_quality_weight() -> Result<()> {
    let relays = node_keys(1..=3)?;
    let exit = node_key(4)?;
    let (degraded, healthy) = match in_did_order(relays.as_slice()).as_slice() {
        [first, second, ..] => (first.delegator_did(), second.delegator_did()),
        _ => return Err(Error::InvalidData),
    };

    let route = select_onion_route_from_candidates(
        &tcp_request(),
        candidates_with_exit(relays.as_slice(), &exit)?,
        vec![
            (degraded, PeerQuality::Degraded),
            (healthy, PeerQuality::Healthy),
        ],
        &mut FixedEntropy::new([0, 1]),
        |did| did == degraded || did == healthy,
    )?;

    assert_session_loop(&route);
    assert_eq!(route.hops().guard().did, healthy);
    Ok(())
}

/// The guard is drawn from the permitted first hops only; later relays need no permission.
#[test]
fn test_guard_policy_constrains_the_guard_only() -> Result<()> {
    let relays = node_keys(1..=3)?;
    let exit = node_key(4)?;
    let direct = relays
        .last()
        .map(DelegateeKey::delegator_did)
        .ok_or(Error::InvalidData)?;

    let route = select_onion_route_from_candidates(
        &tcp_request(),
        candidates_with_exit(relays.as_slice(), &exit)?,
        Vec::new(),
        &mut FixedEntropy::new([]),
        |did| did == direct,
    )?;

    assert_session_loop(&route);
    assert_eq!(route.hops().guard().did, direct);
    Ok(())
}

/// Hall's filter keeps the sole symbol registrant out of the guard: it is first in DID order and
/// a permitted guard, so an unfiltered draw of `0` would take it, and the symbol position would
/// be stranded.
#[test]
fn test_hall_filter_keeps_the_sole_registrant_out_of_the_guard() -> Result<()> {
    let keys = node_keys(1..=4)?;
    let ordered = in_did_order(keys.as_slice());
    let registrant = ordered
        .first()
        .map(|key| key.delegator_did())
        .ok_or(Error::InvalidData)?;
    let relays = ordered
        .iter()
        .map(|key| hop(key, TEST_PROCESS_EPOCH))
        .collect::<Vec<_>>();

    let registrant_hop = relays
        .iter()
        .copied()
        .find(|hop| hop.did == registrant)
        .ok_or(Error::InvalidData)?;
    let hops = draw_loop(
        &[vec![registrant_hop]],
        relays.as_slice(),
        &mut FixedEntropy::new([]),
    )?;

    assert_ne!(hops.guard().did, registrant);
    assert_eq!(hops.symbol(1).map(|hop| hop.did), Some(registrant));
    Ok(())
}

/// A permitted guard that is also a registrant of the symbol is still drawn as guard when
/// another registrant can take the symbol position.
#[test]
fn test_guard_never_strands_the_symbol_position() -> Result<()> {
    let relays = node_keys(1..=2)?;
    let direct = node_key(3)?;
    let remote = node_key(4)?;
    let direct_did = direct.delegator_did();
    let candidates = OnionRouteCandidates {
        relays: relays
            .iter()
            .chain([&direct, &remote])
            .map(|key| hop(key, TEST_PROCESS_EPOCH))
            .collect(),
        exits: vec![live_exit(&direct)?, live_exit(&remote)?],
    };

    let route = select_onion_route_from_candidates(
        &tcp_request(),
        candidates,
        Vec::new(),
        &mut FixedEntropy::new([]),
        |did| did == direct_did,
    )?;

    assert_session_loop(&route);
    assert_eq!(route.hops().guard().did, direct_did);
    assert_eq!(route.exit_did(), remote.delegator_did());
    Ok(())
}

/// The only permitted guard cannot be the only symbol registrant: no loop exists.
#[test]
fn test_route_rejects_loop_without_permitted_guard() -> Result<()> {
    let relays = node_keys(1..=3)?;
    let exit = node_key(4)?;
    let exit_did = exit.delegator_did();
    let outsider = node_key(5)?.delegator_did();

    for permitted in [exit_did, outsider] {
        let result = select_onion_route_from_candidates(
            &tcp_request(),
            candidates_with_exit(relays.as_slice(), &exit)?,
            Vec::new(),
            &mut FixedEntropy::new([]),
            |did| did == permitted,
        );

        assert!(matches!(
            result,
            Err(Error::OnionRouteError(OnionRouteError::NoPermittedFirstHop))
        ));
    }
    Ok(())
}

/// Loop shape over `n` symbols: `H = 3n + 2`, the guard at `1` and `H` only, the `k`-th symbol
/// hop at `3k` drawn from the registrants of symbol `k`, every other position a relay registrant,
/// and `H − 1` distinct hops.
#[test]
fn test_select_loop_places_each_symbol_on_its_registrants() -> Result<()> {
    for symbols in 1..=MAX_ONION_LOOP_SYMBOLS {
        let shape = OnionLoopShape::new(symbols)?;
        let count = u8::try_from(shape.distinct_hops()).map_err(|_| Error::InvalidData)?;
        let keys = node_keys(1..=count)?;
        let relays = keys
            .iter()
            .map(|key| hop(key, TEST_PROCESS_EPOCH))
            .collect::<Vec<_>>();
        let registrants = relays
            .chunks(2)
            .take(symbols)
            .map(<[OnionRouteHop]>::to_vec)
            .collect::<Vec<_>>();

        let hops = draw_loop(
            registrants.as_slice(),
            relays.as_slice(),
            &mut FixedEntropy::new([]),
        )?;
        let dids = hops.positions().map(|hop| hop.did).collect::<Vec<_>>();

        assert_eq!(dids.len(), 3 * symbols + 2);
        assert_eq!(dids.first(), dids.last());
        assert!(!has_duplicate_dids(&hops));
        for (k, registrant) in registrants.iter().enumerate() {
            let symbol_hop = hops.symbol(k + 1);
            assert!(symbol_hop.is_some_and(|hop| registrant.contains(hop)));
            assert_eq!(
                symbol_hop.map(|hop| hop.did).as_ref(),
                dids.get(3 * (k + 1) - 1)
            );
        }
    }
    Ok(())
}

/// `n > n_max` is rejected before any draw.
#[test]
fn test_select_loop_rejects_more_than_max_symbols() -> Result<()> {
    let keys = node_keys(1..=16)?;
    let relays = keys
        .iter()
        .map(|key| hop(key, TEST_PROCESS_EPOCH))
        .collect::<Vec<_>>();

    assert!(matches!(
        draw_loop(
            &vec![relays.clone(); MAX_ONION_LOOP_SYMBOLS + 1],
            relays.as_slice(),
            &mut FixedEntropy::new([]),
        ),
        Err(Error::OnionRouteError(
            OnionRouteError::LoopSymbolsOutOfBounds {
                symbols: 5,
                max_symbols: 4,
            }
        ))
    ));
    Ok(())
}

/// Hall's condition steers the symbol draws: with `S₁ = {a}` and `S₂ = {a, b}` every loop puts
/// `a` at `h₁` and `b` at `h₂`, and with `S₁ = S₂ = {a}` no loop exists.
#[test]
fn test_select_loop_assigns_distinct_symbol_hops_when_possible() -> Result<()> {
    let keys = node_keys(1..=7)?;
    let relays = keys
        .iter()
        .map(|key| hop(key, TEST_PROCESS_EPOCH))
        .collect::<Vec<_>>();
    let (a, b) = match relays.as_slice() {
        [first, second, ..] => (*first, *second),
        _ => return Err(Error::InvalidData),
    };

    for draw in [0, 1, u64::MAX] {
        let hops = draw_loop(
            &[vec![a], vec![a, b]],
            relays.as_slice(),
            &mut FixedEntropy::new([draw; 8]),
        )?;

        assert_eq!(hops.symbol(1), Some(&a));
        assert_eq!(hops.symbol(2), Some(&b));
        assert!(!has_duplicate_dids(&hops));
    }
    assert!(matches!(
        draw_loop(
            &[vec![a], vec![a]],
            relays.as_slice(),
            &mut FixedEntropy::new([]),
        ),
        Err(Error::OnionRouteError(
            OnionRouteError::NoDistinctSymbolHops
        ))
    ));
    Ok(())
}

/// Hall's condition counts only drawable candidates: a registrant outside the relays cannot
/// vouch for the symbol position. With `S = {x, a}`, `x` registering no relay, the guard draw
/// must leave `a` to the symbol although `a` is first in DID order and a permitted guard.
#[test]
fn test_hall_filter_ignores_registrants_outside_the_relays() -> Result<()> {
    let keys = node_keys(1..=5)?;
    let ordered = in_did_order(keys.as_slice());
    let (phantom, relays) = match ordered.split_last() {
        Some((phantom, relays)) => (
            hop(phantom, TEST_PROCESS_EPOCH),
            relays
                .iter()
                .map(|key| hop(key, TEST_PROCESS_EPOCH))
                .collect::<Vec<_>>(),
        ),
        None => return Err(Error::InvalidData),
    };
    let first = *relays.first().ok_or(Error::InvalidData)?;

    let hops = draw_loop(
        &[vec![phantom, first]],
        relays.as_slice(),
        &mut FixedEntropy::new([]),
    )?;

    assert_ne!(hops.guard().did, first.did);
    assert_eq!(hops.symbol(1), Some(&first));
    assert!(hops.positions().all(|hop| hop.did != phantom.did));
    Ok(())
}

/// Guard closure (L7): `has_duplicate_dids` admits the guard exactly twice, at `1` and `H`, and
/// rejects any other repetition, of the guard or of another hop.
#[test]
fn test_has_duplicate_dids_admits_exactly_the_guard_twice() -> Result<()> {
    let keys = node_keys(1..=4)?;
    let at = |index: usize| {
        keys.get(index)
            .map(|key| hop(key, TEST_PROCESS_EPOCH))
            .ok_or(Error::InvalidData)
    };
    let labelled = |[guard, relay, symbol, back]: [usize; 4]| {
        one_symbol_loop([at(guard)?, at(relay)?, at(back)?], at(symbol)?)
    };

    let distinct = labelled([0, 1, 2, 3])?;
    assert!(!has_duplicate_dids(&distinct));
    assert_eq!(
        distinct
            .positions()
            .filter(|hop| hop.did == distinct.guard().did)
            .count(),
        2
    );
    assert!(has_duplicate_dids(&labelled([0, 0, 2, 3])?));
    assert!(has_duplicate_dids(&labelled([0, 1, 2, 0])?));
    assert!(has_duplicate_dids(&labelled([0, 1, 2, 1])?));
    Ok(())
}

/// Draw order (L7): the exit is drawn before the guard and the relays, so its marginal is its
/// quality share among the exits, and a high-quality exit is not consumed as the guard first.
///
/// With `R = {x, a, b, c}`, exits `{x (Healthy, 8), a (Unknown, 4)}` and every relay a permitted
/// guard, the exit roll is taken modulo `12` and the guard roll modulo `12` or `16`, so every
/// pair of rolls in `[0, 48)²` enumerates the two draws exactly:
///
/// ```text
/// P(exit = x)  = 8/12            = 2/3     1536 of 2304
/// P(guard = x) = P(exit = a)·8/16 = 1/6     384 of 2304
/// ```
#[test]
fn test_exit_and_guard_marginals_follow_the_draw_order() -> Result<()> {
    let keys = node_keys(1..=4)?;
    let (x, a) = match keys.as_slice() {
        [x, a, ..] => (x.delegator_did(), a.delegator_did()),
        _ => return Err(Error::InvalidData),
    };
    let candidates = OnionRouteCandidates {
        relays: keys
            .iter()
            .map(|key| hop(key, TEST_PROCESS_EPOCH))
            .collect(),
        exits: keys
            .get(..2)
            .unwrap_or_default()
            .iter()
            .map(live_exit)
            .collect::<Result<Vec<_>>>()?,
    };
    let mut exits_at_x = 0;
    let mut guards_at_x = 0;

    for exit_roll in 0..48 {
        for guard_roll in 0..48 {
            let route = select_onion_route_from_candidates(
                &tcp_request(),
                candidates.clone(),
                vec![(x, PeerQuality::Healthy)],
                &mut FixedEntropy::new([exit_roll, guard_roll]),
                |_| true,
            )?;
            exits_at_x += usize::from(route.exit_did() == x);
            guards_at_x += usize::from(route.hops().guard().did == x);
            assert!([x, a].contains(&route.exit_did()));
        }
    }

    assert_eq!(exits_at_x, 1536);
    assert_eq!(guards_at_x, 384);
    Ok(())
}

/// Fail closed first (D5): below `H − 1` relays the error is `NotEnoughLoopHops`, whatever the
/// guard policy admits.
#[test]
fn test_fail_closed_is_checked_before_the_guard_policy() -> Result<()> {
    let relays = node_keys(1..=2)?;
    let exit = node_key(3)?;

    let result = select_onion_route_from_candidates(
        &tcp_request(),
        candidates_with_exit(relays.as_slice(), &exit)?,
        Vec::new(),
        &mut FixedEntropy::new([]),
        |_| false,
    );

    assert!(matches!(
        result,
        Err(Error::OnionRouteError(OnionRouteError::NotEnoughLoopHops {
            required: 4,
            eligible: 3,
        }))
    ));
    Ok(())
}

/// One registration per DID: the relay registrants and the admitted symbol registrants keep the
/// first registration of each DID, and a symbol hop that is not the DID's relay registration is
/// not admitted (D2).
#[test]
fn test_registrants_keep_one_registration_per_did() -> Result<()> {
    let keys = node_keys(1..=2)?;
    let [first, second] = keys.as_slice() else {
        return Err(Error::InvalidData);
    };
    let relay = hop(first, TEST_PROCESS_EPOCH);
    let other = hop(second, TEST_PROCESS_EPOCH);
    let relays = RelayRegistrants::new(vec![relay, other, relay]);
    assert_eq!(relays.0.len(), 2);

    let stale = hop(second, STALE_PROCESS_EPOCH);
    let admitted = relays.admit([(relay, 'a'), (relay, 'b'), (stale, 'c')], |(hop, _)| *hop);

    assert_eq!(admitted.dids(), [relay.did].as_slice());
    assert_eq!(
        admitted.registrations,
        vec![(relay, (relay, 'a'))],
        "the first registration of a DID is kept, a stale hop is not admitted"
    );
    Ok(())
}

/// Multi-stage `invoke` pipeline route selection (#834 Phase 2b, D2, D5, L7): selects pairwise
/// distinct registrants per `(shape, backend)` stage at their current relay epoch, closes the
/// `H = 8` loop through one guard, and reports missing/stale/relay-less `invoke` registrants.
#[test]
fn test_pipeline_route_selection_places_multi_stage_invoke_symbols() -> Result<()> {
    use crate::onion::route::OnionPipelineRouteCandidates;
    use crate::onion::OnionBackendName;
    use crate::onion::OnionInputType;
    use crate::onion::OnionInvokeDescriptor;
    use crate::onion::OnionInvokeDescriptorBody;
    use crate::onion::OnionInvokePolicy;
    use crate::onion::OnionInvokeShape;
    use crate::onion::OnionLatencyClass;
    use crate::onion::OnionPipelineRouteRequest;
    use crate::onion::OnionWidthClass;

    let local = node_key(1)?.delegator_did();
    let relays = node_keys(2..=6)?;
    let stage1_host = node_key(7)?;
    let stage2_host = node_key(8)?;
    let shape1 = OnionInvokeShape::new(
        OnionInputType::Fixed(OnionWidthClass::B32),
        OnionWidthClass::B64,
        OnionLatencyClass::Ms10,
    );
    let shape2 = OnionInvokeShape::new(
        OnionInputType::Fixed(OnionWidthClass::B64),
        OnionWidthClass::B32,
        OnionLatencyClass::Ms100,
    );
    let backend1 = OnionBackendName::parse("add.v1")?;
    let backend2 = OnionBackendName::parse("jev.typesafe")?;

    let sign_invoke = |key: &DelegateeKey,
                       epoch: OnionProcessEpoch,
                       shape: OnionInvokeShape,
                       backend: OnionBackendName|
     -> Result<OnionInvokeDescriptor> {
        OnionInvokeDescriptor::new_signed(
            OnionInvokeDescriptorBody {
                did: key.delegator_did(),
                public_key: key
                    .delegation()
                    .delegator_verification_pubkey()
                    .map_err(Error::CoreError)?,
                delegatee_public_key: key.delegatee_public_key(),
                process_epoch: epoch,
                node_type: OnlineNodeType::Native,
                network_id: TEST_NETWORK_ID,
                shape,
                backend,
                policy: OnionInvokePolicy::default(),
                started_at_ms: 1,
                fresh_for_ms: 90,
                expires_at_ms: EXPIRES_MS,
                version: "test".to_string(),
            },
            MessageSigner::new(key, TEST_NETWORK_ID),
        )
        .map(|desc| desc.heard_at(HEARTBEAT_MS))
        .map_err(Error::CoreError)
    };

    let online = relays
        .iter()
        .chain([&stage1_host, &stage2_host])
        .map(live_relay)
        .collect::<Result<Vec<_>>>()?;
    let invokes = vec![
        sign_invoke(&stage1_host, TEST_PROCESS_EPOCH, shape1, backend1.clone())?,
        sign_invoke(&stage2_host, TEST_PROCESS_EPOCH, shape2, backend2.clone())?,
    ];
    let request =
        OnionPipelineRouteRequest::new([(shape1, backend1.clone()), (shape2, backend2.clone())])?;
    let candidates = OnionPipelineRouteCandidates::from_validated_descriptors(
        local,
        test_dht_protocol(),
        NOW_MS,
        online.clone(),
        invokes,
    );

    let route = select_onion_pipeline_route_from_candidates(
        &request,
        candidates,
        Vec::new(),
        &mut FixedEntropy::new([]),
        |_| true,
    )?;
    assert_eq!(route.hops().positions().count(), 8);
    assert!(!has_duplicate_dids(route.hops()));
    assert_eq!(
        route.hops().symbol(1).map(|hop| hop.did),
        Some(stage1_host.delegator_did())
    );
    assert_eq!(
        route.hops().symbol(2).map(|hop| hop.did),
        Some(stage2_host.delegator_did())
    );
    assert_eq!(route.descriptors().len(), 2);

    // Stale invoke epoch on stage 2 fails closed with SymbolRelayRegistrationMismatch.
    let stale_candidates = OnionPipelineRouteCandidates::from_validated_descriptors(
        local,
        test_dht_protocol(),
        NOW_MS,
        online,
        [
            sign_invoke(&stage1_host, TEST_PROCESS_EPOCH, shape1, backend1)?,
            sign_invoke(&stage2_host, STALE_PROCESS_EPOCH, shape2, backend2)?,
        ],
    );
    assert!(matches!(
        select_onion_pipeline_route_from_candidates(
            &request,
            stale_candidates,
            Vec::new(),
            &mut FixedEntropy::new([]),
            |_| true,
        ),
        Err(Error::OnionRouteError(
            OnionRouteError::SymbolRelayRegistrationMismatch { ref backend, .. }
        )) if backend == "jev.typesafe"
    ));
    Ok(())
}