~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1317 lines · 46.9 KB Raw History
//! The account's repository: the data model, the MST, signed commits, CAR
//! export. Pure: it does no I/O. Its blocks are read from where its caller
//! keeps them (`Source`), and a commit reads and makes only the tree nodes
//! on the paths to the keys it writes (`edit`).

#![forbid(unsafe_code)]

pub mod data;
pub mod edit;
pub mod full;
pub mod mst;

use crate::data::*;
use crate::mst::Block;
use k256::ecdsa::SigningKey;
use k256::ecdsa::signature::hazmat::PrehashSigner;
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

/// Why the repository refused writes.
#[derive(Debug, PartialEq, Eq)]
pub enum Refused {
    /// `swapCommit` named a commit other than the latest.
    StaleCommit,
    /// A create of a record that exists, by path.
    Exists(String),
    /// An update or delete of a record that does not exist, by path.
    Missing(String),
    /// A commit whose `#commit` event would carry more than
    /// `MAX_EVENT_BLOCKS` bytes of blocks.
    TooBig,
}

/// The most bytes of blocks a commit's `#commit` event may carry, as
/// `subscribeRepos`'s lexicon says.
pub const MAX_EVENT_BLOCKS: usize = 2_000_000;

const TID_CHARS: &[u8; 32] = b"234567abcdefghijklmnopqrstuvwxyz";

pub struct Tids {
    last: u64,
    clock: u64,
}

impl Default for Tids {
    fn default() -> Self {
        Self::new()
    }
}

impl Tids {
    pub fn new() -> Self {
        Tids {
            last: 0,
            clock: rand::random::<u64>() & 1023,
        }
    }

    /// Make sure later TIDs sort after `rev`.
    pub fn after(&mut self, rev: &str) {
        let t = rev.bytes().fold(0u64, |n, c| {
            (n << 5) | TID_CHARS.iter().position(|&x| x == c).unwrap_or(0) as u64
        });
        self.last = self.last.max(t);
    }

    pub fn next_tid(&mut self) -> String {
        let micros = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;
        let t = ((micros << 10) | self.clock).max(self.last + 1);
        self.last = t;
        tid_string(t)
    }

    /// The last TID made, or that `after` was given, as a string: every one
    /// made after it is later.
    pub fn last(&self) -> String {
        tid_string(self.last)
    }
}

fn tid_string(t: u64) -> String {
    (0..13)
        .rev()
        .map(|i| TID_CHARS[((t >> (i * 5)) & 31) as usize] as char)
        .collect()
}

pub struct Record {
    pub cid: Vec<u8>,
    pub bytes: Vec<u8>,
    pub value: V,
}

pub enum Op {
    Create {
        collection: String,
        rkey: Option<String>,
        value: V,
    },
    Update {
        collection: String,
        rkey: String,
        value: V,
    },
    Delete {
        collection: String,
        rkey: String,
    },
}

pub enum OpResult {
    Create { uri: String, cid: String },
    Update { uri: String, cid: String },
    Delete,
}

/// One record operation of a commit, as its firehose event names it. `prev` is
/// the CID the record had before the commit, whatever the action, if it existed.
pub struct EvOp {
    pub action: &'static str,
    pub path: String,
    pub cid: Option<Vec<u8>>,
    pub prev: Option<Vec<u8>>,
    /// The record block for `cid`.
    pub block: Option<Block>,
}

/// What one commit changed, as the log records it, and what its firehose event carries.
#[derive(Default)]
pub struct Change {
    pub rev: String,
    pub head_bytes: Vec<u8>,
    /// Each record it put, by path, as `put_value` has it.
    pub puts: Vec<(String, serde_json::Value)>,
    /// The CID of each record of `puts`, in its order.
    pub put_cids: Vec<Vec<u8>>,
    pub dels: Vec<String>,
    /// The previous commit's rev and tree root, if there was one.
    pub since: Option<String>,
    pub prev_data: Option<Vec<u8>>,
    pub ops: Vec<EvOp>,
    /// The blocks the event carries besides the commit: tree nodes, then the
    /// records the ops wrote, each in CID order.
    pub blocks: Vec<Block>,
    /// The CIDs of the blocks, records and tree nodes, that the repository
    /// holds after this commit and did not before.
    pub added: Vec<Vec<u8>>,
    /// The tree nodes it made, new in the tree.
    pub tree: Vec<Block>,
    /// The tree nodes it took out of the tree.
    pub gone: Vec<Vec<u8>>,
    /// Each record whose count of paths holding it changed: its CID, that
    /// count after, `0` if it left the tree, and the rev of the commit that
    /// put it in the tree.
    pub refs: Vec<(Vec<u8>, u32, String)>,
    /// How many records, and blocks besides the commit, the tree holds after it.
    pub counts: (u64, u64),
    /// The repository as it was before the commit, to put back should the
    /// commit not reach its log.
    pub undo: Option<Undo>,
}

/// What a repository's blocks are read from: its caller's store, which
/// holds the blocks of its current tree, records and nodes, and nothing
/// else (`spec/STORE.md`).
pub trait Source {
    /// A block of the tree, by CID.
    fn block(&self, cid: &[u8]) -> Option<Arc<[u8]>>;
    /// The record at a path: its CID, and the rev of the commit that last wrote it.
    fn path(&self, path: &str) -> Option<(Vec<u8>, String)>;
    /// How many paths hold a record, by its CID, and the rev of the commit
    /// that put it in the tree.
    fn refs(&self, cid: &[u8]) -> Option<(u32, String)>;
}

/// A repository as it was before a commit.
pub struct Undo {
    rev: String,
    head: Vec<u8>,
    head_bytes: Vec<u8>,
    root: Vec<u8>,
    counts: (u64, u64),
}

