rings-node 0.39.0

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
//! Unified onion-layer admission: process epoch, validity window, replay store and unit budgets
//! (#834 L9, D2).
//!
//! # Step
//!
//! One hop's admission is a deterministic transition with no effect:
//!
//! ```text
//! δ : S × Time × I → S × (Out + Rejection)
//! I = Charge(Link × Units) + Admit(Charge × Epoch × Expiry × Tag)
//!   + LinkOpened(Link) + LinkClosed(Link) + Reconcile(𝒫 Link)
//! ρ : S × Epoch × Key → S + NotFresh                            (the reset; it takes no time)
//! Link = Did × Generation
//! ```
//!
//! [`OnionAdmissionState::charge`], [`OnionAdmissionState::admit`],
//! [`OnionAdmissionState::link_opened`], [`OnionAdmissionState::link_closed`], and
//! [`OnionAdmissionState::reconcile`] realise `δ` on the five summands in place, and
//! [`OnionAdmissionState::renew`] realises the reset `ρ`, which restarts the clock.
//! [`OnionAdmissionState::is_rolled_back_at`] is the pure query that tells the shell when to renew.
//! Time is an argument, and the only randomness is the probe key given at construction, so a trace
//! of inputs determines the trace of verdicts. The order is the paper's hop algorithm, with the
//! charge taken on receipt (#834 L9):
//!
//! ```text
//! charge(link, u) at arr ──Err──→ drop   (nothing charged, no ECDH)
//!   │ Ok(token = (arr, epoch_i))
//!   ▼
//! α valid, ECDH, peel, γ ──fails──→ drop the token  (charged once, no admission)
//!   │ holds
//!   ▼
//! admit(token, e, x, ν) = token.epoch = e = epoch_i ; token.arr < x ≤ token.arr + V ; clock < x ;
//!                         ν ∉ R_i[x] ; R_i[x] ← R_i[x] ∪ {ν}
//! ```
//!
//! # Laws
//!
//! * **Charging.** A cell is charged `u(b) = b / 16 KiB` by [`OnionAdmissionState::charge`] on
//!   receipt, against the live link it arrived on, before its group element `α` is checked or its
//!   key computed. The charge returns an [`OnionAdmissionCharge`]: an *affine* token (neither
//!   `Clone` nor `Copy`, built only by `charge`) that records the arrival `arr` and the process
//!   epoch. [`OnionAdmissionState::admit`] consumes the token. Dropping it (for an invalid `α` or
//!   a failed `γ`) is a valid settlement: those cells are already paid for. Replayed, expired and
//!   stale-epoch cells pay too. A charge on a link that is not live, or without headroom, is
//!   refused and charges nothing.
//!
//!   What the types guarantee: a charge requires a live link, [`OnionAdmissionState::charge`]
//!   takes the received [`OnionCell`](crate::onion::sphinx::cell::OnionCell) and charges its own
//!   class's units, and returns it paired with its token as a `Charged` cell, the only value
//!   that can be peeled; admission requires that token, and one token admits at most once. So a
//!   cell is charged once, with its class's units, before its header is read, by construction
//!   (the hop step, `circuit::hop`, is the one caller).
//! * **Clock: safety.** The state's clock is the join of every `now` it has seen,
//!   `now := max(now, clock)`. A wall-clock rollback therefore cannot refund budget or revive a
//!   dropped filter. The window is judged at the cell's arrival `token.arr`, which is the clock at
//!   its charge, not at its admission. Admission also requires `clock < x`, so a filter the clock
//!   has dropped is never written again, and at-most-once holds when an admission completes late.
//! * **Clock: liveness cost.** An honest layer built at `t` has `x ∈ [t + X₀, t + V)` with
//!   `X₀ = V − Q`. If the wall clock jumps forward by `Δ` and back, `clock` stays pinned at the
//!   future instant. Honest layers start failing the window once `Δ ≥ X₀ = 4Q`, and all of them
//!   fail once `Δ ≥ V`, until the wall clock catches up. Safety and liveness cannot both be kept
//!   inside one epoch: recovering early would mean forgetting filters that may still be live. So
//!   the shell (`circuit::shell`), when [`OnionAdmissionState::is_rolled_back_at`] holds
//!   (`now < clock − X₀`), must move to a fresh process epoch with
//!   [`OnionAdmissionState::renew`]. That clears the ledgers, the clock and the replay store, and
//!   then keeps the table's own live links with fresh ledgers, refusing nothing. It is safe by
//!   the epoch law, but it invalidates every loop in flight through this hop.
//! * **Skew.** The window has no skew tolerance. A hop whose clock runs `δ < Q` behind
//!   or ahead of the builder's rejects about `δ / Q` of loops at the window's edges.
//! * **Epoch (D2).** Only layers sealed for the current process epoch are admitted. A restarted
//!   process draws a fresh epoch, so every layer of the previous process is rejected, although the
//!   replay store was lost with that process.
//! * **At most once (L9).** An [`OnionExpiry`] is a quantum index, so it lies on the grid
//!   `x ∈ Q·ℕ` by construction. `R_i[x]` is consulted only while `now < x`. It is dropped as a
//!   whole by the first step at or after `x`, because steps are the only way time enters the state.
//!   A live filter has no false negatives, and once `x` has passed the window rejects `x`. Hence a
//!   pair `(x, ν)` is admitted at most once. At most `V / Q = 5` filters are live, namely the grid
//!   points of `(clock, clock + V]`. An idle hop keeps its filters until its next step. They stay
//!   within the memory bound below.
//! * **Five quanta per filter.** `arr < x ≤ arr + V` gives `arr ∈ [x − V, x)`. With `x = kQ` and `V
//!   = 5Q`, the arrival quanta are exactly `{k − 5, …, k − 1}`, five consecutive aligned quanta.
//!   The window is judged at `token.arr`, the instant of the charge, so these are also the charging
//!   quanta, however late the admission completes. They all lie in the ledger window `(s − 5, s]`
//!   of the last charge admitted into `R_i[x]` (at quantum `s ≤ k − 1`), and that charge bounded
//!   the whole set by the global cap.
//! * **Tags ≤ units.** Tags are counted per cell and budgets per unit, and every admitted cell was
//!   charged at least one unit. So `|R_i[x]| ≤ G = 64·B`, `R_i[x]` has at most `64` blocks, and
//!   its false-positive rate is `≤ 64·2⁻²⁶ = 2⁻²⁰`. A tag is live only if it was admitted in the
//!   current ledger window, so all live filters together hold `≤ G` tags in `≤ 64 + 5` blocks
//!   (`≈ 5.3 MB`).
//! * **Budgets.** Every aligned window of five arrival quanta charges one sender DID at most `B`
//!   units and the hop at most `G = 64·B`. An aligned window covers between `4Q` and `5Q` of wall
//!   time. So every interval of length `≤ 4Q` carries at most `B` units per sender. An interval
//!   just over `4Q` can straddle two windows and carry up to `2·B` (a burst at the end of quantum
//!   `s` and another at the start of `s + 5`). The long-run rate is `B / V ≈ 109` units/s per
//!   sender and `≈ 6990` units/s in total. `G` is one pool shared by all links, which `γ`-failing
//!   cover cells also consume.
//! * **Links and ledgers.** A link is one generation of an authenticated link to a DID,
//!   [`OnionAdmissionLink`] `= (did, generation)`: plain data. Core's link facts reach the
//!   data plane as `LinkFact::{Admitted, Retired}` in its namespace's queue, in core's order and
//!   never dropped (`extension::dispatch`), and the shell numbers each admission of a DID with a
//!   fresh generation. The state keeps the set of live links, and one budget ledger per DID with
//!   at least one live link or some load.
//!   * **Event-pairing obligation.** Between resets the live set shrinks only through
//!     `link_closed` and `reconcile`, so a lost `Retired` would pin a live link and a ledger
//!     slot. The dispatch queue loses no fact, so the obligation holds by construction once the
//!     data plane's namespace is registered; the links admitted before then are read once, by
//!     the [`OnionAdmissionState::reconcile`] the shell applies when it is installed.
//!     `reconcile` closes every live link absent from the snapshot and opens every snapshot link
//!     that is not live, so afterwards the live set is `L \ refused` for the snapshot `L`.
//!   * **Linearisation obligation.** `reconcile` treats its snapshot as authoritative, so the
//!     snapshot must be read and applied atomically at the shell's queue-drain point: the shell
//!     reads core's admitted peers inside the effect, under the protocol's transition gate.
//!     Every fact queued behind it then describes core's later changes, so after the queue
//!     drains the live set is exactly core's admitted links minus the refused ones. A fact
//!     queued before the read and applied after it may briefly close or reopen a link the
//!     snapshot already reflects; the facts after it restore core's state.
//!   * [`OnionAdmissionState::link_opened`] makes a link live, creating its DID's ledger, and is
//!     idempotent on a live link. [`OnionAdmissionState::link_closed`] makes it not live, and is
//!     idempotent too: closing an unknown, refused or closed link changes nothing. A close
//!     therefore affects only its own generation, under any interleaving (`open(g₁) open(g₂)
//!     close(g₁)` leaves `g₂` live, and a late close of a refused `g₁` is a no-op).
//!   * A cell is charged only against a live link, so a cell that arrives before its link is
//!     opened, after it is closed, or on a refused link is never charged and never decrypted.
//!   * A ledger is *releasable* when its DID has no live link and zero window load. Invariant:
//!     after every step no ledger is releasable, because `link_closed` releases a drained ledger
//!     at once and every step that enters a new quantum sweeps the ledgers that have drained.
//!     A load can reach zero only when the quantum advances, since charges only add to it.
//!   * The table holds at most `2·R` ledgers, where `R` is the transport connection-registry
//!     capacity (#723). There is no recycling. Within one epoch, a ledger is never reset while it
//!     carries load, so no DID regains budget by closing and reopening links: a reconnecting DID
//!     finds its old ledger. `(iii)` of the paper's replay bounds therefore holds per DID within an
//!     epoch, however many other DIDs churn. The live-link set is also capped at `2·R`. This is
//!     only a memory bound: under core's laws, which allow at most one live generation per DID and
//!     at most `R` DIDs, the cap is unreachable, and it only matters if the event obligation above
//!     is broken.
//!   * At most `R` links are live, and a closed ledger drains within one window. So the table
//!     fills only under connection churn beyond `R` within `V`. `link_opened` then refuses the
//!     *link*, which stays not live (fail closed): it carries no onion cell, every cell from it
//!     is refused uncharged, and core's link itself is core's to keep (#935). The peer's next
//!     admission is a new generation. There is no fairness here: a churner that opens cheap
//!     DIDs at rate `R / V` can win every freed slot. The event path serves links first come,
//!     first served. `reconcile` opens a snapshot's links in DID order, so when the table is
//!     full, small DIDs win, and DID prefixes can be ground cheaply. Eventual admission of an
//!     honest redial is a liveness *assumption* on churn, as #834 states, not a guarantee.
//!   * [`OnionAdmissionState::renew`] (the epoch reset) requires a *fresh* epoch. Renewing into the
//!     current epoch would clear the replay store while keeping `epoch_i`, so a replay of an
//!     admitted `(x, ν)` could be admitted again. The state rejects only `e′ = epoch_i`. The shell
//!     owes the rest: it draws `e′` independently and uniformly from `2¹²⁸`, and redraws on that
//!     rejection. Over `k` resets, the chance of reusing one *fixed* earlier epoch is `≤ k·2⁻¹²⁸`.
//!     The chance that some reset reuses *any* earlier epoch, the `A → B → A` sequence that would
//!     revive `A`'s layers, is at most the birthday bound `k²·2⁻¹²⁹`. The reset keeps the table's
//!     own live set, `ρ = reconcile(live_links(S)) ∘ clear`, which refuses nothing since it held
//!     that set before; every DID with a live link starts with a zero-load ledger, so every live
//!     link still has a ledger. The per-DID bound `B` therefore holds within one epoch.
//!     A token charged before the reset is never admitted after it, because its epoch differs.
//!   * `G` is independent of the table size and bounds what all DIDs admit together, and hence the
//!     replay store.

