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