mod bloom;
mod ledger;
#[cfg(all(test, rings_native))]
mod tests;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::num::NonZeroU32;
use std::num::NonZeroUsize;
use std::sync::Arc;
use rings_core::dht::Did;
use rings_core::message::FloorUse;
use rings_core::message::Principal;
use rings_core::message::SlotFloorUse;
use rings_core::message::SlotRoster;
pub(crate) use self::bloom::OnionReplayFilterKey;
use self::bloom::ReplayStore;
pub(crate) use self::ledger::OnionSlotId;
use self::ledger::QuantumLedger;
use self::ledger::SlotLedger;
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;
pub(crate) const ONION_ADMISSION_SLOT_FLOOR_UNITS: u32 = 1_024;
const ONION_ADMISSION_GLOBAL_UNITS: u32 = 64 * ONION_ADMISSION_SENDER_UNITS;
const _: () = assert!(ADMISSION_WINDOW_QUANTA_WIDE == ADMISSION_WINDOW_QUANTA as u128);
const _: () = assert!(
ONION_ADMISSION_SLOT_FLOOR_UNITS > 0
&& ONION_ADMISSION_SLOT_FLOOR_UNITS <= ONION_ADMISSION_SENDER_UNITS
);
#[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;
pub(crate) struct OnionAdmissionState {
epoch: OnionProcessEpoch,
clock_ms: u128,
swept_quantum: u128,
replay: ReplayStore,
global: QuantumLedger,
capacity: usize,
slot_capacity: usize,
floor_units: u32,
pool_units: u32,
pool_load: u32,
slot_roster: Arc<SlotRoster>,
owns_slot_roster: bool,
slots: BTreeMap<OnionSlotId, SlotLedger>,
peer_slots: BTreeMap<Did, OnionSlotId>,
}
impl OnionAdmissionState {
pub(crate) fn new(
epoch: OnionProcessEpoch,
filter_key: OnionReplayFilterKey,
link_registry_capacity: NonZeroUsize,
) -> Self {
let capacity = link_registry_capacity.get().saturating_mul(2);
let slot_roster = Arc::new(SlotRoster::new(capacity));
let slot_capacity = slot_roster.capacity().max(1);
let (floor_units, pool_units) = Self::slot_shares(slot_capacity);
Self {
epoch,
clock_ms: 0,
swept_quantum: 0,
replay: ReplayStore::new(filter_key),
global: QuantumLedger::default(),
capacity,
slot_capacity,
floor_units,
pool_units,
pool_load: 0,
slot_roster,
owns_slot_roster: true,
slots: BTreeMap::new(),
peer_slots: BTreeMap::new(),
}
}
pub(crate) fn with_slot_roster(mut self, slot_roster: Arc<SlotRoster>) -> Self {
if slot_roster.capacity() > 0 {
self.slot_capacity = slot_roster.capacity();
(self.floor_units, self.pool_units) = Self::slot_shares(self.slot_capacity);
}
let quantum = self.clock_ms / ONION_EXPIRY_QUANTUM_MS;
slot_roster.set_extra_floor_use(self.floor_use_at(quantum));
self.slot_roster = slot_roster;
self.owns_slot_roster = false;
self
}
#[cfg(all(test, rings_native))]
pub(crate) fn slot_of(&self, did: Did) -> Option<OnionSlotId> {
self.peer_slots.get(&did).copied()
}
#[cfg(all(test, rings_native))]
pub(crate) const fn shares(&self) -> (u32, u32) {
(self.floor_units, self.pool_units)
}
fn slot_shares(slot_capacity: usize) -> (u32, u32) {
let slots = u32::try_from(slot_capacity).unwrap_or(u32::MAX).max(1);
let half_global = ONION_ADMISSION_GLOBAL_UNITS / 2;
let floor_units = (half_global / slots)
.min(ONION_ADMISSION_SLOT_FLOOR_UNITS)
.max(u32::from(slots <= ONION_ADMISSION_GLOBAL_UNITS));
let reserved = slots.saturating_mul(floor_units);
let pool_units = ONION_ADMISSION_GLOBAL_UNITS.saturating_sub(reserved);
(floor_units, pool_units)
}
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 mut slots = BTreeMap::new();
let mut peer_slots = BTreeMap::new();
for (slot_id, slot) in std::mem::take(&mut self.slots) {
if slot.live.is_empty() {
continue;
}
for &did in slot.live.keys() {
peer_slots.insert(did, slot_id);
}
slots.insert(slot_id, SlotLedger {
ledger: QuantumLedger::default(),
live: slot.live,
retained: BTreeMap::new(),
});
}
self.slot_roster
.set_extra_floor_use(SlotFloorUse::default());
*self = Self {
epoch,
clock_ms: 0,
swept_quantum: 0,
replay: ReplayStore::new(filter_key),
global: QuantumLedger::default(),
capacity: self.capacity,
slot_capacity: self.slot_capacity,
floor_units: self.floor_units,
pool_units: self.pool_units,
pool_load: 0,
slot_roster: Arc::clone(&self.slot_roster),
owns_slot_roster: self.owns_slot_roster,
slots,
peer_slots,
};
Ok(())
}
pub(crate) fn reconcile(
&mut self,
now_ms: u128,
live: impl IntoIterator<Item = OnionAdmissionLink>,
) -> OnionRefusedLinks {
self.advance(now_ms);
let mut seen = BTreeSet::new();
let mut snapshot = live
.into_iter()
.filter(|&link| seen.insert(link))
.collect::<Vec<_>>();
let mut absent =
self.slots
.iter()
.flat_map(|(&slot_id, slot)| {
slot.live.iter().flat_map(move |(&did, generations)| {
generations.iter().copied().map(move |generation| {
(slot_id, OnionAdmissionLink::new(did, generation))
})
})
})
.filter(|(_, link)| !seen.contains(link))
.collect::<Vec<_>>();
absent.sort_by_key(|(slot_id, link)| (*slot_id, link.generation()));
absent
.into_iter()
.for_each(|(_, link)| self.link_closed(now_ms, link));
snapshot.sort_by_key(|&link| {
let already_live = self.is_link_live(link);
let assigned = self.assigned_slot_of(link.peer());
(
!already_live,
assigned.is_none(),
assigned.unwrap_or(OnionSlotId::new(0)),
link.generation(),
)
});
let refused = snapshot
.into_iter()
.filter(|&link| self.link_opened(now_ms, link).is_err())
.collect();
OnionRefusedLinks(refused)
}
pub(crate) fn link_opened(
&mut self,
now_ms: u128,
link: OnionAdmissionLink,
) -> Result<(), OnionLinkTableFull> {
let quantum = self.advance(now_ms);
if self.is_link_live(link) {
return Ok(());
}
if self.live_link_count() >= self.capacity {
return Err(OnionLinkTableFull);
}
let did = link.peer();
let slot_id = self.acquire_slot_for(did, quantum)?;
let slot = self.slots.entry(slot_id).or_default();
slot.live.entry(did).or_default().insert(link.generation());
if let Some(previous_slot_id) = self.peer_slots.insert(did, slot_id) {
if previous_slot_id != slot_id {
let transferred = self
.slots
.get_mut(&previous_slot_id)
.and_then(|previous_slot| {
let retired_quantum = previous_slot.retained.remove(&did)?;
QuantumLedger::in_window(retired_quantum, quantum)
.then_some((retired_quantum, previous_slot.ledger))
});
if let Some((retired_quantum, previous_ledger)) = transferred {
if let Some(slot) = self.slots.get_mut(&slot_id) {
slot.ledger = slot.ledger.merge_in_window(
quantum,
&previous_ledger,
ONION_ADMISSION_SENDER_UNITS,
);
slot.retained.entry(did).or_insert(retired_quantum);
}
self.slot_roster
.set_extra_floor_use(self.floor_use_at(quantum));
}
}
}
Ok(())
}
pub(crate) fn link_closed(&mut self, now_ms: u128, link: OnionAdmissionLink) {
let quantum = self.advance(now_ms);
let did = link.peer();
let Some(slot_id) = self.peer_slots.get(&did).copied() else {
return;
};
let removed_last_for_peer = {
let Some(slot) = self.slots.get_mut(&slot_id) else {
return;
};
let Some(true) = slot.remove_live_generation(did, link.generation()) else {
return;
};
let remaining_peer = slot.live.first_key_value().map(|(&peer, _)| peer);
let has_load = slot.ledger.load(quantum) > 0;
let retain_did = slot.has_unexpired_charge(did, quantum);
let slot_empty = slot.live.is_empty();
(remaining_peer, has_load, retain_did, slot_empty)
};
let (remaining_peer, has_load, retain_did, slot_empty) = removed_last_for_peer;
self.release_roster_slot_on_close(did, slot_id, remaining_peer);
if !retain_did {
if let Some(slot) = self.slots.get_mut(&slot_id) {
slot.retained.remove(&did);
}
self.peer_slots.remove(&did);
}
if !has_load && slot_empty {
if let Some(removed) = self.slots.remove(&slot_id) {
for retained_did in removed.retained.into_keys() {
if self.peer_slots.get(&retained_did) == Some(&slot_id) {
self.peer_slots.remove(&retained_did);
}
}
}
}
self.slot_roster
.set_extra_floor_use(self.floor_use_at(quantum));
}
fn release_roster_slot_on_close(
&mut self,
did: Did,
slot_id: OnionSlotId,
remaining_peer: Option<Did>,
) {
if self.owns_slot_roster
&& self.slot_roster.principal_of(Some(did))
== u16::try_from(slot_id.index()).map_or(Principal::Unbound, Principal::Slot)
{
self.slot_roster.depart(did);
if let Some(peer) = remaining_peer.filter(|&peer| !self.slot_roster.holds(peer)) {
self.slot_roster.arrive_preferring(
peer,
u16::try_from(slot_id.index()).ok(),
&SlotFloorUse::default(),
);
}
}
}
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 did = link.peer();
let slot_id = self
.peer_slots
.get(&did)
.copied()
.ok_or(OnionChargeRejection::LinkNotLive)?;
let slot = self
.slots
.get_mut(&slot_id)
.filter(|slot| slot.contains_live(did, link.generation()))
.ok_or(OnionChargeRejection::LinkNotLive)?;
let old_over = slot.ledger.load(quantum).saturating_sub(self.floor_units);
let charged_slot = slot
.ledger
.charged(quantum, units.get(), ONION_ADMISSION_SENDER_UNITS)
.ok_or(OnionChargeRejection::SenderBudget)?;
let new_over = charged_slot.load(quantum).saturating_sub(self.floor_units);
let overflow = new_over.saturating_sub(old_over);
let next_pool_load = if overflow > 0 {
self.pool_load
.checked_add(overflow)
.filter(|&pool| pool <= self.pool_units)
.ok_or(OnionChargeRejection::GlobalBudget)?
} else {
self.pool_load
};
let charged_global = self
.global
.charged(quantum, units.get(), ONION_ADMISSION_GLOBAL_UNITS)
.ok_or(OnionChargeRejection::GlobalBudget)?;
slot.ledger = charged_slot;
slot.retained.insert(did, quantum);
self.global = charged_global;
self.pool_load = next_pool_load;
self.slot_roster
.set_extra_floor_use(self.floor_use_at(quantum));
Ok(OnionAdmissionCharge {
arrival_ms: self.clock_ms,
epoch: self.epoch,
})
}
pub(crate) fn live_link(&self, did: Did) -> Option<OnionAdmissionLink> {
let slot_id = self.peer_slots.get(&did).copied()?;
self.slots
.get(&slot_id)
.and_then(|slot| slot.live.get(&did))
.and_then(|generations| generations.last().copied())
.map(|generation| OnionAdmissionLink::new(did, generation))
}
#[cfg(all(test, rings_native))]
pub(crate) fn sender_units(&self, did: Did) -> u32 {
self.peer_slots
.get(&did)
.and_then(|slot_id| self.slots.get(slot_id))
.map_or(0, |slot| {
slot.ledger.load(self.clock_ms / ONION_EXPIRY_QUANTUM_MS)
})
}
pub(crate) fn live_links(&self) -> Vec<OnionAdmissionLink> {
let mut links = self
.slots
.values()
.flat_map(|slot| {
slot.live.iter().flat_map(|(&did, generations)| {
generations
.iter()
.map(move |&generation| OnionAdmissionLink::new(did, generation))
})
})
.collect::<Vec<_>>();
links.sort();
links
}
fn live_link_count(&self) -> usize {
self.slots.values().map(SlotLedger::live_link_count).sum()
}
fn is_link_live(&self, link: OnionAdmissionLink) -> bool {
self.peer_slots
.get(&link.peer())
.and_then(|slot_id| self.slots.get(slot_id))
.is_some_and(|slot| slot.contains_live(link.peer(), link.generation()))
}
fn roster_slot_of(&self, did: Did) -> Option<OnionSlotId> {
match self.slot_roster.principal_of(Some(did)) {
Principal::Slot(slot) if usize::from(slot) < self.slot_capacity => {
Some(OnionSlotId::new(usize::from(slot)))
}
_ => None,
}
}
fn can_resume_slot(&self, did: Did, slot_id: OnionSlotId) -> bool {
self.slots
.get(&slot_id)
.is_none_or(|slot| slot.is_free() || slot.contains_live_peer(did))
}
fn assigned_slot_of(&self, did: Did) -> Option<OnionSlotId> {
self.peer_slots
.get(&did)
.copied()
.filter(|&slot_id| self.can_resume_slot(did, slot_id))
.or_else(|| self.roster_slot_of(did))
}
fn resume_existing_slot(&mut self, did: Did, quantum: u128) -> Option<OnionSlotId> {
let slot_id = self.peer_slots.get(&did).copied()?;
if !self.can_resume_slot(did, slot_id) {
return None;
}
let slot_was_free = self.slots.get(&slot_id).is_none_or(SlotLedger::is_free);
if self.owns_slot_roster && slot_was_free && !self.slot_roster.holds(did) {
let floor_use = self.floor_use_at(quantum);
self.slot_roster.arrive_preferring(
did,
u16::try_from(slot_id.index()).ok(),
&floor_use,
);
}
Some(slot_id)
}
fn acquire_roster_slot(
&mut self,
did: Did,
preferred: Option<OnionSlotId>,
floor_use: &SlotFloorUse,
) -> Option<OnionSlotId> {
if !self.owns_slot_roster {
return None;
}
self.slot_roster.arrive_preferring(
did,
preferred.and_then(|slot_id| u16::try_from(slot_id.index()).ok()),
floor_use,
);
self.roster_slot_of(did)
.filter(|slot_id| self.slots.get(slot_id).is_none_or(SlotLedger::is_free))
}
fn acquire_slot_for(
&mut self,
did: Did,
quantum: u128,
) -> Result<OnionSlotId, OnionLinkTableFull> {
if let Some(slot_id) = self.resume_existing_slot(did, quantum) {
return Ok(slot_id);
}
let floor_use = self.floor_use_at(quantum);
let cleanest = self.cleanest_free_slot(&floor_use, quantum);
if let Some(slot_id) = self.roster_slot_of(did).filter(|slot_id| {
self.slots.get(slot_id).is_none_or(SlotLedger::is_free)
&& self.is_cleanest_free_roster_slot(*slot_id, cleanest, &floor_use, quantum)
}) {
return Ok(slot_id);
}
if let Some(slot_id) = self.acquire_roster_slot(did, cleanest, &floor_use) {
return Ok(slot_id);
}
cleanest.ok_or(OnionLinkTableFull)
}
fn is_cleanest_free_roster_slot(
&self,
assigned: OnionSlotId,
cleanest: Option<OnionSlotId>,
floor_use: &SlotFloorUse,
quantum: u128,
) -> bool {
let assigned_rank = self.slot_rank(assigned.index(), floor_use, quantum);
cleanest.is_none_or(|cleanest| {
let cleanest_rank = self.slot_rank(cleanest.index(), floor_use, quantum);
(assigned_rank.0, assigned_rank.1, assigned_rank.2)
<= (cleanest_rank.0, cleanest_rank.1, cleanest_rank.2)
})
}
pub(crate) fn floor_use_at(&self, quantum: u128) -> SlotFloorUse {
let floor = usize::try_from(self.floor_units).unwrap_or(1).max(1);
SlotFloorUse::from_slots(self.slots.iter().filter_map(|(&slot_id, slot)| {
let slot_u16 = u16::try_from(slot_id.index()).ok()?;
let load = usize::try_from(slot.ledger.load(quantum)).unwrap_or(usize::MAX);
(load > 0).then(|| (slot_u16, FloorUse::of(load, floor)))
}))
}
fn slot_rank(
&self,
index: usize,
floor_use: &SlotFloorUse,
quantum: u128,
) -> (FloorUse, bool, u32, usize) {
let use_at =
u16::try_from(index).map_or(FloorUse::CLEAN, |slot_u16| floor_use.of(slot_u16));
let (has_retained, load) = self
.slots
.get(&OnionSlotId::new(index))
.map_or((false, 0), |slot| {
(!slot.retained.is_empty(), slot.ledger.load(quantum))
});
(use_at, has_retained, load, index)
}
fn cleanest_free_slot(&self, floor_use: &SlotFloorUse, quantum: u128) -> Option<OnionSlotId> {
(0..self.slot_capacity)
.filter(|&index| {
self.slots
.get(&OnionSlotId::new(index))
.is_none_or(SlotLedger::is_free)
})
.min_by_key(|&index| self.slot_rank(index, floor_use, quantum))
.map(OnionSlotId::new)
}
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 {
let drained_dids = self
.slots
.iter_mut()
.flat_map(|(&slot_id, slot)| {
slot.take_drained_retained(quantum)
.into_iter()
.map(move |did| (slot_id, did))
})
.collect::<Vec<_>>();
for (slot_id, did) in drained_dids {
if self.peer_slots.get(&did) == Some(&slot_id) {
self.peer_slots.remove(&did);
}
}
self.slots.retain(|_, slot| !slot.is_releasable_at(quantum));
self.pool_load = self
.slots
.values()
.map(|slot| slot.ledger.load(quantum).saturating_sub(self.floor_units))
.fold(0_u32, u32::saturating_add);
self.swept_quantum = quantum;
self.slot_roster
.set_extra_floor_use(self.floor_use_at(quantum));
}
quantum
}
}