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
//! Law tests of the session algebra (#834 D2′, D8; #843 Q2, Q5, Q7), one section per module.
//!
//! Reply blocks are built by the client's builder over a fixture return path, so the pool and the
//! machines handle real `OnionSurb`s; nothing here touches a network or a clock.

mod test_deterministic_driver;
mod test_liveness;
mod test_mark;
#[cfg(rings_native)]
mod test_session_order_model;
mod test_witness;

use bytes::Bytes;
use rand::rngs::StdRng;
use rand::SeedableRng;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::ecc::SecretKey;

use super::client::OnionClientCredit;
use super::client::OnionClientEvent;
use super::client::OnionClientSession;
use super::client::OnionControlStep;
use super::client::OnionCreditWindow;
use super::exit::OnionExitEffect;
use super::exit::OnionExitSession;
use super::exit::OnionWorldRead;
use super::frame::OnionFrame;
use super::frame::OnionFrameError;
use super::frame::OnionSequence;
use super::order::OnionReorder;
use super::order::OnionSequenceGap;
use super::pool::OnionSurbPool;
use super::pool::ONION_SURB_POOL_CAPACITY;
use super::OnionSessionArguments;
use super::OnionSessionId;
use super::OnionTargetDigest;
use crate::onion::circuit::OnionExpiry;
use crate::onion::circuit::ONION_ADMISSION_WINDOW_MS;
use crate::onion::sphinx::builder::build_surb;
use crate::onion::sphinx::cell::OnionSurb;
use crate::onion::sphinx::class::OnionLoopClass;
use crate::onion::OnionProcessEpoch;
use crate::onion::OnionRouteHop;

/// The arrival instant of the fixtures, `2Q`.
const NOW_MS: u128 = 60_000;

/// The quantum `Q`.
const QUANTUM_MS: u128 = 30_000;

/// The target of the fixture sessions.
const TARGET: &[u8] = b"example.com:443";

/// The class of every fixture loop.
const CLASS: OnionLoopClass = OnionLoopClass::DEFAULT;

/// The fixture return path: two relays with fixed keys.
fn return_path() -> [OnionRouteHop; 2] {
    [1_u8, 2].map(|byte| {
        let secret =
            SecretKey::try_from(format!("{byte:02x}").repeat(32).as_str()).expect("fixture scalar");
        let key = DelegateeKey::new_with_seckey(&secret).expect("fixture delegation");
        OnionRouteHop::new(
            key.delegator_did(),
            key.delegatee_public_key(),
            OnionProcessEpoch::new([1; 16]),
        )
    })
}

/// `count` reply blocks expiring at `(3 + offset)·Q`, from a seeded RNG.
fn surbs(seed: u64, count: usize, offset: u128) -> Vec<OnionSurb> {
    surbs_of(CLASS, seed, count, offset)
}

/// One reply block expiring at `3Q`.
fn surb(seed: u64) -> OnionSurb {
    surbs(seed, 1, 0).pop().expect("one block")
}

/// The fixture session arguments.
fn arguments() -> OnionSessionArguments {
    OnionSessionArguments {
        session: OnionSessionId([5; 16]),
        digest: OnionTargetDigest::of(TARGET),
    }
}

/// The encoding round trip of `frame`: `decode ∘ encode` and, for the result, `encode` again.
fn round_trip(frame: &OnionFrame) -> Vec<u8> {
    let bytes = frame.encode(CLASS).expect("the frame fits").to_vec();
    let decoded = OnionFrame::decode(CLASS, &bytes).expect("decodes");
    assert_eq!(
        decoded.encode(CLASS).expect("re-encodes").as_slice(),
        bytes.as_slice(),
        "canonical"
    );
    bytes
}

/// `credit(m, υ…)` with the forward high-water mark `m`.
fn credit(mark: u32, blocks: Vec<OnionSurb>) -> OnionFrame {
    OnionFrame::Credit {
        mark: OnionSequence::new(mark),
        surbs: blocks,
    }
}

// ---- frame -------------------------------------------------------------------------------------

/// Every frame round-trips canonically, the widest `data` is exactly `C₀ − 7` bytes of stream
/// (`C₀ − 9 − |t|` under `T`), and a `credit` frame holds exactly `k = 4` blocks at 16 KiB.
#[test]
fn test_frames_round_trip_at_their_width_bounds() {
    let capacity = OnionFrame::data_capacity(CLASS);
    assert_eq!(capacity, CLASS.value_capacity() - 6);
    let widest = Bytes::from(vec![0xa5; capacity]);
    round_trip(&OnionFrame::Data {
        sequence: OnionSequence::new(7),
        target: None,
        payload: widest.clone(),
    });
    round_trip(&OnionFrame::Data {
        sequence: OnionSequence::FIRST,
        target: Some(Bytes::from_static(TARGET)),
        payload: Bytes::from(vec![1; capacity - 2 - TARGET.len()]),
    });
    round_trip(&OnionFrame::Fin {
        sequence: OnionSequence::new(u32::MAX),
        target: None,
    });
    round_trip(&OnionFrame::Abort {
        sequence: OnionSequence::new(u32::MAX),
    });
    round_trip(&OnionFrame::Fin {
        sequence: OnionSequence::FIRST,
        target: Some(Bytes::from_static(TARGET)),
    });
    let widest_credit = credit(u32::MAX, surbs(10, OnionFrame::credit_capacity(CLASS), 0));
    assert_eq!(OnionFrame::credit_capacity(CLASS), 4);
    round_trip(&widest_credit);

    let overwide = OnionFrame::Data {
        sequence: OnionSequence::FIRST,
        target: None,
        payload: Bytes::from(vec![0; capacity + 1]),
    };
    assert!(overwide.encode(CLASS).is_err());
    assert!(credit(0, surbs(11, 5, 0)).encode(CLASS).is_err());
    assert!(credit(0, Vec::new()).encode(CLASS).is_err());
}

