Skip to main content

ledger_engine/
coldreplay.rs

1//! Replays the state patches of cold history and checks them against the headers.
2//!
3//! The XRPLA archive carries no state trees, so the patches in its cold segments
4//! have never been compared with `AccountHash`, and nothing serves them. This
5//! does the comparison: start from the whole state at one ledger, apply each
6//! following ledger's patches, and require the rebuilt root to equal the header's
7//! `AccountHash` on every ledger. The first ledger that differs stops the replay,
8//! so everything before it is known to be good.
9//!
10//! The tree is held in memory, one `SubTree` for each slot at `LEVEL_DEPTH`, as
11//! leaf hashes and inner nodes only: the objects themselves are not kept. Only
12//! the slots a ledger changed are hashed again, on several threads when there
13//! are enough of them. Patches are read and their leaves hashed ahead, on
14//! reader threads.
15//!
16//! A checkpoint holds the leaves and the header of one ledger whose root
17//! matched. It checks itself: loaded again, its leaves must give that header's
18//! `AccountHash`, and the header must be the one in the cold history.
19
20use std::fs;
21use std::path::{Path, PathBuf};
22use std::sync::mpsc;
23
24use witness_core::ledger::{HEADER_LEN, LedgerHeader};
25
26use crate::cold::{Cold, sync_write};
27use crate::statetree::{
28    LEVEL_DEPTH, LEVEL_SLOTS, SubTree, inner_hash, level_range, level_slot, state_leaf_hash_of,
29};
30
31type Hash = [u8; 32];
32
33/// Fewer changed slots than this are hashed on the calling thread: starting
34/// threads would cost more than it saves.
35const PARALLEL_MIN: usize = 32;
36/// Ledgers each reader may run ahead.
37const READ_AHEAD: usize = 64;
38const MAGIC: &[u8; 6] = b"XWRC\x00\x01";
39
40/// The state tree during a replay.
41pub struct StateTree {
42    trees: Vec<SubTree>,
43    hashes: Vec<Hash>,
44    counts: Vec<u32>,
45    dirty: Vec<u16>,
46    /// Hash and key count of each node one level above the slots.
47    mid: Vec<(Hash, u64)>,
48    /// The same two levels above the slots, just below the root.
49    top: Vec<(Hash, u64)>,
50    tops_ready: bool,
51    objects: u64,
52    threads: usize,
53}
54
55/// A node above the slots from its 16 children, by the tree rule: zeros if
56/// empty, the one leaf if alone, else an inner node.
57fn node(children: impl Iterator<Item = (Hash, u64)>) -> (Hash, u64) {
58    let mut hashes = [[0; 32]; 16];
59    let mut total = 0;
60    let mut single = [0; 32];
61    for (i, (h, c)) in children.enumerate() {
62        hashes[i] = h;
63        total += c;
64        if c == 1 {
65            single = h;
66        }
67    }
68    match total {
69        0 => ([0; 32], 0),
70        1 => (single, 1),
71        _ => (inner_hash(&hashes), total),
72    }
73}
74
75impl std::fmt::Debug for StateTree {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("StateTree")
78            .field("objects", &self.objects)
79            .field("threads", &self.threads)
80            .finish_non_exhaustive()
81    }
82}
83
84impl Default for StateTree {
85    fn default() -> Self {
86        Self::with_threads(1)
87    }
88}
89
90impl StateTree {
91    /// An empty tree that hashes changed slots on up to `threads` threads.
92    pub fn with_threads(threads: usize) -> Self {
93        Self {
94            trees: (0..LEVEL_SLOTS)
95                .map(|s| SubTree::new(level_range(s as u16).0, LEVEL_DEPTH))
96                .collect(),
97            hashes: vec![[0; 32]; LEVEL_SLOTS],
98            counts: vec![0; LEVEL_SLOTS],
99            dirty: Vec::new(),
100            mid: vec![([0; 32], 0); LEVEL_SLOTS / 16],
101            top: vec![([0; 32], 0); 16],
102            tops_ready: false,
103            objects: 0,
104            threads: threads.clamp(1, LEVEL_SLOTS),
105        }
106    }
107
108    /// Sets an object, or removes it when `data` is empty.
109    pub fn set(&mut self, key: Hash, data: &[u8]) {
110        self.set_leaf(key, state_leaf_hash_of(data, &key));
111    }
112
113    /// Sets a key's leaf hash, or removes the key with `None`.
114    pub fn set_leaf(&mut self, key: Hash, leaf: Option<Hash>) {
115        let slot = level_slot(&key);
116        let tree = &mut self.trees[usize::from(slot)];
117        let before = tree.len();
118        tree.set(key, leaf);
119        self.objects = self.objects + tree.len() as u64 - before as u64;
120        self.dirty.push(slot);
121    }
122
123    /// Objects in the state now.
124    pub fn objects(&self) -> u64 {
125        self.objects
126    }
127
128    /// Root of the tree, hashing again only what changed since the last call:
129    /// the changed slots, and the nodes above them.
130    pub fn root(&mut self) -> Hash {
131        let mut dirty = std::mem::take(&mut self.dirty);
132        dirty.sort_unstable();
133        dirty.dedup();
134        if self.threads == 1 || dirty.len() < PARALLEL_MIN {
135            for &slot in &dirty {
136                let i = usize::from(slot);
137                self.hashes[i] = self.trees[i].hash();
138                self.counts[i] = self.trees[i].len() as u32;
139            }
140        } else {
141            // Contiguous ranges of slots, one per thread; each thread owns its
142            // range of trees, hashes and counts.
143            let per = LEVEL_SLOTS.div_ceil(self.threads);
144            std::thread::scope(|s| {
145                let ranges = self
146                    .trees
147                    .chunks_mut(per)
148                    .zip(self.hashes.chunks_mut(per))
149                    .zip(self.counts.chunks_mut(per))
150                    .enumerate();
151                for (n, ((trees, hashes), counts)) in ranges {
152                    let first = n * per;
153                    let lo = dirty.partition_point(|&d| usize::from(d) < first);
154                    let hi = dirty.partition_point(|&d| usize::from(d) < first + per);
155                    let mine = &dirty[lo..hi];
156                    if mine.is_empty() {
157                        continue;
158                    }
159                    s.spawn(move || {
160                        for &slot in mine {
161                            let i = usize::from(slot) - first;
162                            hashes[i] = trees[i].hash();
163                            counts[i] = trees[i].len() as u32;
164                        }
165                    });
166                }
167            });
168        }
169        // The two levels between the slots and the root: 256 nodes of 16
170        // slots, then 16 nodes of 16 of those. Only the ancestors of changed
171        // slots are hashed again, all of them on the first call.
172        let all: Vec<u16>;
173        let changed = if self.tops_ready {
174            &dirty
175        } else {
176            all = (0..LEVEL_SLOTS as u16).collect();
177            &all
178        };
179        let mut last = None;
180        for mid in changed.iter().map(|&s| usize::from(s) >> 4) {
181            if last != Some(mid) {
182                last = Some(mid);
183                let r = mid * 16..mid * 16 + 16;
184                self.mid[mid] = node(
185                    self.hashes[r.clone()]
186                        .iter()
187                        .zip(&self.counts[r])
188                        .map(|(h, c)| (*h, u64::from(*c))),
189                );
190            }
191        }
192        let mut last = None;
193        for top in changed.iter().map(|&s| usize::from(s) >> 8) {
194            if last != Some(top) {
195                last = Some(top);
196                self.top[top] = node(self.mid[top * 16..top * 16 + 16].iter().copied());
197            }
198        }
199        self.tops_ready = true;
200        dirty.clear();
201        self.dirty = dirty;
202        // The root is always an inner node.
203        let mut children = [[0; 32]; 16];
204        for (c, t) in children.iter_mut().zip(&self.top) {
205            *c = t.0;
206        }
207        inner_hash(&children)
208    }
209
210    /// Keys and leaf hashes of the whole state, in key order.
211    fn leaves(&self) -> impl Iterator<Item = (&Hash, &Hash)> {
212        self.trees.iter().flat_map(|t| t.leaves())
213    }
214}
215
216/// What a replay went through.
217#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
218pub struct Progress {
219    /// The last ledger whose root matched.
220    pub ledger: u32,
221    /// Object versions applied.
222    pub versions: u64,
223    /// Bytes of object data in those versions, as stored in a ledger.
224    pub bytes: u64,
225    /// Objects in the state at `ledger`.
226    pub objects: u64,
227}
228
229/// How to run a replay.
230#[derive(Debug, Clone, Default)]
231pub struct Options {
232    /// `report` is called every this many ledgers; 0 for never.
233    pub every: u32,
234    /// Threads that read patches ahead; at least one.
235    pub readers: usize,
236    /// Directory for checkpoints and how many ledgers apart they are.
237    pub checkpoint: Option<(PathBuf, u32)>,
238}
239
240/// One ledger as a reader prepares it: header, leaf changes, bytes of data.
241type Prepared = Result<(Vec<u8>, Vec<(Hash, Option<Hash>)>, u64), String>;
242
243fn prepare(cold: &Cold, seq: u32) -> Prepared {
244    let (raw, patches) = cold
245        .patches(seq)
246        .map_err(|e| format!("ledger {seq}: {e}"))?
247        .ok_or(format!("ledger {seq} is not in the cold history"))?;
248    let bytes = patches.iter().map(|(_, d)| d.len() as u64).sum();
249    let leaves = patches
250        .iter()
251        .map(|(k, d)| (*k, state_leaf_hash_of(d, k)))
252        .collect();
253    Ok((raw, leaves, bytes))
254}
255
256/// Replays `from + 1..=to` over `tree`, which holds the state at `from` with
257/// header `base`; `before` is what earlier runs did, for the counters. The
258/// error names the first ledger that doesn't hold; `Progress` in the `Err` is
259/// what did.
260pub fn replay(
261    cold: &Cold,
262    tree: &mut StateTree,
263    base: &[u8],
264    before: Progress,
265    to: u32,
266    opts: &Options,
267    mut report: impl FnMut(&Progress),
268) -> Result<Progress, (Progress, String)> {
269    let parsed = LedgerHeader::parse(base).map_err(|e| (before, e.to_string()))?;
270    let mut done = Progress {
271        ledger: parsed.sequence,
272        objects: tree.objects(),
273        ..before
274    };
275    if base.len() != HEADER_LEN {
276        return Err((done, format!("base header is {} bytes", base.len())));
277    }
278    let root = tree.root();
279    if root != parsed.account_hash {
280        return Err((
281            done,
282            format!(
283                "base ledger {}: state root {} does not match AccountHash {}",
284                parsed.sequence,
285                hex::encode_upper(root),
286                hex::encode_upper(parsed.account_hash)
287            ),
288        ));
289    }
290    let start = parsed.sequence + 1;
291    if start > to {
292        return Ok(done);
293    }
294    let readers = opts.readers.max(1);
295    std::thread::scope(|s| {
296        let mut queues = Vec::with_capacity(readers);
297        for r in 0..readers {
298            let (tx, rx) = mpsc::sync_channel::<Prepared>(READ_AHEAD);
299            queues.push(rx);
300            s.spawn(move || {
301                for seq in (start + r as u32..=to).step_by(readers) {
302                    // A closed queue means the replay stopped.
303                    if tx.send(prepare(cold, seq)).is_err() {
304                        break;
305                    }
306                }
307            });
308        }
309        let mut parent = parsed.hash();
310        for seq in start..=to {
311            let next = queues[((seq - start) as usize) % readers]
312                .recv()
313                .map_err(|_| (done, format!("ledger {seq}: reader stopped")))?;
314            let (raw, leaves, bytes) = next.map_err(|e| (done, e))?;
315            let header = LedgerHeader::parse(&raw).map_err(|e| (done, e.to_string()))?;
316            if header.sequence != seq {
317                return Err((
318                    done,
319                    format!("ledger {seq}: header says {}", header.sequence),
320                ));
321            }
322            if header.parent_hash != parent {
323                return Err((done, format!("ledger {seq}: parent hash breaks the chain")));
324            }
325            let count = leaves.len();
326            for (key, leaf) in leaves {
327                tree.set_leaf(key, leaf);
328            }
329            let root = tree.root();
330            if root != header.account_hash {
331                return Err((
332                    done,
333                    format!(
334                        "ledger {seq}: state root {} does not match AccountHash {} after {count} patches",
335                        hex::encode_upper(root),
336                        hex::encode_upper(header.account_hash)
337                    ),
338                ));
339            }
340            parent = header.hash();
341            done.versions += count as u64;
342            done.bytes += bytes;
343            done.ledger = seq;
344            done.objects = tree.objects();
345            if opts.every != 0 && seq.is_multiple_of(opts.every) {
346                report(&done);
347            }
348            if let Some((dir, every)) = &opts.checkpoint
349                && *every != 0
350                && seq.is_multiple_of(*every)
351            {
352                save(dir, tree, &raw, &done).map_err(|e| (done, e))?;
353            }
354        }
355        Ok(done)
356    })
357}
358
359fn checkpoint_path(dir: &Path, seq: u32) -> PathBuf {
360    dir.join(format!("replay-{seq:010}.xwrc"))
361}
362
363fn checkpoints(dir: &Path) -> Result<Vec<(u32, PathBuf)>, String> {
364    let mut out = Vec::new();
365    for e in fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))? {
366        let p = e.map_err(|e| e.to_string())?.path();
367        let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
368        if let Some(seq) = name
369            .strip_prefix("replay-")
370            .and_then(|n| n.strip_suffix(".xwrc"))
371            .and_then(|n| n.parse().ok())
372        {
373            out.push((seq, p));
374        }
375    }
376    out.sort();
377    Ok(out)
378}
379
380/// Writes a checkpoint for the ledger with header `raw` and keeps only the
381/// latest two.
382pub fn save(dir: &Path, tree: &StateTree, raw: &[u8], done: &Progress) -> Result<(), String> {
383    let mut out = Vec::with_capacity(MAGIC.len() + HEADER_LEN + 24 + tree.objects() as usize * 64);
384    out.extend_from_slice(MAGIC);
385    out.extend_from_slice(raw);
386    out.extend_from_slice(&done.versions.to_le_bytes());
387    out.extend_from_slice(&done.bytes.to_le_bytes());
388    out.extend_from_slice(&tree.objects().to_le_bytes());
389    for (k, h) in tree.leaves() {
390        out.extend_from_slice(k);
391        out.extend_from_slice(h);
392    }
393    sync_write(&checkpoint_path(dir, done.ledger), &out)?;
394    let all = checkpoints(dir)?;
395    for (_, p) in all.iter().rev().skip(2) {
396        fs::remove_file(p).map_err(|e| format!("{}: {e}", p.display()))?;
397    }
398    Ok(())
399}
400
401/// Reads a checkpoint into `tree`, which must be empty. Returns the header and
402/// the counters. The caller's replay then checks the root against the header.
403pub fn load(path: &Path, tree: &mut StateTree) -> Result<(Vec<u8>, Progress), String> {
404    let b = fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
405    let head = MAGIC.len() + HEADER_LEN + 24;
406    if b.len() < head || &b[..MAGIC.len()] != MAGIC {
407        return Err(format!("{}: not a replay checkpoint", path.display()));
408    }
409    let raw = b[MAGIC.len()..MAGIC.len() + HEADER_LEN].to_vec();
410    let num = |at: usize| u64::from_le_bytes(b[at..at + 8].try_into().unwrap_or([0; 8]));
411    let at = MAGIC.len() + HEADER_LEN;
412    let (versions, bytes, objects) = (num(at), num(at + 8), num(at + 16));
413    if (b.len() - head) as u64 != objects * 64 {
414        return Err(format!(
415            "{}: {} bytes of leaves for {objects} objects",
416            path.display(),
417            b.len() - head
418        ));
419    }
420    if tree.objects() != 0 {
421        return Err("checkpoint loaded into a tree that is not empty".into());
422    }
423    let mut last: Option<&[u8]> = None;
424    for leaf in b[head..].as_chunks::<64>().0 {
425        if last.is_some_and(|l| l >= &leaf[..32]) {
426            return Err(format!("{}: keys out of order", path.display()));
427        }
428        last = Some(&leaf[..32]);
429        let mut k = [0; 32];
430        let mut h = [0; 32];
431        k.copy_from_slice(&leaf[..32]);
432        h.copy_from_slice(&leaf[32..]);
433        tree.set_leaf(k, Some(h));
434    }
435    let ledger = LedgerHeader::parse(&raw)
436        .map_err(|e| e.to_string())?
437        .sequence;
438    Ok((
439        raw,
440        Progress {
441            ledger,
442            versions,
443            bytes,
444            objects,
445        },
446    ))
447}
448
449/// The latest checkpoint in `dir`, if any.
450pub fn latest(dir: &Path) -> Result<Option<PathBuf>, String> {
451    Ok(checkpoints(dir)?.pop().map(|(_, p)| p))
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457    use witness_core::shamap::{root, state_leaf_hash};
458
459    fn key(a: u8, b: u8, c: u8) -> Hash {
460        let mut k = [0u8; 32];
461        k[0] = a;
462        k[1] = b;
463        k[31] = c;
464        k
465    }
466
467    fn expected(objects: &[(Hash, Vec<u8>)]) -> Hash {
468        let mut leaves: Vec<_> = objects
469            .iter()
470            .map(|(k, d)| (*k, state_leaf_hash(d, k)))
471            .collect();
472        leaves.sort_unstable_by_key(|l| l.0);
473        root(&leaves)
474    }
475
476    /// Keys spread over many slots, from a small deterministic generator.
477    fn spread(n: usize, seed: u64) -> Vec<(Hash, Vec<u8>)> {
478        let mut x = seed;
479        (0..n)
480            .map(|i| {
481                let mut k = [0u8; 32];
482                for b in k.iter_mut() {
483                    x ^= x << 13;
484                    x ^= x >> 7;
485                    x ^= x << 17;
486                    *b = x as u8;
487                }
488                (k, vec![i as u8, (i >> 8) as u8, 7])
489            })
490            .collect()
491    }
492
493    #[test]
494    fn root_follows_changes_like_a_tree_built_from_scratch() {
495        // Keys that share slots, that share a prefix below a slot, and that are
496        // alone under a nibble at the top.
497        let mut objects = vec![
498            (key(0x10, 0x00, 1), vec![1]),
499            (key(0x10, 0x00, 2), vec![2]),
500            (key(0x10, 0x0F, 3), vec![3]),
501            (key(0x1F, 0xF0, 4), vec![4]),
502            (key(0xF0, 0x00, 5), vec![5]),
503        ];
504        let mut tree = StateTree::default();
505        for (k, d) in &objects {
506            tree.set(*k, d);
507        }
508        assert_eq!(tree.root(), expected(&objects));
509        assert_eq!(tree.objects(), 5);
510
511        // Modified.
512        objects[0].1 = vec![9];
513        tree.set(objects[0].0, &[9]);
514        assert_eq!(tree.root(), expected(&objects));
515
516        // Deleted, leaving one key under a prefix that had two.
517        let gone = objects.remove(1);
518        tree.set(gone.0, &[]);
519        assert_eq!(tree.root(), expected(&objects));
520        assert_eq!(tree.objects(), 4);
521
522        // The prefix fills again: no stale inner node may come back.
523        objects.push((gone.0, vec![7]));
524        tree.set(gone.0, &[7]);
525        assert_eq!(tree.root(), expected(&objects));
526
527        // A slot emptied entirely.
528        let last = objects.remove(3);
529        assert_eq!(last.0, key(0xF0, 0x00, 5));
530        tree.set(last.0, &[]);
531        assert_eq!(tree.root(), expected(&objects));
532    }
533
534    #[test]
535    fn a_change_is_seen_in_the_root() {
536        let mut tree = StateTree::default();
537        tree.set(key(1, 2, 3), &[1]);
538        let before = tree.root();
539        tree.set(key(1, 2, 3), &[2]);
540        assert_ne!(tree.root(), before);
541    }
542
543    #[test]
544    fn threads_give_the_same_root_as_one() {
545        let mut objects = spread(3000, 11);
546        let mut one = StateTree::with_threads(1);
547        let mut many = StateTree::with_threads(7);
548        for round in 0..4 {
549            for (k, d) in &objects {
550                one.set(*k, d);
551                many.set(*k, d);
552            }
553            let r = one.root();
554            assert_eq!(many.root(), r);
555            assert_eq!(r, expected(&objects));
556            // Change some, delete some, between rounds.
557            for (i, o) in objects.iter_mut().enumerate() {
558                if i % 3 == round {
559                    o.1.push(round as u8);
560                }
561            }
562            for (k, _) in objects.drain(..200) {
563                one.set(k, &[]);
564                many.set(k, &[]);
565            }
566        }
567        assert_eq!(many.objects(), one.objects());
568    }
569
570    #[test]
571    fn cached_upper_levels_agree_with_a_full_recount() {
572        // Few keys, so that nodes above the slots are empty, hold one leaf or
573        // several, and move between those as keys come and go.
574        let objects = spread(40, 3);
575        let mut tree = StateTree::with_threads(1);
576        let mut live: Vec<(Hash, Vec<u8>)> = Vec::new();
577        for (i, o) in objects.iter().enumerate() {
578            tree.set(o.0, &o.1);
579            live.push(o.clone());
580            if i % 3 == 2 {
581                let gone = live.remove(i % live.len());
582                tree.set(gone.0, &[]);
583            }
584            let r = tree.root();
585            assert_eq!(
586                r,
587                crate::statetree::root_of_levels(&tree.hashes, &tree.counts)
588            );
589            assert_eq!(r, expected(&live));
590        }
591        // Down to one key, then none.
592        while live.len() > 1 {
593            let gone = live.pop().unwrap();
594            tree.set(gone.0, &[]);
595            assert_eq!(tree.root(), expected(&live));
596        }
597        let last = live.pop().unwrap();
598        tree.set(last.0, &[]);
599        assert_eq!(
600            tree.root(),
601            crate::statetree::root_of_levels(&tree.hashes, &tree.counts)
602        );
603    }
604
605    #[test]
606    fn a_checkpoint_comes_back_with_the_same_root_and_counters() {
607        let dir = tempfile::tempdir().unwrap();
608        let objects = spread(500, 5);
609        let mut tree = StateTree::with_threads(3);
610        for (k, d) in &objects {
611            tree.set(*k, d);
612        }
613        let r = tree.root();
614        let mut raw = vec![0u8; HEADER_LEN];
615        raw[..4].copy_from_slice(&1234u32.to_be_bytes());
616        let done = Progress {
617            ledger: 1234,
618            versions: 99,
619            bytes: 4567,
620            objects: tree.objects(),
621        };
622        save(dir.path(), &tree, &raw, &done).unwrap();
623        let path = latest(dir.path()).unwrap().unwrap();
624        let mut back = StateTree::with_threads(2);
625        let (h, p) = load(&path, &mut back).unwrap();
626        assert_eq!(h, raw);
627        assert_eq!(p, done);
628        assert_eq!(back.root(), r);
629
630        // A changed leaf no longer gives the root.
631        let mut b = fs::read(&path).unwrap();
632        let last = b.len() - 1;
633        b[last] ^= 1;
634        fs::write(&path, &b).unwrap();
635        let mut bad = StateTree::default();
636        load(&path, &mut bad).unwrap();
637        assert_ne!(bad.root(), r);
638
639        // A cut file is refused.
640        fs::write(&path, &b[..b.len() - 10]).unwrap();
641        assert!(load(&path, &mut StateTree::default()).is_err());
642    }
643
644    #[test]
645    fn only_the_latest_two_checkpoints_stay() {
646        let dir = tempfile::tempdir().unwrap();
647        let tree = StateTree::default();
648        for seq in [10u32, 20, 30, 40] {
649            let mut raw = vec![0u8; HEADER_LEN];
650            raw[..4].copy_from_slice(&seq.to_be_bytes());
651            let done = Progress {
652                ledger: seq,
653                ..Progress::default()
654            };
655            save(dir.path(), &tree, &raw, &done).unwrap();
656        }
657        let left: Vec<u32> = checkpoints(dir.path())
658            .unwrap()
659            .into_iter()
660            .map(|c| c.0)
661            .collect();
662        assert_eq!(left, [30, 40]);
663    }
664}