mod bloom;
mod ledger;
#[cfg(all(test, rings_native))]
mod tests;

use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::num::NonZeroU32;
use std::num::NonZeroUsize;

use rings_core::dht::Did;

pub(crate) use self::bloom::OnionReplayFilterKey;
use self::bloom::ReplayStore;
use self::ledger::QuantumLedger;
use super::OnionExpiry;
use super::OnionReplayNonce;
use super::ONION_ADMISSION_WINDOW_MS;
use super::ONION_EXPIRY_OFFSET_MS;
use super::ONION_EXPIRY_QUANTUM_MS;
use crate::onion::sphinx::cell::Charged;
use crate::onion::sphinx::cell::OnionCell;
use crate::onion::OnionProcessEpoch;

/// Arrival quanta per window, `N = V / Q = 5`, as the ledger's array length.
const ADMISSION_WINDOW_QUANTA: usize = 5;

/// `N = V / Q` in the quantum domain.
const ADMISSION_WINDOW_QUANTA_WIDE: u128 = ONION_ADMISSION_WINDOW_MS / ONION_EXPIRY_QUANTUM_MS;

/// Per-sender budget `B`: units of 16 KiB per DID per aligned window of `N` quanta.
pub(crate) const ONION_ADMISSION_SENDER_UNITS: u32 = 16_384;