/// Closure: unknown tags, reserved flags, truncated fields, trailing bytes after `fin` or
/// `abort`, and `credit` frames of a truncated `m`, or of no or partial blocks, are rejected.
#[test]
fn test_malformed_frames_are_rejected() {
    let fin = OnionFrame::Fin {
        sequence: OnionSequence::FIRST,
        target: None,
    }
    .encode(CLASS)
    .expect("fits");
    let abort = OnionFrame::Abort {
        sequence: OnionSequence::FIRST,
    }
    .encode(CLASS)
    .expect("fits");
    let mut partial = credit(7, surbs(12, 1, 0))
        .encode(CLASS)
        .expect("fits")
        .to_vec();
    partial.pop();
    for (bytes, error) in [
        (Vec::new(), OnionFrameError::Tag),
        (vec![0x04], OnionFrameError::Tag),
        (vec![0x03, 0, 0], OnionFrameError::Malformed),
        (vec![0x00, 0, 0, 0, 0, 0x02], OnionFrameError::Flags(0x02)),
        (vec![0x00, 0, 0, 0], OnionFrameError::Malformed),
        (
            vec![0x00, 0, 0, 0, 0, 0x01, 0, 9, b'x'],
            OnionFrameError::Malformed,
        ),
        ([fin.as_slice(), &[0]].concat(), OnionFrameError::Malformed),
        (
            [abort.as_slice(), &[0]].concat(),
            OnionFrameError::Malformed,
        ),
        (vec![0x02], OnionFrameError::Malformed),
        (vec![0x02, 0, 0, 7], OnionFrameError::Malformed),
        (vec![0x02, 0, 0, 0, 7], OnionFrameError::Malformed),
        (partial, OnionFrameError::Malformed),
    ] {
        assert_eq!(
            OnionFrame::decode(CLASS, &bytes).err(),
            Some(error),
            "{bytes:02x?}"
        );
    }
}

/// `ā = ς ‖ d ‖ 0^16` round-trips, and a non-zero padding byte is not a session application.
#[test]
fn test_session_arguments_round_trip_canonically() {
    let encoded = arguments().encode();
    assert_eq!(OnionSessionArguments::decode(&encoded), Some(arguments()));
    let mut bytes = *encoded.as_bytes();
    bytes[63] = 1;
    assert_eq!(
        OnionSessionArguments::decode(&crate::onion::sphinx::layer::OnionArguments::new(bytes)),
        None
    );
}

// ---- pool --------------------------------------------------------------------------------------

/// The pool holds at most `Q_max` blocks, spends the least expiry first, never returns a block
/// twice, and drops a block exactly when its `x` passes.
#[test]
fn test_surb_pool_is_bounded_ordered_and_single_use() {
    let mut pool = OnionSurbPool::default();
    let late = surbs(20, 1, 2).pop().expect("a block");
    assert!(pool.add(NOW_MS, late));
    for block in surbs(21, ONION_SURB_POOL_CAPACITY - 1, 0) {
        assert!(pool.add(NOW_MS, block));
    }
    assert_eq!(pool.len(NOW_MS), ONION_SURB_POOL_CAPACITY);
    assert!(
        !pool.add(NOW_MS, surb(22)),
        "credit beyond Q_max is dropped"
    );

    let first = pool.take(NOW_MS).expect("a block");
    assert_eq!(first.expiry().as_ms(), 3 * QUANTUM_MS, "least x first");
    assert_eq!(
        pool.len(NOW_MS),
        ONION_SURB_POOL_CAPACITY - 1,
        "taken blocks leave"
    );

    // At 3Q every block of x = 3Q has expired; only the later one remains.
    assert_eq!(pool.len(3 * QUANTUM_MS), 1);
    let last = pool.take(3 * QUANTUM_MS).expect("the later block");
    assert_eq!(last.expiry().as_ms(), 5 * QUANTUM_MS);
    assert!(pool.take(3 * QUANTUM_MS).is_none());
    assert!(
        !pool.add(3 * QUANTUM_MS, surb(23)),
        "an expired block is refused"
    );
}

// ---- order -------------------------------------------------------------------------------------

/// Any permutation inside the window releases `0 … m` in order, each once; a duplicate releases
/// nothing.
#[test]
fn test_reorder_releases_every_permutation_in_order() {
    let mut rng = StdRng::seed_from_u64(30);
    for _ in 0..50 {
        let mut order = (0..32_u32).collect::<Vec<_>>();
        rand::seq::SliceRandom::shuffle(order.as_mut_slice(), &mut rng);
        let mut reorder = OnionReorder::default();
        let released = order
            .iter()
            .flat_map(|n| {
                reorder
                    .accept(NOW_MS, OnionSequence::new(*n), *n)
                    .expect("inside the window")
            })
            .collect::<Vec<_>>();
        assert_eq!(released, (0..32).collect::<Vec<_>>());
        assert!(reorder
            .accept(NOW_MS, OnionSequence::new(3), 3)
            .expect("a duplicate is not a gap")
            .is_empty());
    }
}

