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;
const ADMISSION_WINDOW_QUANTA: usize = 5;
const ADMISSION_WINDOW_QUANTA_WIDE: u128 = ONION_ADMISSION_WINDOW_MS / ONION_EXPIRY_QUANTUM_MS;
pub(crate) const ONION_ADMISSION_SENDER_UNITS: u32 = 16_384;
const ONION_ADMISSION_GLOBAL_UNITS: u32 = 64 * ONION_ADMISSION_SENDER_UNITS;
const _: () = assert!(ADMISSION_WINDOW_QUANTA_WIDE == ADMISSION_WINDOW_QUANTA as u128);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct OnionAdmissionUnits(NonZeroU32);
impl OnionAdmissionUnits {
#[cfg(all(test, rings_native))]
pub(super) const fn new(units: NonZeroU32) -> Self {
Self(units)
}
const fn get(self) -> u32 {
self.0.get()
}
}
#[must_use = "a charged cell is admitted with its token, or dropped after an invalid α or γ"]
#[derive(Debug)]
pub(crate) struct OnionAdmissionCharge {
arrival_ms: u128,
epoch: OnionProcessEpoch,
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(crate) struct OnionAdmissionLink {
did: Did,
generation: u64,
}
impl OnionAdmissionLink {
pub(crate) const fn new(did: Did, generation: u64) -> Self {
Self { did, generation }
}
pub(crate) const fn peer(self) -> Did {
self.did
}
pub(crate) const fn generation(self) -> u64 {
self.generation
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct OnionAdmissionLayer {
pub(crate) epoch: OnionProcessEpoch,
pub(crate) expiry: OnionExpiry,
pub(crate) tag: OnionReplayNonce,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OnionChargeRejection {
LinkNotLive,
SenderBudget,
GlobalBudget,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OnionAdmissionRejection {
StaleEpoch,
OutsideWindow,
Replayed,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct OnionLinkTableFull;
#[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 {
pub(crate) fn links(&self) -> &[OnionAdmissionLink] {
self.0.as_slice()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct OnionEpochNotFresh;
#[derive(Clone, Debug, Eq, PartialEq)]
struct SenderLedger {
ledger: QuantumLedger,
live: BTreeSet<u64>,
}
impl SenderLedger {
fn is_releasable_at(&self, quantum: u128) -> bool {
self.live.is_empty() && self.ledger.load(quantum) == 0
}
}
pub(crate) struct OnionAdmissionState {
epoch: OnionProcessEpoch,
clock_ms: u128,
swept_quantum: u128,
replay: ReplayStore,
global: QuantumLedger,
capacity: usize,
senders: BTreeMap<Did, SenderLedger>,
}
impl OnionAdmissionState {
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(),
}
}
pub(crate) const fn is_rolled_back_at(&self, now_ms: u128) -> bool {
now_ms.saturating_add(ONION_EXPIRY_OFFSET_MS) < self.clock_ms
}
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(())
}
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)
}
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(())
}
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();
}
}
}
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))
}
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,
})
}
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))
}
#[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)
})
}
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()
}
fn live_link_count(&self) -> usize {
self.senders.values().map(|sender| sender.live.len()).sum()
}
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(())
}
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
}
}