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

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
949 lines · 38.7 KB Raw History
//! repo commit layer: build/sign, load, and verify
//!
//! the produce side builds and signs a commit (`signCommit`), and the consume
//! side verifies it against the full AT Protocol trust chain:
//!   handle → DID → DID document → signing key
//!                                       ↓
//!   repo CAR → commit → signature ← verified against key
//!                   ↓
//!            MST root CID → walk nodes → verify key heights → structure proven

const std = @import("std");
const Allocator = std.mem.Allocator;

const Did = @import("../syntax/did.zig").Did;
const DidDocument = @import("../identity/did_document.zig").DidDocument;
const multicodec = @import("../crypto/multicodec.zig");
const multibase = @import("../crypto/multibase.zig");
const jwt = @import("../crypto/jwt.zig");
const Keypair = @import("../crypto/keypair.zig").Keypair;
const cbor = @import("cbor.zig");
const car = @import("car.zig");
const mst = @import("mst.zig");

/// result of verifying a commit's CAR data against a signing key.
/// used by the relay to verify firehose frames without identity resolution.
pub const CommitVerifyResult = struct {
    commit_did: []const u8,
    commit_rev: []const u8,
    commit_version: i64,
    record_count: usize,
    commit_cid: []const u8,
};

pub const VerifyError = error{
    NoRootsInCar,
    CommitBlockNotFound,
    InvalidCommit,
    SignatureNotFound,
    MstRootMismatch,
    IncompleteRepo,
} || Allocator.Error;

/// verify a commit's CAR bytes against a pre-resolved signing key.
/// callers resolve the identity and fetch the CAR themselves (see the examples).
/// used by the relay to verify firehose commit frames directly.
///
/// `car_bytes` is the raw CAR data (from the firehose frame's `blocks` field).
/// `public_key` is the pre-resolved signing key for the commit's DID.
///
/// options:
///   `verify_mst` — walk the MST and verify key heights (default true).
///   `expected_did` — if set, verify the commit DID matches.
pub fn verifyCommitCar(
    allocator: Allocator,
    car_bytes: []const u8,
    public_key: multicodec.PublicKey,
    options: VerifyCommitCarOptions,
) VerifyCommitCarError!CommitVerifyResult {
    // 1. parse CAR
    const repo_car = car.readWithOptions(allocator, car_bytes, .{
        .max_size = options.max_car_size,
        .max_blocks = options.max_blocks,
    }) catch return error.InvalidCommit;
    if (repo_car.roots.len == 0) return error.NoRootsInCar;

    // 2. find commit block
    const commit_cid_raw = repo_car.roots[0].raw;
    const commit_data = car.findBlock(repo_car, commit_cid_raw) orelse return error.CommitBlockNotFound;

    // 3. decode commit
    const commit = cbor.decodeAll(allocator, commit_data) catch return error.InvalidCommit;
    const commit_did = commit.getString("did") orelse return error.InvalidCommit;
    const commit_version = commit.getInt("version") orelse return error.InvalidCommit;
    const commit_rev = commit.getString("rev") orelse return error.InvalidCommit;
    try verifyCommitSignature(allocator, commit, public_key, options.expected_did);

    // 7. optionally walk MST
    var record_count: usize = 0;
    if (options.verify_mst) {
        const data_cid_value = commit.get("data") orelse return error.InvalidCommit;
        const data_cid = switch (data_cid_value) {
            .cid => |c| c,
            else => return error.InvalidCommit,
        };
        record_count = walkAndVerifyMst(allocator, repo_car, data_cid.raw, .{
            .require_record_blocks = options.require_complete_repo,
        }) catch |err| switch (err) {
            error.OutOfMemory => return error.OutOfMemory,
            error.IncompleteRepo => if (options.require_complete_repo)
                return error.IncompleteRepo
            else
                return error.MstRootMismatch,
            else => return error.MstRootMismatch,
        };
    }

    return .{
        .commit_did = commit_did,
        .commit_rev = commit_rev,
        .commit_version = commit_version,
        .record_count = record_count,
        .commit_cid = commit_cid_raw,
    };
}

pub const VerifyCommitCarOptions = struct {
    verify_mst: bool = true,
    require_complete_repo: bool = false,
    expected_did: ?[]const u8 = null,
    max_car_size: ?usize = null, // null = default 2MB
    max_blocks: ?usize = null, // null = default 10,000
};

pub const VerifyCommitCarError = error{
    NoRootsInCar,
    CommitBlockNotFound,
    InvalidCommit,
    SignatureNotFound,
    SignatureVerificationFailed,
    MstRootMismatch,
    IncompleteRepo,
    OutOfMemory,
    WriteFailed,
};