/// A frame beyond the window, or a missing frame awaited for `V` after a later one, fails the
/// direction closed, after which it releases nothing.
#[test]
fn test_reorder_fails_closed_on_a_persisting_gap() {
    let mut beyond = OnionReorder::default();
    let window = u32::try_from(ONION_SURB_POOL_CAPACITY).expect("small");
    assert_eq!(
        beyond.accept(NOW_MS, OnionSequence::new(window), ()).err(),
        Some(OnionSequenceGap { missing: 0 })
    );
    assert!(beyond.accept(NOW_MS, OnionSequence::FIRST, ()).is_err());

    let mut stalled = OnionReorder::default();
    assert!(stalled
        .accept(NOW_MS, OnionSequence::new(1), ())
        .expect("inside the window")
        .is_empty());
    assert!(stalled
        .expire(NOW_MS + ONION_ADMISSION_WINDOW_MS - 1)
        .is_ok());
    assert_eq!(
        stalled.expire(NOW_MS + ONION_ADMISSION_WINDOW_MS).err(),
        Some(OnionSequenceGap { missing: 0 })
    );
}

// ---- exit --------------------------------------------------------------------------------------

/// The kinds of `effects`, for comparison: the payloads of writes, and each reply's frame with
/// its sequence (and, for `data`, its length), so a test sees `abort` apart from `fin`.
fn kinds(effects: &[OnionExitEffect]) -> Vec<String> {
    effects
        .iter()
        .map(|effect| match effect {
            OnionExitEffect::Open { target } => format!("open {}", String::from_utf8_lossy(target)),
            OnionExitEffect::Write(bytes) => format!("write {}", String::from_utf8_lossy(bytes)),
            OnionExitEffect::ShutdownWrite => "shutdown".to_string(),
            OnionExitEffect::Reply { frame, .. } => match frame {
                OnionFrame::Data {
                    sequence, payload, ..
                } => format!("data {} {}", sequence.value(), payload.len()),
                OnionFrame::Fin { sequence, .. } => format!("fin {}", sequence.value()),
                OnionFrame::Abort { sequence } => format!("abort {}", sequence.value()),
                OnionFrame::Credit { .. } => "credit".to_string(),
            },
            OnionExitEffect::Close => "close".to_string(),
        })
        .collect()
}

/// A data frame of the client session at `sequence`, with the target inline.
fn opening(sequence: u32, payload: &'static [u8]) -> OnionFrame {
    OnionFrame::Data {
        sequence: OnionSequence::new(sequence),
        target: Some(Bytes::from_static(TARGET)),
        payload: Bytes::from_static(payload),
    }
}

/// The happy path: a `T` loop opens the world, the ack is the first reply, world bytes spend one
/// block each, and `fin` both ways closes the session.
#[test]
fn test_exit_session_opens_acks_replies_and_closes() {
    let mut blocks = surbs(40, 6, 0).into_iter();
    let mut session = OnionExitSession::new(arguments().digest, NOW_MS);
    let mut next = || blocks.next().expect("a fixture block");

    assert_eq!(
        kinds(&session.forward(NOW_MS, opening(0, b"hello"), next())),
        ["open example.com:443", "write hello"]
    );
    let refill = credit(1, vec![next()]);
    assert!(kinds(&session.forward(NOW_MS, refill, next())).is_empty());
    assert_eq!(
        session.reply_capacity(NOW_MS),
        None,
        "no read before the ack"
    );
    assert_eq!(
        kinds(&session.opened(NOW_MS, true)),
        ["data 0 0"],
        "the ack spends a block"
    );
    for (chunk, reply) in [(b"one", "data 1 3"), (b"two", "data 2 3")] {
        assert_eq!(
            session.reply_capacity(NOW_MS),
            Some(OnionFrame::data_capacity(CLASS))
        );
        assert_eq!(
            kinds(&session.world(NOW_MS, OnionWorldRead::Bytes(Bytes::from_static(chunk)))),
            [reply]
        );
    }
    assert_eq!(session.reply_capacity(NOW_MS), None, "Q = ∅ stops reading");

    let fin = OnionFrame::Fin {
        sequence: OnionSequence::new(1),
        target: None,
    };
    assert_eq!(kinds(&session.forward(NOW_MS, fin, next())), ["shutdown"]);
    assert_eq!(
        kinds(&session.world(NOW_MS, OnionWorldRead::Eof)),
        ["fin 3", "close"],
        "fin only after the world's end"
    );
    assert!(session.is_closed());
}

