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