/// Global budget `G = 64·B` units per aligned window of `N` quanta. It is independent of the number
/// of links and bounds the replay store at 64 blocks per filter.
const ONION_ADMISSION_GLOBAL_UNITS: u32 = 64 * ONION_ADMISSION_SENDER_UNITS;

/// Compile-time law: the ledger's array length is `N = V / Q`.
const _: () = assert!(ADMISSION_WINDOW_QUANTA_WIDE == ADMISSION_WINDOW_QUANTA as u128);

/// Units of 16 KiB charged for one cell. A class-`b` cell costs `b / 16 KiB ≥ 1` units.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct OnionAdmissionUnits(NonZeroU32);

impl OnionAdmissionUnits {
    /// Wrap a positive unit count.
    #[cfg(all(test, rings_native))]
    pub(super) const fn new(units: NonZeroU32) -> Self {
        Self(units)
    }

    /// The unit count.
    const fn get(self) -> u32 {
        self.0.get()
    }
}

/// Evidence of one charge, taken at `arrival_ms` by a state of this epoch; it is not bound to a
/// particular cell or to its units (the shell's obligation, see the Charging law). It is affine: it
/// is neither `Clone` nor `Copy`, only [`OnionAdmissionState::charge`] can build it, and
/// [`OnionAdmissionState::admit`] consumes it. Dropping it settles an invalid `α` or a failed `γ`,
/// which are already paid for.
#[must_use = "a charged cell is admitted with its token, or dropped after an invalid α or γ"]
#[derive(Debug)]
pub(crate) struct OnionAdmissionCharge {
    /// The cell's arrival: the monotone clock at its charge. The window is judged here.
    arrival_ms: u128,
    /// The epoch of the state that charged the cell.
    epoch: OnionProcessEpoch,
}