/// An account's repository: its latest commit, and its tree, whose blocks
/// its caller keeps (`Source`).
pub struct Repo {
    pub did: String,
    key: SigningKey,
    /// Empty until the first commit.
    pub rev: String,
    pub head: Vec<u8>,
    head_bytes: Vec<u8>,
    /// The tree's root node.
    pub root: Vec<u8>,
    pub tids: Tids,
    pub change: Option<Change>,
    /// How many records the tree holds, and blocks besides the commit.
    counts: (u64, u64),
}

/// The value of a commit's field.
fn commit_field(head_bytes: &[u8], k: &str) -> Option<V> {
    match decode(head_bytes).ok()? {
        V::Map(m) => m.into_iter().find(|(n, _)| n == k).map(|(_, v)| v),
        _ => None,
    }
}

impl Repo {
    /// A repository with no commit yet: `init` makes its first, or
    /// `restore` puts back one a store holds.
    pub fn new(did: String, key: SigningKey) -> Self {
        Repo {
            did,
            key,
            rev: String::new(),
            head: vec![],
            head_bytes: vec![],
            root: vec![],
            tids: Tids::new(),
            change: None,
            counts: (0, 0),
        }
    }

    /// Put back the latest commit a store holds, with the counts of its
    /// tree's records and blocks and the last TID made: Err for a block that
    /// is no commit of this repository's.
    pub fn restore(
        &mut self,
        head_bytes: Vec<u8>,
        counts: (u64, u64),
        tid: &str,
    ) -> Result<(), String> {
        let Some(V::Str(rev)) = commit_field(&head_bytes, "rev") else {
            return Err("the latest commit has no rev".into());
        };
        let Some(V::Link(root)) = commit_field(&head_bytes, "data") else {
            return Err("the latest commit has no data".into());
        };
        if commit_field(&head_bytes, "did") != Some(V::Str(self.did.clone())) {
            return Err("a commit of another account".into());
        }
        self.head = cid_of(0x71, &head_bytes);
        self.head_bytes = head_bytes;
        self.rev = rev;
        self.root = root;
        self.counts = counts;
        self.tids.after(tid);
        self.tids.after(&self.rev);
        self.change = None;
        Ok(())
    }

    /// The first commit of a new repository: the empty tree.
    pub fn init(&mut self) -> Change {
        let bytes = edit::empty_node();
        let root = cid_of(0x71, &bytes);
        let rev = self.tids.next_tid();
        self.commit(
            rev,
            root.clone(),
            vec![(root, bytes)],
            vec![],
            vec![],
            vec![],
            vec![],
            (0, 1),
        )
    }

    /// The public key of the key that signs its commits.
    pub fn verifying_key(&self) -> &k256::ecdsa::VerifyingKey {
        self.key.verifying_key()
    }

    /// The key that signs its commits, which is its account's signing key.
    pub fn signing_key(&self) -> &SigningKey {
        &self.key
    }

    /// Sign `message` with the repository's key, as an `ES256K` JWT is
    /// signed: ECDSA over SHA-256 of it, `r ‖ s`, `s` in the lower half.
    pub fn sign(&self, message: &[u8]) -> [u8; 64] {
        let sig: k256::ecdsa::Signature = self
            .key
            .sign_prehash(&Sha256::digest(message))
            .expect("signing a 32-byte digest");
        sig.normalize_s().to_bytes().into()
    }

    pub fn head_string(&self) -> String {
        cid_string(&self.head)
    }

    /// The latest commit's block.
    pub fn head_bytes(&self) -> &[u8] {
        &self.head_bytes
    }

    /// How many records its tree holds.
    pub fn record_count(&self) -> u64 {
        self.counts.0
    }

    /// How many distinct blocks the latest commit and its tree are: the
    /// commit, every node of the tree, and every record, each CID once.
    pub fn block_count(&self) -> u64 {
        self.counts.1 + 1
    }

    /// The counts `restore` takes.
    pub fn counts(&self) -> (u64, u64) {
        self.counts
    }

    pub fn uri(&self, collection: &str, rkey: &str) -> String {
        format!("at://{}/{}/{}", self.did, collection, rkey)
    }

    /// The record at `path`, read from `src`.
    pub fn get(&self, src: &dyn Source, path: &str) -> Option<Record> {
        let (cid, _) = src.path(path)?;
        let bytes = src.block(&cid)?;
        let value = decode(&bytes).ok()?;
        Some(Record {
            cid,
            bytes: bytes.to_vec(),
            value,
        })
    }