/// Symmetry of close order and post-fin write rejection: when the world's `Eof` is replied before
/// the client's `Fin`, applying the client's `Fin` emits `Close` immediately without waiting for
/// a tick, and any `Data` after `Fin` is ignored.
#[test]
fn test_exit_session_closes_immediately_on_client_fin_after_world_eof_and_ignores_data_after_fin() {
    let mut blocks = surbs(400, 6, 0).into_iter();
    let mut session = acked(&mut blocks);
    let mut next = || blocks.next().expect("a fixture block");

    assert_eq!(
        kinds(&session.world(NOW_MS, OnionWorldRead::Eof)),
        ["fin 1"],
        "world eof replied first while client write direction is still open"
    );
    assert!(!session.is_closed());

    let fin = OnionFrame::Fin {
        sequence: OnionSequence::new(1),
        target: None,
    };
    assert_eq!(
        kinds(&session.forward(NOW_MS, fin, next())),
        ["shutdown", "close"],
        "client fin after world eof closes immediately"
    );
    assert!(session.is_closed());

    // Also verify that if a session opens with `Fin` and a subsequent `Data` arrives before world
    // `Eof`, the post-`Fin` data frame produces no `Write` effect.
    let mut half_closed = OnionExitSession::new(arguments().digest, NOW_MS);
    let open_fin = OnionFrame::Fin {
        sequence: OnionSequence::FIRST,
        target: Some(Bytes::from_static(TARGET)),
    };
    assert_eq!(kinds(&half_closed.forward(NOW_MS, open_fin, next())), [
        "open example.com:443",
        "shutdown"
    ]);
    assert_eq!(kinds(&half_closed.opened(NOW_MS, true)), ["data 0 0"]);
    let late_data = OnionFrame::Data {
        sequence: OnionSequence::new(1),
        target: None,
        payload: Bytes::from_static(b"after-fin"),
    };
    assert!(
        kinds(&half_closed.forward(NOW_MS, late_data, next())).is_empty(),
        "data after client fin is ignored"
    );
}

/// An opened and acked session over `blocks`: the `T` loop and a credit loop of one block leave
/// three blocks, and the ack spends one.
fn acked(blocks: &mut impl Iterator<Item = OnionSurb>) -> OnionExitSession {
    let mut session = OnionExitSession::new(arguments().digest, NOW_MS);
    let mut next = || blocks.next().expect("a fixture block");
    session.forward(NOW_MS, opening(0, b""), next());
    session.forward(NOW_MS, credit(1, vec![next()]), next());
    assert_eq!(kinds(&session.opened(NOW_MS, true)), ["data 0 0"]);
    session
}

/// Totality: world bytes that arrive after every block has expired are held, not
/// dropped, the world is not read meanwhile, and the held bytes are replied, in order, as soon
/// as credit returns.
#[test]
fn test_exit_session_holds_world_bytes_until_credit_returns() {
    let mut blocks = surbs(45, 3, 0).into_iter();
    let mut session = acked(&mut blocks);
    let expired_ms = 3 * QUANTUM_MS;

    assert!(session.reply_capacity(NOW_MS).is_some());
    assert!(kinds(&session.world(
        expired_ms,
        OnionWorldRead::Bytes(Bytes::from_static(b"late"))
    ))
    .is_empty());
    assert!(!session.is_closed());
    assert_eq!(
        session.reply_capacity(expired_ms),
        None,
        "held bytes pause reads"
    );

    let mut fresh = surbs(46, 2, 2).into_iter();
    let refill = credit(1, vec![fresh.next().expect("a block")]);
    assert_eq!(
        kinds(&session.forward(expired_ms, refill, fresh.next().expect("a block"))),
        ["data 1 4"]
    );
    assert!(session.reply_capacity(expired_ms).is_some());
}

/// Fail closed: a gap spends a remaining block on `abort`, never `fin`,
/// before the session closes.
#[test]
fn test_exit_session_aborts_a_gap() {
    let mut blocks = surbs(47, 4, 0).into_iter();
    let mut session = acked(&mut blocks);
    let far = OnionFrame::Data {
        sequence: OnionSequence::new(10_000),
        target: None,
        payload: Bytes::from_static(b"x"),
    };

    assert_eq!(
        kinds(&session.forward(NOW_MS, far, blocks.next().expect("a block"))),
        ["abort 1", "close"]
    );
    assert!(session.is_closed());
}

/// Fail closed: a world failure replies `abort`, never `fin`, if a block is
/// left, and closes either way; the held bytes are dropped with it.
#[test]
fn test_exit_session_aborts_a_world_failure_while_credit_lasts() {
    let mut blocks = surbs(48, 3, 0).into_iter();
    let mut session = acked(&mut blocks);
    assert_eq!(kinds(&session.fail(NOW_MS)), ["abort 1", "close"]);

    let mut blocks = surbs(49, 3, 0).into_iter();
    let mut drained = acked(&mut blocks);
    for (chunk, reply) in [(b"y", "data 1 1"), (b"z", "data 2 1")] {
        assert_eq!(
            kinds(&drained.world(NOW_MS, OnionWorldRead::Bytes(Bytes::from_static(chunk)))),
            [reply]
        );
    }
    assert_eq!(kinds(&drained.fail(NOW_MS)), ["close"]);
}

/// A session whose first frame is a `fin` carrying `T` opens and shuts its upload;
/// a `fin` naming another target of a bound session aborts it (Law Binding).
#[test]
fn test_exit_session_opens_on_a_first_fin_with_its_target() {
    let mut session = OnionExitSession::new(arguments().digest, NOW_MS);
    let fin = OnionFrame::Fin {
        sequence: OnionSequence::FIRST,
        target: Some(Bytes::from_static(TARGET)),
    };
    assert_eq!(kinds(&session.forward(NOW_MS, fin, surb(62))), [
        "open example.com:443",
        "shutdown"
    ]);

    let mut blocks = surbs(63, 4, 0).into_iter();
    let mut bound = acked(&mut blocks);
    let rebinding = OnionFrame::Fin {
        sequence: OnionSequence::new(1),
        target: Some(Bytes::from_static(b"other.example:443")),
    };
    assert_eq!(
        kinds(&bound.forward(NOW_MS, rebinding, blocks.next().expect("a block"))),
        ["abort 1", "close"]
    );
}