/// One generation of an authenticated link from a sender DID, as the data plane numbers core's
/// admissions of it. It is plain data, not a capability: the state keeps the set of live links.
///
/// Law: the shell draws generations from one counter, so `(did, generation)` names one
/// admission of `did` for the life of the data plane.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(crate) struct OnionAdmissionLink {
    /// The link's sender DID, which owns the budget ledger.
    did: Did,
    /// The shell's generation of this admission of `did`.
    generation: u64,
}

impl OnionAdmissionLink {
    /// The link of `did` at `generation`.
    pub(crate) const fn new(did: Did, generation: u64) -> Self {
        Self { did, generation }
    }

    /// The peer at the other end.
    pub(crate) const fn peer(self) -> Did {
        self.did
    }

    /// The generation of this admission.
    pub(crate) const fn generation(self) -> u64 {
        self.generation
    }
}

/// The authenticated fields of a peeled layer that admission decides on.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct OnionAdmissionLayer {
    /// Process epoch the layer was sealed for.
    pub(crate) epoch: OnionProcessEpoch,
    /// Quantised expiry `x` of the layer's loop.
    pub(crate) expiry: OnionExpiry,
    /// Replay tag `ν` of the layer.
    pub(crate) tag: OnionReplayNonce,
}

/// Why a cell could not be charged. Nothing was charged, and the cell must not be decrypted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OnionChargeRejection {
    /// The cell's link is not live: not yet opened, closed, or refused.
    LinkNotLive,
    /// The sender's ledger lacks headroom for the cell's units.
    SenderBudget,
    /// The hop lacks headroom under `G = 64·B`.
    GlobalBudget,
}

