~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
501 lines · 16.5 KB Raw History
//! The Merkle Search Tree, rebuilt deterministically from the sorted key/value pairs.

use crate::data::{V, cid_of, cid_string, decode, encode};
use sha2::{Digest, Sha256};
use std::collections::HashSet;

pub type Block = (Vec<u8>, Vec<u8>);

pub fn depth(key: &[u8]) -> usize {
    let hash = Sha256::digest(key);
    let mut zeros = 0;
    for b in hash.iter() {
        if *b == 0 {
            zeros += 8;
        } else {
            zeros += b.leading_zeros() as usize;
            break;
        }
    }
    zeros / 2
}

/// One node of the tree: its block, the subtree left of its first entry and its entries.
pub struct Node {
    pub cid: Vec<u8>,
    pub bytes: Vec<u8>,
    pub left: Option<Box<Node>>,
    pub entries: Vec<Entry>,
}

pub struct Entry {
    pub key: Vec<u8>,
    pub sub: Option<Box<Node>>,
}

#[cfg(test)]
thread_local! {
    /// How many nodes walks of a tree have visited, on this thread.
    pub(crate) static VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

impl Node {
    fn collect<'a>(&'a self, out: &mut Vec<&'a Node>) {
        #[cfg(test)]
        VISITS.with(|v| v.set(v.get() + 1));
        if let Some(l) = &self.left {
            l.collect(out);
        }
        for e in &self.entries {
            if let Some(t) = &e.sub {
                t.collect(out);
            }
        }
        out.push(self);
    }

    /// Every node of the tree, children before parents.
    pub fn nodes(&self) -> Vec<&Node> {
        let mut out = Vec::new();
        self.collect(&mut out);
        out
    }

    /// The subtree in gap `i`: before entry 0 for `i == 0`, else after entry `i - 1`.
    fn gap(&self, i: usize) -> Option<&Node> {
        if i == 0 {
            self.left.as_deref()
        } else {
            self.entries[i - 1].sub.as_deref()
        }
    }

    /// This node and the chain of nodes down its left (or right) edge.
    fn spine<'a>(&'a self, right: bool, out: &mut Vec<&'a Node>) {
        let mut n = Some(self);
        while let Some(x) = n {
            out.push(x);
            n = x.gap(if right { x.entries.len() } else { 0 });
        }
    }

    /// The nodes that undoing a change at `key` may need: those on the way to
    /// the key's position and the edges of the subtrees beside that position.
    pub fn context<'a>(&'a self, key: &[u8], out: &mut Vec<&'a Node>) {
        let mut n = Some(self);
        while let Some(x) = n {
            out.push(x);
            let at = x.entries.partition_point(|e| e.key.as_slice() < key);
            let found = x.entries.get(at).is_some_and(|e| e.key == key);
            // The subtrees beside the key's position: undoing may merge or split them.
            let (lo, hi) = (
                at.saturating_sub(1),
                (at + if found { 2 } else { 1 }).min(x.entries.len()),
            );
            for g in lo..=hi {
                if let Some(s) = x.gap(g) {
                    s.spine(true, out);
                    s.spine(false, out);
                }
            }
            if found {
                return;
            }
            n = x.gap(at);
        }
    }

    /// The nodes a search for `key` passes through, from this one: in each,
    /// it ends at the entry whose key it is, or else goes on into the subtree
    /// just before the first entry that sorts after the key, and ends where
    /// there is no such subtree. They prove the key's value, or its absence.
    pub fn path<'a>(&'a self, key: &[u8]) -> Vec<&'a Node> {
        let mut out = Vec::new();
        let mut n = Some(self);
        while let Some(x) = n {
            out.push(x);
            let at = x.entries.partition_point(|e| e.key.as_slice() < key);
            if x.entries.get(at).is_some_and(|e| e.key == key) {
                break;
            }
            n = x.gap(at);
        }
        out
    }
}

