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