/// Why a charged layer was not admitted. The cell was charged and is dropped.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OnionAdmissionRejection {
    /// The layer, or its charge, belongs to another process epoch (D2).
    StaleEpoch,
    /// `x ∉ (token.arr, token.arr + V]`, or `x` has passed on the monotone clock.
    OutsideWindow,
    /// `ν ∈ R_i[x]`: a replay, or a false positive at rate `≤ 2⁻²⁰`.
    Replayed,
}

/// A link refused because the table is full (connection churn beyond `R` within `V`). The link
/// stays not live, and the peer's next admission is a new generation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct OnionLinkTableFull;

/// The links a table refused, which stay not live. Returned by
/// [`OnionAdmissionState::reconcile`].
#[must_use = "refused links carry no onion cell, which the shell reports"]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct OnionRefusedLinks(Vec<OnionAdmissionLink>);

impl OnionRefusedLinks {
    /// The refused links, in DID order.
    pub(crate) fn links(&self) -> &[OnionAdmissionLink] {
        self.0.as_slice()
    }
}

/// A renewal refused because the requested epoch is the current one. Renewing into the current
/// epoch would clear the replay store while keeping `epoch_i`, and so re-admit replays.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct OnionEpochNotFresh;

/// One sender DID's unit ledger and its live link generations.
#[derive(Clone, Debug, Eq, PartialEq)]
struct SenderLedger {
    /// Units charged to this DID in the window.
    ledger: QuantumLedger,
    /// The generations of this DID's live links.
    live: BTreeSet<u64>,
}

impl SenderLedger {
    /// Whether the ledger may be released at `quantum`: it has no live link and no load.
    fn is_releasable_at(&self, quantum: u128) -> bool {
        self.live.is_empty() && self.ledger.load(quantum) == 0
    }
}

/// The admission state `S` of one hop for one process lifetime.
pub(crate) struct OnionAdmissionState {
    /// This process's epoch `epoch_i`.
    epoch: OnionProcessEpoch,
    /// Monotone clock: the greatest `now` seen so far.
    clock_ms: u128,
    /// The quantum at which drained ledgers were last swept.
    swept_quantum: u128,
    /// Replay store `R_i`.
    replay: ReplayStore,
    /// Units charged to the whole hop.
    global: QuantumLedger,
    /// Capacity `2·R`, both of the ledger table and of the live-link set.
    capacity: usize,
    /// At most `capacity` sender ledgers, none of them releasable between steps.
    senders: BTreeMap<Did, SenderLedger>,
}

impl OnionAdmissionState {
    /// The initial state of a process with epoch `epoch` and probe key `filter_key`, both drawn
    /// once at process start by the caller. The table holds `2·R` ledgers and live links, where `R`
    /// is the transport connection-registry capacity.
    pub(crate) fn new(
        epoch: OnionProcessEpoch,
        filter_key: OnionReplayFilterKey,
        link_registry_capacity: NonZeroUsize,
    ) -> Self {
        Self {
            epoch,
            clock_ms: 0,
            swept_quantum: 0,
            replay: ReplayStore::new(filter_key),
            global: QuantumLedger::default(),
            capacity: link_registry_capacity.get().saturating_mul(2),
            senders: BTreeMap::new(),
        }
    }

