uftp 0.3.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! Duplicate and replay detection for opened messages `[UFTP §3.5]`.

use std::collections::{BTreeSet, HashMap};

use jiff::{SignedDuration, Timestamp};

use crate::envelope::Opened;
use crate::error::{RejectKind, Rejection};
use crate::reason::RejectionReason;
use crate::types::{InternetDomain, MessageUuid};

/// Remembers the messages accepted within a time window and refuses replays.
///
/// For each verified sender domain it keeps the MessageIDs seen together with their
/// signature. Ed25519 is deterministic, so the same signed bytes always carry the same
/// signature (research R5):
/// - the same MessageID with the same signature is `Already Submitted`
/// - the same MessageID with another signature is `Duplicate Identifier`
/// - a TimeStamp further than the window from `now` is refused and not remembered
///
/// Memory is bounded per sender. A sender that fills its quota is refused with 429
/// (temporary) and never evicts another sender's entries.
///
/// ```
/// # use uftp::*;
/// # use uftp::jiff::{SignedDuration, Timestamp};
/// # fn demo(opened: &Opened, now: Timestamp) -> Result<(), Rejection> {
/// let mut guard = ReplayGuard::new(SignedDuration::from_mins(15));
/// if let Err(e) = guard.check(opened, now) {
///     // e.response(id, now) is the Rejected response to send back, if any.
///     return Err(e);
/// }
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct ReplayGuard {
    window: SignedDuration,
    per_sender: usize,
    senders: HashMap<InternetDomain, Seen>,
}

#[derive(Debug, Clone, Default)]
struct Seen {
    signatures: HashMap<MessageUuid, [u8; 64]>,
    /// The same entries ordered by TimeStamp, so the oldest leaves first.
    order: BTreeSet<(Timestamp, MessageUuid)>,
}

impl ReplayGuard {
    /// The default number of entries remembered per sender.
    pub const DEFAULT_PER_SENDER: usize = 100_000;

    /// A guard that accepts TimeStamps within `window` of `now`, in either direction, and
    /// remembers ids for as long.
    #[must_use]
    pub fn new(window: SignedDuration) -> Self {
        Self {
            window: window.abs(),
            per_sender: Self::DEFAULT_PER_SENDER,
            senders: HashMap::new(),
        }
    }

    /// Sets how many entries are remembered per wrapper sender domain (at least 1).
    #[must_use]
    pub fn with_capacity(mut self, per_sender: usize) -> Self {
        self.per_sender = per_sender.max(1);
        self
    }

    /// How many entries are remembered in total.
    #[must_use]
    pub fn len(&self) -> usize {
        self.senders.values().map(|s| s.signatures.len()).sum()
    }

    /// Whether nothing is remembered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.senders.is_empty()
    }

    /// Checks `opened` and remembers it if it is new and fresh.
    ///
    /// # Errors
    /// - [`RejectKind::Rule`] with `Already Submitted`, `Duplicate Identifier`, or a
    ///   stale TimeStamp; [`Rejection::response`] answers it.
    /// - [`RejectKind::RateLimited`] (429) when this sender's quota is full.
    pub fn check(&mut self, opened: &Opened, now: Timestamp) -> Result<(), Rejection> {
        if !opened.is_fresh(now, self.window) {
            return Err(opened.reject(Rejection::because(
                RejectionReason::Other("TimeStamp outside the accepted window".into()),
                format!(
                    "The message is stamped {}; this endpoint accepts messages stamped within {:#} of {now}.",
                    opened.timestamp(),
                    self.window
                ),
            )));
        }
        self.evict(now);
        let seen = self
            .senders
            .entry(opened.sender_domain().clone())
            .or_default();
        let id = opened.message_id();
        if let Some(previous) = seen.signatures.get(&id) {
            let (reason, sentence) = if previous == opened.signature() {
                (
                    RejectionReason::AlreadySubmitted,
                    format!("Message {id} was already received; this copy is identical."),
                )
            } else {
                (
                    RejectionReason::DuplicateIdentifier,
                    format!("Message {id} was already received with other content."),
                )
            };
            return Err(opened.reject(Rejection::because(reason, sentence)));
        }
        if seen.signatures.len() >= self.per_sender {
            let oldest = seen.order.first().map_or(now, |&(t, _)| t);
            let retry_after = oldest
                .checked_add(self.window)
                .map_or(self.window, |free| free.duration_since(now));
            return Err(Rejection::new(
                RejectKind::RateLimited,
                "[UFTP App. 4 §4] 429 Too Many Requests",
                format!(
                    "{} has reached this endpoint's limit of {} remembered {}; retry when older ones leave the {:#} window.",
                    opened.sender_domain(),
                    self.per_sender,
                    if self.per_sender == 1 {
                        "message"
                    } else {
                        "messages"
                    },
                    self.window
                ),
            ).with_retry_after(retry_after));
        }
        seen.signatures.insert(id, *opened.signature());
        seen.order.insert((opened.timestamp(), id));
        Ok(())
    }

    /// Drops entries whose own TimeStamp left the window, whatever order they arrived in:
    /// a replay of them is refused as stale anyway.
    fn evict(&mut self, now: Timestamp) {
        let window = self.window;
        self.senders.retain(|_, seen| {
            while let Some(&(t, id)) = seen.order.first() {
                if now.duration_since(t) <= window {
                    break;
                }
                seen.order.pop_first();
                seen.signatures.remove(&id);
            }
            !seen.signatures.is_empty()
        });
    }
}