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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
//! Links as core generations, their ledgers, the table bound, reconciliation, and the epoch reset.

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;

use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use rand::Rng;
use rand::SeedableRng;
use rings_core::dht::Did;
use rings_core::message::SlotFloorUse;
use rings_core::message::SlotRoster;

use super::super::OnionAdmissionLink;
use super::super::OnionSlotId;
use super::generation;
use super::latest_expiry;
use super::layer;
use super::link;
use super::live_filters;
use super::open;
use super::registry;
use super::send;
use super::send_on;
use super::sender_load;
use super::state;
use super::state_with;
use super::units;
use super::Verdict;
use super::EPOCH;
use super::ORIGIN_MS;
use super::Q;
use crate::onion::circuit::admission::OnionAdmissionLayer;
use crate::onion::circuit::admission::OnionAdmissionRejection;
use crate::onion::circuit::admission::OnionAdmissionState;
use crate::onion::circuit::admission::OnionChargeRejection;
use crate::onion::circuit::admission::OnionEpochNotFresh;
use crate::onion::circuit::admission::OnionLinkTableFull;
use crate::onion::circuit::admission::OnionReplayFilterKey;
use crate::onion::circuit::admission::ADMISSION_WINDOW_QUANTA_WIDE;
use crate::onion::circuit::admission::ONION_ADMISSION_SENDER_UNITS;
use crate::onion::circuit::admission::ONION_ADMISSION_SLOT_FLOOR_UNITS;
use crate::onion::circuit::ONION_ADMISSION_WINDOW_MS;
use crate::onion::OnionProcessEpoch;

/// Law: there is no fixed sender limit and no lockout. With `R = 100`, 150 live links, more than
/// the old 64 partitions, are all admitted.
#[test]
fn test_more_than_64_live_links_are_all_admitted() {
    let mut rng = StdRng::seed_from_u64(0x0841_000a);
    let mut admission = state_with(&mut rng, EPOCH, 100, 0..150);
    let x = latest_expiry(ORIGIN_MS);
    for sender in 0..150_u32 {
        assert_eq!(
            send(
                &mut admission,
                ORIGIN_MS,
                sender,
                1,
                layer(x, u128::from(sender))
            ),
            Verdict::Admitted
        );
    }
    assert_eq!(admission.slots.len(), 150);
}

/// Law: closing a link does not reset its ledger while it carries load, even under heavy Sybil
/// churn. A DID spends `B` and closes its link. 38 churning DIDs (`> 2·R` for `R = 8`) then open,
/// send and close within `V`: because ledgers are keyed by connection slot via [`SlotRoster`],
/// none of the churners triggers [`OnionLinkTableFull`], and cleanest-first slot assignment keeps
/// them on the cleaner slots `1..16`. When the original DID reconnects within the window as a new
/// generation, it resumes its retained slot ledger and is still over budget. Once the window
/// passes, the sweep releases every drained churner slot.
#[test]
fn test_closed_link_keeps_its_ledger_until_it_drains() {
    const R: usize = 8;
    let mut rng = StdRng::seed_from_u64(0x0841_000b);
    let mut admission = state_with(&mut rng, EPOCH, R, 1..2);
    let x = latest_expiry(ORIGIN_MS);
    let spender = Did::from(1_u32);
    let spender_slot = admission.slot_of(spender).expect("spender holds a slot");
    assert_eq!(
        send(
            &mut admission,
            ORIGIN_MS,
            1,
            ONION_ADMISSION_SENDER_UNITS,
            layer(x, 1)
        ),
        Verdict::Admitted
    );
    admission.link_closed(ORIGIN_MS, link(1));
    for churner in 2..40_u32 {
        open(&mut admission, ORIGIN_MS + 1, link(churner));
        assert_eq!(
            send(
                &mut admission,
                ORIGIN_MS + 1,
                churner,
                1,
                layer(x, u128::from(churner))
            ),
            Verdict::Admitted
        );
        admission.link_closed(ORIGIN_MS + 1, link(churner));
        assert!(admission.slots.len() <= 2 * R);
    }
    assert_eq!(admission.slot_of(spender), Some(spender_slot));
    open(&mut admission, ORIGIN_MS + 2, generation(1, 1));
    assert_eq!(admission.slot_of(spender), Some(spender_slot));
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS + 2,
            generation(1, 1),
            1,
            layer(x, 100)
        ),
        Verdict::Unpaid(OnionChargeRejection::SenderBudget)
    );
    let drained = ORIGIN_MS + ONION_ADMISSION_WINDOW_MS;
    assert_eq!(
        send_on(
            &mut admission,
            drained,
            generation(1, 1),
            1,
            layer(latest_expiry(drained), 101)
        ),
        Verdict::Admitted
    );
    assert_eq!(admission.slots.keys().collect::<Vec<_>>(), vec![
        &spender_slot
    ]);
    assert_eq!(admission.peer_slots.keys().collect::<Vec<_>>(), vec![
        &spender
    ]);
}

/// Law: when `2·R` links are already live, the table refuses a new link, and the refused link's
/// cells are never charged or decrypted. The shell's close of that refused link is a no-op. Once a
/// live link closes, its connection slot is freed in [`SlotRoster`], so the peer's redial (a new
/// generation) succeeds immediately and inherits the slot's residual load.
#[test]
fn test_full_table_refuses_the_link_and_the_peer_redials() {
    let mut rng = StdRng::seed_from_u64(0x0841_000c);
    let mut admission = state_with(&mut rng, EPOCH, 1, 1..3);
    let x = latest_expiry(ORIGIN_MS);
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 1, 1, layer(x, 1)),
        Verdict::Admitted
    );
    assert_eq!(
        admission.link_opened(ORIGIN_MS, link(3)),
        Err(OnionLinkTableFull)
    );
    let before = admission.slots.clone();
    admission.link_closed(ORIGIN_MS, link(3));
    assert_eq!(admission.slots, before);
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 3, 1, layer(x, 3)),
        Verdict::Unpaid(OnionChargeRejection::LinkNotLive)
    );

    admission.link_closed(ORIGIN_MS, link(1));
    open(&mut admission, ORIGIN_MS + 1, generation(3, 1));
    assert_eq!(sender_load(&admission, 3, ORIGIN_MS + 1), Some(1));
    assert_eq!(
        admission.link_opened(ORIGIN_MS + 1, link(4)),
        Err(OnionLinkTableFull)
    );
    let drained = ORIGIN_MS + ONION_ADMISSION_WINDOW_MS;
    assert_eq!(
        send_on(
            &mut admission,
            drained,
            generation(3, 1),
            1,
            layer(latest_expiry(drained), 3)
        ),
        Verdict::Admitted
    );
    assert!(!admission.peer_slots.contains_key(&Did::from(1_u32)));
    assert!(admission.peer_slots.contains_key(&Did::from(2_u32)));
    assert!(admission.peer_slots.contains_key(&Did::from(3_u32)));
}