/// Authenticates a decoded commit with a caller-resolved key. Does not verify
/// referenced blocks, freshness, or that the supplied key belongs to the DID.
/// Uses scratch allocation only; the caller retains ownership of commit.
pub fn verifyCommitSignature(allocator: Allocator, commit: cbor.Value, public_key: multicodec.PublicKey, expected_did: ?[]const u8) !void {
    const did = commit.getString("did") orelse return error.InvalidCommit;
    if (Did.parse(did) == null or commit.getInt("version") != 3) return error.InvalidCommit;
    _ = commit.getString("rev") orelse return error.InvalidCommit;
    if (expected_did) |expected| {
        if (!std.mem.eql(u8, did, expected)) return error.InvalidCommit;
    }
    const signature = commit.getBytes("sig") orelse return error.SignatureNotFound;
    const unsigned = try encodeUnsignedCommit(allocator, commit);
    defer allocator.free(unsigned);
    try verifySignatureBytes(unsigned, signature, public_key);
}

fn verifySignatureBytes(unsigned: []const u8, signature: []const u8, public_key: multicodec.PublicKey) error{SignatureVerificationFailed}!void {
    switch (public_key.key_type) {
        .p256 => jwt.verifyP256(unsigned, signature, public_key.raw) catch return error.SignatureVerificationFailed,
        .secp256k1 => jwt.verifySecp256k1(unsigned, signature, public_key.raw) catch return error.SignatureVerificationFailed,
    }
}

/// encode a commit value without the "sig" field (for signature verification)
pub fn encodeUnsignedCommit(allocator: Allocator, commit: cbor.Value) ![]u8 {
    const entries = switch (commit) {
        .map => |m| m,
        else => return error.InvalidCommit,
    };

    // filter out "sig", keep everything else
    var unsigned_entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
    defer unsigned_entries.deinit(allocator);
    for (entries) |entry| {
        if (!std.mem.eql(u8, entry.key, "sig")) {
            try unsigned_entries.append(allocator, entry);
        }
    }

    const unsigned_value: cbor.Value = .{ .map = unsigned_entries.items };
    return cbor.encodeAlloc(allocator, unsigned_value);
}

/// parameters for building a signed AT Protocol repo commit (data model v3).
pub const CommitParams = struct {
    /// repo DID the commit belongs to.
    did: []const u8,
    /// commit revision TID; must increase monotonically per repo.
    rev: []const u8,
    /// CID of the MST root — the repo's "data" pointer.
    data: cbor.Cid,
    /// CID of the previous commit, or null for the first commit.
    prev: ?cbor.Cid = null,
    /// commit data-model version. AT Protocol currently requires 3.
    version: u64 = 3,
};

/// a signed commit block ready to embed in a CAR or firehose frame.
pub const SignedCommit = struct {
    /// CID of the signed commit block.
    cid: cbor.Cid,
    /// canonical DAG-CBOR bytes of the signed commit.
    bytes: []const u8,

    pub fn deinit(self: SignedCommit, allocator: Allocator) void {
        allocator.free(self.cid.raw);
        allocator.free(self.bytes);
    }
};

/// build and sign an AT Protocol repo commit.
///
/// producer-side counterpart to `verifyCommitCar`: assembles the canonical
/// unsigned commit, signs its DAG-CBOR bytes with `keypair`, and returns the
/// signed commit block plus its CID. the resulting signature verifies under
/// `verifyCommitCar` / `verifyCommitDiff` against the keypair's public key.
///
/// caller owns the returned `SignedCommit` and must `deinit` it.
pub fn signCommit(
    allocator: Allocator,
    params: CommitParams,
    keypair: *const Keypair,
) !SignedCommit {
    const unsigned_entries = [_]cbor.Value.MapEntry{
        .{ .key = "did", .value = .{ .text = params.did } },
        .{ .key = "version", .value = .{ .unsigned = params.version } },
        .{ .key = "data", .value = .{ .cid = params.data } },
        .{ .key = "rev", .value = .{ .text = params.rev } },
        .{ .key = "prev", .value = if (params.prev) |p| .{ .cid = p } else .null },
    };

    const unsigned_bytes = try cbor.encodeAlloc(allocator, .{ .map = &unsigned_entries });
    defer allocator.free(unsigned_bytes);
    const sig = try keypair.sign(unsigned_bytes);

    const signed_entries = unsigned_entries ++ [_]cbor.Value.MapEntry{
        .{ .key = "sig", .value = .{ .bytes = &sig.bytes } },
    };
    const signed_bytes = try cbor.encodeAlloc(allocator, .{ .map = &signed_entries });
    errdefer allocator.free(signed_bytes);
    const cid = try cbor.Cid.forDagCbor(allocator, signed_bytes);
    return .{ .cid = cid, .bytes = signed_bytes };
}

const MstWalkOptions = struct {
    require_record_blocks: bool = false,
};

/// walk the MST using the specialized decoder, verifying each key's tree layer
/// is deterministically correct. combined with CAR block CID verification
/// (which proves data integrity), this is equivalent to a full MST rebuild.
///
/// When `require_record_blocks` is true, this also proves a full repo CAR is
/// semantically complete by checking that each record CID referenced by the MST
/// is present in the CAR. Keep it false for intentional diff CARs.
fn walkAndVerifyMst(allocator: Allocator, repo_car: car.Car, root_cid_raw: []const u8, options: MstWalkOptions) !usize {
    const root_data = car.findBlock(repo_car, root_cid_raw) orelse return error.IncompleteRepo;
    const root_node = try mst.decodeMstNode(allocator, root_data);
    if (root_node.entries.len == 0 and root_node.left == null) return 0;

    // root layer = key height of first entry (first entry always has prefix_len = 0)
    const root_layer = mst.keyHeight(root_node.entries[0].key_suffix);

    return walkVerifyNode(allocator, repo_car, root_node, root_layer, options);
}