/// The client's `fin` carries `T` until the first reply, as its `data` does.
#[test]
fn test_client_fin_carries_the_target_until_the_first_reply() {
    let mut session = OnionClientSession::new(Bytes::from_static(TARGET), NOW_MS);
    let Ok(OnionFrame::Fin { target, .. }) = session.fin() else {
        panic!("a fin frame");
    };
    assert_eq!(target.as_deref(), Some(TARGET));

    let mut replied = OnionClientSession::new(Bytes::from_static(TARGET), NOW_MS);
    let ack = OnionFrame::Data {
        sequence: OnionSequence::FIRST,
        target: None,
        payload: Bytes::new(),
    };
    assert_eq!(
        replied.reply(NOW_MS, ack),
        Ok(vec![OnionClientEvent::Opened])
    );
    let Ok(OnionFrame::Fin { target, .. }) = replied.fin() else {
        panic!("a fin frame");
    };
    assert_eq!(target, None);
}

/// A failure after the world's `fin` was replied closes without an `abort`, which could overtake
/// that `fin` and turn a complete download into a failure.
#[test]
fn test_exit_session_fails_after_its_fin_without_an_abort() {
    let mut blocks = surbs(61, 4, 0).into_iter();
    let mut session = acked(&mut blocks);
    assert_eq!(kinds(&session.world(NOW_MS, OnionWorldRead::Eof)), [
        "fin 1"
    ]);

    assert_eq!(kinds(&session.fail(NOW_MS)), ["close"]);
}

/// Binding: a later `T` frame naming another target aborts a bound session
/// with `abort`.
#[test]
fn test_exit_session_refuses_to_rebind_its_target() {
    let mut blocks = surbs(50, 4, 0).into_iter();
    let mut session = acked(&mut blocks);
    let other = OnionFrame::Data {
        sequence: OnionSequence::new(1),
        target: Some(Bytes::from_static(b"other.example:443")),
        payload: Bytes::from_static(b"x"),
    };

    assert_eq!(
        kinds(&session.forward(NOW_MS, other, blocks.next().expect("a block"))),
        ["abort 1", "close"]
    );
}

/// The pool refuses a block whose expiry is not admissible now: passed, or beyond
/// `now + V`, whose reply the first relay would refuse.
#[test]
fn test_surb_pool_refuses_inadmissible_expiries() {
    let mut pool = OnionSurbPool::default();
    let beyond = surbs(51, 1, 10).pop().expect("a block");
    let passed = surb(52);

    assert!(!pool.add(NOW_MS, beyond));
    assert!(!pool.add(4 * QUANTUM_MS, passed));
    assert!(pool.add(NOW_MS, surb(53)));
}

/// The sequence space ends cleanly: the frame at `u32::MAX` is released,
/// the direction does not fail by itself (a tick after it passes), and only a further frame
/// fails it.
#[test]
fn test_reorder_releases_the_last_sequence_then_fails() {
    let mut reorder = OnionReorder::<u32>::default();
    reorder.next_for_test(OnionSequence::new(u32::MAX));

    assert_eq!(
        reorder.accept(NOW_MS, OnionSequence::new(u32::MAX), 7),
        Ok(vec![7])
    );
    assert_eq!(reorder.expire(NOW_MS + ONION_ADMISSION_WINDOW_MS), Ok(()));
    assert!(reorder.accept(NOW_MS, OnionSequence::new(0), 8).is_err());
}

/// `count` reply blocks of class `class` expiring at `(3 + offset)·Q`, from a seeded RNG.
fn surbs_of(class: OnionLoopClass, seed: u64, count: usize, offset: u128) -> Vec<OnionSurb> {
    let mut rng = StdRng::seed_from_u64(seed);
    let expiry = OnionExpiry::from_ms((3 + offset) * QUANTUM_MS).expect("on the grid");
    (0..count)
        .map(|_| {
            build_surb(
                return_path().iter(),
                Did::from(9_u32),
                class,
                expiry,
                &mut rng,
            )
            .expect("a reply block")
            .0
        })
        .collect()
}

/// Totality over widths: held bytes wider than one block are cut to each block's
/// own capacity, across blocks of different classes, and a held end of stream is replied after
/// the data; nothing is replied while the pool is empty.
#[test]
fn test_held_bytes_are_cut_to_each_blocks_capacity_then_fin() {
    let mut blocks = surbs(55, 3, 0).into_iter();
    let mut session = acked(&mut blocks);
    let small = OnionFrame::data_capacity(CLASS);
    let expired_ms = 3 * QUANTUM_MS;
    let wide = Bytes::from(vec![0x61; 2 * small + 5]);

    assert!(kinds(&session.world(expired_ms, OnionWorldRead::Bytes(wide))).is_empty());
    assert!(kinds(&session.world(expired_ms, OnionWorldRead::Eof)).is_empty());

    let large = OnionLoopClass::KiB64;
    assert!(OnionFrame::data_capacity(large) > small + 5);
    // The loop's own 16 KiB block arrives first and carries one 16 KiB cut; the 64 KiB block of
    // its credit carries the rest, which exceeds a 16 KiB block; the held fin waits for a block.
    let mut fresh = surbs(56, 2, 2).into_iter();
    let mut wider = surbs_of(large, 57, 1, 2).into_iter();
    assert_eq!(
        kinds(&session.forward(
            expired_ms,
            credit(1, vec![wider.next().expect("a wide block")]),
            fresh.next().expect("a block"),
        )),
        [format!("data 1 {small}"), format!("data 2 {}", small + 5)]
    );
    assert_eq!(
        session.reply_capacity(expired_ms),
        None,
        "the fin is still held"
    );
    assert_eq!(
        kinds(&session.forward(
            expired_ms,
            credit(1, vec![fresh.next().expect("a block")]),
            surbs(58, 1, 2).pop().expect("a block"),
        )),
        ["fin 3"],
        "the held fin leaves with the next block"
    );
}

