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