    /// Sign a new commit over the tree rooted at `root`, with what it
    /// changed, changing nothing but the TIDs given out; put it in place.
    #[allow(
        clippy::too_many_arguments,
        reason = "each is a part of the one change a commit makes, named where its two callers give it"
    )]
    fn commit(
        &mut self,
        rev: String,
        root: Vec<u8>,
        tree: Vec<Block>,
        gone: Vec<Vec<u8>>,
        refs: Vec<(Vec<u8>, u32, String)>,
        ops: Vec<EvOp>,
        nodes: Vec<Block>,
        counts: (u64, u64),
    ) -> Change {
        let first = self.rev.is_empty();
        let mut blocks: Vec<Block> = nodes;
        if first {
            blocks.clone_from(&tree);
        }
        let mut records: Vec<Block> = ops.iter().filter_map(|o| o.block.clone()).collect();
        records.sort();
        records.dedup_by(|a, b| a.0 == b.0);
        blocks.extend(records);
        let unsigned = |sig: Option<Vec<u8>>| {
            let mut m = vec![
                ("did".to_string(), V::Str(self.did.clone())),
                ("version".to_string(), V::Int(3)),
                ("data".to_string(), V::Link(root.clone())),
                ("rev".to_string(), V::Str(rev.clone())),
                ("prev".to_string(), V::Null),
            ];
            if let Some(s) = sig {
                m.push(("sig".to_string(), V::Bytes(s)));
            }
            V::Map(m)
        };
        let hash = Sha256::digest(encode(&unsigned(None)));
        let sig: k256::ecdsa::Signature = self
            .key
            .sign_prehash(&hash)
            .expect("signing a 32-byte digest");
        let sig = sig.normalize_s();
        let bytes = encode(&unsigned(Some(sig.to_bytes().to_vec())));
        let mut added: Vec<Vec<u8>> = tree.iter().map(|(c, _)| c.clone()).collect();
        added.extend(
            refs.iter()
                .filter(|(_, n, r)| *n > 0 && *r == rev)
                .map(|(c, _, _)| c.clone()),
        );
        Change {
            rev: rev.clone(),
            head_bytes: bytes.clone(),
            since: (!first).then(|| self.rev.clone()),
            prev_data: (!first).then(|| self.root.clone()),
            ops,
            blocks,
            added,
            tree,
            gone,
            refs,
            counts,
            undo: Some(Undo {
                rev: std::mem::replace(&mut self.rev, rev),
                head: std::mem::replace(&mut self.head, cid_of(0x71, &bytes)),
                head_bytes: std::mem::replace(&mut self.head_bytes, bytes),
                root: std::mem::replace(&mut self.root, root),
                counts: std::mem::replace(&mut self.counts, counts),
            }),
            ..Default::default()
        }
    }

    /// Put the repository back as it was before the commit `undo` came with.
    pub fn undo(&mut self, u: Undo) {
        self.rev = u.rev;
        self.head = u.head;
        self.head_bytes = u.head_bytes;
        self.root = u.root;
        self.counts = u.counts;
        self.change = None;
    }

    /// Apply writes as one commit, all or nothing, reading from `src`.
    pub fn apply(
        &mut self,
        src: &dyn Source,
        ops: Vec<Op>,
        swap_commit: Option<&str>,
    ) -> Result<Vec<OpResult>, Refused> {
        self.apply_checked(src, ops, swap_commit, || Ok(()))
    }

    /// Apply writes as one commit, all or nothing, once `check` passes: it
    /// runs only once the writes are found possible, and its refusal makes no
    /// commit and changes nothing. A commit whose event would carry more than
    /// `MAX_EVENT_BLOCKS` bytes of blocks is refused too. Only the nodes on
    /// the paths to the keys it writes are read, and those it changes made.
    pub fn apply_checked<E: From<Refused>>(
        &mut self,
        src: &dyn Source,
        ops: Vec<Op>,
        swap_commit: Option<&str>,
        check: impl FnOnce() -> Result<(), E>,
    ) -> Result<Vec<OpResult>, E> {
        self.write(src, ops, swap_commit, check, true)
    }

    /// Apply writes as one commit, all or nothing, as `apply_checked` does,
    /// but with no bound on what its event would carry: a repository
    /// imported whole, whose commit goes on no `#commit` event.
    pub fn import<E: From<Refused>>(
        &mut self,
        src: &dyn Source,
        ops: Vec<Op>,
        check: impl FnOnce() -> Result<(), E>,
    ) -> Result<(), E> {
        self.write(src, ops, None, check, false).map(|_| ())
    }

    fn write<E: From<Refused>>(
        &mut self,
        src: &dyn Source,
        ops: Vec<Op>,
        swap_commit: Option<&str>,
        check: impl FnOnce() -> Result<(), E>,
        bounded: bool,
    ) -> Result<Vec<OpResult>, E> {
        if swap_commit.is_some_and(|s| s != self.head_string()) {
            return Err(Refused::StaleCommit.into());
        }
        // Each path written: its record before the commit, and after.
        let mut before: BTreeMap<String, Option<Vec<u8>>> = BTreeMap::new();
        let mut after: BTreeMap<String, Option<Record>> = BTreeMap::new();
        let mut results = Vec::new();
        let mut evops = Vec::new();
        for op in ops {
            let mut now = |path: &str| -> Option<Vec<u8>> {
                match after.get(path) {
                    Some(r) => r.as_ref().map(|r| r.cid.clone()),
                    None => before
                        .entry(path.to_string())
                        .or_insert_with(|| src.path(path).map(|(c, _)| c))
                        .clone(),
                }
            };
            match op {
                Op::Create {
                    collection,
                    rkey,
                    value,
                } => {
                    let rkey = rkey.unwrap_or_else(|| self.tids.next_tid());
                    let path = format!("{collection}/{rkey}");
                    if now(&path).is_some() {
                        return Err(Refused::Exists(path).into());
                    }
                    let rec = make_record(value);
                    let prev = before.get(&path).cloned().flatten();
                    evops.push(EvOp {
                        action: "create",
                        path: path.clone(),
                        cid: Some(rec.cid.clone()),
                        prev,
                        block: Some((rec.cid.clone(), rec.bytes.clone())),
                    });
                    results.push(OpResult::Create {
                        uri: self.uri(&collection, &rkey),
                        cid: cid_string(&rec.cid),
                    });
                    after.insert(path, Some(rec));
                }
                Op::Update {
                    collection,
                    rkey,
                    value,
                } => {
                    let path = format!("{collection}/{rkey}");
                    if now(&path).is_none() {
                        return Err(Refused::Missing(path).into());
                    }
                    let rec = make_record(value);
                    let prev = before.get(&path).cloned().flatten();
                    evops.push(EvOp {
                        action: "update",
                        path: path.clone(),
                        cid: Some(rec.cid.clone()),
                        prev,
                        block: Some((rec.cid.clone(), rec.bytes.clone())),
                    });
                    results.push(OpResult::Update {
                        uri: self.uri(&collection, &rkey),
                        cid: cid_string(&rec.cid),
                    });
                    after.insert(path, Some(rec));
                }
                Op::Delete { collection, rkey } => {
                    let path = format!("{collection}/{rkey}");
                    if now(&path).is_none() {
                        return Err(Refused::Missing(path).into());
                    }
                    let prev = before.get(&path).cloned().flatten();
                    evops.push(EvOp {
                        action: "delete",
                        path: path.clone(),
                        cid: None,
                        prev,
                        block: None,
                    });
                    results.push(OpResult::Delete);
                    after.insert(path, None);
                }
            }
        }
        check()?;
        // The tree, changed at the keys written.
        let changes: Vec<(Vec<u8>, Option<Vec<u8>>)> = after
            .iter()
            .map(|(p, r)| (p.as_bytes().to_vec(), r.as_ref().map(|r| r.cid.clone())))
            .collect();
        let fetch = |c: &[u8]| src.block(c);
        let mut e = edit::Edit::new(&fetch);
        let (root, made) = match e.apply(&self.root, &changes) {
            Ok(x) => x,
            Err(why) => panic!("the tree of {} cannot be read: {why}", self.did),
        };
        let opened: HashSet<Vec<u8>> = e.opened.into_iter().collect();
        let mut tree: Vec<Block> = made
            .iter()
            .filter(|(c, _)| !opened.contains(*c))
            .map(|(c, b)| (c.clone(), b.clone()))
            .collect();
        tree.sort();
        let mut gone: Vec<Vec<u8>> = opened
            .iter()
            .filter(|c| !made.contains_key(*c))
            .cloned()
            .collect();
        gone.sort();
        // Each record's count of paths, changed.
        let mut delta: BTreeMap<Vec<u8>, i64> = BTreeMap::new();
        for (path, r) in &after {
            let old = before.get(path).cloned().flatten();
            let new = r.as_ref().map(|r| r.cid.clone());
            if old == new {
                continue;
            }
            if let Some(o) = old {
                *delta.entry(o).or_default() -= 1;
            }
            if let Some(n) = new {
                *delta.entry(n).or_default() += 1;
            }
        }
        let rev = self.tids.next_tid();
        let mut refs = Vec::new();
        let (mut records, mut blocks) = self.counts;
        blocks = blocks + tree.len() as u64 - gone.len() as u64;
        for (cid, d) in delta.into_iter().filter(|(_, d)| *d != 0) {
            let (had, added) = src.refs(&cid).unwrap_or((0, rev.clone()));
            let n = (i64::from(had) + d).max(0) as u32;
            if had == 0 && n > 0 {
                blocks += 1;
            } else if had > 0 && n == 0 {
                blocks -= 1;
            }
            refs.push((cid, n, if had == 0 { rev.clone() } else { added }));
        }
        for (path, r) in &after {
            match (before.get(path).cloned().flatten().is_some(), r.is_some()) {
                (false, true) => records += 1,
                (true, false) => records -= 1,
                _ => {}
            }
        }
        // The event's nodes: those made, and each key's context in the new tree.
        let mut nodes: BTreeMap<Vec<u8>, Vec<u8>> = tree.iter().cloned().collect();
        {
            let fetch = |c: &[u8]| {
                made.get(c)
                    .map(|b| Arc::from(b.as_slice()))
                    .or_else(|| src.block(c))
            };
            for (k, _) in &changes {
                let mut out = Vec::new();
                if let Err(why) = edit::context(&fetch, &root, k, &mut out) {
                    panic!("the tree of {} cannot be read: {why}", self.did);
                }
                nodes.extend(out.into_iter().map(|(c, b)| (c, b.to_vec())));
            }
        }
        let nodes: Vec<Block> = nodes.into_iter().collect();
        let mut change = self.commit(rev, root, tree, gone, refs, evops, nodes, (records, blocks));
        if bounded
            && event_blocks_len(&self.head, &self.head_bytes, &change.blocks) > MAX_EVENT_BLOCKS
        {
            if let Some(u) = change.undo.take() {
                self.undo(u);
            }
            return Err(Refused::TooBig.into());
        }
        for (path, r) in &after {
            match r {
                Some(r) => {
                    change.puts.push((path.clone(), put_value(r)));
                    change.put_cids.push(r.cid.clone());
                }
                None => change.dels.push(path.clone()),
            }
        }
        self.change = Some(change);
        Ok(results)
    }

    /// The blocks with these CIDs, each once, as a CAR file with no roots:
    /// None if the repository does not hold one of them, its latest commit or
    /// a node or record of its current tree.
    pub fn blocks_car(&self, src: &dyn Source, cids: &[Vec<u8>]) -> Option<Vec<u8>> {
        let mut seen: HashSet<&[u8]> = HashSet::with_capacity(cids.len());
        let mut found: Vec<(Vec<u8>, Arc<[u8]>)> = Vec::with_capacity(cids.len());
        for cid in cids {
            if !seen.insert(cid.as_slice()) {
                continue;
            }
            if *cid == self.head {
                found.push((cid.clone(), Arc::from(self.head_bytes.as_slice())));
                continue;
            }
            found.push((cid.clone(), src.block(cid)?));
        }
        Some(car_with_roots(
            &[],
            found.iter().map(|(c, b)| (c.as_slice(), &**b)),
        ))
    }

    /// A CAR file rooted at the latest commit that proves the record at
    /// `path`, or that there is none: the commit, the tree nodes a search for
    /// the key passes through, and the record if the tree holds it.
    pub fn proof_car(&self, src: &dyn Source, path: &str) -> Vec<u8> {
        let fetch = |c: &[u8]| src.block(c);
        let nodes = edit::path(&fetch, &self.root, path.as_bytes())
            .unwrap_or_else(|why| panic!("the tree of {} cannot be read: {why}", self.did));
        let mut blocks: Vec<(Vec<u8>, Arc<[u8]>)> =
            vec![(self.head.clone(), Arc::from(self.head_bytes.as_slice()))];
        blocks.extend(nodes);
        if let Some((cid, _)) = src.path(path)
            && let Some(b) = src.block(&cid)
        {
            blocks.push((cid, b));
        }
        car_file(&self.head, blocks.iter().map(|(c, b)| (c.as_slice(), &**b)))
    }
}

