use std::collections::HashMap;
use std::sync::Mutex;
use crate::error::RpError;
pub const DEFAULT_NONCE_TTL_SECS: u64 = 600;
pub const DEFAULT_MAX_LIVE_NONCES: usize = 100_000;
pub trait NonceStore: Send + Sync {
fn issue(&self, now_unix_secs: u64) -> Result<String, RpError>;
fn consume(&self, nonce: &str, now_unix_secs: u64) -> Result<bool, RpError>;
}
pub struct InMemoryNonceStore {
ttl_secs: u64,
max_live: usize,
live: Mutex<HashMap<String, u64>>,
}
impl Default for InMemoryNonceStore {
fn default() -> Self {
Self::new()
}
}
impl InMemoryNonceStore {
pub fn new() -> Self {
Self::with_limits(DEFAULT_NONCE_TTL_SECS, DEFAULT_MAX_LIVE_NONCES)
}
pub fn with_limits(ttl_secs: u64, max_live: usize) -> Self {
Self {
ttl_secs,
max_live,
live: Mutex::new(HashMap::new()),
}
}
}
impl NonceStore for InMemoryNonceStore {
fn issue(&self, now_unix_secs: u64) -> Result<String, RpError> {
let mut live = self.live.lock().expect("nonce mutex poisoned");
if live.len() >= self.max_live {
let ttl = self.ttl_secs;
live.retain(|_, issued_at| now_unix_secs < issued_at.saturating_add(ttl));
if live.len() >= self.max_live {
return Err(RpError::NonceCapacity {
max_live: self.max_live,
});
}
}
let nonce = fresh_nonce()?;
live.insert(nonce.clone(), now_unix_secs);
Ok(nonce)
}
fn consume(&self, nonce: &str, now_unix_secs: u64) -> Result<bool, RpError> {
let mut live = self.live.lock().expect("nonce mutex poisoned");
match live.remove(nonce) {
Some(issued_at) => Ok(now_unix_secs < issued_at.saturating_add(self.ttl_secs)),
None => Ok(false),
}
}
}
pub(crate) fn fresh_nonce() -> Result<String, RpError> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes)
.map_err(|e| RpError::Store(format!("OS RNG unavailable for nonce issuance: {e}")))?;
Ok(to_hex(&bytes))
}
fn to_hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
let _ = write!(out, "{b:02x}");
}
out
}