    /// Whether the wall clock has rolled back far enough behind the monotone clock that honest
    /// layers fail the window: `now < clock − X₀`. The shell then renews into a fresh epoch.
    pub(crate) const fn is_rolled_back_at(&self, now_ms: u128) -> bool {
        now_ms.saturating_add(ONION_EXPIRY_OFFSET_MS) < self.clock_ms
    }

    /// The reset `ρ(epoch, key)`: the epoch reset. It requires a fresh `epoch` and otherwise
    /// changes nothing. On success the state is the initial state of `epoch` with probe key
    /// `filter_key` and the same live links, each DID with a zero-load ledger: `ρ =
    /// reconcile(live_links(S)) ∘ clear`. It refuses nothing, since the table held these links
    /// before, so it keeps no link the shell would have to close.
    pub(crate) fn renew(
        &mut self,
        epoch: OnionProcessEpoch,
        filter_key: OnionReplayFilterKey,
    ) -> Result<(), OnionEpochNotFresh> {
        if epoch == self.epoch {
            return Err(OnionEpochNotFresh);
        }
        let senders = std::mem::take(&mut self.senders)
            .into_iter()
            .filter(|(_, sender)| !sender.live.is_empty())
            .map(|(did, sender)| {
                (did, SenderLedger {
                    ledger: QuantumLedger::default(),
                    live: sender.live,
                })
            })
            .collect();
        *self = Self {
            epoch,
            clock_ms: 0,
            swept_quantum: 0,
            replay: ReplayStore::new(filter_key),
            global: QuantumLedger::default(),
            capacity: self.capacity,
            senders,
        };
        Ok(())
    }

    /// The step `δ` on `Reconcile(live)`: make the live-link set equal core's registry snapshot
    /// `live`, up to refusals. Every live link absent from the snapshot is closed first, which
    /// frees its slot. Then every snapshot link that is not live is opened in DID order, with the
    /// table's usual refusal. Afterwards the live set is `live \ refused`, no link that was already
    /// live and is in the snapshot is refused, and a second reconciliation with the same snapshot,
    /// in any order, changes nothing. It seeds the links admitted before the data plane was
    /// installed. The snapshot must be linearised with the event stream (see the module laws).
    pub(crate) fn reconcile(
        &mut self,
        now_ms: u128,
        live: impl IntoIterator<Item = OnionAdmissionLink>,
    ) -> OnionRefusedLinks {
        self.advance(now_ms);
        let mut snapshot = BTreeMap::<Did, BTreeSet<u64>>::new();
        for link in live {
            snapshot
                .entry(link.peer())
                .or_default()
                .insert(link.generation());
        }
        let absent = self
            .senders
            .iter()
            .flat_map(|(&did, sender)| {
                let kept = snapshot.get(&did);
                sender
                    .live
                    .iter()
                    .copied()
                    .filter(move |generation| {
                        !kept.is_some_and(|generations| generations.contains(generation))
                    })
                    .map(move |generation| OnionAdmissionLink::new(did, generation))
            })
            .collect::<Vec<_>>();
        for link in absent {
            self.link_closed(now_ms, link);
        }
        let mut refused = Vec::new();
        for (did, generations) in snapshot {
            for generation in generations {
                let link = OnionAdmissionLink::new(did, generation);
                if self.link_opened(now_ms, link).is_err() {
                    refused.push(link);
                }
            }
        }
        OnionRefusedLinks(refused)
    }