/// The tree nodes a commit's `#commit` event carries, in CID order: those of
/// `after` that `before` lacks (all of them for a first commit, which has no
/// `before`), and the context of each key the commit wrote.
pub fn event_nodes<'a, 'k>(
    before: Option<&Node>,
    after: &'a Node,
    keys: impl IntoIterator<Item = &'k [u8]>,
) -> Vec<&'a Node> {
    let old: HashSet<&[u8]> = before
        .map(|b| b.nodes().into_iter().map(|n| n.cid.as_slice()).collect())
        .unwrap_or_default();
    let mut out: Vec<&Node> = after
        .nodes()
        .into_iter()
        .filter(|n| !old.contains(n.cid.as_slice()))
        .collect();
    for k in keys {
        after.context(k, &mut out);
    }
    out.sort_by(|a, b| a.cid.cmp(&b.cid));
    out.dedup_by(|a, b| a.cid == b.cid);
    out
}

/// Build the tree for sorted `(key, record cid)` pairs. Returns its root; an
/// empty repository is a single empty node.
pub fn build_tree(entries: &[(Vec<u8>, Vec<u8>)]) -> Node {
    let level = entries.iter().map(|(k, _)| depth(k)).max().unwrap_or(0);
    let depths: Vec<usize> = entries.iter().map(|(k, _)| depth(k)).collect();
    match node(entries, &depths, level) {
        Some(r) => *r,
        None => {
            let bytes = encode(&V::Map(vec![
                ("e".into(), V::Arr(vec![])),
                ("l".into(), V::Null),
            ]));
            Node {
                cid: cid_of(0x71, &bytes),
                bytes,
                left: None,
                entries: vec![],
            }
        }
    }
}

fn node(entries: &[(Vec<u8>, Vec<u8>)], depths: &[usize], level: usize) -> Option<Box<Node>> {
    if entries.is_empty() {
        return None;
    }
    let here: Vec<usize> = (0..entries.len()).filter(|&i| depths[i] == level).collect();
    let sub = |from: usize, to: usize| {
        if level == 0 {
            None
        } else {
            node(&entries[from..to], &depths[from..to], level - 1)
        }
    };
    let left = sub(0, here.first().copied().unwrap_or(entries.len()));
    let mut list = Vec::new();
    let mut kids = Vec::new();
    let mut prev: &[u8] = &[];
    for (n, &i) in here.iter().enumerate() {
        let end = here.get(n + 1).copied().unwrap_or(entries.len());
        let tree = sub(i + 1, end);
        let key = &entries[i].0;
        let p = prev
            .iter()
            .zip(key.iter())
            .take_while(|(a, b)| a == b)
            .count();
        list.push(V::Map(vec![
            ("p".into(), V::Int(p as i64)),
            ("k".into(), V::Bytes(key[p..].to_vec())),
            ("v".into(), V::Link(entries[i].1.clone())),
            (
                "t".into(),
                tree.as_ref().map_or(V::Null, |t| V::Link(t.cid.clone())),
            ),
        ]));
        kids.push(Entry {
            key: key.clone(),
            sub: tree,
        });
        prev = key;
    }
    let bytes = encode(&V::Map(vec![
        (
            "l".into(),
            left.as_ref().map_or(V::Null, |t| V::Link(t.cid.clone())),
        ),
        ("e".into(), V::Arr(list)),
    ]));
    Some(Box::new(Node {
        cid: cid_of(0x71, &bytes),
        bytes,
        left,
        entries: kids,
    }))
}

/// The `(key, value cid)` entries of a tree read from its blocks, in key
/// order, and the CIDs of the nodes it holds, each once.
pub type Walked = (Vec<(Vec<u8>, Vec<u8>)>, Vec<Vec<u8>>);

/// The deepest a tree's nodes may be below its root: a key's depth is at
/// most 128, two bits of its SHA-256 for each level.
const MAX_LEVELS: usize = 129;

/// Walk the tree rooted at `root`, its nodes found by `block`: its entries in
/// key order and its nodes. Err for a node `block` does not find, one that is
/// not a tree node (a map of exactly `l` and `e`, each entry exactly `p`,
/// `k`, `v` and `t`), a node reached twice, nodes deeper than any tree's, or
/// keys not in strictly ascending order. Whether the tree is the one its
/// entries build is not checked: `build_tree` says.
pub fn walk<'a>(root: &[u8], block: impl Fn(&[u8]) -> Option<&'a [u8]>) -> Result<Walked, String> {
    let mut out: Walked = (Vec::new(), Vec::new());
    let mut seen = HashSet::new();
    visit(root, &block, &mut out, &mut seen, 0)?;
    Ok(out)
}