const WalkError = VerifyError || mst.MstDecodeError;

fn walkVerifyNode(allocator: Allocator, repo_car: car.Car, node: mst.MstNodeData, expected_layer: u32, options: MstWalkOptions) WalkError!usize {
    var count: usize = 0;
    var key_buf: [512]u8 = undefined;
    var key_len: usize = 0;

    // left subtree
    if (node.left) |left_cid| {
        if (expected_layer == 0) return error.MstRootMismatch;
        count += try walkVerifyChild(allocator, repo_car, left_cid, expected_layer - 1, options);
    }

    for (node.entries) |entry| {
        // reconstruct key from prefix compression (in-place, zero alloc)
        @memcpy(key_buf[entry.prefix_len..][0..entry.key_suffix.len], entry.key_suffix);
        key_len = entry.prefix_len + entry.key_suffix.len;

        // verify this key belongs at the expected layer
        if (mst.keyHeight(key_buf[0..key_len]) != expected_layer) return error.MstRootMismatch;

        count += 1;

        if (options.require_record_blocks and car.findBlock(repo_car, entry.value) == null) {
            return error.IncompleteRepo;
        }

        // right subtree
        if (entry.tree) |tree_cid| {
            if (expected_layer == 0) return error.MstRootMismatch;
            count += try walkVerifyChild(allocator, repo_car, tree_cid, expected_layer - 1, options);
        }
    }

    return count;
}

fn walkVerifyChild(allocator: Allocator, repo_car: car.Car, cid_raw: []const u8, expected_layer: u32, options: MstWalkOptions) WalkError!usize {
    const block_data = car.findBlock(repo_car, cid_raw) orelse return error.IncompleteRepo;
    const node = try mst.decodeMstNode(allocator, block_data);
    return walkVerifyNode(allocator, repo_car, node, expected_layer, options);
}

// === sync 1.1: commit diff verification ===

/// decoded commit fields from a CAR file
pub const Commit = struct {
    did: []const u8,
    rev: []const u8,
    version: i64,
    sig: []const u8,
    data_cid: []const u8, // raw CID bytes — MST root
    prev: ?[]const u8, // raw CID bytes — previous commit CID (null for first commit)
};

pub const LoadedCommitCar = struct {
    commit: Commit,
    commit_cid: []const u8,
    unsigned_commit_bytes: []const u8,
    repo_car: car.Car,
};

/// lightweight: parse CAR, find root block, decode commit CBOR.
/// no MST loading. reusable for both #commit and #sync frames.
/// pre-computes unsigned commit bytes for signature verification (avoids re-decode).
/// reads with the default CAR limits (2 MB, 10,000 blocks), sized for firehose
/// frames; a whole-repo CAR needs `loadCommitFromCARWithOptions`.
pub fn loadCommitFromCAR(allocator: Allocator, car_bytes: []const u8) !LoadedCommitCar {
    return loadCommitFromCARWithOptions(allocator, car_bytes, .{});
}

/// `loadCommitFromCAR` with caller-chosen CAR read limits.
pub fn loadCommitFromCARWithOptions(allocator: Allocator, car_bytes: []const u8, options: car.ReadOptions) !LoadedCommitCar {
    const repo_car = car.readWithOptions(allocator, car_bytes, options) catch return error.InvalidCommit;
    if (repo_car.roots.len == 0) return error.NoRootsInCar;

    const commit_cid_raw = repo_car.roots[0].raw;
    const commit_data = car.findBlock(repo_car, commit_cid_raw) orelse return error.CommitBlockNotFound;

    const commit_value = cbor.decodeAll(allocator, commit_data) catch return error.InvalidCommit;
    const commit_did = commit_value.getString("did") orelse return error.InvalidCommit;
    const commit_version = commit_value.getInt("version") orelse return error.InvalidCommit;
    const commit_rev = commit_value.getString("rev") orelse return error.InvalidCommit;
    const sig_bytes = commit_value.getBytes("sig") orelse return error.SignatureNotFound;

    // pre-compute unsigned commit bytes while we have the cbor.Value
    const unsigned_commit_bytes = encodeUnsignedCommit(allocator, commit_value) catch return error.InvalidCommit;

    // extract data CID (MST root)
    const data_cid_value = commit_value.get("data") orelse return error.InvalidCommit;
    const data_cid_raw = switch (data_cid_value) {
        .cid => |c| c.raw,
        else => return error.InvalidCommit,
    };

    // extract prev commit CID (optional)
    const prev_cid_raw: ?[]const u8 = if (commit_value.get("prev")) |prev_value| switch (prev_value) {
        .cid => |c| c.raw,
        .null => null,
        else => return error.InvalidCommit,
    } else null;

    return .{
        .commit = .{
            .did = commit_did,
            .rev = commit_rev,
            .version = commit_version,
            .sig = sig_bytes,
            .data_cid = data_cid_raw,
            .prev = prev_cid_raw,
        },
        .commit_cid = commit_cid_raw,
        .unsigned_commit_bytes = unsigned_commit_bytes,
        .repo_car = repo_car,
    };
}