/// Law: liveness is per generation, so interleaved generations of one DID
/// (`open(g₀) open(g₁) close(g₀)`) leave `g₁` live and `g₀` not. Only the last close, together with
/// a drained load, releases the DID's slot ledger.
#[test]
fn test_ledger_counts_interleaved_link_generations() {
    let mut rng = StdRng::seed_from_u64(0x0841_0010);
    let mut admission = state_with(&mut rng, EPOCH, 4, 0..0);
    let peer = Did::from(1_u32);
    open(&mut admission, ORIGIN_MS, generation(1, 0));
    open(&mut admission, ORIGIN_MS, generation(1, 1));
    admission.link_closed(ORIGIN_MS, generation(1, 0));
    let x = latest_expiry(ORIGIN_MS);
    assert_eq!(
        send_on(&mut admission, ORIGIN_MS, generation(1, 0), 1, layer(x, 1)),
        Verdict::Unpaid(OnionChargeRejection::LinkNotLive)
    );
    assert_eq!(
        send_on(&mut admission, ORIGIN_MS, generation(1, 1), 1, layer(x, 1)),
        Verdict::Admitted
    );
    admission.link_closed(ORIGIN_MS, generation(1, 1));
    assert!(admission.peer_slots.contains_key(&peer));
    let drained = ORIGIN_MS + ONION_ADMISSION_WINDOW_MS;
    assert_eq!(
        send_on(
            &mut admission,
            drained,
            generation(1, 1),
            1,
            layer(latest_expiry(drained), 2)
        ),
        Verdict::Unpaid(OnionChargeRejection::LinkNotLive)
    );
    assert!(admission.slots.is_empty());
    assert!(admission.peer_slots.is_empty());
}

/// Law: a close is idempotent and specific to its generation. A late close of a refused `g₀`, a
/// repeated close, and a close of an unknown generation all leave the live `g₁` live, across
/// later windows, so no stale close can lock a link out.
#[test]
fn test_a_refused_generation_cannot_close_a_live_one() {
    let mut rng = StdRng::seed_from_u64(0x0841_0012);
    let mut admission = state_with(&mut rng, EPOCH, 1, 1..3);
    let x = latest_expiry(ORIGIN_MS);
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 1, 1, layer(x, 1)),
        Verdict::Admitted
    );
    assert_eq!(
        admission.link_opened(ORIGIN_MS, generation(3, 0)),
        Err(OnionLinkTableFull)
    );
    admission.link_closed(ORIGIN_MS, link(1));
    let drained = ORIGIN_MS + ONION_ADMISSION_WINDOW_MS;
    open(&mut admission, drained, generation(3, 1));
    admission.link_closed(drained, generation(3, 0));
    admission.link_closed(drained, generation(3, 0));
    admission.link_closed(drained, generation(3, 7));
    for window in 1..4_u128 {
        let now_ms = drained + window * ONION_ADMISSION_WINDOW_MS;
        assert_eq!(
            send_on(
                &mut admission,
                now_ms,
                generation(3, 1),
                1,
                layer(latest_expiry(now_ms), window)
            ),
            Verdict::Admitted
        );
    }
}

/// Law: the epoch reset keeps the table's own live links, `ρ = reconcile(live_links(S)) ∘ clear`,
/// and refuses none. Every live link starts with a zero ledger. The reset clears the loads, the
/// clock and the replay store, and drops every ledger without a live link. Every layer of the
/// old epoch is then rejected, and so is every token charged before the reset, because its epoch
/// differs; a DID that had no live link is still not live.
#[test]
fn test_renewal_keeps_the_live_links_and_clears_the_rest() {
    let mut rng = StdRng::seed_from_u64(0x0841_0015);
    let mut admission = state_with(&mut rng, EPOCH, 4, 1..3);
    let x = latest_expiry(ORIGIN_MS);
    assert_eq!(
        send(
            &mut admission,
            ORIGIN_MS,
            1,
            ONION_ADMISSION_SENDER_UNITS,
            layer(x, 1)
        ),
        Verdict::Admitted
    );
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 2, 1, layer(x, 2)),
        Verdict::Admitted
    );
    let held = admission
        .charge_units(ORIGIN_MS, link(2), units(1))
        .expect("DID 2 has headroom");
    let renewed_epoch = OnionProcessEpoch::new([8; 16]);
    assert_eq!(
        admission.renew(renewed_epoch, OnionReplayFilterKey::new(rng.gen())),
        Ok(())
    );
    assert_eq!(admission.clock_ms, 0);
    assert_eq!(live_filters(&admission), Vec::new());
    assert_eq!(admission.peer_slots.keys().collect::<Vec<_>>(), vec![
        &Did::from(1_u32),
        &Did::from(2_u32)
    ]);
    assert_eq!(sender_load(&admission, 1, ORIGIN_MS), Some(0));
    assert_eq!(sender_load(&admission, 2, ORIGIN_MS), Some(0));
    assert_eq!(
        admission.admit(ORIGIN_MS, held, OnionAdmissionLayer {
            epoch: renewed_epoch,
            ..layer(x, 4)
        }),
        Err(OnionAdmissionRejection::StaleEpoch)
    );
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 1, 1, layer(x, 1)),
        Verdict::Rejected(OnionAdmissionRejection::StaleEpoch)
    );
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 1, 1, OnionAdmissionLayer {
            epoch: renewed_epoch,
            ..layer(x, 1)
        }),
        Verdict::Admitted
    );
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 3, 1, layer(x, 3)),
        Verdict::Unpaid(OnionChargeRejection::LinkNotLive)
    );
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 2, 1, OnionAdmissionLayer {
            epoch: renewed_epoch,
            ..layer(x, 5)
        }),
        Verdict::Admitted
    );
}

