Skip to main content

ledger_engine/
txindex.rs

1//! Static indexes for closed history: transaction by hash and
2//! account history. They are built once over an immutable range of ledgers;
3//! fresh ledgers still go into the fjall indexes.
4//!
5//! **Transaction by hash (`XTXH`).** The range's transactions are numbered in
6//! order: ledger, then position in the ledger. Buckets are keyed by the top `b`
7//! bits of the hash; a bucket holds fixed-width entries: a 16-bit fingerprint (the
8//! next bits of the hash) and the transaction number. The full hash is not stored:
9//! a candidate is read and checked by recomputing its hash, so a matching
10//! fingerprint never returns the wrong transaction. A false candidate for a missing
11//! hash happens with probability about bucket size / 65 536.
12//!
13//! **Account history (`XACC`).** Directory: account (20 bytes, ascending),
14//! offset and entry count; the lists hold positions (ledger, TransactionIndex) in
15//! ascending order, delta-encoded as varints. List order is account_tx order.
16//! Version 2 stores the same lists with Rice codes: a position becomes a transaction
17//! number within the partition (by ledger, then by TransactionIndex; the transaction
18//! count of every ledger is stored in the index), and the differences between
19//! numbers are written with one Rice parameter per list; rare large differences are
20//! written as length and bits. Lists longer than `SKIP_EVERY` get entry points every
21//! `SKIP_EVERY` positions (bit offset and the number before the block), so an
22//! account_tx page in either direction decodes one or two blocks, not the whole list.
23
24use std::collections::BTreeMap;
25
26use crate::index::AccountId;
27
28type Res<T> = Result<T, String>;
29
30const TXH_MAGIC: &[u8; 6] = b"XTXH\x00\x01";
31const ACC_MAGIC: &[u8; 6] = b"XACC\x00\x01";
32const ACC2_MAGIC: &[u8; 6] = b"XACC\x00\x02";
33/// Rice quotient from which a difference is written as length and bits.
34const RICE_ESCAPE: u64 = 16;
35/// Positions per block between entry points of a version 2 list.
36const SKIP_EVERY: u64 = 128;
37/// Target average bucket size used to pick the number of bucket bits.
38const BUCKET_TARGET: u64 = 64;
39
40fn u32_at(b: &[u8], at: usize) -> Res<u32> {
41    let x = b.get(at..at + 4).ok_or("index truncated")?;
42    Ok(u32::from_le_bytes([x[0], x[1], x[2], x[3]]))
43}
44
45/// Top 64 bits of a hash.
46pub(crate) fn top64(h: &[u8; 32]) -> u64 {
47    u64::from_be_bytes(h[..8].try_into().unwrap_or_default())
48}
49
50/// "Transaction by hash" index over a range of ledgers.
51#[derive(Debug)]
52pub struct TxHashIndex<'a> {
53    first: u32,
54    /// Where each ledger's transaction numbering starts (plus the end of the last one).
55    starts: Vec<u32>,
56    bucket_bits: u32,
57    ord_bits: u32,
58    offsets: &'a [u8],
59    entries: &'a [u8],
60}
61
62/// Builds the index: `ledgers` holds, for each ledger of the range in order,
63/// the hashes of its transactions in storage order.
64pub fn build_tx_index(first: u32, ledgers: &[Vec<[u8; 32]>]) -> Vec<u8> {
65    let counts: Vec<u32> = ledgers.iter().map(|l| l.len() as u32).collect();
66    let mut tops = Vec::with_capacity(counts.iter().map(|c| *c as usize).sum());
67    let mut ordinal = 0u32;
68    for txs in ledgers {
69        for h in txs {
70            tops.push((top64(h), ordinal));
71            ordinal += 1;
72        }
73    }
74    build_tx_index_tops(first, &counts, tops)
75}
76
77/// Same, from the top 64 bits of the hashes: (bits, transaction number in the range)
78/// and each ledger's transaction count, without full hashes in memory.
79pub fn build_tx_index_tops(first: u32, counts: &[u32], tops: Vec<(u64, u32)>) -> Vec<u8> {
80    let n = tops.len() as u64;
81    let bucket_bits = (64 - (n / BUCKET_TARGET).max(1).leading_zeros())
82        .saturating_sub(1)
83        .min(32);
84    let ord_bits = (64 - n.max(1).leading_zeros()).max(1);
85    let mut rows: Vec<(u64, u32, u32)> = Vec::with_capacity(n as usize);
86    for (t, ordinal) in tops {
87        let bucket = if bucket_bits == 0 {
88            0
89        } else {
90            (t >> (64 - bucket_bits)) as u32
91        };
92        let fp = ((t << bucket_bits) >> 48) as u32;
93        rows.push((u64::from(bucket), fp, ordinal));
94    }
95    rows.sort_unstable();
96    let mut out = TXH_MAGIC.to_vec();
97    out.extend(first.to_le_bytes());
98    out.extend((counts.len() as u32).to_le_bytes());
99    out.extend(n.to_le_bytes());
100    out.push(bucket_bits as u8);
101    out.push(ord_bits as u8);
102    let mut acc = 0u32;
103    for c in counts {
104        out.extend(acc.to_le_bytes());
105        acc += c;
106    }
107    out.extend(acc.to_le_bytes());
108    let buckets = 1u64 << bucket_bits;
109    let mut i = 0usize;
110    for bkt in 0..=buckets {
111        while i < rows.len() && rows[i].0 < bkt {
112            i += 1;
113        }
114        out.extend((i as u32).to_le_bytes());
115    }
116    // Entries: 16-bit fingerprint and number, packed back to back at bit level.
117    let width = 16 + ord_bits as usize;
118    let mut bits = vec![0u8; (rows.len() * width).div_ceil(8) + 8];
119    for (k, (_, fp, ord)) in rows.iter().enumerate() {
120        let v = (u64::from(*fp) << ord_bits) | u64::from(*ord);
121        put_bits(&mut bits, k * width, width, v);
122    }
123    out.extend(bits);
124    out
125}
126
127fn put_bits(b: &mut [u8], at: usize, width: usize, v: u64) {
128    for j in 0..width {
129        if v >> (width - 1 - j) & 1 == 1 {
130            let p = at + j;
131            b[p / 8] |= 0x80 >> (p % 8);
132        }
133    }
134}
135
136fn get_bits(b: &[u8], at: usize, width: usize) -> u64 {
137    let mut v = 0u64;
138    for j in 0..width {
139        let p = at + j;
140        v = (v << 1) | u64::from(b.get(p / 8).is_some_and(|x| x & (0x80 >> (p % 8)) != 0));
141    }
142    v
143}
144
145impl<'a> TxHashIndex<'a> {
146    pub fn open(b: &'a [u8]) -> Res<TxHashIndex<'a>> {
147        if !b.starts_with(TXH_MAGIC) {
148            return Err("not an XTXH index".into());
149        }
150        let first = u32_at(b, 6)?;
151        let ledgers = u32_at(b, 10)? as usize;
152        let n = u64::from_le_bytes(
153            b.get(14..22)
154                .ok_or("truncated")?
155                .try_into()
156                .map_err(|_| "n")?,
157        );
158        let bucket_bits = u32::from(*b.get(22).ok_or("truncated")?);
159        let ord_bits = u32::from(*b.get(23).ok_or("truncated")?);
160        if bucket_bits > 32 || ord_bits > 40 || ord_bits == 0 {
161            return Err("index parameters out of range".into());
162        }
163        let mut at = 24;
164        let mut starts = Vec::with_capacity(ledgers + 1);
165        for _ in 0..=ledgers {
166            starts.push(u32_at(b, at)?);
167            at += 4;
168        }
169        if u64::from(*starts.last().unwrap_or(&0)) != n {
170            return Err("transaction count does not match".into());
171        }
172        let off_len = ((1usize << bucket_bits) + 1) * 4;
173        let offsets = b.get(at..at + off_len).ok_or("buckets truncated")?;
174        let entries = &b[at + off_len..];
175        let need = (n as usize * (16 + ord_bits as usize)).div_ceil(8);
176        if entries.len() < need {
177            return Err("entries truncated".into());
178        }
179        Ok(TxHashIndex {
180            first,
181            starts,
182            bucket_bits,
183            ord_bits,
184            offsets,
185            entries,
186        })
187    }
188
189    /// Candidates (ledger, position) for a hash; they must be read and checked.
190    pub fn candidates(&self, h: &[u8; 32]) -> Res<Vec<(u32, u32)>> {
191        let t = top64(h);
192        let bucket = if self.bucket_bits == 0 {
193            0
194        } else {
195            (t >> (64 - self.bucket_bits)) as usize
196        };
197        let fp = (t << self.bucket_bits) >> 48;
198        let lo = u32_at(self.offsets, bucket * 4)? as usize;
199        let hi = u32_at(self.offsets, bucket * 4 + 4)? as usize;
200        let width = 16 + self.ord_bits as usize;
201        let mut out = Vec::new();
202        for k in lo..hi {
203            let v = get_bits(self.entries, k * width, width);
204            if v >> self.ord_bits == fp {
205                let ord = (v & ((1u64 << self.ord_bits) - 1)) as u32;
206                let li = self.starts.partition_point(|s| *s <= ord) - 1;
207                out.push((self.first + li as u32, ord - self.starts[li]));
208            }
209        }
210        Ok(out)
211    }
212}
213
214/// A position in account history: ledger and TransactionIndex.
215pub type Posting = (u32, u32);
216
217/// Builds the account history index from entries (account → positions).
218pub fn build_account_index(first: u32, postings: &BTreeMap<AccountId, Vec<Posting>>) -> Vec<u8> {
219    let mut lists = Vec::new();
220    let mut dir = Vec::new();
221    for (acc, ps) in postings {
222        let off = lists.len() as u64;
223        let (mut pl, mut pi) = (first, 0u32);
224        for (k, &(l, i)) in ps.iter().enumerate() {
225            let dl = l - if k == 0 { first } else { pl };
226            crate::varint::put(&mut lists, u64::from(dl));
227            // Within the same ledger store the TransactionIndex difference, otherwise the value itself.
228            crate::varint::put(
229                &mut lists,
230                u64::from(if dl == 0 && k > 0 { i - pi } else { i }),
231            );
232            (pl, pi) = (l, i);
233        }
234        dir.extend_from_slice(acc);
235        crate::varint::put(&mut dir, off);
236        crate::varint::put(&mut dir, ps.len() as u64);
237    }
238    let mut out = ACC_MAGIC.to_vec();
239    out.extend(first.to_le_bytes());
240    out.extend((postings.len() as u32).to_le_bytes());
241    out.extend((dir.len() as u32).to_le_bytes());
242    out.extend(dir);
243    out.extend(lists);
244    out
245}
246
247/// Builds a version 2 account history index with Rice-coded lists. `counts` is
248/// the transaction count of each ledger in the partition, in order.
249pub fn build_account_index_v2(
250    first: u32,
251    counts: &[u32],
252    postings: &BTreeMap<AccountId, Vec<Posting>>,
253) -> Res<Vec<u8>> {
254    let mut starts = Vec::with_capacity(counts.len());
255    let mut acc = 0u64;
256    let mut cs = Vec::new();
257    for &c in counts {
258        starts.push(acc);
259        acc += u64::from(c);
260        crate::varint::put(&mut cs, u64::from(c));
261    }
262    let key = |&(l, i): &Posting| -> Res<u64> {
263        let d = l.checked_sub(first).ok_or("ledger before the partition")? as usize;
264        match (starts.get(d), counts.get(d)) {
265            (Some(&s0), Some(&c)) if i < c => Ok(s0 + u64::from(i)),
266            _ => Err(format!("position {l}/{i} outside the partition")),
267        }
268    };
269    let mut lists = BitWriter::default();
270    let mut dir = Vec::new();
271    let mut skips = Vec::new();
272    for (a, ps) in postings {
273        let last = ps.last().map_or(Ok(0), key)?;
274        let mean = (last + 1) / ps.len().max(1) as u64;
275        let k = if mean <= 1 {
276            0
277        } else {
278            63 - mean.leading_zeros()
279        };
280        let off = lists.len;
281        let skip_off = skips.len() as u64;
282        let (mut prev, mut block_at, mut block_base) = (0u64, off, 0u64);
283        for (j, p) in ps.iter().enumerate() {
284            if j > 0 && (j as u64).is_multiple_of(SKIP_EVERY) {
285                crate::varint::put(&mut skips, lists.len - block_at);
286                crate::varint::put(&mut skips, prev - block_base);
287                (block_at, block_base) = (lists.len, prev);
288            }
289            let v = key(p)?;
290            lists.rice(v.checked_sub(prev).ok_or("positions not ascending")?, k);
291            prev = v;
292        }
293        dir.extend_from_slice(a);
294        crate::varint::put(&mut dir, off);
295        crate::varint::put(&mut dir, ps.len() as u64);
296        dir.push(k as u8);
297        if ps.len() as u64 > SKIP_EVERY {
298            crate::varint::put(&mut dir, skip_off);
299        }
300    }
301    let mut out = ACC2_MAGIC.to_vec();
302    out.extend(first.to_le_bytes());
303    out.extend((postings.len() as u32).to_le_bytes());
304    out.extend((dir.len() as u32).to_le_bytes());
305    out.extend((counts.len() as u32).to_le_bytes());
306    out.extend((cs.len() as u32).to_le_bytes());
307    out.extend((skips.len() as u32).to_le_bytes());
308    out.extend(cs);
309    out.extend(dir);
310    out.extend(skips);
311    out.extend(lists.bytes);
312    Ok(out)
313}
314
315#[derive(Default)]
316struct BitWriter {
317    bytes: Vec<u8>,
318    len: u64,
319}
320
321impl BitWriter {
322    fn bit(&mut self, b: bool) {
323        if self.len.is_multiple_of(8) {
324            self.bytes.push(0);
325        }
326        if b && let Some(x) = self.bytes.last_mut() {
327            *x |= 0x80 >> (self.len % 8);
328        }
329        self.len += 1;
330    }
331
332    fn bits(&mut self, v: u64, width: u32) {
333        for j in (0..width).rev() {
334            self.bit(v >> j & 1 == 1);
335        }
336    }
337
338    fn rice(&mut self, g: u64, k: u32) {
339        let q = g >> k;
340        if q < RICE_ESCAPE {
341            for _ in 0..q {
342                self.bit(true);
343            }
344            self.bit(false);
345            self.bits(g, k);
346        } else {
347            for _ in 0..RICE_ESCAPE {
348                self.bit(true);
349            }
350            let w = 64 - g.leading_zeros();
351            self.bits(u64::from(w), 7);
352            self.bits(g, w);
353        }
354    }
355}
356
357struct BitReader<'a> {
358    b: &'a [u8],
359    at: u64,
360}
361
362impl BitReader<'_> {
363    fn bit(&mut self) -> Res<bool> {
364        let x = *self
365            .b
366            .get(usize::try_from(self.at / 8).map_err(|e| e.to_string())?)
367            .ok_or("list truncated")?;
368        let v = x & (0x80 >> (self.at % 8)) != 0;
369        self.at += 1;
370        Ok(v)
371    }
372
373    fn bits(&mut self, width: u32) -> Res<u64> {
374        let mut v = 0u64;
375        for _ in 0..width {
376            v = (v << 1) | u64::from(self.bit()?);
377        }
378        Ok(v)
379    }
380
381    fn rice(&mut self, k: u32) -> Res<u64> {
382        let mut q = 0u64;
383        while q < RICE_ESCAPE && self.bit()? {
384            q += 1;
385        }
386        if q < RICE_ESCAPE {
387            return Ok((q << k) | self.bits(k)?);
388        }
389        let w = self.bits(7)? as u32;
390        if w > 64 {
391            return Err("list difference wider than 64 bits".into());
392        }
393        self.bits(w)
394    }
395}
396
397/// Account history index.
398#[derive(Debug)]
399pub struct AccountIndex<'a> {
400    first: u32,
401    /// Version 2: where each ledger's transaction numbering starts, plus the end of
402    /// the last one; empty means version 1 (varint lists).
403    starts: Vec<u64>,
404    /// Account → (offset, entry count, Rice parameter, entry point offset).
405    dir: Vec<(AccountId, u64, u64, u32, u64)>,
406    skips: &'a [u8],
407    lists: &'a [u8],
408}
409
410impl<'a> AccountIndex<'a> {
411    pub fn open(b: &'a [u8]) -> Res<AccountIndex<'a>> {
412        let v2 = b.starts_with(ACC2_MAGIC);
413        if !v2 && !b.starts_with(ACC_MAGIC) {
414            return Err("not an XACC index".into());
415        }
416        let first = u32_at(b, 6)?;
417        let n = u32_at(b, 10)? as usize;
418        let dl = u32_at(b, 14)? as usize;
419        let (starts, head, sl) = if v2 {
420            let ledgers = u32_at(b, 18)? as usize;
421            let cl = u32_at(b, 22)? as usize;
422            let sl = u32_at(b, 26)? as usize;
423            let cs = b.get(30..30 + cl).ok_or("transaction counts truncated")?;
424            let mut starts = Vec::with_capacity(ledgers.min(1 << 24) + 1);
425            let (mut at, mut acc) = (0, 0u64);
426            starts.push(0);
427            for _ in 0..ledgers {
428                acc += crate::varint::get(cs, &mut at).map_err(String::from)?;
429                starts.push(acc);
430            }
431            (starts, 30 + cl, sl)
432        } else {
433            (Vec::new(), 18, 0)
434        };
435        let d = b.get(head..head + dl).ok_or("directory truncated")?;
436        let mut dir = Vec::with_capacity(n);
437        let mut at = 0;
438        for _ in 0..n {
439            let acc: AccountId = d
440                .get(at..at + 20)
441                .ok_or("directory truncated")?
442                .try_into()
443                .map_err(|_| "account")?;
444            at += 20;
445            let off = crate::varint::get(d, &mut at).map_err(String::from)?;
446            let cnt = crate::varint::get(d, &mut at).map_err(String::from)?;
447            let (mut k, mut skip) = (0, 0);
448            if v2 {
449                k = u32::from((*d.get(at).ok_or("directory truncated")?).min(63));
450                at += 1;
451                if cnt > SKIP_EVERY {
452                    skip = crate::varint::get(d, &mut at).map_err(String::from)?;
453                }
454            }
455            dir.push((acc, off, cnt, k, skip));
456        }
457        let skips = b
458            .get(head + dl..head + dl + sl)
459            .ok_or("entry points truncated")?;
460        Ok(AccountIndex {
461            first,
462            starts,
463            dir,
464            skips,
465            lists: &b[head + dl + sl..],
466        })
467    }
468
469    /// All of an account's positions in ascending order.
470    pub fn postings(&self, acc: &AccountId) -> Res<Vec<Posting>> {
471        let Ok(k) = self.dir.binary_search_by(|x| x.0.cmp(acc)) else {
472            return Ok(Vec::new());
473        };
474        let (_, off, cnt, rk, _) = self.dir[k];
475        let mut out = Vec::with_capacity(cnt.min(1 << 20) as usize);
476        if !self.starts.is_empty() {
477            for v in self.decode(off, 0, cnt, rk)? {
478                out.push(self.posting_of(v)?);
479            }
480            return Ok(out);
481        }
482        let mut at = usize::try_from(off).map_err(|e| e.to_string())?;
483        let (mut pl, mut pi) = (self.first, 0u32);
484        for j in 0..cnt {
485            let dl = crate::varint::get(self.lists, &mut at).map_err(String::from)? as u32;
486            let v = crate::varint::get(self.lists, &mut at).map_err(String::from)? as u32;
487            let l = if j == 0 { self.first + dl } else { pl + dl };
488            let i = if dl == 0 && j > 0 { pi + v } else { v };
489            out.push((l, i));
490            (pl, pi) = (l, i);
491        }
492        Ok(out)
493    }
494
495    /// A page of account history: up to `limit` positions strictly after `cursor` in
496    /// ascending order or, with `desc`, strictly before it in descending order; without
497    /// a cursor, from the start or the end. Version 2 decodes only the blocks it needs.
498    pub fn page(
499        &self,
500        acc: &AccountId,
501        cursor: Option<Posting>,
502        limit: usize,
503        desc: bool,
504    ) -> Res<Vec<Posting>> {
505        let Ok(k) = self.dir.binary_search_by(|x| x.0.cmp(acc)) else {
506            return Ok(Vec::new());
507        };
508        if self.starts.is_empty() {
509            let all = self.postings(acc)?;
510            let it: Box<dyn Iterator<Item = &Posting>> = if desc {
511                Box::new(all.iter().rev().filter(|p| cursor.is_none_or(|c| **p < c)))
512            } else {
513                Box::new(all.iter().filter(|p| cursor.is_none_or(|c| **p > c)))
514            };
515            return Ok(it.take(limit).copied().collect());
516        }
517        let (_, off, cnt, rk, skip) = self.dir[k];
518        let blocks = self.blocks(off, cnt, skip)?;
519        // Boundary in numbers: forward takes numbers from it, backward takes numbers below it.
520        let x = cursor.map(|c| self.bound(c, desc));
521        // Starting block: the last one whose base (the last number of the previous
522        // block) is below the boundary; earlier blocks lie entirely beyond it.
523        let start = match x {
524            Some(x) => blocks.partition_point(|b| b.1 < x).saturating_sub(1),
525            None if desc => blocks.len() - 1,
526            None => 0,
527        };
528        let mut out = Vec::new();
529        let mut j = start;
530        loop {
531            let n = (cnt - j as u64 * SKIP_EVERY).min(SKIP_EVERY);
532            let vs = self.decode(blocks[j].0, blocks[j].1, n, rk)?;
533            if desc {
534                for &v in vs.iter().rev().filter(|&&v| x.is_none_or(|x| v < x)) {
535                    out.push(self.posting_of(v)?);
536                    if out.len() == limit {
537                        return Ok(out);
538                    }
539                }
540                if j == 0 {
541                    return Ok(out);
542                }
543                j -= 1;
544            } else {
545                for &v in vs.iter().filter(|&&v| x.is_none_or(|x| v >= x)) {
546                    out.push(self.posting_of(v)?);
547                    if out.len() == limit {
548                        return Ok(out);
549                    }
550                }
551                j += 1;
552                if j == blocks.len() {
553                    return Ok(out);
554                }
555            }
556        }
557    }
558
559    pub fn accounts(&self) -> usize {
560        self.dir.len()
561    }
562
563    /// List blocks: (bit offset, number before the block).
564    fn blocks(&self, off: u64, cnt: u64, skip: u64) -> Res<Vec<(u64, u64)>> {
565        let n = cnt.div_ceil(SKIP_EVERY).max(1);
566        let mut out = Vec::with_capacity(n.min(1 << 20) as usize);
567        out.push((off, 0));
568        let mut at = usize::try_from(skip).map_err(|e| e.to_string())?;
569        let (mut bit, mut base) = (off, 0u64);
570        for _ in 1..n {
571            bit = bit
572                .checked_add(crate::varint::get(self.skips, &mut at).map_err(String::from)?)
573                .ok_or("entry point outside the list")?;
574            base = base
575                .checked_add(crate::varint::get(self.skips, &mut at).map_err(String::from)?)
576                .ok_or("entry point outside the partition")?;
577            out.push((bit, base));
578        }
579        Ok(out)
580    }
581
582    /// `n` list numbers starting at bit `at`, after number `base`.
583    fn decode(&self, at: u64, base: u64, n: u64, k: u32) -> Res<Vec<u64>> {
584        let mut r = BitReader { b: self.lists, at };
585        let mut v = base;
586        let mut out = Vec::with_capacity(n.min(1 << 20) as usize);
587        for _ in 0..n {
588            v = v
589                .checked_add(r.rice(k)?)
590                .ok_or("position outside the partition")?;
591            out.push(v);
592        }
593        Ok(out)
594    }
595
596    fn posting_of(&self, v: u64) -> Res<Posting> {
597        let d = self.starts.partition_point(|&x| x <= v);
598        if d == 0 || d >= self.starts.len() {
599            return Err("position outside the partition".into());
600        }
601        let l = u32::try_from(d - 1)
602            .ok()
603            .and_then(|d| self.first.checked_add(d))
604            .ok_or("position outside the partition")?;
605        Ok((l, (v - self.starts[d - 1]) as u32))
606    }
607
608    /// Boundary for a cursor: the first position number after it (forward) or
609    /// the number of partition positions before it (backward, `desc`).
610    fn bound(&self, (l, i): Posting, desc: bool) -> u64 {
611        let last = self.starts.len() - 1;
612        match l.checked_sub(self.first).map(|d| d as usize) {
613            None => 0,
614            Some(d) if d >= last => self.starts[last],
615            Some(d) => {
616                let n = self.starts[d + 1] - self.starts[d];
617                let i = u64::from(i).min(n);
618                self.starts[d] + if desc || i == n { i } else { i + 1 }
619            }
620        }
621    }
622}
623
624/// Every how-many-th account directory entry goes into the sparse directory kept
625/// in memory by the on-disk reader.
626const SPARSE: usize = 128;
627/// Every how-many-th XACC ledger start is kept in memory.
628const MARK: usize = 64;
629/// Maximum bit length of a single difference: 16 ones, 7 length bits, 64 bits.
630const MAX_GAP_BITS: u64 = RICE_ESCAPE + 7 + 64;
631
632fn pread(f: &std::fs::File, at: u64, len: usize) -> Res<Vec<u8>> {
633    use std::os::unix::fs::FileExt;
634    let mut b = vec![0u8; len];
635    f.read_exact_at(&mut b, at).map_err(|e| e.to_string())?;
636    Ok(b)
637}
638
639/// XTXH from disk: only the parameters live in memory; ledger starts, the bucket
640/// table and bucket entries are read with pread on demand (the full history is
641/// hundreds of millions of ledgers, too many to keep in memory).
642#[derive(Debug)]
643pub struct TxHashFile {
644    file: std::fs::File,
645    first: u32,
646    ledgers: u32,
647    bucket_bits: u32,
648    ord_bits: u32,
649    offsets_at: u64,
650    entries_at: u64,
651    entries_len: u64,
652}
653
654/// XTXH ledger starts come right after the header.
655const TXH_STARTS_AT: u64 = 24;
656
657impl TxHashFile {
658    pub fn open(path: &std::path::Path) -> Res<TxHashFile> {
659        let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
660        let len = file.metadata().map_err(|e| e.to_string())?.len();
661        let h = pread(&file, 0, 24)?;
662        if !h.starts_with(TXH_MAGIC) {
663            return Err("not an XTXH index".into());
664        }
665        let first = u32_at(&h, 6)?;
666        let ledgers = u32_at(&h, 10)?;
667        let n = u64::from_le_bytes(h[14..22].try_into().map_err(|_| "n")?);
668        let (bucket_bits, ord_bits) = (u32::from(h[22]), u32::from(h[23]));
669        if bucket_bits > 32 || ord_bits > 40 || ord_bits == 0 {
670            return Err("index parameters out of range".into());
671        }
672        let sl = (u64::from(ledgers) + 1) * 4;
673        let ol = ((1u64 << bucket_bits) + 1) * 4;
674        if TXH_STARTS_AT + sl + ol > len {
675            return Err("XTXH index truncated".into());
676        }
677        let offsets_at = TXH_STARTS_AT + sl;
678        let entries_at = offsets_at + ol;
679        let f = TxHashFile {
680            file,
681            first,
682            ledgers,
683            bucket_bits,
684            ord_bits,
685            offsets_at,
686            entries_at,
687            entries_len: len - entries_at,
688        };
689        if u64::from(f.start(ledgers)?) != n || u64::from(f.word(entries_at - 4)?) != n {
690            return Err("XTXH index is inconsistent".into());
691        }
692        let need = (n * u64::from(16 + ord_bits)).div_ceil(8);
693        if f.entries_len < need {
694            return Err("XTXH entries truncated".into());
695        }
696        Ok(f)
697    }
698
699    fn word(&self, at: u64) -> Res<u32> {
700        u32_at(&pread(&self.file, at, 4)?, 0)
701    }
702
703    /// Number of the first transaction of ledger `d`, counted from the partition start.
704    fn start(&self, d: u32) -> Res<u32> {
705        self.word(TXH_STARTS_AT + u64::from(d) * 4)
706    }
707
708    pub fn first(&self) -> u32 {
709        self.first
710    }
711
712    /// Last ledger of the range.
713    pub fn last(&self) -> u32 {
714        self.first + self.ledgers - 1
715    }
716
717    /// Candidates (ledger, position) for a hash; they must be read and checked.
718    pub fn candidates(&self, h: &[u8; 32]) -> Res<Vec<(u32, u32)>> {
719        let t = top64(h);
720        let bucket = if self.bucket_bits == 0 {
721            0
722        } else {
723            t >> (64 - self.bucket_bits)
724        };
725        let fp = (t << self.bucket_bits) >> 48;
726        let o = pread(&self.file, self.offsets_at + bucket * 4, 8)?;
727        let (lo, hi) = (u64::from(u32_at(&o, 0)?), u64::from(u32_at(&o, 4)?));
728        if lo >= hi {
729            return Ok(Vec::new());
730        }
731        let width = u64::from(16 + self.ord_bits);
732        let (b0, b1) = (
733            lo * width / 8,
734            (hi * width).div_ceil(8).min(self.entries_len),
735        );
736        let len = b1
737            .checked_sub(b0)
738            .ok_or("hash index corrupt: bucket outside the file")?;
739        let w = pread(&self.file, self.entries_at + b0, len as usize)?;
740        let mut out = Vec::new();
741        for k in lo..hi {
742            let v = get_bits(&w, (k * width - b0 * 8) as usize, width as usize);
743            if v >> self.ord_bits == fp {
744                let ord = (v & ((1u64 << self.ord_bits) - 1)) as u32;
745                // The last ledger whose start is no later than ord.
746                let (mut a, mut b) = (0u32, self.ledgers);
747                while b - a > 1 {
748                    let m = a + (b - a) / 2;
749                    if self.start(m)? <= ord {
750                        a = m;
751                    } else {
752                        b = m;
753                    }
754                }
755                out.push((self.first + a, ord - self.start(a)?));
756            }
757        }
758        Ok(out)
759    }
760}
761
762/// XACC v2 from disk: memory holds anchor points for ledger starts (every
763/// `MARK`-th) and a sparse directory (every `SPARSE`-th entry); ledger starts
764/// between anchors, directory entries, entry points and list blocks are read
765/// with pread on demand.
766#[derive(Debug)]
767pub struct AccountFile {
768    file: std::fs::File,
769    first: u32,
770    ledgers: usize,
771    /// Start of ledger `k * MARK` and the offset of its difference at the start of the file.
772    marks: Vec<(u64, u32)>,
773    /// Positions in the partition: the start of the ledger after the last one.
774    total: u64,
775    cs_len: u64,
776    dir_at: u64,
777    dir_len: u64,
778    skips_at: u64,
779    skips_len: u64,
780    lists_at: u64,
781    lists_len: u64,
782    sparse: Vec<(AccountId, u64)>,
783    accounts: usize,
784}
785
786/// Directory entry: list offset in bits, position count, Rice parameter,
787/// entry point offset.
788type DirEntry = (u64, u64, u32, u64);
789
790impl AccountFile {
791    pub fn open(path: &std::path::Path) -> Res<AccountFile> {
792        let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
793        let len = file.metadata().map_err(|e| e.to_string())?.len();
794        let h = pread(&file, 0, 30)?;
795        if !h.starts_with(ACC2_MAGIC) {
796            return Err("not a version 2 XACC index".into());
797        }
798        let first = u32_at(&h, 6)?;
799        let n = u32_at(&h, 10)? as usize;
800        let dl = u64::from(u32_at(&h, 14)?);
801        let ledgers = u32_at(&h, 18)? as usize;
802        let cl = u64::from(u32_at(&h, 22)?);
803        let sl = u64::from(u32_at(&h, 26)?);
804        if 30 + cl + dl + sl > len {
805            return Err("XACC index truncated".into());
806        }
807        let cs = pread(&file, 30, cl as usize)?;
808        let mut marks = Vec::with_capacity(ledgers / MARK + 1);
809        let (mut at, mut acc) = (0, 0u64);
810        for d in 0..ledgers {
811            if d.is_multiple_of(MARK) {
812                marks.push((acc, at as u32));
813            }
814            acc += crate::varint::get(&cs, &mut at).map_err(String::from)?;
815        }
816        if ledgers.is_multiple_of(MARK) {
817            marks.push((acc, at as u32));
818        }
819        drop(cs);
820        // The directory is read in full once, to build the sparse directory.
821        let dir = pread(&file, 30 + cl, dl as usize)?;
822        let mut sparse = Vec::with_capacity(n / SPARSE + 1);
823        let mut at = 0usize;
824        for k in 0..n {
825            let start = at;
826            let a: AccountId = dir
827                .get(at..at + 20)
828                .ok_or("directory truncated")?
829                .try_into()
830                .map_err(|_| "account")?;
831            at += 20;
832            crate::varint::get(&dir, &mut at).map_err(String::from)?;
833            let cnt = crate::varint::get(&dir, &mut at).map_err(String::from)?;
834            at += 1;
835            if cnt > SKIP_EVERY {
836                crate::varint::get(&dir, &mut at).map_err(String::from)?;
837            }
838            if k % SPARSE == 0 {
839                sparse.push((a, start as u64));
840            }
841        }
842        if at as u64 != dl {
843            return Err("XACC directory is inconsistent".into());
844        }
845        let lists_at = 30 + cl + dl + sl;
846        Ok(AccountFile {
847            file,
848            first,
849            ledgers,
850            marks,
851            total: acc,
852            cs_len: cl,
853            dir_at: 30 + cl,
854            dir_len: dl,
855            skips_at: 30 + cl + dl,
856            skips_len: sl,
857            lists_at,
858            lists_len: len - lists_at,
859            sparse,
860            accounts: n,
861        })
862    }
863
864    pub fn accounts(&self) -> usize {
865        self.accounts
866    }
867
868    fn entry(&self, acc: &AccountId) -> Res<Option<DirEntry>> {
869        let Some(i) = self.sparse.partition_point(|x| x.0 <= *acc).checked_sub(1) else {
870            return Ok(None);
871        };
872        let from = self.sparse[i].1;
873        let to = self.sparse.get(i + 1).map_or(self.dir_len, |x| x.1);
874        let d = pread(&self.file, self.dir_at + from, (to - from) as usize)?;
875        let mut at = 0;
876        while at < d.len() {
877            let a: AccountId = d
878                .get(at..at + 20)
879                .ok_or("directory truncated")?
880                .try_into()
881                .map_err(|_| "account")?;
882            at += 20;
883            let off = crate::varint::get(&d, &mut at).map_err(String::from)?;
884            let cnt = crate::varint::get(&d, &mut at).map_err(String::from)?;
885            let k = u32::from((*d.get(at).ok_or("directory truncated")?).min(63));
886            at += 1;
887            let skip = if cnt > SKIP_EVERY {
888                crate::varint::get(&d, &mut at).map_err(String::from)?
889            } else {
890                0
891            };
892            if a == *acc {
893                return Ok(Some((off, cnt, k, skip)));
894            }
895            if a > *acc {
896                break;
897            }
898        }
899        Ok(None)
900    }
901
902    /// Ledger starts `k * MARK ..= min((k + 1) * MARK, ledgers)`.
903    fn starts(&self, k: usize) -> Res<Vec<u64>> {
904        let (mut v, off) = self.marks[k];
905        let n = MARK.min(self.ledgers - k * MARK);
906        let len = ((n * 10) as u64).min(self.cs_len - u64::from(off));
907        let b = pread(&self.file, 30 + u64::from(off), len as usize)?;
908        let mut out = Vec::with_capacity(n + 1);
909        out.push(v);
910        let mut at = 0;
911        for _ in 0..n {
912            v += crate::varint::get(&b, &mut at).map_err(String::from)?;
913            out.push(v);
914        }
915        Ok(out)
916    }
917
918    /// Number of the first position no earlier than (ledger, TransactionIndex).
919    fn ordinal_at(&self, (l, i): Posting) -> Res<u64> {
920        Ok(match l.checked_sub(self.first).map(|d| d as usize) {
921            None => 0,
922            Some(d) if d >= self.ledgers => self.total,
923            Some(d) => {
924                let s = self.starts(d / MARK)?;
925                let (a, b) = (s[d % MARK], s[d % MARK + 1]);
926                a + u64::from(i).min(b - a)
927            }
928        })
929    }
930
931    fn posting_of(&self, v: u64) -> Res<Posting> {
932        let Some(k) = self.marks.partition_point(|m| m.0 <= v).checked_sub(1) else {
933            return Err("position outside the partition".into());
934        };
935        let k = k.min(self.ledgers.saturating_sub(1) / MARK);
936        let s = self.starts(k)?;
937        let j = s.partition_point(|&x| x <= v);
938        let d = k * MARK + j;
939        if j == 0 || d > self.ledgers {
940            return Err("position outside the partition".into());
941        }
942        Ok((self.first + (d - 1) as u32, (v - s[j - 1]) as u32))
943    }
944
945    /// Account positions in [lo, hi] inclusive, at most `limit`; in
946    /// ascending order or, with `desc`, descending.
947    pub fn range(
948        &self,
949        acc: &AccountId,
950        lo: Posting,
951        hi: Posting,
952        limit: usize,
953        desc: bool,
954    ) -> Res<Vec<Posting>> {
955        let Some((off, cnt, k, skip)) = self.entry(acc)? else {
956            return Ok(Vec::new());
957        };
958        let a = self.ordinal_at(lo)?;
959        // First position strictly after hi.
960        let b = self.ordinal_at((hi.0, hi.1.saturating_add(1)))?;
961        if a >= b || limit == 0 {
962            return Ok(Vec::new());
963        }
964        // Blocks: (start bit, number before the block).
965        let nblocks = cnt.div_ceil(SKIP_EVERY).max(1) as usize;
966        let mut blocks = Vec::with_capacity(nblocks);
967        blocks.push((off, 0u64));
968        if nblocks > 1 {
969            let rest = self
970                .skips_len
971                .checked_sub(skip)
972                .ok_or("account index corrupt: entry points outside the file")?;
973            let len = ((nblocks - 1) * 20).min(rest as usize);
974            let sk = pread(&self.file, self.skips_at + skip, len)?;
975            let (mut at, mut bit, mut base) = (0, off, 0u64);
976            for _ in 1..nblocks {
977                bit = bit
978                    .checked_add(crate::varint::get(&sk, &mut at).map_err(String::from)?)
979                    .ok_or("entry point outside the list")?;
980                base = base
981                    .checked_add(crate::varint::get(&sk, &mut at).map_err(String::from)?)
982                    .ok_or("entry point outside the partition")?;
983                blocks.push((bit, base));
984            }
985        }
986        let decode = |j: usize| -> Res<Vec<u64>> {
987            let n = (cnt - j as u64 * SKIP_EVERY).min(SKIP_EVERY);
988            let start = blocks[j].0;
989            let end = blocks
990                .get(j + 1)
991                .map_or(start + n * MAX_GAP_BITS, |x| x.0)
992                .min(self.lists_len * 8);
993            let (b0, b1) = (start / 8, end.div_ceil(8).min(self.lists_len));
994            let len = b1
995                .checked_sub(b0)
996                .ok_or("account index corrupt: block outside the file")?;
997            let w = pread(&self.file, self.lists_at + b0, len as usize)?;
998            let mut r = BitReader {
999                b: &w,
1000                at: start - b0 * 8,
1001            };
1002            let mut v = blocks[j].1;
1003            let mut out = Vec::with_capacity(n as usize);
1004            for _ in 0..n {
1005                v = v
1006                    .checked_add(r.rice(k)?)
1007                    .ok_or("position outside the partition")?;
1008                out.push(v);
1009            }
1010            Ok(out)
1011        };
1012        let x = if desc { b } else { a };
1013        let mut j = blocks.partition_point(|bl| bl.1 < x).saturating_sub(1);
1014        let mut out = Vec::new();
1015        loop {
1016            let vs = decode(j)?;
1017            if desc {
1018                for &v in vs.iter().rev() {
1019                    if v >= b {
1020                        continue;
1021                    }
1022                    if v < a {
1023                        return Ok(out);
1024                    }
1025                    out.push(self.posting_of(v)?);
1026                    if out.len() == limit {
1027                        return Ok(out);
1028                    }
1029                }
1030                if j == 0 {
1031                    return Ok(out);
1032                }
1033                j -= 1;
1034            } else {
1035                for &v in &vs {
1036                    if v < a {
1037                        continue;
1038                    }
1039                    if v >= b {
1040                        return Ok(out);
1041                    }
1042                    out.push(self.posting_of(v)?);
1043                    if out.len() == limit {
1044                        return Ok(out);
1045                    }
1046                }
1047                j += 1;
1048                if j == blocks.len() {
1049                    return Ok(out);
1050                }
1051            }
1052        }
1053    }
1054}
1055
1056#[cfg(test)]
1057mod tests {
1058    use super::*;
1059
1060    #[test]
1061    fn tx_index_finds_every_hash_and_rejects_strangers() {
1062        let mut ledgers = Vec::new();
1063        let mut all = Vec::new();
1064        for l in 0..50u32 {
1065            let txs: Vec<[u8; 32]> = (0..(l % 7) * 13)
1066                .map(|i| witness_core::sha512_half(&[l.to_le_bytes(), i.to_le_bytes()].concat()))
1067                .collect();
1068            all.extend(txs.iter().enumerate().map(|(p, h)| (*h, 100 + l, p as u32)));
1069            ledgers.push(txs);
1070        }
1071        let b = build_tx_index(100, &ledgers);
1072        let idx = TxHashIndex::open(&b).unwrap();
1073        for (h, l, p) in &all {
1074            assert!(idx.candidates(h).unwrap().contains(&(*l, *p)));
1075        }
1076        let stranger = witness_core::sha512_half(b"absent hash");
1077        assert!(idx.candidates(&stranger).unwrap().len() <= 1);
1078    }
1079
1080    #[test]
1081    fn account_postings_round_trip() {
1082        let mut m: BTreeMap<AccountId, Vec<Posting>> = BTreeMap::new();
1083        m.insert([1; 20], vec![(10, 0), (10, 5), (12, 1), (40, 3)]);
1084        m.insert([2; 20], vec![(11, 2)]);
1085        let b = build_account_index(10, &m);
1086        let idx = AccountIndex::open(&b).unwrap();
1087        assert_eq!(idx.postings(&[1; 20]).unwrap(), m[&[1; 20]]);
1088        assert_eq!(idx.postings(&[2; 20]).unwrap(), m[&[2; 20]]);
1089        assert!(idx.postings(&[3; 20]).unwrap().is_empty());
1090        let b2 = build_account_index_v2(10, &[6; 31], &m).unwrap();
1091        let idx2 = AccountIndex::open(&b2).unwrap();
1092        for (acc, ps) in &m {
1093            assert_eq!(&idx2.postings(acc).unwrap(), ps);
1094        }
1095        assert!(idx2.postings(&[3; 20]).unwrap().is_empty());
1096    }
1097
1098    #[test]
1099    fn pages_match_the_full_list_both_ways() {
1100        let mut m: BTreeMap<AccountId, Vec<Posting>> = BTreeMap::new();
1101        let long: Vec<Posting> = (0..1000u32)
1102            .flat_map(|l| (0..(l % 3)).map(move |i| (100 + l, i * 2)))
1103            .collect();
1104        m.insert([1; 20], long.clone());
1105        m.insert([2; 20], vec![(150, 1)]);
1106        let counts = vec![6u32; 1000];
1107        let b = build_account_index_v2(100, &counts, &m).unwrap();
1108        let idx = AccountIndex::open(&b).unwrap();
1109        assert_eq!(idx.postings(&[1; 20]).unwrap(), long);
1110        let cursors = [
1111            None,
1112            Some((99, 0)),
1113            Some((100, 0)),
1114            Some((612, 2)),
1115            Some((613, 1)),
1116            Some((1099, 4)),
1117            Some((5000, 0)),
1118        ];
1119        for c in cursors {
1120            for limit in [1, 7, 128, 300, 5000] {
1121                let fwd: Vec<Posting> = long
1122                    .iter()
1123                    .copied()
1124                    .filter(|p| c.is_none_or(|c| *p > c))
1125                    .take(limit)
1126                    .collect();
1127                let back: Vec<Posting> = long
1128                    .iter()
1129                    .rev()
1130                    .copied()
1131                    .filter(|p| c.is_none_or(|c| *p < c))
1132                    .take(limit)
1133                    .collect();
1134                assert_eq!(
1135                    idx.page(&[1; 20], c, limit, false).unwrap(),
1136                    fwd,
1137                    "{c:?} {limit}"
1138                );
1139                assert_eq!(
1140                    idx.page(&[1; 20], c, limit, true).unwrap(),
1141                    back,
1142                    "{c:?} {limit} desc"
1143                );
1144            }
1145        }
1146        assert_eq!(idx.page(&[2; 20], None, 10, true).unwrap(), vec![(150, 1)]);
1147        assert!(idx.page(&[3; 20], None, 10, true).unwrap().is_empty());
1148    }
1149
1150    #[test]
1151    fn file_readers_match_memory_indexes() {
1152        // Ledger counts that are and are not multiples of MARK, below one anchor step and exactly one.
1153        for total in [300u32, 320, 64, 1] {
1154            file_readers_match(total);
1155        }
1156    }
1157
1158    fn file_readers_match(total: u32) {
1159        let dir = tempfile::tempdir().unwrap();
1160        let mut ledgers = Vec::new();
1161        let mut m: BTreeMap<AccountId, Vec<Posting>> = BTreeMap::new();
1162        for l in 0..total {
1163            let n = (l % 9) * 3;
1164            let txs: Vec<[u8; 32]> = (0..n)
1165                .map(|i| witness_core::sha512_half(&[l.to_le_bytes(), i.to_le_bytes()].concat()))
1166                .collect();
1167            for i in 0..n {
1168                m.entry([(i % 4) as u8; 20])
1169                    .or_default()
1170                    .push((1000 + l, i));
1171                if i % 2 == 0 {
1172                    m.entry([9; 20]).or_default().push((1000 + l, i));
1173                }
1174            }
1175            ledgers.push(txs);
1176        }
1177        for v in m.values_mut() {
1178            v.sort_unstable();
1179            v.dedup();
1180        }
1181        let counts: Vec<u32> = ledgers.iter().map(|l| l.len() as u32).collect();
1182        let xt = dir.path().join("t.xtxh");
1183        let xa = dir.path().join("t.xacc");
1184        std::fs::write(&xt, build_tx_index(1000, &ledgers)).unwrap();
1185        std::fs::write(&xa, build_account_index_v2(1000, &counts, &m).unwrap()).unwrap();
1186        let tf = TxHashFile::open(&xt).unwrap();
1187        assert_eq!((tf.first(), tf.last()), (1000, 999 + total));
1188        for (l, txs) in ledgers.iter().enumerate() {
1189            for (p, h) in txs.iter().enumerate() {
1190                assert!(
1191                    tf.candidates(h)
1192                        .unwrap()
1193                        .contains(&(1000 + l as u32, p as u32))
1194                );
1195            }
1196        }
1197        let af = AccountFile::open(&xa).unwrap();
1198        for (acc, ps) in &m {
1199            let all = af
1200                .range(acc, (0, 0), (u32::MAX, u32::MAX), usize::MAX, false)
1201                .unwrap();
1202            assert_eq!(&all, ps);
1203            let back = af.range(acc, (1100, 3), (1250, 2), 37, true).unwrap();
1204            let want: Vec<Posting> = ps
1205                .iter()
1206                .rev()
1207                .copied()
1208                .filter(|p| *p >= (1100, 3) && *p <= (1250, 2))
1209                .take(37)
1210                .collect();
1211            assert_eq!(back, want);
1212        }
1213        assert!(
1214            af.range(&[7; 20], (0, 0), (u32::MAX, u32::MAX), 10, true)
1215                .unwrap()
1216                .is_empty()
1217        );
1218    }
1219
1220    #[test]
1221    fn rice_escape_round_trips_wide_gaps() {
1222        let mut m: BTreeMap<AccountId, Vec<Posting>> = BTreeMap::new();
1223        m.insert(
1224            [7; 20],
1225            vec![(5, 0), (6, 900), (4_000_000, 1), (4_000_000, 2)],
1226        );
1227        m.insert([8; 20], (5..400).map(|l| (l, l % 3)).collect());
1228        let mut counts = vec![3u32; 4_000_000 - 5];
1229        counts.push(5);
1230        counts[1] = 901;
1231        let b = build_account_index_v2(5, &counts, &m).unwrap();
1232        let idx = AccountIndex::open(&b).unwrap();
1233        for (acc, ps) in &m {
1234            assert_eq!(&idx.postings(acc).unwrap(), ps);
1235        }
1236    }
1237}