Skip to main content

ledger_engine/
state.rs

1//! Ledger state over time: a snapshot plus object versions (fjall).
2//!
3//! Every object version is a separate record: the key is the object key (32 bytes)
4//! and the ledger sequence (4 bytes, big-endian), the value is the object after the
5//! change; an empty value means deletion. The object as of ledger N is the last
6//! version with a sequence no greater than N: one reverse step over the key's range.
7//!
8//! The starting point is a snapshot of the whole state at one ledger, then the
9//! changes of each following ledger, strictly in order and atomically. Headers of
10//! applied ledgers are stored here too; they are used to check the state
11//! root.
12//!
13//! The loader also puts the ledger itself into the same batch, as "pending", until
14//! its block is written to block storage. That gives loading a single recovery
15//! point: everything applied to the state is either already in blocks or
16//! waiting here.
17//!
18//! The same batch carries the indexes (module `index`): transaction by hash
19//! (`tx`: hash → ledger, position in the ledger), ledger by hash (`ledger_hash`) and
20//! account history (`account_tx`: account, ledger, TransactionIndex → position).
21//! History keys are big-endian, so a range scan follows the order in which
22//! transactions were applied, forward or backward.
23//!
24//! The same batch also carries the state tree (module `statetree`): the root after
25//! the ledger's changes is checked against its header's `AccountHash` before writing.
26//! If it does not match, the ledger is rejected and the state stays at the previous one.
27//!
28//! And the tree's history (`levels`): ledger → the subtrees at depth 3 that the
29//! ledger changed, as (slot u16, hash) pairs, all 4096 of them every 256
30//! ledgers. A path at an earlier ledger takes the top of the tree from there
31//! and rebuilds the subtree below from the object versions (`state_path_at`).
32//!
33//! And the NFT index (module `nftindex`), Clio's four NFT tables:
34//! `nft_owner` (token, ledger → owner and whether burned), `nft_uri` (token,
35//! ledger → URI), `nft_issuer` (issuer, taxon, token) and `nft_tx` (token,
36//! ledger, TransactionIndex → position in the ledger). Ledgers from the one
37//! the index started at are indexed as they are applied; earlier ones are
38//! filled in once, in the background (`backfill_nfts`).
39
40use fjall::{Database, Keyspace, KeyspaceCreateOptions, PersistMode};
41
42use crate::index::{AccountId, entries};
43use crate::ledger::{Change, Ledger, StateChange};
44use crate::statetree::{LEVEL_DEPTH, LEVEL_SLOTS, StateTree, leaf_changes};
45use witness_core::evidence::ValidationEvidence;
46
47const BASE: &[u8] = b"base_ledger";
48const LAST: &[u8] = b"last_ledger";
49/// Last ledger included in the indexes.
50const INDEXED: &[u8] = b"indexed_ledger";
51/// Ledger the state tree corresponds to.
52const TREE: &[u8] = b"tree_ledger";
53/// First ledger with a full set of tree levels: paths at earlier ledgers
54/// cannot be rebuilt.
55const LEVELS_FROM: &[u8] = b"levels_from";
56/// A full set of tree levels is written every this many ledgers, so a path
57/// reads at most this many ledgers of them.
58const LEVELS_EVERY: u32 = 256;
59/// Last ledger confirmed by a validator quorum (`confirm`); every ledger
60/// before it is confirmed by the chain of parent hashes.
61const CONFIRMED: &[u8] = b"confirmed_ledger";
62/// The MPT holder index has been built over all object versions (`mpt_holders`).
63const MPT_INDEXED: &[u8] = b"mpt_holders_indexed";
64/// LedgerEntryType of an MPToken object.
65const LT_MPTOKEN: u16 = 0x007F;
66/// First ledger indexed for NFTs as it was applied.
67const NFT_FROM: &[u8] = b"nft_from";
68/// First ledger of the NFT backfill, and the next one it will read.
69const NFT_FILL_FROM: &[u8] = b"nft_fill_from";
70const NFT_FILL: &[u8] = b"nft_fill";
71
72/// Transaction position: the ledger and the order within it.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
74pub struct TxPosition {
75    pub ledger: u32,
76    /// TransactionIndex from the metadata.
77    pub index: u32,
78}
79
80/// A transaction in an account's history.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct AccountTx {
83    pub at: TxPosition,
84    /// Position in the ledger's transaction list, as stored in the block.
85    pub pos: u32,
86}
87
88/// A page of account history.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct AccountTxPage {
91    pub transactions: Vec<AccountTx>,
92    /// Where to resume: the first transaction not returned; `None` if everything was returned.
93    pub marker: Option<TxPosition>,
94}
95
96fn account_key(account: &AccountId, at: TxPosition) -> [u8; 28] {
97    let mut k = [0u8; 28];
98    k[..20].copy_from_slice(account);
99    k[20..24].copy_from_slice(&at.ledger.to_be_bytes());
100    k[24..].copy_from_slice(&at.index.to_be_bytes());
101    k
102}
103
104fn be32(b: &[u8]) -> u32 {
105    u32::from_be_bytes([b[0], b[1], b[2], b[3]])
106}
107
108fn err(e: fjall::Error) -> String {
109    e.to_string()
110}
111
112/// Reads the asked ledgers, in order.
113pub type ReadLedgers<'a> = dyn Fn(&[u32]) -> Result<Vec<Ledger>, String> + 'a;
114
115/// MPT issuance and holder account.
116type Holder = ([u8; 24], [u8; 20]);
117/// MPT holder: the account and the key of its MPToken object.
118pub type MptHolder = ([u8; 20], [u8; 32]);
119
120/// Key of an MPT holder version: issuance, account, ledger.
121fn holder_key(id: &[u8; 24], acc: &[u8; 20], sequence: u32) -> [u8; 48] {
122    let mut k = [0u8; 48];
123    k[..24].copy_from_slice(id);
124    k[24..44].copy_from_slice(acc);
125    k[44..].copy_from_slice(&sequence.to_be_bytes());
126    k
127}
128
129/// Issuance and holder of an MPToken object; `None` for any other object.
130/// LedgerEntryType is the first field of an object in canonical order.
131fn mptoken_holder(data: &[u8]) -> Option<Holder> {
132    use witness_core::stobject::{self, FieldId, types};
133    if data.len() < 3 || data[0] != 0x11 || u16::from_be_bytes([data[1], data[2]]) != LT_MPTOKEN {
134        return None;
135    }
136    let fs = stobject::fields(data).ok()?;
137    let id = stobject::find(&fs, FieldId::new(types::HASH192, 1))?
138        .try_into()
139        .ok()?;
140    let acc = stobject::find(&fs, FieldId::new(types::ACCOUNT, 1))?
141        .try_into()
142        .ok()?;
143    Some((id, acc))
144}
145
146fn version_key(key: &[u8; 32], sequence: u32) -> [u8; 36] {
147    let mut k = [0u8; 36];
148    k[..32].copy_from_slice(key);
149    k[32..].copy_from_slice(&sequence.to_be_bytes());
150    k
151}
152
153/// A `levels` record: (slot u16, hash) pairs in slot order.
154fn encode_levels(level: &std::collections::BTreeMap<u16, [u8; 32]>) -> Vec<u8> {
155    let mut v = Vec::with_capacity(level.len() * 34);
156    for (slot, h) in level {
157        v.extend_from_slice(&slot.to_be_bytes());
158        v.extend_from_slice(h);
159    }
160    v
161}
162
163fn header_key(sequence: u32) -> [u8; 5] {
164    let mut k = [b'h'; 5];
165    k[1..].copy_from_slice(&sequence.to_be_bytes());
166    k
167}
168
169pub struct StateStore {
170    db: Database,
171    objects: Keyspace,
172    meta: Keyspace,
173    pending: Keyspace,
174    tx: Keyspace,
175    ledger_hash: Keyspace,
176    account_tx: Keyspace,
177    /// MPT holders: issuance (24) + account (20) + ledger → MPToken key or
178    /// empty (deleted), versioned like `objects`. Holders are ordered by
179    /// account, as in the Clio table.
180    mpt_holders: Keyspace,
181    /// MPToken key → issuance and account: used to recognize a deleted MPToken.
182    mpt_keys: Keyspace,
183    /// NFT index: token + ledger → owner (20) + burned (1).
184    nft_owner: Keyspace,
185    /// token + ledger → URI.
186    nft_uri: Keyspace,
187    /// issuer + taxon + token → nothing.
188    nft_issuer: Keyspace,
189    /// token + ledger + TransactionIndex → position in the ledger.
190    nft_tx: Keyspace,
191    tree: StateTree,
192    /// Tree history: ledger → changed subtrees at depth 3.
193    levels: Keyspace,
194    /// Anchor evidence: ledger → quorum validations (JSON).
195    evidence: Keyspace,
196    /// State before the snapshot, if a version index is attached.
197    old: std::sync::RwLock<Option<std::sync::Arc<dyn OldState>>>,
198}
199
200/// What the tree holds at a key's position.
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub enum Leaf {
203    Present(Vec<u8>),
204    Empty,
205    /// A different leaf: key and object.
206    Other([u8; 32], Vec<u8>),
207}
208
209/// Path in the state tree to a key, as of the tree's ledger.
210#[derive(Debug, Clone)]
211pub struct TreePath {
212    pub ledger: u32,
213    pub header: Vec<u8>,
214    pub path: witness_core::shamap::Path,
215    pub leaf: Leaf,
216}
217
218/// State before the snapshot, from another store: `version` with the same
219/// contract as `StateStore::version`, for ledgers in `range`.
220pub trait OldState: Send + Sync + std::fmt::Debug {
221    /// First and last ledger it can answer for.
222    fn range(&self) -> (u32, u32);
223    /// The last version of `key` at or before `at`: ledger and object, empty if
224    /// deleted there; `None` if it did not exist yet.
225    fn version(&self, key: &[u8; 32], at: u32) -> Result<Option<(u32, Vec<u8>)>, String>;
226}
227
228/// The version index over cold history and the cold segments it points into.
229#[derive(Debug)]
230pub struct ColdOldState {
231    pub index: crate::coldstate::VersionIndex,
232    pub cold: crate::cold::Cold,
233}
234
235impl OldState for ColdOldState {
236    fn range(&self) -> (u32, u32) {
237        self.index.range()
238    }
239    fn version(&self, key: &[u8; 32], at: u32) -> Result<Option<(u32, Vec<u8>)>, String> {
240        self.index.version_at(&self.cold, key, at)
241    }
242}
243
244impl std::fmt::Debug for StateStore {
245    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        f.debug_struct("StateStore").finish_non_exhaustive()
247    }
248}
249
250impl StateStore {
251    pub fn open(dir: &std::path::Path) -> Result<StateStore, String> {
252        let db = Database::builder(dir).open().map_err(err)?;
253        let objects = db
254            .keyspace("objects", KeyspaceCreateOptions::default)
255            .map_err(err)?;
256        let meta = db
257            .keyspace("meta", KeyspaceCreateOptions::default)
258            .map_err(err)?;
259        let ks = |name: &str| {
260            db.keyspace(name, KeyspaceCreateOptions::default)
261                .map_err(err)
262        };
263        let (pending, tx, ledger_hash, account_tx) = (
264            ks("pending")?,
265            ks("tx")?,
266            ks("ledger_hash")?,
267            ks("account_tx")?,
268        );
269        let tree = StateTree {
270            live: ks("live")?,
271            tree: ks("tree")?,
272        };
273        let evidence = ks("evidence")?;
274        let levels = ks("levels")?;
275        let (mpt_holders, mpt_keys) = (ks("mpt_holders")?, ks("mpt_keys")?);
276        let (nft_owner, nft_uri, nft_issuer, nft_tx) = (
277            ks("nft_owner")?,
278            ks("nft_uri")?,
279            ks("nft_issuer")?,
280            ks("nft_tx")?,
281        );
282        Ok(StateStore {
283            db,
284            objects,
285            meta,
286            pending,
287            tx,
288            ledger_hash,
289            account_tx,
290            mpt_holders,
291            mpt_keys,
292            nft_owner,
293            nft_uri,
294            nft_issuer,
295            nft_tx,
296            tree,
297            levels,
298            evidence,
299            old: std::sync::RwLock::new(None),
300        })
301    }
302
303    fn meta_u32(&self, k: &[u8]) -> Result<Option<u32>, String> {
304        Ok(self
305            .meta
306            .get(k)
307            .map_err(err)?
308            .and_then(|v| <[u8; 4]>::try_from(&v[..]).ok())
309            .map(u32::from_be_bytes))
310    }
311
312    /// The snapshot ledger; there is no state before it.
313    pub fn base(&self) -> Result<Option<u32>, String> {
314        self.meta_u32(BASE)
315    }
316
317    /// Last applied ledger.
318    pub fn last(&self) -> Result<Option<u32>, String> {
319        self.meta_u32(LAST)
320    }
321
322    /// Header of an applied ledger.
323    pub fn header(&self, sequence: u32) -> Result<Option<Vec<u8>>, String> {
324        Ok(self
325            .meta
326            .get(header_key(sequence))
327            .map_err(err)?
328            .map(|v| v.to_vec()))
329    }
330
331    /// Loads a snapshot into an empty store. Objects must be in ascending key order.
332    pub fn load_snapshot(
333        &self,
334        sequence: u32,
335        header: &[u8],
336        objects: impl Iterator<Item = Result<([u8; 32], Vec<u8>), String>>,
337    ) -> Result<u64, String> {
338        if self.base()?.is_some() {
339            return Err("snapshot already loaded".into());
340        }
341        let mut ing = self.objects.start_ingestion().map_err(err)?;
342        let mut n = 0u64;
343        let mut prev: Option<[u8; 32]> = None;
344        for item in objects {
345            let (key, data) = item?;
346            if prev.is_some_and(|p| p >= key) {
347                return Err("snapshot objects are not in ascending key order".into());
348            }
349            ing.write(version_key(&key, sequence), data).map_err(err)?;
350            prev = Some(key);
351            n += 1;
352        }
353        ing.finish().map_err(err)?;
354        let mut b = self.db.batch();
355        b.insert(&self.meta, BASE, sequence.to_be_bytes());
356        b.insert(&self.meta, LAST, sequence.to_be_bytes());
357        b.insert(&self.meta, header_key(sequence), header);
358        b.commit().map_err(err)?;
359        self.db.persist(PersistMode::SyncAll).map_err(err)?;
360        Ok(n)
361    }
362
363    /// Applies the changes of ledger `sequence`; it must be the next one in order.
364    pub fn apply(
365        &self,
366        sequence: u32,
367        header: &[u8],
368        changes: &[StateChange],
369    ) -> Result<(), String> {
370        let ledger = Ledger {
371            header: header.to_vec(),
372            transactions: Vec::new(),
373            changes: changes.to_vec(),
374        };
375        self.apply_batch(sequence, &ledger, None)
376    }
377
378    /// Applies a whole ledger: changes, indexes and the ledger itself (`body` is
379    /// its serialization) into the pending-block set, in one batch.
380    pub fn apply_ledger(&self, sequence: u32, ledger: &Ledger, body: &[u8]) -> Result<(), String> {
381        if self.indexed()? != self.last()? {
382            return Err("indexes lag behind the state: catch them up first".into());
383        }
384        self.apply_batch(sequence, ledger, Some(body))
385    }
386
387    /// Stores a ledger's anchor evidence (quorum validations).
388    pub fn put_evidence(
389        &self,
390        sequence: u32,
391        validations: &[ValidationEvidence],
392    ) -> Result<(), String> {
393        let v = serde_json::to_vec(validations).map_err(|e| e.to_string())?;
394        self.evidence.insert(sequence.to_be_bytes(), v).map_err(err)
395    }
396
397    /// Last ledger with anchor evidence.
398    pub fn last_evidence(&self) -> Result<Option<u32>, String> {
399        match self.evidence.last_key_value() {
400            Some(g) => {
401                let k = g.key().map_err(err)?;
402                Ok(<[u8; 4]>::try_from(&k[..]).ok().map(u32::from_be_bytes))
403            }
404            None => Ok(None),
405        }
406    }
407
408    /// The nearest anchor evidence at ledger `sequence` or later.
409    pub fn evidence_from(
410        &self,
411        sequence: u32,
412    ) -> Result<Option<(u32, Vec<ValidationEvidence>)>, String> {
413        let Some(g) = self.evidence.range(sequence.to_be_bytes()..).next() else {
414            return Ok(None);
415        };
416        let (k, v) = g.into_inner().map_err(err)?;
417        let seq = u32::from_be_bytes(<[u8; 4]>::try_from(&k[..]).map_err(|_| "evidence key")?);
418        Ok(Some((
419            seq,
420            serde_json::from_slice(&v).map_err(|e| e.to_string())?,
421        )))
422    }
423
424    /// Path in the state tree to a key, as of the ledger the tree corresponds
425    /// to. Everything is read from one snapshot, so a loader writing at the
426    /// same time cannot break consistency.
427    pub fn tree_path(&self, key: &[u8; 32]) -> Result<TreePath, String> {
428        use crate::statetree::{decode_node, nibble, node_key, range_of};
429        use fjall::Readable as _;
430        let snap = self.db.snapshot();
431        let u32_of = |v: Option<fjall::UserValue>| {
432            v.and_then(|v| <[u8; 4]>::try_from(&v[..]).ok())
433                .map(u32::from_be_bytes)
434        };
435        let ledger = u32_of(snap.get(&self.meta, TREE).map_err(err)?).ok_or("no state tree")?;
436        let header = snap
437            .get(&self.meta, header_key(ledger))
438            .map_err(err)?
439            .ok_or("no header for the tree's ledger")?
440            .to_vec();
441        let object_at = |k: &[u8; 32]| -> Result<Vec<u8>, String> {
442            let g = snap
443                .range(&self.objects, version_key(k, 0)..=version_key(k, ledger))
444                .next_back()
445                .ok_or("live object missing from versions")?;
446            let (_, v) = g.into_inner().map_err(err)?;
447            Ok(v.to_vec())
448        };
449        let mut levels = Vec::new();
450        for depth in 0..64 {
451            let node = snap
452                .get(&self.tree.tree, node_key(key, depth))
453                .map_err(err)?
454                .and_then(|v| decode_node(&v))
455                .ok_or("tree node missing on the path")?;
456            levels.push(node);
457            let child = node[usize::from(nibble(key, depth))];
458            if child == [0u8; 32] {
459                return Ok(TreePath {
460                    ledger,
461                    header,
462                    path: witness_core::shamap::Path { levels },
463                    leaf: Leaf::Empty,
464                });
465            }
466            if snap
467                .contains_key(&self.tree.tree, node_key(key, depth + 1))
468                .map_err(err)?
469            {
470                continue;
471            }
472            // Below is a leaf: the only live key under this prefix.
473            let (lo, hi) = range_of(key, depth + 1);
474            let g = snap
475                .range(&self.tree.live, lo..=hi)
476                .next()
477                .ok_or("no leaf under the prefix")?;
478            let (k, h) = g.into_inner().map_err(err)?;
479            let k: [u8; 32] = k[..].try_into().map_err(|_| "leaf key")?;
480            if h[..] != child {
481                return Err("leaf hash does not match the node".into());
482            }
483            let object = object_at(&k)?;
484            let leaf = if k == *key {
485                Leaf::Present(object)
486            } else {
487                Leaf::Other(k, object)
488            };
489            return Ok(TreePath {
490                ledger,
491                header,
492                path: witness_core::shamap::Path { levels },
493                leaf,
494            });
495        }
496        Err("path longer than the key".into())
497    }
498
499    /// First ledger a path can be rebuilt at (`state_path_at`).
500    pub fn levels_from(&self) -> Result<Option<u32>, String> {
501        self.meta_u32(LEVELS_FROM)
502    }
503
504    /// Rebuilds the tree history from the snapshot up to `levels_from`, for a
505    /// store that kept it only from a later ledger. Returns the range rebuilt,
506    /// `None` if there was nothing to do.
507    ///
508    /// The subtrees at `LEVEL_DEPTH` don't depend on each other, and the
509    /// object versions of one are a single key range, so `threads` workers
510    /// each take a subtree, read its range once, and replay its versions in
511    /// memory, noting its hash and key count at every ledger that changed it.
512    /// The notes go to `scratch` in one batch per subtree; after a stop, the
513    /// subtrees already noted are not read again. A second pass goes through
514    /// the ledgers in order, puts the top of the tree together from the notes,
515    /// checks it against each ledger's `AccountHash`, and writes the records
516    /// below the existing ones. `levels_from` moves down to the snapshot only
517    /// once all of them are in.
518    pub fn backfill_levels(
519        &self,
520        scratch: &std::path::Path,
521        threads: usize,
522        progress: impl Fn(String) + Sync,
523    ) -> Result<Option<(u32, u32)>, String> {
524        use crate::statetree::{SubTree, level_range, root_of_levels, state_leaf_hash_of};
525        use fjall::Readable as _;
526        use std::sync::atomic::{AtomicUsize, Ordering};
527        let (Some(base), Some(to)) = (self.base()?, self.levels_from()?) else {
528            return Ok(None);
529        };
530        if to <= base {
531            return Ok(None);
532        }
533        let open = || -> Result<_, String> {
534            let db = Database::builder(scratch).open().map_err(err)?;
535            let ks = |name: &str| {
536                db.keyspace(name, KeyspaceCreateOptions::default)
537                    .map_err(err)
538            };
539            let (notes, done) = (ks("notes")?, ks("done")?);
540            Ok((db, notes, done))
541        };
542        // Notes are for this snapshot and this end; anything else starts over.
543        let mut job = [0u8; 8];
544        job[..4].copy_from_slice(&base.to_be_bytes());
545        job[4..].copy_from_slice(&to.to_be_bytes());
546        let kept = match open() {
547            Ok((db, notes, done)) => {
548                let same = done.get("job").map_err(err)?.is_some_and(|v| v[..] == job);
549                same.then_some((db, notes, done))
550            }
551            Err(_) => None,
552        };
553        let (db, notes, done) = match kept {
554            Some(kept) => kept,
555            None => {
556                let _ = std::fs::remove_dir_all(scratch);
557                let (db, notes, done) = open()?;
558                done.insert("job", job).map_err(err)?;
559                (db, notes, done)
560            }
561        };
562        let slot_done = |slot: u16| -> Result<bool, String> {
563            Ok(done.get(slot.to_be_bytes()).map_err(err)?.is_some())
564        };
565        let mut todo = Vec::new();
566        for slot in 0..LEVEL_SLOTS as u16 {
567            if !slot_done(slot)? {
568                todo.push(slot);
569            }
570        }
571        if todo.len() < LEVEL_SLOTS {
572            progress(format!(
573                "{} of {LEVEL_SLOTS} subtrees already replayed",
574                LEVEL_SLOTS - todo.len()
575            ));
576        }
577
578        // Pass 1: each subtree on its own. A note is keyed by ledger and
579        // subtree, and holds the subtree's hash and key count after the ledger.
580        let snap = self.db.snapshot();
581        let next = AtomicUsize::new(0);
582        let replayed = AtomicUsize::new(LEVEL_SLOTS - todo.len());
583        let replay = |slot: u16| -> Result<(), String> {
584            let (lo, hi) = level_range(slot);
585            let mut end = hi.to_vec();
586            end.extend_from_slice(&[0xFF; 4]);
587            let mut tree = SubTree::new(lo, LEVEL_DEPTH);
588            let mut changes: Vec<(u32, [u8; 32], Option<[u8; 32]>)> = Vec::new();
589            for g in snap.range(&self.objects, lo.to_vec()..=end) {
590                let (k, v) = g.into_inner().map_err(err)?;
591                let key: [u8; 32] = k[..32].try_into().map_err(|_| "object key")?;
592                let seq = u32::from_be_bytes(k[32..].try_into().map_err(|_| "object version")?);
593                let leaf = state_leaf_hash_of(&v, &key);
594                if seq <= base {
595                    // Versions of a key come in order: the last one wins.
596                    tree.set(key, leaf);
597                } else if seq < to {
598                    changes.push((seq, key, leaf));
599                }
600            }
601            changes.sort_by_key(|c| c.0);
602            let note = |tree: &mut SubTree, seq: u32| {
603                let mut k = [0u8; 6];
604                k[..4].copy_from_slice(&seq.to_be_bytes());
605                k[4..].copy_from_slice(&slot.to_be_bytes());
606                let mut v = [0u8; 36];
607                v[..32].copy_from_slice(&tree.hash());
608                v[32..].copy_from_slice(&(tree.len() as u32).to_be_bytes());
609                (k, v)
610            };
611            let mut b = db.batch();
612            let (k, v) = note(&mut tree, base);
613            b.insert(&notes, k, v);
614            let mut i = 0;
615            while i < changes.len() {
616                let seq = changes[i].0;
617                while i < changes.len() && changes[i].0 == seq {
618                    tree.set(changes[i].1, changes[i].2);
619                    i += 1;
620                }
621                let (k, v) = note(&mut tree, seq);
622                b.insert(&notes, k, v);
623            }
624            b.insert(&done, slot.to_be_bytes(), [1]);
625            b.commit().map_err(err)?;
626            let n = replayed.fetch_add(1, Ordering::Relaxed) + 1;
627            if n.is_multiple_of(256) {
628                progress(format!("{n} of {LEVEL_SLOTS} subtrees replayed"));
629            }
630            Ok(())
631        };
632        std::thread::scope(|s| {
633            let workers: Vec<_> = (0..threads.max(1))
634                .map(|_| {
635                    s.spawn(|| -> Result<(), String> {
636                        while let Some(slot) = todo.get(next.fetch_add(1, Ordering::Relaxed)) {
637                            replay(*slot)?;
638                        }
639                        Ok(())
640                    })
641                })
642                .collect();
643            let joined: Vec<_> = workers.into_iter().map(|w| w.join()).collect();
644            joined
645                .into_iter()
646                .try_for_each(|w| w.map_err(|_| "a replay worker panicked".to_string())?)
647        })?;
648        db.persist(PersistMode::SyncAll).map_err(err)?;
649
650        // Pass 2: ledgers in order, the top of the tree checked on each.
651        let mut hashes = vec![[0u8; 32]; LEVEL_SLOTS];
652        let mut counts = vec![0u32; LEVEL_SLOTS];
653        let mut it = notes.iter();
654        let mut pending = None;
655        let mut b = self.db.batch();
656        for seq in base..to {
657            let mut level = std::collections::BTreeMap::new();
658            loop {
659                if pending.is_none() {
660                    pending = it.next().map(|g| g.into_inner()).transpose().map_err(err)?;
661                }
662                let Some((k, v)) = pending.take_if(|(k, _)| k[..4] <= seq.to_be_bytes()[..]) else {
663                    break;
664                };
665                let slot = u16::from_be_bytes([k[4], k[5]]);
666                let h: [u8; 32] = v[..32].try_into().map_err(|_| "note")?;
667                hashes[slot as usize] = h;
668                counts[slot as usize] =
669                    u32::from_be_bytes(v[32..36].try_into().map_err(|_| "note")?);
670                level.insert(slot, h);
671            }
672            if seq == base && level.len() != LEVEL_SLOTS {
673                return Err("the snapshot is missing from the notes".into());
674            }
675            let header = Ledger {
676                header: self.header(seq)?.ok_or(format!("no header for {seq}"))?,
677                transactions: Vec::new(),
678                changes: Vec::new(),
679            }
680            .header()?;
681            if root_of_levels(&hashes, &counts) != header.account_hash {
682                return Err(format!(
683                    "replay does not give the state root of ledger {seq}"
684                ));
685            }
686            if seq.is_multiple_of(LEVELS_EVERY) {
687                level = (0..LEVEL_SLOTS as u16)
688                    .map(|s| (s, hashes[s as usize]))
689                    .collect();
690            }
691            if !level.is_empty() {
692                b.insert(&self.levels, seq.to_be_bytes(), encode_levels(&level));
693            }
694            if seq.is_multiple_of(1024) {
695                b.commit().map_err(err)?;
696                b = self.db.batch();
697            }
698            if seq.is_multiple_of(16384) {
699                progress(format!("checked up to ledger {seq} of {to}"));
700            }
701        }
702        b.insert(&self.meta, LEVELS_FROM, base.to_be_bytes());
703        b.commit().map_err(err)?;
704        self.persist()?;
705        drop((notes, done, db));
706        let _ = std::fs::remove_dir_all(scratch);
707        Ok(Some((base, to - 1)))
708    }
709
710    /// Path in the state tree to a key as of an earlier ledger `at`. The top
711    /// of the tree comes from the tree history: for each subtree at depth 3,
712    /// the last hash recorded at or before `at`, back to the nearest full set.
713    /// The key's own subtree is rebuilt from the object versions as of `at` and
714    /// must give the recorded hash, and the root must be the header's
715    /// `AccountHash`: a gap or a fault in the history is an error, never a
716    /// wrong path.
717    pub fn state_path_at(&self, key: &[u8; 32], at: u32) -> Result<TreePath, String> {
718        use crate::statetree::{inner_hash, level_range, level_slot};
719        use fjall::Readable as _;
720        use std::ops::Bound;
721        use witness_core::shamap::{state_leaf_hash, subtree_hash, walk_from};
722        let snap = self.db.snapshot();
723        let u32_of = |v: Option<fjall::UserValue>| {
724            v.and_then(|v| <[u8; 4]>::try_from(&v[..]).ok())
725                .map(u32::from_be_bytes)
726        };
727        let from = u32_of(snap.get(&self.meta, LEVELS_FROM).map_err(err)?);
728        let tree = u32_of(snap.get(&self.meta, TREE).map_err(err)?);
729        match (from, tree) {
730            (Some(f), Some(t)) if f <= at && at <= t => {}
731            (Some(f), _) if at < f => {
732                return Err(format!(
733                    "state paths start at ledger {f}: the tree history begins there"
734                ));
735            }
736            _ => return Err(format!("no tree history for ledger {at}")),
737        }
738        let header = snap
739            .get(&self.meta, header_key(at))
740            .map_err(err)?
741            .ok_or("no header for the ledger")?
742            .to_vec();
743        let want = Ledger {
744            header: header.clone(),
745            transactions: Vec::new(),
746            changes: Vec::new(),
747        }
748        .header()?
749        .account_hash;
750
751        // The subtrees at depth 3 as of `at`.
752        let mut slots: Vec<Option<[u8; 32]>> = vec![None; LEVEL_SLOTS];
753        let mut missing = LEVEL_SLOTS;
754        for g in snap.range(&self.levels, ..=at.to_be_bytes()).rev() {
755            let (_, v) = g.into_inner().map_err(err)?;
756            for e in v.as_chunks::<34>().0 {
757                let slot = usize::from(u16::from_be_bytes([e[0], e[1]]));
758                if slots[slot].is_none() {
759                    slots[slot] = Some(e[2..].try_into().map_err(|_| "level hash")?);
760                    missing -= 1;
761                }
762            }
763            if missing == 0 || v.len() == LEVEL_SLOTS * 34 {
764                break;
765            }
766        }
767        if missing > 0 {
768            return Err(format!("tree history has a gap before ledger {at}"));
769        }
770        let slots: Vec<[u8; 32]> = slots.into_iter().flatten().collect();
771        // 256 nodes at depth 2, 16 at depth 1, the root.
772        let nodes2 = slots.as_chunks::<16>().0;
773        let hashes2: Vec<[u8; 32]> = nodes2.iter().map(inner_hash).collect();
774        let nodes1 = hashes2.as_chunks::<16>().0;
775        let hashes1: Vec<[u8; 32]> = nodes1.iter().map(inner_hash).collect();
776        let root: [[u8; 32]; 16] = hashes1.try_into().map_err(|_| "tree top")?;
777        if inner_hash(&root) != want {
778            return Err(format!(
779                "tree history does not give the state root of ledger {at}"
780            ));
781        }
782
783        // The key's subtree, from the object versions as of `at`. Versions are
784        // read in order; a key with many of them (LedgerHashes and busy
785        // accounts change almost every ledger) costs two seeks instead: its
786        // version as of `at`, and the next key.
787        const SEEK_AFTER: usize = 32;
788        let slot = level_slot(key);
789        let (lo, hi) = level_range(slot);
790        let end = Bound::Included(version_key(&hi, u32::MAX));
791        let mut leaves = Vec::new();
792        let mut objects = std::collections::HashMap::new();
793        let mut keep = |k: [u8; 32], v: &[u8]| {
794            if !v.is_empty() {
795                leaves.push((k, state_leaf_hash(v, &k)));
796                objects.insert(k, v.to_vec());
797            }
798        };
799        let mut from = Bound::Included(version_key(&lo, 0));
800        'scan: loop {
801            // The key being read, its version as of `at` so far, versions seen.
802            let mut cur: Option<([u8; 32], Option<fjall::UserValue>, usize)> = None;
803            for g in snap.range(&self.objects, (from, end)) {
804                let (k, v) = g.into_inner().map_err(err)?;
805                let (k, seq): ([u8; 32], [u8; 4]) = (
806                    k[..32].try_into().map_err(|_| "object key")?,
807                    k[32..].try_into().map_err(|_| "object version")?,
808                );
809                let seq = u32::from_be_bytes(seq);
810                match &mut cur {
811                    Some((ck, best, n)) if *ck == k => {
812                        *n += 1;
813                        if seq <= at {
814                            *best = Some(v);
815                        }
816                        if *n >= SEEK_AFTER {
817                            if let Some(g) = snap
818                                .range(&self.objects, version_key(&k, 0)..=version_key(&k, at))
819                                .next_back()
820                            {
821                                keep(k, &g.into_inner().map_err(err)?.1);
822                            }
823                            from = Bound::Excluded(version_key(&k, u32::MAX));
824                            continue 'scan;
825                        }
826                    }
827                    _ => {
828                        if let Some((ck, Some(b), _)) = cur.take() {
829                            keep(ck, &b);
830                        }
831                        cur = Some((k, (seq <= at).then_some(v), 1));
832                    }
833                }
834            }
835            if let Some((ck, Some(b), _)) = cur {
836                keep(ck, &b);
837            }
838            break;
839        }
840        if subtree_hash(&leaves, LEVEL_DEPTH) != slots[usize::from(slot)] {
841            return Err(format!(
842                "objects as of ledger {at} do not give the recorded subtree"
843            ));
844        }
845        let n1 = usize::from(key[0] >> 4);
846        let n0 = usize::from(key[0]);
847        let mut levels = vec![root, nodes1[n1], nodes2[n0]];
848        let leaf = match leaves.as_slice() {
849            [] => None,
850            [only] => Some(*only),
851            _ => {
852                let (below, leaf) = walk_from(&leaves, key, LEVEL_DEPTH);
853                levels.extend(below);
854                leaf
855            }
856        };
857        let leaf = match leaf {
858            None => Leaf::Empty,
859            Some((k, _)) => {
860                let object = objects.remove(&k).ok_or("leaf object")?;
861                if k == *key {
862                    Leaf::Present(object)
863                } else {
864                    Leaf::Other(k, object)
865                }
866            }
867        };
868        Ok(TreePath {
869            ledger: at,
870            header,
871            path: witness_core::shamap::Path { levels },
872            leaf,
873        })
874    }
875
876    /// Last ledger confirmed by a quorum; `None` if none yet.
877    pub fn confirmed(&self) -> Result<Option<u32>, String> {
878        self.meta_u32(CONFIRMED)
879    }
880
881    /// Marks a ledger as confirmed. Only forward, and only up to the applied
882    /// ledger: confirmation applies to an already verified chain.
883    pub fn set_confirmed(&self, sequence: u32) -> Result<(), String> {
884        if self.confirmed()?.is_some_and(|c| c >= sequence) {
885            return Ok(());
886        }
887        if self.last()?.is_none_or(|l| l < sequence) {
888            return Err(format!("ledger {sequence} not applied yet"));
889        }
890        let mut b = self.db.batch();
891        b.insert(&self.meta, CONFIRMED, sequence.to_be_bytes());
892        b.commit().map_err(err)
893    }
894
895    /// Ledger the state tree corresponds to; `None` if there is no tree.
896    pub fn tree_ledger(&self) -> Result<Option<u32>, String> {
897        self.meta_u32(TREE)
898    }
899
900    /// Deletes the whole state tree (for a rebuild). The store must be reopened
901    /// afterwards.
902    pub fn drop_tree(self) -> Result<(), String> {
903        let mut b = self.db.batch();
904        b.remove(&self.meta, TREE);
905        b.commit().map_err(err)?;
906        self.persist()?;
907        self.db
908            .delete_keyspace(self.tree.live.clone())
909            .map_err(err)?;
910        self.db
911            .delete_keyspace(self.tree.tree.clone())
912            .map_err(err)?;
913        Ok(())
914    }
915
916    /// Root of the state tree.
917    pub fn tree_root(&self) -> Result<[u8; 32], String> {
918        self.tree.root()
919    }
920
921    /// Builds the state tree from scratch for the last applied ledger and
922    /// checks the root against its AccountHash. Returns the ledger and the leaf count.
923    pub fn build_tree(&self) -> Result<(u32, usize), String> {
924        let last = self.last()?.ok_or("store is empty")?;
925        if !self.tree.live.is_empty().map_err(err)? || !self.tree.tree.is_empty().map_err(err)? {
926            return Err("tree already exists: it can only be built into an empty one".into());
927        }
928        let mut leaves = Vec::new();
929        for item in self.objects_at(last) {
930            let (key, data) = item?;
931            leaves.push((key, witness_core::shamap::state_leaf_hash(&data, &key)));
932        }
933        let want = Ledger {
934            header: self.header(last)?.ok_or("no header")?,
935            transactions: Vec::new(),
936            changes: Vec::new(),
937        }
938        .header()?
939        .account_hash;
940        let mut nodes = Vec::new();
941        let root = self.tree.build(&leaves, |k, v| {
942            nodes.push((k, v));
943            Ok(())
944        })?;
945        if root != want {
946            return Err(format!(
947                "root {} does not match AccountHash {} of ledger {last}",
948                hex::encode_upper(root),
949                hex::encode_upper(want)
950            ));
951        }
952        for chunk in nodes.chunks(50_000) {
953            let mut b = self.db.batch();
954            for (k, v) in chunk {
955                b.insert(&self.tree.tree, k.clone(), v.clone());
956            }
957            b.commit().map_err(err)?;
958        }
959        let mut ing = self.tree.live.start_ingestion().map_err(err)?;
960        for (k, h) in &leaves {
961            ing.write(*k, *h).map_err(err)?;
962        }
963        ing.finish().map_err(err)?;
964        let mut b = self.db.batch();
965        b.insert(&self.meta, TREE, last.to_be_bytes());
966        b.commit().map_err(err)?;
967        self.persist()?;
968        Ok((last, leaves.len()))
969    }
970
971    /// Last ledger in the indexes.
972    pub fn indexed(&self) -> Result<Option<u32>, String> {
973        Ok(self.meta_u32(INDEXED)?.or(self.base()?))
974    }
975
976    /// Catches up the indexes for a ledger already applied to the state; it must
977    /// be the one right after the last indexed ledger.
978    pub fn index_ledger(&self, sequence: u32, ledger: &Ledger) -> Result<(), String> {
979        match self.indexed()? {
980            Some(i) if i + 1 == sequence && Some(sequence) <= self.last()? => {}
981            other => {
982                return Err(format!(
983                    "indexes are at {other:?}, got {sequence}: only in order"
984                ));
985            }
986        }
987        let mut b = self.db.batch();
988        self.index_into(&mut b, sequence, ledger)?;
989        b.commit().map_err(err)
990    }
991
992    fn index_into(
993        &self,
994        b: &mut fjall::OwnedWriteBatch,
995        sequence: u32,
996        ledger: &Ledger,
997    ) -> Result<(), String> {
998        let hash = ledger.header()?.hash();
999        b.insert(&self.ledger_hash, hash, sequence.to_be_bytes());
1000        for e in entries(ledger)? {
1001            let mut loc = [0u8; 8];
1002            loc[..4].copy_from_slice(&sequence.to_be_bytes());
1003            loc[4..].copy_from_slice(&e.pos.to_be_bytes());
1004            b.insert(&self.tx, e.id, loc);
1005            let at = TxPosition {
1006                ledger: sequence,
1007                index: e.index,
1008            };
1009            for a in &e.accounts {
1010                b.insert(&self.account_tx, account_key(a, at), e.pos.to_be_bytes());
1011            }
1012        }
1013        if self.nft_from()?.is_some_and(|f| sequence >= f) {
1014            self.nft_rows(b, sequence, ledger);
1015        }
1016        b.insert(&self.meta, INDEXED, sequence.to_be_bytes());
1017        Ok(())
1018    }
1019
1020    /// A ledger's rows in the NFT index. A transaction whose effect can't
1021    /// be read is logged and keeps only its history entry, so one odd
1022    /// transaction does not stop loading.
1023    fn nft_rows(&self, b: &mut fjall::OwnedWriteBatch, sequence: u32, ledger: &Ledger) -> usize {
1024        let n = crate::nftindex::nft_ledger(ledger);
1025        for p in &n.problems {
1026            tracing::warn!("NFT index, ledger {sequence}: {p}");
1027        }
1028        self.put_nft_rows(b, sequence, &n);
1029        n.txs.len()
1030    }
1031
1032    fn put_nft_rows(
1033        &self,
1034        b: &mut fjall::OwnedWriteBatch,
1035        sequence: u32,
1036        n: &crate::nftindex::NftLedger,
1037    ) {
1038        let seq = sequence.to_be_bytes();
1039        for (t, index, pos) in &n.txs {
1040            b.insert(
1041                &self.nft_tx,
1042                [&t[..], &seq, &index.to_be_bytes()].concat(),
1043                pos.to_be_bytes(),
1044            );
1045        }
1046        for (t, (owner, burned)) in &n.owners {
1047            b.insert(
1048                &self.nft_owner,
1049                [&t[..], &seq].concat(),
1050                [&owner[..], &[u8::from(*burned)]].concat(),
1051            );
1052        }
1053        for (t, uri) in &n.uris {
1054            b.insert(&self.nft_uri, [&t[..], &seq].concat(), uri);
1055        }
1056        for t in &n.minted {
1057            let id = crate::nft::token_id(t);
1058            b.insert(
1059                &self.nft_issuer,
1060                [&id.issuer[..], &id.taxon.to_be_bytes(), &t[..]].concat(),
1061                [],
1062            );
1063        }
1064    }
1065
1066    /// First ledger indexed for NFTs as it is applied.
1067    pub fn nft_from(&self) -> Result<Option<u32>, String> {
1068        self.meta_u32(NFT_FROM)
1069    }
1070
1071    /// Starts the NFT index at the next ledger to be applied, if it hasn't
1072    /// started; returns the ledger it starts at.
1073    pub fn start_nft_index(&self) -> Result<u32, String> {
1074        if let Some(f) = self.nft_from()? {
1075            return Ok(f);
1076        }
1077        let from = self.last()?.ok_or("state is empty")? + 1;
1078        self.meta
1079            .insert(NFT_FROM, from.to_be_bytes())
1080            .map_err(err)?;
1081        Ok(from)
1082    }
1083
1084    /// The ledgers the NFT index covers: from the first one backfilled up to
1085    /// the last applied, once the backfill has reached the live part.
1086    pub fn nft_coverage(&self) -> Result<Option<u32>, String> {
1087        match (self.nft_from()?, self.meta_u32(NFT_FILL)?) {
1088            (Some(from), Some(fill)) if fill >= from => self.meta_u32(NFT_FILL_FROM),
1089            _ => Ok(None),
1090        }
1091    }
1092
1093    /// Fills the NFT index for ledgers `start..nft_from`, `chunk` ledgers per
1094    /// batch; `read` returns the asked ledgers in order. Progress is stored
1095    /// with each batch, so a restart continues where it stopped. Returns the
1096    /// ledgers filled, or `None` if there was nothing to do.
1097    pub fn backfill_nfts(
1098        &self,
1099        start: u32,
1100        chunk: u32,
1101        read: &ReadLedgers<'_>,
1102        progress: &dyn Fn(u32, u32),
1103    ) -> Result<Option<(u32, u32)>, String> {
1104        let Some(to) = self.nft_from()? else {
1105            return Ok(None);
1106        };
1107        let mut fill = match self.meta_u32(NFT_FILL)? {
1108            Some(f) => f,
1109            None => {
1110                let mut b = self.db.batch();
1111                b.insert(&self.meta, NFT_FILL_FROM, start.to_be_bytes());
1112                b.insert(&self.meta, NFT_FILL, start.to_be_bytes());
1113                b.commit().map_err(err)?;
1114                start
1115            }
1116        };
1117        if fill >= to {
1118            return Ok(None);
1119        }
1120        let from = self.meta_u32(NFT_FILL_FROM)?.unwrap_or(start);
1121        while fill < to {
1122            let end = fill.saturating_add(chunk.max(1)).min(to);
1123            let seqs: Vec<u32> = (fill..end).collect();
1124            let ledgers = read(&seqs)?;
1125            if ledgers.len() != seqs.len() {
1126                return Err(format!(
1127                    "NFT backfill: asked for {} ledgers from {fill}, got {}",
1128                    seqs.len(),
1129                    ledgers.len()
1130                ));
1131            }
1132            for (seq, l) in seqs.iter().zip(&ledgers) {
1133                if l.header()?.sequence != *seq {
1134                    return Err(format!("NFT backfill: ledger {seq} came back as another"));
1135                }
1136            }
1137            // Decoding NFT transactions is the slow part: on several threads.
1138            let piece = ledgers.len().div_ceil(8).max(1);
1139            let parsed: Vec<crate::nftindex::NftLedger> = std::thread::scope(|s| {
1140                let hs: Vec<_> = ledgers
1141                    .chunks(piece)
1142                    .map(|c| {
1143                        s.spawn(|| {
1144                            c.iter()
1145                                .map(crate::nftindex::nft_ledger)
1146                                .collect::<Vec<_>>()
1147                        })
1148                    })
1149                    .collect();
1150                hs.into_iter()
1151                    .map(|h| {
1152                        h.join()
1153                            .map_err(|_| "NFT backfill parser panicked".to_string())
1154                    })
1155                    .collect::<Result<Vec<_>, String>>()
1156            })?
1157            .into_iter()
1158            .flatten()
1159            .collect();
1160            let mut b = self.db.batch();
1161            for (seq, n) in seqs.iter().zip(&parsed) {
1162                for p in &n.problems {
1163                    tracing::warn!("NFT index, ledger {seq}: {p}");
1164                }
1165                self.put_nft_rows(&mut b, *seq, n);
1166            }
1167            b.insert(&self.meta, NFT_FILL, end.to_be_bytes());
1168            b.commit().map_err(err)?;
1169            fill = end;
1170            progress(fill, to);
1171        }
1172        self.persist()?;
1173        Ok(Some((from, to)))
1174    }
1175
1176    /// The starting point for an NFT index whose history doesn't reach back to
1177    /// the first NFTs: every token in the state at the snapshot ledger, at the
1178    /// owner whose page holds it, as Clio fills its tables from its first
1179    /// ledger. The backfill then continues from the next ledger. Does nothing
1180    /// once the backfill has started; an interrupted seeding starts over.
1181    pub fn seed_nfts(&self) -> Result<(), String> {
1182        if self.meta_u32(NFT_FILL)?.is_some() {
1183            return Ok(());
1184        }
1185        let base = self.base()?.ok_or("state is empty")?;
1186        let mut b = self.db.batch();
1187        let mut pending = 0usize;
1188        for item in self.objects_at(base) {
1189            let (key, data) = item?;
1190            if let Some(n) = crate::nftindex::nft_page(&key, &data) {
1191                pending += n.owners.len();
1192                self.put_nft_rows(&mut b, base, &n);
1193            }
1194            if pending >= 10_000 {
1195                std::mem::replace(&mut b, self.db.batch())
1196                    .commit()
1197                    .map_err(err)?;
1198                pending = 0;
1199            }
1200        }
1201        b.insert(&self.meta, NFT_FILL_FROM, base.to_be_bytes());
1202        b.insert(&self.meta, NFT_FILL, (base + 1).to_be_bytes());
1203        b.commit().map_err(err)
1204    }
1205
1206    /// The token as of ledger `at`: the ledger of its last owner change, the
1207    /// owner, whether burned.
1208    pub fn nft_at(
1209        &self,
1210        token: &[u8; 32],
1211        at: u32,
1212    ) -> Result<Option<(u32, [u8; 20], bool)>, String> {
1213        let lo = [&token[..], &0u32.to_be_bytes()].concat();
1214        let hi = [&token[..], &at.to_be_bytes()].concat();
1215        let Some(g) = self.nft_owner.range(lo..=hi).next_back() else {
1216            return Ok(None);
1217        };
1218        let (k, v) = g.into_inner().map_err(err)?;
1219        if v.len() != 21 {
1220            return Err("nft_owner record".into());
1221        }
1222        let owner: [u8; 20] = v[..20].try_into().map_err(|_| "nft_owner record")?;
1223        Ok(Some((be32(&k[32..36]), owner, v[20] != 0)))
1224    }
1225
1226    /// The token's URI as of ledger `at`.
1227    pub fn nft_uri_at(&self, token: &[u8; 32], at: u32) -> Result<Option<Vec<u8>>, String> {
1228        let lo = [&token[..], &0u32.to_be_bytes()].concat();
1229        let hi = [&token[..], &at.to_be_bytes()].concat();
1230        match self.nft_uri.range(lo..=hi).next_back() {
1231            Some(g) => Ok(Some(g.into_inner().map_err(err)?.1.to_vec())),
1232            None => Ok(None),
1233        }
1234    }
1235
1236    /// The token's transactions between `lo` and `hi` inclusive, ascending
1237    /// (`forward`) or descending, at most `limit`.
1238    pub fn nft_txs(
1239        &self,
1240        token: &[u8; 32],
1241        lo: TxPosition,
1242        hi: TxPosition,
1243        forward: bool,
1244        limit: usize,
1245    ) -> Result<Vec<AccountTx>, String> {
1246        if lo > hi {
1247            return Ok(Vec::new());
1248        }
1249        let key =
1250            |p: TxPosition| [&token[..], &p.ledger.to_be_bytes(), &p.index.to_be_bytes()].concat();
1251        let range = self.nft_tx.range(key(lo)..=key(hi));
1252        let items: Box<dyn Iterator<Item = fjall::Guard>> = if forward {
1253            Box::new(range)
1254        } else {
1255            Box::new(range.rev())
1256        };
1257        let mut out = Vec::new();
1258        for g in items.take(limit) {
1259            let (k, v) = g.into_inner().map_err(err)?;
1260            out.push(AccountTx {
1261                at: TxPosition {
1262                    ledger: be32(&k[32..36]),
1263                    index: be32(&k[36..40]),
1264                },
1265                pos: be32(&v),
1266            });
1267        }
1268        Ok(out)
1269    }
1270
1271    /// Tokens minted by `issuer`, by taxon then token, strictly after
1272    /// `after` (taxon, token); only of `taxon` if given. At most `limit`.
1273    pub fn nfts_by_issuer(
1274        &self,
1275        issuer: &[u8; 20],
1276        taxon: Option<u32>,
1277        after: Option<(u32, [u8; 32])>,
1278        limit: usize,
1279    ) -> Result<Vec<[u8; 32]>, String> {
1280        use std::ops::Bound;
1281        let key = |t: u32, id: &[u8; 32]| [&issuer[..], &t.to_be_bytes(), &id[..]].concat();
1282        let start = match after {
1283            Some((t, id)) => Bound::Excluded(key(t, &id)),
1284            None => Bound::Included(key(taxon.unwrap_or(0), &[0; 32])),
1285        };
1286        let end = Bound::Included(key(taxon.unwrap_or(u32::MAX), &[0xFF; 32]));
1287        let mut out = Vec::new();
1288        for g in self
1289            .nft_issuer
1290            .range::<Vec<u8>, _>((start, end))
1291            .take(limit)
1292        {
1293            let k = g.key().map_err(err)?;
1294            out.push(k[24..56].try_into().map_err(|_| "nft_issuer record")?);
1295        }
1296        Ok(out)
1297    }
1298
1299    /// On-disk size and approximate record count of each index. Fresh
1300    /// records not yet flushed from memory are not counted in the on-disk size.
1301    pub fn index_sizes(&self) -> Vec<(&'static str, u64, usize)> {
1302        [
1303            ("tx", &self.tx),
1304            ("ledger_hash", &self.ledger_hash),
1305            ("account_tx", &self.account_tx),
1306            ("levels", &self.levels),
1307            ("nft_owner", &self.nft_owner),
1308            ("nft_uri", &self.nft_uri),
1309            ("nft_issuer", &self.nft_issuer),
1310            ("nft_tx", &self.nft_tx),
1311        ]
1312        .into_iter()
1313        .map(|(n, k)| (n, k.disk_space(), k.approximate_len()))
1314        .collect()
1315    }
1316
1317    /// The ledger and position of the transaction with this hash.
1318    pub fn tx_location(&self, id: &[u8; 32]) -> Result<Option<(u32, u32)>, String> {
1319        Ok(self
1320            .tx
1321            .get(id)
1322            .map_err(err)?
1323            .filter(|v| v.len() == 8)
1324            .map(|v| (be32(&v[..4]), be32(&v[4..]))))
1325    }
1326
1327    /// Ledger sequence by its hash.
1328    pub fn ledger_by_hash(&self, hash: &[u8; 32]) -> Result<Option<u32>, String> {
1329        Ok(self
1330            .ledger_hash
1331            .get(hash)
1332            .map_err(err)?
1333            .filter(|v| v.len() == 4)
1334            .map(|v| be32(&v)))
1335    }
1336
1337    /// Account history in ledgers `min..=max`: ascending (`forward`) or
1338    /// descending, at most `limit`, starting at `marker` inclusive.
1339    pub fn account_tx(
1340        &self,
1341        account: &AccountId,
1342        min: u32,
1343        max: u32,
1344        forward: bool,
1345        limit: usize,
1346        marker: Option<TxPosition>,
1347    ) -> Result<AccountTxPage, String> {
1348        let mut lo = TxPosition {
1349            ledger: min,
1350            index: 0,
1351        };
1352        let mut hi = TxPosition {
1353            ledger: max,
1354            index: u32::MAX,
1355        };
1356        if let Some(m) = marker {
1357            if forward {
1358                lo = lo.max(m);
1359            } else {
1360                hi = hi.min(m);
1361            }
1362        }
1363        let mut page = AccountTxPage {
1364            transactions: Vec::new(),
1365            marker: None,
1366        };
1367        if lo > hi {
1368            return Ok(page);
1369        }
1370        let range = self
1371            .account_tx
1372            .range(account_key(account, lo)..=account_key(account, hi));
1373        let items: Box<dyn Iterator<Item = fjall::Guard>> = if forward {
1374            Box::new(range)
1375        } else {
1376            Box::new(range.rev())
1377        };
1378        for g in items {
1379            let (k, v) = g.into_inner().map_err(err)?;
1380            let at = TxPosition {
1381                ledger: be32(&k[20..24]),
1382                index: be32(&k[24..28]),
1383            };
1384            if page.transactions.len() == limit {
1385                page.marker = Some(at);
1386                break;
1387            }
1388            page.transactions.push(AccountTx { at, pos: be32(&v) });
1389        }
1390        Ok(page)
1391    }
1392
1393    fn apply_batch(
1394        &self,
1395        sequence: u32,
1396        ledger: &Ledger,
1397        body: Option<&[u8]>,
1398    ) -> Result<(), String> {
1399        let (header, changes) = (&ledger.header[..], &ledger.changes[..]);
1400        match self.last()? {
1401            Some(last) if last + 1 == sequence => {}
1402            Some(last) => {
1403                return Err(format!(
1404                    "applied {last}, got {sequence}: changes only in order"
1405                ));
1406            }
1407            None => return Err("load a state snapshot first".into()),
1408        }
1409        let mut b = self.db.batch();
1410        // State root is checked before writing: if it does not match, the ledger is rejected.
1411        let tree_current = self.tree_ledger()? == Some(sequence - 1);
1412        if tree_current {
1413            let levels_from = self.levels_from()?;
1414            let full = levels_from.is_none() || sequence.is_multiple_of(LEVELS_EVERY);
1415            let (root, level) = self
1416                .tree
1417                .update_levels(&leaf_changes(changes), &mut b, full)?;
1418            let want = ledger.header()?.account_hash;
1419            if root != want {
1420                return Err(format!(
1421                    "ledger {sequence}: state root {} does not match AccountHash {}, changes rejected",
1422                    hex::encode_upper(root),
1423                    hex::encode_upper(want)
1424                ));
1425            }
1426            b.insert(&self.meta, TREE, sequence.to_be_bytes());
1427            if !level.is_empty() {
1428                b.insert(&self.levels, sequence.to_be_bytes(), encode_levels(&level));
1429            }
1430            if levels_from.is_none() && level.len() == LEVEL_SLOTS {
1431                b.insert(&self.meta, LEVELS_FROM, sequence.to_be_bytes());
1432            }
1433        }
1434        for c in changes {
1435            let value: &[u8] = match c.change {
1436                Change::Deleted => &[],
1437                Change::Created | Change::Modified => &c.data,
1438            };
1439            b.insert(&self.objects, version_key(&c.key, sequence), value);
1440            self.index_mpt(&mut b, sequence, c)?;
1441        }
1442        if let Some(l) = body {
1443            b.insert(&self.pending, sequence.to_be_bytes(), l);
1444            self.index_into(&mut b, sequence, ledger)?;
1445        }
1446        b.insert(&self.meta, LAST, sequence.to_be_bytes());
1447        b.insert(&self.meta, header_key(sequence), header);
1448        b.commit().map_err(err)
1449    }
1450
1451    /// An MPT holder appeared or disappeared: a version in `mpt_holders`. An
1452    /// MPToken's issuance and account never change, so modifications are ignored.
1453    fn index_mpt(
1454        &self,
1455        b: &mut fjall::OwnedWriteBatch,
1456        sequence: u32,
1457        c: &StateChange,
1458    ) -> Result<(), String> {
1459        match c.change {
1460            Change::Created => {
1461                if let Some((id, acc)) = mptoken_holder(&c.data) {
1462                    b.insert(&self.mpt_holders, holder_key(&id, &acc, sequence), c.key);
1463                    b.insert(&self.mpt_keys, c.key, [&id[..], &acc[..]].concat());
1464                }
1465            }
1466            Change::Deleted => {
1467                if let Some(v) = self.mpt_keys.get(c.key).map_err(err)?
1468                    && v.len() == 44
1469                {
1470                    let (id, acc) = v.split_at(24);
1471                    let id: &[u8; 24] = id.try_into().map_err(|_| "mpt_keys record")?;
1472                    let acc: &[u8; 20] = acc.try_into().map_err(|_| "mpt_keys record")?;
1473                    b.insert(&self.mpt_holders, holder_key(id, acc, sequence), []);
1474                }
1475            }
1476            Change::Modified => {}
1477        }
1478        Ok(())
1479    }
1480
1481    /// Builds the MPT holder index over all object versions if it does not
1482    /// exist yet: a single pass on first start. After that `apply` maintains it.
1483    /// Returns the number of holder versions found, or `None` if the index
1484    /// already existed.
1485    pub fn ensure_mpt_index(&self) -> Result<Option<usize>, String> {
1486        if self.meta.get(MPT_INDEXED).map_err(err)?.is_some() {
1487            return Ok(None);
1488        }
1489        let mut b = self.db.batch();
1490        let (mut n, mut pending) = (0usize, 0usize);
1491        // The key and its holder at the latest version (if it is an MPToken).
1492        let mut cur: Option<([u8; 32], Option<Holder>)> = None;
1493        for g in self.objects.iter() {
1494            let (k, v) = g.into_inner().map_err(err)?;
1495            let mut key = [0u8; 32];
1496            key.copy_from_slice(&k[..32]);
1497            let seq = u32::from_be_bytes([k[32], k[33], k[34], k[35]]);
1498            let was = match &cur {
1499                Some((ck, h)) if *ck == key => *h,
1500                _ => None,
1501            };
1502            let now = mptoken_holder(&v);
1503            match (was, now) {
1504                (None, Some((id, acc))) => {
1505                    b.insert(&self.mpt_holders, holder_key(&id, &acc, seq), key);
1506                    b.insert(&self.mpt_keys, key, [&id[..], &acc[..]].concat());
1507                    n += 1;
1508                    pending += 1;
1509                }
1510                (Some((id, acc)), None) => {
1511                    b.insert(&self.mpt_holders, holder_key(&id, &acc, seq), []);
1512                    n += 1;
1513                    pending += 1;
1514                }
1515                _ => {}
1516            }
1517            cur = Some((key, now));
1518            if pending >= 10_000 {
1519                std::mem::replace(&mut b, self.db.batch())
1520                    .commit()
1521                    .map_err(err)?;
1522                pending = 0;
1523            }
1524        }
1525        b.insert(&self.meta, MPT_INDEXED, [1u8]);
1526        b.commit().map_err(err)?;
1527        Ok(Some(n))
1528    }
1529
1530    /// Holders of issuance `id` as of ledger `at` in ascending account order, strictly
1531    /// after `after`: the account and MPToken key, at most `limit`.
1532    pub fn mpt_holders(
1533        &self,
1534        id: &[u8; 24],
1535        at: u32,
1536        after: Option<&[u8; 20]>,
1537        limit: usize,
1538    ) -> Result<Vec<MptHolder>, String> {
1539        use std::ops::Bound;
1540        let start = match after {
1541            Some(a) => Bound::Excluded(holder_key(id, a, u32::MAX).to_vec()),
1542            None => Bound::Included(holder_key(id, &[0; 20], 0).to_vec()),
1543        };
1544        let end = Bound::Included(holder_key(id, &[0xFF; 20], u32::MAX).to_vec());
1545        let mut out = Vec::new();
1546        // The account and the key of its latest version no later than `at` (empty if deleted).
1547        let mut cur: Option<([u8; 20], Vec<u8>)> = None;
1548        let flush = |c: Option<([u8; 20], Vec<u8>)>, out: &mut Vec<_>| {
1549            if let Some((a, v)) = c
1550                && let Ok(k) = <[u8; 32]>::try_from(&v[..])
1551            {
1552                out.push((a, k));
1553            }
1554        };
1555        for g in self.mpt_holders.range::<Vec<u8>, _>((start, end)) {
1556            let (k, v) = g.into_inner().map_err(err)?;
1557            let mut acc = [0u8; 20];
1558            acc.copy_from_slice(&k[24..44]);
1559            let seq = u32::from_be_bytes([k[44], k[45], k[46], k[47]]);
1560            if cur.as_ref().is_some_and(|(a, _)| *a != acc) {
1561                flush(cur.take(), &mut out);
1562                if out.len() >= limit {
1563                    return Ok(out);
1564                }
1565            }
1566            if seq <= at {
1567                cur = Some((acc, v.to_vec()));
1568            } else if cur.is_none() {
1569                // The holder appeared after the requested ledger: skip it by
1570                // keeping an empty version so it is not returned.
1571                cur = Some((acc, Vec::new()));
1572            }
1573        }
1574        flush(cur, &mut out);
1575        out.truncate(limit);
1576        Ok(out)
1577    }
1578
1579    /// Ledgers waiting for their block, in order.
1580    pub fn pending(&self) -> Result<Vec<(u32, Vec<u8>)>, String> {
1581        self.pending
1582            .iter()
1583            .map(|g| {
1584                let (k, v) = g.into_inner().map_err(err)?;
1585                let k = <[u8; 4]>::try_from(&k[..]).map_err(|_| "pending key")?;
1586                Ok((u32::from_be_bytes(k), v.to_vec()))
1587            })
1588            .collect()
1589    }
1590
1591    /// A single ledger waiting for its block.
1592    pub fn pending_ledger(&self, sequence: u32) -> Result<Option<Vec<u8>>, String> {
1593        Ok(self
1594            .pending
1595            .get(sequence.to_be_bytes())
1596            .map_err(err)?
1597            .map(|v| v.to_vec()))
1598    }
1599
1600    /// Removes pending ledgers up to `upto` inclusive; their block is already written.
1601    pub fn drop_pending(&self, upto: u32) -> Result<(), String> {
1602        let mut b = self.db.batch();
1603        for g in self.pending.range(..=upto.to_be_bytes()) {
1604            let k = g.key().map_err(err)?;
1605            b.remove(&self.pending, k);
1606        }
1607        b.commit().map_err(err)
1608    }
1609
1610    pub fn persist(&self) -> Result<(), String> {
1611        self.db.persist(PersistMode::SyncAll).map_err(err)
1612    }
1613
1614    /// Object `key` as of ledger `at`; `None` if it does not exist (not created or deleted).
1615    pub fn get(&self, key: &[u8; 32], at: u32) -> Result<Option<Vec<u8>>, String> {
1616        Ok(self
1617            .version(key, at)?
1618            .and_then(|(_, v)| (!v.is_empty()).then_some(v)))
1619    }
1620
1621    /// Attaches the state before the snapshot (the version index over cold
1622    /// history). From then on `version`, `get` and `get_many` answer for its range
1623    /// too.
1624    pub fn set_old_state(&self, old: std::sync::Arc<dyn OldState>) {
1625        *self.old.write().unwrap_or_else(|p| p.into_inner()) = Some(old);
1626    }
1627
1628    /// The attached old state, unless the current request may not read it
1629    /// (one from a public listener, see `limits::start_public`).
1630    fn old(&self) -> Option<std::sync::Arc<dyn OldState>> {
1631        if !crate::limits::old_state_allowed() {
1632            return None;
1633        }
1634        self.old.read().unwrap_or_else(|p| p.into_inner()).clone()
1635    }
1636
1637    /// Ledgers the attached old state answers for, if one is attached and the
1638    /// current request may read it.
1639    pub fn old_range(&self) -> Option<(u32, u32)> {
1640        self.old().map(|o| o.range())
1641    }
1642
1643    /// Whether state as of ledger `seq` can be read: from the snapshot on, or
1644    /// within the range of the attached old state.
1645    pub fn serves(&self, seq: u32) -> Result<bool, String> {
1646        if self.base()?.is_some_and(|b| seq >= b) {
1647            return Ok(true);
1648        }
1649        Ok(self
1650            .old_range()
1651            .is_some_and(|(lo, hi)| seq >= lo && seq <= hi))
1652    }
1653
1654    /// The last version of `key` written up to ledger `at`: the ledger and the
1655    /// object, empty if it was deleted in that ledger. Below the snapshot it is
1656    /// read from the attached old state, within its range.
1657    pub fn version(&self, key: &[u8; 32], at: u32) -> Result<Option<(u32, Vec<u8>)>, String> {
1658        match self.base()? {
1659            Some(b) if at >= b => {}
1660            _ => {
1661                if let Some(o) = self.old() {
1662                    let (lo, hi) = o.range();
1663                    if at >= lo && at <= hi {
1664                        return o.version(key, at);
1665                    }
1666                }
1667                return Err(format!(
1668                    "no state for ledger {at}: it is before the snapshot"
1669                ));
1670            }
1671        }
1672        let Some(guard) = self
1673            .objects
1674            .range(version_key(key, 0)..=version_key(key, at))
1675            .next_back()
1676        else {
1677            return Ok(None);
1678        };
1679        let (k, v) = guard.into_inner().map_err(err)?;
1680        let seq = u32::from_be_bytes(
1681            k[32..36]
1682                .try_into()
1683                .map_err(|_| "bad version key".to_string())?,
1684        );
1685        Ok(Some((seq, v.to_vec())))
1686    }
1687
1688    /// Objects `keys` as of ledger `at`, in the same order. Each version read is a
1689    /// range seek across all LSM levels (about 0.2 ms), so large sets are read
1690    /// on several threads.
1691    pub fn get_many(&self, keys: &[[u8; 32]], at: u32) -> Result<Vec<Option<Vec<u8>>>, String> {
1692        const PER_THREAD: usize = 32;
1693        const THREADS: usize = 6;
1694        if keys.len() <= PER_THREAD {
1695            return keys.iter().map(|k| self.get(k, at)).collect();
1696        }
1697        let chunk = keys.len().div_ceil(THREADS).max(PER_THREAD);
1698        std::thread::scope(|s| {
1699            let parts: Vec<_> = keys
1700                .chunks(chunk)
1701                .map(|c| s.spawn(move || c.iter().map(|k| self.get(k, at)).collect::<Vec<_>>()))
1702                .collect();
1703            let mut out = Vec::with_capacity(keys.len());
1704            for p in parts {
1705                for r in p.join().map_err(|_| "reader thread panicked".to_string())? {
1706                    out.push(r?);
1707                }
1708            }
1709            Ok(out)
1710        })
1711    }
1712
1713    /// All objects as of ledger `at`, in ascending key order.
1714    pub fn objects_at(
1715        &self,
1716        at: u32,
1717    ) -> impl Iterator<Item = Result<([u8; 32], Vec<u8>), String>> + '_ {
1718        self.objects_after(at, None)
1719    }
1720
1721    /// Like `objects_after`, but for `ledger_data` pages: it jumps from key to key
1722    /// and finds the version at `at` with a seek. The cost of a page depends on its
1723    /// size, not on how many versions the keys along the way have piled up
1724    /// (LedgerHashes and busy accounts change almost every ledger).
1725    pub fn objects_page(
1726        &self,
1727        at: u32,
1728        after: Option<&[u8; 32]>,
1729    ) -> impl Iterator<Item = Result<([u8; 32], Vec<u8>), String>> + '_ {
1730        use std::ops::Bound;
1731        let mut from = match after {
1732            Some(k) => Bound::Excluded(version_key(k, u32::MAX).to_vec()),
1733            None => Bound::Unbounded,
1734        };
1735        let mut done = false;
1736        std::iter::from_fn(move || {
1737            while !done {
1738                let next = self
1739                    .objects
1740                    .range::<Vec<u8>, _>((from.clone(), Bound::Unbounded))
1741                    .next();
1742                let k = match next.map(|g| g.key()) {
1743                    None => {
1744                        done = true;
1745                        return None;
1746                    }
1747                    Some(Err(e)) => {
1748                        done = true;
1749                        return Some(Err(err(e)));
1750                    }
1751                    Some(Ok(k)) => k,
1752                };
1753                let mut key = [0u8; 32];
1754                key.copy_from_slice(&k[..32]);
1755                from = Bound::Excluded(version_key(&key, u32::MAX).to_vec());
1756                match self.get(&key, at) {
1757                    Ok(Some(d)) => return Some(Ok((key, d))),
1758                    Ok(None) => {}
1759                    Err(e) => {
1760                        done = true;
1761                        return Some(Err(e));
1762                    }
1763                }
1764            }
1765            None
1766        })
1767    }
1768
1769    /// Objects as of ledger `at` with keys strictly greater than `after`, in
1770    /// ascending key order.
1771    pub fn objects_after(
1772        &self,
1773        at: u32,
1774        after: Option<&[u8; 32]>,
1775    ) -> impl Iterator<Item = Result<([u8; 32], Vec<u8>), String>> + '_ {
1776        use std::ops::Bound;
1777        let start = match after {
1778            Some(k) => Bound::Excluded(version_key(k, u32::MAX).to_vec()),
1779            None => Bound::Unbounded,
1780        };
1781        let mut it = self.objects.range::<Vec<u8>, _>((start, Bound::Unbounded));
1782        let mut current: Option<([u8; 32], Vec<u8>)> = None;
1783        let mut done = false;
1784        std::iter::from_fn(move || {
1785            loop {
1786                if done {
1787                    return None;
1788                }
1789                let next = match it.next() {
1790                    Some(g) => match g.into_inner() {
1791                        Ok(kv) => Some(kv),
1792                        Err(e) => return Some(Err(err(e))),
1793                    },
1794                    None => None,
1795                };
1796                let Some((k, v)) = next else {
1797                    done = true;
1798                    return current.take().filter(|(_, d)| !d.is_empty()).map(Ok);
1799                };
1800                let mut key = [0u8; 32];
1801                key.copy_from_slice(&k[..32]);
1802                let seq = u32::from_be_bytes([k[32], k[33], k[34], k[35]]);
1803                let emitted = match &current {
1804                    Some((ck, _)) if *ck != key => current.take(),
1805                    _ => None,
1806                };
1807                if seq <= at {
1808                    current = Some((key, v.to_vec()));
1809                } else if current.as_ref().is_none_or(|(ck, _)| *ck != key) {
1810                    // A version later than the requested ledger, and the key has no earlier one.
1811                    current = None;
1812                }
1813                if let Some((ek, ed)) = emitted
1814                    && !ed.is_empty()
1815                {
1816                    return Some(Ok((ek, ed)));
1817                }
1818            }
1819        })
1820    }
1821}
1822
1823#[cfg(test)]
1824mod tests {
1825    use super::*;
1826
1827    fn ch(key: u8, change: Change, data: &[u8]) -> StateChange {
1828        StateChange {
1829            key: [key; 32],
1830            change,
1831            data: data.to_vec(),
1832        }
1833    }
1834
1835    /// MPToken: issuance `id`, holder `acc`, MPTAmount 7.
1836    fn mptoken(id: u8, acc: u8) -> Vec<u8> {
1837        let mut d = vec![0x11, 0x00, 0x7F, 0x22, 0, 0, 0, 0, 0x30, 0x1A];
1838        d.extend(7u64.to_be_bytes());
1839        d.extend([0x81, 0x14]);
1840        d.extend([acc; 20]);
1841        d.extend([0x01, 0x15]);
1842        d.extend([id; 24]);
1843        d
1844    }
1845
1846    #[test]
1847    fn mpt_holders_follow_creation_and_deletion() {
1848        let holders = |s: &StateStore, at, after: Option<[u8; 20]>, limit| {
1849            s.mpt_holders(&[9; 24], at, after.as_ref(), limit)
1850                .unwrap()
1851                .into_iter()
1852                .map(|(a, k)| (a[0], k[0]))
1853                .collect::<Vec<_>>()
1854        };
1855        for ensure_after_apply in [false, true] {
1856            let dir = tempfile::tempdir().unwrap();
1857            let s = StateStore::open(dir.path()).unwrap();
1858            let snap = vec![
1859                ([5u8; 32], mptoken(9, 0x20)),
1860                ([6u8; 32], b"not an mptoken".to_vec()),
1861                ([7u8; 32], mptoken(8, 0x01)),
1862            ];
1863            s.load_snapshot(100, &[0; 118], snap.into_iter().map(Ok))
1864                .unwrap();
1865            if !ensure_after_apply {
1866                assert_eq!(s.ensure_mpt_index().unwrap(), Some(2));
1867            }
1868            s.apply(101, &[1; 118], &[ch(4, Change::Created, &mptoken(9, 0x10))])
1869                .unwrap();
1870            s.apply(
1871                102,
1872                &[2; 118],
1873                &[ch(5, Change::Deleted, b""), ch(6, Change::Deleted, b"")],
1874            )
1875            .unwrap();
1876            if ensure_after_apply {
1877                assert!(s.ensure_mpt_index().unwrap().is_some());
1878            }
1879            assert_eq!(s.ensure_mpt_index().unwrap(), None);
1880            assert_eq!(holders(&s, 100, None, 10), vec![(0x20, 5)]);
1881            assert_eq!(holders(&s, 101, None, 10), vec![(0x10, 4), (0x20, 5)]);
1882            assert_eq!(holders(&s, 101, None, 1), vec![(0x10, 4)]);
1883            assert_eq!(holders(&s, 101, Some([0x10; 20]), 10), vec![(0x20, 5)]);
1884            assert_eq!(holders(&s, 102, None, 10), vec![(0x10, 4)]);
1885        }
1886    }
1887
1888    #[test]
1889    fn versions_answer_by_ledger() {
1890        let dir = tempfile::tempdir().unwrap();
1891        let s = StateStore::open(dir.path()).unwrap();
1892        let snap = vec![([1u8; 32], b"a1".to_vec()), ([2u8; 32], b"b1".to_vec())];
1893        assert_eq!(
1894            s.load_snapshot(100, &[0; 118], snap.into_iter().map(Ok))
1895                .unwrap(),
1896            2
1897        );
1898        s.apply(
1899            101,
1900            &[1; 118],
1901            &[
1902                ch(1, Change::Modified, b"a2"),
1903                ch(3, Change::Created, b"c1"),
1904            ],
1905        )
1906        .unwrap();
1907        s.apply(102, &[2; 118], &[ch(2, Change::Deleted, b"")])
1908            .unwrap();
1909        assert!(s.apply(104, &[4; 118], &[]).is_err(), "only in order");
1910
1911        assert_eq!(s.get(&[1; 32], 100).unwrap().unwrap(), b"a1");
1912        assert_eq!(s.get(&[1; 32], 101).unwrap().unwrap(), b"a2");
1913        assert_eq!(s.get(&[1; 32], 500).unwrap().unwrap(), b"a2");
1914        assert_eq!(s.get(&[2; 32], 101).unwrap().unwrap(), b"b1");
1915        assert_eq!(s.get(&[2; 32], 102).unwrap(), None);
1916        assert_eq!(s.get(&[3; 32], 100).unwrap(), None);
1917        assert_eq!(s.get(&[3; 32], 101).unwrap().unwrap(), b"c1");
1918        assert!(s.get(&[1; 32], 99).is_err());
1919
1920        // A batch read matches reading one by one, in the same order, and runs
1921        // on several threads.
1922        let many: Vec<[u8; 32]> = (0..100).map(|i| [[1u8, 2, 3, 9][i % 4]; 32]).collect();
1923        for at in [100, 101, 102] {
1924            let one: Vec<_> = many.iter().map(|k| s.get(k, at).unwrap()).collect();
1925            assert_eq!(s.get_many(&many, at).unwrap(), one);
1926        }
1927        assert!(s.get_many(&many, 99).is_err());
1928
1929        let at = |n| -> Vec<(u8, Vec<u8>)> {
1930            s.objects_at(n)
1931                .map(|r| r.map(|(k, v)| (k[0], v)).unwrap())
1932                .collect()
1933        };
1934        assert_eq!(at(100), vec![(1, b"a1".to_vec()), (2, b"b1".to_vec())]);
1935        assert_eq!(
1936            at(101),
1937            vec![
1938                (1, b"a2".to_vec()),
1939                (2, b"b1".to_vec()),
1940                (3, b"c1".to_vec())
1941            ]
1942        );
1943        assert_eq!(at(102), vec![(1, b"a2".to_vec()), (3, b"c1".to_vec())]);
1944        assert_eq!(s.header(101).unwrap().unwrap(), vec![1; 118]);
1945        assert_eq!(s.last().unwrap(), Some(102));
1946    }
1947
1948    #[test]
1949    fn survives_reopen() {
1950        let dir = tempfile::tempdir().unwrap();
1951        {
1952            let s = StateStore::open(dir.path()).unwrap();
1953            s.load_snapshot(
1954                7,
1955                &[0; 118],
1956                std::iter::once(Ok(([9u8; 32], b"x".to_vec()))),
1957            )
1958            .unwrap();
1959            s.apply(8, &[0; 118], &[ch(9, Change::Modified, b"y")])
1960                .unwrap();
1961            s.persist().unwrap();
1962        }
1963        let s = StateStore::open(dir.path()).unwrap();
1964        assert_eq!((s.base().unwrap(), s.last().unwrap()), (Some(7), Some(8)));
1965        assert_eq!(s.get(&[9; 32], 8).unwrap().unwrap(), b"y");
1966    }
1967
1968    fn empty(n: u32) -> Ledger {
1969        Ledger {
1970            header: header(n),
1971            transactions: Vec::new(),
1972            changes: Vec::new(),
1973        }
1974    }
1975
1976    fn header(n: u32) -> Vec<u8> {
1977        let mut h = vec![0u8; 118];
1978        h[..4].copy_from_slice(&n.to_be_bytes());
1979        h
1980    }
1981
1982    /// Metadata: TransactionIndex and one modified object with an account.
1983    fn meta(index: u32, account: u8) -> Vec<u8> {
1984        let mut m = vec![0x20, 0x1C];
1985        m.extend(index.to_be_bytes());
1986        m.extend([0xF8, 0xE5, 0xE7, 0x81, 20]);
1987        m.extend([account; 20]);
1988        m.extend([0xE1, 0xE1, 0xF1]);
1989        m
1990    }
1991
1992    #[test]
1993    fn indexes_answer_tx_ledger_and_account_history() {
1994        let dir = tempfile::tempdir().unwrap();
1995        let s = StateStore::open(dir.path()).unwrap();
1996        s.load_snapshot(1, &header(1), std::iter::empty()).unwrap();
1997        // Ledgers 2..=4 with two transactions each; account 7 is in all of them,
1998        // account 8 only in the second transaction of ledger 3. The order in the block
1999        // is the reverse of the application order, and history follows TransactionIndex.
2000        for n in 2..=4u32 {
2001            let second = if n == 3 { 8 } else { 7 };
2002            let l = Ledger {
2003                header: header(n),
2004                transactions: vec![
2005                    (vec![n as u8, 1], meta(1, second)),
2006                    (vec![n as u8, 0], meta(0, 7)),
2007                ],
2008                changes: Vec::new(),
2009            };
2010            s.apply_ledger(n, &l, b"").unwrap();
2011        }
2012        let id = witness_core::shamap::tx_id(&[3, 1]);
2013        assert_eq!(s.tx_location(&id).unwrap(), Some((3, 0)));
2014        let h = Ledger::header(&empty(4)).unwrap().hash();
2015        assert_eq!(s.ledger_by_hash(&h).unwrap(), Some(4));
2016
2017        let pos = |l, i| TxPosition {
2018            ledger: l,
2019            index: i,
2020        };
2021        let page = s.account_tx(&[7; 20], 1, 10, false, 3, None).unwrap();
2022        let got: Vec<_> = page.transactions.iter().map(|t| (t.at, t.pos)).collect();
2023        assert_eq!(got, vec![(pos(4, 1), 0), (pos(4, 0), 1), (pos(3, 0), 1)]);
2024        assert_eq!(page.marker, Some(pos(2, 1)));
2025        let rest = s
2026            .account_tx(&[7; 20], 1, 10, false, 3, page.marker)
2027            .unwrap();
2028        assert_eq!(rest.transactions.len(), 2);
2029        assert_eq!(rest.marker, None);
2030        let fwd = s.account_tx(&[7; 20], 3, 4, true, 10, None).unwrap();
2031        let got: Vec<_> = fwd.transactions.iter().map(|t| t.at).collect();
2032        assert_eq!(got, vec![pos(3, 0), pos(4, 0), pos(4, 1)]);
2033        let only = s.account_tx(&[8; 20], 1, 10, true, 10, None).unwrap();
2034        assert_eq!(only.transactions.len(), 1);
2035        assert_eq!(only.transactions[0].at, pos(3, 1));
2036    }
2037
2038    /// A header with a sequence and AccountHash.
2039    fn header_with(n: u32, account_hash: [u8; 32]) -> Vec<u8> {
2040        let mut h = header(n);
2041        h[76..108].copy_from_slice(&account_hash);
2042        h
2043    }
2044
2045    #[test]
2046    fn state_root_is_checked_on_every_ledger() {
2047        use witness_core::shamap::{root, state_leaf_hash};
2048        let dir = tempfile::tempdir().unwrap();
2049        let s = StateStore::open(dir.path()).unwrap();
2050        let objs: Vec<([u8; 32], Vec<u8>)> = (1..=5u8).map(|i| ([i; 32], vec![i, i])).collect();
2051        let leaves = |o: &[([u8; 32], Vec<u8>)]| -> Vec<([u8; 32], [u8; 32])> {
2052            o.iter().map(|(k, v)| (*k, state_leaf_hash(v, k))).collect()
2053        };
2054        let h1 = header_with(1, root(&leaves(&objs)));
2055        s.load_snapshot(1, &h1, objs.clone().into_iter().map(Ok))
2056            .unwrap();
2057        assert_eq!(s.build_tree().unwrap(), (1, 5));
2058        assert_eq!(s.tree_ledger().unwrap(), Some(1));
2059
2060        // Ledger 2: modify object 1, delete 2, create 9, with a correct root.
2061        let after: Vec<([u8; 32], Vec<u8>)> = vec![
2062            ([1; 32], vec![7]),
2063            ([3; 32], vec![3, 3]),
2064            ([4; 32], vec![4, 4]),
2065            ([5; 32], vec![5, 5]),
2066            ([9; 32], vec![9]),
2067        ];
2068        let l2 = Ledger {
2069            header: header_with(2, root(&leaves(&after))),
2070            transactions: Vec::new(),
2071            changes: vec![
2072                ch(1, Change::Modified, &[7]),
2073                ch(2, Change::Deleted, b""),
2074                ch(9, Change::Created, &[9]),
2075            ],
2076        };
2077        s.apply_ledger(2, &l2, b"").unwrap();
2078        assert_eq!(
2079            (s.last().unwrap(), s.tree_ledger().unwrap()),
2080            (Some(2), Some(2))
2081        );
2082
2083        // Ledger 3 with a tampered object: the root does not match, so it is rejected.
2084        let l3 = Ledger {
2085            header: header_with(3, root(&leaves(&after))),
2086            transactions: Vec::new(),
2087            changes: vec![ch(3, Change::Modified, &[0xFF])],
2088        };
2089        let e = s.apply_ledger(3, &l3, b"").unwrap_err();
2090        assert!(e.contains("state root"), "{e}");
2091        assert_eq!(s.last().unwrap(), Some(2));
2092        assert_eq!(s.get(&[3; 32], 2).unwrap().unwrap(), vec![3, 3]);
2093        assert_eq!(s.tree_root().unwrap(), root(&leaves(&after)));
2094
2095        // Proofs from the tree match the header's AccountHash.
2096        use witness_core::stateproof::StateProof;
2097        let proof = |k: [u8; 32]| {
2098            let t = s.tree_path(&k).unwrap();
2099            assert_eq!(t.ledger, 2);
2100            let (object, other) = match &t.leaf {
2101                Leaf::Present(o) => (Some(o.clone()), None),
2102                Leaf::Empty => (None, None),
2103                Leaf::Other(ok, o) => (None, Some((*ok, o.clone()))),
2104            };
2105            StateProof::new(
2106                &t.header,
2107                &k,
2108                object.as_deref(),
2109                other.as_ref().map(|(k, o)| (k, &o[..])),
2110                &t.path,
2111            )
2112            .verify()
2113            .unwrap()
2114        };
2115        assert!(proof([1; 32]).present);
2116        assert!(proof([9; 32]).present);
2117        assert!(!proof([2; 32]).present, "deleted in ledger 2");
2118        let mut near = [3u8; 32];
2119        near[31] = 4;
2120        assert!(
2121            !proof(near).present,
2122            "neighbouring key under the same prefix"
2123        );
2124    }
2125
2126    #[test]
2127    fn paths_at_earlier_ledgers_from_the_tree_history() {
2128        use std::collections::BTreeMap;
2129        use witness_core::sha512_half;
2130        use witness_core::shamap::{root, state_leaf_hash};
2131        use witness_core::stateproof::StateProof;
2132        let dir = tempfile::tempdir().unwrap();
2133        let s = StateStore::open(dir.path()).unwrap();
2134        // Dense enough that every node above depth 3 is an inner node, as on
2135        // mainnet; the subtrees at depth 3 hold zero, one or a few keys.
2136        let key = |i: u32| sha512_half(&i.to_be_bytes());
2137        let mut state: BTreeMap<[u8; 32], Vec<u8>> =
2138            (0..6000u32).map(|i| (key(i), vec![i as u8, 1])).collect();
2139        let hdr = |seq: u32, st: &BTreeMap<[u8; 32], Vec<u8>>| {
2140            let leaves: Vec<_> = st
2141                .iter()
2142                .map(|(k, v)| (*k, state_leaf_hash(v, k)))
2143                .collect();
2144            header_with(seq, root(&leaves))
2145        };
2146        s.load_snapshot(1, &hdr(1, &state), state.clone().into_iter().map(Ok))
2147            .unwrap();
2148        s.build_tree().unwrap();
2149        let snapshot = state.clone();
2150        let mut at = BTreeMap::new();
2151        for seq in 2..=300u32 {
2152            let mut changes = Vec::new();
2153            for j in 0..12u32 {
2154                let i = (seq * 131 + j * 977) % 6400;
2155                let (k, change) = match (state.contains_key(&key(i)), (seq + j) % 5) {
2156                    (true, 0) => (key(i), Change::Deleted),
2157                    (true, _) => (key(i), Change::Modified),
2158                    (false, _) => (key(i), Change::Created),
2159                };
2160                if changes.iter().any(|c: &StateChange| c.key == k) {
2161                    continue;
2162                }
2163                let data = vec![i as u8, seq as u8, 2];
2164                match change {
2165                    Change::Deleted => state.remove(&k),
2166                    _ => state.insert(k, data.clone()),
2167                };
2168                changes.push(StateChange {
2169                    key: k,
2170                    change,
2171                    data: if change == Change::Deleted {
2172                        Vec::new()
2173                    } else {
2174                        data
2175                    },
2176                });
2177            }
2178            let l = Ledger {
2179                header: hdr(seq, &state),
2180                transactions: Vec::new(),
2181                changes,
2182            };
2183            s.apply_ledger(seq, &l, b"").unwrap();
2184            if [2, 3, 100, 255, 256, 257, 300].contains(&seq) {
2185                at.insert(seq, state.clone());
2186            }
2187        }
2188        assert_eq!(s.levels_from().unwrap(), Some(2));
2189        assert!(
2190            s.state_path_at(&key(1), 1)
2191                .unwrap_err()
2192                .contains("start at ledger 2")
2193        );
2194
2195        // As if the history had started at 256: rebuilt down to the snapshot,
2196        // in windows, it is the history written while loading, plus ledger 1.
2197        let records = |s: &StateStore| -> BTreeMap<u32, Vec<u8>> {
2198            s.levels
2199                .iter()
2200                .map(|g| {
2201                    let (k, v) = g.into_inner().unwrap();
2202                    (u32::from_be_bytes(k[..].try_into().unwrap()), v.to_vec())
2203                })
2204                .collect()
2205        };
2206        let written = records(&s);
2207        let mut b = s.db.batch();
2208        for seq in written.keys().filter(|seq| **seq < 256) {
2209            b.remove(&s.levels, seq.to_be_bytes());
2210        }
2211        b.insert(&s.meta, LEVELS_FROM, 256u32.to_be_bytes());
2212        b.commit().unwrap();
2213        assert!(s.state_path_at(&key(1), 100).is_err());
2214        let scratch = dir.path().join("scratch");
2215        // Stopped after a quarter of the subtrees, it goes on from there.
2216        let stopped = s.backfill_levels(&scratch, 1, |m| {
2217            assert_ne!(m, "1024 of 4096 subtrees replayed")
2218        });
2219        assert!(stopped.is_err());
2220        assert!(scratch.exists());
2221        assert_eq!(s.levels_from().unwrap(), Some(256));
2222        let seen = std::sync::Mutex::new(Vec::new());
2223        assert_eq!(
2224            s.backfill_levels(&scratch, 4, |m| seen.lock().unwrap().push(m))
2225                .unwrap(),
2226            Some((1, 255))
2227        );
2228        assert_eq!(
2229            seen.into_inner().unwrap()[0],
2230            "1024 of 4096 subtrees already replayed"
2231        );
2232        assert_eq!(s.levels_from().unwrap(), Some(1));
2233        assert!(!scratch.exists());
2234        let rebuilt = records(&s);
2235        // Ledger 2 was a full set while loading; the rebuild puts that at 1.
2236        for (seq, v) in written.iter().filter(|(seq, _)| **seq != 2) {
2237            assert_eq!(rebuilt.get(seq), Some(v), "ledger {seq}");
2238        }
2239        assert_eq!(rebuilt[&1].len(), LEVEL_SLOTS * 34);
2240        assert_eq!(s.backfill_levels(&scratch, 4, |_| {}).unwrap(), None);
2241        at.insert(1, snapshot.clone());
2242        for (seq, st) in &at {
2243            for i in [0u32, 7, 4321, 6001, 6399, 9999] {
2244                let k = key(i);
2245                let t = s.state_path_at(&k, *seq).unwrap();
2246                let (object, other) = match &t.leaf {
2247                    Leaf::Present(o) => (Some(o.clone()), None),
2248                    Leaf::Empty => (None, None),
2249                    Leaf::Other(ok, o) => (None, Some((*ok, o.clone()))),
2250                };
2251                let p = StateProof::new(
2252                    &t.header,
2253                    &k,
2254                    object.as_deref(),
2255                    other.as_ref().map(|(k, o)| (k, &o[..])),
2256                    &t.path,
2257                )
2258                .verify()
2259                .unwrap_or_else(|e| panic!("ledger {seq}, key {i}: {e}"));
2260                assert_eq!(p.ledger_index, *seq);
2261                assert_eq!(object.as_ref(), st.get(&k), "ledger {seq}, key {i}");
2262            }
2263        }
2264    }
2265
2266    #[test]
2267    fn nft_index_answers_owner_uri_history_and_issuer() {
2268        use crate::nftindex::NftLedger;
2269        let dir = tempfile::tempdir().unwrap();
2270        let s = StateStore::open(dir.path()).unwrap();
2271        // Token 2 of issuer [4; 20] with taxon 0 (serial 0 ciphers taxon 0 as 2459).
2272        let mut t = [0u8; 32];
2273        t[4..24].fill(4);
2274        t[24..28].copy_from_slice(&2459u32.to_be_bytes());
2275        let put = |seq: u32, n: NftLedger| {
2276            let mut b = s.db.batch();
2277            s.put_nft_rows(&mut b, seq, &n);
2278            b.commit().unwrap();
2279        };
2280        // Minted to 7 in ledger 10, sold to 8 in 12 (two transactions), URI changed in 13, burned in 15.
2281        put(
2282            10,
2283            NftLedger {
2284                txs: vec![(t, 3, 0)],
2285                owners: [(t, ([7; 20], false))].into(),
2286                uris: [(t, vec![1])].into(),
2287                minted: [t].into(),
2288                ..NftLedger::default()
2289            },
2290        );
2291        put(
2292            12,
2293            NftLedger {
2294                txs: vec![(t, 0, 5), (t, 4, 1)],
2295                owners: [(t, ([8; 20], false))].into(),
2296                ..NftLedger::default()
2297            },
2298        );
2299        put(
2300            13,
2301            NftLedger {
2302                txs: vec![(t, 2, 0)],
2303                uris: [(t, vec![2])].into(),
2304                ..NftLedger::default()
2305            },
2306        );
2307        put(
2308            15,
2309            NftLedger {
2310                txs: vec![(t, 1, 0)],
2311                owners: [(t, ([8; 20], true))].into(),
2312                ..NftLedger::default()
2313            },
2314        );
2315        assert_eq!(s.nft_at(&t, 9).unwrap(), None);
2316        assert_eq!(s.nft_at(&t, 11).unwrap(), Some((10, [7; 20], false)));
2317        assert_eq!(s.nft_at(&t, 14).unwrap(), Some((12, [8; 20], false)));
2318        assert_eq!(s.nft_at(&t, 99).unwrap(), Some((15, [8; 20], true)));
2319        assert_eq!(s.nft_uri_at(&t, 12).unwrap(), Some(vec![1]));
2320        assert_eq!(s.nft_uri_at(&t, 13).unwrap(), Some(vec![2]));
2321        let pos = |l, i| TxPosition {
2322            ledger: l,
2323            index: i,
2324        };
2325        let all = |fwd| {
2326            s.nft_txs(&t, pos(0, 0), pos(u32::MAX, u32::MAX), fwd, 10)
2327                .unwrap()
2328                .iter()
2329                .map(|x| (x.at, x.pos))
2330                .collect::<Vec<_>>()
2331        };
2332        assert_eq!(
2333            all(true),
2334            vec![
2335                (pos(10, 3), 0),
2336                (pos(12, 0), 5),
2337                (pos(12, 4), 1),
2338                (pos(13, 2), 0),
2339                (pos(15, 1), 0)
2340            ]
2341        );
2342        assert_eq!(all(false)[0], (pos(15, 1), 0));
2343        let some = s.nft_txs(&t, pos(12, 1), pos(13, 2), true, 10).unwrap();
2344        assert_eq!(some.len(), 2);
2345        assert_eq!(s.nfts_by_issuer(&[4; 20], None, None, 10).unwrap(), vec![t]);
2346        assert_eq!(
2347            s.nfts_by_issuer(&[4; 20], Some(0), None, 10).unwrap(),
2348            vec![t]
2349        );
2350        assert!(
2351            s.nfts_by_issuer(&[4; 20], Some(1), None, 10)
2352                .unwrap()
2353                .is_empty()
2354        );
2355        assert!(
2356            s.nfts_by_issuer(&[4; 20], None, Some((0, t)), 10)
2357                .unwrap()
2358                .is_empty()
2359        );
2360        assert!(
2361            s.nfts_by_issuer(&[5; 20], None, None, 10)
2362                .unwrap()
2363                .is_empty()
2364        );
2365    }
2366
2367    #[test]
2368    fn nft_backfill_resumes_and_reaches_the_live_part() {
2369        let dir = tempfile::tempdir().unwrap();
2370        let s = StateStore::open(dir.path()).unwrap();
2371        s.load_snapshot(1, &header(1), std::iter::empty()).unwrap();
2372        assert_eq!(s.start_nft_index().unwrap(), 2);
2373        assert_eq!(s.start_nft_index().unwrap(), 2);
2374        assert_eq!(s.nft_coverage().unwrap(), None);
2375        let read = |seqs: &[u32]| -> Result<Vec<Ledger>, String> {
2376            if seqs.contains(&1) {
2377                return Err("ledger 1 is missing".into());
2378            }
2379            Ok(seqs.iter().map(|&n| empty(n)).collect())
2380        };
2381        // A missing ledger stops the backfill; progress before it is kept.
2382        assert!(s.backfill_nfts(0, 1, &read, &|_, _| {}).is_err());
2383        assert_eq!(s.meta_u32(NFT_FILL).unwrap(), Some(1));
2384        let read = |seqs: &[u32]| -> Result<Vec<Ledger>, String> {
2385            Ok(seqs.iter().map(|&n| empty(n)).collect())
2386        };
2387        assert_eq!(
2388            s.backfill_nfts(0, 1, &read, &|_, _| {}).unwrap(),
2389            Some((0, 2))
2390        );
2391        assert_eq!(s.nft_coverage().unwrap(), Some(0));
2392        assert_eq!(s.backfill_nfts(0, 1, &read, &|_, _| {}).unwrap(), None);
2393        // Seeding does nothing once the backfill has started.
2394        s.seed_nfts().unwrap();
2395        assert_eq!(s.nft_coverage().unwrap(), Some(0));
2396    }
2397
2398    #[test]
2399    fn nft_index_is_seeded_from_the_snapshot_state() {
2400        // An NFT page of account [7; 20] holding one token with URI AB.
2401        let mut key = [7u8; 32];
2402        key[20..].fill(0xFF);
2403        let token = [9u8; 32];
2404        let mut page = vec![0x11, 0x00, 0x50];
2405        page.extend([0xFA, 0xEC, 0x5A]);
2406        page.extend(token);
2407        page.extend([0x75, 0x01, 0xAB, 0xE1, 0xF1]);
2408        let dir = tempfile::tempdir().unwrap();
2409        let s = StateStore::open(dir.path()).unwrap();
2410        s.load_snapshot(5, &header(5), std::iter::once(Ok((key, page))))
2411            .unwrap();
2412        s.start_nft_index().unwrap();
2413        s.seed_nfts().unwrap();
2414        assert_eq!(s.nft_at(&token, 5).unwrap(), Some((5, [7; 20], false)));
2415        assert_eq!(s.nft_uri_at(&token, 5).unwrap(), Some(vec![0xAB]));
2416        let read = |seqs: &[u32]| -> Result<Vec<Ledger>, String> {
2417            Ok(seqs.iter().map(|&n| empty(n)).collect())
2418        };
2419        assert_eq!(s.backfill_nfts(0, 8, &read, &|_, _| {}).unwrap(), None);
2420        assert_eq!(s.nft_coverage().unwrap(), Some(5));
2421    }
2422
2423    #[test]
2424    fn pending_ledgers_wait_for_their_block() {
2425        let dir = tempfile::tempdir().unwrap();
2426        let s = StateStore::open(dir.path()).unwrap();
2427        s.load_snapshot(1, &[0; 118], std::iter::empty()).unwrap();
2428        for n in 2..=5u32 {
2429            s.apply_ledger(n, &empty(n), &n.to_le_bytes()).unwrap();
2430        }
2431        s.drop_pending(3).unwrap();
2432        assert_eq!(
2433            s.pending().unwrap(),
2434            vec![
2435                (4, 4u32.to_le_bytes().to_vec()),
2436                (5, 5u32.to_le_bytes().to_vec())
2437            ]
2438        );
2439    }
2440}