/// Forward frames reach the world in sequence order although their loops arrive reversed, and
/// the target is bound by the first released `T` frame.
#[test]
fn test_exit_session_writes_in_sequence_order() {
    let mut blocks = surbs(41, 3, 0).into_iter();
    let mut session = OnionExitSession::new(arguments().digest, NOW_MS);
    let mut next = || blocks.next().expect("a fixture block");

    assert!(kinds(&session.forward(NOW_MS, opening(2, b"c"), next())).is_empty());
    assert!(kinds(&session.forward(NOW_MS, opening(1, b"b"), next())).is_empty());
    assert_eq!(kinds(&session.forward(NOW_MS, opening(0, b"a"), next())), [
        "open example.com:443",
        "write a",
        "write b",
        "write c"
    ]);
}

/// A `T` frame whose target does not hash to `d`, or stream bytes before any target, is no
/// session: it closes without opening.
#[test]
fn test_exit_session_rejects_an_unbound_or_mismatching_target() {
    let mut mismatched = OnionExitSession::new(OnionTargetDigest::of(b"other:443"), NOW_MS);
    assert_eq!(
        kinds(&mismatched.forward(NOW_MS, opening(0, b""), surb(42))),
        ["close"]
    );

    let mut untargeted = OnionExitSession::new(arguments().digest, NOW_MS);
    let bare = OnionFrame::Data {
        sequence: OnionSequence::FIRST,
        target: None,
        payload: Bytes::from_static(b"x"),
    };
    assert_eq!(kinds(&untargeted.forward(NOW_MS, bare, surb(43))), [
        "close"
    ]);
}

/// A refused open replies `abort(0)` and closes; an ack without a block waits for credit, and
/// the credit resumes the session.
#[test]
fn test_exit_session_refusal_and_credit_resumption() {
    let mut refused = OnionExitSession::new(arguments().digest, NOW_MS);
    refused.forward(NOW_MS, opening(0, b""), surb(44));
    assert_eq!(kinds(&refused.opened(NOW_MS, false)), ["abort 0", "close"]);

    let mut starved = OnionExitSession::new(arguments().digest, NOW_MS);
    let mut blocks = surbs(45, 1, 0);
    starved.forward(NOW_MS, opening(0, b""), blocks.remove(0));
    // The open ack spends the session's only block.
    assert_eq!(kinds(&starved.opened(NOW_MS, true)), ["data 0 0"]);
    assert_eq!(starved.reply_capacity(NOW_MS), None);
    let refill = credit(1, surbs(46, 4, 0));
    assert!(kinds(&starved.forward(NOW_MS, refill, surb(47))).is_empty());
    assert_eq!(
        starved.reply_capacity(NOW_MS),
        Some(OnionFrame::data_capacity(CLASS)),
        "new credit resumes reading"
    );
}

/// A client `abort` closes the session on arrival, with no reply: held world bytes are dropped
/// and a closed session ignores every later frame.
#[test]
fn test_exit_session_closes_on_a_client_abort() {
    let mut blocks = surbs(60, 5, 0).into_iter();
    let mut session = acked(&mut blocks);
    let mut next = || blocks.next().expect("a fixture block");
    // A sequence far ahead of the reorder window: an abort is still applied on arrival.
    let abort = OnionFrame::Abort {
        sequence: OnionSequence::new(10_000),
    };

    assert_eq!(kinds(&session.forward(NOW_MS, abort, next())), ["close"]);
    assert!(session.is_closed());
    assert!(kinds(&session.forward(NOW_MS, opening(1, b"late"), next())).is_empty());
}

/// `V` without a forward loop closes the session.
#[test]
fn test_exit_session_closes_after_v_without_forward_loops() {
    let mut session = OnionExitSession::new(arguments().digest, NOW_MS);
    session.forward(NOW_MS, opening(0, b""), surb(48));
    assert!(session
        .tick(NOW_MS + ONION_ADMISSION_WINDOW_MS - 1)
        .is_empty());
    assert_eq!(kinds(&session.tick(NOW_MS + ONION_ADMISSION_WINDOW_MS)), [
        "close"
    ]);
}

// ---- client ------------------------------------------------------------------------------------

/// `T` is set on every data frame until the first reply and on none after it, sequences count
/// up, and the first released reply decides the open.
#[test]
fn test_client_session_sets_t_until_the_first_reply() {
    let mut session = OnionClientSession::new(Bytes::from_static(TARGET), NOW_MS);
    assert_eq!(
        session.data_capacity(CLASS),
        OnionFrame::data_capacity(CLASS) - 2 - TARGET.len()
    );
    for expected in 0..3 {
        let OnionFrame::Data {
            sequence, target, ..
        } = session.data(Bytes::new()).expect("sequence left")
        else {
            panic!("a data frame");
        };
        assert_eq!(sequence.value(), expected);
        assert_eq!(target.as_deref(), Some(TARGET));
    }

    let ack = OnionFrame::Data {
        sequence: OnionSequence::FIRST,
        target: None,
        payload: Bytes::new(),
    };
    assert_eq!(
        session.reply(NOW_MS, ack),
        Ok(vec![OnionClientEvent::Opened])
    );
    let OnionFrame::Data { target, .. } = session.data(Bytes::new()).expect("sequence left") else {
        panic!("a data frame");
    };
    assert_eq!(target, None);
    assert_eq!(
        session.data_capacity(CLASS),
        OnionFrame::data_capacity(CLASS)
    );

    let data = OnionFrame::Data {
        sequence: OnionSequence::new(1),
        target: None,
        payload: Bytes::from_static(b"bytes"),
    };
    let fin = OnionFrame::Fin {
        sequence: OnionSequence::new(2),
        target: None,
    };
    assert_eq!(session.reply(NOW_MS, fin), Ok(Vec::new()));
    assert_eq!(
        session.reply(NOW_MS, data),
        Ok(vec![
            OnionClientEvent::Data(Bytes::from_static(b"bytes")),
            OnionClientEvent::Fin
        ])
    );
}