/// Load a full repo CAR and verify that all MST nodes and record blocks
/// reachable from the commit's data root are present in the CAR.
///
/// Use this for `com.atproto.sync.getRepo` responses without `since`. Do not
/// use it for intentional diff CARs, where unchanged referenced blocks are
/// legitimately absent.
fn loadCompleteCommitFromCAR(allocator: Allocator, car_bytes: []const u8) !LoadedCommitCar {
    const loaded = try loadCommitFromCAR(allocator, car_bytes);
    _ = try walkAndVerifyMst(allocator, loaded.repo_car, loaded.commit.data_cid, .{
        .require_record_blocks = true,
    });
    return loaded;
}

pub const VerifyCommitDiffOptions = struct {
    expected_did: ?[]const u8 = null,
    skip_inversion: bool = false,
    max_car_size: ?usize = null,
    max_blocks: ?usize = null,
};

pub const VerifyCommitDiffError = error{
    NoRootsInCar,
    CommitBlockNotFound,
    InvalidCommit,
    SignatureNotFound,
    SignatureVerificationFailed,
    MstRootMismatch,
    PrevDataMismatch,
    InversionMismatch,
    PartialTree,
    DuplicatePath,
    OutOfMemory,
    InvalidMstNode,
};

/// result of commit diff verification
pub const CommitDiffResult = struct {
    commit_did: []const u8,
    commit_rev: []const u8,
    commit_version: i64,
    commit_cid: []const u8,
    data_cid: []const u8,
};

/// verify a commit diff: parse CAR, verify signature, load partial MST,
/// invert operations, and verify the resulting root matches prev_data.
pub fn verifyCommitDiff(
    allocator: Allocator,
    blocks: []const u8,
    msg_ops: []const mst.Operation,
    prev_data: ?[]const u8,
    public_key: multicodec.PublicKey,
    options: VerifyCommitDiffOptions,
) VerifyCommitDiffError!CommitDiffResult {
    // 1. parse CAR + extract commit
    const loaded = loadCommitFromCAR(allocator, blocks) catch return error.InvalidCommit;
    const commit = loaded.commit;
    const repo_car = loaded.repo_car;

    // 2. verify commit structure
    if (commit.version != 3) return error.InvalidCommit;
    if (Did.parse(commit.did) == null) return error.InvalidCommit;

    // 3. check expected_did
    if (options.expected_did) |expected| {
        if (!std.mem.eql(u8, commit.did, expected)) return error.InvalidCommit;
    }

    // 4. verify signature (unsigned bytes pre-computed by loadCommitFromCAR)
    try verifySignatureBytes(loaded.unsigned_commit_bytes, commit.sig, public_key);

    // 5. if no prev_data or skip_inversion, we're done (first commit or lenient mode)
    if (prev_data == null or options.skip_inversion) {
        return .{
            .commit_did = commit.did,
            .commit_rev = commit.rev,
            .commit_version = commit.version,
            .commit_cid = loaded.commit_cid,
            .data_cid = commit.data_cid,
        };
    }

    // 6. load partial MST from CAR blocks
    var tree = mst.Mst.loadFromBlocks(allocator, repo_car, commit.data_cid) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        error.InvalidMstNode => return error.InvalidMstNode,
        else => return error.MstRootMismatch,
    };

    // 7. deep copy for inversion
    var inverted = tree.copy() catch return error.OutOfMemory;

    // 8. undo the original operation sequence, including repeated paths
    var remaining = msg_ops.len;
    while (remaining > 0) {
        remaining -= 1;
        const op = msg_ops[remaining];
        mst.invertOp(&inverted, op) catch |err| switch (err) {
            error.OutOfMemory, error.WriteFailed => return error.OutOfMemory,
            error.InversionMismatch => return error.InversionMismatch,
            error.PartialTree => return error.PartialTree,
            else => return error.InvalidMstNode,
        };
    }

    // 9. compute root CID of inverted tree
    const inverted_root = inverted.rootCid() catch |err| switch (err) {
        error.OutOfMemory, error.WriteFailed => return error.OutOfMemory,
        error.PartialTree => return error.PartialTree,
    };

    // 10. compare against prev_data
    if (!std.mem.eql(u8, inverted_root.raw, prev_data.?)) {
        return error.PrevDataMismatch;
    }

    return .{
        .commit_did = commit.did,
        .commit_rev = commit.rev,
        .commit_version = commit.version,
        .commit_cid = loaded.commit_cid,
        .data_cid = commit.data_cid,
    };
}

// === tests ===