/// Whether `s` is a TID: 13 characters of base32-sortable, the first of them
/// one that leaves the top bit clear.
pub fn valid_tid(s: &str) -> bool {
    let b = s.as_bytes();
    b.len() == 13 && b"234567abcdefghij".contains(&b[0]) && b.iter().all(|c| TID_CHARS.contains(c))
}

/// A CAR file with one root and these blocks, in order.
pub fn car_file<'a>(
    root: &[u8],
    blocks: impl IntoIterator<Item = (&'a [u8], &'a [u8])>,
) -> Vec<u8> {
    car_with_roots(&[root], blocks)
}

/// A CAR file with these roots, if any, and these blocks, in order.
pub fn car_with_roots<'a>(
    roots: &[&[u8]],
    blocks: impl IntoIterator<Item = (&'a [u8], &'a [u8])>,
) -> Vec<u8> {
    let header = encode(&V::Map(vec![
        (
            "roots".into(),
            V::Arr(roots.iter().map(|r| V::Link(r.to_vec())).collect()),
        ),
        ("version".into(), V::Int(1)),
    ]));
    let mut out = Vec::new();
    varint(&mut out, header.len());
    out.extend(header);
    for (cid, data) in blocks {
        varint(&mut out, cid.len() + data.len());
        out.extend(cid);
        out.extend(data);
    }
    out
}

