Skip to main content

ant_node/pointer/
store.rs

1//! Durable storage for pointer records, with merge-on-put.
2//!
3//! The chunk store answers "already have it" and stops, which is right for an
4//! immutable record and wrong for a mutable one — it would silently drop every
5//! update. It also requires `BLAKE3(content) == address`, which no pointer can
6//! satisfy. So pointers get their own store rather than an exemption carved
7//! into that one.
8//!
9//! # The shape of a write
10//!
11//! A put is three steps, because the caller's gates sit between them:
12//!
13//! 1. `inspect` parses and compares against what is held: the arrival is
14//!    either unchanged, stale, or a candidate that would win.
15//! 2. `verify` checks the candidate's signature — after the caller's
16//!    admission gates, and before it verifies payment.
17//! 3. `commit` writes it, and settles the disk charge taken for it.
18//!
19//! Those three are internal to the crate; [`PointerStore::put_bytes`] is the
20//! same sequence in one call, for callers with nothing to do in between.
21//!
22//! Nothing cheap happens after something expensive: a resubmission of what is
23//! held is refused before any signature check, so repeatedly submitting one
24//! paid state buys no ML-DSA verifications. Step 2 runs **outside** any store
25//! lock, so a flood of unpaid candidates cannot block every other address
26//! behind one verification, and step 3 re-checks under the lock, because the
27//! world may have moved while payment was being verified.
28//!
29//! # Atomicity
30//!
31//! The commit — compare, write, re-index — runs inside a single blocking task
32//! holding a synchronous lock. Splitting it across an `await` would let a
33//! cancelled caller release the lock while its write was still in flight,
34//! leaving the index describing a record the disk no longer holds. Because the
35//! whole transaction lives in one task, dropping the caller's future cannot
36//! tear it.
37//!
38//! On disk each record is one file named by its hex address, under
39//! `{root}/pointers/<shard>/`, where the shard is the address's last byte in
40//! hex: 256 directories, as the chunk store keeps, so no directory grows with
41//! the whole store. The last byte rather than the first because a node holds
42//! addresses near its own identity, and their leading bytes cluster. Writes go
43//! to a uniquely named temporary file in the shard and are renamed into place,
44//! so a crash leaves either the old record or the new one, never a torn one. A
45//! lock file under `{root}/pointers/` keeps two processes from keeping two
46//! indexes over one set of files.
47
48use std::collections::{HashMap, VecDeque};
49
50use bytes::Bytes;
51use std::fs::{File, OpenOptions};
52use std::io::{Read, Write};
53use std::path::{Path, PathBuf};
54use std::sync::atomic::{AtomicU64, Ordering};
55use std::sync::Arc;
56use std::time::{Duration, Instant};
57
58use fs2::FileExt;
59use parking_lot::Mutex;
60use tokio::task::spawn_blocking;
61
62use crate::ant_protocol::XorName;
63use crate::error::{Error, Result};
64use crate::logging::{debug, warn};
65use ant_protocol::pointer::{ParsedPointer, Pointer, PointerState, POINTER_WIRE_LEN};
66
67use crate::storage::{rename_with_retry, Reservation};
68
69/// Directory under the store root that holds pointer records.
70const POINTERS_DIR_NAME: &str = "pointers";
71
72/// Prefix for the temporary file a write lands in before being renamed.
73const TEMP_PREFIX: &str = ".tmp-";
74
75/// Name of the file whose lock grants exclusive use of the directory.
76const LOCK_FILE_NAME: &str = ".pointer-store-lock";
77
78/// How many shard directories records are spread across: one per value of an
79/// address's last byte.
80const SHARD_COUNT: u16 = 256;
81
82/// How long a replaced record is kept after an update, in memory.
83///
84/// A storage audit binds the record a node holds in its first round and asks
85/// for it in the second (ADR-0016). An owner updating the pointer between the
86/// two would otherwise fail the honest node that took the update, so every
87/// record an update replaces stays servable, however many updates follow it
88/// (ADR-0019), for longer than the slowest audit takes with the default
89/// configuration: a round 1 over the largest subtree an auditor will wait
90/// for, then the session its round 2 must arrive within. Round 1 can read a
91/// pointer at its very start and take that long to finish, so the time counts
92/// from the read, not from the session.
93pub const SUPERSEDED_RETENTION: Duration = Duration::from_mins(10);
94
95/// Most replaced records kept at once, across every address, about 11 MB at
96/// the cap. Past it the oldest goes first; reaching it inside
97/// [`SUPERSEDED_RETENTION`] takes that many paid updates to pointers this
98/// node holds.
99const MAX_SUPERSEDED: usize = 2048;
100
101/// Every record a recent update replaced, by address, oldest first, each with
102/// when it was replaced (see [`SUPERSEDED_RETENTION`]). Held as [`Bytes`] so
103/// handing them out copies nothing.
104type Superseded = HashMap<XorName, VecDeque<(Instant, Bytes)>>;
105
106/// Drop every kept record older than [`SUPERSEDED_RETENTION`] at `now`, and
107/// every address left with none.
108fn drop_expired(superseded: &mut Superseded, now: Instant) {
109    superseded.retain(|_, kept| {
110        kept.retain(|(at, _)| now.saturating_duration_since(*at) < SUPERSEDED_RETENTION);
111        !kept.is_empty()
112    });
113}
114
115/// The name of the shard directory `address` lives in: its last byte in hex.
116fn shard_name(address: &XorName) -> String {
117    let last = address.last().copied().unwrap_or_default();
118    format!("{last:02x}")
119}
120
121/// The shard directory `address` lives in.
122fn shard_dir(dir: &Path, address: &XorName) -> PathBuf {
123    dir.join(shard_name(address))
124}
125
126/// The file that holds the record at `address`.
127fn record_path(dir: &Path, address: &XorName) -> PathBuf {
128    shard_dir(dir, address).join(hex::encode(address))
129}
130
131/// What a put did.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum PutOutcome {
134    /// The record was written: either nothing was held, or it won the merge.
135    ///
136    /// One outcome rather than two, because nothing downstream treats "stored"
137    /// differently from "replaced": both mean the node now holds this state.
138    Changed,
139    /// The held record is the same authenticated state. Nothing was written.
140    ///
141    /// This is the case that keeps one payment from funding many writes: an
142    /// owner can produce unboundedly many valid signatures over one state, and
143    /// every one of them lands here.
144    Unchanged,
145    /// The incoming record lost under the merge rule. Nothing was written.
146    Stale,
147}
148
149/// What the store has done since it was opened, for telemetry.
150#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
151pub struct PointerStoreStats {
152    /// Records written, whether new or replacing an older state.
153    pub written: u64,
154    /// Arrivals that carried the state already held. Nothing was written.
155    pub unchanged: u64,
156    /// Arrivals that lost to the state already held. Nothing was written.
157    pub stale: u64,
158    /// Records served to a reader.
159    pub served: u64,
160    /// Records removed because this node stopped being responsible for them.
161    pub deleted: u64,
162}
163
164/// The live counters behind [`PointerStoreStats`].
165#[derive(Debug, Default)]
166struct Counters {
167    written: AtomicU64,
168    unchanged: AtomicU64,
169    stale: AtomicU64,
170    served: AtomicU64,
171    deleted: AtomicU64,
172}
173
174impl Counters {
175    fn count(&self, outcome: PutOutcome) {
176        let counter = match outcome {
177            PutOutcome::Changed => &self.written,
178            PutOutcome::Unchanged => &self.unchanged,
179            PutOutcome::Stale => &self.stale,
180        };
181        counter.fetch_add(1, Ordering::Relaxed);
182    }
183
184    fn snapshot(&self) -> PointerStoreStats {
185        PointerStoreStats {
186            written: self.written.load(Ordering::Relaxed),
187            unchanged: self.unchanged.load(Ordering::Relaxed),
188            stale: self.stale.load(Ordering::Relaxed),
189            served: self.served.load(Ordering::Relaxed),
190            deleted: self.deleted.load(Ordering::Relaxed),
191        }
192    }
193}
194
195/// The result of [`PointerStore::inspect`]: what an arrival claims, before any
196/// signature has been checked.
197#[derive(Debug)]
198pub(crate) enum Inspected {
199    /// The node already holds exactly this state. No signature check is owed:
200    /// a resubmission of what was paid for and a forgery of it are the same
201    /// no-op.
202    Unchanged(PointerState),
203    /// The arrival loses to what is held, so it changes nothing either.
204    Stale(PointerState),
205    /// The arrival would win as it stands. Its signature has **not** been
206    /// checked yet — pass it to [`PointerStore::verify`] once admission gates
207    /// have had their say.
208    Candidate(ParsedPointer),
209}
210
211/// What the store knows about a held record without reading it back.
212#[derive(Debug, Clone, Copy)]
213struct IndexEntry {
214    /// The held record's authenticated state.
215    ///
216    /// The state itself rather than fields copied out of it, so the merge order
217    /// the store applies is the protocol's own rule applied to the held state,
218    /// and cannot drift from it.
219    state: PointerState,
220    /// Whether the file behind `state` is still there and still that record.
221    ///
222    /// A read that finds it gone or different clears this rather than dropping
223    /// the entry. The node stops serving the record, because it does not have
224    /// it — but it still knows what it had, and that is what lets the state be
225    /// restored. Dropping the entry would leave the address looking untouched,
226    /// where any record is admissible, so a replay of an older state could roll
227    /// the node back.
228    on_disk: bool,
229    /// Which insertion this entry is.
230    ///
231    /// Monotonic for the life of this store, so an entry can be told apart
232    /// from a later one carrying the same `state_id`. Without it a repair that
233    /// restores exactly the state a reader found corrupt would be
234    /// indistinguishable from the corrupt entry that reader set out to disown,
235    /// and a second reader would erase the repair. Reuse would take 2^64
236    /// commits without a restart, and an observation never outlives the store
237    /// that produced it, so a restart resetting the counter is harmless.
238    generation: u64,
239}
240
241impl IndexEntry {
242    /// Describe a validated record.
243    fn of(record: &Pointer, generation: u64) -> Self {
244        Self::held(record.state(), generation)
245    }
246
247    /// Describe a record held on disk in `state`.
248    const fn held(state: PointerState, generation: u64) -> Self {
249        Self {
250            state,
251            on_disk: true,
252            generation,
253        }
254    }
255}
256
257/// A store of pointer records.
258#[derive(Debug, Clone)]
259pub struct PointerStore {
260    inner: Arc<Inner>,
261}
262
263/// Shared state behind [`PointerStore`].
264#[derive(Debug)]
265struct Inner {
266    /// Directory holding one file per record.
267    dir: PathBuf,
268    /// What is held, by address.
269    ///
270    /// Guarded by a synchronous lock held across the disk write, so the index
271    /// and the directory can never disagree about which version is current.
272    /// The critical section is one ~5 KB write, and it is only ever taken
273    /// inside a blocking task.
274    index: Mutex<HashMap<XorName, IndexEntry>>,
275    /// Distinguishes concurrent temporary files so two writers to one address
276    /// cannot land in the same partial file.
277    write_seq: AtomicU64,
278    /// Source of index generations, monotonic for this store's lifetime.
279    generation: AtomicU64,
280    /// What the store has done, for telemetry.
281    counters: Counters,
282    /// Every record a recent update replaced (see [`Superseded`]).
283    superseded: Mutex<Superseded>,
284    /// Held for the store's lifetime; releasing it releases the directory.
285    _lock_file: File,
286}
287
288impl PointerStore {
289    /// Open a store under `root_dir`, rebuilding its index from disk.
290    ///
291    /// Takes an exclusive lock on the directory. Two stores over one directory
292    /// would each keep their own index, and the one with the staler view would
293    /// happily overwrite the other's newer record.
294    ///
295    /// A file that does not parse as a valid pointer, or that is not at the
296    /// address its owner derives, is skipped and logged rather than deleted: a
297    /// store that prunes what it cannot read destroys the evidence of its own
298    /// bug.
299    ///
300    /// # Errors
301    ///
302    /// Returns [`Error::Storage`] if the directory cannot be created, locked or
303    /// read.
304    pub async fn new(root_dir: &Path) -> Result<Self> {
305        let dir = root_dir.join(POINTERS_DIR_NAME);
306        let scan_dir = dir.clone();
307        let (lock_file, index) = spawn_blocking(move || {
308            std::fs::create_dir_all(&scan_dir).map_err(|e| {
309                Error::Storage(format!("cannot create {}: {e}", scan_dir.display()))
310            })?;
311            let lock_file = acquire_lock(&scan_dir)?;
312            create_shards(&scan_dir)?;
313            let index = scan(&scan_dir)?;
314            Ok::<_, Error>((lock_file, index))
315        })
316        .await
317        .map_err(|e| Error::Storage(format!("pointer store scan panicked: {e}")))??;
318
319        let next_generation = index
320            .values()
321            .map(|entry| entry.generation)
322            .max()
323            .map_or(0, |highest| highest.saturating_add(1));
324        debug!(
325            "Pointer store opened at {} with {} records",
326            dir.display(),
327            index.len()
328        );
329        Ok(Self {
330            inner: Arc::new(Inner {
331                dir,
332                index: Mutex::new(index),
333                write_seq: AtomicU64::new(0),
334                generation: AtomicU64::new(next_generation),
335                counters: Counters::default(),
336                superseded: Mutex::new(HashMap::new()),
337                _lock_file: lock_file,
338            }),
339        })
340    }
341
342    /// Parse an arrival and decide whether it could change anything, without
343    /// verifying its signature.
344    ///
345    /// Cheap checks first: an arrival that cannot change anything is refused
346    /// before its signature is looked at, because it is a no-op whether or not
347    /// it is correctly signed. That ordering is what stops repeated submission
348    /// of one paid state from buying ML-DSA verifications. Callers that gate on
349    /// admission — capacity, responsibility for the address — run this first,
350    /// apply their
351    /// gates, and only then pay for [`Self::verify`]. Otherwise a forged record
352    /// for an address the node is not responsible for still buys an ML-DSA
353    /// verification before anything rejects it.
354    ///
355    /// # Errors
356    ///
357    /// Returns [`Error::Protocol`] if the bytes are not a well-formed record.
358    pub(crate) async fn inspect(&self, bytes: &[u8]) -> Result<Inspected> {
359        // Off the executor: deciding this reads the held record back off the
360        // disk, and a flood of arrivals must not put a blocking read on a
361        // runtime worker for each one.
362        let store = self.clone();
363        let bytes = bytes.to_vec();
364        spawn_blocking(move || store.inspect_blocking(&bytes))
365            .await
366            .map_err(|e| Error::Storage(format!("pointer inspection panicked: {e}")))?
367    }
368
369    /// The body of [`Self::inspect`], on a blocking thread.
370    fn inspect_blocking(&self, bytes: &[u8]) -> Result<Inspected> {
371        // Parsing decodes the owner key once; `verify` reuses that parse rather
372        // than decoding again. The bytes travel with it, so the two cannot be
373        // mismatched.
374        let parsed = ParsedPointer::parse(bytes.to_vec())?;
375        let state = *parsed.state();
376
377        // Both early answers below assert that this node holds something at
378        // least as good as what arrived, so neither may be given on the index's
379        // word alone.
380        if let Some(held) = self.held_state(&state.address) {
381            if held.state_id == state.state_id {
382                self.inner.counters.count(PutOutcome::Unchanged);
383                return Ok(Inspected::Unchanged(state));
384            }
385            if !state.replaces(&held) {
386                self.inner.counters.count(PutOutcome::Stale);
387                return Ok(Inspected::Stale(state));
388            }
389        }
390        Ok(Inspected::Candidate(parsed))
391    }
392
393    /// Verify a candidate's signature.
394    ///
395    /// Runs with no lock held and off the async executor: an ML-DSA
396    /// verification is milliseconds of CPU, and an attacker can ask for one per
397    /// forged record, so it must not run on a thread other work needs.
398    ///
399    /// # Errors
400    ///
401    /// Returns [`Error::Crypto`] if the signature does not verify.
402    pub(crate) async fn verify(&self, parsed: ParsedPointer) -> Result<Pointer> {
403        spawn_blocking(move || Pointer::verify_parsed(parsed))
404            .await
405            .map_err(|e| Error::Storage(format!("pointer verification panicked: {e}")))?
406            .map_err(Into::into)
407    }
408
409    /// Commit a prepared record.
410    ///
411    /// Re-checks against what is held before writing: `prepare` may have run
412    /// before a payment check that took long enough for a newer state to
413    /// arrive, and the re-check is what keeps that newer state from being
414    /// overwritten.
415    ///
416    /// `reservation` is the disk charge for this write, taken before the call.
417    /// It moves into the blocking transaction rather than staying with the
418    /// caller, because the caller's future can be dropped while that
419    /// transaction runs on: a charge released here would leave the file that
420    /// landed a moment later uncounted.
421    ///
422    /// # Errors
423    ///
424    /// Returns [`Error::Storage`] if the write fails.
425    pub(crate) async fn commit(
426        &self,
427        record: Pointer,
428        reservation: Option<Reservation>,
429    ) -> Result<PutOutcome> {
430        let inner = Arc::clone(&self.inner);
431        // The whole transaction runs in one task, so dropping this future
432        // cannot leave the write done and the index un-updated.
433        let outcome = spawn_blocking(move || inner.commit_blocking(&record, reservation))
434            .await
435            .map_err(|e| Error::Storage(format!("pointer commit panicked: {e}")))??;
436        self.inner.counters.count(outcome);
437        Ok(outcome)
438    }
439
440    /// Validate and store in one step, with no payment gate.
441    ///
442    /// For callers that have already settled payment, and for tests. The
443    /// request path runs the same three steps with its admission and payment
444    /// gates between them.
445    ///
446    /// # Errors
447    ///
448    /// As the three steps it runs: a malformed record, a signature that does
449    /// not verify, or a write that fails.
450    pub async fn put_bytes(&self, bytes: &[u8]) -> Result<PutOutcome> {
451        match self.inspect(bytes).await? {
452            Inspected::Unchanged(_) => Ok(PutOutcome::Unchanged),
453            Inspected::Stale(_) => Ok(PutOutcome::Stale),
454            Inspected::Candidate(parsed) => {
455                let record = self.verify(parsed).await?;
456                self.commit(record, None).await
457            }
458        }
459    }
460
461    /// Read the record held at `address`, if any.
462    ///
463    /// Re-validates on the way out: the signature is checked and the record
464    /// must belong at the address asked for, so a file corrupted under the node
465    /// is reported as missing rather than served as authentic, and the entry is
466    /// disowned so the node will take a fresh copy instead of answering
467    /// "unchanged" to its own repair.
468    ///
469    /// The file is what is served, not the index. A file replaced under the
470    /// node by a *different* record that is genuinely signed for this address
471    /// is served as held — it is a real record, the reader verifies it, and the
472    /// read quorum is what decides between replicas that disagree. What the
473    /// index is not allowed to do is claim a state the file does not have —
474    /// that check guards `inspect`'s two early answers, the ones that
475    /// assert this node already holds something.
476    ///
477    /// # Errors
478    ///
479    /// Returns [`Error::Storage`] if the file cannot be read for a reason other
480    /// than its absence.
481    pub async fn get(&self, address: &XorName) -> Result<Option<Pointer>> {
482        // What the index claimed before the read. A commit can land while the
483        // read is in flight, and its entry must not then be mistaken for the
484        // stale one this read is about to disown.
485        let claimed = self.snapshot(address).map(|entry| entry.generation);
486
487        let path = self.path_for(address);
488        // Reading and verifying happen in one blocking task: an ML-DSA check is
489        // milliseconds of CPU and must not run on an async worker thread.
490        let read = spawn_blocking(move || {
491            read_record_file(&path).map(|bytes| bytes.map(|bytes| Pointer::from_bytes(&bytes)))
492        })
493        .await
494        .map_err(|e| Error::Storage(format!("pointer read panicked: {e}")))?;
495
496        let validated = match read {
497            Ok(Some(validated)) => validated,
498            Ok(None) => {
499                self.disown_if_unchanged(address, claimed);
500                return Ok(None);
501            }
502            Err(e) => return Err(e),
503        };
504
505        match validated {
506            Ok(record) if record.address() == *address => {
507                self.inner.counters.served.fetch_add(1, Ordering::Relaxed);
508                Ok(Some(record))
509            }
510            Ok(_) => {
511                warn!(
512                    "Pointer file at {} holds a record for another address; dropping it \
513                     from the index",
514                    hex::encode(address)
515                );
516                self.disown_if_unchanged(address, claimed);
517                Ok(None)
518            }
519            Err(e) => {
520                warn!(
521                    "Pointer file at {} does not validate ({e}); dropping it from the index",
522                    hex::encode(address)
523                );
524                self.disown_if_unchanged(address, claimed);
525                Ok(None)
526            }
527        }
528    }
529
530    /// The authenticated-state identifier held at `address`, if any.
531    ///
532    /// This is what a sync hint carries and what a fetch decision compares. It
533    /// names the state, not the encoding, so two replicas holding one state
534    /// under different signatures agree and do not refetch each other forever.
535    #[must_use]
536    pub fn state_id(&self, address: &XorName) -> Option<XorName> {
537        self.snapshot(address)
538            .filter(|entry| entry.on_disk)
539            .map(|entry| entry.state.state_id)
540    }
541
542    /// The record the last update at `address` replaced, within the last
543    /// [`SUPERSEDED_RETENTION`], if any. See [`Self::superseded_all`] for
544    /// every one kept.
545    #[must_use]
546    pub fn superseded(&self, address: &XorName) -> Option<Vec<u8>> {
547        self.superseded_all(address)
548            .into_iter()
549            .next()
550            .map(|bytes| bytes.to_vec())
551    }
552
553    /// Every record updates at `address` replaced within the last
554    /// [`SUPERSEDED_RETENTION`], newest first: what a storage audit that bound
555    /// one of them before the updates is still owed (ADR-0019).
556    #[must_use]
557    pub fn superseded_all(&self, address: &XorName) -> Vec<Bytes> {
558        self.inner
559            .superseded
560            .lock()
561            .get(address)
562            .map(|kept| {
563                kept.iter()
564                    .rev()
565                    .filter(|(at, _)| at.elapsed() < SUPERSEDED_RETENTION)
566                    .map(|(_, bytes)| bytes.clone())
567                    .collect()
568            })
569            .unwrap_or_default()
570    }
571
572    /// Forget every replaced record older than [`SUPERSEDED_RETENTION`].
573    ///
574    /// Updates do this as they keep a record; this is for when none come, so
575    /// memory goes back within a pass of the retention running out rather
576    /// than at the next update, which may never come.
577    pub fn drop_expired_superseded(&self) {
578        drop_expired(&mut self.inner.superseded.lock(), Instant::now());
579    }
580
581    /// The bytes of the record held at `address`, read from disk without
582    /// verifying them.
583    ///
584    /// For a caller that only binds the bytes and has them verified later, by
585    /// whoever they are served to: verifying here would cost a signature check
586    /// per record for nothing.
587    ///
588    /// # Errors
589    ///
590    /// Returns [`Error::Storage`] if the file exists but cannot be read.
591    pub async fn record_bytes(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
592        let path = self.path_for(address);
593        spawn_blocking(move || read_record_file(&path))
594            .await
595            .map_err(|e| Error::Storage(format!("pointer read panicked: {e}")))?
596    }
597
598    /// The state held at `address`, as the index records it, if this node can
599    /// serve one.
600    ///
601    /// What a peer asking "which state do you hold?" is told. Taken from the
602    /// index rather than the file, so answering costs no disk read; a file lost
603    /// since is caught by the first read, which stops the index claiming it.
604    #[must_use]
605    pub fn state(&self, address: &XorName) -> Option<PointerState> {
606        self.snapshot(address)
607            .filter(|entry| entry.on_disk)
608            .map(|entry| entry.state)
609    }
610
611    /// Whether a paid PUT of `state` may be taken.
612    ///
613    /// Any state the merge rule prefers to what is held, whatever its counter.
614    /// The counter orders states; it does not meter them, since each state is
615    /// paid for on its own. That is also what lets a node catch up: a write
616    /// ends once its quorum has answered, so a node can miss an update, and one
617    /// that joins the group later holds nothing at all. Either takes the next
618    /// update, however far ahead of it that is.
619    ///
620    /// A record this node knew and lost admits the lost state itself as well,
621    /// so the arrival that restores it is not mistaken for a resubmission. It
622    /// admits nothing older, so a node that lost its copy cannot be rolled
623    /// back by a replay.
624    #[must_use]
625    pub fn admits(&self, state: &PointerState) -> bool {
626        self.snapshot(&state.address).is_none_or(|entry| {
627            state.replaces(&entry.state)
628                || (!entry.on_disk && state.state_id == entry.state.state_id)
629        })
630    }
631
632    /// Whether a record is held at `address`.
633    #[must_use]
634    pub fn contains(&self, address: &XorName) -> bool {
635        self.snapshot(address).is_some_and(|entry| entry.on_disk)
636    }
637
638    /// How many records the store holds.
639    #[must_use]
640    pub fn len(&self) -> usize {
641        self.inner
642            .index
643            .lock()
644            .values()
645            .filter(|entry| entry.on_disk)
646            .count()
647    }
648
649    /// Whether the store holds nothing.
650    #[must_use]
651    pub fn is_empty(&self) -> bool {
652        self.len() == 0
653    }
654
655    /// Directory holding the records.
656    #[must_use]
657    pub fn dir(&self) -> &Path {
658        &self.inner.dir
659    }
660
661    /// The file the record at `address` is kept in.
662    #[must_use]
663    pub fn file_for(&self, address: &XorName) -> PathBuf {
664        self.path_for(address)
665    }
666
667    /// Every state this node can serve, sorted by address.
668    ///
669    /// Taken from the index, which every other answer the store gives is also
670    /// based on. A record whose file has gone is left out: it is not something
671    /// this node can offer to anyone.
672    #[must_use]
673    pub fn held_states(&self) -> Vec<PointerState> {
674        let mut states: Vec<PointerState> = self
675            .inner
676            .index
677            .lock()
678            .values()
679            .filter(|entry| entry.on_disk)
680            .map(|entry| entry.state)
681            .collect();
682        states.sort_unstable_by_key(|state| state.address);
683        states
684    }
685
686    /// What the store has done since it was opened.
687    #[must_use]
688    pub fn stats(&self) -> PointerStoreStats {
689        self.inner.counters.snapshot()
690    }
691
692    /// Remove the record at `address` and forget it entirely.
693    ///
694    /// For a node that is no longer responsible for the address. Unlike a
695    /// record lost to the disk, nothing about it is remembered, because the
696    /// node is not meant to take it back. Returns whether a file was removed,
697    /// so the caller can give its space back to the disk budget.
698    ///
699    /// # Errors
700    ///
701    /// Returns [`Error::Storage`] if the file exists and cannot be removed; the
702    /// record is then still held and still indexed.
703    pub async fn delete(&self, address: &XorName) -> Result<bool> {
704        let inner = Arc::clone(&self.inner);
705        let address = *address;
706        let removed = spawn_blocking(move || inner.delete_blocking(&address))
707            .await
708            .map_err(|e| Error::Storage(format!("pointer delete panicked: {e}")))??;
709        if removed {
710            self.inner.counters.deleted.fetch_add(1, Ordering::Relaxed);
711        }
712        Ok(removed)
713    }
714
715    /// The state this node can actually serve at `address`, having read it
716    /// back.
717    ///
718    /// The index is a claim about a file; this is that claim checked. The file
719    /// must still be there and must still be the record the index names —
720    /// comparing the state, not merely the address, because the disk and the
721    /// index are updated under one lock and an answer taken between the two
722    /// would otherwise describe a record that is no longer the one held.
723    ///
724    /// Only the structure is parsed: these bytes verified when they were
725    /// committed, and the question here is what is held, not whether it is
726    /// authentic. Corruption inside the signature therefore passes here — the
727    /// state is read from the body — and is caught by [`Self::get`], which
728    /// verifies and disowns. Checking it here instead would put an ML-DSA
729    /// verification in front of the payment gate, which is the one place it
730    /// must not be. A failed check disowns the entry, so the arrival that found
731    /// it becomes a repair.
732    fn held_state(&self, address: &XorName) -> Option<PointerState> {
733        let entry = self.snapshot(address).filter(|entry| entry.on_disk)?;
734        let serves = matches!(
735            read_record_file(&self.path_for(address)),
736            Ok(Some(ref bytes)) if matches!(
737                PointerState::parse(bytes),
738                Ok(ref state) if *state == entry.state
739            )
740        );
741        if !serves {
742            self.disown_if_unchanged(address, Some(entry.generation));
743            return None;
744        }
745        Some(entry.state)
746    }
747
748    /// Copy out what is held for `address`, releasing the index lock at once.
749    fn snapshot(&self, address: &XorName) -> Option<IndexEntry> {
750        self.inner.index.lock().get(address).copied()
751    }
752
753    /// Stop serving `address`, but only if the entry is still the exact one
754    /// the caller found unreadable.
755    ///
756    /// The entry stays, marked as no longer on disk: what was lost is what says
757    /// which states can restore it.
758    ///
759    /// A read is not atomic with a write. Removing unconditionally would let a
760    /// slow read of a corrupt file erase the entry for a record committed while
761    /// it was reading, leaving the node holding a record it no longer
762    /// announces, commits to, or can be audited for. Matching on the generation
763    /// rather than the state identifier also covers the case where the record
764    /// written meanwhile is a *repair of the same state*, which a state
765    /// comparison could not tell apart from the entry being disowned.
766    fn disown_if_unchanged(&self, address: &XorName, claimed: Option<u64>) {
767        let Some(claimed) = claimed else {
768            // Nothing was claimed when the read began, so there is nothing this
769            // read is entitled to disown.
770            return;
771        };
772        let mut index = self.inner.index.lock();
773        if let Some(entry) = index.get_mut(address) {
774            if entry.generation == claimed {
775                entry.on_disk = false;
776            }
777        }
778    }
779
780    /// Path of the file backing `address`.
781    fn path_for(&self, address: &XorName) -> PathBuf {
782        record_path(&self.inner.dir, address)
783    }
784}
785
786impl Inner {
787    /// Keep `bytes` beside whatever else was recently replaced at `address`,
788    /// dropping what has aged out.
789    ///
790    /// Nothing is evicted to make room here: the update that replaced it may
791    /// yet fail, and a record evicted for an update that never happened would
792    /// be lost for nothing. [`Self::trim_superseded`] does that once it has.
793    fn keep_superseded(&self, address: XorName, bytes: Vec<u8>) {
794        let now = Instant::now();
795        let mut superseded = self.superseded.lock();
796        drop_expired(&mut superseded, now);
797        superseded
798            .entry(address)
799            .or_default()
800            .push_back((now, Bytes::from(bytes)));
801    }
802
803    /// Past the cap, drop the oldest kept records, wherever they are.
804    fn trim_superseded(&self) {
805        let mut superseded = self.superseded.lock();
806        let mut held: usize = superseded.values().map(VecDeque::len).sum();
807        while held > MAX_SUPERSEDED {
808            // Each address keeps its records oldest first, so the oldest
809            // anywhere is the first of one of them.
810            let Some(oldest) = superseded
811                .iter()
812                .filter_map(|(address, kept)| kept.front().map(|(at, _)| (*at, *address)))
813                .min()
814                .map(|(_, address)| address)
815            else {
816                break;
817            };
818            if let Some(kept) = superseded.get_mut(&oldest) {
819                kept.pop_front();
820                if kept.is_empty() {
821                    superseded.remove(&oldest);
822                }
823            }
824            held = held.saturating_sub(1);
825        }
826        drop(superseded);
827    }
828
829    /// Take back the record [`Self::keep_superseded`] just kept for `address`,
830    /// when the update that replaced it did not happen after all. Called under
831    /// the index lock that kept it, so nothing was kept for `address` since.
832    fn unkeep_superseded(&self, address: &XorName) {
833        let mut superseded = self.superseded.lock();
834        if let Some(kept) = superseded.get_mut(address) {
835            kept.pop_back();
836            if kept.is_empty() {
837                superseded.remove(address);
838            }
839        }
840    }
841
842    /// Remove the file and the index entry for `address` under one lock, so a
843    /// commit can never land between the two and be forgotten on disk.
844    fn delete_blocking(&self, address: &XorName) -> Result<bool> {
845        let shard = shard_dir(&self.dir, address);
846        let path = record_path(&self.dir, address);
847        let removed = {
848            let mut index = self.index.lock();
849            let removed = match std::fs::remove_file(&path) {
850                Ok(()) => true,
851                Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
852                Err(e) => {
853                    return Err(Error::Storage(format!(
854                        "cannot delete {}: {e}",
855                        path.display()
856                    )))
857                }
858            };
859            index.remove(address);
860            removed
861        };
862        if removed {
863            if let Err(e) = sync_directory(&shard) {
864                warn!(
865                    "{} is deleted, but {} could not be synced: {e}",
866                    path.display(),
867                    shard.display()
868                );
869            }
870        }
871        Ok(removed)
872    }
873
874    /// Compare, write and re-index under one lock.
875    ///
876    /// Runs entirely inside a blocking task: the lock is synchronous and is
877    /// never released between the decision and the index update, so neither
878    /// caller cancellation nor a concurrent writer can separate them.
879    // Holding the guard across the write is the point of this function, so the
880    // lint's advice to drop it earlier would reintroduce exactly the window
881    // this closes: a second writer deciding against an index that no longer
882    // describes the disk.
883    #[allow(
884        clippy::significant_drop_tightening,
885        reason = "the write must happen under the same guard as the decision"
886    )]
887    fn commit_blocking(
888        &self,
889        record: &Pointer,
890        reservation: Option<Reservation>,
891    ) -> Result<PutOutcome> {
892        let address = record.address();
893        let shard = shard_dir(&self.dir, &address);
894        let path = record_path(&self.dir, &address);
895
896        // A cheap look before doing any work. The authoritative check is the
897        // one under the lock below; this only avoids staging a file for an
898        // arrival that is already obviously a no-op.
899        if let Some(entry) = self.index.lock().get(&address).filter(|e| e.on_disk) {
900            if entry.state.state_id == record.state_id() {
901                return Ok(PutOutcome::Unchanged);
902            }
903            if !record.state().replaces(&entry.state) {
904                return Ok(PutOutcome::Stale);
905            }
906        }
907
908        // Stage and fsync the new bytes *before* taking the lock. This is the
909        // slow part — a 5 KB write plus an fsync — and holding the index lock
910        // across it would block every other address, including the cheap
911        // lookups async callers make.
912        let seq = self.write_seq.fetch_add(1, Ordering::Relaxed);
913        let temp = shard.join(format!("{TEMP_PREFIX}{}-{seq}", hex::encode(address)));
914        if let Err(failed) = stage(&temp, &record.to_bytes()) {
915            // Bytes that could not be cleaned up are still on the disk, so the
916            // charge for them stands rather than going back.
917            if failed.bytes_remain {
918                settle(reservation);
919            }
920            return Err(failed.error);
921        }
922
923        let outcome = {
924            let mut index = self.index.lock();
925
926            // Re-check: staging is not instantaneous and a newer state may
927            // have committed while it ran.
928            let replacing = index.get(&address).is_some_and(|entry| entry.on_disk);
929            let outcome = match index.get(&address) {
930                // Nothing held: any state lands.
931                None => PutOutcome::Changed,
932                // A record this node lost: the lost state itself lands, to
933                // restore it, and so does anything that replaces it, but
934                // nothing older, so an arrival verified before the loss cannot
935                // roll the node back past it (the rule `admits` states).
936                Some(entry @ IndexEntry { on_disk: false, .. }) => {
937                    if entry.state.state_id == record.state_id()
938                        || record.state().replaces(&entry.state)
939                    {
940                        PutOutcome::Changed
941                    } else {
942                        PutOutcome::Stale
943                    }
944                }
945                Some(entry) if entry.state.state_id == record.state_id() => PutOutcome::Unchanged,
946                Some(entry) if record.state().replaces(&entry.state) => PutOutcome::Changed,
947                Some(_) => PutOutcome::Stale,
948            };
949            if outcome != PutOutcome::Changed {
950                // Nothing lands, so the charge goes back — unless the staged
951                // bytes could not be removed, in which case they are still on
952                // the disk and the charge has to stand for them.
953                if std::fs::remove_file(&temp).is_err() {
954                    settle(reservation);
955                }
956                return Ok(outcome);
957            }
958
959            // What this replaces, read under the lock so it is the record the
960            // index names. Kept for an audit that bound it, and kept before
961            // the rename makes the new record visible, so a round 2 reading
962            // the new record always finds the old one kept beside it. A record
963            // that cannot be read is not kept, and an audit owed it fails as
964            // it would have on the lost file.
965            let mut kept = false;
966            if replacing {
967                if let Some(previous) = read_record_file(&path).ok().flatten() {
968                    self.keep_superseded(address, previous);
969                    kept = true;
970                }
971            }
972
973            // The rename is the commit point: nothing fallible happens between
974            // it and the index update, and both are under this one lock.
975            if let Err(e) = rename_with_retry(&temp, &path) {
976                // Nothing was replaced, so nothing replaced is kept.
977                if kept {
978                    self.unkeep_superseded(&address);
979                }
980                if std::fs::remove_file(&temp).is_err() {
981                    settle(reservation);
982                }
983                return Err(Error::Storage(format!(
984                    "cannot rename {} onto {}: {e}",
985                    temp.display(),
986                    path.display()
987                )));
988            }
989            if kept {
990                self.trim_superseded();
991            }
992            let generation = self.generation.fetch_add(1, Ordering::Relaxed);
993            index.insert(address, IndexEntry::of(record, generation));
994            // A file is on the disk now. Charge it whether or not this replaced
995            // one: telling those apart would mean trusting an observation taken
996            // before the rename, and that observation can be wrong in the one
997            // direction that matters — a file the index claims can be gone, so
998            // what looks like a replacement grows the disk after all.
999            // Over-counting corrects itself at the next measurement.
1000            settle(reservation);
1001            outcome
1002        };
1003
1004        // Durability of the directory entry, after the commit and outside the
1005        // lock. The record is already stored and indexed, so a failure here
1006        // cannot be reported as "nothing happened"; it is logged instead, which
1007        // is how an operator learns the filesystem is not giving the store what
1008        // it asks for.
1009        if let Err(e) = sync_directory(&shard) {
1010            warn!(
1011                "{} is stored and indexed, but {} could not be synced: {e}. It is \
1012                 visible now; its survival across a power loss depends on the \
1013                 filesystem",
1014                path.display(),
1015                shard.display()
1016            );
1017        }
1018        Ok(outcome)
1019    }
1020}
1021
1022/// Take the exclusive lock that grants use of `dir`.
1023fn acquire_lock(dir: &Path) -> Result<File> {
1024    let path = dir.join(LOCK_FILE_NAME);
1025    let file = OpenOptions::new()
1026        .write(true)
1027        .create(true)
1028        .truncate(false)
1029        .open(&path)
1030        .map_err(|e| {
1031            Error::Storage(format!(
1032                "cannot create the pointer store lock {}: {e}",
1033                path.display()
1034            ))
1035        })?;
1036    file.try_lock_exclusive().map_err(|e| {
1037        Error::Storage(format!(
1038            "another pointer store already has {} open ({e}). Two stores over one \
1039             directory each keep their own index, and the staler one would overwrite \
1040             the other's newer record",
1041            dir.display()
1042        ))
1043    })?;
1044    Ok(file)
1045}
1046
1047/// Read one record file, refusing anything that is not exactly a record long.
1048///
1049/// The length is taken from the directory entry before any bytes are read, so a
1050/// corrupt oversized file cannot be pulled into memory.
1051fn read_record_file(path: &Path) -> Result<Option<Vec<u8>>> {
1052    let file = match File::open(path) {
1053        Ok(file) => file,
1054        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1055        Err(e) => return Err(Error::Storage(format!("pointer read failed: {e}"))),
1056    };
1057    let len = file
1058        .metadata()
1059        .map_err(|e| Error::Storage(format!("pointer stat failed: {e}")))?
1060        .len();
1061    if len != POINTER_WIRE_LEN as u64 {
1062        warn!(
1063            "Pointer file {} is {len} bytes, not {POINTER_WIRE_LEN}",
1064            path.display()
1065        );
1066        return Ok(None);
1067    }
1068
1069    let mut bytes = Vec::with_capacity(POINTER_WIRE_LEN);
1070    // One byte past the record: a file that grew between the stat and the read
1071    // is refused rather than silently truncated into something that parses.
1072    file.take(POINTER_WIRE_LEN as u64 + 1)
1073        .read_to_end(&mut bytes)
1074        .map_err(|e| Error::Storage(format!("pointer read failed: {e}")))?;
1075    if bytes.len() != POINTER_WIRE_LEN {
1076        warn!(
1077            "Pointer file {} changed size while being read",
1078            path.display()
1079        );
1080        return Ok(None);
1081    }
1082    Ok(Some(bytes))
1083}
1084
1085/// Create the shard directories, so a write never has to.
1086fn create_shards(dir: &Path) -> Result<()> {
1087    for shard in 0..SHARD_COUNT {
1088        let path = dir.join(format!("{shard:02x}"));
1089        std::fs::create_dir_all(&path)
1090            .map_err(|e| Error::Storage(format!("cannot create {}: {e}", path.display())))?;
1091    }
1092    sync_directory(dir)
1093}
1094
1095/// Rebuild the index from the records in `dir`'s shards.
1096///
1097/// Each record's structure is parsed, but its signature is not checked. Every
1098/// record was verified when it was committed, and every read verifies it again
1099/// before serving it, so a file damaged in place is caught — and disowned — the
1100/// first time anyone asks for it. Checking an ML-DSA signature per record here
1101/// instead would make opening a large store take minutes, and the chunk store
1102/// likewise opens on names alone.
1103///
1104/// A record left at the top level by the flat layout earlier builds used is
1105/// moved into its shard.
1106fn scan(dir: &Path) -> Result<HashMap<XorName, IndexEntry>> {
1107    let entries = std::fs::read_dir(dir)
1108        .map_err(|e| Error::Storage(format!("cannot read {}: {e}", dir.display())))?;
1109
1110    let mut index = HashMap::new();
1111    for entry in entries {
1112        let entry = match entry {
1113            Ok(entry) => entry,
1114            Err(e) => {
1115                warn!("Skipping unreadable pointer directory entry: {e}");
1116                continue;
1117            }
1118        };
1119        let path = entry.path();
1120        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
1121            continue;
1122        };
1123        if name == LOCK_FILE_NAME {
1124            continue;
1125        }
1126        if path.is_dir() {
1127            if name.len() == 2 && name.bytes().all(|b| b.is_ascii_hexdigit()) {
1128                scan_shard(&path, &mut index);
1129            }
1130            continue;
1131        }
1132        adopt_flat_record(dir, &path, name, &mut index);
1133    }
1134    Ok(index)
1135}
1136
1137/// Index the records in one shard directory.
1138fn scan_shard(shard: &Path, index: &mut HashMap<XorName, IndexEntry>) {
1139    let entries = match std::fs::read_dir(shard) {
1140        Ok(entries) => entries,
1141        Err(e) => {
1142            warn!("Skipping unreadable pointer shard {}: {e}", shard.display());
1143            return;
1144        }
1145    };
1146    for entry in entries {
1147        let entry = match entry {
1148            Ok(entry) => entry,
1149            Err(e) => {
1150                warn!("Skipping unreadable pointer directory entry: {e}");
1151                continue;
1152            }
1153        };
1154        let path = entry.path();
1155        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
1156            continue;
1157        };
1158        if name.starts_with(TEMP_PREFIX) {
1159            // A temporary file means a crash mid-write: the rename never
1160            // happened, so the old record (if any) is intact and the partial
1161            // file has no claim. Sweep it, or the next write to that address
1162            // collides with it — `create_new` would refuse, and the write
1163            // sequence restarts at zero on every opening.
1164            if let Err(e) = std::fs::remove_file(&path) {
1165                warn!(
1166                    "Could not sweep the partial pointer write {}: {e}",
1167                    path.display()
1168                );
1169            }
1170            continue;
1171        }
1172        let Some(state) = parse_record_file(&path) else {
1173            continue;
1174        };
1175        let in_its_shard = shard
1176            .file_name()
1177            .and_then(|n| n.to_str())
1178            .is_some_and(|n| n == shard_name(&state.address));
1179        if hex::encode(state.address) != name || !in_its_shard {
1180            warn!(
1181                "Skipping pointer file {} that is not at its own address",
1182                path.display()
1183            );
1184            continue;
1185        }
1186        let generation = u64::try_from(index.len()).unwrap_or(u64::MAX);
1187        index.insert(state.address, IndexEntry::held(state, generation));
1188    }
1189}
1190
1191/// Move a record from the flat layout into its shard and index it.
1192fn adopt_flat_record(
1193    dir: &Path,
1194    path: &Path,
1195    name: &str,
1196    index: &mut HashMap<XorName, IndexEntry>,
1197) {
1198    if name.starts_with(TEMP_PREFIX) {
1199        if let Err(e) = std::fs::remove_file(path) {
1200            warn!(
1201                "Could not sweep the partial pointer write {}: {e}",
1202                path.display()
1203            );
1204        }
1205        return;
1206    }
1207    let Some(state) = parse_record_file(path) else {
1208        return;
1209    };
1210    if hex::encode(state.address) != name {
1211        warn!(
1212            "Skipping pointer file {} that is not at its own address",
1213            path.display()
1214        );
1215        return;
1216    }
1217    let target = record_path(dir, &state.address);
1218    if let Err(e) = rename_with_retry(path, &target) {
1219        warn!(
1220            "Could not move pointer file {} into its shard: {e}",
1221            path.display()
1222        );
1223        return;
1224    }
1225    let generation = u64::try_from(index.len()).unwrap_or(u64::MAX);
1226    index.insert(state.address, IndexEntry::held(state, generation));
1227}
1228
1229/// Read a record file and parse its structure, logging anything unusable.
1230fn parse_record_file(path: &Path) -> Option<PointerState> {
1231    let bytes = match read_record_file(path) {
1232        Ok(Some(bytes)) => bytes,
1233        Ok(None) => return None,
1234        Err(e) => {
1235            warn!("Skipping unreadable pointer file {}: {e}", path.display());
1236            return None;
1237        }
1238    };
1239    match PointerState::parse(&bytes) {
1240        Ok(state) => Some(state),
1241        Err(e) => {
1242            warn!("Skipping invalid pointer file {}: {e}", path.display());
1243            None
1244        }
1245    }
1246}
1247
1248/// Write `bytes` to `temp` and fsync it, ready to be renamed into place.
1249///
1250/// Leaves nothing half written: the bytes are durable in the temporary file
1251/// before any rename can make them visible. The caller performs the rename,
1252/// which is the commit point.
1253///
1254/// A failure tries to remove what it wrote, and says whether that worked:
1255/// `Err(StagingFailed { bytes_remain })` reports a partial file still on the
1256/// disk, so the caller knows the charge for it cannot be given back.
1257fn stage(temp: &Path, bytes: &[u8]) -> std::result::Result<(), StagingFailed> {
1258    // `create_new` so a leftover temporary file from a crashed write is never
1259    // silently appended to or shared with a concurrent writer.
1260    let mut file = OpenOptions::new()
1261        .write(true)
1262        .create_new(true)
1263        .open(temp)
1264        .map_err(|e| StagingFailed {
1265            // Nothing was created, so nothing is left behind.
1266            error: Error::Storage(format!("cannot create {}: {e}", temp.display())),
1267            bytes_remain: false,
1268        })?;
1269    let written = file
1270        .write_all(bytes)
1271        .and_then(|()| file.sync_all())
1272        .map_err(|e| Error::Storage(format!("cannot write {}: {e}", temp.display())));
1273    drop(file);
1274    if let Err(error) = written {
1275        // A partial file exists. If it cannot be removed it is still occupying
1276        // the disk, and its charge has to stand for it.
1277        return Err(StagingFailed {
1278            error,
1279            bytes_remain: std::fs::remove_file(temp).is_err(),
1280        });
1281    }
1282    Ok(())
1283}
1284
1285/// A staged write that did not complete, and whether it left bytes behind.
1286struct StagingFailed {
1287    /// What went wrong, for the caller to return.
1288    error: Error,
1289    /// Whether a partial file is still on the disk.
1290    bytes_remain: bool,
1291}
1292
1293/// Turn a charge into bytes that are now on the disk.
1294///
1295/// A charge that is simply dropped is released instead, which is what every
1296/// path that writes nothing wants.
1297fn settle(reservation: Option<Reservation>) {
1298    if let Some(reservation) = reservation {
1299        reservation.commit();
1300    }
1301}
1302
1303/// Flush the directory entry a rename created.
1304///
1305/// Without it a crash can leave the entry unflushed and the record invisible on
1306/// restart.
1307#[cfg(unix)]
1308fn sync_directory(dir: &Path) -> Result<()> {
1309    match File::open(dir) {
1310        Ok(handle) => handle
1311            .sync_all()
1312            .map_err(|e| Error::Storage(format!("cannot sync {}: {e}", dir.display()))),
1313        Err(e) => Err(Error::Storage(format!(
1314            "cannot open {} to flush it: {e}",
1315            dir.display()
1316        ))),
1317    }
1318}
1319
1320/// As above, where there is no such thing to ask for.
1321///
1322/// A directory cannot be opened as a file on Windows without backup semantics,
1323/// so the Unix form fails on every write there — which is not a durability
1324/// warning, it is the wrong question. NTFS orders the rename's own metadata.
1325#[cfg(not(unix))]
1326#[allow(clippy::unnecessary_wraps, reason = "one signature for both platforms")]
1327fn sync_directory(_dir: &Path) -> Result<()> {
1328    Ok(())
1329}
1330
1331#[cfg(test)]
1332#[allow(
1333    clippy::unwrap_used,
1334    clippy::expect_used,
1335    clippy::panic,
1336    reason = "test assertions"
1337)]
1338mod tests {
1339    use super::*;
1340    use ant_protocol::pointer::{PointerTarget, PointerTargetKind, POINTER_BODY_LEN};
1341    use saorsa_pqc::api::sig::{ml_dsa_65, MlDsaPublicKey, MlDsaSecretKey};
1342    use std::future::Future;
1343
1344    fn keypair(seed: u8) -> (MlDsaPublicKey, MlDsaSecretKey) {
1345        ml_dsa_65().generate_keypair_from_seed(&[seed; 32])
1346    }
1347
1348    fn signed(seed: u8, counter: u64, target_byte: u8) -> Pointer {
1349        let (pk, sk) = keypair(seed);
1350        let target = PointerTarget::new(PointerTargetKind::Chunk, [target_byte; 32]);
1351        Pointer::sign(&sk, &pk, counter, target).expect("sign")
1352    }
1353
1354    /// A record with its signature destroyed: the body still parses, the
1355    /// record does not verify.
1356    fn forged(record: &Pointer) -> Vec<u8> {
1357        let mut bytes = record.to_bytes();
1358        if let Some(byte) = bytes.get_mut(POINTER_BODY_LEN + 3) {
1359            *byte ^= 0xff;
1360        }
1361        assert!(
1362            Pointer::from_bytes(&bytes).is_err(),
1363            "the forged record must not verify"
1364        );
1365        bytes
1366    }
1367
1368    async fn store() -> (PointerStore, tempfile::TempDir) {
1369        let dir = tempfile::tempdir().expect("tempdir");
1370        let store = PointerStore::new(dir.path()).await.expect("open store");
1371        (store, dir)
1372    }
1373
1374    /// The record an update replaces stays servable for a while, byte for
1375    /// byte, so an audit that bound it before the update is not failed by it.
1376    #[tokio::test]
1377    async fn an_update_keeps_the_record_it_replaced_for_a_while() {
1378        let (store, _dir) = store().await;
1379        let first = signed(1, 1, 1);
1380        store.put_bytes(&first.to_bytes()).await.expect("put");
1381        assert!(
1382            store.superseded_all(&first.address()).is_empty(),
1383            "a creation replaces nothing"
1384        );
1385
1386        let second = signed(1, 2, 2);
1387        assert_eq!(
1388            store.put_bytes(&second.to_bytes()).await.expect("put"),
1389            PutOutcome::Changed
1390        );
1391        assert_eq!(
1392            store.superseded_all(&first.address()),
1393            vec![Bytes::from(first.to_bytes())],
1394            "the replaced record, exactly as it was held"
1395        );
1396        assert_eq!(
1397            store.record_bytes(&first.address()).await.expect("read"),
1398            Some(second.to_bytes()),
1399            "and the new one is what is held"
1400        );
1401
1402        // A stale arrival replaces nothing, so it keeps nothing.
1403        store.put_bytes(&first.to_bytes()).await.expect("put");
1404        assert_eq!(
1405            store.superseded_all(&first.address()),
1406            vec![Bytes::from(first.to_bytes())]
1407        );
1408
1409        // A later update keeps the one before it too, newest first: an audit
1410        // may have bound either.
1411        let third = signed(1, 3, 3);
1412        store.put_bytes(&third.to_bytes()).await.expect("put");
1413        assert_eq!(
1414            store.superseded_all(&first.address()),
1415            vec![
1416                Bytes::from(second.to_bytes()),
1417                Bytes::from(first.to_bytes())
1418            ]
1419        );
1420        assert_eq!(
1421            store.superseded(&first.address()),
1422            Some(second.to_bytes()),
1423            "the earlier accessor still answers with the record last replaced"
1424        );
1425    }
1426
1427    /// Past the cap the oldest record kept goes first, whichever address it
1428    /// is for, and an address whose last record goes is forgotten.
1429    /// Keeping a record evicts nothing: an update that then fails takes back
1430    /// what it kept and leaves every other kept record where it was.
1431    #[tokio::test]
1432    async fn a_record_kept_for_an_update_that_fails_costs_no_other_record() {
1433        let (store, _dir) = store().await;
1434        let (owed, failing) = ([1u8; 32], [2u8; 32]);
1435        store.inner.keep_superseded(owed, vec![1]);
1436        for i in 0..MAX_SUPERSEDED - 1 {
1437            store
1438                .inner
1439                .keep_superseded(failing, (i as u64).to_le_bytes().to_vec());
1440        }
1441        // The cap is full. The next update keeps its record first ...
1442        store.inner.keep_superseded(failing, vec![0xFF]);
1443        // ... and its rename fails, so it takes that record back.
1444        store.inner.unkeep_superseded(&failing);
1445        assert_eq!(
1446            store.superseded_all(&owed),
1447            vec![Bytes::from(vec![1])],
1448            "the record an audit may be owed is still kept"
1449        );
1450        assert_eq!(store.superseded_all(&failing).len(), MAX_SUPERSEDED - 1);
1451    }
1452
1453    /// A replaced record past its retention is forgotten even if no update
1454    /// comes to do it.
1455    #[tokio::test]
1456    async fn expired_replaced_records_are_dropped_without_another_update() {
1457        let (store, _dir) = store().await;
1458        let old = Instant::now()
1459            .checked_sub(SUPERSEDED_RETENTION + Duration::from_secs(1))
1460            .expect("the clock is past one retention");
1461        store
1462            .inner
1463            .superseded
1464            .lock()
1465            .insert([3u8; 32], VecDeque::from([(old, Bytes::from(vec![3]))]));
1466        store.inner.keep_superseded([4u8; 32], vec![4]);
1467        store.drop_expired_superseded();
1468        assert!(
1469            store.superseded_all(&[3u8; 32]).is_empty()
1470                && !store.inner.superseded.lock().contains_key(&[3u8; 32]),
1471            "the expired record is gone"
1472        );
1473        assert!(
1474            store.inner.superseded.lock().contains_key(&[4u8; 32]),
1475            "a fresh one stays"
1476        );
1477    }
1478
1479    #[tokio::test]
1480    async fn past_the_cap_the_oldest_replaced_record_anywhere_goes_first() {
1481        let (store, _dir) = store().await;
1482        let (first, second) = ([1u8; 32], [2u8; 32]);
1483        let keep = |address: XorName, bytes: Vec<u8>| {
1484            store.inner.keep_superseded(address, bytes);
1485            store.inner.trim_superseded();
1486        };
1487        keep(first, vec![1]);
1488        for i in 0..MAX_SUPERSEDED - 1 {
1489            keep(second, (i as u64).to_le_bytes().to_vec());
1490        }
1491        assert_eq!(store.superseded_all(&first), vec![Bytes::from(vec![1])]);
1492        assert_eq!(store.superseded_all(&second).len(), MAX_SUPERSEDED - 1);
1493
1494        // One more: the first address held the oldest record, so it goes.
1495        keep(second, vec![0xFF]);
1496        let evicted = store.superseded_all(&first);
1497        assert!(
1498            evicted.is_empty(),
1499            "expected the oldest address evicted, got {evicted:?}"
1500        );
1501        assert!(!store.inner.superseded.lock().contains_key(&first));
1502        assert_eq!(store.superseded_all(&second).len(), MAX_SUPERSEDED);
1503
1504        // And the next goes from the front of the second address's history.
1505        keep(first, vec![2]);
1506        let kept = store.superseded_all(&second);
1507        assert_eq!(kept.len(), MAX_SUPERSEDED - 1);
1508        assert_eq!(kept.first(), Some(&Bytes::from(vec![0xFF])), "newest first");
1509        assert_eq!(
1510            kept.last(),
1511            Some(&Bytes::from(1u64.to_le_bytes().to_vec())),
1512            "the oldest of them went"
1513        );
1514    }
1515
1516    #[tokio::test]
1517    async fn stores_then_reads_back_the_same_bytes() {
1518        let (store, _dir) = store().await;
1519        let record = signed(1, 1, 1);
1520        assert_eq!(
1521            store.put_bytes(&record.to_bytes()).await.expect("put"),
1522            PutOutcome::Changed
1523        );
1524
1525        let read = store
1526            .get(&record.address())
1527            .await
1528            .expect("get")
1529            .expect("present");
1530        assert_eq!(read.to_bytes(), record.to_bytes());
1531        assert_eq!(store.state_id(&record.address()), Some(record.state_id()));
1532        assert!(store.contains(&record.address()));
1533        assert_eq!(store.len(), 1);
1534    }
1535
1536    #[tokio::test]
1537    async fn a_higher_counter_replaces_and_a_lower_one_does_not() {
1538        let (store, _dir) = store().await;
1539        let first = signed(1, 1, 1);
1540        let second = signed(1, 2, 1);
1541        assert_eq!(
1542            store.put_bytes(&first.to_bytes()).await.expect("put"),
1543            PutOutcome::Changed
1544        );
1545        assert_eq!(
1546            store.put_bytes(&second.to_bytes()).await.expect("put"),
1547            PutOutcome::Changed
1548        );
1549        assert_eq!(
1550            store.put_bytes(&first.to_bytes()).await.expect("put"),
1551            PutOutcome::Stale
1552        );
1553
1554        let held = store
1555            .get(&first.address())
1556            .await
1557            .expect("get")
1558            .expect("present");
1559        assert_eq!(held.counter(), 2);
1560        assert_eq!(store.len(), 1, "an update replaces in place");
1561    }
1562
1563    #[tokio::test]
1564    async fn re_signing_one_state_never_reaches_the_disk() {
1565        // One payment must not fund many writes. Every re-signature of a stored
1566        // state is a no-op, so storage, replication and commitment work is paid
1567        // for once.
1568        let (store, _dir) = store().await;
1569        let first = signed(1, 5, 5);
1570        store.put_bytes(&first.to_bytes()).await.expect("put");
1571
1572        let path = store.file_for(&first.address());
1573        let held_bytes = std::fs::read(&path).expect("read");
1574
1575        for _ in 0..16 {
1576            let variant = signed(1, 5, 5);
1577            assert_ne!(
1578                variant.to_bytes(),
1579                first.to_bytes(),
1580                "signing is randomized"
1581            );
1582            assert_eq!(variant.state_id(), first.state_id());
1583            assert_eq!(
1584                store.put_bytes(&variant.to_bytes()).await.expect("put"),
1585                PutOutcome::Unchanged
1586            );
1587        }
1588
1589        assert_eq!(
1590            std::fs::read(&path).expect("read"),
1591            held_bytes,
1592            "not one of the 16 re-signatures reached the disk"
1593        );
1594    }
1595
1596    #[tokio::test]
1597    async fn a_resubmission_is_refused_before_its_signature_is_checked() {
1598        // An arrival that cannot change anything is a no-op whether or not it
1599        // is correctly signed, so it must not buy an ML-DSA verification. A
1600        // record whose signature is destroyed proves the check was skipped:
1601        // had it run, this would have been an error rather than Unchanged.
1602        let (store, _dir) = store().await;
1603        let held = signed(1, 4, 4);
1604        store.put_bytes(&held.to_bytes()).await.expect("put");
1605
1606        assert_eq!(
1607            store.put_bytes(&forged(&held)).await.expect("put"),
1608            PutOutcome::Unchanged
1609        );
1610
1611        let after = store
1612            .get(&held.address())
1613            .await
1614            .expect("get")
1615            .expect("present");
1616        assert_eq!(after.to_bytes(), held.to_bytes(), "nothing was written");
1617    }
1618
1619    #[tokio::test]
1620    async fn a_stale_arrival_is_refused_before_its_signature_is_checked() {
1621        let (store, _dir) = store().await;
1622        store
1623            .put_bytes(&signed(1, 9, 1).to_bytes())
1624            .await
1625            .expect("put");
1626
1627        // Unsigned *and* stale: refused as Stale, which can only happen if the
1628        // signature was never checked.
1629        let older = signed(1, 2, 1);
1630        assert_eq!(
1631            store.put_bytes(&forged(&older)).await.expect("put"),
1632            PutOutcome::Stale
1633        );
1634    }
1635
1636    #[tokio::test]
1637    async fn a_would_be_winner_is_always_verified() {
1638        // Losing records skip verification; a record that would win never does.
1639        let (store, _dir) = store().await;
1640        store
1641            .put_bytes(&signed(1, 1, 1).to_bytes())
1642            .await
1643            .expect("put");
1644
1645        let winner = signed(1, 5, 1);
1646        assert!(store.put_bytes(&forged(&winner)).await.is_err());
1647
1648        let held = store
1649            .get(&winner.address())
1650            .await
1651            .expect("get")
1652            .expect("present");
1653        assert_eq!(held.counter(), 1, "the forged winner did not land");
1654    }
1655
1656    #[tokio::test]
1657    async fn an_arrival_that_changes_nothing_is_not_a_candidate() {
1658        let (store, _dir) = store().await;
1659        let held = signed(1, 6, 6);
1660        store.put_bytes(&held.to_bytes()).await.expect("put");
1661
1662        match store.inspect(&held.to_bytes()).await.expect("inspect") {
1663            Inspected::Unchanged(_) => (),
1664            other => panic!("an identical state is not a candidate, got {other:?}"),
1665        }
1666        match store
1667            .inspect(&signed(1, 1, 6).to_bytes())
1668            .await
1669            .expect("inspect")
1670        {
1671            Inspected::Stale(_) => (),
1672            other => panic!("a stale record is not a candidate, got {other:?}"),
1673        }
1674    }
1675
1676    #[tokio::test]
1677    async fn a_verified_record_exposes_what_a_payment_check_needs() {
1678        let (store, _dir) = store().await;
1679        let record = signed(1, 2, 2);
1680        let verified = verified(&store, &record).await;
1681        // A verified record is a `Pointer`, so the payment check reads the
1682        // address and state straight off it — there is no wrapper type in
1683        // between restating what it already knows.
1684        assert_eq!(verified.address(), record.address());
1685        assert_eq!(verified.state_id(), record.state_id());
1686        assert_eq!(verified.to_bytes(), record.to_bytes());
1687        assert_eq!(
1688            store.commit(verified, None).await.expect("commit"),
1689            PutOutcome::Changed
1690        );
1691        assert_eq!(store.len(), 1);
1692    }
1693
1694    #[tokio::test]
1695    async fn a_commit_that_writes_nothing_gives_its_charge_back() {
1696        // The reservation settles inside the commit transaction, so this is
1697        // where a no-op has to release it. Losing a race is the reachable way
1698        // to get there: the arrival is a candidate when it is inspected, and by
1699        // the time it commits a better state is held.
1700        //
1701        // Asserted on the guard's own counters, because "the next reservation
1702        // still succeeds" would pass just as well with the charge stranded.
1703        let (store, dir) = store().await;
1704        let chunks = crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
1705            root_dir: dir.path().to_path_buf(),
1706            verify_on_read: false,
1707            max_map_size: 0,
1708            disk_reserve: 0,
1709            migration: crate::storage::MigrationConfig::default(),
1710        })
1711        .await
1712        .expect("chunk store");
1713
1714        // Verified while nothing is held, so it is a candidate...
1715        let slow = verified(&store, &signed(1, 2, 1)).await;
1716        // ...and a better state lands before it commits.
1717        store
1718            .put_bytes(&signed(1, 7, 1).to_bytes())
1719            .await
1720            .expect("put");
1721
1722        let before = chunks.capacity_counters();
1723        let charge = chunks.reserve(POINTER_WIRE_LEN as u64).expect("reserve");
1724        assert!(
1725            chunks.capacity_counters().1 > before.1,
1726            "taking a charge must raise in-flight"
1727        );
1728
1729        assert_eq!(
1730            store.commit(slow, Some(charge)).await.expect("commit"),
1731            PutOutcome::Stale,
1732            "the newer state must stand"
1733        );
1734        assert_eq!(
1735            chunks.capacity_counters(),
1736            before,
1737            "a write that did not happen must leave both counters where it found them"
1738        );
1739    }
1740
1741    #[tokio::test]
1742    async fn a_commit_that_writes_charges_the_disk_for_it() {
1743        // The other half: bytes that land move from in-flight to written, so
1744        // the guard counts them against the reserve from then on.
1745        let (store, dir) = store().await;
1746        let chunks = crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
1747            root_dir: dir.path().to_path_buf(),
1748            verify_on_read: false,
1749            max_map_size: 0,
1750            disk_reserve: 0,
1751            migration: crate::storage::MigrationConfig::default(),
1752        })
1753        .await
1754        .expect("chunk store");
1755
1756        let record = verified(&store, &signed(1, 0, 1)).await;
1757        // Exactly one allocation charge, not merely "more than before": a
1758        // record is rounded up to the allocation unit, so an inequality would
1759        // accept one charge standing in for two writes.
1760        let one = crate::storage::ChunkStore::capacity_charge_for(POINTER_WIRE_LEN as u64);
1761        let (written_before, in_flight_before) = chunks.capacity_counters();
1762        let charge = chunks.reserve(POINTER_WIRE_LEN as u64).expect("reserve");
1763
1764        assert_eq!(
1765            store.commit(record, Some(charge)).await.expect("commit"),
1766            PutOutcome::Changed
1767        );
1768        assert_eq!(
1769            chunks.capacity_counters(),
1770            (written_before + one, in_flight_before),
1771            "the bytes that landed move from in flight to written, exactly once"
1772        );
1773
1774        // A replacement charges too: telling it apart would mean trusting an
1775        // observation taken before the rename.
1776        let update = verified(&store, &signed(1, 1, 1)).await;
1777        let charge = chunks.reserve(POINTER_WIRE_LEN as u64).expect("reserve");
1778        assert_eq!(
1779            store.commit(update, Some(charge)).await.expect("commit"),
1780            PutOutcome::Changed
1781        );
1782        assert_eq!(
1783            chunks.capacity_counters(),
1784            (written_before + 2 * one, in_flight_before)
1785        );
1786    }
1787
1788    #[tokio::test]
1789    async fn a_commit_rechecks_what_verification_saw() {
1790        // Verification runs before the payment check; a newer state can land
1791        // while that check is in flight, and must not then be overwritten.
1792        let (store, _dir) = store().await;
1793        let slow = verified(&store, &signed(1, 2, 1)).await;
1794
1795        // Someone else's newer state arrives while the payment is being checked.
1796        store
1797            .put_bytes(&signed(1, 7, 1).to_bytes())
1798            .await
1799            .expect("put");
1800
1801        assert_eq!(
1802            store.commit(slow, None).await.expect("commit"),
1803            PutOutcome::Stale,
1804            "the newer state must survive a late commit"
1805        );
1806        let held = store
1807            .get(&signed(1, 2, 1).address())
1808            .await
1809            .expect("get")
1810            .expect("present");
1811        assert_eq!(held.counter(), 7);
1812    }
1813
1814    #[tokio::test]
1815    async fn put_bytes_rejects_junk() {
1816        let (store, _dir) = store().await;
1817        assert!(store.put_bytes(b"not a pointer").await.is_err());
1818        assert!(store.put_bytes(&[]).await.is_err());
1819        assert!(store.is_empty());
1820    }
1821
1822    #[tokio::test]
1823    async fn every_rotation_of_a_delivery_reaches_one_answer() {
1824        let records = [
1825            signed(1, 1, 9),
1826            signed(1, 3, 4),
1827            signed(1, 3, 1),
1828            signed(1, 2, 8),
1829            signed(1, 3, 7),
1830        ];
1831        let address = records.first().expect("non-empty").address();
1832
1833        let mut winners = Vec::new();
1834        for rotation in 0..records.len() {
1835            let (store, _dir) = store().await;
1836            for offset in 0..records.len() {
1837                let index = (rotation + offset) % records.len();
1838                let record = records.get(index).expect("in range");
1839                store.put_bytes(&record.to_bytes()).await.expect("put");
1840            }
1841            let held = store.get(&address).await.expect("get").expect("present");
1842            winners.push(held.state_id());
1843        }
1844
1845        let distinct: std::collections::BTreeSet<&XorName> = winners.iter().collect();
1846        assert_eq!(
1847            distinct.len(),
1848            1,
1849            "every rotation converges: {winners:?}. Exhaustive permutations are \
1850             covered by the convergence property test"
1851        );
1852    }
1853
1854    #[tokio::test]
1855    async fn a_node_started_empty_reaches_the_same_answer() {
1856        let dir = tempfile::tempdir().expect("tempdir");
1857        let address;
1858        let before;
1859        {
1860            let store = PointerStore::new(dir.path()).await.expect("open");
1861            for record in [signed(1, 1, 1), signed(1, 4, 2), signed(1, 2, 3)] {
1862                store.put_bytes(&record.to_bytes()).await.expect("put");
1863            }
1864            address = signed(1, 1, 1).address();
1865            before = store.get(&address).await.expect("get").expect("present");
1866        }
1867
1868        // A fresh store over the same directory, as after a restart. The first
1869        // must be dropped: the directory lock allows only one at a time.
1870        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
1871        assert_eq!(reopened.len(), 1);
1872        let after = reopened.get(&address).await.expect("get").expect("present");
1873        assert_eq!(after.to_bytes(), before.to_bytes());
1874        assert_eq!(reopened.state_id(&address), Some(before.state_id()));
1875    }
1876
1877    #[tokio::test]
1878    async fn a_second_store_over_one_directory_is_refused() {
1879        // Two indexes over one set of files means the staler one overwrites the
1880        // fresher one's record.
1881        let dir = tempfile::tempdir().expect("tempdir");
1882        let _first = PointerStore::new(dir.path()).await.expect("open");
1883        let err = PointerStore::new(dir.path())
1884            .await
1885            .expect_err("a second store must not open the same directory");
1886        let message = format!("{err}");
1887        assert!(
1888            message.contains("another pointer store already has"),
1889            "it must be refused by the directory lock, not by something else: {message}"
1890        );
1891    }
1892
1893    #[tokio::test]
1894    async fn two_owners_occupy_two_addresses() {
1895        let (store, _dir) = store().await;
1896        let first = signed(1, 1, 1);
1897        let second = signed(2, 1, 1);
1898        assert_ne!(first.address(), second.address());
1899        store.put_bytes(&first.to_bytes()).await.expect("put");
1900        store.put_bytes(&second.to_bytes()).await.expect("put");
1901        assert_eq!(store.len(), 2);
1902    }
1903
1904    #[tokio::test]
1905    async fn a_corrupt_file_is_forgotten_so_the_record_can_be_repaired() {
1906        let (store, _dir) = store().await;
1907        let record = signed(1, 1, 1);
1908        store.put_bytes(&record.to_bytes()).await.expect("put");
1909
1910        let path = store.file_for(&record.address());
1911        let mut bytes = std::fs::read(&path).expect("read back");
1912        if let Some(byte) = bytes.get_mut(10) {
1913            *byte ^= 0xff;
1914        }
1915        std::fs::write(&path, &bytes).expect("corrupt it");
1916
1917        assert!(store.get(&record.address()).await.expect("get").is_none());
1918        assert!(
1919            !store.contains(&record.address()),
1920            "the index must not keep claiming a record the disk lost"
1921        );
1922        assert_eq!(store.state_id(&record.address()), None);
1923
1924        // The repair a peer would send is accepted rather than dismissed as
1925        // "unchanged", which is the whole point of forgetting it.
1926        assert_eq!(
1927            store.put_bytes(&record.to_bytes()).await.expect("put"),
1928            PutOutcome::Changed
1929        );
1930        assert!(store.get(&record.address()).await.expect("get").is_some());
1931    }
1932
1933    /// Run the production sequence as far as the payment gate: inspect, then
1934    /// verify the candidate it yields.
1935    async fn verified(store: &PointerStore, record: &Pointer) -> Pointer {
1936        match store.inspect(&record.to_bytes()).await.expect("inspect") {
1937            Inspected::Candidate(parsed) => store.verify(parsed).await.expect("verify"),
1938            other => panic!("expected a candidate, got {other:?}"),
1939        }
1940    }
1941
1942    #[tokio::test]
1943    async fn a_resubmission_repairs_a_record_the_disk_lost() {
1944        // "Unchanged" is an acknowledgement: the sender stops on it. If the
1945        // index still claims a record whose file has gone, answering Unchanged
1946        // would end the write while this node holds nothing.
1947        let (store, _dir) = store().await;
1948        let record = signed(1, 0, 1);
1949        store.put_bytes(&record.to_bytes()).await.expect("put");
1950
1951        // The file disappears under the node; the index has not noticed.
1952        std::fs::remove_file(store.file_for(&record.address())).expect("remove");
1953        assert!(
1954            store.contains(&record.address()),
1955            "the index still claims it"
1956        );
1957
1958        // The same state arriving again is a repair, not a no-op.
1959        assert_eq!(
1960            store.put_bytes(&record.to_bytes()).await.expect("put"),
1961            PutOutcome::Changed,
1962            "a resubmission must repair a record the disk lost"
1963        );
1964        assert!(store.get(&record.address()).await.expect("get").is_some());
1965    }
1966
1967    /// The commit itself holds the line `admits` states for a lost record, so
1968    /// an older state that reaches it without that gate, or was admitted
1969    /// before the loss, cannot roll the node back.
1970    #[tokio::test]
1971    async fn a_commit_after_a_loss_takes_nothing_older_than_what_was_lost() {
1972        let (store, _dir) = store().await;
1973        let held = signed(1, 3, 1);
1974        store.put_bytes(&held.to_bytes()).await.expect("put");
1975        std::fs::remove_file(store.file_for(&held.address())).expect("remove");
1976        assert!(store.get(&held.address()).await.expect("get").is_none());
1977
1978        assert_eq!(
1979            store
1980                .put_bytes(&signed(1, 2, 2).to_bytes())
1981                .await
1982                .expect("put"),
1983            PutOutcome::Stale,
1984            "an older state must not replace the one that was lost"
1985        );
1986        assert!(!store.contains(&held.address()), "nothing was written");
1987        assert_eq!(
1988            store.put_bytes(&held.to_bytes()).await.expect("put"),
1989            PutOutcome::Changed,
1990            "the lost state itself is restored"
1991        );
1992    }
1993
1994    #[tokio::test]
1995    async fn a_lost_record_is_restored_and_cannot_be_rolled_back() {
1996        // The node remembers what it lost. Without that the address would look
1997        // untouched, where any record is admissible, and a replay of an older
1998        // state would roll the node back.
1999        let (store, _dir) = store().await;
2000        for counter in 0..=3u64 {
2001            store
2002                .put_bytes(&signed(1, counter, 1).to_bytes())
2003                .await
2004                .expect("put");
2005        }
2006        let held = signed(1, 3, 1);
2007
2008        std::fs::remove_file(store.file_for(&held.address())).expect("remove");
2009        // A read notices the loss and stops the node answering for it.
2010        assert!(store.get(&held.address()).await.expect("get").is_none());
2011        assert!(!store.contains(&held.address()), "it is not served");
2012        assert_eq!(store.state_id(&held.address()), None);
2013
2014        // What it lost is what it will take back, and so is anything newer.
2015        assert!(
2016            store.admits(&held.state()),
2017            "the state this node lost must be admissible again"
2018        );
2019        assert!(
2020            store.admits(&signed(1, 9, 1).state()),
2021            "so must a newer state the rest of the group has moved on to"
2022        );
2023        assert!(
2024            !store.admits(&signed(1, 2, 1).state()),
2025            "but not one that loses to what was lost"
2026        );
2027
2028        assert_eq!(
2029            store.put_bytes(&held.to_bytes()).await.expect("put"),
2030            PutOutcome::Changed,
2031            "the repair must write, not be answered as unchanged"
2032        );
2033        let back = store
2034            .get(&held.address())
2035            .await
2036            .expect("get")
2037            .expect("present");
2038        assert_eq!(back.counter(), 3);
2039        assert_eq!(back.state_id(), held.state_id());
2040
2041        // Held again: any later counter is admitted, the held state is not.
2042        assert!(store.admits(&signed(1, 4, 1).state()));
2043        assert!(store.admits(&signed(1, 6, 1).state()), "a skip is admitted");
2044        assert!(
2045            !store.admits(&held.state()),
2046            "held again, so a resubmission"
2047        );
2048    }
2049
2050    #[tokio::test]
2051    async fn a_file_swapped_for_another_valid_record_is_not_answered_for() {
2052        // The index names one state; the disk holds a different, perfectly
2053        // valid one. Answering from the index would acknowledge a state this
2054        // node cannot serve.
2055        let (store, _dir) = store().await;
2056        let indexed = signed(1, 4, 1);
2057        store.put_bytes(&indexed.to_bytes()).await.expect("put");
2058
2059        let other = signed(1, 9, 1);
2060        std::fs::write(store.file_for(&indexed.address()), other.to_bytes())
2061            .expect("swap the file");
2062
2063        match store.inspect(&indexed.to_bytes()).await.expect("inspect") {
2064            Inspected::Candidate(_) => (),
2065            other => panic!("a state the node cannot serve must not be answered for: {other:?}"),
2066        }
2067    }
2068
2069    #[tokio::test]
2070    async fn a_deleted_file_is_forgotten_too() {
2071        let (store, _dir) = store().await;
2072        let record = signed(1, 1, 1);
2073        store.put_bytes(&record.to_bytes()).await.expect("put");
2074
2075        std::fs::remove_file(store.file_for(&record.address())).expect("remove");
2076        assert!(store.get(&record.address()).await.expect("get").is_none());
2077        assert!(!store.contains(&record.address()));
2078    }
2079
2080    #[tokio::test]
2081    async fn a_scan_skips_what_it_cannot_validate() {
2082        let dir = tempfile::tempdir().expect("tempdir");
2083        let record = signed(1, 1, 1);
2084        {
2085            let store = PointerStore::new(dir.path()).await.expect("open");
2086            store.put_bytes(&record.to_bytes()).await.expect("put");
2087
2088            // Junk under a plausible name, an oversized file, and a partial write.
2089            std::fs::write(store.file_for(&[9u8; 32]), b"not a pointer").expect("write junk");
2090            std::fs::write(store.file_for(&[8u8; 32]), vec![0u8; POINTER_WIRE_LEN * 4])
2091                .expect("write oversized");
2092            std::fs::write(
2093                store.file_for(&[7u8; 32]).with_file_name(".tmp-abc-0"),
2094                vec![0u8; POINTER_WIRE_LEN],
2095            )
2096            .expect("write temp");
2097        }
2098
2099        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
2100        assert_eq!(reopened.len(), 1, "only the valid record is indexed");
2101        assert!(reopened.contains(&record.address()));
2102    }
2103
2104    #[tokio::test]
2105    async fn concurrent_writers_leave_the_index_agreeing_with_the_disk() {
2106        let (store, _dir) = store().await;
2107        let address = signed(1, 0, 0).address();
2108
2109        let mut tasks = Vec::new();
2110        for counter in 1..=12u64 {
2111            let store = store.clone();
2112            let bytes = signed(1, counter, 1).to_bytes();
2113            tasks.push(tokio::spawn(async move { store.put_bytes(&bytes).await }));
2114        }
2115        for task in tasks {
2116            task.await.expect("join").expect("put");
2117        }
2118
2119        let held = store.get(&address).await.expect("get").expect("present");
2120        assert_eq!(held.counter(), 12, "the highest counter must win");
2121        assert_eq!(store.state_id(&address), Some(held.state_id()));
2122        assert_eq!(store.len(), 1);
2123
2124        // No temporary file survived the race.
2125        assert!(
2126            temporary_files(&store).is_empty(),
2127            "temporary files were left behind"
2128        );
2129    }
2130
2131    /// Every temporary file anywhere under the store.
2132    fn temporary_files(store: &PointerStore) -> Vec<PathBuf> {
2133        let mut found = Vec::new();
2134        for shard in std::fs::read_dir(store.dir()).expect("read dir").flatten() {
2135            if !shard.path().is_dir() {
2136                continue;
2137            }
2138            for entry in std::fs::read_dir(shard.path())
2139                .expect("read shard")
2140                .flatten()
2141            {
2142                if entry.file_name().to_string_lossy().starts_with(TEMP_PREFIX) {
2143                    found.push(entry.path());
2144                }
2145            }
2146        }
2147        found
2148    }
2149
2150    #[tokio::test]
2151    async fn a_record_is_kept_in_the_shard_named_by_its_last_byte() {
2152        let (store, _dir) = store().await;
2153        let record = signed(3, 0, 1);
2154        store.put_bytes(&record.to_bytes()).await.expect("put");
2155
2156        let path = store.file_for(&record.address());
2157        let last = record.address().last().copied().expect("32 bytes");
2158        assert_eq!(
2159            path.parent().expect("a shard"),
2160            store.dir().join(format!("{last:02x}"))
2161        );
2162        assert_eq!(
2163            std::fs::read(&path).expect("read"),
2164            record.to_bytes(),
2165            "the record is on disk where the store says it is"
2166        );
2167        let shards = std::fs::read_dir(store.dir())
2168            .expect("read dir")
2169            .flatten()
2170            .filter(|e| e.path().is_dir())
2171            .count();
2172        assert_eq!(shards, 256, "every shard exists before any write needs it");
2173    }
2174
2175    #[tokio::test]
2176    async fn held_states_lists_what_is_served_in_address_order() {
2177        let (store, _dir) = store().await;
2178        let records: Vec<Pointer> = (1..=5u8).map(|seed| signed(seed, 2, seed)).collect();
2179        for record in &records {
2180            store.put_bytes(&record.to_bytes()).await.expect("put");
2181        }
2182        let lost = records.first().expect("five records");
2183        std::fs::remove_file(store.file_for(&lost.address())).expect("remove");
2184        assert!(store.get(&lost.address()).await.expect("get").is_none());
2185
2186        let held = store.held_states();
2187        let mut expected: Vec<XorName> = records.iter().skip(1).map(Pointer::address).collect();
2188        expected.sort_unstable();
2189        assert_eq!(
2190            held.iter().map(|state| state.address).collect::<Vec<_>>(),
2191            expected,
2192            "sorted, and without the record whose file is gone"
2193        );
2194        for state in &held {
2195            assert_eq!(store.state_id(&state.address), Some(state.state_id));
2196        }
2197    }
2198
2199    #[tokio::test]
2200    async fn delete_removes_the_record_and_forgets_it() {
2201        let (store, _dir) = store().await;
2202        let record = signed(4, 3, 1);
2203        store.put_bytes(&record.to_bytes()).await.expect("put");
2204        let path = store.file_for(&record.address());
2205
2206        assert!(store.delete(&record.address()).await.expect("delete"));
2207        assert!(!path.exists(), "the file is gone");
2208        assert!(!store.contains(&record.address()));
2209        assert!(store.get(&record.address()).await.expect("get").is_none());
2210        // Forgotten, not remembered as lost: an older state is admissible again,
2211        // which a lost record would refuse.
2212        assert!(store.admits(&signed(4, 1, 1).state()));
2213        assert!(
2214            !store.delete(&record.address()).await.expect("delete"),
2215            "nothing left to delete"
2216        );
2217        assert_eq!(store.stats().deleted, 1);
2218
2219        // Still usable afterwards, and gone across a reopen too.
2220        store
2221            .put_bytes(&record.to_bytes())
2222            .await
2223            .expect("put again");
2224        assert!(store.contains(&record.address()));
2225        store.delete(&record.address()).await.expect("delete");
2226        let dir = store.dir().parent().expect("root").to_path_buf();
2227        drop(store);
2228        let reopened = PointerStore::new(&dir).await.expect("reopen");
2229        assert!(!reopened.contains(&record.address()));
2230    }
2231
2232    #[tokio::test]
2233    async fn stats_count_what_each_arrival_did() {
2234        let (store, _dir) = store().await;
2235        let first = signed(5, 1, 1);
2236        let newer = signed(5, 2, 1);
2237        store.put_bytes(&first.to_bytes()).await.expect("put");
2238        store.put_bytes(&newer.to_bytes()).await.expect("put");
2239        store
2240            .put_bytes(&signed(5, 2, 1).to_bytes())
2241            .await
2242            .expect("put");
2243        store.put_bytes(&first.to_bytes()).await.expect("put");
2244        store.get(&first.address()).await.expect("get");
2245
2246        assert_eq!(
2247            store.stats(),
2248            PointerStoreStats {
2249                written: 2,
2250                unchanged: 1,
2251                stale: 1,
2252                served: 1,
2253                deleted: 0,
2254            }
2255        );
2256    }
2257
2258    #[tokio::test]
2259    async fn opening_indexes_records_without_verifying_them_and_a_read_still_does() {
2260        // The scan parses structure only. A signature damaged in place is
2261        // indexed, and caught by the first read, which disowns it.
2262        let dir = tempfile::tempdir().expect("tempdir");
2263        let record = signed(6, 1, 1);
2264        let path = {
2265            let store = PointerStore::new(dir.path()).await.expect("open");
2266            store.put_bytes(&record.to_bytes()).await.expect("put");
2267            store.file_for(&record.address())
2268        };
2269        let mut bytes = std::fs::read(&path).expect("read");
2270        if let Some(byte) = bytes.get_mut(POINTER_BODY_LEN + 7) {
2271            *byte ^= 0xff;
2272        }
2273        std::fs::write(&path, &bytes).expect("damage");
2274
2275        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
2276        assert!(
2277            reopened.contains(&record.address()),
2278            "indexed on its structure"
2279        );
2280        assert!(
2281            reopened
2282                .get(&record.address())
2283                .await
2284                .expect("get")
2285                .is_none(),
2286            "never served"
2287        );
2288        assert!(
2289            !reopened.contains(&record.address()),
2290            "and disowned once read"
2291        );
2292    }
2293
2294    #[tokio::test]
2295    async fn a_record_in_the_flat_layout_is_moved_into_its_shard() {
2296        let dir = tempfile::tempdir().expect("tempdir");
2297        let record = signed(7, 4, 2);
2298        let flat = dir
2299            .path()
2300            .join(POINTERS_DIR_NAME)
2301            .join(hex::encode(record.address()));
2302        std::fs::create_dir_all(flat.parent().expect("parent")).expect("mkdir");
2303        std::fs::write(&flat, record.to_bytes()).expect("write");
2304
2305        let store = PointerStore::new(dir.path()).await.expect("open");
2306        assert!(!flat.exists(), "moved out of the top level");
2307        assert!(store.file_for(&record.address()).exists(), "into its shard");
2308        let held = store
2309            .get(&record.address())
2310            .await
2311            .expect("get")
2312            .expect("present");
2313        assert_eq!(held.state_id(), record.state_id());
2314    }
2315
2316    #[tokio::test]
2317    async fn a_cancelled_commit_leaves_the_index_agreeing_with_the_disk() {
2318        // Dropping the caller's future must not split the transaction: either
2319        // the write and the index update both happened, or neither did.
2320        let (store, _dir) = store().await;
2321        let record = signed(1, 3, 3);
2322        let prepared = verified(&store, &record).await;
2323
2324        {
2325            let committing = store.commit(prepared, None);
2326            tokio::pin!(committing);
2327            // Poll exactly once, then drop. That first poll hands the write to
2328            // a blocking thread and returns `Pending`, so the caller is always
2329            // abandoned mid-commit. A timeout would not be: on a fast machine
2330            // the commit finishes inside any timeout and the test then proves
2331            // nothing, which is how this failed on CI and passed locally.
2332            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
2333            assert!(
2334                committing.as_mut().poll(&mut cx).is_pending(),
2335                "the first poll must hand the write to a blocking task, not finish it"
2336            );
2337        }
2338
2339        // Wait for the detached task to settle rather than guessing at a
2340        // duration: poll until the disk and the index agree and stop changing.
2341        let mut settled = false;
2342        for _ in 0..200 {
2343            let on_disk = store.get(&record.address()).await.expect("get").is_some();
2344            if on_disk == store.contains(&record.address()) && on_disk {
2345                settled = true;
2346                break;
2347            }
2348            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2349        }
2350
2351        let on_disk = store.get(&record.address()).await.expect("get").is_some();
2352        let indexed = store.contains(&record.address());
2353        assert_eq!(
2354            on_disk, indexed,
2355            "the index and the disk must agree however the commit was interrupted"
2356        );
2357        assert!(
2358            settled,
2359            "the detached commit must run to completion rather than stopping half done"
2360        );
2361    }
2362
2363    #[tokio::test]
2364    async fn an_empty_store_holds_nothing() {
2365        let (store, _dir) = store().await;
2366        assert!(store.is_empty());
2367        assert_eq!(store.state_id(&[0u8; 32]), None);
2368        assert!(store.get(&[0u8; 32]).await.expect("get").is_none());
2369    }
2370
2371    #[tokio::test]
2372    async fn a_failed_read_does_not_erase_a_record_written_since() {
2373        // A read that finds the file unreadable may only disown the entry it
2374        // set out to read. A commit that lands meanwhile must survive, or the
2375        // node ends up holding a record it never announces or commits to.
2376        let (store, _dir) = store().await;
2377        let old = signed(1, 1, 1);
2378        store.put_bytes(&old.to_bytes()).await.expect("put");
2379
2380        // Simulate the interleaving: the read observed the old entry, then a
2381        // newer state was committed, and only then does the read disown what
2382        // it saw.
2383        let observed = store.snapshot(&old.address()).map(|entry| entry.generation);
2384        let new = signed(1, 2, 1);
2385        store.put_bytes(&new.to_bytes()).await.expect("put");
2386
2387        store.disown_if_unchanged(&old.address(), observed);
2388        assert_eq!(
2389            store.state_id(&new.address()),
2390            Some(new.state_id()),
2391            "the record committed during the read must still be indexed"
2392        );
2393
2394        // And the ordinary case still works: disowning what is actually there.
2395        let current = store.snapshot(&new.address()).map(|entry| entry.generation);
2396        store.disown_if_unchanged(&new.address(), current);
2397        assert!(!store.contains(&new.address()));
2398    }
2399
2400    #[tokio::test]
2401    async fn a_repair_of_the_same_state_is_not_erased_by_a_second_reader() {
2402        // Two readers observe one corrupt entry. The first disowns it, a repair
2403        // restores exactly the same logical state, and the second reader must
2404        // not then erase the repair — the state identifier alone cannot tell
2405        // the repaired entry from the corrupt one it replaced.
2406        let (store, _dir) = store().await;
2407        let record = signed(1, 1, 1);
2408        store.put_bytes(&record.to_bytes()).await.expect("put");
2409
2410        let first_reader = store
2411            .snapshot(&record.address())
2412            .map(|entry| entry.generation);
2413        let second_reader = first_reader;
2414
2415        // Reader one finds the file unreadable and disowns what it saw.
2416        store.disown_if_unchanged(&record.address(), first_reader);
2417        assert!(!store.contains(&record.address()));
2418
2419        // A peer repairs it with the very same state.
2420        assert_eq!(
2421            store.put_bytes(&record.to_bytes()).await.expect("put"),
2422            PutOutcome::Changed
2423        );
2424
2425        // Reader two, still holding its stale observation, must not erase it.
2426        store.disown_if_unchanged(&record.address(), second_reader);
2427        assert!(
2428            store.contains(&record.address()),
2429            "the repair must survive a second reader disowning the old entry"
2430        );
2431        assert_eq!(store.state_id(&record.address()), Some(record.state_id()));
2432    }
2433
2434    #[tokio::test]
2435    async fn a_leftover_partial_write_is_swept_and_does_not_block_the_next_write() {
2436        // The write sequence restarts at zero on every opening, so a temporary
2437        // file left by a crash would collide with the next write to that
2438        // address and `create_new` would refuse it.
2439        let dir = tempfile::tempdir().expect("tempdir");
2440        let record = signed(1, 1, 1);
2441        {
2442            let store = PointerStore::new(dir.path()).await.expect("open");
2443            let leftover = store
2444                .dir()
2445                .join(format!("{TEMP_PREFIX}{}-0", hex::encode(record.address())));
2446            std::fs::write(&leftover, vec![0u8; POINTER_WIRE_LEN]).expect("write leftover");
2447        }
2448
2449        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
2450        assert_eq!(
2451            reopened.put_bytes(&record.to_bytes()).await.expect("put"),
2452            PutOutcome::Changed,
2453            "a swept leftover must not block the first write to its address"
2454        );
2455    }
2456
2457    #[tokio::test]
2458    async fn holding_the_key_is_not_holding_the_state() {
2459        // The fetch decision a mutable record needs: a replica on version N
2460        // must not count as satisfied for version N+1.
2461        let (store, _dir) = store().await;
2462        let old = signed(1, 1, 1);
2463        let new = signed(1, 2, 1);
2464        store.put_bytes(&old.to_bytes()).await.expect("put");
2465
2466        assert!(store.contains(&new.address()));
2467    }
2468}