test "verifyCommitDiff: signed repeated-path transitions retain intermediate checks" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const v1 = try cbor.Cid.forDagCbor(a, "v1");
    const v2 = try cbor.Cid.forDagCbor(a, "v2");
    const v3 = try cbor.Cid.forDagCbor(a, "v3");
    const keypair = try Keypair.fromSecretKey(.p256, @splat(7));
    const wrong_keypair = try Keypair.fromSecretKey(.p256, @splat(8));
    const did = try keypair.did(a);
    const pubkey = try keypair.publicKey();
    const wrong_pubkey = try wrong_keypair.publicKey();
    const key: multicodec.PublicKey = .{ .key_type = .p256, .raw = &pubkey };
    const path = "app.bsky.feed.post/test";
    const cases = [_]struct { initial: ?cbor.Cid, ops: []const mst.Operation }{
        .{ .initial = v1, .ops = &.{
            .{ .path = path, .value = v2.raw, .prev = v1.raw },
            .{ .path = path, .value = v3.raw, .prev = v2.raw },
        } },
        .{ .initial = v1, .ops = &.{
            .{ .path = path, .value = null, .prev = v1.raw },
            .{ .path = path, .value = v2.raw, .prev = null },
        } },
        .{ .initial = null, .ops = &.{
            .{ .path = path, .value = v1.raw, .prev = null },
            .{ .path = path, .value = null, .prev = v1.raw },
        } },
        .{ .initial = null, .ops = &.{
            .{ .path = path, .value = v1.raw, .prev = null },
            .{ .path = path, .value = v2.raw, .prev = v1.raw },
        } },
        .{ .initial = v1, .ops = &.{
            .{ .path = path, .value = v2.raw, .prev = v1.raw },
            .{ .path = path, .value = null, .prev = v2.raw },
        } },
    };
    for (cases) |case| {
        var tree = mst.Mst.init(a);
        if (case.initial) |initial| try tree.put(path, initial);
        const prev = try tree.rootCid();
        for (case.ops) |op| {
            if (op.value) |value| try tree.put(path, .{ .raw = value }) else try tree.delete(path);
        }
        const root = try tree.rootCid();
        const signed = try signCommit(a, .{ .did = did, .rev = "3k2abcdefghij", .data = root }, &keypair);
        var blocks: std.ArrayList(car.Block) = .empty;
        try blocks.append(a, .{ .cid_raw = signed.cid.raw, .data = signed.bytes });
        try tree.collectBlocks(&blocks);
        const bytes = try car.writeAlloc(a, .{ .roots = &.{signed.cid}, .blocks = blocks.items });
        _ = try verifyCommitDiff(a, bytes, case.ops, prev.raw, key, .{ .expected_did = did });
        const reversed = [_]mst.Operation{ case.ops[1], case.ops[0] };
        try std.testing.expectError(error.InversionMismatch, verifyCommitDiff(a, bytes, &reversed, prev.raw, key, .{}));
        var bad_ops = [_]mst.Operation{ case.ops[0], case.ops[1] };
        if (bad_ops[1].prev != null) bad_ops[1].prev = v3.raw else bad_ops[1].value = v3.raw;
        try std.testing.expectError(error.InversionMismatch, verifyCommitDiff(a, bytes, &bad_ops, prev.raw, key, .{}));
        const wrong_prev = try a.dupe(u8, prev.raw);
        wrong_prev[wrong_prev.len - 1] ^= 1;
        try std.testing.expectError(error.PrevDataMismatch, verifyCommitDiff(a, bytes, case.ops, wrong_prev, key, .{}));
        try std.testing.expectError(error.SignatureVerificationFailed, verifyCommitDiff(a, bytes, case.ops, prev.raw, .{ .key_type = .p256, .raw = &wrong_pubkey }, .{}));
    }
}

test "verifyCommitDiff: captured signed delete-create partial CARs" {
    for ([_][]const u8{ @embedFile("testdata/commit-proof-delete-create.cbor"), @embedFile("testdata/commit-proof-shadow-delete-create.cbor") }) |bytes| {
        var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
        defer arena.deinit();
        const a = arena.allocator();
        const packet = try cbor.decodeAll(a, bytes);
        const frame = packet.getBytes("frame").?;
        const header = try cbor.decode(a, frame);
        const payload = try cbor.decodeAll(a, frame[header.consumed..]);
        const ops = payload.getArray("ops").?;
        try std.testing.expectEqual(@as(usize, 2), ops.len);
        try std.testing.expectEqualStrings("delete", ops[0].getString("action").?);
        try std.testing.expectEqualStrings("create", ops[1].getString("action").?);
        try std.testing.expectEqualStrings(ops[0].getString("path").?, ops[1].getString("path").?);
        const parsed_ops = [_]mst.Operation{
            .{ .path = ops[0].getString("path").?, .value = null, .prev = ops[0].get("prev").?.cid.raw },
            .{ .path = ops[1].getString("path").?, .value = ops[1].get("cid").?.cid.raw, .prev = null },
        };
        const key: multicodec.PublicKey = .{
            .key_type = std.meta.stringToEnum(multicodec.KeyType, packet.getString("curve").?).?,
            .raw = packet.getBytes("key").?,
        };
        _ = try verifyCommitDiff(a, payload.getBytes("blocks").?, &parsed_ops, payload.get("prevData").?.cid.raw, key, .{ .expected_did = payload.getString("repo").? });
        const reversed = [_]mst.Operation{ parsed_ops[1], parsed_ops[0] };
        try std.testing.expectError(error.InversionMismatch, verifyCommitDiff(a, payload.getBytes("blocks").?, &reversed, payload.get("prevData").?.cid.raw, key, .{}));
    }
}

