use std::collections::BTreeMap;
use std::net::IpAddr;
pub const MAX_PINHOLES_PER_SESSION: usize = 256;
pub const MAX_PINHOLE_TTL_MS: u64 = 300_000;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct OnionUdpPinholeTable {
max_entries: usize,
entries: BTreeMap<IpAddr, u128>,
}
impl Default for OnionUdpPinholeTable {
fn default() -> Self {
Self::new()
}
}
impl OnionUdpPinholeTable {
pub const fn new() -> Self {
Self::with_capacity_limit(MAX_PINHOLES_PER_SESSION)
}
pub const fn with_capacity_limit(max_entries: usize) -> Self {
Self {
max_entries,
entries: BTreeMap::new(),
}
}
pub fn allow_ip(&mut self, peer_ip: IpAddr, ttl_ms: u64, now_ms: u128) -> bool {
self.prune_expired(now_ms);
let clamped_ttl_ms = u128::from(ttl_ms.min(MAX_PINHOLE_TTL_MS));
if clamped_ttl_ms == 0 || self.max_entries == 0 {
return false;
}
let expires_at_ms = now_ms.saturating_add(clamped_ttl_ms);
if let Some(existing) = self.entries.get_mut(&peer_ip) {
*existing = expires_at_ms;
return true;
}
if self.entries.len() >= self.max_entries {
return false;
}
self.entries.insert(peer_ip, expires_at_ms);
true
}
pub fn allows(&self, peer_ip: IpAddr, now_ms: u128) -> bool {
self.entries
.get(&peer_ip)
.is_some_and(|&expires_at_ms| expires_at_ms > now_ms)
}
pub fn prune_expired(&mut self, now_ms: u128) {
self.entries
.retain(|_, expires_at_ms| *expires_at_ms > now_ms);
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}