/// Law (M1 of the round-5 review): renewing into the current epoch is refused and changes nothing,
/// so the replay store survives and an admitted `(x, ν)` cannot be admitted again.
#[test]
fn test_a_same_epoch_renewal_is_refused_and_cannot_readmit_a_replay() {
    let mut rng = StdRng::seed_from_u64(0x0841_0017);
    let mut admission = state(&mut rng);
    let x = latest_expiry(ORIGIN_MS);
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 1, 1, layer(x, 1)),
        Verdict::Admitted
    );
    assert_eq!(
        admission.renew(EPOCH, OnionReplayFilterKey::new(rng.gen())),
        Err(OnionEpochNotFresh)
    );
    assert_eq!(admission.clock_ms, ORIGIN_MS);
    assert_eq!(live_filters(&admission), vec![x]);
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 1, 1, layer(x, 1)),
        Verdict::Rejected(OnionAdmissionRejection::Replayed)
    );
}

/// Law (M2 of the round-5 review): lost `Retired` events pin live links until the shell
/// reconciles with core's snapshot. Here every `Retired` is lost, so the table fills and refuses a
/// newcomer. `reconcile` then closes every generation absent from the snapshot, opens the snapshot
/// generation that was never reported (a lost `Admitted`), and returns the links it refuses.
#[test]
fn test_reconcile_recovers_lost_link_events() {
    let mut rng = StdRng::seed_from_u64(0x0841_0018);
    let mut admission = state_with(&mut rng, EPOCH, 2, 1..5);
    assert_eq!(
        admission.link_opened(ORIGIN_MS, link(5)),
        Err(OnionLinkTableFull)
    );
    let refused = admission.reconcile(ORIGIN_MS, [link(1), generation(6, 3)]);
    assert!(refused.links().is_empty());
    assert_eq!(admission.peer_slots.keys().collect::<Vec<_>>(), vec![
        &Did::from(1_u32),
        &Did::from(6_u32)
    ]);
    open(&mut admission, ORIGIN_MS, link(5));
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS,
            generation(6, 3),
            1,
            layer(latest_expiry(ORIGIN_MS), 1)
        ),
        Verdict::Admitted
    );
    assert_eq!(
        send(
            &mut admission,
            ORIGIN_MS,
            2,
            1,
            layer(latest_expiry(ORIGIN_MS), 2)
        ),
        Verdict::Unpaid(OnionChargeRejection::LinkNotLive)
    );

    // DIDs 1, 5, and 6 are absent from `crowded`, so `reconcile` closes all three and frees their
    // connection slots (`0..4`), while DID 6's slot retains its 1 unit of residual load. All four
    // slots can therefore admit new live links (`10..14`), and `14..20` are refused.
    let crowded = (10..20).map(link).collect::<Vec<_>>();
    let refused = admission.reconcile(ORIGIN_MS, crowded);
    assert_eq!(
        refused.links(),
        (14..20).map(link).collect::<Vec<_>>().as_slice()
    );
    assert_eq!(admission.slots.len(), 4);
    assert_eq!(
        admission.slot_of(Did::from(6_u32)),
        Some(OnionSlotId::new(1))
    );
    assert_eq!(sender_load(&admission, 13, ORIGIN_MS), Some(1));
}