    /// The step `δ` on `LinkOpened(link)`: make `link` live, creating its DID's ledger if it has
    /// none. Opening a live link again changes nothing. A full table refuses the link, which stays
    /// not live.
    pub(crate) fn link_opened(
        &mut self,
        now_ms: u128,
        link: OnionAdmissionLink,
    ) -> Result<(), OnionLinkTableFull> {
        self.advance(now_ms);
        let live_links = self.live_link_count();
        let ledgers = self.senders.len();
        let capacity = self.capacity;
        let sender = match self.senders.entry(link.peer()) {
            Entry::Occupied(occupied) if occupied.get().live.contains(&link.generation()) => {
                return Ok(());
            }
            Entry::Occupied(occupied) if live_links < capacity => occupied.into_mut(),
            Entry::Vacant(vacant) if live_links < capacity && ledgers < capacity => {
                vacant.insert(SenderLedger {
                    ledger: QuantumLedger::default(),
                    live: BTreeSet::new(),
                })
            }
            Entry::Occupied(_) | Entry::Vacant(_) => return Err(OnionLinkTableFull),
        };
        sender.live.insert(link.generation());
        Ok(())
    }

    /// The step `δ` on `LinkClosed(link)`: make `link` no longer live, and release its DID's ledger
    /// at once if that leaves it releasable. It is idempotent: closing a link that is not live
    /// (unknown, refused, or already closed) changes nothing, so a close can never take another
    /// generation's liveness away.
    pub(crate) fn link_closed(&mut self, now_ms: u128, link: OnionAdmissionLink) {
        let quantum = self.advance(now_ms);
        if let Entry::Occupied(mut occupied) = self.senders.entry(link.peer()) {
            occupied.get_mut().live.remove(&link.generation());
            if occupied.get().is_releasable_at(quantum) {
                occupied.remove();
            }
        }
    }

    /// The step `δ` on `Charge(link, u(b))` for a received cell: charge it `u(b) = b / 16 KiB`
    /// units, the units of its own class, and pair it with the token (#843). This is the only
    /// source of tokens outside this module, so a peel is always paid for, with its cell's units
    /// (see `sphinx::cell`).
    ///
    /// # Errors
    ///
    /// The [`OnionChargeRejection`] of the unit step; nothing is charged, and the cell must be
    /// dropped undecrypted.
    pub(crate) fn charge(
        &mut self,
        now_ms: u128,
        link: OnionAdmissionLink,
        cell: OnionCell,
    ) -> Result<Charged<OnionCell>, OnionChargeRejection> {
        let units = OnionAdmissionUnits(cell.class().units());
        self.charge_units(now_ms, link, units)
            .map(|charge| Charged::new(cell, charge))
    }

    /// The step `δ` on `Charge(link, u)`: charge a cell received on `link` to its DID's ledger and
    /// to the global ledger, both or neither, before its key is computed. Only a live link is
    /// charged. Private: the crate charges cells through [`Self::charge`].
    ///
    /// ```text
    ///  now := max(now, clock);  drop R[x] for x ≤ now;  s = ⌊now / Q⌋;  sweep if s is new
    ///   ├─ link not live ─────────────────→ LinkNotLive
    ///   ├─ load_did(s) + u > B ───────────→ SenderBudget
    ///   ├─ load_global(s) + u > G ────────→ GlobalBudget
    ///   └─ charge both ledgers ───────────→ Ok(token = (clock, epoch_i))
    /// ```
    fn charge_units(
        &mut self,
        now_ms: u128,
        link: OnionAdmissionLink,
        units: OnionAdmissionUnits,
    ) -> Result<OnionAdmissionCharge, OnionChargeRejection> {
        let quantum = self.advance(now_ms);
        let sender = self
            .senders
            .get_mut(&link.peer())
            .filter(|sender| sender.live.contains(&link.generation()))
            .ok_or(OnionChargeRejection::LinkNotLive)?;
        let charged_sender = sender
            .ledger
            .charged(quantum, units.get(), ONION_ADMISSION_SENDER_UNITS)
            .ok_or(OnionChargeRejection::SenderBudget)?;
        let charged_global = self
            .global
            .charged(quantum, units.get(), ONION_ADMISSION_GLOBAL_UNITS)
            .ok_or(OnionChargeRejection::GlobalBudget)?;
        sender.ledger = charged_sender;
        self.global = charged_global;
        Ok(OnionAdmissionCharge {
            arrival_ms: self.clock_ms,
            epoch: self.epoch,
        })
    }