/// A `fin` before any data is a refusal.
#[test]
fn test_client_session_reads_a_first_fin_as_a_refusal() {
    let mut session = OnionClientSession::new(Bytes::from_static(TARGET), NOW_MS);
    let fin = OnionFrame::Fin {
        sequence: OnionSequence::FIRST,
        target: None,
    };
    assert_eq!(
        session.reply(NOW_MS, fin),
        Ok(vec![OnionClientEvent::Refused])
    );
}

/// An `abort` after the open is `Aborted`, applied on arrival and never an end of stream: a
/// `fin` held behind a gap is not released as one, and every later frame is ignored.
#[test]
fn test_client_session_reads_abort_as_a_failure_never_eof() {
    let mut session = OnionClientSession::new(Bytes::from_static(TARGET), NOW_MS);
    let ack = OnionFrame::Data {
        sequence: OnionSequence::FIRST,
        target: None,
        payload: Bytes::new(),
    };
    let data = OnionFrame::Data {
        sequence: OnionSequence::new(1),
        target: None,
        payload: Bytes::from_static(b"part"),
    };
    let held_fin = OnionFrame::Fin {
        sequence: OnionSequence::new(3),
        target: None,
    };
    let abort = OnionFrame::Abort {
        sequence: OnionSequence::new(4),
    };
    let missing = OnionFrame::Data {
        sequence: OnionSequence::new(2),
        target: None,
        payload: Bytes::from_static(b"rest"),
    };

    assert_eq!(
        session.reply(NOW_MS, ack),
        Ok(vec![OnionClientEvent::Opened])
    );
    assert_eq!(
        session.reply(NOW_MS, data),
        Ok(vec![OnionClientEvent::Data(Bytes::from_static(b"part"))])
    );
    assert_eq!(session.reply(NOW_MS, held_fin), Ok(Vec::new()));
    assert_eq!(
        session.reply(NOW_MS, abort),
        Ok(vec![OnionClientEvent::Aborted])
    );
    assert_eq!(session.reply(NOW_MS, missing), Ok(Vec::new()));
}

/// An `abort` before any data is a refusal, and the client's own `abort` is sequenced like any
/// frame it sends.
#[test]
fn test_client_session_reads_a_first_abort_as_a_refusal() {
    let mut session = OnionClientSession::new(Bytes::from_static(TARGET), NOW_MS);
    let abort = OnionFrame::Abort {
        sequence: OnionSequence::FIRST,
    };
    assert_eq!(
        session.reply(NOW_MS, abort),
        Ok(vec![OnionClientEvent::Refused])
    );

    let mut giving_up = OnionClientSession::new(Bytes::from_static(TARGET), NOW_MS);
    giving_up.data(Bytes::new()).expect("sequence left");
    let Ok(OnionFrame::Abort { sequence }) = giving_up.abort() else {
        panic!("an abort frame");
    };
    assert_eq!(sequence.value(), 1);
}

/// The credit window asks `⌊D / (k + 1)⌋` full loops, so it never exceeds `min(W, Q_max)` and
/// sends nothing until it is `k + 1` short.
#[test]
fn test_credit_window_fills_to_its_target() {
    let window = OnionCreditWindow::DEFAULT;

    assert_eq!(window.credit_loops(0, CLASS), 12);
    assert_eq!(window.credit_loops(59, CLASS), 1);
    assert_eq!(window.credit_loops(60, CLASS), 0);
    assert_eq!(window.credit_loops(64, CLASS), 0);
    assert_eq!(window.credit_loops(300, CLASS), 0);
    assert_eq!(
        OnionCreditWindow::new(10_000).credit_loops(0, CLASS),
        ONION_SURB_POOL_CAPACITY / 5
    );
}

/// Batching (Prop. SURB batching, #843 acceptance): over a steady download of `n` replies, with
/// the window topped up after every reply, the client sends at most `⌈n / (k + 1)⌉ + 1` forward
/// loops after the open, so upload is `≈ 1/(k + 1)` of download.
#[test]
fn test_a_steady_download_costs_one_loop_per_k_plus_one_replies() {
    let window = OnionCreditWindow::DEFAULT;
    let k = OnionFrame::credit_capacity(CLASS);
    let x = OnionExpiry::from_ms(150_000).expect("on the grid");
    let mut credit = OnionClientCredit::default();
    credit.sent(NOW_MS, x, 1);
    for _ in 0..window.credit_loops(credit.count(NOW_MS), CLASS) {
        credit.sent(NOW_MS, x, k + 1);
    }

    let replies: usize = 10_000;
    let mut loops = 0;
    for _ in 0..replies {
        credit.replied(NOW_MS);
        for _ in 0..window.credit_loops(credit.count(NOW_MS), CLASS) {
            credit.sent(NOW_MS, x, k + 1);
            loops += 1;
        }
    }

    assert!(loops <= replies.div_ceil(k + 1) + 1, "{loops} loops");
    assert!(loops >= replies / (k + 1) - 1, "{loops} loops");
}

