Skip to main content

ledger_engine/
coldstate.rs

1//! Version index over cold history: for every object key, the ledgers whose
2//! state patches changed it, so that the object as of an old ledger can be read
3//! from the cold segments without a database.
4//!
5//! The object as of ledger N is the patch of the last ledger at or before N that
6//! changed its key; an empty patch means the object was deleted there. A ledger
7//! number is enough to find its cold segment (`Cold::find`), so the index keeps
8//! no pointers into segments, only ledger numbers.
9//!
10//! Layout of an index directory, written by `build`:
11//! - `bucket-XX.xver` for each first key byte `XX`: `MAGIC`, then blocks of
12//!   zstd-compressed entries sorted by key, then a directory of the blocks, then a
13//!   footer. An entry is the key (32 bytes), the number of ledgers (varint) and the
14//!   ledgers as ascending deltas (varints, the first absolute). The directory holds,
15//!   per block, its first key (32 bytes), offset (u64), stored length (u32),
16//!   decoded length (u32) and the sha256 of its stored bytes (32 bytes); the footer
17//!   holds the block count (u32), the directory offset (u64), the sha256 of the
18//!   directory (32 bytes) and `MAGIC`. All integers are little-endian.
19//! - `base.bin`: the objects of the base state at ledger `first - 1`, which the
20//!   cold patches do not carry: `MAGIC`, the base ledger (u32), the first and last
21//!   indexed cold ledger (u32 each), the count (u32), then
22//!   per object the key, the length (u32) and the bytes, in key order.
23//! - `manifest.json`, written last: format, `first` and `last` cold ledger, base
24//!   ledger, and the sha256 of every file. Without it the index does not open, so
25//!   a build that stopped half way is never read.
26//!
27//! Damage is refused, never answered: opening checks every bucket's directory
28//! against the sha256 in its footer, `base.bin` against the manifest, and the
29//! manifest's ledger range against the copy in `base.bin`; every
30//! block read checks the block against its sha256 in the directory. `verify`
31//! checks every file against the manifest in full, for use before an index is
32//! attached.
33//!
34//! The served range is from the base ledger to `last`. Building it is a single pass
35//! over the cold patches; pairs of key and ledger are held per bucket in memory and
36//! written to temporary files past `spill_after` pairs, then each bucket is sorted
37//! on its own, so memory stays bounded and the result does not depend on the
38//! threshold.
39
40use std::collections::BTreeMap;
41use std::fs::{self, File};
42use std::io::{BufReader, BufWriter, Read, Write};
43use std::os::unix::fs::FileExt;
44use std::path::Path;
45
46use serde_json::{Value, json};
47use sha2::{Digest, Sha256};
48
49use crate::cold::{Cold, sync_write};
50use crate::varint;
51
52type Hash = [u8; 32];
53type Res<T> = Result<T, String>;
54
55/// Magic and format version of every index file.
56pub const MAGIC: &[u8; 6] = b"XVER\x00\x01";
57/// Format version recorded in the manifest.
58pub const FORMAT: u64 = 1;
59const BUCKETS: usize = 256;
60const BLOCK: usize = 64 << 10;
61const MANIFEST: &str = "manifest.json";
62const BASE: &str = "base.bin";
63const FOOTER: usize = 4 + 8 + 32 + MAGIC.len();
64
65fn io(e: std::io::Error) -> String {
66    e.to_string()
67}
68
69fn corrupt(what: impl std::fmt::Display) -> String {
70    format!("corrupt_history: version index: {what}")
71}
72
73fn bucket_name(b: usize) -> String {
74    format!("bucket-{b:02x}.xver")
75}
76
77/// What to build an index of.
78#[derive(Debug)]
79pub struct Build<'a> {
80    pub cold: &'a Cold,
81    /// First and last cold ledger to index.
82    pub first: u32,
83    pub last: u32,
84    /// The whole state at ledger `first - 1`: objects the cold patches don't carry.
85    pub base: Vec<(Hash, Vec<u8>)>,
86    /// Pairs held in memory before they go to temporary files.
87    pub spill_after: usize,
88}
89
90/// A file being written: hashed as it goes, moved into place when finished.
91struct Out {
92    w: BufWriter<File>,
93    sha: Sha256,
94    len: u64,
95    tmp: std::path::PathBuf,
96    path: std::path::PathBuf,
97}
98
99impl Out {
100    fn create(path: &Path) -> Res<Out> {
101        let tmp = path.with_extension("tmp");
102        Ok(Out {
103            w: BufWriter::new(File::create(&tmp).map_err(io)?),
104            sha: Sha256::new(),
105            len: 0,
106            tmp,
107            path: path.to_path_buf(),
108        })
109    }
110    fn put(&mut self, b: &[u8]) -> Res<()> {
111        self.sha.update(b);
112        self.len += b.len() as u64;
113        self.w.write_all(b).map_err(io)
114    }
115    fn finish(self) -> Res<String> {
116        let f = self.w.into_inner().map_err(|e| e.to_string())?;
117        f.sync_all().map_err(io)?;
118        fs::rename(&self.tmp, &self.path).map_err(io)?;
119        Ok(hex::encode(self.sha.finalize()))
120    }
121}
122
123/// Writes one bucket from its pairs, sorted and without duplicates. Returns
124/// keys, versions and the file's sha256.
125fn write_bucket(path: &Path, pairs: &[(Hash, u32)]) -> Res<(u64, u64, String)> {
126    let mut out = Out::create(path)?;
127    out.put(MAGIC)?;
128    let mut dir: Vec<BlockRef> = Vec::new();
129    let mut block = Vec::with_capacity(BLOCK * 2);
130    let mut block_first: Option<Hash> = None;
131    let mut keys = 0u64;
132    let mut flush = |out: &mut Out, block: &mut Vec<u8>, first: &mut Option<Hash>| -> Res<()> {
133        let Some(k) = first.take() else {
134            return Ok(());
135        };
136        let z = zstd::bulk::compress(block, 3).map_err(io)?;
137        dir.push(BlockRef {
138            first: k,
139            off: out.len,
140            len: z.len() as u32,
141            raw: block.len() as u32,
142            sha: Sha256::digest(&z).into(),
143        });
144        out.put(&z)?;
145        block.clear();
146        Ok(())
147    };
148    let mut i = 0;
149    while i < pairs.len() {
150        let key = pairs[i].0;
151        let mut j = i;
152        while j < pairs.len() && pairs[j].0 == key {
153            j += 1;
154        }
155        if block_first.is_none() {
156            block_first = Some(key);
157        }
158        block.extend_from_slice(&key);
159        varint::put(&mut block, (j - i) as u64);
160        let mut prev = 0u32;
161        for p in &pairs[i..j] {
162            varint::put(&mut block, u64::from(p.1 - prev));
163            prev = p.1;
164        }
165        keys += 1;
166        if block.len() >= BLOCK {
167            flush(&mut out, &mut block, &mut block_first)?;
168        }
169        i = j;
170    }
171    flush(&mut out, &mut block, &mut block_first)?;
172    let dir_at = out.len;
173    let mut table = Vec::with_capacity(dir.len() * DIR_ENTRY);
174    for b in &dir {
175        table.extend_from_slice(&b.first);
176        table.extend_from_slice(&b.off.to_le_bytes());
177        table.extend_from_slice(&b.len.to_le_bytes());
178        table.extend_from_slice(&b.raw.to_le_bytes());
179        table.extend_from_slice(&b.sha);
180    }
181    out.put(&table)?;
182    out.put(&(dir.len() as u32).to_le_bytes())?;
183    out.put(&dir_at.to_le_bytes())?;
184    out.put(&Sha256::digest(&table))?;
185    out.put(MAGIC)?;
186    Ok((keys, pairs.len() as u64, out.finish()?))
187}
188
189/// Builds the index of `b` into `dir` and returns its manifest.
190pub fn build(dir: &Path, b: &Build<'_>) -> Res<Value> {
191    if b.first == 0 || b.first > b.last {
192        return Err(format!("bad range {}..={}", b.first, b.last));
193    }
194    if !b.cold.contains(b.first) || !b.cold.contains(b.last) {
195        return Err(format!(
196            "{}..={} is not in the cold history",
197            b.first, b.last
198        ));
199    }
200    let base_seq = b.first - 1;
201    fs::create_dir_all(dir).map_err(io)?;
202    let tmp = dir.join("spill");
203    fs::create_dir_all(&tmp).map_err(io)?;
204    let spill_after = b.spill_after.max(1);
205    let mut held: Vec<Vec<(Hash, u32)>> = vec![Vec::new(); BUCKETS];
206    let mut count = 0usize;
207    let mut spills: Vec<Option<BufWriter<File>>> = (0..BUCKETS).map(|_| None).collect();
208    let spill =
209        |held: &mut Vec<Vec<(Hash, u32)>>, spills: &mut Vec<Option<BufWriter<File>>>| -> Res<()> {
210            for (n, pairs) in held.iter_mut().enumerate() {
211                if pairs.is_empty() {
212                    continue;
213                }
214                if spills[n].is_none() {
215                    let f = File::create(tmp.join(format!("{n:02x}"))).map_err(io)?;
216                    spills[n] = Some(BufWriter::new(f));
217                }
218                let w = spills[n].as_mut().ok_or("spill file")?;
219                for (k, s) in pairs.drain(..) {
220                    w.write_all(&k).map_err(io)?;
221                    w.write_all(&s.to_le_bytes()).map_err(io)?;
222                }
223            }
224            Ok(())
225        };
226    let mut push = |k: Hash,
227                    s: u32,
228                    held: &mut Vec<Vec<(Hash, u32)>>,
229                    spills: &mut Vec<Option<BufWriter<File>>>|
230     -> Res<()> {
231        held[usize::from(k[0])].push((k, s));
232        count += 1;
233        if count >= spill_after {
234            spill(held, spills)?;
235            count = 0;
236        }
237        Ok(())
238    };
239    for (k, _) in &b.base {
240        push(*k, base_seq, &mut held, &mut spills)?;
241    }
242    for seq in b.first..=b.last {
243        let (_, patches) = b
244            .cold
245            .patches(seq)?
246            .ok_or(format!("ledger {seq} is not in the cold history"))?;
247        for (k, _) in patches {
248            push(k, seq, &mut held, &mut spills)?;
249        }
250    }
251    for w in spills.iter_mut().flatten() {
252        w.flush().map_err(io)?;
253    }
254    drop(spills);
255    let mut buckets = Vec::with_capacity(BUCKETS);
256    for (n, mine) in held.iter_mut().enumerate() {
257        let mut pairs = Vec::new();
258        let sp = tmp.join(format!("{n:02x}"));
259        if sp.exists() {
260            let mut r = BufReader::new(File::open(&sp).map_err(io)?);
261            let mut rec = [0u8; 36];
262            loop {
263                match r.read_exact(&mut rec) {
264                    Ok(()) => {
265                        let mut k = [0u8; 32];
266                        k.copy_from_slice(&rec[..32]);
267                        let s = u32::from_le_bytes([rec[32], rec[33], rec[34], rec[35]]);
268                        pairs.push((k, s));
269                    }
270                    Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
271                    Err(e) => return Err(io(e)),
272                }
273            }
274            fs::remove_file(&sp).map_err(io)?;
275        }
276        pairs.append(mine);
277        pairs.sort_unstable();
278        pairs.dedup();
279        let name = bucket_name(n);
280        let (keys, versions, sha) = write_bucket(&dir.join(&name), &pairs)?;
281        buckets.push(json!({"file": name, "keys": keys, "versions": versions, "sha256": sha}));
282    }
283    fs::remove_dir(&tmp).map_err(io)?;
284    let mut base = b.base.clone();
285    base.sort_unstable_by_key(|a| a.0);
286    base.dedup_by(|a, b| a.0 == b.0);
287    let mut out = Out::create(&dir.join(BASE))?;
288    out.put(MAGIC)?;
289    out.put(&base_seq.to_le_bytes())?;
290    // The range is repeated here so that the hashed file, not only the
291    // manifest, decides which ledgers the index answers for.
292    out.put(&b.first.to_le_bytes())?;
293    out.put(&b.last.to_le_bytes())?;
294    out.put(&(base.len() as u32).to_le_bytes())?;
295    for (k, d) in &base {
296        out.put(k)?;
297        out.put(&(d.len() as u32).to_le_bytes())?;
298        out.put(d)?;
299    }
300    let base_sha = out.finish()?;
301    let manifest = json!({
302        "format": FORMAT,
303        "first": b.first,
304        "last": b.last,
305        "base": base_seq,
306        "base_objects": base.len(),
307        "base_sha256": base_sha,
308        "buckets": buckets,
309    });
310    let text = serde_json::to_vec_pretty(&manifest).map_err(|e| e.to_string())?;
311    sync_write(&dir.join(MANIFEST), &text)?;
312    Ok(manifest)
313}
314
315/// Where a block lies in its bucket file and what its stored bytes hash to.
316#[derive(Debug, Clone)]
317struct BlockRef {
318    first: Hash,
319    off: u64,
320    len: u32,
321    raw: u32,
322    sha: Hash,
323}
324
325const DIR_ENTRY: usize = 32 + 8 + 4 + 4 + 32;
326
327/// One bucket file opened for reading: its block directory in memory.
328#[derive(Debug)]
329struct Bucket {
330    file: File,
331    dir: Vec<BlockRef>,
332}
333
334impl Bucket {
335    fn open(path: &Path) -> Res<Bucket> {
336        let file = File::open(path).map_err(io)?;
337        let len = file.metadata().map_err(io)?.len();
338        let mut head = [0u8; MAGIC.len()];
339        file.read_exact_at(&mut head, 0).map_err(io)?;
340        let mut foot = [0u8; FOOTER];
341        if len < (MAGIC.len() + FOOTER) as u64 {
342            return Err(corrupt("bucket too short"));
343        }
344        file.read_exact_at(&mut foot, len - FOOTER as u64)
345            .map_err(io)?;
346        if &head != MAGIC || &foot[44..] != MAGIC {
347            return Err(corrupt("bucket magic"));
348        }
349        let n = u32::from_le_bytes(foot[..4].try_into().map_err(|_| corrupt("footer"))?) as usize;
350        let at = u64::from_le_bytes(foot[4..12].try_into().map_err(|_| corrupt("footer"))?);
351        let size = n
352            .checked_mul(DIR_ENTRY)
353            .filter(|s| at.checked_add(*s as u64) == Some(len - FOOTER as u64))
354            .ok_or_else(|| corrupt("directory size"))?;
355        let mut table = vec![0u8; size];
356        file.read_exact_at(&mut table, at).map_err(io)?;
357        if Sha256::digest(&table).as_slice() != &foot[12..44] {
358            return Err(corrupt("directory does not match its sha256"));
359        }
360        let dir = table
361            .as_chunks::<DIR_ENTRY>()
362            .0
363            .iter()
364            .map(|c| {
365                let mut first = [0u8; 32];
366                first.copy_from_slice(&c[..32]);
367                let mut sha = [0u8; 32];
368                sha.copy_from_slice(&c[48..80]);
369                BlockRef {
370                    first,
371                    off: u64::from_le_bytes(c[32..40].try_into().unwrap_or_default()),
372                    len: u32::from_le_bytes(c[40..44].try_into().unwrap_or_default()),
373                    raw: u32::from_le_bytes(c[44..48].try_into().unwrap_or_default()),
374                    sha,
375                }
376            })
377            .collect();
378        Ok(Bucket { file, dir })
379    }
380
381    /// Ledgers that changed `key`, ascending; empty if it was never changed.
382    fn ledgers(&self, key: &Hash) -> Res<Vec<u32>> {
383        let Some(b) = self.dir.partition_point(|d| d.first <= *key).checked_sub(1) else {
384            return Ok(vec![]);
385        };
386        let r = &self.dir[b];
387        let mut z = vec![0u8; r.len as usize];
388        self.file.read_exact_at(&mut z, r.off).map_err(io)?;
389        if Sha256::digest(&z).as_slice() != r.sha {
390            return Err(corrupt(format!(
391                "block at offset {} does not match its sha256",
392                r.off
393            )));
394        }
395        let block = zstd::bulk::decompress(&z, r.raw as usize).map_err(io)?;
396        let mut at = 0;
397        while at < block.len() {
398            let k: Hash = block
399                .get(at..at + 32)
400                .ok_or_else(|| corrupt("entry key"))?
401                .try_into()
402                .map_err(|_| corrupt("entry key"))?;
403            at += 32;
404            let n = varint::get(&block, &mut at).map_err(corrupt)? as usize;
405            if k == *key {
406                let mut out = Vec::with_capacity(n);
407                let mut prev = 0u64;
408                for _ in 0..n {
409                    prev += varint::get(&block, &mut at).map_err(corrupt)?;
410                    out.push(u32::try_from(prev).map_err(|_| corrupt("ledger"))?);
411                }
412                return Ok(out);
413            }
414            if k > *key {
415                return Ok(vec![]);
416            }
417            for _ in 0..n {
418                varint::get(&block, &mut at).map_err(corrupt)?;
419            }
420        }
421        Ok(vec![])
422    }
423}
424
425/// An index opened for reading.
426#[derive(Debug)]
427pub struct VersionIndex {
428    first: u32,
429    last: u32,
430    base_seq: u32,
431    base: BTreeMap<Hash, Vec<u8>>,
432    buckets: Vec<Bucket>,
433}
434
435impl VersionIndex {
436    /// Opens the index in `dir`; refuses one without a manifest or with files
437    /// that don't match it.
438    pub fn open(dir: &Path) -> Res<VersionIndex> {
439        let m: Value =
440            serde_json::from_slice(&fs::read(dir.join(MANIFEST)).map_err(io)?).map_err(corrupt)?;
441        if m["format"].as_u64() != Some(FORMAT) {
442            return Err(corrupt(format!("format {}", m["format"])));
443        }
444        let num = |f: &str| -> Res<u32> {
445            m[f].as_u64()
446                .and_then(|v| u32::try_from(v).ok())
447                .ok_or_else(|| corrupt(format!("manifest field {f}")))
448        };
449        let (first, last, base_seq) = (num("first")?, num("last")?, num("base")?);
450        let list = m["buckets"].as_array().ok_or_else(|| corrupt("buckets"))?;
451        if list.len() != BUCKETS {
452            return Err(corrupt("bucket count"));
453        }
454        let mut buckets = Vec::with_capacity(BUCKETS);
455        for (n, b) in list.iter().enumerate() {
456            if b["file"].as_str() != Some(bucket_name(n).as_str()) {
457                return Err(corrupt(format!("bucket {n} file name")));
458            }
459            buckets.push(Bucket::open(&dir.join(bucket_name(n)))?);
460        }
461        let raw = fs::read(dir.join(BASE)).map_err(io)?;
462        if m["base_sha256"].as_str() != Some(hex::encode(Sha256::digest(&raw)).as_str()) {
463            return Err(corrupt("base.bin does not match the manifest"));
464        }
465        if raw.get(..MAGIC.len()) != Some(&MAGIC[..]) {
466            return Err(corrupt("base magic"));
467        }
468        let mut at = MAGIC.len();
469        let mut take = |n: usize| -> Res<&[u8]> {
470            let s = raw
471                .get(at..at + n)
472                .ok_or_else(|| corrupt("base truncated"))?;
473            at += n;
474            Ok(s)
475        };
476        let mut word = || -> Res<u32> {
477            Ok(u32::from_le_bytes(
478                take(4)?.try_into().map_err(|_| corrupt("base"))?,
479            ))
480        };
481        let (seq, f, l) = (word()?, word()?, word()?);
482        if (seq, f, l) != (base_seq, first, last)
483            || first != base_seq.wrapping_add(1)
484            || last < first
485        {
486            return Err(corrupt(
487                "ledger range in base.bin does not match the manifest",
488            ));
489        }
490        let count = u32::from_le_bytes(take(4)?.try_into().map_err(|_| corrupt("base"))?);
491        let mut base = BTreeMap::new();
492        for _ in 0..count {
493            let k: Hash = take(32)?.try_into().map_err(|_| corrupt("base key"))?;
494            let len = u32::from_le_bytes(take(4)?.try_into().map_err(|_| corrupt("base"))?);
495            base.insert(k, take(len as usize)?.to_vec());
496        }
497        Ok(VersionIndex {
498            first,
499            last,
500            base_seq,
501            base,
502            buckets,
503        })
504    }
505
506    /// Ledgers the index can answer for: the base ledger through the last
507    /// indexed cold ledger.
508    pub fn range(&self) -> (u32, u32) {
509        (self.base_seq, self.last)
510    }
511
512    /// First cold ledger in the index.
513    pub fn first(&self) -> u32 {
514        self.first
515    }
516
517    /// Ledgers that changed `key`, ascending, including the base ledger if the
518    /// object was in the base state.
519    pub fn ledgers(&self, key: &Hash) -> Res<Vec<u32>> {
520        self.buckets[usize::from(key[0])].ledgers(key)
521    }
522
523    /// The last version of `key` at or before ledger `at`: the ledger and the
524    /// object, empty if it was deleted there; `None` if it did not exist yet.
525    /// Ledgers outside `range` are refused.
526    pub fn version_at(&self, cold: &Cold, key: &Hash, at: u32) -> Res<Option<(u32, Vec<u8>)>> {
527        if at < self.base_seq || at > self.last {
528            return Err(format!(
529                "no state for ledger {at}: outside the version index {}..={}",
530                self.base_seq, self.last
531            ));
532        }
533        let ledgers = self.ledgers(key)?;
534        let Some(seq) = (match ledgers.partition_point(|&s| s <= at) {
535            0 => None,
536            n => Some(ledgers[n - 1]),
537        }) else {
538            return Ok(None);
539        };
540        if seq == self.base_seq {
541            return match self.base.get(key) {
542                Some(d) => Ok(Some((seq, d.clone()))),
543                None => Err(corrupt("base ledger listed for a key not in the base")),
544            };
545        }
546        let (_, patches) = cold
547            .patches(seq)?
548            .ok_or(format!("ledger {seq} is not in the cold history"))?;
549        let (_, data) = patches
550            .into_iter()
551            .find(|(k, _)| k == key)
552            .ok_or_else(|| corrupt(format!("ledger {seq} has no change of a key listed for it")))?;
553        Ok(Some((seq, data)))
554    }
555}
556
557/// Checks every file of the index in `dir` against the sha256 in its manifest,
558/// reading each file in full. Meant to run once before an index is attached;
559/// `open` and every read check their own parts on top of this.
560pub fn verify(dir: &Path) -> Res<()> {
561    let m: Value =
562        serde_json::from_slice(&fs::read(dir.join(MANIFEST)).map_err(io)?).map_err(corrupt)?;
563    let list = m["buckets"].as_array().ok_or_else(|| corrupt("buckets"))?;
564    if list.len() != BUCKETS {
565        return Err(corrupt("bucket count"));
566    }
567    let mut files: Vec<(String, &str)> = Vec::with_capacity(BUCKETS + 1);
568    for (n, b) in list.iter().enumerate() {
569        let sha = b["sha256"]
570            .as_str()
571            .ok_or_else(|| corrupt(format!("bucket {n} sha256")))?;
572        files.push((bucket_name(n), sha));
573    }
574    let base = m["base_sha256"]
575        .as_str()
576        .ok_or_else(|| corrupt("base_sha256"))?;
577    files.push((BASE.to_string(), base));
578    for (name, want) in files {
579        let mut f = File::open(dir.join(&name)).map_err(io)?;
580        let mut h = Sha256::new();
581        std::io::copy(&mut f, &mut h).map_err(io)?;
582        if hex::encode(h.finalize()) != want {
583            return Err(corrupt(format!("{name} does not match the manifest")));
584        }
585    }
586    Ok(())
587}
588
589/// The command-line entry: builds from a cold directory into `out` with the
590/// given base state. Same result as `build`.
591pub fn build_from_dirs(
592    cold_dir: &Path,
593    out: &Path,
594    first: u32,
595    last: u32,
596    base: Vec<(Hash, Vec<u8>)>,
597    spill_after: usize,
598) -> Res<Value> {
599    let cold = Cold::open(cold_dir)?;
600    build(
601        out,
602        &Build {
603            cold: &cold,
604            first,
605            last,
606            base,
607            spill_after,
608        },
609    )
610}
611
612#[cfg(test)]
613mod tests {
614    use super::*;
615    use crate::cold::{Kinds, write};
616    use crate::ledger::{Change, Ledger, StateChange};
617    use witness_core::ledger::LedgerHeader;
618
619    struct Rng(u64);
620    impl Rng {
621        fn step(&mut self) -> u64 {
622            self.0 ^= self.0 << 13;
623            self.0 ^= self.0 >> 7;
624            self.0 ^= self.0 << 17;
625            self.0
626        }
627    }
628
629    fn key(n: u8) -> Hash {
630        // Spread over buckets and share buckets: first byte cycles over 7 values.
631        let mut k = [n; 32];
632        k[0] = n % 7 * 37;
633        k
634    }
635
636    /// A base state at `first - 1`, `n` ledgers of creations, changes and
637    /// deletions (a key can come back after deletion), and the state after each
638    /// ledger, as the truth to compare with.
639    #[allow(clippy::type_complexity)]
640    fn history(
641        first: u32,
642        n: u32,
643    ) -> (
644        Vec<(Hash, Vec<u8>)>,
645        Vec<Ledger>,
646        Vec<BTreeMap<Hash, Vec<u8>>>,
647    ) {
648        let mut rng = Rng(0x2545_F491_4F6C_DD1D);
649        let mut state: BTreeMap<Hash, Vec<u8>> = BTreeMap::new();
650        for i in 0..10u8 {
651            state.insert(key(i), vec![0x11, 0x00, 0x61, i, 0]);
652        }
653        let base: Vec<_> = state.iter().map(|(k, v)| (*k, v.clone())).collect();
654        let mut truth = vec![state.clone()];
655        let mut ledgers = Vec::new();
656        let mut parent = [0u8; 32];
657        for s in 0..n {
658            let mut header = vec![0u8; 118];
659            header[..4].copy_from_slice(&(first + s).to_be_bytes());
660            header[12..44].copy_from_slice(&parent);
661            parent = LedgerHeader::parse(&header).unwrap().hash();
662            let mut touched = std::collections::BTreeSet::new();
663            let mut changes = Vec::new();
664            for _ in 0..1 + rng.step() % 6 {
665                let k = key((rng.step() % 40) as u8);
666                if !touched.insert(k) {
667                    continue;
668                }
669                let exists = state.contains_key(&k);
670                if exists && rng.step().is_multiple_of(4) {
671                    state.remove(&k);
672                    changes.push(StateChange {
673                        key: k,
674                        change: Change::Deleted,
675                        data: vec![],
676                    });
677                } else {
678                    let d = vec![
679                        0x11,
680                        0x00,
681                        0x61,
682                        k[1],
683                        (s % 251) as u8,
684                        (rng.step() % 256) as u8,
685                    ];
686                    state.insert(k, d.clone());
687                    let change = if exists {
688                        Change::Modified
689                    } else {
690                        Change::Created
691                    };
692                    changes.push(StateChange {
693                        key: k,
694                        change,
695                        data: d,
696                    });
697                }
698            }
699            ledgers.push(Ledger {
700                header,
701                transactions: vec![],
702                changes,
703            });
704            truth.push(state.clone());
705        }
706        (base, ledgers, truth)
707    }
708
709    fn sha_of(dir: &Path) -> String {
710        let mut h = Sha256::new();
711        let mut names: Vec<_> = fs::read_dir(dir)
712            .unwrap()
713            .map(|e| e.unwrap().file_name())
714            .collect();
715        names.sort();
716        for n in names {
717            h.update(n.to_string_lossy().as_bytes());
718            h.update(fs::read(dir.join(&n)).unwrap());
719        }
720        hex::encode(h.finalize())
721    }
722
723    const FIRST: u32 = 1001;
724    const N: u32 = 300;
725
726    #[allow(clippy::type_complexity)]
727    fn setup() -> (
728        tempfile::TempDir,
729        Cold,
730        Vec<(Hash, Vec<u8>)>,
731        Vec<BTreeMap<Hash, Vec<u8>>>,
732    ) {
733        let cold_dir = tempfile::tempdir().unwrap();
734        let (base, ledgers, truth) = history(FIRST, N);
735        write(cold_dir.path(), &ledgers, Kinds::Explicit).unwrap();
736        let cold = Cold::open(cold_dir.path()).unwrap();
737        (cold_dir, cold, base, truth)
738    }
739
740    fn build_into(dir: &Path, cold: &Cold, base: &[(Hash, Vec<u8>)], spill_after: usize) -> Value {
741        build(
742            dir,
743            &Build {
744                cold,
745                first: FIRST,
746                last: FIRST + N - 1,
747                base: base.to_vec(),
748                spill_after,
749            },
750        )
751        .unwrap()
752    }
753
754    #[test]
755    fn read_matches_patch_replay() {
756        let (_c, cold, base, truth) = setup();
757        let out = tempfile::tempdir().unwrap();
758        build_into(out.path(), &cold, &base, 1 << 20);
759        let idx = VersionIndex::open(out.path()).unwrap();
760        assert_eq!(idx.range(), (FIRST - 1, FIRST + N - 1));
761        for (i, state) in truth.iter().enumerate() {
762            let at = FIRST - 1 + i as u32;
763            for n in 0..40u8 {
764                let k = key(n);
765                let got = idx
766                    .version_at(&cold, &k, at)
767                    .unwrap()
768                    .and_then(|(_, d)| (!d.is_empty()).then_some(d));
769                assert_eq!(got.as_ref(), state.get(&k), "key {n} at ledger {at}");
770            }
771        }
772        // Outside the range: refused, not answered.
773        assert!(idx.version_at(&cold, &key(1), FIRST - 2).is_err());
774        assert!(idx.version_at(&cold, &key(1), FIRST + N).is_err());
775    }
776
777    #[test]
778    fn build_twice_same_sha256() {
779        let (_c, cold, base, _) = setup();
780        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
781        let ma = build_into(a.path(), &cold, &base, 1 << 20);
782        let mb = build_into(b.path(), &cold, &base, 1 << 20);
783        assert_eq!(ma, mb);
784        assert_eq!(sha_of(a.path()), sha_of(b.path()));
785    }
786
787    #[test]
788    fn spill_threshold_same_sha256() {
789        let (_c, cold, base, _) = setup();
790        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
791        build_into(a.path(), &cold, &base, 1 << 20);
792        // Spills to temporary files every 5 pairs.
793        build_into(b.path(), &cold, &base, 5);
794        assert_eq!(sha_of(a.path()), sha_of(b.path()));
795        assert!(!b.path().join("spill").exists());
796    }
797
798    #[test]
799    fn cli_entry_same_sha256() {
800        let (cold_dir, cold, base, _) = setup();
801        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
802        build_into(a.path(), &cold, &base, 1 << 20);
803        build_from_dirs(
804            cold_dir.path(),
805            b.path(),
806            FIRST,
807            FIRST + N - 1,
808            base.clone(),
809            1 << 20,
810        )
811        .unwrap();
812        assert_eq!(sha_of(a.path()), sha_of(b.path()));
813    }
814
815    #[test]
816    fn a_damaged_or_unfinished_index_does_not_open() {
817        let (_c, cold, base, _) = setup();
818        let out = tempfile::tempdir().unwrap();
819        build_into(out.path(), &cold, &base, 1 << 20);
820        let path = out.path().join(bucket_name(0));
821        let mut b = fs::read(&path).unwrap();
822        let n = b.len();
823        b[n - 1] ^= 1;
824        fs::write(&path, &b).unwrap();
825        assert!(VersionIndex::open(out.path()).is_err());
826        fs::remove_file(out.path().join(MANIFEST)).unwrap();
827        assert!(VersionIndex::open(out.path()).is_err());
828    }
829
830    /// The bucket whose first block has the most bytes, and that block's span.
831    fn biggest_block(dir: &Path) -> (usize, u64, u32) {
832        (0..BUCKETS)
833            .filter_map(|n| {
834                let b = Bucket::open(&dir.join(bucket_name(n))).unwrap();
835                b.dir.first().map(|d| (n, d.off, d.len))
836            })
837            .max_by_key(|x| x.2)
838            .unwrap()
839    }
840
841    #[test]
842    fn a_byte_flipped_inside_a_block_is_refused_on_read() {
843        let (_c, cold, base, _) = setup();
844        let out = tempfile::tempdir().unwrap();
845        build_into(out.path(), &cold, &base, 1 << 20);
846        verify(out.path()).unwrap();
847        let (n, off, len) = biggest_block(out.path());
848        let path = out.path().join(bucket_name(n));
849        let mut b = fs::read(&path).unwrap();
850        b[(off + u64::from(len) / 2) as usize] ^= 0x40;
851        fs::write(&path, &b).unwrap();
852        // The directory is intact, so the index opens; every read of that
853        // block fails instead of answering, and verify names the file.
854        let idx = VersionIndex::open(out.path()).unwrap();
855        let first = Bucket::open(&path).unwrap().dir[0].first;
856        let end = Bucket::open(&path).unwrap().dir.get(1).map(|d| d.first);
857        assert!(idx.ledgers(&first).unwrap_err().contains("sha256"));
858        let mut refused = 0;
859        for n2 in 0..40u8 {
860            let k = key(n2);
861            if usize::from(k[0]) == n && k >= first && end.is_none_or(|e| k < e) {
862                let e = idx.version_at(&cold, &k, FIRST + N - 1).unwrap_err();
863                assert!(e.contains("sha256"), "{e}");
864                refused += 1;
865            }
866        }
867        assert!(refused > 0);
868        assert!(verify(out.path()).unwrap_err().contains(&bucket_name(n)));
869    }
870
871    #[test]
872    fn a_changed_range_in_the_manifest_does_not_open() {
873        let (_c, cold, base, _) = setup();
874        let out = tempfile::tempdir().unwrap();
875        build_into(out.path(), &cold, &base, 1 << 20);
876        let mp = out.path().join(MANIFEST);
877        let good = fs::read_to_string(&mp).unwrap();
878        VersionIndex::open(out.path()).unwrap();
879        // One range field changed by 9: still valid JSON, and the file hashes
880        // in the manifest still match, so only the range check sees it.
881        for (field, at) in [
882            ("last", FIRST + N - 1),
883            ("first", FIRST),
884            ("base", FIRST - 1),
885        ] {
886            let mut m: Value = serde_json::from_str(&good).unwrap();
887            assert_eq!(m[field], json!(at), "{field}");
888            m[field] = json!(at + 9);
889            fs::write(&mp, serde_json::to_vec_pretty(&m).unwrap()).unwrap();
890            let e = VersionIndex::open(out.path()).unwrap_err();
891            assert!(e.contains("does not match the manifest"), "{field}: {e}");
892        }
893        fs::write(&mp, &good).unwrap();
894        VersionIndex::open(out.path()).unwrap();
895    }
896
897    #[test]
898    fn a_byte_flipped_in_the_directory_or_base_does_not_open() {
899        let (_c, cold, base, _) = setup();
900        let out = tempfile::tempdir().unwrap();
901        build_into(out.path(), &cold, &base, 1 << 20);
902        let (n, _, _) = biggest_block(out.path());
903        let path = out.path().join(bucket_name(n));
904        let good = fs::read(&path).unwrap();
905        // The directory starts right after the last block; byte 40 is inside
906        // the stored length of the first entry.
907        let b0 = Bucket::open(&path).unwrap();
908        let last = b0.dir.last().unwrap();
909        let dir_at = (last.off + u64::from(last.len)) as usize;
910        let mut b = good.clone();
911        b[dir_at + 40] ^= 1;
912        fs::write(&path, &b).unwrap();
913        assert!(VersionIndex::open(out.path()).is_err());
914        fs::write(&path, &good).unwrap();
915        VersionIndex::open(out.path()).unwrap();
916
917        let bp = out.path().join(BASE);
918        let mut raw = fs::read(&bp).unwrap();
919        let mid = raw.len() / 2;
920        raw[mid] ^= 1;
921        fs::write(&bp, &raw).unwrap();
922        assert!(
923            VersionIndex::open(out.path())
924                .unwrap_err()
925                .contains("base.bin")
926        );
927        assert!(verify(out.path()).unwrap_err().contains("base.bin"));
928    }
929}