    /// The live link of `did`, against which its cells are charged: core admits at most one
    /// generation of a DID at a time, so this is that generation. If a lost `Retired` has left
    /// two live until the next reconciliation, the newest is taken, since core's generations
    /// increase.
    pub(crate) fn live_link(&self, did: Did) -> Option<OnionAdmissionLink> {
        self.senders
            .get(&did)
            .and_then(|sender| sender.live.last().copied())
            .map(|generation| OnionAdmissionLink::new(did, generation))
    }

    /// The units charged to `did` in the window of the state's clock, for tests of the Paid law.
    #[cfg(all(test, rings_native))]
    pub(crate) fn sender_units(&self, did: Did) -> u32 {
        self.senders.get(&did).map_or(0, |sender| {
            sender.ledger.load(self.clock_ms / ONION_EXPIRY_QUANTUM_MS)
        })
    }

    /// Every live link, in DID and generation order: the table's own view, linearised with the
    /// facts it has applied.
    pub(crate) fn live_links(&self) -> Vec<OnionAdmissionLink> {
        self.senders
            .iter()
            .flat_map(|(&did, sender)| {
                sender
                    .live
                    .iter()
                    .map(move |&generation| OnionAdmissionLink::new(did, generation))
            })
            .collect()
    }

    /// The number of live links, `Σ_d |live(d)|`, derived rather than stored.
    fn live_link_count(&self) -> usize {
        self.senders.values().map(|sender| sender.live.len()).sum()
    }

    /// The step `δ` on `Admit(token, e, x, ν)`: admit a charged, `γ`-verified layer, or reject it.
    /// The charge stands either way. The window is judged at the token's arrival, not at `now`.
    ///
    /// ```text
    ///  now := max(now, clock);  drop R[x] for x ≤ now
    ///   ├─ e ≠ epoch_i ∨ token.epoch ≠ epoch_i ──────→ StaleEpoch
    ///   ├─ ¬ x.admissible_at(token.arr) ∨ x ≤ clock ─→ OutsideWindow
    ///   ├─ ν ∈ R[x] ─────────────────────────────────→ Replayed
    ///   └─ R[x] ← R[x] ∪ {ν} ────────────────────────→ Ok
    /// ```
    ///
    /// A wire expiry off the grid never reaches this step: the layer decoder parses it with
    /// `OnionExpiry::from_wire_ms`, and `None` drops the cell, which is already charged.
    pub(crate) fn admit(
        &mut self,
        now_ms: u128,
        charge: OnionAdmissionCharge,
        layer: OnionAdmissionLayer,
    ) -> Result<(), OnionAdmissionRejection> {
        let OnionAdmissionCharge { arrival_ms, epoch } = charge;
        self.advance(now_ms);
        if layer.epoch != self.epoch || epoch != self.epoch {
            return Err(OnionAdmissionRejection::StaleEpoch);
        }
        if !layer.expiry.admissible_at(arrival_ms) || layer.expiry.has_passed_at(self.clock_ms) {
            return Err(OnionAdmissionRejection::OutsideWindow);
        }
        let probe = self.replay.probe(layer.tag);
        if self.replay.contains(layer.expiry, &probe) {
            return Err(OnionAdmissionRejection::Replayed);
        }
        self.replay.insert(layer.expiry, &probe);
        Ok(())
    }

    /// Advance the monotone clock to `max(now, clock)`, drop every filter whose `x` has passed,
    /// and, on entering a new quantum, release every ledger that has become releasable. Return the
    /// current arrival quantum `⌊clock / Q⌋`.
    fn advance(&mut self, now_ms: u128) -> u128 {
        self.clock_ms = self.clock_ms.max(now_ms);
        self.replay.forget_through(self.clock_ms);
        let quantum = self.clock_ms / ONION_EXPIRY_QUANTUM_MS;
        if quantum > self.swept_quantum {
            self.senders
                .retain(|_, sender| !sender.is_releasable_at(quantum));
            self.swept_quantum = quantum;
        }
        quantum
    }
}