/// Idle: a session with no replies and no data, driven through the
/// driver's control rule every 10 s for 10 minutes after its open, sends exactly one keep-alive
/// loop per `V/2` rounded up to a tick (every 80 s, so `⌊600 / 80⌋ = 7`), and no refill burst
/// as the open's credit expires.
#[test]
fn test_an_idle_session_sends_one_loop_per_half_window() {
    let window = OnionCreditWindow::DEFAULT;
    let mut credit = OnionClientCredit::default();
    let expiry = |sent_ms: u128| {
        OnionExpiry::from_ms((sent_ms / QUANTUM_MS + 4) * QUANTUM_MS).expect("on the grid")
    };
    let blocks = OnionFrame::credit_capacity(CLASS);
    let send = |credit: &mut OnionClientCredit, now_ms: u128, loops: usize| {
        for _ in 0..loops {
            credit.sent(now_ms, expiry(now_ms), blocks);
        }
    };
    let opened = window.control_loops(OnionControlStep::Refill, 0, CLASS, 0, 0);
    send(&mut credit, 0, opened);
    assert_eq!(opened, 12, "the open fills the window");

    let mut last_forward_ms = 0;
    let mut loops = 0;
    for tick in 1..=60_u128 {
        let now_ms = tick * 10_000;
        let due = window.control_loops(
            OnionControlStep::Tick,
            credit.count(now_ms),
            CLASS,
            now_ms,
            last_forward_ms,
        );
        assert!(due <= 1, "a tick sends at most the keep-alive");
        if due > 0 {
            send(&mut credit, now_ms, due);
            last_forward_ms = now_ms;
            loops += due;
        }
    }

    assert_eq!(
        loops,
        600 / 80,
        "one keep-alive per V/2, at 10 s ticks, over 600 s"
    );
}

/// The ledger saturates at `Q_max`, where `h`'s pool refuses further blocks (#895 H4): a long
/// upload does not leave phantom credit behind, so the following download is topped up again
/// once `h` has spent its blocks.
#[test]
fn test_credit_ledger_saturates_at_the_pool_bound() {
    let mut credit = OnionClientCredit::default();
    let x = OnionExpiry::from_ms(150_000).expect("on the grid");

    for _ in 0..700 {
        credit.sent(NOW_MS, x, 1);
    }
    assert_eq!(credit.count(NOW_MS), ONION_SURB_POOL_CAPACITY);
    for _ in 0..ONION_SURB_POOL_CAPACITY {
        credit.replied(NOW_MS);
    }
    assert_eq!(credit.count(NOW_MS), 0);
    assert!(OnionCreditWindow::DEFAULT.credit_loops(credit.count(NOW_MS), CLASS) > 0);
}

/// Regression (#1224): `credit_blocks` caps per-frame SURB minting at `min(W, Q_max)`, and
/// `credit_loops` triggers refills at session open and throughout steady multi-frame downloads
/// across every loop class (`KiB16..MiB12`), preventing both `credit_loops == 0` starvation and
/// wasteful over-minting beyond `ONION_SURB_POOL_CAPACITY`.
#[test]
fn test_credit_window_caps_blocks_and_refills_every_loop_class() {
    let default_window = OnionCreditWindow::DEFAULT;
    let wide_window = OnionCreditWindow::new(500);
    let x = OnionExpiry::from_ms(150_000).expect("on the grid");

    for class in [
        OnionLoopClass::KiB16,
        OnionLoopClass::KiB64,
        OnionLoopClass::KiB256,
        OnionLoopClass::MiB1,
        OnionLoopClass::MiB4,
        OnionLoopClass::MiB12,
    ] {
        let blocks = default_window.credit_blocks(class);
        assert!(blocks >= 1);
        assert!(blocks <= 64, "{class:?} minted {blocks} > 64");
        assert!(
            wide_window.credit_blocks(class) <= ONION_SURB_POOL_CAPACITY,
            "{class:?} exceeded pool bound"
        );

        assert!(
            default_window.credit_loops(0, class) >= 1,
            "{class:?} starved at 0 outstanding"
        );
        assert!(
            default_window.credit_loops(1, class) >= 1,
            "{class:?} starved after open loop (+1 outstanding)"
        );

        let mut credit = OnionClientCredit::default();
        // Open loop contributes 1 implicit reply block, then Refill runs.
        credit.sent(NOW_MS, x, 0);
        for _ in 0..default_window.credit_loops(credit.count(NOW_MS), class) {
            credit.sent(NOW_MS, x, blocks);
        }
        assert!(credit.count(NOW_MS) > 1, "{class:?} failed to top up pool");

        // Stream 200 replies in `class` without credit ever dropping to 0.
        for step in 0..200_usize {
            assert!(
                credit.count(NOW_MS) > 0,
                "{class:?} starved at reply {step}"
            );
            credit.replied(NOW_MS);
            for _ in 0..default_window.credit_loops(credit.count(NOW_MS), class) {
                credit.sent(NOW_MS, x, blocks);
            }
        }
    }
}