test "verifyCommitDiff: interop — real @atproto second commit inverts to prevData" {
    // Golden fixture from @atproto/repo, not from our own encoder: the CAR holds
    // only newBlocks + relevantBlocks, so the deleted key's subtree is the sole
    // occupant of its node. A self-built fixture that ships the whole tree, or
    // that inverts an update instead of a create, does not exercise this.
    const fixture_json = @embedFile("testdata/atproto-commit-proof.json");

    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const Fixture = struct {
        signingKey: []const u8,
        prevDataCid: []const u8,
        dataCid: []const u8,
        ops: []const struct {
            action: []const u8,
            path: []const u8,
            cid: []const u8,
        },
        carHex: []const u8,
    };
    const parsed = try std.json.parseFromSlice(Fixture, a, fixture_json, .{ .ignore_unknown_fields = true });
    defer parsed.deinit();
    const fixture = parsed.value;

    const car_bytes = try a.alloc(u8, fixture.carHex.len / 2);
    _ = try std.fmt.hexToBytes(car_bytes, fixture.carHex);

    const did_key_prefix = "did:key:";
    try std.testing.expect(std.mem.startsWith(u8, fixture.signingKey, did_key_prefix));
    const key_bytes = try multibase.decode(a, fixture.signingKey[did_key_prefix.len..]);
    const public_key = try multicodec.parsePublicKey(key_bytes);

    var ops: std.ArrayListUnmanaged(mst.Operation) = .empty;
    for (fixture.ops) |op| {
        try std.testing.expectEqualStrings("create", op.action);
        const value = try mst.parseCidString(a, op.cid);
        try ops.append(a, .{ .path = op.path, .value = value.raw, .prev = null });
    }

    const prev_data = try mst.parseCidString(a, fixture.prevDataCid);
    const result = try verifyCommitDiff(a, car_bytes, ops.items, prev_data.raw, public_key, .{});

    const expected_data = try mst.parseCidString(a, fixture.dataCid);
    try std.testing.expectEqualSlices(u8, expected_data.raw, result.data_cid);
}

test "verifyCommitDiff: build tree, serialize partial CAR, verify inversion" {
    // this test constructs a tree, applies ops, builds a partial CAR
    // with the commit + changed MST nodes, and verifies the diff
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const cid1 = try cbor.Cid.forDagCbor(a, "record1");
    const cid2 = try cbor.Cid.forDagCbor(a, "record2");
    const cid3 = try cbor.Cid.forDagCbor(a, "record3");

    // build "before" tree
    var before_tree = mst.Mst.init(a);
    try before_tree.put("col/existing", cid1);
    try before_tree.put("col/to_update", cid1);
    try before_tree.put("col/to_delete", cid2);
    const prev_data_cid = try before_tree.rootCid();

    // build "after" tree (apply ops forward)
    var after_tree = try before_tree.copy();
    try after_tree.put("col/new_record", cid3); // create
    try after_tree.put("col/to_update", cid2); // update
    try after_tree.delete("col/to_delete"); // delete
    const new_data_cid = try after_tree.rootCid();

    // verify inversion works at the MST level
    var inverted = try after_tree.copy();
    const ops = [_]mst.Operation{
        .{ .path = "col/new_record", .value = cid3.raw, .prev = null },
        .{ .path = "col/to_update", .value = cid2.raw, .prev = cid1.raw },
        .{ .path = "col/to_delete", .value = null, .prev = cid2.raw },
    };
    const sorted = try mst.normalizeOps(a, &ops);
    for (sorted) |op| {
        try mst.invertOp(&inverted, op);
    }
    const inverted_root = try inverted.rootCid();
    try std.testing.expectEqualSlices(u8, prev_data_cid.raw, inverted_root.raw);

    // also verify the after tree has the expected new root
    try std.testing.expect(!std.mem.eql(u8, prev_data_cid.raw, new_data_cid.raw));
}

test "signCommit round-trips through verifyCommitCar" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // real MST root so verify_mst walks a genuine tree
    var tree = mst.Mst.init(a);
    try tree.put("app.bsky.feed.post/3k2abcdefghij", try cbor.Cid.forDagCbor(a, "record1"));
    try tree.put("app.bsky.feed.post/3k2abcdefghik", try cbor.Cid.forDagCbor(a, "record2"));
    const data_cid = try tree.rootCid();

    const keypair = try Keypair.fromSecretKey(.p256, @splat(7));
    const did = try keypair.did(a);

    const signed = try signCommit(a, .{
        .did = did,
        .rev = "3k2abcdefghij",
        .data = data_cid,
    }, &keypair);

    // assemble a full-repo CAR: commit root + all MST blocks
    var blocks: std.ArrayList(car.Block) = .empty;
    try blocks.append(a, .{ .cid_raw = signed.cid.raw, .data = signed.bytes });
    try tree.collectBlocks(&blocks);
    const car_bytes = try car.writeAlloc(a, .{
        .roots = &.{signed.cid},
        .blocks = blocks.items,
    });

    const pubkey = try keypair.publicKey();
    const result = try verifyCommitCar(a, car_bytes, .{ .key_type = .p256, .raw = &pubkey }, .{
        .expected_did = did,
    });
    try std.testing.expectEqualStrings(did, result.commit_did);
    try std.testing.expectEqual(@as(i64, 3), result.commit_version);
    try std.testing.expectEqualStrings("3k2abcdefghij", result.commit_rev);
}