fn visit<'a>(
    cid: &[u8],
    block: &impl Fn(&[u8]) -> Option<&'a [u8]>,
    out: &mut Walked,
    seen: &mut HashSet<Vec<u8>>,
    level: usize,
) -> Result<(), String> {
    let bad = |why: &str| format!("tree node {}: {why}", cid_string(cid));
    if level >= MAX_LEVELS {
        return Err(bad("deeper than any tree's nodes"));
    }
    if !seen.insert(cid.to_vec()) {
        return Err(bad("reached twice"));
    }
    let bytes = block(cid).ok_or_else(|| bad("missing"))?;
    out.1.push(cid.to_vec());
    let V::Map(mut m) = decode(bytes).map_err(|e| bad(&e))? else {
        return Err(bad("not a map"));
    };
    let link = |v: Option<V>| match v {
        Some(V::Null) => Ok(None),
        Some(V::Link(l)) => Ok(Some(l)),
        _ => Err(bad("a subtree that is no link or null")),
    };
    let (l, e) = (take(&mut m, "l"), take(&mut m, "e"));
    let (Some(V::Arr(entries)), true) = (e, m.is_empty()) else {
        return Err(bad("not exactly l and a list e"));
    };
    if let Some(l) = link(l)? {
        visit(&l, block, out, seen, level + 1)?;
    }
    let mut prev: Vec<u8> = Vec::new();
    for e in entries {
        let V::Map(mut e) = e else {
            return Err(bad("an entry not a map"));
        };
        let (p, k, v, t) = (
            take(&mut e, "p"),
            take(&mut e, "k"),
            take(&mut e, "v"),
            take(&mut e, "t"),
        );
        let (Some(V::Int(p)), Some(V::Bytes(k)), Some(V::Link(v)), true) = (p, k, v, e.is_empty())
        else {
            return Err(bad("an entry not exactly p, k, v and t"));
        };
        let p = usize::try_from(p)
            .ok()
            .filter(|p| *p <= prev.len())
            .ok_or_else(|| bad("a prefix longer than the key before"))?;
        prev.truncate(p);
        prev.extend(k);
        if out.0.last().is_some_and(|(last, _)| *last >= prev) {
            return Err(bad("keys out of order"));
        }
        out.0.push((prev.clone(), v));
        if let Some(t) = link(t)? {
            visit(&t, block, out, seen, level + 1)?;
        }
    }
    Ok(())
}