/// Read a CAR v1 file whole: its roots and its blocks, in order. Err for
/// anything else: a header that is not exactly `{roots, version: 1}` with
/// `roots` a list of links, a section cut short or empty, a CID not version 1
/// or whose multihash is not as long as it says, or bytes after the last
/// section. Whether each CID is its block's hash is not checked.
pub fn read_car(bytes: &[u8]) -> Result<(Vec<Vec<u8>>, Vec<Block>), String> {
    let mut pos = 0;
    let header = section(bytes, &mut pos).map_err(|e| format!("the CAR header: {e}"))?;
    let roots = match decode(header).map_err(|e| format!("the CAR header: {e}"))? {
        V::Map(m) if m.len() == 2 => {
            let get = |k: &str| m.iter().find(|(n, _)| n == k).map(|(_, v)| v);
            match (get("roots"), get("version")) {
                (Some(V::Arr(roots)), Some(V::Int(1))) => roots
                    .iter()
                    .map(|r| {
                        if let V::Link(l) = r {
                            Ok(l.clone())
                        } else {
                            Err("a CAR root that is no link".to_string())
                        }
                    })
                    .collect::<Result<Vec<_>, _>>()?,
                _ => return Err("a CAR header not of version 1 with a list of roots".into()),
            }
        }
        _ => return Err("a CAR header not exactly roots and version".into()),
    };
    let mut blocks = Vec::new();
    while pos < bytes.len() {
        let at = pos;
        let s = section(bytes, &mut pos).map_err(|e| format!("the CAR section at {at}: {e}"))?;
        let mut p = 0;
        let bad = || format!("the CAR section at {at}: a CID not of version 1, or cut short");
        let [version, _codec, _hash, len] = [(); 4].map(|_| read_varint(s, &mut p));
        let (Some(1), Some(_), Some(_), Some(len)) = (version, _codec, _hash, len) else {
            return Err(bad());
        };
        let end = p
            .checked_add(usize::try_from(len).map_err(|_| bad())?)
            .filter(|e| *e <= s.len())
            .ok_or_else(bad)?;
        blocks.push((s[..end].to_vec(), s[end..].to_vec()));
    }
    Ok((roots, blocks))
}

/// Whether `cid`, a CID of version 1 with a one-byte codec and a SHA-256
/// multihash, is the hash of `bytes`.
fn hashes_to(cid: &[u8], bytes: &[u8]) -> bool {
    cid.len() == 36 && cid[0] == 1 && cid[1] < 0x80 && cid_of(cid[1], bytes) == cid
}

/// The record at `path` that a CAR file proves to be `did`'s, as
/// `atproto/sync.md` has a consumer check one: the CAR's one root is a
/// commit of `did`, version 3, whose signature `signed` accepts (given the
/// commit's bytes without its `sig`, and the `sig`), and whose tree holds
/// `path` at a CID whose block, in the CAR, hashes to it. Every block read
/// must hash to its CID. Err says why not.
pub fn proven_record(
    car: &[u8],
    did: &str,
    path: &str,
    signed: impl Fn(&[u8], &[u8]) -> bool,
) -> Result<V, String> {
    let (roots, blocks) = read_car(car)?;
    let [root] = roots.as_slice() else {
        return Err("a CAR without exactly one root".into());
    };
    let block = |cid: &[u8]| {
        blocks
            .iter()
            .find(|(c, b)| c == cid && hashes_to(c, b))
            .map(|(_, b)| b.as_slice())
    };
    let commit = block(root).ok_or("the commit is not in the CAR under its CID")?;
    let V::Map(mut fields) = decode(commit)? else {
        return Err("a commit that is no map".into());
    };
    let sig = match fields.iter().position(|(k, _)| k == "sig") {
        Some(i) => match fields.remove(i).1 {
            V::Bytes(s) => s,
            _ => return Err("a commit whose sig is not bytes".into()),
        },
        None => return Err("a commit with no sig".into()),
    };
    let field = |k: &str| fields.iter().find(|(n, _)| n == k).map(|(_, v)| v);
    if field("did") != Some(&V::Str(did.to_string())) {
        return Err(format!("a commit not of {did}"));
    }
    if field("version") != Some(&V::Int(3)) {
        return Err("a commit not of version 3".into());
    }
    let Some(V::Link(data)) = field("data") else {
        return Err("a commit with no tree".into());
    };
    let data = data.clone();
    if !signed(&encode(&V::Map(fields)), &sig) {
        return Err("a commit its key did not sign".into());
    }
    let fetch = |c: &[u8]| block(c).map(Arc::from);
    let cid = edit::get(&fetch, &data, path.as_bytes())?
        .ok_or_else(|| format!("a tree that does not hold {path}"))?;
    decode(block(&cid).ok_or("the record is not in the CAR under its CID")?)
}

