use std::collections::BTreeMap;
use arrayref::mut_array_refs;
use rings_core::ecc::keccak256;
use zeroize::Zeroize;
use super::OnionExpiry;
use super::ONION_ADMISSION_SENDER_UNITS;
use crate::onion::circuit::OnionReplayNonce;
pub(super) const REPLAY_BLOCK_TAGS: u32 = ONION_ADMISSION_SENDER_UNITS;
pub(super) const REPLAY_BLOCK_HASHES: usize = 26;
pub(super) const REPLAY_SLICE_WORDS: usize = 370;
pub(super) const REPLAY_SLICE_BITS: u32 = 23_680;
const REPLAY_PROBE_DIGESTS: usize = 4;
const _: () = assert!(
REPLAY_SLICE_BITS as usize == 64 * REPLAY_SLICE_WORDS
&& REPLAY_SLICE_BITS <= 1 << 16
&& 4 * REPLAY_BLOCK_HASHES <= 32 * REPLAY_PROBE_DIGESTS
);
pub(crate) struct OnionReplayFilterKey([u8; 32]);
impl OnionReplayFilterKey {
pub(crate) const fn new(bytes: [u8; 32]) -> Self {
Self(bytes)
}
}
impl Drop for OnionReplayFilterKey {
fn drop(&mut self) {
self.0.zeroize();
}
}
pub(super) struct ReplayProbe {
addresses: [u16; REPLAY_BLOCK_HASHES],
}
impl ReplayProbe {
fn of(key: &OnionReplayFilterKey, tag: OnionReplayNonce) -> Self {
let OnionReplayFilterKey(key_bytes) = key;
let OnionReplayNonce(tag_bytes) = tag;
let mut preimage = [0_u8; 49];
let mut stream = [0_u8; 32 * REPLAY_PROBE_DIGESTS];
stream
.as_chunks_mut::<32>()
.0
.iter_mut()
.zip(0_u8..)
.for_each(|(digest, counter)| {
let (key_part, tag_part, counter_part) = mut_array_refs!(&mut preimage, 32, 16, 1);
key_part.copy_from_slice(key_bytes.as_slice());
tag_part.copy_from_slice(tag_bytes.as_slice());
*counter_part = [counter];
*digest = keccak256(preimage.as_slice());
});
preimage.zeroize();
let mut addresses = [0_u16; REPLAY_BLOCK_HASHES];
addresses
.iter_mut()
.zip(stream.as_chunks::<4>().0)
.for_each(|(address, word)| {
*address = (u32::from_le_bytes(word.to_owned()) % REPLAY_SLICE_BITS) as u16;
});
stream.zeroize();
Self { addresses }
}
}
fn word_and_mask(address: u16) -> (usize, u64) {
(usize::from(address / 64), 1_u64 << (address % 64))
}
type ReplaySlice = [u64; REPLAY_SLICE_WORDS];
#[derive(Debug)]
pub(super) struct ReplayBlock {
bits: Box<[ReplaySlice; REPLAY_BLOCK_HASHES]>,
tags: u32,
}
impl ReplayBlock {
fn empty() -> Self {
Self {
bits: Box::new([[0; REPLAY_SLICE_WORDS]; REPLAY_BLOCK_HASHES]),
tags: 0,
}
}
fn is_full(&self) -> bool {
self.tags >= REPLAY_BLOCK_TAGS
}
fn contains(&self, probe: &ReplayProbe) -> bool {
self.bits
.iter()
.zip(probe.addresses)
.all(|(slice, address)| {
let (word, mask) = word_and_mask(address);
slice.get(word).is_none_or(|bits| bits & mask == mask)
})
}
fn insert(&mut self, probe: &ReplayProbe) {
self.bits
.iter_mut()
.zip(probe.addresses)
.for_each(|(slice, address)| {
let (word, mask) = word_and_mask(address);
if let Some(bits) = slice.get_mut(word) {
*bits |= mask;
}
});
self.tags = self.tags.saturating_add(1);
}
#[cfg(all(test, rings_native))]
pub(super) fn false_positive_rate(&self) -> f64 {
self.bits
.iter()
.map(|slice| {
let ones = slice.iter().map(|word| word.count_ones()).sum::<u32>();
f64::from(ones) / f64::from(REPLAY_SLICE_BITS)
})
.product()
}
}
#[derive(Debug)]
pub(super) struct ReplayFilter {
sealed: Vec<ReplayBlock>,
open: ReplayBlock,
}
impl ReplayFilter {
fn singleton(probe: &ReplayProbe) -> Self {
let mut open = ReplayBlock::empty();
open.insert(probe);
Self {
sealed: Vec::new(),
open,
}
}
fn contains(&self, probe: &ReplayProbe) -> bool {
self.open.contains(probe) || self.sealed.iter().any(|block| block.contains(probe))
}
fn insert(&mut self, probe: &ReplayProbe) {
if self.open.is_full() {
self.sealed
.push(std::mem::replace(&mut self.open, ReplayBlock::empty()));
}
self.open.insert(probe);
}
#[cfg(all(test, rings_native))]
pub(super) fn blocks(&self) -> impl Iterator<Item = &ReplayBlock> {
self.sealed.iter().chain([&self.open])
}
}
pub(super) struct ReplayStore {
key: OnionReplayFilterKey,
filters: BTreeMap<OnionExpiry, ReplayFilter>,
}
impl ReplayStore {
pub(super) fn new(key: OnionReplayFilterKey) -> Self {
Self {
key,
filters: BTreeMap::new(),
}
}
pub(super) fn probe(&self, tag: OnionReplayNonce) -> ReplayProbe {
ReplayProbe::of(&self.key, tag)
}
pub(super) fn forget_through(&mut self, now_ms: u128) {
self.filters
.retain(|expiry, _| !expiry.has_passed_at(now_ms));
}
pub(super) fn contains(&self, expiry: OnionExpiry, probe: &ReplayProbe) -> bool {
self.filters
.get(&expiry)
.is_some_and(|filter| filter.contains(probe))
}
pub(super) fn insert(&mut self, expiry: OnionExpiry, probe: &ReplayProbe) {
self.filters
.entry(expiry)
.and_modify(|filter| filter.insert(probe))
.or_insert_with(|| ReplayFilter::singleton(probe));
}
#[cfg(all(test, rings_native))]
pub(super) fn filters(&self) -> &BTreeMap<OnionExpiry, ReplayFilter> {
&self.filters
}
}