/// Law (#1183): rotating `> 2·R` Sybil connections within a single window `V` never triggers
/// [`OnionLinkTableFull`] for an admitted connection slot, [`SlotRoster`]'s cleanest-first slot
/// assignment gives an arriving honest peer an uncharged slot whenever one is free, and peers
/// mapped to the same slot share one [`SlotLedger`] and its `B` budget.
#[test]
fn test_sybil_churn_beyond_2r_never_locks_out_admitted_slot_and_assigns_cleanest_first() {
    const R: usize = 8;
    let mut rng = StdRng::seed_from_u64(0x0841_0021);
    let mut admission = state_with(&mut rng, EPOCH, R, 1..2);
    let x = latest_expiry(ORIGIN_MS);

    // Rotate 100 > 2·R Sybil connections within V, each sending 1 unit and disconnecting.
    for sybil in 100..200_u32 {
        assert_eq!(admission.link_opened(ORIGIN_MS + 1, link(sybil)), Ok(()));
        assert_eq!(
            send(
                &mut admission,
                ORIGIN_MS + 1,
                sybil,
                1,
                layer(x, u128::from(sybil))
            ),
            Verdict::Admitted
        );
        admission.link_closed(ORIGIN_MS + 1, link(sybil));
    }
    // Honest peer 1 on slot 0 is untouched (0 units spent), and a new honest peer 2 is admitted
    // without `OnionLinkTableFull` into the cleanest free slot.
    assert_eq!(sender_load(&admission, 1, ORIGIN_MS + 1), Some(0));
    assert_eq!(admission.link_opened(ORIGIN_MS + 2, link(2)), Ok(()));
    assert_eq!(
        send(&mut admission, ORIGIN_MS + 2, 2, 1, layer(x, 500)),
        Verdict::Admitted
    );

    // Cleanest-first rotation residual (Prop. 1(3)): on a fresh table with `2·R = 16` slots, 15
    // rotating attackers each fill their slot's floor `f` and depart. Because slot 15 is still
    // clean, an arriving honest peer takes slot 15 with zero inherited load; a second peer that
    // later takes one of the charged slots shares that slot's ledger and `B` budget.
    let roster = Arc::new(SlotRoster::new(2 * R));
    let mut clean_first =
        OnionAdmissionState::new(EPOCH, OnionReplayFilterKey::new(rng.gen()), registry(R))
            .with_slot_roster(Arc::clone(&roster));
    for attacker in 0..15_u32 {
        let did = 1_000 + attacker;
        roster.arrive(Did::from(did), &SlotFloorUse::default());
        open(&mut clean_first, ORIGIN_MS, link(did));
        assert_eq!(
            send(
                &mut clean_first,
                ORIGIN_MS,
                did,
                ONION_ADMISSION_SLOT_FLOOR_UNITS,
                layer(x, u128::from(did))
            ),
            Verdict::Admitted
        );
        clean_first.link_closed(ORIGIN_MS, link(did));
        roster.depart(Did::from(did));
    }
    roster.arrive(Did::from(50_u32), &SlotFloorUse::default());
    open(&mut clean_first, ORIGIN_MS, link(50));
    assert_eq!(
        clean_first.slot_of(Did::from(50_u32)),
        Some(OnionSlotId::new(15))
    );
    assert_eq!(sender_load(&clean_first, 50, ORIGIN_MS), Some(0));

    // The next arriving peer (51) takes slot 0 (which already carries `f` units from attacker
    // 1_000) and shares slot 0's `ONION_ADMISSION_SENDER_UNITS` budget with it.
    roster.arrive(Did::from(51_u32), &SlotFloorUse::default());
    open(&mut clean_first, ORIGIN_MS, link(51));
    assert_eq!(
        clean_first.slot_of(Did::from(51_u32)),
        Some(OnionSlotId::new(0))
    );
    assert_eq!(
        sender_load(&clean_first, 51, ORIGIN_MS),
        Some(ONION_ADMISSION_SLOT_FLOOR_UNITS)
    );
    let remaining_slot_budget = ONION_ADMISSION_SENDER_UNITS - ONION_ADMISSION_SLOT_FLOOR_UNITS;
    assert_eq!(
        send(
            &mut clean_first,
            ORIGIN_MS,
            51,
            remaining_slot_budget,
            layer(x, 2_000)
        ),
        Verdict::Admitted
    );
    assert_eq!(
        send(&mut clean_first, ORIGIN_MS, 51, 1, layer(x, 2_001)),
        Verdict::Unpaid(OnionChargeRejection::SenderBudget)
    );

    // Retained identities expire once their own retirement window elapses, even when a successor
    // peer on the same slot keeps the slot's aggregate ledger load positive across quanta.
    assert_eq!(
        send(&mut clean_first, ORIGIN_MS, 50, 1, layer(x, 2_500)),
        Verdict::Admitted
    );
    clean_first.link_closed(ORIGIN_MS, link(50));
    roster.depart(Did::from(50_u32));
    roster.arrive(Did::from(52_u32), &SlotFloorUse::default());
    open(&mut clean_first, ORIGIN_MS, link(52));
    assert_eq!(
        clean_first.slot_of(Did::from(52_u32)),
        Some(OnionSlotId::new(15))
    );
    for step in 1..=5_u128 {
        let now = ORIGIN_MS + step * Q;
        let expiry = latest_expiry(now);
        assert_eq!(
            send(&mut clean_first, now, 52, 1, layer(expiry, 3_000 + step)),
            Verdict::Admitted
        );
    }
    assert_eq!(clean_first.slot_of(Did::from(50_u32)), None);
    assert_eq!(
        clean_first.slot_of(Did::from(52_u32)),
        Some(OnionSlotId::new(15))
    );
    assert_eq!(sender_load(&clean_first, 52, ORIGIN_MS + 5 * Q), Some(5));

    // Disconnecting peers that sent zero Onion cells on a charged slot leave no retained identity
    // in `slot.retained` or `peer_slots`, keeping identity state bounded by `2·R + B·S`.
    let zero_cell_now = ORIGIN_MS + 5 * Q;
    for zero_peer in 10_000..10_100_u32 {
        clean_first.link_closed(zero_cell_now, link(52));
        roster.depart(Did::from(52_u32));
        roster.arrive(Did::from(zero_peer), &SlotFloorUse::default());
        open(&mut clean_first, zero_cell_now, link(zero_peer));
        clean_first.link_closed(zero_cell_now, link(zero_peer));
        roster.depart(Did::from(zero_peer));
        assert_eq!(clean_first.slot_of(Did::from(zero_peer)), None);
        roster.arrive(Did::from(52_u32), &SlotFloorUse::default());
        open(&mut clean_first, zero_cell_now, link(52));
    }
}

/// Law (#1183): `reconcile` allocates connection slots without depending on `Did` ordering, so an
/// attacker who grinds small `Did`s gains no advantage over honest peers with larger `Did`s.
#[test]
fn test_reconcile_does_not_depend_on_did_ordering() {
    let mut rng = StdRng::seed_from_u64(0x0841_0022);
    let mut admission = state_with(&mut rng, EPOCH, 2, 0..0);

    // 4 honest peers with large DIDs were admitted at earlier generations `0..4`, while 4 Sybil
    // peers with ground small DIDs (`1..=4`) were admitted at later generations `4..8`.
    let honest = [
        generation(10_000, 0),
        generation(20_000, 1),
        generation(30_000, 2),
        generation(40_000, 3),
    ];
    let sybils = [
        generation(1, 4),
        generation(2, 5),
        generation(3, 6),
        generation(4, 7),
    ];
    let snapshot = sybils
        .iter()
        .chain(honest.iter())
        .copied()
        .collect::<Vec<_>>();
    let refused = admission.reconcile(ORIGIN_MS, snapshot);
    assert_eq!(refused.links(), &sybils);
    let mut expected_live = honest.to_vec();
    expected_live.sort();
    assert_eq!(admission.live_links(), expected_live);
}

/// Law (memory bound): the live-link set is capped at `2·R` even for one DID. That can only be
/// reached if the event obligation is broken, so that many generations of one DID stay live.
#[test]
fn test_live_links_are_capped_as_a_memory_bound() {
    let mut rng = StdRng::seed_from_u64(0x0841_0019);
    let mut admission = state_with(&mut rng, EPOCH, 2, 0..0);
    for generation_index in 0..4 {
        open(&mut admission, ORIGIN_MS, generation(1, generation_index));
    }
    assert_eq!(
        admission.link_opened(ORIGIN_MS, generation(1, 4)),
        Err(OnionLinkTableFull)
    );
    assert_eq!(admission.live_link_count(), 4);
}