/// A varint-prefixed section of a CAR file, at `pos`, moving past it.
fn section<'a>(bytes: &'a [u8], pos: &mut usize) -> Result<&'a [u8], String> {
    let n = read_varint(bytes, pos).ok_or("a length cut short")?;
    let n = usize::try_from(n)
        .ok()
        .filter(|n| *n > 0 && *n <= bytes.len() - *pos)
        .ok_or("a length of nothing, or past the end")?;
    let s = &bytes[*pos..*pos + n];
    *pos += n;
    Ok(s)
}

/// An unsigned LEB128 varint at `pos`, of at most 9 bytes, moving past it.
fn read_varint(bytes: &[u8], pos: &mut usize) -> Option<u64> {
    let mut n = 0u64;
    for i in 0..9 {
        let b = *bytes.get(*pos)?;
        *pos += 1;
        n |= u64::from(b & 0x7f) << (7 * i);
        if b & 0x80 == 0 {
            return Some(n);
        }
    }
    None
}

pub fn make_record(value: V) -> Record {
    let bytes = encode(&value);
    Record {
        cid: cid_of(0x71, &bytes),
        bytes,
        value,
    }
}

/// A record as a commit's `puts` hold it, for the log: its JSON, where that
/// reads back as its block, and otherwise its block, in hex. JSON is not
/// one-to-one: a map of the one key `$link`, a CID string, as some servers
/// wrote a blob ref's `ref`, is written as a link is, and a map with `$bytes`
/// as bytes are, so a record a CAR file brings may hold a map that JSON reads
/// back as another value, of another CID. A record is a map, so a string is
/// never one's JSON.
pub fn put_value(r: &Record) -> serde_json::Value {
    let json = to_json(&r.value);
    if from_json(&json).is_ok_and(|v| encode(&v) == r.bytes) {
        json
    } else {
        serde_json::Value::String(hex::encode(&r.bytes))
    }
}

/// The block of the record a put holds, as `put_value` wrote it.
pub fn put_block(put: &serde_json::Value) -> Result<Vec<u8>, String> {
    match put {
        serde_json::Value::String(h) => hex::decode(h).map_err(|_| format!("{h} for hex")),
        _ => from_json(put).map(|v| encode(&v)),
    }
}

/// The record a put holds, as `put_value` wrote it.
pub fn put_record(put: &serde_json::Value) -> Result<Record, String> {
    if !put.is_string() {
        return from_json(put).map(make_record);
    }
    let bytes = put_block(put)?;
    Ok(Record {
        cid: cid_of(0x71, &bytes),
        value: decode(&bytes)?,
        bytes,
    })
}

fn varint(out: &mut Vec<u8>, mut n: usize) {
    while n >= 0x80 {
        out.push((n as u8 & 0x7f) | 0x80);
        n >>= 7;
    }
    out.push(n as u8);
}

fn varint_len(n: usize) -> usize {
    (usize::BITS - n.max(1).leading_zeros()).div_ceil(7) as usize
}

