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