Skip to main content

astraea_journal_codec/
fast.rs

1//! Compiled, byte-exact document programs. No per-field Rc/Vec allocation at read time.
2use super::*;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, OnceLock};
5/// Transaction hashes of a block by position, shared with the pool so that a
6/// block prepared again after eviction does not hash its transactions again.
7pub(crate) type TxMemo = Arc<[OnceLock<[u8; 32]>]>;
8#[derive(Clone, Copy, Debug)]
9pub(crate) struct Atom {
10    pub(crate) at: u32,
11    pub(crate) len: u32,
12}
13pub(crate) const NODE: u32 = u32::MAX - 3;
14#[derive(Clone, Hash, PartialEq, Eq)]
15pub(crate) enum PlanOp {
16    Fixed(Vec<u8>),
17    Value,
18    Child,
19}
20pub(crate) const FIXED: u32 = 1 << 31;
21pub(crate) const TX: u32 = u32::MAX;
22pub(crate) const KEY: u32 = u32::MAX - 2;
23const REPEAT: u32 = u32::MAX - 1;
24#[derive(Clone, Copy)]
25enum Item {
26    Value(Atom),
27    Delta(u8, u64),
28}
29#[derive(Clone, Copy)]
30enum Op {
31    Value(Atom),
32    Column(usize),
33    Cached(usize),
34    Child,
35}
36struct Column {
37    items: Vec<Item>,
38    pos: usize,
39}
40#[derive(Clone)]
41pub(crate) struct Doc {
42    pub(crate) start: usize,
43    pub(crate) end: usize,
44    pub(crate) size: usize,
45}
46#[derive(Clone)]
47pub(crate) struct Layout {
48    pub(crate) seq: u32,
49    pub(crate) header: usize,
50    pub(crate) tx: Vec<(usize, usize)>,
51    pub(crate) patches: Vec<(usize, usize)>,
52}
53fn append(pool: &mut Vec<u8>, value: &[u8]) -> Res<Atom> {
54    let at = u32::try_from(pool.len()).map_err(er)?;
55    if pool.len().checked_add(value.len()).is_none_or(|n| n > MAX) {
56        return Err("arena limit".into());
57    }
58    pool.extend(value);
59    Ok(Atom {
60        at,
61        len: value.len() as u32,
62    })
63}
64fn bytes(pool: &[u8], atom: Atom) -> Res<&[u8]> {
65    pool.get(atom.at as usize..atom.at as usize + (atom.len & !FIXED) as usize)
66        .ok_or("atom extent".into())
67}
68/// Hasher for the compiler's field cache, keyed by pairs of small indexes.
69/// SipHash took a quarter of block preparation; the keys come from the block
70/// being read, so a multiplicative mix is enough. Added during integration.
71#[derive(Default, Clone, Copy)]
72struct PairHasher(u64);
73impl std::hash::Hasher for PairHasher {
74    fn finish(&self) -> u64 {
75        self.0
76    }
77    fn write(&mut self, bytes: &[u8]) {
78        for &b in bytes {
79            self.write_u64(u64::from(b));
80        }
81    }
82    fn write_u64(&mut self, n: u64) {
83        self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(0x517c_c1b7_2722_0a95);
84    }
85    fn write_usize(&mut self, n: usize) {
86        self.write_u64(n as u64);
87    }
88}
89type PairMap<V> = HashMap<(usize, usize), V, std::hash::BuildHasherDefault<PairHasher>>;
90type IdMap = HashMap<usize, usize, std::hash::BuildHasherDefault<PairHasher>>;
91/// A stored value appended to the arena without an intermediate copy.
92fn value_append(r: &mut Read<'_>, pool: &mut Vec<u8>) -> Res<Atom> {
93    let tag = r.var()?;
94    if tag == 1 {
95        let mut der = [0; DER_MAX];
96        let n = der_signature(r.take(64)?, &mut der)?;
97        return append(pool, &der[..n]);
98    }
99    if tag & 1 != 0 {
100        return Err("value tag".into());
101    }
102    let n = usize::try_from(tag >> 1).map_err(er)?;
103    if n > MAX {
104        return Err("value size".into());
105    }
106    append(pool, r.take(n)?)
107}
108/// A ledger as the layout stream describes it, known before any part of the
109/// block is compiled.
110#[derive(Clone)]
111struct Planned {
112    seq: u32,
113    txs: usize,
114    patches: usize,
115    /// Encoded position -> original position, when they differ and the
116    /// stream says how.
117    order: Option<Vec<usize>>,
118    /// Position of the ledger's first transaction among all of the block's.
119    first_tx: usize,
120    part: usize,
121    /// Header document, once the ledger's part is compiled.
122    header_doc: usize,
123    /// `Layout::tx` is in original order.
124    sorted: bool,
125}
126/// Compressed parts and (offset, length, raw length) of each.
127type Frames = (Vec<u8>, Vec<(usize, usize, usize)>);
128/// What compiling a part needs from the shared section.
129struct Shared {
130    templates: Vec<Vec<Op>>,
131    /// Column key -> dense id used by `Op::Column` / `Op::Cached`.
132    dense: IdMap,
133    dict: Vec<Atom>,
134    v3: bool,
135    v4: bool,
136    v6: bool,
137    auxiliary: bool,
138    /// JC06: compressed parts, (offset, length, raw length) of each in
139    /// `frames`, and the shared section as their dictionary.
140    frames: Vec<u8>,
141    spans: Vec<(usize, usize, usize)>,
142    parts: Vec<std::ops::Range<usize>>,
143    done: Vec<bool>,
144    dictionary: Option<zstd::dict::DecoderDictionary<'static>>,
145    dictionary_bytes: usize,
146    /// Block hash and part digests from a seal (`check_parts`).
147    sealed: Option<([u8; 32], Vec<[u8; 32]>)>,
148    /// Which of the block's seal digests (the head first, then every part)
149    /// its stored bytes were already found to match in this process, kept by
150    /// the pool across preparations (`remember`).
151    checked: Option<Arc<[AtomicBool]>>,
152}
153/// JC06 frame: the shared section, and every part with its raw size, as
154/// ranges of the frame. `head` ends where the parts begin.
155pub(crate) struct FrameParts {
156    pub(crate) head: usize,
157    pub(crate) shared: std::ops::Range<usize>,
158    pub(crate) shared_raw: usize,
159    pub(crate) parts: Vec<(std::ops::Range<usize>, usize)>,
160}
161/// Layout of a JC06 frame: u64 raw and compressed size of the shared section,
162/// u32 part count, u64 raw and compressed size of every part, then the
163/// shared section and the parts.
164pub(crate) fn frame_parts(frame: &[u8]) -> Res<FrameParts> {
165    fn size(fr: &mut Read<'_>) -> Res<usize> {
166        let n = fr.u64()?;
167        if n > MAX as u64 {
168            return Err("part limit".into());
169        }
170        Ok(n as usize)
171    }
172    let mut fr = Read::new(frame);
173    let (shared_raw, shared_z) = (size(&mut fr)?, size(&mut fr)?);
174    let n = fr.u32()? as usize;
175    if n == 0 || n > (frame.len() - fr.p) / 16 {
176        return Err("part count".into());
177    }
178    let mut sizes = vec![];
179    for _ in 0..n {
180        sizes.push((size(&mut fr)?, size(&mut fr)?));
181    }
182    let start = fr.p;
183    fr.take(shared_z)?;
184    let shared = start..fr.p;
185    let head = fr.p;
186    let mut parts = vec![];
187    for (raw, z) in sizes {
188        let at = fr.p;
189        fr.take(z)?;
190        parts.push((at..fr.p, raw));
191    }
192    fr.end()?;
193    Ok(FrameParts {
194        head,
195        shared,
196        shared_raw,
197        parts,
198    })
199}
200/// Prepared block: shared literal arena plus flat document instructions.
201/// Preparing does not itself authenticate the archive or recompute ledger roots.
202///
203/// JC06 blocks (added during integration) are cut into parts that compile on
204/// their own; `open` compiles a part the first time one of its ledgers is
205/// read. Ledgers stored in hash order are put back into it only when a whole
206/// ledger is read.
207pub struct Prepared {
208    pub(crate) pool: Vec<u8>,
209    pub(crate) atoms: Vec<Atom>,
210    pub(crate) docs: Vec<Doc>,
211    pub(crate) layout: Vec<Layout>,
212    pub(crate) tree: Vec<Atom>,
213    pub(crate) tree_docs: Vec<(usize, usize)>,
214    pub(crate) plans: Vec<Vec<PlanOp>>,
215    pub(crate) keys: Vec<(u8, Vec<Atom>)>,
216    key_hashes: Vec<Option<[u8; 32]>>,
217    tx_hashes: Vec<Option<[u8; 32]>>,
218    /// The pool's copy of `tx_hashes`, for a sealed JC06 block (`remember`).
219    tx_memo: Option<TxMemo>,
220    ledgers: Vec<Planned>,
221    shared: Box<Shared>,
222}
223struct Compiler<'a> {
224    auxiliary: bool,
225    pool: &'a mut Vec<u8>,
226    templates: &'a [Vec<Op>],
227    local: &'a [usize],
228    shapes: &'a [usize],
229    contexts: &'a [usize],
230    columns: &'a mut [Column],
231    at: usize,
232    cache: PairMap<Atom>,
233    atoms: &'a mut Vec<Atom>,
234    docs: &'a mut Vec<Doc>,
235    tree: &'a mut Vec<Atom>,
236    tree_docs: &'a mut Vec<(usize, usize)>,
237}
238impl Compiler<'_> {
239    fn column(&self, dense: usize) -> Res<usize> {
240        match self.local.get(dense) {
241            Some(&k) if k != usize::MAX => Ok(k),
242            _ => Err("missing column".into()),
243        }
244    }
245    fn visit(&mut self, depth: usize) -> Res<()> {
246        if depth > 64 {
247            return Err("template depth".into());
248        }
249        let id = *self.shapes.get(self.at).ok_or("shape exhausted")?;
250        let ctx = self.contexts[self.at];
251        self.at += 1;
252        if self.auxiliary {
253            self.tree.push(Atom {
254                at: id as u32,
255                len: NODE,
256            });
257        }
258        let t = self.templates.get(id).ok_or("template id")?;
259        for &op in t {
260            match op {
261                Op::Value(a) => self.atoms.push(Atom {
262                    at: a.at,
263                    len: a.len | FIXED,
264                }),
265                Op::Child => self.visit(depth + 1)?,
266                Op::Cached(k) => {
267                    if ctx == 0 {
268                        return Err("cached field without context".into());
269                    }
270                    let a = *self.cache.get(&(ctx, k)).ok_or("missing cached field")?;
271                    self.atoms.push(a);
272                    if self.auxiliary {
273                        self.tree.push(a);
274                    }
275                }
276                Op::Column(k) => {
277                    let c = &mut self.columns[self.column(k)?];
278                    let item = *c.items.get(c.pos).ok_or("column exhausted")?;
279                    c.pos += 1;
280                    let a = match item {
281                        Item::Value(Atom { len: REPEAT, .. }) => {
282                            *self.cache.get(&(ctx, k)).ok_or("missing repeat")?
283                        }
284                        Item::Value(a) => a,
285                        Item::Delta(width, z) => {
286                            let a = *self.cache.get(&(ctx, k)).ok_or("missing delta base")?;
287                            if a.len != u32::from(width) {
288                                return Err("context delta width".into());
289                            }
290                            let mut b = [0u8; 8];
291                            b[8 - width as usize..].copy_from_slice(bytes(self.pool, a)?);
292                            let d = ((z >> 1) as i64) ^ -((z & 1) as i64);
293                            let n = u64::from_be_bytes(b).wrapping_add(d as u64);
294                            if width == 4 && n > u32::MAX as u64 {
295                                return Err("context delta overflow".into());
296                            }
297                            append(self.pool, &n.to_be_bytes()[8 - width as usize..])?
298                        }
299                    };
300                    if ctx != 0 {
301                        self.cache.insert((ctx, k), a);
302                    }
303                    self.atoms.push(a);
304                    if self.auxiliary {
305                        self.tree.push(a);
306                    }
307                }
308            }
309            if self.atoms.len() > MAX / 8 {
310                return Err("instruction limit".into());
311            }
312        }
313        Ok(())
314    }
315    fn doc(&mut self) -> Res<usize> {
316        let start = self.atoms.len();
317        let tree_start = self.tree.len();
318        self.visit(0)?;
319        let end = self.atoms.len();
320        if self.auxiliary {
321            self.tree_docs.push((tree_start, self.tree.len()));
322        }
323        let size = self.atoms[start..end]
324            .iter()
325            .map(|a| {
326                if [TX, KEY].contains(&a.len) {
327                    32
328                } else {
329                    (a.len & !FIXED) as usize
330                }
331            })
332            .sum();
333        if size > MAX {
334            return Err("document size".into());
335        }
336        let id = self.docs.len();
337        self.docs.push(Doc { start, end, size });
338        Ok(id)
339    }
340}
341/// Dictionary entries: values, hashes of the block's transactions, and keys
342/// derived from arguments. An id names `base` first, then these entries.
343fn read_dictionary(
344    r: &mut Read<'_>,
345    pool: &mut Vec<u8>,
346    base: &[Atom],
347    keys: &mut Vec<(u8, Vec<Atom>)>,
348) -> Res<Vec<Atom>> {
349    let nd = r.items()?;
350    let mut dict = Vec::with_capacity(nd);
351    let mut recipes = vec![];
352    for i in 0..nd {
353        let atom = match r.byte()? {
354            0 => value_append(r, pool)?,
355            1 => Atom {
356                at: u32::try_from(r.var()?).map_err(er)?,
357                len: TX,
358            },
359            2 => {
360                let domain = r.byte()?;
361                let n = r.count()?;
362                if n > 4 {
363                    return Err("key args".into());
364                }
365                let mut args = vec![];
366                for _ in 0..n {
367                    let x = r.count()?;
368                    args.push(if x == 0 {
369                        Ok(append(pool, r.blob()?)?)
370                    } else {
371                        Err(x - 1)
372                    })
373                }
374                recipes.push((i, domain, args));
375                Atom { at: 0, len: REPEAT }
376            }
377            _ => return Err("dictionary tag".into()),
378        };
379        dict.push(atom)
380    }
381    for (i, domain, args) in recipes {
382        let mut arguments = vec![];
383        for arg in args {
384            let a = match arg {
385                Ok(a) => a,
386                Err(id) if id < base.len() => base[id],
387                Err(id) => *dict.get(id - base.len()).ok_or("key reference")?,
388            };
389            if ![4, 20].contains(&a.len) {
390                return Err("key argument is not literal".into());
391            }
392            arguments.push(a);
393        }
394        dict[i] = Atom {
395            at: keys.len() as u32,
396            len: KEY,
397        };
398        keys.push((domain, arguments));
399    }
400    Ok(dict)
401}
402fn decompress_frame(frame: &[u8]) -> Res<Vec<u8>> {
403    let mut fr = Read::new(frame);
404    let size = fr.u64()?;
405    if size > MAX as u64 {
406        return Err("block limit".into());
407    }
408    let raw = zstd::bulk::decompress(&frame[8..], size as usize).map_err(er)?;
409    if raw.len() != size as usize {
410        return Err("journal size".into());
411    }
412    Ok(raw)
413}
414impl std::fmt::Debug for Prepared {
415    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
416        f.debug_struct("Prepared")
417            .field("ledgers", &self.layout.len())
418            .finish_non_exhaustive()
419    }
420}
421impl Prepared {
422    pub fn parse(frame: &[u8]) -> Res<Self> {
423        let mut p = Self::shared(&decompress_frame(frame)?, true, None)?;
424        p.finish()?;
425        Ok(p)
426    }
427    /// Serving needs flat programs only; encoder inspection trees are optional.
428    pub fn for_read(frame: &[u8]) -> Res<Self> {
429        let mut p = Self::open(frame)?;
430        p.finish()?;
431        Ok(p)
432    }
433    /// For reading: JC02-JC05 frame, compiled except for the hash order of
434    /// ledgers, which is restored when a whole ledger is read.
435    pub fn open(frame: &[u8]) -> Res<Self> {
436        Self::shared(&decompress_frame(frame)?, false, None)
437    }
438    /// JC06 frame (payload mode 2): `open_parts` compiles no part yet,
439    /// `parse_parts` all of them with inspection trees.
440    pub fn open_parts(frame: &[u8]) -> Res<Self> {
441        Self::parts_frame(frame, false)
442    }
443    pub fn parse_parts(frame: &[u8]) -> Res<Self> {
444        let mut p = Self::parts_frame(frame, true)?;
445        p.finish()?;
446        Ok(p)
447    }
448    fn parts_frame(frame: &[u8], auxiliary: bool) -> Res<Self> {
449        let l = frame_parts(frame)?;
450        let raw = zstd::bulk::decompress(&frame[l.shared.clone()], l.shared_raw).map_err(er)?;
451        if raw.len() != l.shared_raw {
452            return Err("shared section size".into());
453        }
454        let base = l.head;
455        let spans = l
456            .parts
457            .iter()
458            .map(|(r, raw)| (r.start - base, r.len(), *raw))
459            .collect();
460        Self::shared(&raw, auxiliary, Some((frame[base..].to_vec(), spans)))
461    }
462    /// Checks every part against its digest before compiling it: the block
463    /// passed the full check when the digests were taken (`pool` seals).
464    pub fn check_parts(&mut self, hash: [u8; 32], digests: Vec<[u8; 32]>) -> Res<()> {
465        if digests.len() != self.shared.spans.len() || !self.shared.v6 {
466            return Err("part digests".into());
467        }
468        self.shared.sealed = Some((hash, digests));
469        Ok(())
470    }
471    /// For a block checked by its seal (`check_parts`): what earlier
472    /// preparations of the same block in this process found. `checked` has a
473    /// flag per seal digest (the head, then every part): a part whose flag is
474    /// set already matched its digest and is not hashed again, and a part that
475    /// matches sets it. `tx` holds the hashes of the block's transactions by
476    /// position; they are taken from it and added to it. Both come from bytes
477    /// that matched the seal, so neither is used for a block without one.
478    pub(crate) fn remember(&mut self, checked: Arc<[AtomicBool]>, tx: TxMemo) {
479        if self.shared.sealed.is_none() {
480            return;
481        }
482        if checked.len() == self.shared.spans.len() + 1 {
483            self.shared.checked = Some(checked);
484        }
485        if tx.len() == self.tx_hashes.len() {
486            self.tx_memo = Some(tx);
487        }
488    }
489    /// Transactions in the block.
490    pub(crate) fn tx_count(&self) -> usize {
491        self.tx_hashes.len()
492    }
493    /// Hash of the transaction at `index`, if this block or an earlier
494    /// preparation of it already computed it.
495    fn known_tx(&mut self, index: usize) -> Res<Option<[u8; 32]>> {
496        let local = *self.tx_hashes.get(index).ok_or("TX hash index")?;
497        if local.is_some() {
498            return Ok(local);
499        }
500        let memo = self
501            .tx_memo
502            .as_ref()
503            .and_then(|m| m.get(index)?.get().copied());
504        if memo.is_some() {
505            self.tx_hashes[index] = memo;
506        }
507        Ok(memo)
508    }
509    fn keep_tx(&mut self, index: usize, hash: [u8; 32]) {
510        self.tx_hashes[index] = Some(hash);
511        if let Some(m) = self.tx_memo.as_ref().and_then(|m| m.get(index)) {
512            let _ = m.set(hash);
513        }
514    }
515    /// Shared section of `raw`; for JC02-JC05 the single part that follows it is
516    /// compiled too, for JC06 `parts` holds the compressed parts.
517    fn shared(raw: &[u8], auxiliary: bool, parts: Option<Frames>) -> Res<Self> {
518        let mut r = Read::new(raw);
519        let magic = r.take(4)?;
520        let v6 = magic == b"JC06";
521        let v5 = magic == b"JC05" || v6;
522        let v4 = magic == b"JC04" || v5;
523        let v3 = magic == b"JC03" || v4;
524        if !v3 && magic != b"JC02" {
525            return Err("journal magic".into());
526        }
527        if v6 != parts.is_some() {
528            return Err("journal parts".into());
529        }
530        let layout_bytes = r.blob()?;
531        let mut part_ledgers = vec![];
532        if v6 {
533            let mut pr = Read::new(r.blob()?);
534            for _ in 0..pr.items()? {
535                part_ledgers.push(pr.count()?);
536            }
537            pr.end()?;
538        }
539        let mut pool = Vec::with_capacity(raw.len());
540        let mut keys = vec![];
541        let dict = read_dictionary(&mut r, &mut pool, &[], &mut keys)?;
542        let mut templates = vec![];
543        let mut dense = IdMap::default();
544        for _ in 0..r.items()? {
545            let mut t = vec![];
546            for _ in 0..r.items()? {
547                t.push(match r.byte()? {
548                    0 => Op::Value(append(&mut pool, r.blob()?)?),
549                    tag @ (1 | 3) => {
550                        if tag == 3 && !v5 {
551                            return Err("template tag".into());
552                        }
553                        let key = usize::try_from(r.var()?).map_err(er)?;
554                        let next = dense.len();
555                        let k = *dense.entry(key).or_insert(next);
556                        if tag == 1 {
557                            Op::Column(k)
558                        } else {
559                            Op::Cached(k)
560                        }
561                    }
562                    2 => Op::Child,
563                    _ => return Err("template tag".into()),
564                })
565            }
566            templates.push(t)
567        }
568        // The layout of every ledger, before any document is compiled.
569        let total_raw = parts
570            .as_ref()
571            .map_or(raw.len(), |(_, s)| s.iter().map(|x| x.2).sum::<usize>());
572        let mut lr = Read::new(layout_bytes);
573        let mut ledgers = vec![];
574        let mut first_tx = 0;
575        for _ in 0..lr.count()? {
576            let seq = u32::try_from(lr.var()?).map_err(er)?;
577            let nt = lr.count()?;
578            // Every transaction takes at least two shapes of a byte each.
579            if nt > total_raw / 4 {
580                return Err("TX layout count".into());
581            }
582            let canonical = v5 && lr.b.get(lr.p) == Some(&2);
583            let order = if canonical {
584                lr.byte()?;
585                None
586            } else if v5 {
587                Some(read_order(&mut lr, nt)?)
588                    .filter(|o| o.iter().enumerate().any(|(i, &j)| i != j))
589            } else {
590                None
591            };
592            let patches = lr.count()?;
593            if patches > total_raw / 4 {
594                return Err("patch layout count".into());
595            }
596            ledgers.push(Planned {
597                seq,
598                txs: nt,
599                patches,
600                order,
601                first_tx,
602                part: 0,
603                header_doc: usize::MAX,
604                sorted: !canonical,
605            });
606            first_tx += nt;
607        }
608        lr.end()?;
609        let (frames, spans) = parts.unwrap_or_default();
610        let mut ranges = vec![];
611        if v6 {
612            if part_ledgers.len() != spans.len()
613                || part_ledgers.contains(&0)
614                || part_ledgers.iter().sum::<usize>() != ledgers.len()
615            {
616                return Err("part ledgers".into());
617            }
618            let mut at = 0;
619            for (p, &n) in part_ledgers.iter().enumerate() {
620                for l in &mut ledgers[at..at + n] {
621                    l.part = p;
622                }
623                ranges.push(at..at + n);
624                at += n;
625            }
626        } else {
627            ranges.push(0..ledgers.len());
628        }
629        let dictionary = v6.then(|| zstd::dict::DecoderDictionary::copy(raw));
630        let layout = ledgers
631            .iter()
632            .map(|l| Layout {
633                seq: l.seq,
634                header: usize::MAX,
635                tx: vec![],
636                patches: vec![],
637            })
638            .collect();
639        let plans = if auxiliary {
640            templates
641                .iter()
642                .map(|t| {
643                    t.iter()
644                        .map(|op| {
645                            Ok(match op {
646                                Op::Value(a) => PlanOp::Fixed(bytes(&pool, *a)?.to_vec()),
647                                Op::Column(_) | Op::Cached(_) => PlanOp::Value,
648                                Op::Child => PlanOp::Child,
649                            })
650                        })
651                        .collect::<Res<Vec<_>>>()
652                })
653                .collect::<Res<Vec<_>>>()?
654        } else {
655            vec![]
656        };
657        let n_parts = ranges.len();
658        let mut prepared = Self {
659            pool,
660            atoms: vec![],
661            docs: vec![],
662            layout,
663            tree: vec![],
664            tree_docs: vec![],
665            plans,
666            key_hashes: vec![None; keys.len()],
667            keys,
668            tx_hashes: vec![None; first_tx],
669            tx_memo: None,
670            ledgers,
671            shared: Box::new(Shared {
672                templates,
673                dense,
674                dict,
675                v3,
676                v4,
677                v6,
678                auxiliary,
679                frames,
680                spans,
681                parts: ranges,
682                done: vec![false; n_parts],
683                dictionary_bytes: if v6 { raw.len() } else { 0 },
684                dictionary,
685                sealed: None,
686                checked: None,
687            }),
688        };
689        if !v6 {
690            prepared.compile(0, &raw[r.p..])?;
691        }
692        Ok(prepared)
693    }
694    /// Compiles every part and restores the original order of every ledger.
695    fn finish(&mut self) -> Res<()> {
696        for i in 0..self.ledgers.len() {
697            self.sorted(i)?;
698        }
699        Ok(())
700    }
701    /// Parts compiled so far.
702    pub fn compiled_parts(&self) -> usize {
703        self.shared.done.iter().filter(|d| **d).count()
704    }
705    fn ledger_part(&mut self, i: usize) -> Res<()> {
706        let p = self.ledgers.get(i).ok_or("ledger index")?.part;
707        if self.shared.done[p] {
708            return Ok(());
709        }
710        let (at, len, raw) = self.shared.spans[p];
711        if let Some((hash, digests)) = &self.shared.sealed {
712            let flag = self.shared.checked.as_ref().map(|c| &c[p + 1]);
713            if !flag.is_some_and(|f| f.load(Ordering::Acquire)) {
714                if seal_digest(hash, &self.shared.frames[at..at + len]) != digests[p] {
715                    return Err("part does not match its seal".into());
716                }
717                if let Some(f) = flag {
718                    f.store(true, Ordering::Release);
719                }
720            }
721        }
722        let bytes = {
723            let d = self.shared.dictionary.as_ref().ok_or("journal parts")?;
724            let mut z = zstd::bulk::Decompressor::with_prepared_dictionary(d).map_err(er)?;
725            z.decompress(&self.shared.frames[at..at + len], raw)
726                .map_err(er)?
727        };
728        if bytes.len() != raw {
729            return Err("part size".into());
730        }
731        self.compile(p, &bytes)
732    }
733    /// Ledger `i` with `Layout::tx` in original order.
734    fn sorted(&mut self, i: usize) -> Res<()> {
735        self.ledger_part(i)?;
736        if self.ledgers[i].sorted {
737            return Ok(());
738        }
739        let l = &self.ledgers[i];
740        let (first, header) = (l.first_tx, l.header_doc);
741        let v6 = self.shared.v6;
742        let mut tx = Vec::with_capacity(self.layout[i].tx.len());
743        for (id, meta) in self.layout[i].tx.clone() {
744            // Derived hashes name encoded positions in JC06, original ones before.
745            let index = v6.then(|| first + (id - header - 1) / 2);
746            let known = match index {
747                Some(k) => self.known_tx(k)?,
748                None => None,
749            };
750            let hash = match known {
751                Some(hash) => hash,
752                None => {
753                    // TX programs cannot refer to TX-derived hashes (checked when compiled).
754                    let hash = shamap::tx_id(&self.document(id)?);
755                    if let Some(k) = index {
756                        self.keep_tx(k, hash);
757                    }
758                    hash
759                }
760            };
761            tx.push((hash, id, meta));
762        }
763        tx.sort_unstable();
764        if tx.windows(2).any(|w| w[0].0 == w[1].0) {
765            return Err("canonical TX hash duplicate".into());
766        }
767        if !v6 {
768            for (k, (hash, _, _)) in tx.iter().enumerate() {
769                self.tx_hashes[first + k] = Some(*hash);
770            }
771        }
772        self.layout[i].tx = tx.into_iter().map(|(_, id, m)| (id, m)).collect();
773        self.ledgers[i].sorted = true;
774        Ok(())
775    }
776    /// Compiles part `p` from its bytes: shapes, contexts and columns.
777    fn compile(&mut self, p: usize, raw: &[u8]) -> Res<()> {
778        let sh = &*self.shared;
779        let (v3, v4) = (sh.v3, sh.v4);
780        let mut r = Read::new(raw);
781        let pool = &mut self.pool;
782        pool.reserve(raw.len() / 2);
783        // A JC06 part starts with its own dictionary; its ids follow the shared ones.
784        let local = if sh.v6 {
785            let local = read_dictionary(&mut r, pool, &sh.dict, &mut self.keys)?;
786            self.key_hashes.resize(self.keys.len(), None);
787            local
788        } else {
789            vec![]
790        };
791        let base = &sh.dict;
792        let lookup = |id: usize| -> Option<Atom> {
793            if id < base.len() {
794                Some(base[id])
795            } else {
796                local.get(id - base.len()).copied()
797            }
798        };
799        let dict_len = base.len() + local.len();
800        let ns = r.count()?;
801        let mut shapes = Vec::with_capacity(ns.min(1_000_000));
802        let mut contexts = vec![];
803        if v3 {
804            let mut s = Read::new(r.blob()?);
805            let mut c = Read::new(r.blob()?);
806            if ns > s.b.len() || ns > c.b.len() {
807                return Err("count exceeds input".into());
808            }
809            let mut prev = 0u64;
810            for _ in 0..ns {
811                shapes.push(s.count()?);
812                let z = c.var()?;
813                let d = ((z >> 1) as i64) ^ -((z & 1) as i64);
814                prev = prev.wrapping_add(d as u64);
815                contexts.push(usize::try_from(prev).map_err(er)?);
816            }
817            s.end()?;
818            c.end()?;
819        } else {
820            if ns > r.b.len() - r.p {
821                return Err("count exceeds input".into());
822            }
823            for _ in 0..ns {
824                shapes.push(r.count()?);
825                contexts.push(r.count()?);
826            }
827        }
828        let mut columns = vec![];
829        let mut map = vec![usize::MAX; sh.dense.len()];
830        for _ in 0..r.items()? {
831            let key = usize::try_from(r.var()?).map_err(er)?;
832            let count = r.count()?;
833            let mode = r.byte()?;
834            let mut c = Read::new(r.blob()?);
835            // Modes 0 and 1 spend at least a byte per item.
836            if mode != 2 && count > c.b.len() {
837                return Err("count exceeds input".into());
838            }
839            let mut items = Vec::with_capacity(count.min(c.b.len()));
840            match mode {
841                0 => {
842                    for _ in 0..count {
843                        let tag = c.count()?;
844                        items.push(if tag == 0 {
845                            Item::Value(value_append(&mut c, pool)?)
846                        } else if tag == 1 {
847                            Item::Value(Atom { at: 0, len: REPEAT })
848                        } else if v3 && [2, 3].contains(&tag) {
849                            Item::Delta(if tag == 2 { 4 } else { 8 }, c.var()?)
850                        } else {
851                            let id = tag
852                                .checked_sub(if v3 { 4 } else { 2 })
853                                .ok_or("dictionary id")?;
854                            Item::Value(lookup(id).ok_or("dictionary id")?)
855                        });
856                    }
857                }
858                1 => {
859                    let width = c.byte()? as usize;
860                    if ![4, 8].contains(&width) {
861                        return Err("delta width".into());
862                    }
863                    let mut prev = 0u64;
864                    for _ in 0..count {
865                        let z = c.var()?;
866                        let d = ((z >> 1) as i64) ^ -((z & 1) as i64);
867                        prev = prev.wrapping_add(d as u64);
868                        if width == 4 && prev > u32::MAX as u64 {
869                            return Err("delta overflow".into());
870                        }
871                        items.push(Item::Value(append(pool, &prev.to_be_bytes()[8 - width..])?));
872                    }
873                }
874                2 if v4 => {
875                    let data = c.take(c.b.len() - c.p)?;
876                    joint::decode_into(data, count, dict_len, |token| {
877                        items.push(match token {
878                            joint::Scalar::Literal(v) => Item::Value(append(pool, v)?),
879                            joint::Scalar::Dictionary(id) => {
880                                Item::Value(lookup(id).ok_or("dictionary id")?)
881                            }
882                            joint::Scalar::Repeat => Item::Value(Atom { at: 0, len: REPEAT }),
883                            joint::Scalar::ContextDelta(w, z) => Item::Delta(w, z),
884                        });
885                        Ok(())
886                    })?;
887                }
888                _ => return Err("column mode".into()),
889            }
890            c.end()?;
891            // A column no template names would stay unread.
892            let Some(&d) = sh.dense.get(&key) else {
893                if items.is_empty() {
894                    continue;
895                }
896                return Err("unused programs".into());
897            };
898            if map[d] != usize::MAX {
899                return Err("duplicate column".into());
900            }
901            map[d] = columns.len();
902            columns.push(Column { items, pos: 0 });
903        }
904        r.end()?;
905        let range = sh.parts[p].clone();
906        let mut atoms = std::mem::take(&mut self.atoms);
907        let mut docs = std::mem::take(&mut self.docs);
908        atoms.reserve(raw.len() / 4);
909        docs.reserve(
910            self.ledgers[range.clone()]
911                .iter()
912                .map(|l| 1 + 2 * (l.txs + l.patches))
913                .sum(),
914        );
915        let mut tree = std::mem::take(&mut self.tree);
916        let mut tree_docs = std::mem::take(&mut self.tree_docs);
917        let mut c = Compiler {
918            auxiliary: sh.auxiliary,
919            pool,
920            templates: &sh.templates,
921            local: &map,
922            shapes: &shapes,
923            contexts: &contexts,
924            columns: &mut columns,
925            at: 0,
926            cache: PairMap::with_capacity_and_hasher(shapes.len() / 2, Default::default()),
927            atoms: &mut atoms,
928            docs: &mut docs,
929            tree: &mut tree,
930            tree_docs: &mut tree_docs,
931        };
932        let mut built = vec![];
933        let mut tx_ids = vec![];
934        for i in range.clone() {
935            let l = &self.ledgers[i];
936            if l.txs > shapes.len() / 2 {
937                return Err("TX layout count".into());
938            }
939            let header = c.doc()?;
940            let mut tx = vec![(0, 0); l.txs];
941            for k in 0..l.txs {
942                let id = c.doc()?;
943                let meta = c.doc()?;
944                tx_ids.push(id);
945                tx[l.order.as_ref().map_or(k, |o| o[k])] = (id, meta);
946            }
947            let mut patches = vec![];
948            for _ in 0..l.patches {
949                patches.push((c.doc()?, c.doc()?));
950            }
951            built.push((header, tx, patches));
952        }
953        let unused = c.at != shapes.len() || c.columns.iter().any(|c| c.pos != c.items.len());
954        drop(c);
955        self.atoms = atoms;
956        self.docs = docs;
957        self.tree = tree;
958        self.tree_docs = tree_docs;
959        if unused {
960            return Err("unused programs".into());
961        }
962        for &id in &tx_ids {
963            let d = &self.docs[id];
964            if self.atoms[d.start..d.end].iter().any(|a| a.len == TX) {
965                return Err("TX depends on TX hash".into());
966            }
967        }
968        for (i, (header, tx, patches)) in range.zip(built) {
969            self.ledgers[i].header_doc = header;
970            self.layout[i].header = header;
971            self.layout[i].tx = tx;
972            self.layout[i].patches = patches;
973        }
974        self.shared.done[p] = true;
975        Ok(())
976    }
977    /// Document of the transaction a derived hash names.
978    fn tx_document(&mut self, index: usize) -> Res<usize> {
979        let i = self
980            .ledgers
981            .partition_point(|l| l.first_tx <= index)
982            .checked_sub(1)
983            .ok_or("TX document")?;
984        let k = index - self.ledgers[i].first_tx;
985        if k >= self.ledgers[i].txs {
986            return Err("TX document".into());
987        }
988        if self.shared.v6 {
989            self.ledger_part(i)?;
990            Ok(self.ledgers[i].header_doc + 1 + 2 * k)
991        } else {
992            self.sorted(i)?;
993            Ok(self.layout[i].tx[k].0)
994        }
995    }
996    fn document(&mut self, id: usize) -> Res<Vec<u8>> {
997        let d = self.docs.get(id).ok_or("document index")?;
998        let (start, end, size) = (d.start, d.end, d.size);
999        let mut out = Vec::with_capacity(size);
1000        for at in start..end {
1001            let a = self.atoms[at];
1002            if a.len == TX {
1003                let index = a.at as usize;
1004                let hash = if let Some(hash) = self.known_tx(index)? {
1005                    hash
1006                } else {
1007                    let doc = self.tx_document(index)?;
1008                    let hash = shamap::tx_id(&self.document(doc)?);
1009                    self.keep_tx(index, hash);
1010                    hash
1011                };
1012                out.extend(hash)
1013            } else if a.len == KEY {
1014                let i = a.at as usize;
1015                let h = if let Some(h) = self.key_hashes.get(i).ok_or("key id")? {
1016                    *h
1017                } else {
1018                    let (domain, args) = self.keys.get(i).ok_or("key recipe")?;
1019                    let mut pre = vec![0, *domain];
1020                    for &v in args {
1021                        pre.extend(bytes(&self.pool, v)?)
1022                    }
1023                    let h = sha512_half(&pre);
1024                    self.key_hashes[i] = Some(h);
1025                    h
1026                };
1027                out.extend(h);
1028            } else {
1029                out.extend(bytes(&self.pool, a)?)
1030            }
1031        }
1032        Ok(out)
1033    }
1034    /// Transaction at position `index` of the block, in original order.
1035    pub fn tx(&mut self, index: usize) -> Res<(Vec<u8>, Vec<u8>)> {
1036        let i = self
1037            .ledgers
1038            .partition_point(|l| l.first_tx <= index)
1039            .checked_sub(1)
1040            .ok_or("TX index")?;
1041        let k = index - self.ledgers[i].first_tx;
1042        if k >= self.ledgers[i].txs {
1043            return Err("TX index".into());
1044        }
1045        self.sorted(i)?;
1046        let (t, m) = self.layout[i].tx[k];
1047        Ok((self.document(t)?, self.document(m)?))
1048    }
1049    /// Transaction of ledger `ledger` whose metadata has TransactionIndex
1050    /// `index`, without the rest of the ledger. Ledgers are encoded in
1051    /// TransactionIndex order, so the position is tried first.
1052    pub fn tx_with_index(&mut self, ledger: usize, index: u32) -> Res<Option<(Vec<u8>, Vec<u8>)>> {
1053        self.ledger_part(ledger)?;
1054        let (header, n) = (self.ledgers[ledger].header_doc, self.ledgers[ledger].txs);
1055        let at = index as usize;
1056        let tries = (at < n)
1057            .then_some(at)
1058            .into_iter()
1059            .chain((0..n).filter(|&k| k != at));
1060        for k in tries {
1061            let meta = self.document(header + 2 + 2 * k)?;
1062            if tx_index(&meta) == Some(index) {
1063                return Ok(Some((self.document(header + 1 + 2 * k)?, meta)));
1064            }
1065        }
1066        Ok(None)
1067    }
1068    pub fn patch(&mut self, ledger: usize, index: usize) -> Res<([u8; 32], Vec<u8>)> {
1069        self.ledger_part(ledger)?;
1070        let (k, v) = *self
1071            .layout
1072            .get(ledger)
1073            .ok_or("ledger index")?
1074            .patches
1075            .get(index)
1076            .ok_or("patch index")?;
1077        Ok((
1078            self.document(k)?
1079                .try_into()
1080                .map_err(|_| "patch key width")?,
1081            self.document(v)?,
1082        ))
1083    }
1084    /// Number of ledgers in the block.
1085    pub fn ledger_count(&self) -> usize {
1086        self.ledgers.len()
1087    }
1088    /// Sequence of ledger `index`.
1089    pub fn seq(&self, index: usize) -> Option<u32> {
1090        self.ledgers.get(index).map(|l| l.seq)
1091    }
1092    /// Transactions in ledger `index`.
1093    pub fn txs_in(&self, index: usize) -> Option<usize> {
1094        self.ledgers.get(index).map(|l| l.txs)
1095    }
1096    pub fn row(&mut self, index: usize) -> Res<Row> {
1097        self.sorted(index)?;
1098        let l = self.layout.get(index).ok_or("ledger index")?.clone();
1099        let header = self.document(l.header)?;
1100        let mut txs = vec![];
1101        let mut patches = vec![];
1102        for (t, m) in l.tx {
1103            txs.push((self.document(t)?, self.document(m)?));
1104        }
1105        for (k, v) in l.patches {
1106            patches.push((
1107                self.document(k)?
1108                    .try_into()
1109                    .map_err(|_| "patch key width")?,
1110                self.document(v)?,
1111            ));
1112        }
1113        Ok(Row {
1114            seq: l.seq,
1115            header,
1116            txs,
1117            patches,
1118        })
1119    }
1120    /// Header of ledger `index`, without touching its transactions or patches.
1121    pub fn header(&mut self, index: usize) -> Res<Vec<u8>> {
1122        self.ledger_part(index)?;
1123        let h = self.layout.get(index).ok_or("ledger index")?.header;
1124        self.document(h)
1125    }
1126    /// Ledger `index` with its transactions but without patches (left empty):
1127    /// readers that serve transactions don't pay for state changes.
1128    pub fn row_txs(&mut self, index: usize) -> Res<Row> {
1129        self.sorted(index)?;
1130        let l = self.layout.get(index).ok_or("ledger index")?;
1131        let (seq, h, tx) = (l.seq, l.header, l.tx.clone());
1132        let header = self.document(h)?;
1133        let mut txs = Vec::with_capacity(tx.len());
1134        for (t, m) in tx {
1135            txs.push((self.document(t)?, self.document(m)?));
1136        }
1137        Ok(Row {
1138            seq,
1139            header,
1140            txs,
1141            patches: Vec::new(),
1142        })
1143    }
1144    pub fn all_rows(&mut self) -> Res<Vec<Row>> {
1145        (0..self.layout.len()).map(|i| self.row(i)).collect()
1146    }
1147    pub fn memory_bytes(&self) -> usize {
1148        self.tree.capacity() * 8
1149            + self.tree_docs.capacity() * 16
1150            + self
1151                .plans
1152                .iter()
1153                .map(|p| {
1154                    p.capacity() * 32
1155                        + p.iter()
1156                            .map(|op| match op {
1157                                PlanOp::Fixed(v) => v.capacity(),
1158                                _ => 0,
1159                            })
1160                            .sum::<usize>()
1161                })
1162                .sum::<usize>()
1163            + self
1164                .keys
1165                .iter()
1166                .map(|(_, v)| 24 + v.capacity() * 8)
1167                .sum::<usize>()
1168            + self.key_hashes.capacity() * 33
1169            + self.pool.capacity()
1170            + self.atoms.capacity() * std::mem::size_of::<Atom>()
1171            + self.docs.capacity() * std::mem::size_of::<Doc>()
1172            + self.tx_hashes.capacity() * std::mem::size_of::<Option<[u8; 32]>>()
1173            + self.ledgers.capacity() * std::mem::size_of::<Planned>()
1174            + self.shared.frames.capacity()
1175            + self.shared.dictionary_bytes
1176            + self
1177                .shared
1178                .templates
1179                .iter()
1180                .map(|t| 24 + t.capacity() * 16)
1181                .sum::<usize>()
1182            + self.layout.capacity() * std::mem::size_of::<Layout>()
1183            + self
1184                .layout
1185                .iter()
1186                .map(|l| (l.tx.capacity() + l.patches.capacity()) * 16)
1187                .sum::<usize>()
1188    }
1189}
1190
1191/// TransactionIndex of canonical metadata: its first field.
1192fn tx_index(meta: &[u8]) -> Option<u32> {
1193    match *meta {
1194        [0x20, 0x1C, a, b, c, d, ..] => Some(u32::from_be_bytes([a, b, c, d])),
1195        _ => None,
1196    }
1197}
1198/// Encoded-position -> original-position permutation, checked before document compilation.
1199fn read_order(r: &mut Read<'_>, n: usize) -> Res<Vec<usize>> {
1200    match r.byte()? {
1201        0 => Ok((0..n).collect()),
1202        1 => {
1203            if n > r.b.len() - r.p {
1204                return Err("permutation count".into());
1205            }
1206            let mut seen = vec![false; n];
1207            let mut out = Vec::with_capacity(n);
1208            for _ in 0..n {
1209                let i = r.count()?;
1210                if i >= n || seen[i] {
1211                    return Err("invalid permutation".into());
1212                }
1213                seen[i] = true;
1214                out.push(i);
1215            }
1216            Ok(out)
1217        }
1218        _ => Err("permutation mode".into()),
1219    }
1220}
1221#[cfg(test)]
1222mod order_tests {
1223    use super::*;
1224    #[test]
1225    fn permutation_validation() {
1226        assert_eq!(
1227            read_order(&mut Read::new(&[1, 2, 0, 1]), 3).unwrap(),
1228            vec![2, 0, 1]
1229        );
1230        for b in [&[1, 0, 0, 2][..], &[1, 0, 1, 3], &[1, 0, 1], &[2]] {
1231            assert!(read_order(&mut Read::new(b), 3).is_err());
1232        }
1233    }
1234}