/// The length of the CAR file a commit's `#commit` event carries as its
/// `blocks`: rooted at the commit, holding it and then `blocks`.
pub fn event_blocks_len(head: &[u8], head_bytes: &[u8], blocks: &[Block]) -> usize {
    let header = encode(&V::Map(vec![
        ("roots".into(), V::Arr(vec![V::Link(head.to_vec())])),
        ("version".into(), V::Int(1)),
    ]))
    .len();
    let block =
        |cid: &[u8], data: &[u8]| varint_len(cid.len() + data.len()) + cid.len() + data.len();
    varint_len(header)
        + header
        + block(head, head_bytes)
        + blocks.iter().map(|(c, d)| block(c, d)).sum::<usize>()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn varint_lengths() {
        for n in [
            0usize,
            1,
            127,
            128,
            16383,
            16384,
            2_000_000,
            usize::MAX >> 1,
        ] {
            let mut out = Vec::new();
            varint(&mut out, n);
            assert_eq!(out.len(), varint_len(n), "{n}");
        }
    }

    /// A block kept: its bytes, its count of paths, and its rev.
    type Kept = (Arc<[u8]>, u32, String);

    /// A store in memory, as the server's keeps its blocks: those of the
    /// current tree, each record with its count of paths, and each path.
    #[derive(Default)]
    pub(crate) struct Memory {
        blocks: HashMap<Vec<u8>, Kept>,
        paths: BTreeMap<String, (Vec<u8>, String)>,
    }

    impl Source for Memory {
        fn block(&self, cid: &[u8]) -> Option<Arc<[u8]>> {
            self.blocks.get(cid).map(|b| b.0.clone())
        }
        fn path(&self, path: &str) -> Option<(Vec<u8>, String)> {
            self.paths.get(path).cloned()
        }
        fn refs(&self, cid: &[u8]) -> Option<(u32, String)> {
            self.blocks
                .get(cid)
                .filter(|b| b.1 > 0)
                .map(|b| (b.1, b.2.clone()))
        }
    }

    impl Memory {
        /// Keep what a commit changed, as the server's store does once it is logged.
        pub(crate) fn commit(&mut self, c: &Change) {
            for (cid, bytes) in &c.tree {
                self.blocks
                    .insert(cid.clone(), (Arc::from(bytes.as_slice()), 1, c.rev.clone()));
            }
            for cid in &c.gone {
                self.blocks.remove(cid);
            }
            for (cid, n, rev) in &c.refs {
                if *n == 0 {
                    self.blocks.remove(cid);
                    continue;
                }
                let bytes = self
                    .blocks
                    .get(cid)
                    .map(|b| b.0.clone())
                    .unwrap_or_else(|| {
                        let at = c
                            .put_cids
                            .iter()
                            .position(|p| p == cid)
                            .expect("a record new in the tree is put");
                        Arc::from(put_block(&c.puts[at].1).unwrap())
                    });
                self.blocks.insert(cid.clone(), (bytes, *n, rev.clone()));
            }
            for (p, cid) in c.puts.iter().map(|(p, _)| p).zip(&c.put_cids) {
                self.paths.insert(p.clone(), (cid.clone(), c.rev.clone()));
            }
            for p in &c.dels {
                self.paths.remove(p);
            }
        }
    }

    struct Rng(u64);
    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        fn below(&mut self, n: u64) -> u64 {
            self.next() % n
        }
    }

    fn value(n: u64) -> V {
        V::Map(vec![
            ("$type".into(), V::Str("a.b.c".into())),
            ("n".into(), V::Int((n % 9) as i64)),
        ])
    }

    /// Over random batches of creates, updates and deletes, records sharing
    /// values too, the repository changed in place commits what the one
    /// rebuilt whole does: the same tree, the same blocks held with the
    /// same revs, the same event blocks and ops, and the same refusals.
    #[test]
    fn the_same_as_rebuilt_whole() {
        let key = SigningKey::from_slice(&[7u8; 32]).unwrap();
        for seed in 1..=12u64 {
            let mut rng = Rng(seed.wrapping_mul(0x2545_f491_4f6c_dd1d));
            let did = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa".to_string();
            let mut whole = full::Repo::new(did.clone(), key.clone());
            let mut lazy = Repo::new(did, key.clone());
            let mut mem = Memory::default();
            // TIDs past any time now, so that both make the same.
            whole.tids = Tids {
                last: 1 << 62,
                clock: 0,
            };
            lazy.tids = Tids {
                last: 1 << 62,
                clock: 0,
            };
            whole.init();
            let c = lazy.init();
            mem.commit(&c);
            for _ in 0..60 {
                let mut ops = Vec::new();
                for _ in 0..1 + rng.below(8) {
                    let rkey = format!("k{}", rng.below(40));
                    let collection = format!("a.b.c{}", rng.below(2));
                    ops.push(match rng.below(3) {
                        0 => Op::Create {
                            collection,
                            rkey: Some(rkey),
                            value: value(rng.next()),
                        },
                        1 => Op::Update {
                            collection,
                            rkey,
                            value: value(rng.next()),
                        },
                        _ => Op::Delete { collection, rkey },
                    });
                }
                let dup = |ops: &Vec<Op>| {
                    ops.iter()
                        .map(|o| match o {
                            Op::Create {
                                collection,
                                rkey,
                                value,
                            } => Op::Create {
                                collection: collection.clone(),
                                rkey: rkey.clone(),
                                value: value.clone(),
                            },
                            Op::Update {
                                collection,
                                rkey,
                                value,
                            } => Op::Update {
                                collection: collection.clone(),
                                rkey: rkey.clone(),
                                value: value.clone(),
                            },
                            Op::Delete { collection, rkey } => Op::Delete {
                                collection: collection.clone(),
                                rkey: rkey.clone(),
                            },
                        })
                        .collect::<Vec<_>>()
                };
                // The same TIDs on both sides.
                lazy.tids = Tids {
                    last: whole.tids.last,
                    clock: 0,
                };
                whole.tids = Tids {
                    last: whole.tids.last,
                    clock: 0,
                };
                let a = whole.apply(dup(&ops), None).map(|_| ());
                let b = lazy.apply(&mem, ops, None).map(|_| ());
                assert_eq!(a, b, "seed {seed}");
                if b.is_err() {
                    continue;
                }
                let (cw, cl) = (whole.change.take().unwrap(), lazy.change.take().unwrap());
                mem.commit(&cl);
                assert_eq!(cl.head_bytes, cw.head_bytes, "seed {seed}");
                assert_eq!(cl.blocks, cw.blocks, "seed {seed}: the event's blocks");
                assert_eq!(
                    cl.ops
                        .iter()
                        .map(|o| (o.action, &o.path, &o.cid, &o.prev))
                        .collect::<Vec<_>>(),
                    cw.ops
                        .iter()
                        .map(|o| (o.action, &o.path, &o.cid, &o.prev))
                        .collect::<Vec<_>>()
                );
                let mut added_l = cl.added.clone();
                let mut added_w = cw.added.clone();
                added_l.sort();
                added_w.sort();
                assert_eq!(added_l, added_w, "seed {seed}: the blocks added");
                // Every block held, with its rev.
                let mut held: Vec<(Vec<u8>, String)> = mem
                    .blocks
                    .iter()
                    .map(|(c, b)| (c.clone(), b.2.clone()))
                    .collect();
                held.sort();
                let mut want: Vec<(Vec<u8>, String)> = whole
                    .block_revs()
                    .map(|(c, r)| (c.to_vec(), r.to_string()))
                    .collect();
                want.sort();
                assert_eq!(held, want, "seed {seed}: the blocks held");
                assert_eq!(lazy.block_count(), whole.block_count() as u64);
                assert_eq!(lazy.record_count(), whole.records.len() as u64);
                let paths: Vec<(String, Vec<u8>, String)> = mem
                    .paths
                    .iter()
                    .map(|(p, (c, r))| (p.clone(), c.clone(), r.clone()))
                    .collect();
                let want: Vec<(String, Vec<u8>, String)> = whole
                    .records
                    .iter()
                    .map(|(p, r)| (p.clone(), r.cid.clone(), whole.written[p].clone()))
                    .collect();
                assert_eq!(paths, want);
                for p in whole.records.keys().take(2) {
                    assert_eq!(lazy.proof_car(&mem, p), whole.proof_car(p));
                }
            }
        }
    }

    /// A commit undone leaves the repository as it was; refused too big,
    /// nothing changes.
    #[test]
    fn undo_and_too_big() {
        let key = SigningKey::from_slice(&[7u8; 32]).unwrap();
        let mut r = Repo::new("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa".into(), key);
        let mut mem = Memory::default();
        let c = r.init();
        mem.commit(&c);
        let before = (r.head.clone(), r.rev.clone(), r.root.clone(), r.counts());
        let big = V::Map(vec![("b".into(), V::Bytes(vec![1; MAX_EVENT_BLOCKS]))]);
        assert_eq!(
            r.apply(
                &mem,
                vec![Op::Create {
                    collection: "a.b.c".into(),
                    rkey: Some("x".into()),
                    value: big
                }],
                None
            )
            .err(),
            Some(Refused::TooBig)
        );
        assert_eq!(
            (r.head.clone(), r.rev.clone(), r.root.clone(), r.counts()),
            before
        );
        r.apply(
            &mem,
            vec![Op::Create {
                collection: "a.b.c".into(),
                rkey: Some("x".into()),
                value: value(1),
            }],
            None,
        )
        .unwrap();
        let c = r.change.take().unwrap();
        r.undo(c.undo.unwrap());
        assert_eq!(
            (r.head.clone(), r.rev.clone(), r.root.clone(), r.counts()),
            before
        );
    }

    /// A record proven by the CAR `proof_car` makes passes the check a
    /// consumer makes, against the repository's key; with its record, its
    /// commit or the commit's signature changed, or another DID or path
    /// asked for, it does not.
    #[test]
    fn proofs() {
        use k256::ecdsa::signature::Verifier;
        let key = SigningKey::from_slice(&[9u8; 32]).unwrap();
        let did = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
        let mut r = Repo::new(did.into(), key.clone());
        let mut mem = Memory::default();
        let c = r.init();
        mem.commit(&c);
        let ops = (0..40)
            .map(|n| Op::Create {
                collection: "com.example.thing".into(),
                rkey: Some(format!("k{n}")),
                value: value(n),
            })
            .collect();
        r.apply(&mem, ops, None).unwrap();
        mem.commit(&r.change.take().unwrap());
        let path = "com.example.thing/k7";
        let car = r.proof_car(&mem, path);
        let vk = *key.verifying_key();
        let signed = |msg: &[u8], sig: &[u8]| {
            k256::ecdsa::Signature::from_slice(sig).is_ok_and(|s| vk.verify(msg, &s).is_ok())
        };
        let seven = encode(&value(7));
        assert_eq!(
            proven_record(&car, did, path, signed).map(|v| encode(&v)),
            Ok(seven.clone())
        );
        assert!(proven_record(&car, "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb", path, signed).is_err());
        assert!(proven_record(&car, did, "com.example.thing/k8", signed).is_err());
        let other = SigningKey::from_slice(&[8u8; 32]).unwrap();
        let ovk = *other.verifying_key();
        let other_signed = |msg: &[u8], sig: &[u8]| {
            k256::ecdsa::Signature::from_slice(sig).is_ok_and(|s| ovk.verify(msg, &s).is_ok())
        };
        assert!(proven_record(&car, did, path, other_signed).is_err());
        // Each block rewritten in place, its CID kept: the record, a tree
        // node or the commit no longer hashes to it, and the proof fails.
        let (roots, blocks) = read_car(&car).unwrap();
        for i in 0..blocks.len() {
            let mut tampered = blocks.clone();
            let last = tampered[i].1.len() - 1;
            tampered[i].1[last] ^= 1;
            let bad = car_with_roots(
                &[roots[0].as_slice()],
                tampered.iter().map(|(c, b)| (c.as_slice(), b.as_slice())),
            );
            assert!(proven_record(&bad, did, path, signed).is_err(), "block {i}");
        }
        // A record changed with its CID made to match: the tree does not hold that CID.
        let rec = blocks.iter().position(|(_, b)| *b == seven).unwrap();
        let mut swapped = blocks.clone();
        let other_value = encode(&value(8));
        swapped[rec] = (cid_of(0x71, &other_value), other_value);
        let bad = car_with_roots(
            &[roots[0].as_slice()],
            swapped.iter().map(|(c, b)| (c.as_slice(), b.as_slice())),
        );
        assert!(proven_record(&bad, did, path, signed).is_err());
        // A commit re-signed by another key, its CID made to match.
        let V::Map(mut m) = decode(&blocks[0].1).unwrap() else {
            panic!()
        };
        m.retain(|(k, _)| k != "sig");
        let hash = Sha256::digest(encode(&V::Map(m.clone())));
        let sig: k256::ecdsa::Signature = other.sign_prehash(&hash).unwrap();
        m.push((
            "sig".into(),
            V::Bytes(sig.normalize_s().to_bytes().to_vec()),
        ));
        let commit = encode(&V::Map(m));
        let cid = cid_of(0x71, &commit);
        let mut resigned = blocks.clone();
        resigned[0] = (cid.clone(), commit);
        let bad = car_with_roots(
            &[cid.as_slice()],
            resigned.iter().map(|(c, b)| (c.as_slice(), b.as_slice())),
        );
        assert!(proven_record(&bad, did, path, signed).is_err());
        assert!(proven_record(&bad, did, path, other_signed).is_ok());
    }
}