test "signCommit rev change produces a different signature and CID" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const keypair = try Keypair.fromSecretKey(.p256, @splat(9));
    const did = try keypair.did(a);
    const data_cid = try cbor.Cid.forDagCbor(a, "mst-root");

    const first = try signCommit(a, .{ .did = did, .rev = "3k2aaaaaaaaaa", .data = data_cid }, &keypair);
    const second = try signCommit(a, .{ .did = did, .rev = "3k2bbbbbbbbbb", .data = data_cid, .prev = first.cid }, &keypair);

    try std.testing.expect(!std.mem.eql(u8, first.cid.raw, second.cid.raw));
    try std.testing.expect(!std.mem.eql(u8, first.bytes, second.bytes));
}

test "loadCommitFromCAR extracts commit fields" {
    // build a minimal valid commit CAR
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const data_cid = try cbor.Cid.forDagCbor(a, "mst-root-placeholder");

    // build commit CBOR
    const commit_value: cbor.Value = .{ .map = &.{
        .{ .key = "data", .value = .{ .cid = data_cid } },
        .{ .key = "did", .value = .{ .text = "did:plc:test123" } },
        .{ .key = "rev", .value = .{ .text = "3k2abc000000" } },
        .{ .key = "sig", .value = .{ .bytes = "fakesig" } },
        .{ .key = "version", .value = .{ .unsigned = 3 } },
    } };
    const commit_bytes = try cbor.encodeAlloc(a, commit_value);
    const commit_cid = try cbor.Cid.forDagCbor(a, commit_bytes);

    // build CAR with commit block
    const car_data = car.Car{
        .roots = &.{commit_cid},
        .blocks = &.{
            .{ .cid_raw = commit_cid.raw, .data = commit_bytes },
        },
    };
    const car_bytes = try car.writeAlloc(a, car_data);

    // parse it back
    const loaded = try loadCommitFromCAR(a, car_bytes);
    try std.testing.expectEqualStrings("did:plc:test123", loaded.commit.did);
    try std.testing.expectEqualStrings("3k2abc000000", loaded.commit.rev);
    try std.testing.expectEqual(@as(i64, 3), loaded.commit.version);
    try std.testing.expectEqualSlices(u8, data_cid.raw, loaded.commit.data_cid);
    try std.testing.expect(loaded.commit.prev == null);
}

test "loadCommitFromCARWithOptions reads a CAR past the default block limit" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const data_cid = try cbor.Cid.forDagCbor(a, "mst-root-placeholder");
    const commit_bytes = try cbor.encodeAlloc(a, .{ .map = &.{
        .{ .key = "data", .value = .{ .cid = data_cid } },
        .{ .key = "did", .value = .{ .text = "did:plc:test123" } },
        .{ .key = "rev", .value = .{ .text = "3k2abc000000" } },
        .{ .key = "sig", .value = .{ .bytes = "fakesig" } },
        .{ .key = "version", .value = .{ .unsigned = 3 } },
    } });
    const commit_cid = try cbor.Cid.forDagCbor(a, commit_bytes);

    const block_count = 10_001;
    const blocks = try a.alloc(car.Block, block_count);
    blocks[0] = .{ .cid_raw = commit_cid.raw, .data = commit_bytes };
    for (blocks[1..], 1..) |*block, i| {
        const data = try cbor.encodeAlloc(a, .{ .unsigned = i });
        block.* = .{ .cid_raw = (try cbor.Cid.forDagCbor(a, data)).raw, .data = data };
    }
    const car_bytes = try car.writeAlloc(a, .{ .roots = &.{commit_cid}, .blocks = blocks });

    try std.testing.expectError(error.InvalidCommit, loadCommitFromCAR(a, car_bytes));
    const loaded = try loadCommitFromCARWithOptions(a, car_bytes, .{ .max_size = car_bytes.len, .max_blocks = block_count });
    try std.testing.expectEqualStrings("did:plc:test123", loaded.commit.did);
    try std.testing.expectEqual(@as(usize, block_count), loaded.repo_car.blocks.len);
}

const CompleteCarFixture = struct {
    car_bytes: []const u8,
    commit_cid: cbor.Cid,
    root_cid: cbor.Cid,
    record_cids: []const cbor.Cid,
    mst_blocks: []const car.Block,
};

