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