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