~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

atproto: the MST, CAR files, signed commits and commit proofs

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:atproto/repo
crates/atproto/src/car.rsnew+138−0
@@ -0,0 +1,138 @@
//! CAR files (CARv1): a header naming the roots, then blocks, each its
//! CID and bytes. How a repo is exported, imported, and sent down the
//! firehose a commit at a time.
use crate::cid::{Cid, DAG_CBOR};
use crate::drisl::{self, Value};
use std::collections::BTreeMap;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CarError(pub String);
impl fmt::Display for CarError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for CarError {}
fn err<T>(what: impl Into<String>) -> Result<T, CarError> {
Err(CarError(what.into()))
}
/// A CAR file read: its roots, and its blocks by CID.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Car {
pub roots: Vec<Cid>,
pub blocks: BTreeMap<Cid, Vec<u8>>,
}
fn varint(mut n: u64, out: &mut Vec<u8>) {
while n >= 0x80 {
out.push((n as u8) | 0x80);
n >>= 7;
}
out.push(n as u8);
}
/// A CAR file of `roots` and `blocks`, the blocks in the order given.
pub fn write<'a>(roots: &[Cid], blocks: impl IntoIterator<Item = (&'a Cid, &'a [u8])>) -> Vec<u8> {
let header = drisl::encode(&Value::Map(BTreeMap::from([
(
"roots".into(),
Value::Array(roots.iter().map(|c| Value::Link(*c)).collect()),
),
("version".into(), Value::Integer(1)),
])));
let mut out = Vec::new();
varint(header.len() as u64, &mut out);
out.extend(header);
for (cid, bytes) in blocks {
let cid = cid.to_bytes();
varint((cid.len() + bytes.len()) as u64, &mut out);
out.extend(cid);
out.extend(bytes);
}
out
}
struct Reader<'a> {
bytes: &'a [u8],
at: usize,
}
impl Reader<'_> {
fn varint(&mut self) -> Result<usize, CarError> {
let mut n: u64 = 0;
for shift in (0..64).step_by(7) {
let Some(&b) = self.bytes.get(self.at) else {
return err("the file ends in the middle of a length");
};
self.at += 1;
n |= u64::from(b & 0x7f) << shift;
if b & 0x80 == 0 {
// Past what this machine can hold, `take` refuses it.
return Ok(usize::try_from(n).unwrap_or(usize::MAX));
}
}
err("a length too long")
}
fn take(&mut self, n: usize) -> Result<&[u8], CarError> {
if n > self.bytes.len() - self.at {
return err("the file ends in the middle of a block");
}
let start = self.at;
self.at += n;
Ok(&self.bytes[start..self.at])
}
}
/// The CAR file `bytes` hold. Each block's CID is checked against its
/// bytes; a block whose CID is not one atproto blesses is refused.
pub fn read(bytes: &[u8]) -> Result<Car, CarError> {
let mut r = Reader { bytes, at: 0 };
let len = r.varint()?;
let header = drisl::decode(r.take(len)?).or_else(|e| err(format!("the header: {e}")))?;
let Value::Map(header) = header else {
return err("the header is not a map");
};
let (Some(Value::Integer(1)), Some(Value::Array(roots))) =
(header.get("version"), header.get("roots"))
else {
return err("the header is not version 1 with roots");
};
let roots = roots
.iter()
.map(|r| match r {
Value::Link(c) => Ok(*c),
_ => err("a root is not a link"),
})
.collect::<Result<_, _>>()?;
let mut car = Car {
roots,
blocks: BTreeMap::new(),
};
while r.at < bytes.len() {
let len = r.varint()?;
let block = r.take(len)?;
// A blessed CID is 36 bytes: version, codec, hash and its length.
let Some((cid, data)) = block.split_at_checked(36) else {
return err("a block too short for its CID");
};
let cid = Cid::from_bytes(cid).or_else(|e| err(format!("a block's CID: {e}")))?;
// Cid::from_bytes allows only these two codecs.
let hashed = if cid.codec() == DAG_CBOR {
Cid::of_cbor(data)
} else {
Cid::of_raw(data)
};
if hashed != cid {
return err(format!("block {cid} does not hash to its CID"));
}
car.blocks.insert(cid, data.to_vec());
}
Ok(car)
}
crates/atproto/src/commit.rsnew+120−0
@@ -0,0 +1,120 @@
//! A repo's signed commit (version 3): the account, the root of its
//! records' tree, a revision, and the account's signature over the rest.
use crate::cid::Cid;
use crate::drisl::{self, Value};
use crate::keys::{Keypair, PublicKey};
use std::collections::BTreeMap;
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub struct Commit {
pub did: String,
/// The root of the records' tree.
pub data: Cid,
/// A TID, later than every commit's before it.
pub rev: String,
/// Kept for version 2's sake, and almost always none.
pub prev: Option<Cid>,
pub sig: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommitError(pub &'static str);
impl fmt::Display for CommitError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for CommitError {}
impl Commit {
/// The commit of `did`'s tree `data` at `rev`, signed with `key`.
pub fn sign(did: &str, data: Cid, rev: &str, key: &Keypair) -> Commit {
let mut commit = Commit {
did: did.to_string(),
data,
rev: rev.to_string(),
prev: None,
sig: Vec::new(),
};
commit.sig = key.sign(&drisl::encode(&commit.unsigned())).to_vec();
commit
}
fn unsigned(&self) -> Value {
Value::Map(self.fields())
}
fn fields(&self) -> BTreeMap<String, Value> {
BTreeMap::from([
("did".into(), Value::String(self.did.clone())),
("version".into(), Value::Integer(3)),
("data".into(), Value::Link(self.data)),
("rev".into(), Value::String(self.rev.clone())),
("prev".into(), self.prev.map_or(Value::Null, Value::Link)),
])
}
/// The signed commit, as its block holds it.
pub fn to_bytes(&self) -> Vec<u8> {
let mut map = self.fields();
map.insert("sig".into(), Value::Bytes(self.sig.clone()));
drisl::encode(&Value::Map(map))
}
pub fn cid(&self) -> Cid {
Cid::of_cbor(&self.to_bytes())
}
/// The commit a block holds: version 3, with every field it needs.
pub fn from_bytes(bytes: &[u8]) -> Result<Commit, CommitError> {
let bad = CommitError("not a version 3 commit");
let Ok(Value::Map(map)) = drisl::decode(bytes) else {
return Err(bad);
};
// Its fields and no others: one more would be dropped here, and the
// commit written back would not come to its CID.
if map.len() != 6 {
return Err(bad);
}
let field = |k: &str| map.get(k);
let (
Some(Value::String(did)),
Some(Value::Integer(3)),
Some(Value::Link(data)),
Some(Value::String(rev)),
Some(prev),
Some(Value::Bytes(sig)),
) = (
field("did"),
field("version"),
field("data"),
field("rev"),
field("prev"),
field("sig"),
)
else {
return Err(bad);
};
let prev = match prev {
Value::Null => None,
Value::Link(c) => Some(*c),
_ => return Err(bad),
};
Ok(Commit {
did: did.clone(),
data: *data,
rev: rev.clone(),
prev,
sig: sig.clone(),
})
}
/// Whether `key`, the account's signing key, signed this.
pub fn verify(&self, key: &PublicKey) -> bool {
key.verify(&drisl::encode(&self.unsigned()), &self.sig)
}
}
crates/atproto/src/lib.rs+4−0
@@ -8,12 +8,16 @@
//! `tests/interop`. The parts still to come are in `docs/design/README.md`.
pub mod base32;
pub mod car;
pub mod cid;
pub mod commit;
pub mod drisl;
pub mod keys;
pub mod mst;
pub mod syntax;
pub mod tid;
pub use cid::Cid;
pub use commit::Commit;
pub use drisl::Value;
pub use keys::{Curve, Keypair, PublicKey};
crates/atproto/src/mst.rsnew+368−0
@@ -0,0 +1,368 @@
//! The Merkle search tree a repo's records hang from: keys
//! (`collection/rkey`) to the CIDs of their records, in a tree whose shape
//! follows from the keys alone, so that the same records always hash to
//! the same root.
//!
//! A tree is built whole from its keys ([`Tree::build`]) rather than
//! changed in place. That is all a group's repo needs while repos are
//! small; changing it in place is for when they are not.
use crate::cid::{Cid, DAG_CBOR};
use crate::drisl::{self, Value};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MstError(pub String);
impl fmt::Display for MstError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for MstError {}
fn err<T>(what: impl Into<String>) -> Result<T, MstError> {
Err(MstError(what.into()))
}
/// The layer a key sits at: the leading zero bits of its SHA-256, in
/// pairs, so that each layer holds about a quarter of the one below.
pub fn depth(key: &[u8]) -> u32 {
let hash = Sha256::digest(key);
let mut zeros = 0;
for byte in hash {
zeros += byte.leading_zeros();
if byte != 0 {
break;
}
}
zeros / 2
}
/// How many bytes `a` and `b` start with in common.
pub fn common_prefix(a: &[u8], b: &[u8]) -> usize {
a.iter().zip(b).take_while(|(x, y)| x == y).count()
}
/// A part of a node, in key order: a subtree of the keys between its
/// neighbours, or a key and its record's CID.
#[derive(Debug, Clone, PartialEq)]
pub enum Entry {
Tree(Node),
Leaf { key: String, value: Cid },
}
/// A node of the tree, with its bytes and CID worked out once.
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
entries: Vec<Entry>,
bytes: Vec<u8>,
cid: Cid,
}
impl Node {
fn new(entries: Vec<Entry>) -> Node {
let bytes = drisl::encode(&Node::value(&entries));
Node {
cid: Cid::of_cbor(&bytes),
entries,
bytes,
}
}
/// The node as DRISL has it: `l`, its leftmost subtree, then `e`, its
/// keys, each with its prefix shared with the key before it elided, and
/// `t`, the subtree to its right.
fn value(entries: &[Entry]) -> Value {
let link = |e: Option<&Entry>| match e {
Some(Entry::Tree(n)) => Value::Link(n.cid),
_ => Value::Null,
};
let mut e = Vec::new();
let mut last: &[u8] = &[];
for (i, entry) in entries.iter().enumerate() {
if let Entry::Leaf { key, value } = entry {
let p = common_prefix(last, key.as_bytes());
e.push(Value::Map(BTreeMap::from([
("p".into(), Value::Integer(p as i64)),
("k".into(), Value::Bytes(key.as_bytes()[p..].to_vec())),
("v".into(), Value::Link(*value)),
("t".into(), link(entries.get(i + 1))),
])));
last = key.as_bytes();
}
}
Value::Map(BTreeMap::from([
("l".into(), link(entries.first())),
("e".into(), Value::Array(e)),
]))
}
pub fn cid(&self) -> Cid {
self.cid
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
pub fn entries(&self) -> &[Entry] {
&self.entries
}
/// The index of the first key at or after `key`, or past the end.
fn index_at_or_after(&self, key: &str) -> usize {
self.entries
.iter()
.position(|e| matches!(e, Entry::Leaf { key: k, .. } if k.as_str() >= key))
.unwrap_or(self.entries.len())
}
fn tree_at(&self, index: usize) -> Option<&Node> {
match self.entries.get(index) {
Some(Entry::Tree(n)) => Some(n),
_ => None,
}
}
fn before(&self, index: usize) -> Option<&Node> {
index.checked_sub(1).and_then(|i| self.tree_at(i))
}
fn add_to(&self, blocks: &mut Blocks) {
blocks.insert(self.cid, self.bytes.clone());
}
// What a reader needs to see `key`'s place in the tree, as the
// reference implementation gives it, so that the firehose's proofs are
// the same: the nodes down to where the key is or would be, and down
// the edges of the subtrees either side of it.
fn proof_for_key(&self, key: &str, blocks: &mut Blocks) {
let index = self.index_at_or_after(key);
let found = matches!(self.entries.get(index), Some(Entry::Leaf { key: k, .. }) if k == key);
if !found {
match self.before(index) {
Some(prev) => prev.proof_for_key(key, blocks),
None => return,
}
}
self.add_to(blocks);
}
fn proof_for_left(&self, key: &str, blocks: &mut Blocks) {
let index = self.index_at_or_after(key);
if let Some(prev) = self.before(index) {
prev.proof_for_left(key, blocks);
}
self.add_to(blocks);
}
fn proof_for_right(&self, key: &str, blocks: &mut Blocks) {
let index = self.index_at_or_after(key);
let at = match self.entries.get(index) {
Some(e) => Some((index, e)),
None => index.checked_sub(1).map(|i| (i, &self.entries[i])),
};
// Its neighbour from `index`, not from where it was found, as the
// reference has it: past the end, that is the key itself, and so no
// subtree.
let next = match at {
Some((_, Entry::Tree(n))) => Some(n),
Some((_, Entry::Leaf { key: k, .. })) if k == key => self.tree_at(index + 1),
Some((_, Entry::Leaf { .. })) => self.before(index),
None => None,
};
if let Some(n) = next {
n.proof_for_right(key, blocks);
}
self.add_to(blocks);
}
fn walk<'a>(&'a self, nodes: &mut Vec<&'a Node>, leaves: &mut Vec<(&'a str, Cid)>) {
nodes.push(self);
for e in &self.entries {
match e {
Entry::Tree(n) => n.walk(nodes, leaves),
Entry::Leaf { key, value } => leaves.push((key, *value)),
}
}
}
}
/// Blocks by CID: a node's, a record's, a commit's.
pub type Blocks = BTreeMap<Cid, Vec<u8>>;
/// A whole tree.
#[derive(Debug, Clone, PartialEq)]
pub struct Tree {
root: Node,
}
impl Tree {
/// The tree of `records`, keys to their records' CIDs.
pub fn build(records: &BTreeMap<String, Cid>) -> Tree {
let items: Vec<(&str, Cid, u32)> = records
.iter()
.map(|(k, v)| (k.as_str(), *v, depth(k.as_bytes())))
.collect();
let top = items.iter().map(|i| i.2).max().unwrap_or(0);
Tree {
root: build(&items, top),
}
}
/// The root's CID: a commit's `data`.
pub fn root(&self) -> Cid {
self.root.cid
}
pub fn root_node(&self) -> &Node {
&self.root
}
/// Every node, parents before children, in key order.
pub fn nodes(&self) -> Vec<&Node> {
let (mut nodes, mut leaves) = (Vec::new(), Vec::new());
self.root.walk(&mut nodes, &mut leaves);
nodes
}
/// Every key and its record's CID, in key order.
pub fn leaves(&self) -> Vec<(&str, Cid)> {
let (mut nodes, mut leaves) = (Vec::new(), Vec::new());
self.root.walk(&mut nodes, &mut leaves);
leaves
}
/// Every node's block.
pub fn blocks(&self) -> Blocks {
self.nodes()
.into_iter()
.map(|n| (n.cid, n.bytes.clone()))
.collect()
}
/// The nodes of this tree that `before` does not have: what a commit
/// from `before` to this adds.
pub fn new_since(&self, before: &Tree) -> Blocks {
let had: BTreeSet<Cid> = before.nodes().into_iter().map(|n| n.cid).collect();
self.nodes()
.into_iter()
.filter(|n| !had.contains(&n.cid))
.map(|n| (n.cid, n.bytes.clone()))
.collect()
}
/// The nodes a reader needs, beside the new ones, to undo a change to
/// `key` and find the tree before: the nodes down to its place, and
/// down the edges of its neighbours.
pub fn covering_proof(&self, key: &str) -> Blocks {
let mut blocks = Blocks::new();
self.root.proof_for_key(key, &mut blocks);
self.root.proof_for_left(key, &mut blocks);
self.root.proof_for_right(key, &mut blocks);
blocks
}
/// The tree whose root is `root`, read from `blocks`, every node
/// checked: keys in order, each at its depth, and the whole the one
/// tree its keys make. A node missing from `blocks` fails it.
pub fn read(root: Cid, blocks: &Blocks) -> Result<Tree, MstError> {
let mut records = BTreeMap::new();
read_node(root, blocks, &mut records, &mut BTreeSet::new(), 0)?;
let tree = Tree::build(&records);
if tree.root() != root {
return err("the tree is not the one its keys make");
}
Ok(tree)
}
}
fn build(items: &[(&str, Cid, u32)], height: u32) -> Node {
let mut entries = Vec::new();
let mut run = 0;
for (i, &(key, value, d)) in items.iter().enumerate() {
if d == height {
if run < i {
entries.push(Entry::Tree(build(&items[run..i], height - 1)));
}
entries.push(Entry::Leaf {
key: key.to_string(),
value,
});
run = i + 1;
}
}
if run < items.len() {
entries.push(Entry::Tree(build(&items[run..], height - 1)));
}
Node::new(entries)
}
/// How deep a tree read from elsewhere may go.
const MAX_LAYERS: usize = 64;
/// Reads the node `cid` and the tree under it into `records`. A node
/// reached twice is refused: no tree reaches one node from two places, and
/// blocks that do could make the walk take time exponential in depth.
fn read_node(
cid: Cid,
blocks: &Blocks,
records: &mut BTreeMap<String, Cid>,
seen: &mut BTreeSet<Cid>,
layer: usize,
) -> Result<(), MstError> {
if layer > MAX_LAYERS {
return err("the tree is too deep");
}
if !seen.insert(cid) {
return err(format!("node {cid} is reached twice"));
}
if cid.codec() != DAG_CBOR {
return err(format!("node {cid} is not DAG-CBOR"));
}
let Some(bytes) = blocks.get(&cid) else {
return err(format!("node {cid} is missing"));
};
let value = drisl::decode(bytes).or_else(|e| err(format!("node {cid}: {e}")))?;
let bad = || MstError(format!("node {cid} is not a tree node"));
let Value::Map(map) = value else {
return Err(bad());
};
let (Some(Value::Array(entries)), Some(left), 2) = (map.get("e"), map.get("l"), map.len())
else {
return Err(bad());
};
let subtree = |v: &Value, records: &mut BTreeMap<String, Cid>, seen: &mut BTreeSet<Cid>| match v
{
Value::Null => Ok(()),
Value::Link(c) => read_node(*c, blocks, records, seen, layer + 1),
_ => Err(bad()),
};
subtree(left, records, seen)?;
let mut last: Vec<u8> = Vec::new();
for e in entries {
let Value::Map(e) = e else {
return Err(bad());
};
let (Some(Value::Integer(p)), Some(Value::Bytes(k)), Some(Value::Link(v)), Some(t), 4) =
(e.get("p"), e.get("k"), e.get("v"), e.get("t"), e.len())
else {
return Err(bad());
};
let p = usize::try_from(*p).map_err(|_| bad())?;
if p > last.len() {
return Err(bad());
}
let key = [&last[..p], k].concat();
let key = String::from_utf8(key).map_err(|_| bad())?;
records.insert(key.clone(), *v);
subtree(t, records, seen)?;
last = key.into_bytes();
}
Ok(())
}
crates/atproto/tests/interop/firehose/commit-proof-fixtures.jsonnew+118−0
@@ -0,0 +1,118 @@
[
{
"comment": "two deep split",
"leafValue": "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454",
"keys": [
"A0/374913",
"B1/986427",
"C0/451630",
"E0/670489",
"F1/085263",
"G0/765327"
],
"adds": ["D2/269196"],
"dels": [],
"rootBeforeCommit": "bafyreicraprx2xwnico4tuqir3ozsxpz46qkcpox3obf5bagicqwurghpy",
"rootAfterCommit": "bafyreihvay6pazw3dfa47u5d2tn3rd6pa57sr37bo5bqyvjuqc73ib65my",
"blocksInProof": [
"bafyreieazvzmba35p4phksumwfoklwe5o4ncmo7otud74idcyv4orrbzxi",
"bafyreie4227qpa4vbtbpnsvuhp322b776vjuhxsidi5hxp2gawumr4m3de",
"bafyreid44jgimksqqdratyste2moqu6zo4h6co2pknjppfoiplsqxtuxae",
"bafyreiaerlvitye7fjjwodkshtbqqdsmfsdjtnlz4vs6y4trnddshsmd5a",
"bafyreihvay6pazw3dfa47u5d2tn3rd6pa57sr37bo5bqyvjuqc73ib65my"
]
},
{
"comment": "two deep leafless split",
"leafValue": "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454",
"keys": ["A0/374913", "B0/601692", "D0/952776", "E0/670489"],
"adds": ["C2/014073"],
"dels": [],
"rootBeforeCommit": "bafyreialm5sgf7pijawbschsjpdevid5rss5ip3d4n4w6cc4mhu53sfl4i",
"rootAfterCommit": "bafyreibxh4iztp5l2yshz3ectg2qjpeyprpw2gogao3pvceowpq3k3thya",
"blocksInProof": [
"bafyreih7dxytqtcjv3cfia3fi3wxofeip62teqkpynnkxisxqwfchfb4bu",
"bafyreiaqbymlnvpklmogx75gozjl3y73gva43jbgwcrqu2pp5g5ejou5vm",
"bafyreicfh3st5ghtnoqyyvznjv4lhfnvl7qsndempx35i4tcmoxakqbgrm",
"bafyreieyjrrai6igjceyxzkajrxgxz37da2eufb33anvesb4ev6yzztauu",
"bafyreibxh4iztp5l2yshz3ectg2qjpeyprpw2gogao3pvceowpq3k3thya"
]
},
{
"comment": "add on edge with neighbor two layers down",
"leafValue": "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454",
"keys": ["A0/374913", "B2/827649", "C0/451630"],
"adds": ["D2/269196"],
"dels": [],
"rootBeforeCommit": "bafyreigc6ay2qwfk7kuevvrczummpd64nknfo4yxpaooknfymzyb7u3ntq",
"rootAfterCommit": "bafyreign6kxoll35r5f2ske6hjx7vg56aw3jn6r5hcopgrepzafpvohr2a",
"blocksInProof": [
"bafyreieazvzmba35p4phksumwfoklwe5o4ncmo7otud74idcyv4orrbzxi",
"bafyreidicvcjgrpm5bmhm3ndh2ysqfhgzk4chwn3m4kuvwkenfusspb4uy",
"bafyreign6kxoll35r5f2ske6hjx7vg56aw3jn6r5hcopgrepzafpvohr2a"
]
},
{
"comment": "merge and split in multi-op commit",
"leafValue": "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454",
"keys": ["A0/374913", "B2/827649", "D2/269196", "E0/670489"],
"adds": ["C2/014073"],
"dels": ["B2/827649", "D2/269196"],
"rootBeforeCommit": "bafyreiceld4icym4qjmdcn3dfgtxt7t66hdgyhvigessgmkvb56dx6amgi",
"rootAfterCommit": "bafyreigkalika3taqauapfha556lo36zzcjoiifny5xeru6yis3nxw5ruq",
"blocksInProof": [
"bafyreid44jgimksqqdratyste2moqu6zo4h6co2pknjppfoiplsqxtuxae",
"bafyreihytu6onh476trave25zuo63ziebkeong2755sc5nmf55uzdawgt4",
"bafyreigkalika3taqauapfha556lo36zzcjoiifny5xeru6yis3nxw5ruq",
"bafyreidnnkrdkcaswbflgtdsxm7nzs7p5f2rdous6wrlupzstuwqu5pfgm",
"bafyreia2kq243hqq3volwlzkbzzphoeqauk54sc5h7vgogq4ei5fjizxvy"
]
},
{
"comment": "complex multi-op commit",
"leafValue": "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454",
"keys": [
"B0/601692",
"C2/014073",
"D0/952776",
"E2/819540",
"F0/697858",
"H0/131238"
],
"adds": ["A2/827942", "G2/611528"],
"dels": ["C2/014073"],
"rootBeforeCommit": "bafyreigr3plnts7dax6yokvinbhcqpyicdfgg6npvvyx6okc5jo55slfqi",
"rootAfterCommit": "bafyreiftrcrbhrwmi37u4egedlg56gk3jeh3tvmqvwgowoifuklfysyx54",
"blocksInProof": [
"bafyreih62n3gjbzzvlicuggpfydyzrp3ssyx7hdgtltd3sct3ribm3u73e",
"bafyreihrjhuoynjvgteuefin5vwnqmupyfzvmytdobpstqt3mbawgw5qhm",
"bafyreibevzst4gzkxo263syohlmq3lpxdvpjhlpyqx2ay3moh43lifydca",
"bafyreifsdd7dv2neal7zjhyrsvndkaocelqlpgfxwo4utoq2g77klih37e",
"bafyreid2wwyroodj2lxx2obikac74q77lsn6vqkoetlqqwwnr3criwlcvy",
"bafyreie55b224oljhykpsxdjq4ajn2ysksud7qm347s6kn2ei6a775faum",
"bafyreiftrcrbhrwmi37u4egedlg56gk3jeh3tvmqvwgowoifuklfysyx54"
]
},
{
"comment": "split with earlier leaves on same layer",
"leafValue": "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454",
"keys": [
"app.bsky.feed.post/3lo3kqqljmfe2",
"app.bsky.feed.post/3log4547dm6h2",
"app.bsky.feed.post/3log45inogon2",
"app.bsky.feed.post/3logaodrh74d2",
"app.bsky.feed.post/3logteazog2n2",
"app.bsky.feed.post/3lon5cqsbwrj2",
"app.bsky.feed.repost/3l6sjhvqonco2"
],
"adds": ["app.bsky.feed.post/3lon5dzeaihj2"],
"dels": [],
"rootBeforeCommit": "bafyreigfcsro2up7qi7l3rxdpg7n6gjtteotkmgrrqztl5oy2tf4ncl4ji",
"rootAfterCommit": "bafyreig33hsjiplaixvmccy65n7rn3in5nsbtcittzx6k3w5wjfhk2sg3a",
"blocksInProof": [
"bafyreig33hsjiplaixvmccy65n7rn3in5nsbtcittzx6k3w5wjfhk2sg3a",
"bafyreih2rhjm3apcghihwfojv2em7noqkgt5qyjcnxux7do674m464oc3m",
"bafyreiajhswkduap4zvqvfhth3skdgckmk2eb5gow7vv3gvj45f4fqwmxm"
]
}
]
crates/atproto/tests/interop/README.md+3−2
@@ -3,5 +3,6 @@
From github.com/bluesky-social/atproto-interop-tests at
056e5741bb330757205d6b16db5266fffcae937b (2026-07-01), under CC0
(LICENSE-CC0), copied as they are: the syntax of the identifiers this
crate checks, the crypto and data-model vectors, and the MST's, which the
MST's pull reads. Copy a newer release over them as they change upstream.
crate checks, the crypto and data-model vectors, the MST's, and the
firehose's commit proofs. Copy a newer release over them as they change
upstream.
crates/atproto/tests/car.rsnew+84−0
@@ -0,0 +1,84 @@
//! CAR files written and read, and every file refused.
use atproto::car::{self, Car};
use atproto::cid::Cid;
use atproto::drisl::{self, Value};
use std::collections::BTreeMap;
fn header(value: Value) -> Vec<u8> {
let h = drisl::encode(&value);
[vec![h.len() as u8], h].concat()
}
fn roots(roots: Value, version: i64) -> Value {
Value::Map(BTreeMap::from([
("roots".into(), roots),
("version".into(), Value::Integer(version)),
]))
}
#[test]
fn round_trips() {
let record = drisl::encode(&Value::String("hello".into()));
let blob = vec![7u8; 200];
let (rc, bc) = (Cid::of_cbor(&record), Cid::of_raw(&blob));
let bytes = car::write(&[rc], [(&rc, &record[..]), (&bc, &blob[..])]);
let read = car::read(&bytes).unwrap();
assert_eq!(
read,
Car {
roots: vec![rc],
blocks: BTreeMap::from([(rc, record), (bc, blob)]),
}
);
}
fn refused(bytes: &[u8]) -> String {
car::read(bytes).unwrap_err().to_string()
}
#[test]
fn refuses_what_is_no_car() {
let ok = header(roots(Value::Array(vec![]), 1));
assert_eq!(refused(&[]), "the file ends in the middle of a length");
assert_eq!(refused(&[0xff; 10]), "a length too long");
assert_eq!(
refused(&[5, 0xa0]),
"the file ends in the middle of a block"
);
assert!(refused(&[1, 0xff]).starts_with("the header: "));
assert_eq!(
refused(&header(Value::Integer(1))),
"the header is not a map"
);
assert_eq!(
refused(&header(roots(Value::Array(vec![]), 2))),
"the header is not version 1 with roots"
);
assert_eq!(
refused(&header(roots(Value::Array(vec![Value::Integer(1)]), 1))),
"a root is not a link"
);
assert_eq!(
refused(&[ok.clone(), vec![3, 1, 2, 3]].concat()),
"a block too short for its CID"
);
let mut unblessed = Cid::of_raw(b"x").to_bytes();
unblessed[2] = 0x13;
assert!(
refused(&[ok.clone(), vec![unblessed.len() as u8], unblessed].concat())
.starts_with("a block's CID: ")
);
let cid = Cid::of_raw(b"x");
let lying = [ok.clone(), vec![37], cid.to_bytes(), b"y".to_vec()].concat();
assert_eq!(
refused(&lying),
format!("block {cid} does not hash to its CID")
);
let cbor = Cid::of_cbor(b"\xa0");
let lying = [ok, vec![37], cbor.to_bytes(), b"\xa1".to_vec()].concat();
assert_eq!(
refused(&lying),
format!("block {cbor} does not hash to its CID")
);
}
crates/atproto/tests/commit.rsnew+68−0
@@ -0,0 +1,68 @@
//! Commits signed, written, read back and checked.
use atproto::cid::Cid;
use atproto::commit::Commit;
use atproto::drisl::{self, Value};
use atproto::keys::{Curve, Keypair};
use std::collections::BTreeMap;
#[test]
fn signs_and_verifies() {
for curve in [Curve::K256, Curve::P256] {
let key = Keypair::generate(curve);
let data = Cid::of_cbor(b"\xa0");
let commit = Commit::sign("did:plc:abc", data, "3l5mz5mkbn22b", &key);
assert!(commit.verify(&key.public()));
assert!(!commit.verify(&Keypair::generate(curve).public()));
let read = Commit::from_bytes(&commit.to_bytes()).unwrap();
assert_eq!(read, commit);
assert_eq!(read.cid(), Cid::of_cbor(&commit.to_bytes()));
let mut changed = commit.clone();
changed.rev = "3l5mz5mkbn22c".into();
assert!(!changed.verify(&key.public()));
}
}
#[test]
fn keeps_a_prev() {
let key = Keypair::generate(Curve::K256);
let mut commit = Commit::sign("did:plc:abc", Cid::of_cbor(b"\xa0"), "3l5mz5mkbn22b", &key);
commit.prev = Some(Cid::of_cbor(b"\xf6"));
assert_eq!(Commit::from_bytes(&commit.to_bytes()).unwrap(), commit);
}
#[test]
fn refuses_what_is_no_commit() {
let refused = |v: Value| {
Commit::from_bytes(&drisl::encode(&v))
.unwrap_err()
.to_string()
};
assert_eq!(refused(Value::Integer(1)), "not a version 3 commit");
assert_eq!(
Commit::from_bytes(&[0xff]).unwrap_err().to_string(),
"not a version 3 commit"
);
let key = Keypair::generate(Curve::K256);
let good = Commit::sign("did:plc:abc", Cid::of_cbor(b"\xa0"), "3l5mz5mkbn22b", &key);
let Value::Map(map) = drisl::decode(&good.to_bytes()).unwrap() else {
unreachable!()
};
let with = |k: &str, v: Value| {
let mut m: BTreeMap<String, Value> = map.clone();
m.insert(k.into(), v);
Value::Map(m)
};
assert_eq!(
refused(with("version", Value::Integer(2))),
"not a version 3 commit"
);
assert_eq!(
refused(with("prev", Value::Integer(2))),
"not a version 3 commit"
);
assert_eq!(
refused(with("extra", Value::Integer(2))),
"not a version 3 commit"
);
}
crates/atproto/tests/mst.rsnew+209−0
@@ -0,0 +1,209 @@
//! The MST, against atproto's interop test vectors (tests/interop/mst and
//! tests/interop/firehose), and every tree it refuses to read.
use atproto::cid::Cid;
use atproto::drisl::{self, Value};
use atproto::mst::{Blocks, Tree, common_prefix, depth};
use serde_json::Value as Json;
use std::collections::{BTreeMap, BTreeSet};
fn vectors(path: &str) -> Vec<Json> {
let path = format!("{}/tests/interop/{path}", env!("CARGO_MANIFEST_DIR"));
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
fn s(v: &Json) -> &str {
v.as_str().unwrap()
}
#[test]
fn depths_and_prefixes_as_the_vectors_say() {
for v in vectors("mst/key_heights.json") {
assert_eq!(
depth(s(&v["key"]).as_bytes()),
v["height"].as_u64().unwrap() as u32
);
}
for v in vectors("mst/common_prefix.json") {
let len = common_prefix(s(&v["left"]).as_bytes(), s(&v["right"]).as_bytes());
assert_eq!(len, v["len"].as_u64().unwrap() as usize);
}
}
#[test]
fn an_empty_tree_is_one_empty_node() {
let tree = Tree::build(&BTreeMap::new());
assert_eq!(
tree.root().to_string(),
"bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm"
);
assert!(tree.leaves().is_empty());
assert!(tree.root_node().entries().is_empty());
assert_eq!(tree.root_node().cid(), tree.root());
assert_eq!(tree.root_node().bytes(), b"\xa2ae\x80al\xf6");
// A key's proof in an empty tree is the one node.
assert_eq!(tree.covering_proof("a/b").len(), 1);
}
#[test]
fn commits_and_proofs_as_the_vectors_say() {
for v in vectors("firehose/commit-proof-fixtures.json") {
let leaf = Cid::parse(s(&v["leafValue"])).unwrap();
let keys = |k: &Json| {
k.as_array()
.unwrap()
.iter()
.map(|k| s(k).to_string())
.collect::<Vec<_>>()
};
let mut records: BTreeMap<String, Cid> =
keys(&v["keys"]).into_iter().map(|k| (k, leaf)).collect();
let before = Tree::build(&records);
assert_eq!(
before.root().to_string(),
s(&v["rootBeforeCommit"]),
"{}",
v["comment"]
);
let (adds, dels) = (keys(&v["adds"]), keys(&v["dels"]));
for k in &adds {
records.insert(k.clone(), leaf);
}
for k in &dels {
records.remove(k);
}
let after = Tree::build(&records);
assert_eq!(
after.root().to_string(),
s(&v["rootAfterCommit"]),
"{}",
v["comment"]
);
let mut proof = after.new_since(&before);
for k in adds.iter().chain(&dels) {
proof.extend(after.covering_proof(k));
}
let got: BTreeSet<String> = proof.keys().map(Cid::to_string).collect();
let want: BTreeSet<String> = keys(&v["blocksInProof"]).into_iter().collect();
assert_eq!(got, want, "{}", v["comment"]);
}
}
#[test]
fn reads_back_what_it_built() {
let path = format!(
"{}/tests/interop/mst/example_keys.txt",
env!("CARGO_MANIFEST_DIR")
);
let records: BTreeMap<String, Cid> = std::fs::read_to_string(path)
.unwrap()
.lines()
.map(|k| (k.to_string(), Cid::of_cbor(k.as_bytes())))
.collect();
let tree = Tree::build(&records);
assert!(tree.nodes().len() > 1);
let read = Tree::read(tree.root(), &tree.blocks()).unwrap();
assert_eq!(read, tree);
let leaves: BTreeMap<String, Cid> = read
.leaves()
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
assert_eq!(leaves, records);
}
/// A node's block, as `entries` (each `[p, k, v, t]`) and `l` make it.
fn node(l: Value, entries: Vec<Value>) -> (Cid, Vec<u8>) {
let bytes = drisl::encode(&Value::Map(BTreeMap::from([
("l".into(), l),
("e".into(), Value::Array(entries)),
])));
(Cid::of_cbor(&bytes), bytes)
}
fn entry(p: i64, k: &[u8], v: Cid, t: Value) -> Value {
Value::Map(BTreeMap::from([
("p".into(), Value::Integer(p)),
("k".into(), Value::Bytes(k.to_vec())),
("v".into(), Value::Link(v)),
("t".into(), t),
]))
}
fn refused(root: Cid, blocks: &[(Cid, Vec<u8>)]) -> String {
let blocks: Blocks = blocks.iter().cloned().collect();
Tree::read(root, &blocks).unwrap_err().to_string()
}
#[test]
fn refuses_every_tree_but_the_one_its_keys_make() {
let v = Cid::of_cbor(b"\xa0");
let block = |value: Value| {
let bytes = drisl::encode(&value);
(Cid::of_cbor(&bytes), bytes)
};
let (missing, _) = node(Value::Null, vec![]);
assert_eq!(refused(missing, &[]), format!("node {missing} is missing"));
let raw = Cid::of_raw(b"x");
assert_eq!(refused(raw, &[]), format!("node {raw} is not DAG-CBOR"));
let garbage = (Cid::of_cbor(&[0xff]), vec![0xff]);
assert!(
refused(garbage.0, std::slice::from_ref(&garbage))
.starts_with(&format!("node {}: ", garbage.0))
);
let not_node = |b: (Cid, Vec<u8>)| {
assert_eq!(
refused(b.0, std::slice::from_ref(&b)),
format!("node {} is not a tree node", b.0)
);
};
not_node(block(Value::Integer(1)));
not_node(block(Value::Map(BTreeMap::from([(
"e".into(),
Value::Array(vec![]),
)]))));
not_node(node(Value::Integer(1), vec![]));
not_node(node(Value::Null, vec![Value::Integer(1)]));
not_node(node(Value::Null, vec![Value::Map(BTreeMap::new())]));
not_node(node(Value::Null, vec![entry(-1, b"a/b", v, Value::Null)]));
not_node(node(Value::Null, vec![entry(1, b"a/b", v, Value::Null)]));
not_node(node(Value::Null, vec![entry(0, &[0xff], v, Value::Null)]));
// Keys at the wrong depth: two keys at depth 0 split across a node and
// its subtree, where they belong in one.
let (sub, sub_bytes) = node(Value::Null, vec![entry(0, b"g", v, Value::Null)]);
let (top, top_bytes) = node(Value::Link(sub), vec![entry(0, b"h", v, Value::Null)]);
assert_eq!(depth(b"g"), 0);
assert_eq!(depth(b"h"), 0);
assert_eq!(
refused(top, &[(sub, sub_bytes), (top, top_bytes)]),
"the tree is not the one its keys make"
);
// One node reached from two places: the left link and an entry's
// right link both name it.
let (leaf, leaf_bytes) = node(Value::Null, vec![entry(0, b"g", v, Value::Null)]);
let (both, both_bytes) = node(
Value::Link(leaf),
vec![entry(0, b"h", v, Value::Link(leaf))],
);
assert_eq!(
refused(both, &[(leaf, leaf_bytes), (both, both_bytes)]),
format!("node {leaf} is reached twice")
);
// A chain of nodes deeper than any tree of real keys.
let mut chain = vec![node(Value::Null, vec![entry(0, b"a", v, Value::Null)])];
for _ in 0..65 {
let below = chain.last().unwrap().0;
chain.push(node(Value::Link(below), vec![]));
}
assert_eq!(
refused(chain.last().unwrap().0, &chain),
"the tree is too deep"
);
}
docs/design/README.md+2−1
@@ -53,7 +53,8 @@ says otherwise.
atproto's interop test vectors (`crates/atproto/tests/interop`):
- the data model: DRISL and CIDs, TIDs, the identifiers' syntax, and
secp256k1 and P-256 keys as multikeys and `did:key`s (done);
- the repo: the MST, CAR files, signed commits;
- the repo: the MST, CAR files, signed commits, and the firehose's
commit proofs (done);
- identity: PLC operations, DID documents, service-auth JWTs.
3. **Accounts and repos.** The SQLite store, group accounts and their
keys, `did:plc` creation, records and commits, the firehose