fn buildCompleteCarFixture(allocator: Allocator, record_count: usize) !CompleteCarFixture {
    var tree = mst.Mst.init(allocator);
    var record_cids: std.ArrayList(cbor.Cid) = .empty;

    for (0..record_count) |i| {
        const record = try std.fmt.allocPrint(allocator, "record-{d}", .{i});
        const record_cid = try cbor.Cid.forDagCbor(allocator, record);
        try record_cids.append(allocator, record_cid);

        const path = try std.fmt.allocPrint(allocator, "app.bsky.feed.post/{d:0>13}", .{i});
        try tree.put(path, record_cid);
    }

    const root_cid = try tree.rootCid();
    var mst_blocks: std.ArrayList(car.Block) = .empty;
    try tree.collectBlocks(&mst_blocks);

    const commit_value: cbor.Value = .{ .map = &.{
        .{ .key = "data", .value = .{ .cid = root_cid } },
        .{ .key = "did", .value = .{ .text = "did:plc:test123" } },
        .{ .key = "rev", .value = .{ .text = "3k2abc000000" } },
        .{ .key = "sig", .value = .{ .bytes = "fakesig" } },
        .{ .key = "version", .value = .{ .unsigned = 3 } },
    } };
    const commit_bytes = try cbor.encodeAlloc(allocator, commit_value);
    const commit_cid = try cbor.Cid.forDagCbor(allocator, commit_bytes);

    var blocks: std.ArrayList(car.Block) = .empty;
    try blocks.append(allocator, .{ .cid_raw = commit_cid.raw, .data = commit_bytes });
    for (mst_blocks.items) |block| try blocks.append(allocator, block);
    for (record_cids.items, 0..) |record_cid, i| {
        const record = try std.fmt.allocPrint(allocator, "record-{d}", .{i});
        try blocks.append(allocator, .{ .cid_raw = record_cid.raw, .data = record });
    }

    const car_bytes = try car.writeAlloc(allocator, .{
        .roots = &.{commit_cid},
        .blocks = blocks.items,
    });

    return .{
        .car_bytes = car_bytes,
        .commit_cid = commit_cid,
        .root_cid = root_cid,
        .record_cids = try record_cids.toOwnedSlice(allocator),
        .mst_blocks = try mst_blocks.toOwnedSlice(allocator),
    };
}

fn writeCarWithoutBlock(
    allocator: Allocator,
    fixture: CompleteCarFixture,
    missing_cid: []const u8,
) ![]const u8 {
    const loaded = try car.readWithOptions(allocator, fixture.car_bytes, .{
        .max_size = fixture.car_bytes.len,
        .max_blocks = fixture.car_bytes.len,
    });

    var blocks: std.ArrayList(car.Block) = .empty;
    for (loaded.blocks) |block| {
        if (std.mem.eql(u8, block.cid_raw, missing_cid)) continue;
        try blocks.append(allocator, block);
    }
    return car.writeAlloc(allocator, .{
        .roots = loaded.roots,
        .blocks = blocks.items,
    });
}

test "loadCompleteCommitFromCAR accepts complete full repo" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const fixture = try buildCompleteCarFixture(a, 4);
    const loaded = try loadCompleteCommitFromCAR(a, fixture.car_bytes);

    try std.testing.expectEqualSlices(u8, fixture.commit_cid.raw, loaded.commit_cid);
    try std.testing.expectEqualSlices(u8, fixture.root_cid.raw, loaded.commit.data_cid);
}

test "loadCompleteCommitFromCAR rejects missing record block" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const fixture = try buildCompleteCarFixture(a, 4);
    const partial = try writeCarWithoutBlock(a, fixture, fixture.record_cids[0].raw);

    _ = try loadCommitFromCAR(a, partial);
    try std.testing.expectError(error.IncompleteRepo, loadCompleteCommitFromCAR(a, partial));
}

test "loadCompleteCommitFromCAR rejects missing interior MST block" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const fixture = try buildCompleteCarFixture(a, 120);
    var missing: ?[]const u8 = null;
    for (fixture.mst_blocks) |block| {
        if (!std.mem.eql(u8, block.cid_raw, fixture.root_cid.raw)) {
            missing = block.cid_raw;
            break;
        }
    }
    try std.testing.expect(missing != null);

    const partial = try writeCarWithoutBlock(a, fixture, missing.?);
    _ = try loadCommitFromCAR(a, partial);
    try std.testing.expectError(error.IncompleteRepo, loadCompleteCommitFromCAR(a, partial));
}

test "loadCompleteCommitFromCAR catches block-boundary truncation" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const fixture = try buildCompleteCarFixture(a, 12);
    var found_boundary_cut = false;

    for (1..fixture.car_bytes.len) |n| {
        const prefix = fixture.car_bytes[0..n];
        _ = loadCommitFromCAR(a, prefix) catch continue;

        if (loadCompleteCommitFromCAR(a, prefix)) |_| {
            continue;
        } else |err| {
            try std.testing.expectEqual(error.IncompleteRepo, err);
            found_boundary_cut = true;
            break;
        }
    }

    try std.testing.expect(found_boundary_cut);
}

test "verifyCommitDiff is semantically analyzed (error-set exhaustiveness)" {
    // forces full body analysis so a non-exhaustive error switch (e.g. the
    // invertOp catch) is caught here rather than only in a downstream consumer.
    _ = &verifyCommitDiff;
}