Skip to main content

ant_node/pointer/
store.rs

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