Skip to main content

ant_node/replication/
commitment_state.rs

1//! Responder-side commitment builder + rotation state.
2//!
3//! Phase 2b of the v12 storage-bound audit design. Builds, signs, and
4//! caches a [`StorageCommitment`] over the responder's currently-stored
5//! key set; serves audit lookups by `expected_commitment_hash`; retains
6//! recently-gossiped commitments for a bounded TTL window (with a slot
7//! backstop) so an audit pinned to a still-answerable commitment does not
8//! false-fail across rotations.
9//!
10//! Rotation strategy:
11//!
12//! - `rotate(new_built)` atomically replaces `current` with `new_built`
13//!   and demotes the prior `current` to `previous`. The prior
14//!   `previous` is dropped.
15//! - `lookup(hash)` reads the in-memory map and returns an [`Arc`] to
16//!   the matching `BuiltCommitment`, keeping it alive for the audit
17//!   response regardless of subsequent rotation (mirrors the `ArcSwap`
18//!   semantics specified in v6 §2: an in-flight reader holding its
19//!   `Arc` is unaffected by a concurrent rotate).
20//!
21//! Retention is persisted across restart (ADR-0004 A1): [`ResponderCommitmentState::snapshot`]
22//! captures the signed commitments + their key sets + gossip stamps, and
23//! [`ResponderCommitmentState::restore`] reloads them and rebuilds each tree from
24//! its persisted key set — so an honest restarted node can answer every pin that
25//! is still inside its answerability window, and an unanswerable pin is provable
26//! misbehaviour rather than an honest crash-restart. Trees are otherwise rebuilt
27//! from `LmdbStorage` at the next rotation tick. Memory cost is bounded by
28//! `2 × (key_count × ~64 bytes + signature_size)` — for 10k keys, ~1.3 MB.
29
30use std::sync::Arc;
31use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
32
33use parking_lot::RwLock;
34use saorsa_pqc::api::sig::MlDsaSecretKey;
35use serde::{Deserialize, Serialize};
36
37use crate::ant_protocol::XorName;
38use crate::replication::commitment::{
39    commitment_hash, sign_commitment, verify_commitment_signature, CommitmentError, MerkleTree,
40    StorageCommitment,
41};
42
43/// Auditor-side per-peer commitment state.
44///
45/// Holds two things that together implement v10/v12 §2 step 5 and §6:
46///   - `last_commitment`: the most recently received, verified, signed
47///     commitment from this peer. `None` if we've evicted it (TTL,
48///     sybil cap, peer-removed) or never received one.
49///   - `commitment_capable`: a **sticky** boolean that flips to `true`
50///     on the first successful gossip ingest and NEVER reverts. Used
51///     by holder-eligibility (§6) and bootstrap-claim shield: a peer
52///     that has at least once proven it speaks v12 is forever held to
53///     that standard. Without stickiness, a peer could flip the flag
54///     off by silencing its gossip and downgrade to the weaker legacy
55///     audit path.
56#[derive(Debug, Clone)]
57pub struct PeerCommitmentRecord {
58    /// Last verified commitment, or `None` if evicted/expired. PRIVATE so it can
59    /// only be mutated through [`Self::set_commitment`] / [`Self::clear_commitment`],
60    /// which keep `cached_hash` in lockstep (codex#2 — a stray
61    /// `record.last_commitment = …` would otherwise stale the cached hash). Read
62    /// it via [`Self::last_commitment`].
63    last_commitment: Option<StorageCommitment>,
64    /// `commitment_hash(last_commitment)`, cached so the per-cycle verifier
65    /// snapshot doesn't re-serialize + re-hash every peer's ~5 KiB commitment
66    /// each verification round (§13). Kept in sync via [`Self::set_commitment`]
67    /// / [`Self::clear_commitment`]; `None` exactly when `last_commitment` is
68    /// `None`.
69    cached_hash: Option<[u8; 32]>,
70    /// Sticky: true once this peer has gossiped a valid commitment.
71    /// Set on ingest. Never set back to false except by full
72    /// `PeerRemoved` cleanup.
73    pub commitment_capable: bool,
74    /// When `last_commitment` was received. Used for TTL on the
75    /// commitment itself (independent of the `commitment_capable`
76    /// stickiness — losing the commitment via TTL doesn't make us
77    /// forget the peer ever spoke v12).
78    pub received_at: Instant,
79    /// Last time we performed an ML-DSA signature verify for this
80    /// peer's commitment. Used to enforce the §2 step 3 rate limit
81    /// (at most one sig verify per peer per 60s).
82    pub last_sig_verify_at: Instant,
83}
84
85impl PeerCommitmentRecord {
86    /// Construct from a freshly-verified commitment. `commitment_capable`
87    /// is set to `true` here and must remain so for the lifetime of the
88    /// record.
89    #[must_use]
90    pub fn from_verified(commitment: StorageCommitment, now: Instant) -> Self {
91        let cached_hash = commitment_hash(&commitment);
92        Self {
93            last_commitment: Some(commitment),
94            cached_hash,
95            commitment_capable: true,
96            received_at: now,
97            last_sig_verify_at: now,
98        }
99    }
100
101    /// Mark commitment-capable without storing a commitment (used when
102    /// we've TTL-expired the commitment itself but want to remember the
103    /// peer has spoken v12 before).
104    #[must_use]
105    pub fn capable_but_no_commitment(now: Instant) -> Self {
106        Self {
107            last_commitment: None,
108            cached_hash: None,
109            commitment_capable: true,
110            received_at: now,
111            last_sig_verify_at: now,
112        }
113    }
114
115    /// The stored commitment, if any. Read-only view of the private field.
116    #[must_use]
117    pub fn last_commitment(&self) -> Option<&StorageCommitment> {
118        self.last_commitment.as_ref()
119    }
120
121    /// The cached `commitment_hash` of the stored commitment (§13) — `None`
122    /// when no commitment is held. Avoids re-serializing/re-hashing on every
123    /// verifier snapshot.
124    #[must_use]
125    pub fn commitment_hash(&self) -> Option<[u8; 32]> {
126        self.cached_hash
127    }
128
129    /// Replace the stored commitment and refresh the cached hash together, so
130    /// the two never drift.
131    pub fn set_commitment(&mut self, commitment: StorageCommitment, now: Instant) {
132        self.cached_hash = commitment_hash(&commitment);
133        self.last_commitment = Some(commitment);
134        self.received_at = now;
135    }
136
137    /// Drop the stored commitment and its cached hash together.
138    pub fn clear_commitment(&mut self) {
139        self.last_commitment = None;
140        self.cached_hash = None;
141    }
142}
143
144/// A fully-built commitment: signed wire blob, cached hash, Merkle tree
145/// for inclusion proofs, and a sorted leaf-index lookup for the auditor's
146/// `leaf_index` field.
147///
148/// Held inside an [`Arc`] so audit responders can grab a reference and
149/// build a reply without holding the [`ResponderCommitmentState`] read
150/// lock for the duration of the response.
151pub struct BuiltCommitment {
152    /// The signed wire blob.
153    commitment: StorageCommitment,
154    /// `commitment_hash(commitment)` — cached so audit lookups don't
155    /// re-serialize on every match.
156    cached_hash: [u8; 32],
157    /// The Merkle tree behind the commitment. `path_for(key)` produces the
158    /// inclusion proof and `key_index(key)` reconstructs a key's leaf index in
159    /// `O(log n)` — so no separate `sorted_keys` Vec is kept (it duplicated the
160    /// keys already in `tree.leaves`, §14).
161    tree: MerkleTree,
162}
163
164impl BuiltCommitment {
165    /// Build a commitment over `entries = [(key, bytes_hash), ...]` and
166    /// sign it with `secret_key`.
167    ///
168    /// `entries` does not need to be sorted (the inner [`MerkleTree`]
169    /// sorts internally); `sender_peer_id` is bound into the signature
170    /// and the commitment.
171    ///
172    /// # Errors
173    ///
174    /// Returns the wrapped [`CommitmentError`] on empty key sets,
175    /// over-cap key counts, duplicates, or signing failures.
176    pub fn build(
177        entries: Vec<(XorName, [u8; 32])>,
178        sender_peer_id: &[u8; 32],
179        secret_key: &MlDsaSecretKey,
180        sender_public_key: &[u8],
181    ) -> Result<Self, CommitmentError> {
182        let tree = MerkleTree::build(entries)?;
183        Self::build_from_tree(tree, sender_peer_id, secret_key, sender_public_key)
184    }
185
186    /// Sign and wrap an ALREADY-BUILT Merkle tree. Lets callers that already
187    /// built the tree (e.g. the rotation no-op-root check, §11) avoid rebuilding
188    /// it inside [`Self::build`].
189    ///
190    /// # Errors
191    ///
192    /// Propagates signing / serialization failures, identical to [`Self::build`].
193    pub fn build_from_tree(
194        tree: MerkleTree,
195        sender_peer_id: &[u8; 32],
196        secret_key: &MlDsaSecretKey,
197        sender_public_key: &[u8],
198    ) -> Result<Self, CommitmentError> {
199        let root = tree.root();
200        let key_count = tree.key_count();
201        let signature = sign_commitment(
202            secret_key,
203            &root,
204            key_count,
205            sender_peer_id,
206            sender_public_key,
207        )?;
208        let commitment = StorageCommitment {
209            root,
210            key_count,
211            sender_peer_id: *sender_peer_id,
212            sender_public_key: sender_public_key.to_vec(),
213            signature,
214        };
215        // `commitment_hash` only returns None on a postcard serialization
216        // failure, which for our fixed-size commitment cannot occur in
217        // practice (ML-DSA-65 signature is 3293 bytes). If it ever
218        // somehow does, surface as a SignatureFailed so callers don't
219        // need a new error variant for an unreachable case.
220        let cached_hash = commitment_hash(&commitment).ok_or_else(|| {
221            CommitmentError::SignatureFailed("commitment serialization failed".to_string())
222        })?;
223        Ok(Self {
224            commitment,
225            cached_hash,
226            tree,
227        })
228    }
229
230    /// The signed wire blob.
231    #[must_use]
232    pub fn commitment(&self) -> &StorageCommitment {
233        &self.commitment
234    }
235
236    /// The cached commitment hash. Equal to
237    /// [`crate::replication::commitment::commitment_hash`]
238    /// `(self.commitment())`.
239    #[must_use]
240    pub fn hash(&self) -> [u8; 32] {
241        self.cached_hash
242    }
243
244    /// The Merkle tree behind this commitment.
245    ///
246    /// Used by the subtree-audit responder to plan a proof (select the
247    /// nonce-determined branch and read its sibling cut-hashes).
248    #[must_use]
249    pub fn tree(&self) -> &MerkleTree {
250        &self.tree
251    }
252
253    /// Inclusion path + leaf index for `key`, if it is in this
254    /// commitment. Returns `None` if `key` is not committed.
255    #[must_use]
256    pub fn proof_for(&self, key: &XorName) -> Option<(Vec<[u8; 32]>, u32)> {
257        let idx = self.tree.key_index(key)?;
258        let path = self.tree.path_for(key)?;
259        // u32 cast safe because MerkleTree::build rejects > MAX_COMMITMENT_KEY_COUNT.
260        let leaf_index = u32::try_from(idx).unwrap_or(u32::MAX);
261        Some((path, leaf_index))
262    }
263
264    /// Whether `key` is committed in this tree. Allocation-free membership
265    /// check (binary search over the sorted leaf keys) — equivalent to
266    /// `proof_for(key).is_some()` but without building the inclusion path, for
267    /// hot callers (e.g. the pruner's `is_held` veto) that only need the
268    /// boolean.
269    #[must_use]
270    pub fn contains_key(&self, key: &XorName) -> bool {
271        self.tree.contains_key(key)
272    }
273
274    /// The committed leaf keys — the key set persisted so this commitment can be
275    /// rebuilt after a restart without re-reading chunks.
276    #[must_use]
277    pub fn leaf_keys(&self) -> Vec<XorName> {
278        self.tree.leaf_keys()
279    }
280
281    /// Reconstruct a `BuiltCommitment` from a persisted signed commitment and a
282    /// `tree` rebuilt from its leaf keys — WITHOUT re-signing, so the pin
283    /// (`commitment_hash`) is preserved exactly across a restart (ML-DSA
284    /// signatures are randomized, so re-signing would change the pin).
285    ///
286    /// Returns `None` (never trusts the blob) unless the rebuilt tree matches the
287    /// signed `root` and `key_count` AND the embedded-key ML-DSA signature still
288    /// verifies — so a corrupted or forged persisted commitment is rejected.
289    #[must_use]
290    pub fn from_persisted(commitment: StorageCommitment, tree: MerkleTree) -> Option<Self> {
291        if tree.root() != commitment.root || tree.key_count() != commitment.key_count {
292            return None;
293        }
294        if !verify_commitment_signature(&commitment) {
295            return None;
296        }
297        let cached_hash = commitment_hash(&commitment)?;
298        Some(Self {
299            commitment,
300            cached_hash,
301            tree,
302        })
303    }
304}
305
306/// Expected steady-state count of retained recently-gossiped commitments (the
307/// last ~two, plus the current one) — used only as an initial `Vec` capacity
308/// hint. Retention itself is TTL-based (see [`GOSSIP_ANSWERABILITY_TTL`] and
309/// [`prune_slots`]), NOT a hard count: a commitment stays answerable for the
310/// full TTL after its last gossip regardless of how many rotations occur.
311///
312/// (A hard count cap was a flawed proxy — under a restart with a shifted
313/// responsible range, an in-window root could be evicted by count before its
314/// TTL, which after grace removal would be a false conviction.)
315const RETAINED_GOSSIPED_COMMITMENTS: usize = 2;
316
317/// Hard upper bound on retained gossip records — a pure memory backstop against
318/// pathological churn (e.g. an implausibly fast rotation producing many distinct
319/// in-window roots). At the 1 h rotation cadence and 3 h TTL only ~3 distinct
320/// roots are ever in-window, so this is never hit in practice; it exists solely
321/// so `recently_gossiped` cannot grow unbounded.
322const MAX_RETAINED_GOSSIPED_SLOTS: usize = 16;
323
324/// How long a gossiped commitment stays answerable after it was last put on the
325/// wire. Retention (and therefore the pruner's `is_held` deletion veto) is
326/// anchored to gossip emission, not to the rotation timer or to distinct-hash
327/// churn: a commitment record expires this long after its last `mark_gossiped`,
328/// even if the node keeps re-gossiping nothing new (the steady-state no-op
329/// rotation case) or stops being responsible for all its keys.
330///
331/// Sized so it strictly dominates the longest realistic auditor pin lifetime —
332/// well above the neighbor-sync gossip cadence and per-peer cooldown (≤1 h) —
333/// while staying far below the prune hysteresis (days), so once a stale key
334/// stops being gossiped the pruner reclaims it promptly. At
335/// `RETAINED_GOSSIPED_COMMITMENTS = 2` this is `(2 + 1) ×` the 1 h rotation
336/// interval = 3 h.
337pub(crate) const GOSSIP_ANSWERABILITY_TTL: Duration = Duration::from_secs(3 * 3600);
338
339/// Extra answerability margin applied ONLY when reloading retention after a
340/// restart (ADR-0004 A1). A gossip-stamp refresh in the last persist window may
341/// not have been flushed before an unclean restart, so a persisted deadline can
342/// be slightly early. Adding this margin on reload guarantees an honest node
343/// never *under*-retains across a restart (it may over-retain by the margin,
344/// which is harmless — it only makes the responder answer a little longer, and a
345/// data-deleter still fails the round-2 slice challenge). Sized well above the
346/// persist interval + gossip cadence, far below the TTL.
347const RESTART_STAMP_GRACE: Duration = Duration::from_secs(5 * 60);
348
349/// One persisted retention slot (ADR-0004 A1): the signed commitment, its
350/// committed key set (so the tree can be rebuilt without re-reading chunks), and
351/// the wall-clock time its hash was last gossiped (`None` if never gossiped —
352/// then it only survives reload while it is the current slot).
353#[derive(Serialize, Deserialize)]
354struct PersistedSlot {
355    commitment: StorageCommitment,
356    leaf_keys: Vec<XorName>,
357    /// Absolute wall-clock time (unix secs) at which this slot's answerability
358    /// expires. Storing the ABSOLUTE deadline (not the last-gossip time) makes
359    /// downtime count against the TTL: a node down past the deadline reloads the
360    /// slot as already expired. `None` if the slot was never gossiped — then it
361    /// survives reload only while it is the current slot.
362    expires_at_unix: Option<u64>,
363}
364
365/// Persisted-format version. Bump on any layout OR semantic change so an
366/// incompatible on-disk snapshot is rejected (→ empty retention, which self-heals
367/// via re-gossip) rather than silently misinterpreted (e.g. an old field read
368/// under new semantics).
369const RETENTION_FORMAT_VERSION: u32 = 1;
370
371/// The persisted responder retention. Slots are newest-first; `has_current`
372/// says whether `slots[0]` was the live advertised commitment.
373#[derive(Serialize, Deserialize)]
374pub struct PersistedRetention {
375    /// Format version (see [`RETENTION_FORMAT_VERSION`]); a mismatch is rejected.
376    version: u32,
377    slots: Vec<PersistedSlot>,
378    has_current: bool,
379}
380
381impl PersistedRetention {
382    /// Serialize for durable persistence (caller writes it atomically). `None`
383    /// on a serialization error, so the caller can refuse to overwrite the
384    /// durable file rather than truncate it.
385    #[must_use]
386    pub fn to_bytes(&self) -> Option<Vec<u8>> {
387        postcard::to_allocvec(self).ok()
388    }
389
390    /// Decode a persisted snapshot. `None` on a corrupt blob OR a version
391    /// mismatch — the caller then fails open LOCALLY (empty retention; the node
392    /// re-gossips a fresh root), which never grants a remote grace.
393    #[must_use]
394    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
395        let this: Self = postcard::from_bytes(bytes).ok()?;
396        (this.version == RETENTION_FORMAT_VERSION).then_some(this)
397    }
398}
399
400/// Responder retention state (ADR-0002).
401///
402/// Keeps the current (latest-rotated) commitment plus every commitment that was
403/// recently gossiped and is still in-window (its `GOSSIP_ANSWERABILITY_TTL` has
404/// not expired) — retention is TTL-based, not a fixed count. A
405/// built-but-never-gossiped commitment is dropped on the next rotation unless
406/// it gets gossiped. Rotation and gossip are the only paths that mutate this.
407pub struct ResponderCommitmentState {
408    inner: RwLock<Inner>,
409}
410
411/// A commitment hash that was emitted on the wire, with the monotonic instant at
412/// which its answerability EXPIRES (`last_gossiped_at + GOSSIP_ANSWERABILITY_TTL`).
413///
414/// Storing the deadline rather than the last-gossip instant makes reload after a
415/// restart robust: `restore` sets `expires_at = now + remaining` (pure addition),
416/// so an OS reboot — where the monotonic clock resets and uptime can be far less
417/// than the wall-clock age — cannot underflow and wrongly drop a still-in-window
418/// root.
419#[derive(Clone, Copy)]
420struct GossipedAt {
421    hash: [u8; 32],
422    expires_at: Instant,
423}
424
425struct Inner {
426    /// Newest-first. When `has_current` is true, `slots[0]` is the current
427    /// (advertised) commitment; the rest — and, once retired, `slots[0]` too —
428    /// are retained only because their hash is still in `recently_gossiped` and
429    /// not yet expired.
430    slots: Vec<Arc<BuiltCommitment>>,
431    /// Whether `slots[0]` is the live, advertised current commitment. Set by
432    /// `rotate`; cleared by `retire_current` (and when the slot set empties).
433    /// When false, `current()` returns `None` — the node stops advertising and
434    /// re-gossiping the stale root, so it ages out by its gossip TTL — while
435    /// `lookup_by_hash` still answers any in-flight pin until then. This
436    /// decouples ADVERTISE (gossiped as current, refreshes the TTL) from ANSWER
437    /// (still resolvable during the TTL window).
438    has_current: bool,
439    /// Commitments recently emitted on the wire, newest-first, each stamped with
440    /// when it was last gossiped (in steady state the last ~two, but bounded by
441    /// the answerability TTL, not a fixed count). A commitment is retained iff it
442    /// is the live current one or its hash appears here with an unexpired stamp.
443    recently_gossiped: Vec<GossipedAt>,
444}
445
446impl Default for ResponderCommitmentState {
447    fn default() -> Self {
448        Self::new()
449    }
450}
451
452impl ResponderCommitmentState {
453    /// Empty state: no commitments yet. Audits before the first rotation
454    /// see `None` lookups and the auditor falls back to the legacy plain
455    /// digest path.
456    #[must_use]
457    pub fn new() -> Self {
458        Self {
459            inner: RwLock::new(Inner {
460                slots: Vec::with_capacity(RETAINED_GOSSIPED_COMMITMENTS + 1),
461                has_current: false,
462                recently_gossiped: Vec::with_capacity(RETAINED_GOSSIPED_COMMITMENTS),
463            }),
464        }
465    }
466
467    /// Rotate: the freshly-rebuilt commitment becomes `current`. Slots that are
468    /// neither the new current nor among the last gossiped hashes are dropped
469    /// (a built-but-never-gossiped commitment does not linger).
470    pub fn rotate(&self, new_current: BuiltCommitment) {
471        let new_current = Arc::new(new_current);
472        let mut guard = self.inner.write();
473        guard.slots.insert(0, new_current);
474        guard.has_current = true;
475        prune_slots(&mut guard, Instant::now());
476    }
477
478    /// Retire the current commitment WITHOUT clearing retention: stop
479    /// advertising it (so `current()` returns `None`, the gossip-emit sites stop
480    /// re-emitting and re-stamping it, and it can age out by its gossip TTL),
481    /// while keeping it answerable via `lookup_by_hash` for any in-flight pin a
482    /// peer already formed — until that pin's gossip stamp expires.
483    ///
484    /// Called when the node has no key it is still responsible for: it must no
485    /// longer claim to hold that data going forward, but must not strand a peer
486    /// mid-audit on a root it gossiped moments ago. A never-gossiped current is
487    /// simply dropped (nothing to stay answerable for).
488    pub fn retire_current(&self) {
489        let mut guard = self.inner.write();
490        guard.has_current = false;
491        prune_slots(&mut guard, Instant::now());
492    }
493
494    /// Record that `hash` was emitted on the wire (gossiped). Keeps every
495    /// in-window gossiped hash (unexpired `GOSSIP_ANSWERABILITY_TTL`) so the
496    /// matching commitments stay answerable (ADR-0002). Call at every gossip-emit site.
497    ///
498    /// Re-gossiping a hash already present **refreshes** its answerability
499    /// deadline to now and moves it to the front: every time the node actually
500    /// puts a root on the wire — including re-emitting the current root in the
501    /// steady-state no-op-rotation case — its retention legitimately extends.
502    /// Conversely a root that stops being gossiped expires
503    /// `GOSSIP_ANSWERABILITY_TTL` after its last emission, which is what lets
504    /// an out-of-range key age out even when the no-op guard freezes the
505    /// committed key set.
506    pub fn mark_gossiped(&self, hash: [u8; 32]) {
507        let now = Instant::now();
508        let mut guard = self.inner.write();
509        mark_gossiped_locked(&mut guard, hash, now);
510    }
511
512    /// Atomically snapshot the current commitment to advertise AND mark it
513    /// gossiped, under a single lock. Returns the commitment to put on the wire,
514    /// or `None` if there is no live current (never rotated, or retired).
515    ///
516    /// This is the ONLY correct way to gossip the current commitment: doing
517    /// `current()` then a separate `mark_gossiped()` is a TOCTOU — a concurrent
518    /// `retire_current`/`rotate` between the two could drop the slot, so the node
519    /// would emit a root the responder no longer retains (a peer pinning it would
520    /// get "unknown commitment hash" → false failure). Taking the snapshot and
521    /// the stamp in one critical section guarantees anything emitted is
522    /// simultaneously retained for its answerability TTL.
523    #[must_use]
524    pub fn current_for_gossip(&self) -> Option<Arc<BuiltCommitment>> {
525        let now = Instant::now();
526        let mut guard = self.inner.write();
527        if !guard.has_current {
528            return None;
529        }
530        let current = guard.slots.first().map(Arc::clone)?;
531        mark_gossiped_locked(&mut guard, current.cached_hash, now);
532        Some(current)
533    }
534
535    /// Atomically snapshot the current commitment to PIN IN A QUOTE and refresh
536    /// its answerability, under a single lock. Returns the live current
537    /// commitment, or `None` if there is no live current (never rotated, or
538    /// retired) — in which case the caller must quote the baseline with no pin.
539    ///
540    /// ADR-0004 ("quoting is advertising"): issuing a quote that prices against
541    /// the current commitment must extend that commitment's answerability
542    /// exactly as gossiping it does, so a recently-quoted pin stays resolvable
543    /// for its TTL and a peer auditing it cannot false-fail an honest node.
544    /// This deliberately mirrors [`Self::current_for_gossip`]: same atomic
545    /// snapshot-and-stamp, same TOCTOU-free guarantee that anything a quote can
546    /// pin is simultaneously retained. It refreshes the CURRENT commitment only
547    /// — a retired or merely-retained-but-not-current commitment is never
548    /// returned here, so quote traffic can never keep a stale fat commitment
549    /// alive (it can only be answered, via `lookup_by_hash`, until its own
550    /// gossip/quote stamp lapses).
551    #[must_use]
552    pub fn current_for_quote(&self) -> Option<Arc<BuiltCommitment>> {
553        let now = Instant::now();
554        let mut guard = self.inner.write();
555        if !guard.has_current {
556            return None;
557        }
558        let current = guard.slots.first().map(Arc::clone)?;
559        mark_gossiped_locked(&mut guard, current.cached_hash, now);
560        Some(current)
561    }
562
563    /// Expire retention purely by the wall clock, without building, signing, or
564    /// rotating anything. Call once per rotation tick so a gossiped commitment's
565    /// answerability deadline advances even when the rotation no-op guard
566    /// returns early (unchanged committed set) or when the node has no
567    /// responsible keys to commit to. This is the time-driven half of the
568    /// retention contract — without it, a frozen `recently_gossiped` entry would
569    /// keep a stale key `is_held` forever.
570    pub fn age_out(&self) {
571        let mut guard = self.inner.write();
572        prune_slots(&mut guard, Instant::now());
573    }
574
575    /// Look up a commitment by its hash. Returns `Some(arc)` if `hash`
576    /// matches any retained slot. The returned `Arc` keeps the
577    /// [`BuiltCommitment`] alive for as long as the caller holds it,
578    /// even if a concurrent `rotate` ages it out of the retention buffer.
579    #[must_use]
580    pub fn lookup_by_hash(&self, hash: &[u8; 32]) -> Option<Arc<BuiltCommitment>> {
581        let guard = self.inner.read();
582        for c in &guard.slots {
583            if &c.cached_hash == hash {
584                return Some(Arc::clone(c));
585            }
586        }
587        None
588    }
589
590    /// Whether `key` is committed under any retained slot (the current
591    /// commitment plus any still-in-window gossiped ones) — i.e. whether a peer
592    /// could still pin a recently gossiped root and open this key's blocks in a
593    /// round-2 slice challenge.
594    ///
595    /// This is the SAME predicate the round-2 responder uses to decide a key is
596    /// "committed" (`handle_subtree_slice_challenge` calls `built.proof_for(key)`
597    /// on the pinned slot, which is committed iff `contains_key`), folded over
598    /// every retained slot. The pruner consults it before deleting an
599    /// out-of-range key, so "the pruner will not delete it" and "the responder
600    /// still owes an answer for it" are provably the same boolean and cannot
601    /// drift. `slots` holds at most `RETAINED_GOSSIPED_COMMITMENTS` + 1
602    /// commitments, and `contains_key` is an allocation-free binary search, so
603    /// this is a short, allocation-free read.
604    #[must_use]
605    pub fn is_held(&self, key: &XorName) -> bool {
606        self.inner.read().slots.iter().any(|c| c.contains_key(key))
607    }
608
609    /// Snapshot the current commitment to ADVERTISE, if any. Used by the gossip
610    /// piggyback path: emit `state.current()` on the next outbound
611    /// `NeighborSyncRequest`/`Response`. Returns `None` once the current
612    /// commitment has been retired (the node has no responsible keys), so the
613    /// node stops re-gossiping a stale root even though `lookup_by_hash` may
614    /// still answer it during its remaining TTL.
615    #[must_use]
616    pub fn current(&self) -> Option<Arc<BuiltCommitment>> {
617        let guard = self.inner.read();
618        if guard.has_current {
619            guard.slots.first().map(Arc::clone)
620        } else {
621            None
622        }
623    }
624
625    /// Number of commitment slots currently retained (the current commitment
626    /// plus any still-answerable recently-gossiped ones). Used only for the
627    /// v12 `commitment_rotated` event's `retained_slots` field; carries no
628    /// behavioural meaning.
629    #[must_use]
630    pub fn retained_slot_count(&self) -> usize {
631        self.inner.read().slots.len()
632    }
633
634    /// Drop every retained slot. Called when the local store has
635    /// transitioned to empty: keeping the previously-advertised
636    /// commitment alive would invite audit failures (we can no longer
637    /// answer for any of the keys we committed to), and would leave
638    /// remote auditors pinning a hash this node will never satisfy
639    /// again. After clearing, the gossip piggyback path will emit
640    /// `commitment: None` until a fresh rotation occurs.
641    ///
642    /// This is the one sanctioned escape from the "callers MUST NOT
643    /// clear retention by any other mechanism" invariant — empty
644    /// storage means there is nothing to retain.
645    pub fn clear_all(&self) {
646        let mut guard = self.inner.write();
647        guard.slots.clear();
648        guard.has_current = false;
649        guard.recently_gossiped.clear();
650    }
651
652    /// Snapshot retention for durable persistence (ADR-0004 A1): each slot's
653    /// signed commitment + committed key set + wall-clock gossip stamp. Reloading
654    /// this after a restart makes every still-in-window pin answerable again, so
655    /// an unanswerable pin is provable misbehaviour, not an honest crash-restart.
656    #[must_use]
657    pub fn snapshot(&self) -> PersistedRetention {
658        let now_i = Instant::now();
659        let now_s = SystemTime::now();
660        let guard = self.inner.read();
661        let slots = guard
662            .slots
663            .iter()
664            .map(|c| {
665                let expires_at_unix = guard
666                    .recently_gossiped
667                    .iter()
668                    .find(|g| g.hash == c.cached_hash)
669                    .and_then(|g| {
670                        // Persist the ABSOLUTE wall-clock deadline = now + remaining,
671                        // so a restart accounts for downtime. Skip if already expired.
672                        let remaining = g.expires_at.saturating_duration_since(now_i);
673                        if remaining.is_zero() {
674                            return None;
675                        }
676                        now_s
677                            .checked_add(remaining)
678                            .and_then(|w| w.duration_since(UNIX_EPOCH).ok())
679                            .map(|d| d.as_secs())
680                    });
681                PersistedSlot {
682                    commitment: c.commitment().clone(),
683                    leaf_keys: c.leaf_keys(),
684                    expires_at_unix,
685                }
686            })
687            .collect();
688        PersistedRetention {
689            version: RETENTION_FORMAT_VERSION,
690            slots,
691            has_current: guard.has_current,
692        }
693    }
694
695    /// Reload retention from a persisted snapshot at startup (ADR-0004 A1).
696    /// Rebuilds each slot's tree from its persisted (content-addressed) key set,
697    /// verifies it against the signed root, converts wall-clock gossip stamps
698    /// back to the monotonic clock, drops corrupt or already-expired slots, and
699    /// enforces retention. Replaces any existing state.
700    pub fn restore(&self, persisted: &PersistedRetention) {
701        let now_i = Instant::now();
702        let now_s = SystemTime::now();
703        let mut guard = self.inner.write();
704        guard.slots.clear();
705        guard.recently_gossiped.clear();
706        guard.has_current = false;
707        // Track whether the FIRST persisted slot (the pre-restart current)
708        // restored successfully — `has_current` may only be honoured if it did,
709        // else a later slot would be wrongly promoted to current.
710        let mut first_slot_restored = false;
711        for (i, slot) in persisted.slots.iter().enumerate() {
712            let entries: Vec<_> = slot.leaf_keys.iter().map(|k| (*k, *k)).collect();
713            let Ok(tree) = MerkleTree::build(entries) else {
714                continue;
715            };
716            let Some(built) = BuiltCommitment::from_persisted(slot.commitment.clone(), tree) else {
717                continue;
718            };
719            let hash = built.cached_hash;
720            if i == 0 {
721                first_slot_restored = true;
722            }
723            guard.slots.push(Arc::new(built));
724            if let Some(exp_unix) = slot.expires_at_unix {
725                if let Some(expires_at) = wall_expiry_to_instant(exp_unix, now_s, now_i) {
726                    guard
727                        .recently_gossiped
728                        .push(GossipedAt { hash, expires_at });
729                }
730            }
731        }
732        guard.has_current = persisted.has_current && first_slot_restored;
733        prune_slots(&mut guard, now_i);
734    }
735}
736
737/// Convert a persisted ABSOLUTE wall-clock expiry (unix secs) to a monotonic
738/// [`Instant`] deadline, given the current wall-clock/monotonic pair. Returns
739/// `None` if the deadline has already passed (downtime consumed the TTL). Uses
740/// `now_i + remaining` (addition), so it never underflows across an OS reboot
741/// where the monotonic clock has reset; `remaining` is clamped to the TTL so a
742/// forward clock skew cannot over-extend answerability.
743fn wall_expiry_to_instant(expires_unix: u64, now_s: SystemTime, now_i: Instant) -> Option<Instant> {
744    let expires_wall = UNIX_EPOCH.checked_add(Duration::from_secs(expires_unix))?;
745    // Apply RESTART_STAMP_GRACE to the persisted deadline BEFORE deciding expiry:
746    // the persisted deadline can be slightly early (a stamp refresh lost in the
747    // last persist window may have already carried the true deadline past the
748    // persisted one — even past `now`). Treating `persisted + grace` as the
749    // effective deadline means an honest node never under-retains across a
750    // restart. A slot only drops here if it expired MORE than the grace ago
751    // (genuine expiry — downtime still counts, minus the grace margin).
752    let effective_wall = expires_wall.checked_add(RESTART_STAMP_GRACE)?;
753    let remaining = effective_wall.duration_since(now_s).ok()?;
754    if remaining.is_zero() {
755        return None;
756    }
757    // Clamp so a forward wall-clock skew cannot over-extend beyond one TTL + grace.
758    now_i.checked_add(remaining.min(GOSSIP_ANSWERABILITY_TTL + RESTART_STAMP_GRACE))
759}
760
761/// ADR-0004: the responder commitment state is the quote generator's commitment
762/// source. `current_binding_for_quote` snapshots the live current commitment's
763/// `(key_count, pin)` and refreshes its answerability in one atomic step (via
764/// [`ResponderCommitmentState::current_for_quote`]), so a quote that prices
765/// against the current commitment keeps it answerable for its TTL.
766impl crate::payment::quote::CommitmentSource for ResponderCommitmentState {
767    fn current_binding_for_quote(&self) -> Option<crate::payment::quote::QuoteBinding> {
768        self.current_for_quote()
769            .map(|built| crate::payment::quote::QuoteBinding {
770                key_count: built.commitment().key_count,
771                pin: built.hash(),
772            })
773    }
774
775    fn current_binding_snapshot(&self) -> Option<crate::payment::quote::QuoteBinding> {
776        // Read-only sibling of `current_binding_for_quote`: same live current
777        // commitment (via `current()`), but no gossip stamp — the price-floor
778        // consumer reads pricing state without extending answerability.
779        self.current()
780            .map(|built| crate::payment::quote::QuoteBinding {
781                key_count: built.commitment().key_count,
782                pin: built.hash(),
783            })
784    }
785
786    fn commitment_blob_for_pin(&self, pin: [u8; 32]) -> Option<Vec<u8>> {
787        // rmp-encode the `StorageCommitment` itself — the EXACT form the storer's
788        // `index_valid_sidecars` deserializes (`rmp_serde::from_slice::<StorageCommitment>`),
789        // so a sidecar shipped here resolves identically to one fetched via
790        // `GetCommitmentByPin`. Only retained pins resolve; a rotated-out pin
791        // yields `None` and the response simply carries no commitment.
792        let built = self.lookup_by_hash(&pin)?;
793        rmp_serde::to_vec(built.commitment()).ok()
794    }
795}
796
797/// Enforce retention as of `now`: first expire any gossip record older than
798/// `GOSSIP_ANSWERABILITY_TTL`, then keep the live current slot (only while
799/// `has_current`) and any slot whose hash is still among the unexpired
800/// recently-gossiped hashes; drop the rest. Idempotent; preserves newest-first
801/// order. This is the single place retention is enforced.
802///
803/// The current-slot exemption is conditional on `has_current`: once the current
804/// commitment is retired (no responsible keys), `slots[0]` is no longer exempt
805/// and ages out by its own gossip TTL exactly like any other retained slot —
806/// the fix that stops a stale, continuously-re-gossiped current from pinning its
807/// keys forever.
808/// Stamp `hash` as gossiped at `now` (newest-first, de-duplicated, bounded to
809/// `RETAINED_GOSSIPED_COMMITMENTS`) and re-run retention. Shared by
810/// `mark_gossiped` and `current_for_gossip` so the snapshot-and-stamp can be one
811/// critical section.
812fn mark_gossiped_locked(inner: &mut Inner, hash: [u8; 32], now: Instant) {
813    inner.recently_gossiped.retain(|g| g.hash != hash);
814    inner.recently_gossiped.insert(
815        0,
816        GossipedAt {
817            hash,
818            expires_at: now + GOSSIP_ANSWERABILITY_TTL,
819        },
820    );
821    // Retention is TTL-based; truncation is only a memory backstop and must never
822    // drop an unexpired (still-in-window) record, so it caps at a value far above
823    // the number of roots that can be in-window at once.
824    inner
825        .recently_gossiped
826        .truncate(MAX_RETAINED_GOSSIPED_SLOTS);
827    prune_slots(inner, now);
828}
829
830fn prune_slots(inner: &mut Inner, now: Instant) {
831    // 1. TTL-expire gossip records first (the answerability anchor). A record
832    //    whose answerability deadline has passed no longer keeps anything
833    //    answerable, regardless of distinct-hash churn or rotation ticks.
834    inner.recently_gossiped.retain(|g| g.expires_at > now);
835
836    // 2. Keep the live current slot (only while has_current) + any slot still
837    //    covered by an unexpired record. Snapshot the live hashes first to avoid
838    //    borrowing `inner` twice (both collections are at most
839    //    RETAINED_GOSSIPED_COMMITMENTS + 1 long).
840    let live: Vec<[u8; 32]> = inner.recently_gossiped.iter().map(|g| g.hash).collect();
841    let has_current = inner.has_current;
842    let mut idx = 0usize;
843    inner.slots.retain(|c| {
844        let keep = (has_current && idx == 0) || live.contains(&c.cached_hash);
845        idx += 1;
846        keep
847    });
848    // If nothing remains, there is no current slot to advertise.
849    if inner.slots.is_empty() {
850        inner.has_current = false;
851    }
852}
853
854// ---------------------------------------------------------------------------
855// Tests
856// ---------------------------------------------------------------------------
857
858#[cfg(test)]
859#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
860mod tests {
861    use super::*;
862    use crate::replication::commitment::{commitment_hash, leaf_hash, verify_path};
863    use saorsa_pqc::api::sig::ml_dsa_65;
864
865    fn key(byte: u8) -> XorName {
866        let mut k = [0u8; 32];
867        k[0] = byte;
868        k
869    }
870
871    fn bh(byte: u8) -> [u8; 32] {
872        [byte ^ 0x5A; 32]
873    }
874
875    fn keypair() -> (saorsa_pqc::api::sig::MlDsaPublicKey, MlDsaSecretKey) {
876        ml_dsa_65().generate_keypair().unwrap()
877    }
878
879    /// ADR-0004 A1: retention survives a restart. A snapshot → serialize →
880    /// deserialize → restore into a fresh state keeps the exact pre-restart pin
881    /// answerable (signature preserved, not re-signed) and its keys held — so an
882    /// honest restarted node is not falsely convicted once grace is removed.
883    #[test]
884    fn retention_survives_restart_via_snapshot_reload() {
885        let (pk, sk) = keypair();
886        let pk_bytes = pk.to_bytes();
887        // Content-addressed leaves (bytes_hash := key), matching production.
888        let entries: Vec<_> = (1..=5u8).map(|i| (key(i), key(i))).collect();
889        let built = BuiltCommitment::build(entries, &[0xAB; 32], &sk, &pk_bytes).unwrap();
890        let pin = built.hash();
891
892        let state = ResponderCommitmentState::new();
893        state.rotate(built);
894        state.mark_gossiped(pin);
895        assert!(state.lookup_by_hash(&pin).is_some());
896        assert!(state.is_held(&key(3)));
897
898        // "Restart": snapshot -> bytes -> reload into a fresh state.
899        let bytes = state.snapshot().to_bytes().expect("serialize");
900        let reloaded = PersistedRetention::from_bytes(&bytes).expect("deserialize");
901        let fresh = ResponderCommitmentState::new();
902        fresh.restore(&reloaded);
903
904        // The pre-restart pin is still answerable, with the SAME hash, and its
905        // committed keys are still held.
906        let got = fresh.lookup_by_hash(&pin).expect("pin survives restart");
907        assert_eq!(got.hash(), pin, "pin preserved (not re-signed)");
908        assert!(
909            fresh.is_held(&key(3)),
910            "committed key still held after restart"
911        );
912    }
913
914    /// A corrupt snapshot blob decodes to `None`, so the caller fails open with
915    /// empty retention rather than trusting garbage.
916    #[test]
917    fn corrupt_retention_snapshot_is_rejected() {
918        assert!(PersistedRetention::from_bytes(&[0xffu8; 9]).is_none());
919    }
920
921    /// A snapshot from an incompatible format version is rejected (→ empty
922    /// retention), not silently misdecoded.
923    #[test]
924    fn wrong_format_version_is_rejected() {
925        let entries: Vec<_> = (1..=3u8).map(|i| (key(i), key(i))).collect();
926        let (pk, sk) = keypair();
927        let built = BuiltCommitment::build(entries, &[9; 32], &sk, &pk.to_bytes()).unwrap();
928        let bad = PersistedRetention {
929            version: RETENTION_FORMAT_VERSION + 1,
930            slots: vec![PersistedSlot {
931                commitment: built.commitment().clone(),
932                leaf_keys: vec![key(1)],
933                expires_at_unix: None,
934            }],
935            has_current: true,
936        };
937        let bytes = bad.to_bytes().expect("serialize");
938        assert!(PersistedRetention::from_bytes(&bytes).is_none());
939    }
940
941    /// ADR-0004 A1 restart grace: a persisted deadline that is slightly in the
942    /// PAST (within `RESTART_STAMP_GRACE`, e.g. a stamp refresh lost in the last
943    /// persist window before an unclean restart) must still be answerable — an
944    /// honest node never under-retains across restart. A deadline older than the
945    /// grace is genuinely expired and dropped (downtime still counts).
946    #[test]
947    fn restore_grace_retains_slightly_stale_deadline_but_drops_expired() {
948        let (pk, sk) = keypair();
949        let pk_bytes = pk.to_bytes();
950        let entries: Vec<_> = (1..=3u8).map(|i| (key(i), key(i))).collect();
951        let built = BuiltCommitment::build(entries.clone(), &[0xCD; 32], &sk, &pk_bytes).unwrap();
952        let pin = built.hash();
953        let leaf_keys: Vec<_> = entries.iter().map(|(k, _)| *k).collect();
954        let now_unix = SystemTime::now()
955            .duration_since(UNIX_EPOCH)
956            .expect("after epoch")
957            .as_secs();
958
959        let make = |expires_at_unix: Option<u64>| PersistedRetention {
960            version: RETENTION_FORMAT_VERSION,
961            slots: vec![PersistedSlot {
962                commitment: built.commitment().clone(),
963                leaf_keys: leaf_keys.clone(),
964                expires_at_unix,
965            }],
966            has_current: false, // not current -> retention depends on the stamp
967        };
968
969        // 60s past the persisted deadline — within the grace -> still answerable.
970        let within = ResponderCommitmentState::new();
971        within.restore(&make(Some(now_unix.saturating_sub(60))));
972        assert!(
973            within.lookup_by_hash(&pin).is_some(),
974            "a deadline within RESTART_STAMP_GRACE stays answerable across restart"
975        );
976
977        // 30 min past — well beyond the grace -> genuinely expired, dropped.
978        let beyond = ResponderCommitmentState::new();
979        beyond.restore(&make(Some(now_unix.saturating_sub(30 * 60))));
980        assert!(
981            beyond.lookup_by_hash(&pin).is_none(),
982            "a deadline older than the grace is expired and dropped"
983        );
984    }
985
986    #[test]
987    fn built_commitment_hash_matches_global_hash() {
988        let (pk, sk) = keypair();
989        let pk_bytes = pk.to_bytes();
990        let entries: Vec<_> = (1..=5u8).map(|i| (key(i), bh(i))).collect();
991        let built = BuiltCommitment::build(entries, &[0xAB; 32], &sk, &pk_bytes).unwrap();
992        let expected = commitment_hash(built.commitment()).unwrap();
993        assert_eq!(built.hash(), expected);
994    }
995
996    #[test]
997    fn built_commitment_proof_verifies_under_its_own_root() {
998        let (pk, sk) = keypair();
999        let pk_bytes = pk.to_bytes();
1000        let entries: Vec<_> = (1..=8u8).map(|i| (key(i), bh(i))).collect();
1001        let built = BuiltCommitment::build(entries.clone(), &[1; 32], &sk, &pk_bytes).unwrap();
1002        let root = built.commitment().root;
1003        let key_count = built.commitment().key_count;
1004
1005        for (k, _) in &entries {
1006            let (path, leaf_index) = built.proof_for(k).expect("present");
1007            // Find the bytes_hash for this key.
1008            let bh_k = entries.iter().find(|(kk, _)| kk == k).unwrap().1;
1009            let lh = leaf_hash(k, &bh_k);
1010            assert!(
1011                verify_path(&lh, &path, leaf_index as usize, key_count, &root),
1012                "path verify failed for key {k:?}"
1013            );
1014        }
1015    }
1016
1017    #[test]
1018    fn proof_for_absent_key_is_none() {
1019        let (pk, sk) = keypair();
1020        let pk_bytes = pk.to_bytes();
1021        let built = BuiltCommitment::build(
1022            vec![(key(1), bh(1)), (key(2), bh(2))],
1023            &[0; 32],
1024            &sk,
1025            &pk_bytes,
1026        )
1027        .unwrap();
1028        assert!(built.proof_for(&key(99)).is_none());
1029    }
1030
1031    #[test]
1032    fn empty_state_returns_none() {
1033        let state = ResponderCommitmentState::new();
1034        assert!(state.current().is_none());
1035        assert!(state.lookup_by_hash(&[0; 32]).is_none());
1036    }
1037
1038    #[test]
1039    fn clear_all_drops_every_slot() {
1040        // Empty-storage transition: after clear_all, the gossip path
1041        // must observe `current() == None` so it stops piggybacking a
1042        // commitment the node can no longer answer audits against.
1043        let (pk, sk) = keypair();
1044        let pk_bytes = pk.to_bytes();
1045        let state = ResponderCommitmentState::new();
1046        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
1047
1048        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &peer_id, &sk, &pk_bytes).unwrap();
1049        let h1 = c1.hash();
1050        state.rotate(c1);
1051        state.mark_gossiped(h1); // gossiped → retained across the next rotation
1052        let c2 = BuiltCommitment::build(vec![(key(2), bh(2))], &peer_id, &sk, &pk_bytes).unwrap();
1053        let h2 = c2.hash();
1054        state.rotate(c2);
1055        state.mark_gossiped(h2);
1056
1057        assert!(state.current().is_some());
1058        assert!(state.lookup_by_hash(&h1).is_some());
1059
1060        state.clear_all();
1061
1062        assert!(state.current().is_none());
1063        assert!(state.lookup_by_hash(&h1).is_none());
1064    }
1065
1066    #[test]
1067    fn lookup_arc_outlives_subsequent_rotation() {
1068        // INV-R2: an in-flight audit responder that grabbed an Arc must
1069        // be able to finish building the response even after the state
1070        // rotates that commitment out past the retention window.
1071        let (pk, sk) = keypair();
1072        let pk_bytes = pk.to_bytes();
1073        let state = ResponderCommitmentState::new();
1074
1075        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &[0; 32], &sk, &pk_bytes).unwrap();
1076        let h1 = c1.hash();
1077        state.rotate(c1);
1078
1079        let in_flight = state.lookup_by_hash(&h1).unwrap();
1080
1081        // c1 was never gossiped, so the next rotation (a new current) drops it
1082        // from the retention buffer.
1083        let c2 = BuiltCommitment::build(vec![(key(2), bh(2))], &[0; 32], &sk, &pk_bytes).unwrap();
1084        state.rotate(c2);
1085        assert!(state.lookup_by_hash(&h1).is_none());
1086
1087        // But the in-flight Arc still works (INV: Arc keeps it alive).
1088        assert_eq!(in_flight.hash(), h1);
1089        assert!(in_flight.proof_for(&key(1)).is_some());
1090    }
1091
1092    #[test]
1093    fn gossiped_commitment_stays_answerable_across_rotations() {
1094        // ADR-0002: a commitment that was actually gossiped stays answerable
1095        // even after rotation, for its gossip TTL (retention is TTL-based, not a
1096        // fixed count).
1097        let (pk, sk) = keypair();
1098        let pk_bytes = pk.to_bytes();
1099        let state = ResponderCommitmentState::new();
1100
1101        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &[0; 32], &sk, &pk_bytes).unwrap();
1102        let h1 = c1.hash();
1103        state.rotate(c1);
1104        state.mark_gossiped(h1); // we put c1 on the wire
1105
1106        // Rotate to c2 and gossip it. c1's gossip is still in-window (unexpired TTL).
1107        let c2 = BuiltCommitment::build(vec![(key(2), bh(2))], &[0; 32], &sk, &pk_bytes).unwrap();
1108        let h2 = c2.hash();
1109        state.rotate(c2);
1110        state.mark_gossiped(h2);
1111        assert!(
1112            state.lookup_by_hash(&h1).is_some(),
1113            "c1 must stay answerable"
1114        );
1115        assert!(state.lookup_by_hash(&h2).is_some());
1116
1117        // Rotate to c3 and gossip it. Retention is TTL-based, not a fixed count:
1118        // no wall time has elapsed here, so c1 and c2 are still within their
1119        // gossip TTL and MUST remain answerable — a rotation never evicts an
1120        // in-window root (count-based eviction would be a false conviction once
1121        // grace is removed). Aging out BY TTL is covered by the synthetic-clock
1122        // prune_slots tests.
1123        let c3 = BuiltCommitment::build(vec![(key(3), bh(3))], &[0; 32], &sk, &pk_bytes).unwrap();
1124        let h3 = c3.hash();
1125        state.rotate(c3);
1126        state.mark_gossiped(h3);
1127        assert!(
1128            state.lookup_by_hash(&h1).is_some(),
1129            "c1 stays answerable across rotations while within its gossip TTL"
1130        );
1131        assert!(state.lookup_by_hash(&h2).is_some());
1132        assert!(state.lookup_by_hash(&h3).is_some());
1133    }
1134
1135    #[test]
1136    fn current_and_recently_gossiped_roots_stay_answerable_within_ttl() {
1137        // Retention is TTL-based: the current commitment AND every distinct root
1138        // gossiped within the answerability TTL are simultaneously answerable —
1139        // which absorbs the race where an auditor asks about a root published
1140        // just before the newest one, with NO count-based eviction (that was a
1141        // false-conviction bug once grace is removed). No wall time elapses here,
1142        // so all three distinct roots stay live; aging out is time-based and
1143        // covered by the synthetic-clock prune_slots tests.
1144        let (pk, sk) = keypair();
1145        let pk_bytes = pk.to_bytes();
1146        let state = ResponderCommitmentState::new();
1147
1148        // Gossip three distinct commitments in order: c1, c2, c3. All were put
1149        // on the wire within the TTL, so all three stay simultaneously
1150        // answerable (current c3 plus the recently-gossiped c2 and c1).
1151        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &[0; 32], &sk, &pk_bytes).unwrap();
1152        let h1 = c1.hash();
1153        state.rotate(c1);
1154        state.mark_gossiped(h1);
1155
1156        let c2 = BuiltCommitment::build(vec![(key(2), bh(2))], &[0; 32], &sk, &pk_bytes).unwrap();
1157        let h2 = c2.hash();
1158        state.rotate(c2);
1159        state.mark_gossiped(h2);
1160
1161        // At this moment: current = c2, in-window gossiped = {h2, h1}. Both the
1162        // current AND the previously-gossiped c1 must be answerable — the "two,
1163        // not one" race window. c1 is the commitment "published just before the
1164        // newest one" and an auditor may still pin it.
1165        assert!(
1166            state.lookup_by_hash(&h1).is_some(),
1167            "the commitment published just before the newest one must stay answerable"
1168        );
1169        assert!(
1170            state.lookup_by_hash(&h2).is_some(),
1171            "current must be answerable"
1172        );
1173        assert_ne!(h1, h2, "the two retained commitments must be distinct");
1174
1175        // Now gossip a third distinct commitment c3. All of c1, c2, c3 were
1176        // gossiped within the TTL (no wall time elapsed), so all three remain
1177        // simultaneously answerable — retention is bounded by TTL, not a count.
1178        let c3 = BuiltCommitment::build(vec![(key(3), bh(3))], &[0; 32], &sk, &pk_bytes).unwrap();
1179        let h3 = c3.hash();
1180        state.rotate(c3);
1181        state.mark_gossiped(h3);
1182
1183        assert_ne!(h2, h3);
1184        assert_ne!(h1, h3);
1185        assert!(
1186            state.lookup_by_hash(&h3).is_some(),
1187            "current (c3) answerable"
1188        );
1189        assert!(
1190            state.lookup_by_hash(&h2).is_some(),
1191            "c2 answerable within its TTL"
1192        );
1193        assert!(
1194            state.lookup_by_hash(&h1).is_some(),
1195            "c1 also stays answerable within its TTL — no count-based eviction"
1196        );
1197    }
1198
1199    #[test]
1200    fn is_held_tracks_keys_across_the_retention_window() {
1201        // The pruner's deletion veto relies on `is_held`: a key committed under
1202        // ANY retained slot (current + any root gossiped within the TTL) must
1203        // read held. It stops reading held once its commitment ages out BY TTL —
1204        // a bounded reprieve, not a permanent pin (the time-based age-out is
1205        // covered by the synthetic-clock prune_slots tests). This mirrors the
1206        // round-2 responder's `built.proof_for(key).is_some()` check folded over
1207        // the slots, so "pruner won't delete" == "responder owes an answer".
1208        let (pk, sk) = keypair();
1209        let pk_bytes = pk.to_bytes();
1210        let state = ResponderCommitmentState::new();
1211
1212        // c1 commits to key(1). Gossip it -> key(1) is held (current slot).
1213        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &[0; 32], &sk, &pk_bytes).unwrap();
1214        let h1 = c1.hash();
1215        state.rotate(c1);
1216        state.mark_gossiped(h1);
1217        assert!(
1218            state.is_held(&key(1)),
1219            "freshly committed+gossiped key is held"
1220        );
1221        assert!(!state.is_held(&key(99)), "never-committed key is not held");
1222
1223        // c2 commits to key(2) only (key(1) dropped from the new commitment,
1224        // e.g. it went out of range). key(1) must STILL be held via the retained
1225        // previous gossiped slot (the race-absorbing window), and key(2) too.
1226        let c2 = BuiltCommitment::build(vec![(key(2), bh(2))], &[0; 32], &sk, &pk_bytes).unwrap();
1227        let h2 = c2.hash();
1228        state.rotate(c2);
1229        state.mark_gossiped(h2);
1230        assert!(
1231            state.is_held(&key(1)),
1232            "key dropped from the newest commitment is still held via the previous gossiped slot"
1233        );
1234        assert!(state.is_held(&key(2)), "newly committed key is held");
1235
1236        // c3 commits to key(3). No wall time has elapsed, so c1 and c2 are still
1237        // within their gossip TTL: key(1), key(2), key(3) are all still held (no
1238        // count-based age-out). key(1) is reclaimed only once c1's TTL lapses,
1239        // which the synthetic-clock prune_slots tests cover.
1240        let c3 = BuiltCommitment::build(vec![(key(3), bh(3))], &[0; 32], &sk, &pk_bytes).unwrap();
1241        let h3 = c3.hash();
1242        state.rotate(c3);
1243        state.mark_gossiped(h3);
1244        assert!(
1245            state.is_held(&key(1)),
1246            "key(1) still held within c1's gossip TTL (no count-based eviction)"
1247        );
1248        assert!(state.is_held(&key(2)), "key(2) still held");
1249        assert!(state.is_held(&key(3)), "current key held");
1250    }
1251
1252    /// Build a `BuiltCommitment` over the given keys for use in raw `prune_slots`
1253    /// tests (each key's `bytes_hash` is `bh(k[0])`).
1254    fn built(keys: &[u8]) -> BuiltCommitment {
1255        let (pk, sk) = keypair();
1256        let entries: Vec<_> = keys.iter().map(|&b| (key(b), bh(b))).collect();
1257        BuiltCommitment::build(entries, &[0; 32], &sk, &pk.to_bytes()).unwrap()
1258    }
1259
1260    #[test]
1261    fn stale_gossip_record_expires_by_ttl_even_without_new_distinct_gossip() {
1262        // Frozen-retention-window regression: the no-op-rotation guard can freeze
1263        // `recently_gossiped` (no new distinct hash is ever gossiped once the
1264        // responsible key set stabilizes). The retention window must still age a
1265        // stale gossiped commitment out by the WALL CLOCK, so its key stops
1266        // being `is_held` and the pruner can reclaim it. Driven directly through
1267        // `prune_slots(now)` with a synthetic clock so it is deterministic.
1268        let c_current = Arc::new(built(&[1])); // root over key(1) — current
1269        let c_stale = Arc::new(built(&[2])); // root over key(2) — out-of-range, only retained via gossip
1270        let h_current = c_current.hash();
1271        let h_stale = c_stale.hash();
1272
1273        // Synthetic clock: stamps anchor at `base` and the prune evaluates at a
1274        // FUTURE `now` (adding to an `Instant` never underflows, unlike
1275        // subtracting a TTL from a fresh Windows monotonic clock). The stale
1276        // record was last gossiped just over the TTL before `now`; the current
1277        // record was gossiped at `now`. This is exactly the frozen-window state:
1278        // current keeps being re-gossiped (refreshing its stamp) while the stale
1279        // root is never gossiped again.
1280        let base = Instant::now();
1281        let now = base + GOSSIP_ANSWERABILITY_TTL + Duration::from_secs(1);
1282        let mut inner = Inner {
1283            slots: vec![Arc::clone(&c_current), Arc::clone(&c_stale)],
1284            has_current: true,
1285            recently_gossiped: vec![
1286                GossipedAt {
1287                    hash: h_current,
1288                    expires_at: now + GOSSIP_ANSWERABILITY_TTL,
1289                },
1290                GossipedAt {
1291                    hash: h_stale,
1292                    expires_at: base + GOSSIP_ANSWERABILITY_TTL,
1293                },
1294            ],
1295        };
1296
1297        prune_slots(&mut inner, now);
1298
1299        // The stale record (and its slot) must be gone; the current one stays.
1300        assert!(
1301            inner.recently_gossiped.iter().all(|g| g.hash != h_stale),
1302            "stale gossip record past its TTL must expire"
1303        );
1304        assert_eq!(inner.slots.len(), 1, "the stale slot must be dropped");
1305        assert_eq!(inner.slots[0].hash(), h_current, "current slot retained");
1306        // key(2) — committed only under the now-expired stale slot — is no
1307        // longer held, so the pruner may reclaim it. key(1) stays held.
1308        assert!(
1309            inner.slots.iter().all(|c| c.proof_for(&key(2)).is_none()),
1310            "stale key is no longer held once its commitment ages out"
1311        );
1312        assert!(
1313            inner.slots.iter().any(|c| c.proof_for(&key(1)).is_some()),
1314            "current key still held"
1315        );
1316    }
1317
1318    #[test]
1319    fn recent_gossip_record_stays_answerable_within_ttl() {
1320        // Early-drop regression: a commitment gossiped recently (within the TTL)
1321        // must remain answerable even if it is no longer the current root — a
1322        // peer may still have pinned it. `prune_slots` must NOT drop it early.
1323        let c_current = Arc::new(built(&[1]));
1324        let c_prev = Arc::new(built(&[2]));
1325        let h_current = c_current.hash();
1326        let h_prev = c_prev.hash();
1327
1328        // Synthetic clock (forward-only, see the stale-expiry test above).
1329        let base = Instant::now();
1330        let now = base + GOSSIP_ANSWERABILITY_TTL / 2;
1331        let mut inner = Inner {
1332            slots: vec![Arc::clone(&c_current), Arc::clone(&c_prev)],
1333            has_current: true,
1334            recently_gossiped: vec![
1335                GossipedAt {
1336                    hash: h_current,
1337                    expires_at: now + GOSSIP_ANSWERABILITY_TTL,
1338                },
1339                GossipedAt {
1340                    // Gossiped a while ago, but still comfortably within the TTL.
1341                    hash: h_prev,
1342                    expires_at: base + GOSSIP_ANSWERABILITY_TTL,
1343                },
1344            ],
1345        };
1346
1347        prune_slots(&mut inner, now);
1348
1349        assert_eq!(
1350            inner.slots.len(),
1351            2,
1352            "a commitment gossiped within the TTL must stay answerable (the 'two, not one' race window)"
1353        );
1354        assert!(
1355            inner.slots.iter().any(|c| c.hash() == h_prev),
1356            "the recently-gossiped previous commitment must not be dropped early"
1357        );
1358    }
1359
1360    #[test]
1361    fn retire_current_hides_current_but_keeps_recent_pin_answerable() {
1362        // Retire-current regression: retiring the current commitment (no responsible
1363        // keys) must STOP advertising it (current() -> None, so the gossip loop
1364        // stops re-stamping it) while keeping it answerable for an in-flight pin.
1365        let state = ResponderCommitmentState::new();
1366        let c1 = built(&[1]);
1367        let h1 = c1.hash();
1368        state.rotate(c1);
1369        state.mark_gossiped(h1);
1370
1371        assert!(state.current().is_some(), "fresh current is advertised");
1372
1373        state.retire_current();
1374
1375        assert!(
1376            state.current().is_none(),
1377            "retired current must not be advertised (stops the gossip loop re-stamping it)"
1378        );
1379        assert!(
1380            state.lookup_by_hash(&h1).is_some(),
1381            "retired current stays answerable for an in-flight pin within its TTL"
1382        );
1383        assert!(
1384            state.is_held(&key(1)),
1385            "its keys are still held while answerable, so the pruner still vetoes them"
1386        );
1387    }
1388
1389    #[test]
1390    fn retired_current_ages_out_by_gossip_ttl() {
1391        // The retired current must age out by its gossip TTL — the exact fix for
1392        // the stale-current permanent pin: its record is never refreshed (not
1393        // advertised), so once the TTL lapses prune_slots drops it.
1394        let c1 = Arc::new(built(&[1]));
1395        let h1 = c1.hash();
1396        // Synthetic clock (forward-only, see the stale-expiry test above).
1397        let base = Instant::now();
1398        let now = base + GOSSIP_ANSWERABILITY_TTL + Duration::from_secs(1);
1399        let mut inner = Inner {
1400            slots: vec![Arc::clone(&c1)],
1401            has_current: false, // already retired
1402            recently_gossiped: vec![GossipedAt {
1403                hash: h1,
1404                expires_at: base + GOSSIP_ANSWERABILITY_TTL,
1405            }],
1406        };
1407
1408        prune_slots(&mut inner, now);
1409
1410        assert!(
1411            inner.slots.is_empty(),
1412            "retired current past its TTL is dropped"
1413        );
1414        assert!(!inner.has_current);
1415        assert!(
1416            inner.slots.iter().all(|c| c.proof_for(&key(1)).is_none()),
1417            "its key is no longer held -> pruner reclaims it"
1418        );
1419    }
1420
1421    #[test]
1422    fn retired_current_stays_answerable_within_ttl() {
1423        // A retired current within its TTL must remain answerable (not dropped).
1424        let c1 = Arc::new(built(&[1]));
1425        let h1 = c1.hash();
1426        // Synthetic clock (forward-only, see the stale-expiry test above).
1427        let base = Instant::now();
1428        let now = base + GOSSIP_ANSWERABILITY_TTL / 2;
1429        let mut inner = Inner {
1430            slots: vec![Arc::clone(&c1)],
1431            has_current: false, // retired
1432            recently_gossiped: vec![GossipedAt {
1433                hash: h1,
1434                expires_at: base + GOSSIP_ANSWERABILITY_TTL,
1435            }],
1436        };
1437
1438        prune_slots(&mut inner, now);
1439
1440        assert_eq!(
1441            inner.slots.len(),
1442            1,
1443            "retired-but-recent current stays answerable"
1444        );
1445        assert_eq!(inner.slots[0].hash(), h1);
1446    }
1447
1448    #[test]
1449    fn re_acquire_after_retire_advertises_fresh_current_without_resurrecting_stale() {
1450        // Re-acquire path: a node retires its current (went out of range), then
1451        // becomes responsible again and rotates a fresh commitment. The fresh
1452        // one must become the advertised current; the retired one must only
1453        // linger as a retained (answerable) slot if still gossiped+unexpired,
1454        // never resurrect as current.
1455        let state = ResponderCommitmentState::new();
1456        let c1 = built(&[1]);
1457        let h1 = c1.hash();
1458        state.rotate(c1);
1459        state.mark_gossiped(h1); // gossiped, so it stays answerable after retire
1460        state.retire_current();
1461        assert!(state.current().is_none());
1462
1463        // Become responsible again: rotate a fresh commitment.
1464        let c2 = built(&[2]);
1465        let h2 = c2.hash();
1466        state.rotate(c2);
1467        state.mark_gossiped(h2);
1468
1469        let cur = state
1470            .current()
1471            .expect("fresh current advertised after re-acquire");
1472        assert_eq!(
1473            cur.hash(),
1474            h2,
1475            "the FRESH commitment is current, not the retired one"
1476        );
1477        assert!(
1478            state.lookup_by_hash(&h1).is_some(),
1479            "the retired-but-recently-gossiped commitment is still answerable as a retained slot"
1480        );
1481        assert!(
1482            state.is_held(&key(1)),
1483            "retired key still held within its TTL"
1484        );
1485        assert!(state.is_held(&key(2)), "fresh current key held");
1486    }
1487
1488    #[test]
1489    fn retire_current_drops_ungossiped_current() {
1490        // A current that was never gossiped has nothing to stay answerable for,
1491        // so retiring it drops it outright (no lookup, no current).
1492        let state = ResponderCommitmentState::new();
1493        let c1 = built(&[1]);
1494        let h1 = c1.hash();
1495        state.rotate(c1); // built but NOT gossiped
1496
1497        state.retire_current();
1498
1499        assert!(state.current().is_none(), "no current after retire");
1500        assert!(
1501            state.lookup_by_hash(&h1).is_none(),
1502            "an ungossiped retired current is not answerable (nothing to retain)"
1503        );
1504        assert!(!state.is_held(&key(1)));
1505    }
1506
1507    #[test]
1508    fn ungossiped_rebuild_does_not_evict_gossiped_commitment() {
1509        // The rebuild-faster-than-gossip case: a node rebuilds (rotates) several
1510        // times without gossiping. The last *gossiped* commitment must remain
1511        // answerable so the node is not wrongly failed for "unknown hash".
1512        let (pk, sk) = keypair();
1513        let pk_bytes = pk.to_bytes();
1514        let state = ResponderCommitmentState::new();
1515
1516        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &[0; 32], &sk, &pk_bytes).unwrap();
1517        let h1 = c1.hash();
1518        state.rotate(c1);
1519        state.mark_gossiped(h1);
1520
1521        // Several ungossiped rebuilds.
1522        for i in 2..=6u8 {
1523            let c =
1524                BuiltCommitment::build(vec![(key(i), bh(i))], &[0; 32], &sk, &pk_bytes).unwrap();
1525            state.rotate(c);
1526        }
1527        // h1 was gossiped and is still in-window (unexpired TTL)
1528        // (nothing else was gossiped), so it must still be answerable.
1529        assert!(
1530            state.lookup_by_hash(&h1).is_some(),
1531            "gossiped commitment must survive ungossiped rebuilds"
1532        );
1533    }
1534
1535    // === ADR-0004: current_for_quote (quote-issuance answerability) ===
1536
1537    use crate::payment::quote::CommitmentSource;
1538
1539    #[test]
1540    fn current_for_quote_returns_current_binding_and_is_current_only() {
1541        let (pk, sk) = keypair();
1542        let pk_bytes = pk.to_bytes();
1543        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
1544        let state = ResponderCommitmentState::new();
1545
1546        // No current yet -> baseline (None).
1547        assert!(state.current_binding_for_quote().is_none());
1548
1549        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &peer_id, &sk, &pk_bytes).unwrap();
1550        let h1 = c1.hash();
1551        state.rotate(c1);
1552        state.mark_gossiped(h1);
1553        let c2 = BuiltCommitment::build(
1554            vec![(key(2), bh(2)), (key(3), bh(3))],
1555            &peer_id,
1556            &sk,
1557            &pk_bytes,
1558        )
1559        .unwrap();
1560        let h2 = c2.hash();
1561        state.rotate(c2);
1562
1563        // current_for_quote returns the CURRENT (c2) binding, never the
1564        // previous (c1) — a quote may pin only the live current commitment.
1565        let binding = state
1566            .current_binding_for_quote()
1567            .expect("current binding present");
1568        assert_eq!(
1569            binding.pin, h2,
1570            "must bind the current commitment, not previous"
1571        );
1572        assert_eq!(binding.key_count, 2, "current commitment's key count");
1573        assert_ne!(
1574            binding.pin, h1,
1575            "must never pin the retired/previous commitment"
1576        );
1577    }
1578
1579    #[test]
1580    fn current_for_quote_refreshes_answerability() {
1581        // Issuing a quote must refresh the current commitment's answerability,
1582        // exactly like gossiping it (ADR-0004 "quoting is advertising").
1583        let (pk, sk) = keypair();
1584        let pk_bytes = pk.to_bytes();
1585        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
1586        let state = ResponderCommitmentState::new();
1587
1588        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &peer_id, &sk, &pk_bytes).unwrap();
1589        let h1 = c1.hash();
1590        state.rotate(c1);
1591        // NOT gossiped; instead "quote" it. The quote-issuance refresh must make
1592        // it answerable just as a gossip emission would.
1593        let binding = state.current_binding_for_quote().expect("binding");
1594        assert_eq!(binding.pin, h1);
1595        assert!(
1596            state.lookup_by_hash(&h1).is_some(),
1597            "a quoted current pin must be answerable (issuance refreshed retention)"
1598        );
1599    }
1600
1601    #[test]
1602    fn retired_current_cannot_be_quoted() {
1603        // After retire_current (node has no responsible keys), there is no live
1604        // current commitment, so current_for_quote yields baseline — a retired
1605        // commitment can never be newly quoted.
1606        let (pk, sk) = keypair();
1607        let pk_bytes = pk.to_bytes();
1608        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
1609        let state = ResponderCommitmentState::new();
1610
1611        let c1 = BuiltCommitment::build(vec![(key(1), bh(1))], &peer_id, &sk, &pk_bytes).unwrap();
1612        let h1 = c1.hash();
1613        state.rotate(c1);
1614        state.mark_gossiped(h1);
1615        state.retire_current();
1616
1617        assert!(
1618            state.current_binding_for_quote().is_none(),
1619            "a retired current commitment must not be quotable"
1620        );
1621        // ...but it stays answerable for any in-flight pin until its TTL lapses.
1622        assert!(state.lookup_by_hash(&h1).is_some());
1623    }
1624}