/// A map's value of key `k`, taken out of it.
fn take(m: &mut Vec<(String, V)>, k: &str) -> Option<V> {
    let i = m.iter().position(|(n, _)| n == k)?;
    Some(m.swap_remove(i).1)
}

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

    #[test]
    fn heights() {
        let text = std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../spec/interop/mst/key_heights.json"
        ))
        .unwrap();
        let cases: Vec<serde_json::Value> = serde_json::from_str(&text).unwrap();
        for c in cases {
            assert_eq!(
                depth(c["key"].as_str().unwrap().as_bytes()),
                c["height"].as_u64().unwrap() as usize,
                "{}",
                c["key"]
            );
        }
    }

    /// The fixtures' trees, before and after each commit, and every block a
    /// proof of its ops needs among the nodes its event carries.
    #[test]
    fn commit_proofs() {
        use crate::data::{cid_string, parse_cid};
        let text = std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../spec/interop/firehose/commit-proof-fixtures.json"
        ))
        .unwrap();
        let cases: Vec<serde_json::Value> = serde_json::from_str(&text).unwrap();
        assert!(!cases.is_empty());
        for c in cases {
            let leaf = parse_cid(c["leafValue"].as_str().unwrap()).unwrap();
            let strs = |k: &str| {
                c[k].as_array()
                    .unwrap()
                    .iter()
                    .map(|v| v.as_str().unwrap().to_string())
                    .collect::<Vec<_>>()
            };
            let (keys, adds, dels) = (strs("keys"), strs("adds"), strs("dels"));
            let tree = |ks: Vec<&String>| {
                let mut e: Vec<(Vec<u8>, Vec<u8>)> = ks
                    .into_iter()
                    .map(|k| (k.as_bytes().to_vec(), leaf.clone()))
                    .collect();
                e.sort();
                build_tree(&e)
            };
            let before = tree(keys.iter().collect());
            let after = tree(
                keys.iter()
                    .filter(|k| !dels.contains(k))
                    .chain(&adds)
                    .collect(),
            );
            assert_eq!(
                cid_string(&before.cid),
                c["rootBeforeCommit"],
                "{}",
                c["comment"]
            );
            assert_eq!(
                cid_string(&after.cid),
                c["rootAfterCommit"],
                "{}",
                c["comment"]
            );
            let carried = event_nodes(
                Some(&before),
                &after,
                adds.iter().chain(&dels).map(|k| k.as_bytes()),
            );
            assert!(
                carried.windows(2).all(|w| w[0].cid < w[1].cid),
                "{}: in CID order",
                c["comment"]
            );
            let carried: HashSet<String> = carried.iter().map(|n| cid_string(&n.cid)).collect();
            for b in strs("blocksInProof") {
                assert!(
                    carried.contains(&b),
                    "{}: {b} missing from the event",
                    c["comment"]
                );
            }
        }
    }

    /// A tree walked from its blocks answers its entries and every node;
    /// one missing a node, or with keys out of order, is refused.
    #[test]
    fn walks() {
        use std::collections::HashMap;
        for n in [0usize, 1, 40, 1000] {
            let mut entries: Vec<(Vec<u8>, Vec<u8>)> = (0..n)
                .map(|i| {
                    (
                        format!("a.b.c/k{i}").into_bytes(),
                        cid_of(0x71, &i.to_le_bytes()),
                    )
                })
                .collect();
            entries.sort();
            let tree = build_tree(&entries);
            let blocks: HashMap<Vec<u8>, Vec<u8>> = tree
                .nodes()
                .into_iter()
                .map(|x| (x.cid.clone(), x.bytes.clone()))
                .collect();
            let (got, nodes) = walk(&tree.cid, |c| blocks.get(c).map(Vec::as_slice)).unwrap();
            assert_eq!(got, entries);
            let mut want: Vec<Vec<u8>> = blocks.keys().cloned().collect();
            let mut nodes = nodes;
            want.sort();
            nodes.sort();
            assert_eq!(nodes, want);
            if n > 1 {
                let leaf = tree.nodes()[0].cid.clone();
                assert!(
                    walk(&tree.cid, |c| if *c == leaf[..] {
                        None
                    } else {
                        blocks.get(c).map(Vec::as_slice)
                    })
                    .is_err()
                );
            }
        }
        // Two keys swapped in one node.
        let (a, b) = (b"a.b.c/2".to_vec(), b"a.b.c/1".to_vec());
        let e = |k: &[u8]| {
            V::Map(vec![
                ("p".into(), V::Int(0)),
                ("k".into(), V::Bytes(k.to_vec())),
                ("v".into(), V::Link(cid_of(0x71, b"x"))),
                ("t".into(), V::Null),
            ])
        };
        let bytes = encode(&V::Map(vec![
            ("l".into(), V::Null),
            ("e".into(), V::Arr(vec![e(&a), e(&b)])),
        ]));
        let cid = cid_of(0x71, &bytes);
        assert!(walk(&cid, |c| (*c == cid[..]).then_some(bytes.as_slice())).is_err());
    }

    /// A node reached twice, as a left subtree and below an entry, is no
    /// tree, and is refused rather than walked again.
    #[test]
    fn a_node_reached_twice_is_refused() {
        let leaf = encode(&V::Map(vec![
            ("l".into(), V::Null),
            ("e".into(), V::Arr(vec![])),
        ]));
        let leaf_cid = cid_of(0x71, &leaf);
        let root = encode(&V::Map(vec![
            ("l".into(), V::Link(leaf_cid.clone())),
            (
                "e".into(),
                V::Arr(vec![V::Map(vec![
                    ("p".into(), V::Int(0)),
                    ("k".into(), V::Bytes(b"a/b".to_vec())),
                    ("v".into(), V::Link(cid_of(0x71, b"x"))),
                    ("t".into(), V::Link(leaf_cid.clone())),
                ])]),
            ),
        ]));
        let root_cid = cid_of(0x71, &root);
        let got = walk(&root_cid, |c| {
            if *c == root_cid[..] {
                Some(root.as_slice())
            } else if *c == leaf_cid[..] {
                Some(leaf.as_slice())
            } else {
                None
            }
        });
        assert!(got.is_err_and(|e| e.contains("reached twice")));
    }
}