Skip to main content

ant_node/replication/
paid_list.rs

1//! Persistent `PaidForList` backed by LMDB.
2//!
3//! Tracks keys this node believes are paid-authorized. Survives restarts
4//! (Invariant 15). Bounded by `PaidCloseGroup` membership with
5//! hysteresis-based pruning.
6//!
7//! ## Storage layout
8//!
9//! ```text
10//! {root}/paid_list.mdb/   -- LMDB environment directory
11//! ```
12//!
13//! One unnamed database stores set membership: key = 32-byte `XorName`,
14//! value = empty byte slice.
15//!
16//! ## Out-of-range timestamps
17//!
18//! Per-key `PaidOutOfRangeFirstSeen` and `RecordOutOfRangeFirstSeen`
19//! timestamps live in memory only. On restart the hysteresis clock
20//! restarts from zero, which is safe: the prune timer simply starts
21//! fresh.
22
23use crate::ant_protocol::XorName;
24use crate::error::{Error, Result};
25use crate::logging::{debug, trace, warn};
26use heed::types::Bytes;
27use heed::{Database, Env, EnvOpenOptions};
28use parking_lot::RwLock;
29use std::collections::HashMap;
30use std::path::Path;
31use std::time::Instant;
32use tokio::task::spawn_blocking;
33use tokio_util::task::TaskTracker;
34
35use crate::ant_protocol::XORNAME_LEN;
36
37/// Default LMDB map size for the paid list: 256 MiB.
38///
39/// The paid list stores only 32-byte keys with empty values, so this is
40/// generous even for very large close-group memberships.
41const DEFAULT_MAP_SIZE: usize = 256 * 1_024 * 1_024;
42
43/// Persistent paid-for-list backed by LMDB.
44///
45/// Tracks which keys this node believes are paid-authorized.
46/// Survives node restarts via LMDB persistence.
47pub struct PaidList {
48    /// LMDB environment.
49    env: Env,
50    /// The unnamed default database (key = `XorName` bytes, value = empty).
51    db: Database<Bytes, Bytes>,
52    /// In-memory: when each paid key first went out of `PaidCloseGroup` range.
53    /// Cleared on restart (safe: hysteresis clock restarts from zero).
54    paid_out_of_range: RwLock<HashMap<XorName, Instant>>,
55    /// In-memory: when each stored record first went out of
56    /// storage-responsibility range.
57    record_out_of_range: RwLock<HashMap<XorName, Instant>>,
58    /// Cursor used by paid-list pruning to rotate through expired entries when
59    /// the per-pass remote confirmation cap is exhausted.
60    paid_prune_cursor: RwLock<usize>,
61    /// Tracks every paid-list LMDB blocking task.
62    ///
63    /// Same rationale as `LmdbStorage::blocking_tracker`: a `spawn_blocking`
64    /// closure owns a cloned [`Env`] and keeps running when its async awaiter
65    /// is dropped, so [`Self::wait_idle`] waits on the blocking tasks
66    /// themselves before the environment may be reopened.
67    blocking_tracker: TaskTracker,
68}
69
70impl PaidList {
71    /// Open or create a `PaidList` backed by LMDB at `{root_dir}/paid_list.mdb/`.
72    ///
73    /// # Errors
74    ///
75    /// Returns an error if the LMDB environment cannot be opened or the
76    /// database cannot be created.
77    #[allow(unsafe_code)]
78    pub async fn new(root_dir: &Path) -> Result<Self> {
79        let env_dir = root_dir.join("paid_list.mdb");
80
81        std::fs::create_dir_all(&env_dir)
82            .map_err(|e| Error::Storage(format!("Failed to create paid-list directory: {e}")))?;
83
84        let env_dir_clone = env_dir.clone();
85        // Constructor-only blocking task: it runs before `self` (and its
86        // `blocking_tracker`) exists, so it is deliberately untracked.  The
87        // constructor awaits it right here, so it cannot outlive this call.
88        let (env, db) = spawn_blocking(move || -> Result<(Env, Database<Bytes, Bytes>)> {
89            // SAFETY: `EnvOpenOptions::open()` is unsafe because LMDB uses
90            // memory-mapped I/O and relies on OS file-locking to prevent
91            // corruption from concurrent access by multiple processes. We
92            // satisfy this by giving each node instance a unique `root_dir`
93            // (typically named by its full 64-hex peer ID), ensuring no two
94            // processes open the same LMDB environment.
95            let env = unsafe {
96                EnvOpenOptions::new()
97                    .map_size(DEFAULT_MAP_SIZE)
98                    .max_dbs(1)
99                    .open(&env_dir_clone)
100                    .map_err(|e| {
101                        Error::Storage(format!("Failed to open paid-list LMDB env: {e}"))
102                    })?
103            };
104
105            let mut wtxn = env
106                .write_txn()
107                .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
108            let db: Database<Bytes, Bytes> = env
109                .create_database(&mut wtxn, None)
110                .map_err(|e| Error::Storage(format!("Failed to create paid-list database: {e}")))?;
111            wtxn.commit()
112                .map_err(|e| Error::Storage(format!("Failed to commit db creation: {e}")))?;
113
114            Ok((env, db))
115        })
116        .await
117        .map_err(|e| Error::Storage(format!("Paid-list init task failed: {e}")))??;
118
119        let paid_list = Self {
120            env,
121            db,
122            paid_out_of_range: RwLock::new(HashMap::new()),
123            record_out_of_range: RwLock::new(HashMap::new()),
124            paid_prune_cursor: RwLock::new(0),
125            blocking_tracker: TaskTracker::new(),
126        };
127
128        let count = paid_list.count()?;
129        debug!("Initialized paid-list at {env_dir:?} ({count} existing keys)");
130
131        Ok(paid_list)
132    }
133
134    /// Insert a key into the paid-for set.
135    ///
136    /// Returns `true` if the key was newly added, `false` if it already existed.
137    ///
138    /// # Errors
139    ///
140    /// Returns an error if the LMDB write transaction fails.
141    pub async fn insert(&self, key: &XorName) -> Result<bool> {
142        // Fast-path: avoid write transaction if key already present.
143        if self.contains(key)? {
144            trace!("Paid-list key {} already present", hex::encode(key));
145            return Ok(false);
146        }
147
148        let key_owned = *key;
149        let env = self.env.clone();
150        let db = self.db;
151
152        let was_new = self
153            .blocking_tracker
154            .spawn_blocking(move || -> Result<bool> {
155                let mut wtxn = env
156                    .write_txn()
157                    .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
158
159                // Authoritative existence check inside the serialized write txn.
160                if db
161                    .get(&wtxn, &key_owned)
162                    .map_err(|e| {
163                        Error::Storage(format!("Failed to check paid-list existence: {e}"))
164                    })?
165                    .is_some()
166                {
167                    return Ok(false);
168                }
169
170                db.put(&mut wtxn, &key_owned, &[])
171                    .map_err(|e| Error::Storage(format!("Failed to insert into paid-list: {e}")))?;
172                wtxn.commit().map_err(|e| {
173                    Error::Storage(format!("Failed to commit paid-list insert: {e}"))
174                })?;
175
176                Ok(true)
177            })
178            .await
179            .map_err(|e| Error::Storage(format!("Paid-list insert task failed: {e}")))??;
180
181        if was_new {
182            debug!("Added key {} to paid-list", hex::encode(key));
183        }
184
185        Ok(was_new)
186    }
187
188    /// Remove a key from the paid-for set.
189    ///
190    /// Also clears any in-memory out-of-range timestamps for this key.
191    ///
192    /// Returns `true` if the key existed and was removed, `false` otherwise.
193    ///
194    /// # Errors
195    ///
196    /// Returns an error if the LMDB write transaction fails.
197    pub async fn remove(&self, key: &XorName) -> Result<bool> {
198        let key_owned = *key;
199        let env = self.env.clone();
200        let db = self.db;
201
202        let existed = self
203            .blocking_tracker
204            .spawn_blocking(move || -> Result<bool> {
205                let mut wtxn = env
206                    .write_txn()
207                    .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
208                let deleted = db
209                    .delete(&mut wtxn, &key_owned)
210                    .map_err(|e| Error::Storage(format!("Failed to delete from paid-list: {e}")))?;
211                wtxn.commit().map_err(|e| {
212                    Error::Storage(format!("Failed to commit paid-list delete: {e}"))
213                })?;
214                Ok(deleted)
215            })
216            .await
217            .map_err(|e| Error::Storage(format!("Paid-list remove task failed: {e}")))??;
218
219        if existed {
220            self.paid_out_of_range.write().remove(key);
221            self.record_out_of_range.write().remove(key);
222            debug!("Removed key {} from paid-list", hex::encode(key));
223        }
224
225        Ok(existed)
226    }
227
228    /// Check whether a key is in the paid-for set.
229    ///
230    /// This is a synchronous read-only operation (no write transaction needed).
231    ///
232    /// # Errors
233    ///
234    /// Returns an error if the LMDB read transaction fails.
235    pub fn contains(&self, key: &XorName) -> Result<bool> {
236        let rtxn = self
237            .env
238            .read_txn()
239            .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
240        let found = self
241            .db
242            .get(&rtxn, key.as_ref())
243            .map_err(|e| Error::Storage(format!("Failed to check paid-list membership: {e}")))?
244            .is_some();
245        Ok(found)
246    }
247
248    /// Return the number of keys in the paid-for set.
249    ///
250    /// This is an O(1) read of the B-tree page header, not a full scan.
251    ///
252    /// # Errors
253    ///
254    /// Returns an error if the LMDB read transaction fails.
255    pub fn count(&self) -> Result<u64> {
256        let rtxn = self
257            .env
258            .read_txn()
259            .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
260        let entries = self
261            .db
262            .stat(&rtxn)
263            .map_err(|e| Error::Storage(format!("Failed to read paid-list stats: {e}")))?
264            .entries;
265        Ok(entries as u64)
266    }
267
268    /// Return all keys in the paid-for set.
269    ///
270    /// Used during hint construction to advertise which keys this node holds.
271    ///
272    /// # Errors
273    ///
274    /// Returns an error if the LMDB read transaction or iteration fails.
275    pub fn all_keys(&self) -> Result<Vec<XorName>> {
276        let rtxn = self
277            .env
278            .read_txn()
279            .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
280        let mut keys = Vec::new();
281        let iter = self
282            .db
283            .iter(&rtxn)
284            .map_err(|e| Error::Storage(format!("Failed to iterate paid-list: {e}")))?;
285        for result in iter {
286            let (key_bytes, _) = result
287                .map_err(|e| Error::Storage(format!("Failed to read paid-list entry: {e}")))?;
288            if key_bytes.len() == XORNAME_LEN {
289                let mut key = [0u8; XORNAME_LEN];
290                key.copy_from_slice(key_bytes);
291                keys.push(key);
292            } else {
293                warn!(
294                    "PaidList: skipping entry with unexpected key length {} (expected {XORNAME_LEN})",
295                    key_bytes.len()
296                );
297            }
298        }
299        Ok(keys)
300    }
301
302    /// Record the `PaidOutOfRangeFirstSeen` timestamp for a key.
303    ///
304    /// Only sets the timestamp if one is not already recorded (first
305    /// observation wins).
306    pub fn set_paid_out_of_range(&self, key: &XorName) {
307        self.paid_out_of_range
308            .write()
309            .entry(*key)
310            .or_insert_with(Instant::now);
311    }
312
313    /// Clear the `PaidOutOfRangeFirstSeen` timestamp for a key.
314    ///
315    /// Called when the key moves back into `PaidCloseGroup` range.
316    pub fn clear_paid_out_of_range(&self, key: &XorName) {
317        self.paid_out_of_range.write().remove(key);
318    }
319
320    /// Get the `PaidOutOfRangeFirstSeen` timestamp for a key.
321    ///
322    /// Returns `None` if the key is currently in range (no timestamp set).
323    pub fn paid_out_of_range_since(&self, key: &XorName) -> Option<Instant> {
324        self.paid_out_of_range.read().get(key).copied()
325    }
326
327    /// Record the `RecordOutOfRangeFirstSeen` timestamp for a key.
328    ///
329    /// Only sets the timestamp if one is not already recorded (first
330    /// observation wins).
331    pub fn set_record_out_of_range(&self, key: &XorName) {
332        self.record_out_of_range
333            .write()
334            .entry(*key)
335            .or_insert_with(Instant::now);
336    }
337
338    /// Clear the `RecordOutOfRangeFirstSeen` timestamp for a key.
339    ///
340    /// Called when the record moves back into storage-responsibility range.
341    pub fn clear_record_out_of_range(&self, key: &XorName) {
342        self.record_out_of_range.write().remove(key);
343    }
344
345    /// Get the `RecordOutOfRangeFirstSeen` timestamp for a key.
346    ///
347    /// Returns `None` if the record is currently in range (no timestamp set).
348    pub fn record_out_of_range_since(&self, key: &XorName) -> Option<Instant> {
349        self.record_out_of_range.read().get(key).copied()
350    }
351
352    /// Starting offset for the next paid-list prune scan.
353    ///
354    /// LMDB iteration order is stable, so a bounded prune pass must rotate its
355    /// verification window or later expired entries can be starved behind
356    /// earlier unconfirmed entries.
357    pub(crate) fn paid_prune_scan_start(&self, paid_key_count: usize) -> usize {
358        if paid_key_count == 0 {
359            return 0;
360        }
361
362        *self.paid_prune_cursor.read() % paid_key_count
363    }
364
365    /// Advance the paid-list prune cursor after one pass.
366    pub(crate) fn advance_paid_prune_cursor(
367        &self,
368        paid_key_count: usize,
369        scan_start: usize,
370        last_selected_offset: Option<usize>,
371    ) {
372        let mut cursor = self.paid_prune_cursor.write();
373        if paid_key_count == 0 {
374            *cursor = 0;
375            return;
376        }
377
378        let advance_by = last_selected_offset.map_or(1, |offset| offset.saturating_add(1));
379        *cursor = (scan_start + advance_by) % paid_key_count;
380    }
381
382    /// Remove multiple keys in a single write transaction.
383    ///
384    /// Also clears any in-memory out-of-range timestamps for removed keys.
385    ///
386    /// Returns the number of keys that were actually present and removed.
387    ///
388    /// # Cancellation
389    ///
390    /// The delete commits inside `spawn_blocking`, which cancellation cannot
391    /// reach; the timestamp clear below happens only after that await resumes.
392    /// Dropping this future in between therefore leaves keys deleted on disk
393    /// with their `paid_out_of_range` entries still set.
394    ///
395    /// That window is deliberately left open. The only caller is the prune pass
396    /// (`pruning::prune_paid_entries`), reached from `run_neighbor_sync_round`,
397    /// which is awaited inside a `select!` racing the engine's shutdown token —
398    /// so shutdown is the only way to hit it. `paid_out_of_range` is in-memory
399    /// only (never persisted), so the stale entries die with the process that
400    /// cancelled the prune, and a reopened `PaidList` starts with an empty map.
401    ///
402    /// Do NOT "fix" this by clearing the timestamps before the commit: a failed
403    /// commit would then leave a live key with a cleared hysteresis clock,
404    /// restarting its prune countdown from zero. That is a real correctness
405    /// regression in exchange for a window with no observable effect.
406    ///
407    /// # Errors
408    ///
409    /// Returns an error if the LMDB write transaction fails.
410    pub async fn remove_batch(&self, keys: &[XorName]) -> Result<usize> {
411        if keys.is_empty() {
412            return Ok(0);
413        }
414
415        let keys_owned: Vec<XorName> = keys.to_vec();
416        let env = self.env.clone();
417        let db = self.db;
418
419        let removed_keys = self
420            .blocking_tracker
421            .spawn_blocking(move || -> Result<Vec<XorName>> {
422                let mut wtxn = env
423                    .write_txn()
424                    .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
425
426                let mut removed = Vec::new();
427                for key in &keys_owned {
428                    let deleted = db.delete(&mut wtxn, key.as_ref()).map_err(|e| {
429                        Error::Storage(format!("Failed to delete from paid-list: {e}"))
430                    })?;
431                    if deleted {
432                        removed.push(*key);
433                    }
434                }
435
436                wtxn.commit()
437                    .map_err(|e| Error::Storage(format!("Failed to commit batch remove: {e}")))?;
438
439                Ok(removed)
440            })
441            .await
442            .map_err(|e| Error::Storage(format!("Paid-list batch remove task failed: {e}")))??;
443
444        // Clear in-memory timestamps for all removed keys.
445        // Acquire and release each lock separately to minimize hold time.
446        if !removed_keys.is_empty() {
447            {
448                let mut paid_oor = self.paid_out_of_range.write();
449                for key in &removed_keys {
450                    paid_oor.remove(key);
451                }
452            }
453            {
454                let mut record_oor = self.record_out_of_range.write();
455                for key in &removed_keys {
456                    record_oor.remove(key);
457                }
458            }
459        }
460
461        let count = removed_keys.len();
462        debug!("Batch-removed {count} keys from paid-list");
463        Ok(count)
464    }
465
466    /// Wait until every tracked paid-list LMDB blocking task has finished.
467    ///
468    /// Dropping an async caller (e.g. a `select!` losing to a shutdown token)
469    /// does not cancel an already-spawned blocking closure — the closure keeps
470    /// running on the blocking pool with a cloned [`Env`].  This method waits
471    /// for those detached closures too, so when it returns no blocking
472    /// operation still holds the environment.
473    ///
474    /// Quiescence is only meaningful once callers have stopped issuing new
475    /// operations; concurrent traffic can keep the tracker non-empty
476    /// indefinitely.  The paid list remains fully usable afterwards (the
477    /// internal tracker is reopened before returning).
478    pub async fn wait_idle(&self) {
479        self.blocking_tracker.close();
480        self.blocking_tracker.wait().await;
481        self.blocking_tracker.reopen();
482    }
483}
484
485#[cfg(test)]
486#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
487mod tests {
488    use super::*;
489
490    /// Short probe used to prove `wait_idle` is still blocked on a parked op.
491    const WAIT_IDLE_BLOCKED_PROBE: std::time::Duration = std::time::Duration::from_millis(200);
492    /// Generous ceiling for `wait_idle` to complete once the op is released.
493    const WAIT_IDLE_COMPLETE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
494
495    async fn create_test_paid_list() -> (PaidList, tempfile::TempDir) {
496        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
497        let paid_list = PaidList::new(temp_dir.path())
498            .await
499            .expect("create paid list");
500        (paid_list, temp_dir)
501    }
502
503    #[tokio::test]
504    async fn test_insert_and_contains() {
505        let (pl, _temp) = create_test_paid_list().await;
506
507        let key: XorName = [0xAA; 32];
508        assert!(!pl.contains(&key).expect("contains before insert"));
509
510        let was_new = pl.insert(&key).await.expect("insert");
511        assert!(was_new);
512
513        assert!(pl.contains(&key).expect("contains after insert"));
514    }
515
516    #[tokio::test]
517    async fn test_insert_duplicate_returns_false() {
518        let (pl, _temp) = create_test_paid_list().await;
519
520        let key: XorName = [0xBB; 32];
521
522        let first = pl.insert(&key).await.expect("first insert");
523        assert!(first);
524
525        let second = pl.insert(&key).await.expect("second insert");
526        assert!(!second);
527    }
528
529    #[tokio::test]
530    async fn test_remove_existing() {
531        let (pl, _temp) = create_test_paid_list().await;
532
533        let key: XorName = [0xCC; 32];
534        pl.insert(&key).await.expect("insert");
535        assert!(pl.contains(&key).expect("contains"));
536
537        let removed = pl.remove(&key).await.expect("remove");
538        assert!(removed);
539        assert!(!pl.contains(&key).expect("contains after remove"));
540    }
541
542    #[tokio::test]
543    async fn test_remove_nonexistent() {
544        let (pl, _temp) = create_test_paid_list().await;
545
546        let key: XorName = [0xDD; 32];
547        let removed = pl.remove(&key).await.expect("remove nonexistent");
548        assert!(!removed);
549    }
550
551    #[tokio::test]
552    async fn test_persistence_across_reopen() {
553        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
554        let key: XorName = [0xEE; 32];
555
556        // Insert a key, then drop the PaidList.
557        {
558            let pl = PaidList::new(temp_dir.path())
559                .await
560                .expect("create paid list");
561            pl.insert(&key).await.expect("insert");
562            assert_eq!(pl.count().expect("count"), 1);
563        }
564
565        // Re-open and verify the key persisted.
566        {
567            let pl = PaidList::new(temp_dir.path())
568                .await
569                .expect("reopen paid list");
570            assert_eq!(pl.count().expect("count"), 1);
571            assert!(pl.contains(&key).expect("contains after reopen"));
572        }
573    }
574
575    #[tokio::test]
576    async fn test_all_keys() {
577        let (pl, _temp) = create_test_paid_list().await;
578
579        let key_a: XorName = [0x01; 32];
580        let key_b: XorName = [0x02; 32];
581        let key_c: XorName = [0x03; 32];
582
583        pl.insert(&key_a).await.expect("insert 1");
584        pl.insert(&key_b).await.expect("insert 2");
585        pl.insert(&key_c).await.expect("insert 3");
586
587        let mut keys = pl.all_keys().expect("all_keys");
588        keys.sort_unstable();
589
590        let mut expected = vec![key_a, key_b, key_c];
591        expected.sort_unstable();
592
593        assert_eq!(keys, expected);
594    }
595
596    #[tokio::test]
597    async fn test_count() {
598        let (pl, _temp) = create_test_paid_list().await;
599
600        assert_eq!(pl.count().expect("count empty"), 0);
601
602        let key1: XorName = [0x10; 32];
603        let key2: XorName = [0x20; 32];
604
605        pl.insert(&key1).await.expect("insert 1");
606        assert_eq!(pl.count().expect("count after 1"), 1);
607
608        pl.insert(&key2).await.expect("insert 2");
609        assert_eq!(pl.count().expect("count after 2"), 2);
610
611        pl.remove(&key1).await.expect("remove 1");
612        assert_eq!(pl.count().expect("count after remove"), 1);
613    }
614
615    #[tokio::test]
616    async fn test_paid_out_of_range_timestamps() {
617        let (pl, _temp) = create_test_paid_list().await;
618
619        let key: XorName = [0xF0; 32];
620
621        // Initially no timestamp.
622        assert!(pl.paid_out_of_range_since(&key).is_none());
623
624        // Set timestamp.
625        let before = Instant::now();
626        pl.set_paid_out_of_range(&key);
627        let after = Instant::now();
628
629        let ts = pl
630            .paid_out_of_range_since(&key)
631            .expect("timestamp should exist");
632        assert!(ts >= before);
633        assert!(ts <= after);
634
635        // Setting again should not update (first observation wins).
636        std::thread::sleep(std::time::Duration::from_millis(10));
637        pl.set_paid_out_of_range(&key);
638        let ts2 = pl
639            .paid_out_of_range_since(&key)
640            .expect("timestamp should still exist");
641        assert_eq!(ts, ts2);
642
643        // Clear.
644        pl.clear_paid_out_of_range(&key);
645        assert!(pl.paid_out_of_range_since(&key).is_none());
646    }
647
648    #[tokio::test]
649    async fn test_record_out_of_range_timestamps() {
650        let (pl, _temp) = create_test_paid_list().await;
651
652        let key: XorName = [0xF1; 32];
653
654        assert!(pl.record_out_of_range_since(&key).is_none());
655
656        let before = Instant::now();
657        pl.set_record_out_of_range(&key);
658        let after = Instant::now();
659
660        let ts = pl
661            .record_out_of_range_since(&key)
662            .expect("timestamp should exist");
663        assert!(ts >= before);
664        assert!(ts <= after);
665
666        // Setting again should not update.
667        std::thread::sleep(std::time::Duration::from_millis(10));
668        pl.set_record_out_of_range(&key);
669        let ts2 = pl
670            .record_out_of_range_since(&key)
671            .expect("timestamp should still exist");
672        assert_eq!(ts, ts2);
673
674        // Clear.
675        pl.clear_record_out_of_range(&key);
676        assert!(pl.record_out_of_range_since(&key).is_none());
677    }
678
679    #[tokio::test]
680    async fn test_remove_clears_timestamps() {
681        let (pl, _temp) = create_test_paid_list().await;
682
683        let key: XorName = [0xA0; 32];
684        pl.insert(&key).await.expect("insert");
685
686        pl.set_paid_out_of_range(&key);
687        pl.set_record_out_of_range(&key);
688        assert!(pl.paid_out_of_range_since(&key).is_some());
689        assert!(pl.record_out_of_range_since(&key).is_some());
690
691        pl.remove(&key).await.expect("remove");
692        assert!(pl.paid_out_of_range_since(&key).is_none());
693        assert!(pl.record_out_of_range_since(&key).is_none());
694    }
695
696    #[tokio::test]
697    async fn test_remove_batch() {
698        let (pl, _temp) = create_test_paid_list().await;
699
700        let key1: XorName = [0x01; 32];
701        let key2: XorName = [0x02; 32];
702        let key3: XorName = [0x03; 32];
703        let key4: XorName = [0x04; 32]; // not inserted
704
705        pl.insert(&key1).await.expect("insert 1");
706        pl.insert(&key2).await.expect("insert 2");
707        pl.insert(&key3).await.expect("insert 3");
708
709        // Set timestamps to verify they get cleared.
710        pl.set_paid_out_of_range(&key1);
711        pl.set_record_out_of_range(&key2);
712
713        let removed = pl
714            .remove_batch(&[key1, key2, key4])
715            .await
716            .expect("remove_batch");
717        assert_eq!(removed, 2); // key1 and key2 existed; key4 did not
718
719        assert!(!pl.contains(&key1).expect("key1 gone"));
720        assert!(!pl.contains(&key2).expect("key2 gone"));
721        assert!(pl.contains(&key3).expect("key3 still present"));
722        assert_eq!(pl.count().expect("count"), 1);
723
724        // Timestamps should be cleared for removed keys.
725        assert!(pl.paid_out_of_range_since(&key1).is_none());
726        assert!(pl.record_out_of_range_since(&key2).is_none());
727    }
728
729    #[tokio::test]
730    async fn test_remove_batch_empty() {
731        let (pl, _temp) = create_test_paid_list().await;
732
733        let removed = pl.remove_batch(&[]).await.expect("remove_batch empty");
734        assert_eq!(removed, 0);
735    }
736
737    /// Park the paid-list env's single LMDB writer slot on a test-held write
738    /// transaction, so the next tracked write blocks inside its closure.
739    ///
740    /// Returns once the transaction is open. Dropping the returned sender
741    /// releases the slot.
742    async fn hold_write_txn(
743        pl: &PaidList,
744    ) -> (
745        tokio::sync::oneshot::Sender<()>,
746        tokio::task::JoinHandle<()>,
747    ) {
748        let env = pl.env.clone();
749        let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
750        let (opened_tx, opened_rx) = tokio::sync::oneshot::channel::<()>();
751        let holder = tokio::task::spawn_blocking(move || {
752            let _wtxn = env.write_txn().expect("open holder write txn");
753            let _ = opened_tx.send(());
754            let _ = release_rx.blocking_recv();
755        });
756        opened_rx.await.expect("holder txn opened");
757        (release_tx, holder)
758    }
759
760    /// Dropping an `insert` awaiter does not cancel its `spawn_blocking` LMDB
761    /// transaction; `wait_idle` must wait for that detached write, and the
762    /// paid list must remain usable afterwards.
763    #[tokio::test]
764    async fn wait_idle_waits_for_detached_insert_blocking_op() {
765        let (pl, _temp) = create_test_paid_list().await;
766        let key: XorName = [0x77; 32];
767
768        let (release, holder) = hold_write_txn(&pl).await;
769
770        // Drop the awaiting future mid-flight: the biased select! polls the
771        // insert once — far enough to spawn the blocking task, which parks on
772        // the held writer slot — then completes on the ready branch.
773        tokio::select! {
774            biased;
775            res = pl.insert(&key) => {
776                panic!("insert must be parked on the writer slot, got {res:?}")
777            }
778            () = std::future::ready(()) => {}
779        }
780
781        // The blocking op is still running: wait_idle must not complete.
782        let blocked = tokio::time::timeout(WAIT_IDLE_BLOCKED_PROBE, pl.wait_idle()).await;
783        assert!(
784            blocked.is_err(),
785            "wait_idle returned while the insert blocking op was parked"
786        );
787
788        // Release the writer slot: the detached closure commits and exits.
789        drop(release);
790        holder.await.expect("holder task");
791        tokio::time::timeout(WAIT_IDLE_COMPLETE_TIMEOUT, pl.wait_idle())
792            .await
793            .expect("wait_idle after release");
794
795        // The dropped awaiter did not lose the write: it committed.
796        assert!(pl.contains(&key).expect("contains after release"));
797
798        // The paid list remains usable after wait_idle (tracker reopened).
799        let key2: XorName = [0x78; 32];
800        assert!(pl.insert(&key2).await.expect("insert after wait_idle"));
801    }
802
803    /// Same shape as the insert test, for `remove_batch`: a detached batch
804    /// removal must hold `wait_idle` open until its transaction commits.
805    #[tokio::test]
806    async fn wait_idle_waits_for_detached_remove_batch_blocking_op() {
807        let (pl, _temp) = create_test_paid_list().await;
808        let key_a: XorName = [0x79; 32];
809        let key_b: XorName = [0x7A; 32];
810        pl.insert(&key_a).await.expect("insert a");
811        pl.insert(&key_b).await.expect("insert b");
812
813        let (release, holder) = hold_write_txn(&pl).await;
814
815        let batch = [key_a, key_b];
816        tokio::select! {
817            biased;
818            res = pl.remove_batch(&batch) => {
819                panic!("remove_batch must be parked on the writer slot, got {res:?}")
820            }
821            () = std::future::ready(()) => {}
822        }
823
824        let blocked = tokio::time::timeout(WAIT_IDLE_BLOCKED_PROBE, pl.wait_idle()).await;
825        assert!(
826            blocked.is_err(),
827            "wait_idle returned while the remove_batch blocking op was parked"
828        );
829
830        drop(release);
831        holder.await.expect("holder task");
832        tokio::time::timeout(WAIT_IDLE_COMPLETE_TIMEOUT, pl.wait_idle())
833            .await
834            .expect("wait_idle after release");
835
836        // The dropped awaiter did not lose the batch removal: it committed.
837        assert!(!pl.contains(&key_a).expect("key_a removed"));
838        assert!(!pl.contains(&key_b).expect("key_b removed"));
839
840        // The paid list remains usable after wait_idle (tracker reopened).
841        assert!(pl.insert(&key_a).await.expect("insert after wait_idle"));
842    }
843
844    #[tokio::test]
845    async fn paid_prune_cursor_advances_past_selected_window() {
846        const PAID_KEY_COUNT: usize = 10;
847        const START_CURSOR: usize = 2;
848        const LAST_SELECTED_OFFSET: usize = 3;
849        const EXPECTED_CURSOR: usize = 6;
850
851        let (pl, _temp) = create_test_paid_list().await;
852        *pl.paid_prune_cursor.write() = START_CURSOR;
853
854        let scan_start = pl.paid_prune_scan_start(PAID_KEY_COUNT);
855        pl.advance_paid_prune_cursor(PAID_KEY_COUNT, scan_start, Some(LAST_SELECTED_OFFSET));
856
857        assert_eq!(*pl.paid_prune_cursor.read(), EXPECTED_CURSOR);
858    }
859
860    #[tokio::test]
861    async fn paid_prune_cursor_advances_even_without_selected_entry() {
862        const PAID_KEY_COUNT: usize = 10;
863        const START_CURSOR: usize = 9;
864        const EXPECTED_CURSOR: usize = 0;
865
866        let (pl, _temp) = create_test_paid_list().await;
867        *pl.paid_prune_cursor.write() = START_CURSOR;
868
869        let scan_start = pl.paid_prune_scan_start(PAID_KEY_COUNT);
870        pl.advance_paid_prune_cursor(PAID_KEY_COUNT, scan_start, None);
871
872        assert_eq!(*pl.paid_prune_cursor.read(), EXPECTED_CURSOR);
873    }
874
875    #[tokio::test]
876    async fn paid_prune_cursor_resets_for_empty_paid_list() {
877        const STALE_CURSOR: usize = 7;
878        const EMPTY_PAID_KEY_COUNT: usize = 0;
879        const EXPECTED_CURSOR: usize = 0;
880
881        let (pl, _temp) = create_test_paid_list().await;
882        *pl.paid_prune_cursor.write() = STALE_CURSOR;
883
884        let scan_start = pl.paid_prune_scan_start(EMPTY_PAID_KEY_COUNT);
885        pl.advance_paid_prune_cursor(EMPTY_PAID_KEY_COUNT, scan_start, Some(STALE_CURSOR));
886
887        assert_eq!(*pl.paid_prune_cursor.read(), EXPECTED_CURSOR);
888    }
889
890    // -- Scenario tests -------------------------------------------------------
891
892    /// #50: Key goes out of range. `set_record_out_of_range` called.
893    /// Immediately the elapsed time is less than `PRUNE_HYSTERESIS_DURATION`,
894    /// so a prune pass should NOT delete it. We verify the timestamp is
895    /// present but recent.
896    #[tokio::test]
897    async fn scenario_50_hysteresis_prevents_premature_deletion() {
898        let hysteresis = crate::replication::config::PRUNE_HYSTERESIS_DURATION;
899        let (pl, _temp) = create_test_paid_list().await;
900        let key: XorName = [0x50; 32];
901
902        // Key goes out of range — record the timestamp.
903        pl.set_record_out_of_range(&key);
904
905        // Timestamp must be present.
906        let since = pl
907            .record_out_of_range_since(&key)
908            .expect("timestamp should exist after set");
909
910        // Elapsed time is effectively zero — well below hysteresis threshold.
911        let elapsed = since.elapsed();
912        assert!(
913            elapsed < hysteresis,
914            "elapsed ({elapsed:?}) should be far below PRUNE_HYSTERESIS_DURATION ({hysteresis:?})",
915        );
916    }
917
918    /// #51: Key goes out of range, then comes back. Timestamp is cleared.
919    /// If the key leaves again, the clock restarts from now.
920    #[tokio::test]
921    async fn scenario_51_timestamp_reset_on_heal() {
922        let (pl, _temp) = create_test_paid_list().await;
923        let key: XorName = [0x51; 32];
924
925        // Key goes out of range.
926        pl.set_record_out_of_range(&key);
927        assert!(
928            pl.record_out_of_range_since(&key).is_some(),
929            "timestamp should exist after going out of range"
930        );
931
932        // Partition heals — key comes back in range.
933        pl.clear_record_out_of_range(&key);
934        assert!(
935            pl.record_out_of_range_since(&key).is_none(),
936            "timestamp should be cleared after heal"
937        );
938
939        // Key goes out of range again — clock must restart.
940        let before_second = Instant::now();
941        pl.set_record_out_of_range(&key);
942        let second_ts = pl
943            .record_out_of_range_since(&key)
944            .expect("timestamp should exist after second out-of-range");
945        assert!(
946            second_ts >= before_second,
947            "new timestamp should be >= the instant before second set call"
948        );
949    }
950
951    /// #52: Paid and record out-of-range timestamps are independent.
952    /// Clearing one must not affect the other.
953    #[tokio::test]
954    async fn scenario_52_paid_and_record_timestamps_independent() {
955        let (pl, _temp) = create_test_paid_list().await;
956        let key: XorName = [0x52; 32];
957
958        // Set both timestamps.
959        pl.set_paid_out_of_range(&key);
960        pl.set_record_out_of_range(&key);
961        assert!(pl.paid_out_of_range_since(&key).is_some());
962        assert!(pl.record_out_of_range_since(&key).is_some());
963
964        // Clear record — paid must survive.
965        pl.clear_record_out_of_range(&key);
966        assert!(
967            pl.paid_out_of_range_since(&key).is_some(),
968            "paid timestamp should survive clearing record timestamp"
969        );
970        assert!(pl.record_out_of_range_since(&key).is_none());
971
972        // Re-set record, then clear paid — record must survive.
973        pl.set_record_out_of_range(&key);
974        pl.clear_paid_out_of_range(&key);
975        assert!(
976            pl.record_out_of_range_since(&key).is_some(),
977            "record timestamp should survive clearing paid timestamp"
978        );
979        assert!(pl.paid_out_of_range_since(&key).is_none());
980    }
981
982    /// #23: Inserting then removing a key from the paid list clears both
983    /// the persistence entry and any in-memory out-of-range timestamps.
984    #[tokio::test]
985    async fn scenario_23_paid_list_entry_removed() {
986        let (pl, _temp) = create_test_paid_list().await;
987        let key: XorName = [0x23; 32];
988
989        // Insert key and attach out-of-range timestamps.
990        pl.insert(&key).await.expect("insert");
991        pl.set_paid_out_of_range(&key);
992        pl.set_record_out_of_range(&key);
993
994        // Remove — should clear everything.
995        let removed = pl.remove(&key).await.expect("remove");
996        assert!(removed, "key should have existed");
997        assert!(
998            !pl.contains(&key).expect("contains check"),
999            "key should be gone from paid list"
1000        );
1001        assert!(
1002            pl.paid_out_of_range_since(&key).is_none(),
1003            "paid timestamp should be cleaned up on remove"
1004        );
1005        assert!(
1006            pl.record_out_of_range_since(&key).is_none(),
1007            "record timestamp should be cleaned up on remove"
1008        );
1009    }
1010
1011    /// #13: Responsible range shrink — out-of-range records have their
1012    /// timestamp recorded, are NOT pruned before `PRUNE_HYSTERESIS_DURATION`,
1013    /// and new in-range keys are still accepted while out-of-range keys
1014    /// await expiry.
1015    #[tokio::test]
1016    async fn scenario_13_responsible_range_shrink() {
1017        let hysteresis = crate::replication::config::PRUNE_HYSTERESIS_DURATION;
1018        let (pl, _temp) = create_test_paid_list().await;
1019
1020        let out_of_range_key: XorName = [0x13; 32];
1021        let in_range_key: XorName = [0x14; 32];
1022
1023        // Insert both keys initially (simulating they were once in range).
1024        pl.insert(&out_of_range_key)
1025            .await
1026            .expect("insert out-of-range");
1027        pl.insert(&in_range_key).await.expect("insert in-range");
1028
1029        // Range shrinks: out_of_range_key is no longer in responsibility range.
1030        // Record RecordOutOfRangeFirstSeen.
1031        pl.set_record_out_of_range(&out_of_range_key);
1032        let first_seen = pl
1033            .record_out_of_range_since(&out_of_range_key)
1034            .expect("timestamp should be recorded for out-of-range key");
1035
1036        // Key must NOT be pruned yet — elapsed time is far below hysteresis.
1037        let elapsed = first_seen.elapsed();
1038        assert!(
1039            elapsed < hysteresis,
1040            "elapsed {elapsed:?} should be below PRUNE_HYSTERESIS_DURATION \
1041             ({hysteresis:?}) — key must not be pruned yet"
1042        );
1043
1044        // The key should still exist in the paid list (not deleted).
1045        assert!(
1046            pl.contains(&out_of_range_key).expect("contains"),
1047            "out-of-range key should still be retained within hysteresis window"
1048        );
1049
1050        // In-range key is unaffected — no out-of-range timestamp set.
1051        assert!(
1052            pl.record_out_of_range_since(&in_range_key).is_none(),
1053            "in-range key should have no out-of-range timestamp"
1054        );
1055
1056        // New in-range keys are still accepted during this period.
1057        let new_key: XorName = [0x15; 32];
1058        let was_new = pl.insert(&new_key).await.expect("insert new key");
1059        assert!(
1060            was_new,
1061            "new in-range keys should still be accepted while out-of-range keys await expiry"
1062        );
1063        assert!(
1064            pl.contains(&new_key).expect("contains new"),
1065            "newly inserted in-range key should be present"
1066        );
1067    }
1068
1069    /// #46: Bootstrap claim first-seen is recorded and follows
1070    /// first-observation-wins semantics.
1071    #[test]
1072    fn scenario_46_bootstrap_claim_first_seen_recorded() {
1073        let grace_period = crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD;
1074        let peer = saorsa_core::identity::PeerId::from_bytes([0x46; 32]);
1075        let mut state = crate::replication::types::NeighborSyncState::new_cycle(vec![peer]);
1076
1077        let first_ts = Instant::now()
1078            .checked_sub(std::time::Duration::from_secs(3))
1079            .unwrap_or_else(Instant::now);
1080        let observed = state.observe_bootstrap_claim(peer, first_ts, grace_period);
1081        assert_eq!(
1082            observed,
1083            crate::replication::types::BootstrapClaimObservation::WithinGrace {
1084                first_seen: first_ts
1085            }
1086        );
1087
1088        // Verify recorded.
1089        assert_eq!(
1090            state.bootstrap_claims.get(&peer),
1091            Some(&first_ts),
1092            "first-seen timestamp should be recorded"
1093        );
1094        assert_eq!(
1095            state.bootstrap_claim_history.get(&peer),
1096            Some(&first_ts),
1097            "first-ever timestamp should be retained"
1098        );
1099
1100        // Observe again while still active — must NOT overwrite
1101        // (first-observation-wins).
1102        let later_ts = Instant::now();
1103        let observed = state.observe_bootstrap_claim(peer, later_ts, grace_period);
1104        assert_eq!(
1105            observed,
1106            crate::replication::types::BootstrapClaimObservation::WithinGrace {
1107                first_seen: first_ts
1108            }
1109        );
1110        assert_eq!(
1111            state.bootstrap_claims.get(&peer),
1112            Some(&first_ts),
1113            "second insert must not overwrite the original timestamp"
1114        );
1115    }
1116
1117    /// #48: Peer P first claimed bootstrapping >24 h ago.  On next interaction
1118    /// the claim age exceeds `BOOTSTRAP_CLAIM_GRACE_PERIOD` and the node emits
1119    /// `BootstrapClaimAbuse` evidence.
1120    #[test]
1121    fn scenario_48_bootstrap_claim_abuse_after_grace_period() {
1122        let grace_period = crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD;
1123        let peer = saorsa_core::identity::PeerId::from_bytes([0x48; 32]);
1124        let mut state = crate::replication::types::NeighborSyncState::new_cycle(vec![peer]);
1125
1126        // Record a first-seen timestamp >24 h ago.
1127        // `Instant::checked_sub` can fail on Windows where the epoch is
1128        // process-start, so fall back to a recent instant when the platform
1129        // cannot represent the backdated time (the claim-age assertion is
1130        // skipped in that case since the subtraction itself proves nothing
1131        // about production behaviour).
1132        let grace_plus_margin = grace_period + std::time::Duration::from_secs(3600);
1133        let first_seen = Instant::now()
1134            .checked_sub(grace_plus_margin)
1135            .unwrap_or_else(Instant::now);
1136        state.bootstrap_claims.insert(peer, first_seen);
1137        state.bootstrap_claim_history.insert(peer, first_seen);
1138
1139        // On platforms that support the backdated instant, verify claim age.
1140        let claim_age = Instant::now().duration_since(first_seen);
1141        if claim_age > std::time::Duration::from_secs(1) {
1142            assert!(
1143                claim_age > grace_period,
1144                "claim age {claim_age:?} should exceed grace period {grace_period:?}",
1145            );
1146        }
1147
1148        // Caller constructs BootstrapClaimAbuse evidence.
1149        let evidence =
1150            crate::replication::types::FailureEvidence::BootstrapClaimAbuse { peer, first_seen };
1151
1152        let crate::replication::types::FailureEvidence::BootstrapClaimAbuse {
1153            peer: p,
1154            first_seen: fs,
1155        } = evidence
1156        else {
1157            unreachable!("evidence was just constructed as BootstrapClaimAbuse");
1158        };
1159        assert_eq!(p, peer);
1160        assert_eq!(fs, first_seen);
1161    }
1162
1163    /// #49: Bootstrap claim is cleared when a peer responds normally.
1164    #[test]
1165    fn scenario_49_bootstrap_claim_cleared() {
1166        let grace_period = crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD;
1167        let peer = saorsa_core::identity::PeerId::from_bytes([0x49; 32]);
1168        let mut state = crate::replication::types::NeighborSyncState::new_cycle(vec![peer]);
1169
1170        // Record a bootstrap claim.
1171        let first_seen = Instant::now();
1172        let _ = state.observe_bootstrap_claim(peer, first_seen, grace_period);
1173        assert!(
1174            state.bootstrap_claims.contains_key(&peer),
1175            "claim should exist after insert"
1176        );
1177
1178        // Peer responded normally — clear only the active claim.
1179        state.clear_active_bootstrap_claim(&peer);
1180        assert!(
1181            !state.bootstrap_claims.contains_key(&peer),
1182            "claim should be gone after normal response"
1183        );
1184        assert!(
1185            state.bootstrap_claim_history.contains_key(&peer),
1186            "claim history should remain so the peer cannot claim bootstrapping again"
1187        );
1188
1189        let repeated = state.observe_bootstrap_claim(peer, Instant::now(), grace_period);
1190        assert_eq!(
1191            repeated,
1192            crate::replication::types::BootstrapClaimObservation::Repeated { first_seen },
1193            "a second bootstrap claim should be classified as repeated abuse"
1194        );
1195    }
1196}