Skip to main content

ant_node/replication/
recent_provers.rs

1//! Holder-eligibility cache: which peers recently proved storage of
2//! which key, against which commitment.
3//!
4//! Phase 2d of the v12 storage-bound audit design (`notes/security-
5//! findings-2026-05-22/proposal-gossip-audit-v12.md`).
6//!
7//! When the auditor successfully verifies a commitment-bound audit for
8//! peer P on key K (against P's currently-credited commitment hash H),
9//! it inserts `(P, H, now)` into `recent_provers[K]`. Reward / quorum
10//! eligibility for P-as-holder-of-K then checks that this cache entry
11//! still matches P's *currently credited* commitment hash; if P rotates
12//! the hash via fresh gossip, the cache entry becomes stale and credit
13//! is denied until the next successful audit against the new hash.
14//!
15//! Invariants enforced here:
16//!
17//! - **Per-key cap**: at most [`MAX_PROVERS_PER_KEY`] entries per key,
18//!   LRU-evicted by `proved_at`. Bounds the per-key working set so a
19//!   well-replicated key cannot fill memory.
20//! - **RT-only**: only peers in the caller's routing table populate
21//!   entries — the caller is responsible for filtering before
22//!   [`RecentProvers::record_proof`]; this module just stores what it's
23//!   told.
24//! - **Hash-bound credit**: [`RecentProvers::is_credited_holder`]
25//!   requires the cache entry's `commitment_hash` to match the peer's
26//!   *current* `commitment_hash`. A peer who proves K under C1 then
27//!   rotates to C2 loses credit until re-proving K under C2.
28//!
29//! - **TTL**: entries older than [`PROVER_ENTRY_TTL`] are ignored by
30//!   [`RecentProvers::is_credited_holder`] on read, and
31//!   [`RecentProvers::sweep_expired`] reclaims their memory when a
32//!   caller invokes it (e.g. periodically from the engine).
33//! - **`PeerRemoved` cleanup**: the caller should call
34//!   [`RecentProvers::forget_peer`] when a peer leaves the routing
35//!   table to drop their entries immediately (faster than waiting for
36//!   TTL).
37
38use std::collections::HashMap;
39use std::time::{Duration, Instant};
40
41use saorsa_core::identity::PeerId;
42
43use crate::ant_protocol::XorName;
44
45/// Maximum number of cached provers per key.
46///
47/// Comfortably above `CLOSE_GROUP_SIZE = 7` (a key has at most 7 responsible
48/// holders), leaving slack slots for churn without unbounded growth.
49/// LRU-evicted within the cap.
50pub const MAX_PROVERS_PER_KEY: usize = 16;
51
52/// Maximum age of a cached prover entry before it is considered stale.
53///
54/// A proof older than this is treated as "no credit" by
55/// [`RecentProvers::is_credited_holder`] even if the commitment hash
56/// still matches.
57///
58/// v10/v12 §6 spec: `RECENT_PROOF_TTL = 2 × max audit interval` (≈40 min
59/// at the default 20 min max). Setting too low → peers fall out of
60/// credit between audits. Setting too high → lazy node has more leeway
61/// before re-audit is required. 40 min comfortably covers one audit
62/// cycle on the average peer while still requiring re-proof inside the
63/// rotation window.
64pub const PROVER_ENTRY_TTL: Duration = Duration::from_secs(40 * 60);
65
66/// One cached prover entry: who proved the key, when, and against which
67/// commitment.
68#[derive(Debug, Clone, Copy)]
69pub struct ProverEntry {
70    /// The peer that produced the audit proof.
71    pub peer_id: PeerId,
72    /// When the proof was recorded. Used for LRU eviction.
73    pub proved_at: Instant,
74    /// The peer's commitment hash at proof time. Holder-eligibility
75    /// requires this to match the peer's *currently credited* hash.
76    pub commitment_hash: [u8; 32],
77}
78
79/// Per-key cache of recent provers, capped at [`MAX_PROVERS_PER_KEY`].
80#[derive(Debug, Default, Clone)]
81pub struct RecentProvers {
82    /// `entries[K]` is the per-key bounded list. Entries are kept sorted
83    /// by `proved_at` ascending so eviction is `O(1)` (drop head).
84    entries: HashMap<XorName, Vec<ProverEntry>>,
85}
86
87impl RecentProvers {
88    /// Empty cache.
89    #[must_use]
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    /// Record that `peer_id` proved storage of `key` under commitment
95    /// `commitment_hash` at `proved_at`.
96    ///
97    /// If the same `(peer_id, commitment_hash)` is already cached for
98    /// this key, the entry is updated in place (refreshes `proved_at`).
99    /// Otherwise a new entry is appended, evicting the oldest entry if
100    /// the per-key cap would be exceeded.
101    pub fn record_proof(
102        &mut self,
103        key: XorName,
104        peer_id: PeerId,
105        commitment_hash: [u8; 32],
106        proved_at: Instant,
107    ) {
108        let bucket = self.entries.entry(key).or_default();
109
110        // Refresh-in-place if the (peer, hash) already exists.
111        for e in bucket.iter_mut() {
112            if e.peer_id == peer_id && e.commitment_hash == commitment_hash {
113                e.proved_at = proved_at;
114                bucket.sort_by_key(|e| e.proved_at);
115                return;
116            }
117        }
118
119        // Evict the oldest entry if we're at the cap.
120        if bucket.len() >= MAX_PROVERS_PER_KEY {
121            // bucket is sorted ascending; oldest is index 0.
122            bucket.remove(0);
123        }
124
125        bucket.push(ProverEntry {
126            peer_id,
127            proved_at,
128            commitment_hash,
129        });
130        bucket.sort_by_key(|e| e.proved_at);
131    }
132
133    /// Is `peer_id` currently credited as a holder of `key`?
134    ///
135    /// Returns `true` iff there is a non-stale cached entry with `peer_id`
136    /// and `commitment_hash == current_commitment_hash`.
137    ///
138    /// "Non-stale" means `now - proved_at < PROVER_ENTRY_TTL`. The hash
139    /// binding is the v12 §6 lever: a peer that rotates their commitment
140    /// must re-prove every key they want credit for. The TTL is a
141    /// secondary safety net that revokes credit even if the hash
142    /// happens to match (e.g. a peer who proved long ago but has been
143    /// silent or offline since).
144    #[must_use]
145    pub fn is_credited_holder(
146        &self,
147        key: &XorName,
148        peer_id: &PeerId,
149        current_commitment_hash: &[u8; 32],
150    ) -> bool {
151        let now = Instant::now();
152        self.entries.get(key).is_some_and(|bucket| {
153            bucket.iter().any(|e| {
154                &e.peer_id == peer_id
155                    && &e.commitment_hash == current_commitment_hash
156                    && now.saturating_duration_since(e.proved_at) < PROVER_ENTRY_TTL
157            })
158        })
159    }
160
161    /// Sweep entries older than [`PROVER_ENTRY_TTL`] across all keys.
162    ///
163    /// Returns the number of entries dropped. Intended for periodic
164    /// invocation by a background task; `is_credited_holder` already
165    /// honours the TTL on read, so the sweep only reclaims memory.
166    pub fn sweep_expired(&mut self, now: Instant) -> usize {
167        let mut dropped = 0;
168        for bucket in self.entries.values_mut() {
169            let before = bucket.len();
170            bucket.retain(|e| now.saturating_duration_since(e.proved_at) < PROVER_ENTRY_TTL);
171            dropped += before - bucket.len();
172        }
173        self.entries.retain(|_, b| !b.is_empty());
174        dropped
175    }
176
177    /// Drop every cached entry for `peer_id` across all keys.
178    ///
179    /// Called when a peer leaves the routing table (RT-only invariant)
180    /// or on explicit eviction.
181    pub fn forget_peer(&mut self, peer_id: &PeerId) {
182        for bucket in self.entries.values_mut() {
183            bucket.retain(|e| &e.peer_id != peer_id);
184        }
185        self.entries.retain(|_, b| !b.is_empty());
186    }
187
188    /// Drop every entry whose `commitment_hash` matches `stale_hash`
189    /// (used when the auditor invalidates a peer's `last_commitment` —
190    /// e.g. on `UnknownCommitmentHash` rejection — to remove the cached
191    /// proofs against that no-longer-valid commitment).
192    pub fn forget_commitment(&mut self, stale_hash: &[u8; 32]) {
193        for bucket in self.entries.values_mut() {
194            bucket.retain(|e| &e.commitment_hash != stale_hash);
195        }
196        self.entries.retain(|_, b| !b.is_empty());
197    }
198
199    /// Number of cached entries for `key`. Test/observability helper.
200    #[must_use]
201    pub fn provers_for(&self, key: &XorName) -> usize {
202        self.entries.get(key).map_or(0, Vec::len)
203    }
204
205    /// Total number of cached entries across all keys.
206    #[must_use]
207    pub fn total_entries(&self) -> usize {
208        self.entries.values().map(Vec::len).sum()
209    }
210}
211
212// ---------------------------------------------------------------------------
213// Tests
214// ---------------------------------------------------------------------------
215
216#[cfg(test)]
217#[allow(clippy::unwrap_used, clippy::expect_used)]
218mod tests {
219    use super::*;
220    use std::time::Duration;
221
222    fn peer(byte: u8) -> PeerId {
223        let mut bytes = [0u8; 32];
224        bytes[0] = byte;
225        PeerId::from_bytes(bytes)
226    }
227
228    fn key(byte: u8) -> XorName {
229        let mut k = [0u8; 32];
230        k[0] = byte;
231        k
232    }
233
234    fn hash(byte: u8) -> [u8; 32] {
235        [byte; 32]
236    }
237
238    #[test]
239    fn empty_cache_credits_no_one() {
240        let cache = RecentProvers::new();
241        assert!(!cache.is_credited_holder(&key(1), &peer(1), &hash(1)));
242        assert_eq!(cache.total_entries(), 0);
243    }
244
245    #[test]
246    fn recorded_proof_credits_under_same_hash() {
247        let mut cache = RecentProvers::new();
248        cache.record_proof(key(1), peer(7), hash(0xAB), Instant::now());
249        assert!(cache.is_credited_holder(&key(1), &peer(7), &hash(0xAB)));
250    }
251
252    #[test]
253    fn rotated_hash_loses_credit() {
254        // Core v12 §6 attack-bound property: a peer who proves K under
255        // C1 must re-prove under C2 to keep credit. The cache entry's
256        // hash binding enforces this.
257        let mut cache = RecentProvers::new();
258        cache.record_proof(key(1), peer(7), hash(0xAB), Instant::now());
259        // Same peer, same key, but the auditor's "current" hash for
260        // this peer is now different (peer gossiped a new commitment).
261        assert!(!cache.is_credited_holder(&key(1), &peer(7), &hash(0xCD)));
262    }
263
264    #[test]
265    fn other_peer_under_same_hash_not_credited() {
266        let mut cache = RecentProvers::new();
267        cache.record_proof(key(1), peer(7), hash(0xAB), Instant::now());
268        assert!(!cache.is_credited_holder(&key(1), &peer(8), &hash(0xAB)));
269    }
270
271    #[test]
272    fn per_key_cap_evicts_oldest() {
273        let mut cache = RecentProvers::new();
274        let now = Instant::now();
275        // MAX_PROVERS_PER_KEY is a small usize (16). Narrow to u8 once
276        // so the test loop can hand the peer-id byte directly to
277        // `peer(...)` without per-iteration casts.
278        let max_u8 = u8::try_from(MAX_PROVERS_PER_KEY).unwrap_or(u8::MAX);
279        // Fill the bucket with MAX_PROVERS_PER_KEY + 1 distinct peers.
280        for i in 0..=max_u8 {
281            let t = now + Duration::from_millis(u64::from(i));
282            cache.record_proof(key(1), peer(i), hash(0xAB), t);
283        }
284        assert_eq!(cache.provers_for(&key(1)), MAX_PROVERS_PER_KEY);
285        // The oldest (peer 0) should be evicted; peer MAX should be present.
286        assert!(!cache.is_credited_holder(&key(1), &peer(0), &hash(0xAB)));
287        assert!(cache.is_credited_holder(&key(1), &peer(max_u8), &hash(0xAB)));
288    }
289
290    #[test]
291    fn refresh_in_place_does_not_grow_bucket() {
292        let mut cache = RecentProvers::new();
293        let now = Instant::now();
294        // Same (peer, hash) repeated three times. Bucket should stay at 1.
295        cache.record_proof(key(1), peer(1), hash(0xAB), now);
296        cache.record_proof(key(1), peer(1), hash(0xAB), now + Duration::from_secs(1));
297        cache.record_proof(key(1), peer(1), hash(0xAB), now + Duration::from_secs(2));
298        assert_eq!(cache.provers_for(&key(1)), 1);
299    }
300
301    #[test]
302    fn forget_peer_drops_all_entries() {
303        let mut cache = RecentProvers::new();
304        let now = Instant::now();
305        cache.record_proof(key(1), peer(1), hash(0xAB), now);
306        cache.record_proof(key(2), peer(1), hash(0xAB), now);
307        cache.record_proof(key(1), peer(2), hash(0xAB), now);
308        assert_eq!(cache.total_entries(), 3);
309
310        cache.forget_peer(&peer(1));
311        assert_eq!(cache.total_entries(), 1);
312        assert!(!cache.is_credited_holder(&key(1), &peer(1), &hash(0xAB)));
313        assert!(cache.is_credited_holder(&key(1), &peer(2), &hash(0xAB)));
314    }
315
316    #[test]
317    fn forget_peer_drops_credit_across_all_commitments() {
318        // A confirmed audit failure (e.g. a `ResponsiveBootstrap` on a stale pin
319        // H1) revokes ALL of the peer's holder credit, INCLUDING credit earned
320        // under a newer commitment H2: the contradiction is identity-level, not
321        // scoped to one key set. Another peer's credit is untouched.
322        let mut cache = RecentProvers::new();
323        let now = Instant::now();
324        let h1 = hash(0x11);
325        let h2 = hash(0x22);
326        cache.record_proof(key(1), peer(1), h1, now);
327        cache.record_proof(key(2), peer(1), h2, now);
328        cache.record_proof(key(1), peer(2), h1, now);
329
330        cache.forget_peer(&peer(1));
331
332        assert!(
333            !cache.is_credited_holder(&key(1), &peer(1), &h1),
334            "H1 credit dropped"
335        );
336        assert!(
337            !cache.is_credited_holder(&key(2), &peer(1), &h2),
338            "H2 credit dropped too (peer-wide, not pin-scoped)"
339        );
340        assert!(
341            cache.is_credited_holder(&key(1), &peer(2), &h1),
342            "another peer's credit is preserved"
343        );
344    }
345
346    #[test]
347    fn forget_commitment_drops_only_matching_entries() {
348        let mut cache = RecentProvers::new();
349        let now = Instant::now();
350        cache.record_proof(key(1), peer(1), hash(0xAB), now);
351        cache.record_proof(key(1), peer(1), hash(0xCD), now);
352        cache.record_proof(key(2), peer(2), hash(0xAB), now);
353        assert_eq!(cache.total_entries(), 3);
354
355        cache.forget_commitment(&hash(0xAB));
356        assert_eq!(cache.total_entries(), 1);
357        // Only the (peer(1), hash 0xCD) entry remains.
358        assert!(cache.is_credited_holder(&key(1), &peer(1), &hash(0xCD)));
359        assert!(!cache.is_credited_holder(&key(1), &peer(1), &hash(0xAB)));
360        assert!(!cache.is_credited_holder(&key(2), &peer(2), &hash(0xAB)));
361    }
362
363    #[test]
364    fn lazy_rotation_via_unknown_commitment_hash_drops_credit() {
365        // Scenario from v12 §5 (revised UnknownCommitmentHash handler):
366        //   1. Peer P proves K under C1 → cached.
367        //   2. Auditor pinned to C1 sends a new challenge.
368        //   3. P replies UnknownCommitmentHash (they rotated and
369        //      dropped the bytes).
370        //   4. Auditor invalidates last_commitment[P] AND calls
371        //      forget_commitment(C1) so credit doesn't linger.
372        //
373        // Property checked: after forget_commitment(C1), P is no longer
374        // credited as holder of K under C1.
375        let mut cache = RecentProvers::new();
376        cache.record_proof(key(1), peer(7), hash(0xAB), Instant::now());
377        assert!(cache.is_credited_holder(&key(1), &peer(7), &hash(0xAB)));
378
379        // Auditor detects rotation/dodge, invalidates the C1 hash.
380        cache.forget_commitment(&hash(0xAB));
381
382        assert!(!cache.is_credited_holder(&key(1), &peer(7), &hash(0xAB)));
383        // And under any new hash too — the peer has to re-prove.
384        assert!(!cache.is_credited_holder(&key(1), &peer(7), &hash(0xCD)));
385    }
386}