/// Law (invariant): no ledger is releasable after any step. A closed ledger with load is released
/// by the first step in the quantum in which it drains, whatever that step is, and not only under
/// table pressure.
#[test]
fn test_drained_closed_ledgers_are_swept_on_the_next_quantum() {
    let mut rng = StdRng::seed_from_u64(0x0841_0011);
    let mut admission = state_with(&mut rng, EPOCH, 64, 1..3);
    let x = latest_expiry(ORIGIN_MS);
    assert_eq!(
        send(&mut admission, ORIGIN_MS, 1, 1, layer(x, 1)),
        Verdict::Admitted
    );
    admission.link_closed(ORIGIN_MS, link(1));
    let still_loaded = ORIGIN_MS + ONION_ADMISSION_WINDOW_MS - 1;
    assert_eq!(
        send(
            &mut admission,
            still_loaded,
            2,
            1,
            layer(latest_expiry(still_loaded), 2)
        ),
        Verdict::Admitted
    );
    assert!(admission.peer_slots.contains_key(&Did::from(1_u32)));
    let drained = ORIGIN_MS + ONION_ADMISSION_WINDOW_MS;
    assert_eq!(
        send(
            &mut admission,
            drained,
            2,
            1,
            layer(latest_expiry(drained), 3)
        ),
        Verdict::Admitted
    );
    assert!(!admission.peer_slots.contains_key(&Did::from(1_u32)));
    assert!(admission
        .slots
        .values()
        .all(|slot| !slot.is_releasable_at(drained / Q)));
}

/// Property, seeded: under random link churn (48 DIDs, `R = 16`, two of them heavy), no DID is
/// ever charged more than `B` units in any window of five consecutive quanta, the table never
/// exceeds `2·R`, the live-link count equals the model's, and no ledger is ever releasable between
/// steps. Closes and charges pick a random live generation, or with probability ¼ a random
/// generation that may be stale, refused or unknown. The run hits the sender budget, links that
/// are not live, and the full table, so none of the bounds holds vacuously.
#[test]
fn test_rotation_through_many_dids_never_exceeds_the_sender_budget() {
    const R: usize = 16;
    let mut rng = StdRng::seed_from_u64(0x0841_000d);
    let mut admission = state_with(&mut rng, EPOCH, R, 0..0);
    let mut live_generations = BTreeMap::<u32, Vec<u64>>::new();
    let mut next_generation = 0_u64;
    let mut charged = BTreeMap::<(u32, u128), u32>::new();
    let mut outcomes = [0_u32; 3];
    let mut now_ms = ORIGIN_MS;
    for tag in 0..30_000_u128 {
        now_ms += rng.gen_range(0..=Q / 64);
        let sender = if rng.gen_bool(0.5) {
            rng.gen_range(0..2_u32)
        } else {
            rng.gen_range(2..48_u32)
        };
        match rng.gen_range(0..16) {
            0 => {
                let generations = live_generations.entry(sender).or_default();
                let closed = if generations.is_empty() || rng.gen_ratio(1, 4) {
                    rng.gen_range(0..=next_generation)
                } else {
                    generations.swap_remove(rng.gen_range(0..generations.len()))
                };
                generations.retain(|live| *live != closed);
                admission.link_closed(now_ms, generation(sender, closed));
            }
            1 | 2 => {
                next_generation += 1;
                match admission.link_opened(now_ms, generation(sender, next_generation)) {
                    Ok(()) => live_generations
                        .entry(sender)
                        .or_default()
                        .push(next_generation),
                    Err(OnionLinkTableFull) => outcomes[2] += 1,
                }
            }
            _ => {
                let cost = rng.gen_range(1..=768_u32);
                let on = match live_generations.get(&sender) {
                    Some(generations) if !generations.is_empty() && !rng.gen_ratio(1, 4) => {
                        generations
                            .get(rng.gen_range(0..generations.len()))
                            .copied()
                            .unwrap_or(0)
                    }
                    _ => rng.gen_range(0..=next_generation),
                };
                let modelled_live = live_generations
                    .get(&sender)
                    .is_some_and(|generations| generations.contains(&on));
                let verdict = send_on(
                    &mut admission,
                    now_ms,
                    generation(sender, on),
                    cost,
                    layer(latest_expiry(now_ms), tag),
                );
                assert_eq!(
                    verdict == Verdict::Unpaid(OnionChargeRejection::LinkNotLive),
                    !modelled_live
                );
                match verdict {
                    Verdict::Admitted => {
                        *charged.entry((sender, now_ms / Q)).or_default() += cost;
                    }
                    Verdict::Unpaid(OnionChargeRejection::SenderBudget) => outcomes[0] += 1,
                    Verdict::Unpaid(OnionChargeRejection::LinkNotLive) => outcomes[1] += 1,
                    unexpected => assert_eq!(unexpected, Verdict::Admitted),
                }
            }
        }
        assert!(admission.slots.len() <= 2 * R);
        assert_eq!(
            admission.live_link_count(),
            live_generations.values().map(Vec::len).sum::<usize>()
        );
        assert!(admission
            .slots
            .values()
            .all(|slot| !slot.is_releasable_at(now_ms / Q)));
    }
    assert!(outcomes.iter().all(|count| *count > 0), "{outcomes:?}");
    for (sender, quantum) in charged.keys() {
        let window = charged
            .range(
                (
                    *sender,
                    quantum.saturating_sub(ADMISSION_WINDOW_QUANTA_WIDE - 1),
                )..=(*sender, *quantum),
            )
            .map(|(_, units)| *units)
            .sum::<u32>();
        assert!(window <= ONION_ADMISSION_SENDER_UNITS);
    }
}

/// Whether the table has no room for `link`, given the modelled number of live links: the
/// live-link set is at its `2·R` capacity. This is the only justification for a refusal.
fn is_full_for(
    admission: &OnionAdmissionState,
    live_links: usize,
    _link: &OnionAdmissionLink,
) -> bool {
    live_links >= admission.capacity
}

/// The live links of `admission`, as `(did, generation)` pairs.
fn live_links(admission: &OnionAdmissionState) -> BTreeSet<(Did, u64)> {
    admission
        .live_links()
        .into_iter()
        .map(|link| (link.peer(), link.generation()))
        .collect()
}

/// The model of the lost-events property: core's truth `L`, the live set admission should hold,
/// and two states driven in lockstep, one reconciled with sorted snapshots and one with shuffled
/// snapshots.
struct Lockstep {
    /// The seeded source of every choice.
    rng: StdRng,
    /// The state reconciled with sorted snapshots.
    sorted: OnionAdmissionState,
    /// The state reconciled with shuffled snapshots.
    shuffled: OnionAdmissionState,
    /// Core's registry of live links, `L`.
    truth: BTreeSet<(Did, u64)>,
    /// The live set admission should hold, given the events it received.
    modelled: BTreeSet<(Did, u64)>,
    /// The last generation core issued.
    next_generation: u64,
    /// Reconciliations run.
    reconciliations: u32,
    /// Events lost before reaching admission.
    lost: u32,
    /// Delivered opens, delivered closes, event refusals, and reconciliations with a refusal.
    occurred: [u32; 4],
}

