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