impl Lockstep {
    /// Two fresh states with `R = 8` under one probe key, and empty truth.
    fn new(seed: u64) -> Self {
        let mut rng = StdRng::seed_from_u64(seed);
        let key: [u8; 32] = rng.gen();
        let fresh = || OnionAdmissionState::new(EPOCH, OnionReplayFilterKey::new(key), registry(8));
        Self {
            rng,
            sorted: fresh(),
            shuffled: fresh(),
            truth: BTreeSet::new(),
            modelled: BTreeSet::new(),
            next_generation: 0,
            reconciliations: 0,
            lost: 0,
            occurred: [0; 4],
        }
    }

    /// Core admits a new generation of `did`. The event is lost with probability ⅙. Otherwise both
    /// states open it; a refusal must be justified, and the shell then closes the link in core.
    fn open(&mut self, now_ms: u128, did: Did) {
        self.next_generation += 1;
        let opened = OnionAdmissionLink::new(did, self.next_generation);
        self.truth.insert((did, opened.generation()));
        if self.rng.gen_ratio(1, 6) {
            self.lost += 1;
            return;
        }
        let verdict = self.sorted.link_opened(now_ms, opened);
        assert_eq!(self.shuffled.link_opened(now_ms, opened), verdict);
        match verdict {
            Ok(()) => {
                self.occurred[0] += 1;
                self.modelled.insert((did, opened.generation()));
            }
            Err(OnionLinkTableFull) => {
                self.occurred[2] += 1;
                assert!(is_full_for(&self.sorted, self.modelled.len(), &opened));
                self.truth.remove(&(did, opened.generation()));
            }
        }
    }

    /// Core retires a random live generation. The event is lost with probability ⅙; otherwise both
    /// states close it.
    fn retire(&mut self, now_ms: u128) {
        let index = self.rng.gen_range(0..self.truth.len().max(1));
        let Some((did, generation)) = self.truth.iter().nth(index).copied() else {
            return;
        };
        self.truth.remove(&(did, generation));
        if self.rng.gen_ratio(1, 6) {
            self.lost += 1;
            return;
        }
        let closed = OnionAdmissionLink::new(did, generation);
        self.sorted.link_closed(now_ms, closed);
        self.shuffled.link_closed(now_ms, closed);
        self.occurred[1] += 1;
        self.modelled.remove(&(did, generation));
    }

    /// Reconcile both states against `L`, sorted and shuffled, and check the four reconciliation
    /// laws and the justification of every refusal. The shell then closes the refused links in
    /// core.
    fn reconcile(&mut self, now_ms: u128) {
        self.reconciliations += 1;
        let snapshot = self
            .truth
            .iter()
            .map(|&(did, generation)| OnionAdmissionLink::new(did, generation))
            .collect::<Vec<_>>();
        let mut permuted = snapshot.clone();
        permuted.shuffle(&mut self.rng);
        let before = live_links(&self.sorted);
        let refused = self.sorted.reconcile(now_ms, snapshot.iter().copied());
        assert_eq!(
            self.shuffled.reconcile(now_ms, permuted.iter().copied()),
            refused
        );
        let refused_set = refused
            .links()
            .iter()
            .map(|link| (link.peer(), link.generation()))
            .collect::<BTreeSet<_>>();
        let expected = self
            .truth
            .difference(&refused_set)
            .copied()
            .collect::<BTreeSet<_>>();
        assert_eq!(live_links(&self.sorted), expected);
        assert!(before
            .intersection(&self.truth)
            .all(|link| !refused_set.contains(link)));
        assert!(refused
            .links()
            .iter()
            .all(|link| is_full_for(&self.sorted, expected.len(), link)));
        self.occurred[3] += u32::from(!refused.links().is_empty());
        let ledgers = self.sorted.slots.clone();
        assert_eq!(
            self.sorted.reconcile(now_ms, snapshot.iter().copied()),
            refused
        );
        assert_eq!(
            self.shuffled.reconcile(now_ms, permuted.iter().copied()),
            refused
        );
        assert_eq!(self.sorted.slots, ledgers);
        self.truth = expected;
        self.modelled = self.truth.clone();
    }

    /// Charge a cell on a random modelled link, or with probability ¼ on a possibly stale
    /// generation of `did`. Both states agree, and `LinkNotLive` holds exactly when the model lacks
    /// the link.
    fn charge(&mut self, now_ms: u128, did: Did, tag: u128) {
        let index = self.rng.gen_range(0..self.modelled.len().max(1));
        let on = match self.modelled.iter().nth(index) {
            Some(&(did, generation)) if !self.rng.gen_ratio(1, 4) => {
                OnionAdmissionLink::new(did, generation)
            }
            _ => OnionAdmissionLink::new(did, self.rng.gen_range(0..=self.next_generation)),
        };
        let cost = self.rng.gen_range(1..=64_u32);
        let x = layer(latest_expiry(now_ms), tag);
        let verdict = send_on(&mut self.sorted, now_ms, on, cost, x);
        assert_eq!(send_on(&mut self.shuffled, now_ms, on, cost, x), verdict);
        assert_eq!(
            verdict == Verdict::Unpaid(OnionChargeRejection::LinkNotLive),
            !self.modelled.contains(&(on.peer(), on.generation()))
        );
    }
}

/// Property, seeded (M2 of the round-6 review): with lost `Admitted`/`Retired` events, periodic
/// reconciliation against core's truth `L` restores the laws. Two states are driven in lockstep
/// with the same inputs; one receives every snapshot sorted and the other shuffled. After every
/// reconciliation:
/// * `𝓛ᵢ = L \ refused`;
/// * no link that was live before and is in `L` is refused;
/// * a second reconciliation with the same snapshot changes nothing and refuses the same links;
/// * the shuffled snapshot yields the same state as the sorted one.
///
/// Every refusal is justified: after a refused `link_opened`, or after a reconciliation that
/// refuses a link, the table has no room for that link, counting live links from the model.
/// Throughout, a charge is `LinkNotLive` exactly when the modelled live set lacks the link, and
/// the state's live set equals the model's after every step. The shell closes every refused link
/// in core, so the model removes it from `L`. The run asserts that delivered opens, delivered
/// closes, event refusals and reconcile refusals all occur.
#[test]
fn test_reconcile_restores_core_truth_under_lost_events() {
    let mut model = Lockstep::new(0x0841_001b);
    let mut now_ms = ORIGIN_MS;
    for tag in 0..6_000_u128 {
        now_ms += model.rng.gen_range(0..=Q / 16);
        let did = Did::from(model.rng.gen_range(0..24_u32));
        match model.rng.gen_range(0..16) {
            0 | 1 => model.open(now_ms, did),
            2 => model.retire(now_ms),
            3 => model.reconcile(now_ms),
            _ => model.charge(now_ms, did, tag),
        }
        assert_eq!(live_links(&model.sorted), model.modelled);
        assert_eq!(model.sorted.slots, model.shuffled.slots);
    }
    assert!(
        model.reconciliations > 100 && model.lost > 50,
        "{} {}",
        model.reconciliations,
        model.lost
    );
    assert!(
        model.occurred.iter().all(|count| *count > 0),
        "{:?}",
        model.occurred
    );
}

/// Regression (#1224): a reconnecting peer whose previously retained slot is now occupied by a
/// live honest peer must not resume that live slot or co-locate onto the honest peer's ledger.
#[test]
fn test_reconnecting_peer_does_not_colocate_onto_occupied_live_slot() {
    const R: usize = 2;
    let mut rng = StdRng::seed_from_u64(0x1224_0001);
    let mut admission = state_with(&mut rng, EPOCH, R, 0..0);
    let x = latest_expiry(ORIGIN_MS);

    // Charge all `2·R = 4` slots and close their links: attacker `1` leaves 1 unit on slot 0, and
    // peers `2..=4` leave 2 units on slots `1..4`.
    open(&mut admission, ORIGIN_MS, generation(1, 0));
    assert_eq!(
        admission.slot_of(Did::from(1_u32)),
        Some(OnionSlotId::new(0))
    );
    assert_eq!(
        send_on(&mut admission, ORIGIN_MS, generation(1, 0), 1, layer(x, 1)),
        Verdict::Admitted
    );
    admission.link_closed(ORIGIN_MS, generation(1, 0));

    for filler in 2..=4_u32 {
        open(&mut admission, ORIGIN_MS, generation(filler, 0));
        assert_eq!(
            send_on(
                &mut admission,
                ORIGIN_MS,
                generation(filler, 0),
                2,
                layer(x, u128::from(filler))
            ),
            Verdict::Admitted
        );
        admission.link_closed(ORIGIN_MS, generation(filler, 0));
    }

    // Honest peer `10` connects and receives the cleanest free slot (slot 0, with 1 unit).
    open(&mut admission, ORIGIN_MS + 1, generation(10, 0));
    assert_eq!(
        admission.slot_of(Did::from(10_u32)),
        Some(OnionSlotId::new(0))
    );

    // Attacker `1` reconnects while honest peer `10` is live on slot 0: `1` must get a free slot
    // (`slot 1`), never co-locating onto `10`'s live slot or exhausting `10`'s sender budget.
    open(&mut admission, ORIGIN_MS + 2, generation(1, 1));
    let attacker_slot = admission
        .slot_of(Did::from(1_u32))
        .expect("reconnected attacker holds a slot");
    assert_ne!(attacker_slot, OnionSlotId::new(0));
    assert_eq!(attacker_slot, OnionSlotId::new(1));

    let attacker_remaining = ONION_ADMISSION_SENDER_UNITS - 3;
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS + 2,
            generation(1, 1),
            attacker_remaining,
            layer(x, 100)
        ),
        Verdict::Admitted
    );
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS + 2,
            generation(1, 1),
            1,
            layer(x, 101)
        ),
        Verdict::Unpaid(OnionChargeRejection::SenderBudget)
    );

    // Honest peer `10` on slot 0 retains its own slot budget unimpaired by attacker `1`.
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS + 2,
            generation(10, 0),
            ONION_ADMISSION_SLOT_FLOOR_UNITS - 1,
            layer(x, 200)
        ),
        Verdict::Admitted
    );
}

/// Regression (#1224): attaching an `R`-slot [`SlotRoster`] aligns `OnionAdmissionState` slot
/// capacity to `R`, so cleanest-first `SlotRoster` assignments in `0..R` are honored even when
/// every slot in `0..R` carries residual load, while overlapping generations of one live peer
/// remain permitted up to `2·R`.
#[test]
fn test_with_slot_roster_aligns_slot_capacity_and_honors_charged_roster_assignments() {
    const R: usize = 4;
    let mut rng = StdRng::seed_from_u64(0x1224_0002);
    let roster = Arc::new(SlotRoster::new(R));
    let mut admission =
        OnionAdmissionState::new(EPOCH, OnionReplayFilterKey::new(rng.gen()), registry(R))
            .with_slot_roster(Arc::clone(&roster));
    assert_eq!(admission.slot_capacity, R);

    let x = latest_expiry(ORIGIN_MS);
    for (idx, load) in [10_u32, 3_u32, 20_u32, 30_u32].into_iter().enumerate() {
        let did = 100 + u32::try_from(idx).unwrap();
        roster.arrive(Did::from(did), &SlotFloorUse::default());
        open(&mut admission, ORIGIN_MS, generation(did, 0));
        assert_eq!(
            admission.slot_of(Did::from(did)),
            Some(OnionSlotId::new(idx))
        );
        assert_eq!(
            send_on(
                &mut admission,
                ORIGIN_MS,
                generation(did, 0),
                load,
                layer(x, u128::from(did))
            ),
            Verdict::Admitted
        );
        admission.link_closed(ORIGIN_MS, generation(did, 0));
        roster.depart(Did::from(did));
    }

    // Every slot `0..R` now has residual load > 0; slot 1 is cleanest (load 3). `SlotRoster`
    // assigns newcomer `500` to slot 1, and `admission` must honor slot 1 rather than inventing
    // phantom slots in `R..2R`.
    roster.arrive(Did::from(500_u32), &SlotFloorUse::default());
    open(&mut admission, ORIGIN_MS + 1, generation(500, 0));
    assert_eq!(
        admission.slot_of(Did::from(500_u32)),
        Some(OnionSlotId::new(1))
    );

    // Fill the remaining 3 slots (`0`, `2`, `3`) with live peers `501..=503`.
    for newcomer in 501..=503_u32 {
        roster.arrive(Did::from(newcomer), &SlotFloorUse::default());
        open(&mut admission, ORIGIN_MS + 1, generation(newcomer, 0));
        assert!(admission.slot_of(Did::from(newcomer)).unwrap().index() < R);
    }

    // An overlapping generation of an already-live peer on slot 1 is accepted (`live_link_count`
    // headroom is `2·R`), whereas a 5th distinct peer has no free slot in `0..R` and is refused.
    open(&mut admission, ORIGIN_MS + 1, generation(500, 1));
    assert_eq!(
        admission.link_opened(ORIGIN_MS + 1, generation(999, 0)),
        Err(OnionLinkTableFull)
    );
}

/// Regression (#1224 / #1229 item 3): a peer that exhausts its slot budget on generation 0,
/// reconnects on generation 1 sending zero cells, and disconnects again must keep its unexpired
/// charge bound across the zero-charge reconnect so generation 2 still resumes the charged slot.
#[test]
fn test_reconnect_with_zero_new_charges_retains_prior_charge_until_window_expires() {
    const R: usize = 4;
    let mut rng = StdRng::seed_from_u64(0x1224_0003);
    let mut admission = state_with(&mut rng, EPOCH, R, 0..0);
    let x = latest_expiry(ORIGIN_MS);

    open(&mut admission, ORIGIN_MS, generation(1, 0));
    let charged_slot = admission
        .slot_of(Did::from(1_u32))
        .expect("peer 1 holds a slot");
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS,
            generation(1, 0),
            ONION_ADMISSION_SENDER_UNITS,
            layer(x, 1)
        ),
        Verdict::Admitted
    );
    admission.link_closed(ORIGIN_MS, generation(1, 0));

    // Reconnect as generation 1, send zero cells, and close generation 1 within the same window.
    open(&mut admission, ORIGIN_MS + 1, generation(1, 1));
    assert_eq!(admission.slot_of(Did::from(1_u32)), Some(charged_slot));
    admission.link_closed(ORIGIN_MS + 2, generation(1, 1));
    assert_eq!(admission.slot_of(Did::from(1_u32)), Some(charged_slot));

    // Reconnect again as generation 2 while cleaner slots are completely free: peer 1 must still
    // resume `charged_slot` and remain capped by `ONION_ADMISSION_SENDER_UNITS`.
    open(&mut admission, ORIGIN_MS + 3, generation(1, 2));
    assert_eq!(admission.slot_of(Did::from(1_u32)), Some(charged_slot));
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS + 3,
            generation(1, 2),
            1,
            layer(x, 2)
        ),
        Verdict::Unpaid(OnionChargeRejection::SenderBudget)
    );
}

/// Regression (#1224): cleanest-first free-slot selection prefers unretained and lower-total-load
/// slots over exhausted grace-period slots whose `FloorUse` saturates at `f`, and a peer forced
/// onto a new slot during its grace period retains its spent window charge.
#[test]
fn test_grace_period_slot_ranking_and_relocated_peer_charge_preservation() {
    const R: usize = 1;
    let mut rng = StdRng::seed_from_u64(0x1224_0004);
    let mut admission = state_with(&mut rng, EPOCH, R, 0..0);
    let x = latest_expiry(ORIGIN_MS);

    // Peer 1 on slot 0 spends its entire sender budget `B` and disconnects into its grace period.
    open(&mut admission, ORIGIN_MS, generation(1, 0));
    assert_eq!(
        admission.slot_of(Did::from(1_u32)),
        Some(OnionSlotId::new(0))
    );
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS,
            generation(1, 0),
            ONION_ADMISSION_SENDER_UNITS,
            layer(x, 1)
        ),
        Verdict::Admitted
    );
    admission.link_closed(ORIGIN_MS, generation(1, 0));

    // Peer 2 on slot 1 spends exactly the floor `f` (`FloorUse = 1.0`, matching slot 0's saturated
    // `FloorUse`), then we clear `retained` on slot 1 to model an unretained residual slot at `f`.
    open(&mut admission, ORIGIN_MS, generation(2, 0));
    assert_eq!(
        admission.slot_of(Did::from(2_u32)),
        Some(OnionSlotId::new(1))
    );
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS,
            generation(2, 0),
            ONION_ADMISSION_SLOT_FLOOR_UNITS,
            layer(x, 2)
        ),
        Verdict::Admitted
    );
    admission.link_closed(ORIGIN_MS, generation(2, 0));
    if let Some(slot1) = admission.slots.get_mut(&OnionSlotId::new(1)) {
        slot1.retained.clear();
    }
    admission.peer_slots.remove(&Did::from(2_u32));

    // Both slots 0 and 1 are free and have `FloorUse == 1.0`, but slot 0 is a retained
    // grace-period slot at `load = B` whereas slot 1 is unretained at `load = f`. An arriving
    // honest peer `10` must be assigned to slot 1, not slot 0.
    open(&mut admission, ORIGIN_MS + 1, generation(10, 0));
    assert_eq!(
        admission.slot_of(Did::from(10_u32)),
        Some(OnionSlotId::new(1))
    );

    // Now honest peer `11` takes the only remaining free slot (slot 0), occupying peer `1`'s
    // grace-period slot. When peer `1` reconnects after `10` closes slot 1, peer `1` is relocated
    // onto slot 1 and must retain its spent window charge `B`.
    open(&mut admission, ORIGIN_MS + 2, generation(11, 0));
    assert_eq!(
        admission.slot_of(Did::from(11_u32)),
        Some(OnionSlotId::new(0))
    );
    admission.link_closed(ORIGIN_MS + 2, generation(10, 0));

    open(&mut admission, ORIGIN_MS + 3, generation(1, 1));
    assert_eq!(
        admission.slot_of(Did::from(1_u32)),
        Some(OnionSlotId::new(1))
    );
    assert_eq!(
        send_on(
            &mut admission,
            ORIGIN_MS + 3,
            generation(1, 1),
            1,
            layer(x, 3)
        ),
        Verdict::Unpaid(OnionChargeRejection::SenderBudget)
    );
}