//! CAR v1 codec (Content Addressable aRchive) //! //! read and write CAR v1 files used in AT Protocol firehose commit events. //! the `blocks` field of a #commit payload is a CAR file containing //! the signed commit, MST nodes, and record data. //! //! format: [varint header_len] [DAG-CBOR header] [varint block_len] [CID] [data] ... //! //! see: https://ipld.io/specs/transport/car/carv1/ const std = @import("std"); const cbor = @import("cbor.zig"); const Allocator = std.mem.Allocator; /// a single block from a CAR file pub const Block = struct { cid_raw: []const u8, // raw CID bytes (for matching against op CIDs) data: []const u8, // block content (DAG-CBOR encoded) }; /// parsed CAR file pub const Car = struct { roots: []const cbor.Cid, blocks: []const Block, /// CID bytes → block data for O(1) lookup. built by read/readWithOptions. /// empty for manually-constructed Cars (findBlock falls back to linear scan). block_index: std.StringHashMapUnmanaged([]const u8) = .empty, const toEphemeral = EphemeralCar.initCar; }; pub const CarError = error{ InvalidHeader, InvalidVarint, InvalidCid, UnexpectedEof, OutOfMemory, BadBlockHash, BlocksTooLarge, TooManyBlocks, BlockTooLarge, }; /// match indigo's safety limits const max_blocks_size: usize = 2 * 1024 * 1024; // 2 MB const max_block_count: usize = 10_000; const max_block_size: usize = 1024 * 1024; // 1 MB per block (matches atmos) pub const ReadOptions = struct { /// verify that each block's content hashes to its CID. /// this is the correct behavior for untrusted data (e.g. from the network). /// set to false only for trusted local data where you want raw decode speed. verify_block_hashes: bool = true, /// max total CAR size in bytes. null = use default (2 MB). max_size: ?usize = null, /// max number of blocks. null = use default (10,000). max_blocks: ?usize = null, }; /// parse a CAR v1 file from raw bytes pub fn read(allocator: Allocator, data: []const u8) CarError!Car { return readWithOptions(allocator, data, .{}); } /// parse a CAR v1 file from raw bytes with options pub fn readWithOptions(allocator: Allocator, data: []const u8, options: ReadOptions) CarError!Car { if (data.len > (options.max_size orelse max_blocks_size)) return error.BlocksTooLarge; var pos: usize = 0; // read header length (unsigned varint) const header_len = cbor.readUvarint(data, &pos) orelse return error.InvalidVarint; const header_len_usize = std.math.cast(usize, header_len) orelse return error.InvalidHeader; const header_end = pos + header_len_usize; if (header_end > data.len) return error.UnexpectedEof; // decode header using a temporary arena (the header's Value tree is only // needed to extract version + roots, then discarded). this avoids leaking // the header's CBOR allocations if a later allocation fails. var header_arena = std.heap.ArenaAllocator.init(allocator); defer header_arena.deinit(); const header_bytes = data[pos..header_end]; const header = cbor.decodeAll(header_arena.allocator(), header_bytes) catch |err| switch (err) { // Exhaustion is ours, not the file's. Callers retire a repository // permanently on InvalidHeader, so an OOM reported as one loses good // data and blames the remote. error.OutOfMemory => return error.OutOfMemory, else => return error.InvalidHeader, }; // validate version == 1 const version = header.getUint("version") orelse return error.InvalidHeader; if (version != 1) return error.InvalidHeader; // extract roots (array of CID links) — CAR v1 requires at least one root. // CID.raw slices point into the input `data` (zero-copy), so they outlive // the header arena. var roots: std.ArrayList(cbor.Cid) = .empty; errdefer roots.deinit(allocator); const root_values = header.getArray("roots") orelse return error.InvalidHeader; for (root_values) |root_val| { switch (root_val) { .cid => |c| try roots.append(allocator, c), else => return error.InvalidHeader, // roots must all be CID links } } if (roots.items.len == 0) return error.InvalidHeader; pos = header_end; // read blocks var blocks: std.ArrayList(Block) = .empty; errdefer blocks.deinit(allocator); var block_index: std.StringHashMapUnmanaged([]const u8) = .empty; errdefer block_index.deinit(allocator); while (pos < data.len) { // block: [varint total_len] [CID bytes] [data bytes] // total_len includes both CID and data const block_len = cbor.readUvarint(data, &pos) orelse return error.InvalidVarint; const block_len_usize = std.math.cast(usize, block_len) orelse return error.InvalidHeader; if (block_len_usize == 0) return error.InvalidCid; // zero-length block has no CID if (block_len_usize > max_block_size) return error.BlockTooLarge; const block_end = pos + block_len_usize; if (block_end > data.len) return error.UnexpectedEof; const block_data = data[pos..block_end]; // parse CID to determine its length, then the rest is block content const cid_len = cidLength(block_data) orelse return error.InvalidCid; if (cid_len > block_data.len) return error.InvalidCid; const cid_bytes = block_data[0..cid_len]; const content = block_data[cid_len..]; if (options.verify_block_hashes) { try verifyBlockHash(cid_bytes, content); } if (blocks.items.len >= (options.max_blocks orelse max_block_count)) return error.TooManyBlocks; try blocks.append(allocator, .{ .cid_raw = cid_bytes, .data = content, }); try block_index.put(allocator, cid_bytes, content); pos = block_end; } return .{ .roots = try roots.toOwnedSlice(allocator), .blocks = try blocks.toOwnedSlice(allocator), .block_index = block_index, }; } // === streaming iterator === /// a single block yielded by BlockIterator. slices borrow from the input /// buffer and stay valid for the iterator's entire lifetime (the iterator /// never overwrites input data). pub const BlockEntry = struct { cid_raw: []const u8, data: []const u8, }; /// pull-style iterator over CAR blocks. yields one block per `next()` call /// and does zero allocation in the hot path — no hashmap, no block list. /// caller picks what to remember (CID → offset index, MST nodes only, etc.). /// /// blocks are slices into the original input buffer, so this is strictly /// cheaper than `read()` for streaming walks where random access isn't /// required upfront. pub const BlockIterator = struct { data: []const u8, pos: usize, verify: bool, max_per_block: usize, pub fn next(self: *BlockIterator) CarError!?BlockEntry { if (self.pos >= self.data.len) return null; const block_len = cbor.readUvarint(self.data, &self.pos) orelse return error.InvalidVarint; const block_len_usize = std.math.cast(usize, block_len) orelse return error.InvalidHeader; if (block_len_usize == 0) return error.InvalidCid; if (block_len_usize > self.max_per_block) return error.BlockTooLarge; const block_end = self.pos + block_len_usize; if (block_end > self.data.len) return error.UnexpectedEof; const block_data = self.data[self.pos..block_end]; const cid_len = cidLength(block_data) orelse return error.InvalidCid; if (cid_len > block_data.len) return error.InvalidCid; const cid_bytes = block_data[0..cid_len]; const content = block_data[cid_len..]; if (self.verify) try verifyBlockHash(cid_bytes, content); self.pos = block_end; return .{ .cid_raw = cid_bytes, .data = content }; } /// byte offset within the original input of the next block to be read. /// useful for building a CID → offset index while iterating. pub fn offset(self: BlockIterator) usize { return self.pos; } }; pub const StreamOptions = struct { verify_block_hashes: bool = true, /// max total CAR size in bytes. null = use default (2 MB). for a /// trusted response you fetched yourself, pass `data.len` to disable. max_size: ?usize = null, /// max size of any single block. null = use default (1 MB). max_block_size: ?usize = null, }; pub const StreamResult = struct { roots: []const cbor.Cid, iter: BlockIterator, }; /// parse only the CAR header and return an iterator over the remaining /// blocks. unlike `read`, this does not build a hashmap or collect a /// `Block[]` — it's O(1) space beyond the input buffer. zero-copy: the /// iterator yields slices into `data`. /// /// the caller owns `result.roots` (backed by `allocator`) and should free /// it via `allocator.free(result.roots)` when done. the iterator itself /// holds no allocations. pub fn streamBlocks(allocator: Allocator, data: []const u8, options: StreamOptions) CarError!StreamResult { if (data.len > (options.max_size orelse max_blocks_size)) return error.BlocksTooLarge; var pos: usize = 0; const header_len = cbor.readUvarint(data, &pos) orelse return error.InvalidVarint; const header_len_usize = std.math.cast(usize, header_len) orelse return error.InvalidHeader; const header_end = pos + header_len_usize; if (header_end > data.len) return error.UnexpectedEof; // decode header into a throwaway arena — we only need the roots array, // which we deep-copy (via cbor.Cid.raw slices pointing into `data`). var header_arena = std.heap.ArenaAllocator.init(allocator); defer header_arena.deinit(); const header = cbor.decodeAll(header_arena.allocator(), data[pos..header_end]) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.InvalidHeader, }; const version = header.getUint("version") orelse return error.InvalidHeader; if (version != 1) return error.InvalidHeader; var roots: std.ArrayList(cbor.Cid) = .empty; errdefer roots.deinit(allocator); const root_values = header.getArray("roots") orelse return error.InvalidHeader; for (root_values) |root_val| { switch (root_val) { .cid => |c| try roots.append(allocator, c), else => return error.InvalidHeader, } } if (roots.items.len == 0) return error.InvalidHeader; return .{ .roots = try roots.toOwnedSlice(allocator), .iter = .{ .data = data, .pos = header_end, .verify = options.verify_block_hashes, .max_per_block = options.max_block_size orelse max_block_size, }, }; } /// verify block content against its full CID. structure is checked /// strictly (atmos parity): CIDv0 must be exactly the 34-byte sha2-256 /// multihash; CIDv1 must declare version 1 and its digest must end the /// CID exactly (no trailing bytes). sha2-256 digests are recomputed and /// compared; identity digests must equal the content byte-for-byte. /// codec is not restricted — any parseable codec is accepted. fn verifyBlockHash(cid_bytes: []const u8, content: []const u8) CarError!void { const Sha256 = std.crypto.hash.sha2.Sha256; if (cid_bytes.len < 2) return error.InvalidCid; // CIDv0: bare sha2-256 multihash, fixed 34-byte layout if (cid_bytes[0] == 0x12 and cid_bytes[1] == 0x20) { if (cid_bytes.len != 34) return error.InvalidCid; var computed: [Sha256.digest_length]u8 = undefined; Sha256.hash(content, &computed, .{}); if (!std.mem.eql(u8, cid_bytes[2..34], &computed)) return error.BadBlockHash; return; } var pos: usize = 0; const version = cbor.readUvarint(cid_bytes, &pos) orelse return error.InvalidCid; if (version != 1) return error.InvalidCid; _ = cbor.readUvarint(cid_bytes, &pos) orelse return error.InvalidCid; // codec const hash_fn = cbor.readUvarint(cid_bytes, &pos) orelse return error.InvalidCid; const digest_len = cbor.readUvarint(cid_bytes, &pos) orelse return error.InvalidCid; const digest_len_usize = std.math.cast(usize, digest_len) orelse return error.InvalidCid; if (cid_bytes.len - pos != digest_len_usize) return error.InvalidCid; const digest = cid_bytes[pos..]; switch (hash_fn) { cbor.HashFn.identity => { if (!std.mem.eql(u8, digest, content)) return error.BadBlockHash; }, cbor.HashFn.sha2_256 => { if (digest.len != Sha256.digest_length) return error.BadBlockHash; var computed: [Sha256.digest_length]u8 = undefined; Sha256.hash(content, &computed, .{}); if (!std.mem.eql(u8, digest, &computed)) return error.BadBlockHash; }, else => return error.BadBlockHash, } } /// determine the byte length of a CID at the start of data fn cidLength(data: []const u8) ?usize { if (data.len < 2) return null; // CIDv0: starts with 0x12 0x20 (sha2-256 multihash, 32 byte digest) if (data[0] == 0x12 and data[1] == 0x20) { return 34; // 1 + 1 + 32 } // CIDv1: version varint + codec varint + multihash (hash_fn varint + digest_len varint + digest) var pos: usize = 0; _ = cbor.readUvarint(data, &pos) orelse return null; // version _ = cbor.readUvarint(data, &pos) orelse return null; // codec _ = cbor.readUvarint(data, &pos) orelse return null; // hash function const digest_len = cbor.readUvarint(data, &pos) orelse return null; const digest_len_usize = std.math.cast(usize, digest_len) orelse return null; return pos + digest_len_usize; } /// find a block by matching CID bytes. /// uses the hash index when available (O(1)), falls back to linear scan for /// manually-constructed Cars without an index. pub fn findBlock(c: Car, cid_raw: []const u8) ?[]const u8 { if (c.block_index.count() > 0) return c.block_index.get(cid_raw); for (c.blocks) |block| { if (std.mem.eql(u8, block.cid_raw, cid_raw)) return block.data; } return null; } // === writer === /// write a CAR v1 file to the given writer. /// produces: [varint header_len] [DAG-CBOR header] [blocks...] /// where each block is: [varint block_len] [CID bytes] [data bytes] pub fn write(allocator: Allocator, writer: *std.Io.Writer, c: Car) !void { try c.toEphemeral().write(allocator, writer); } /// write a CAR v1 file to a freshly allocated byte slice pub fn writeAlloc(allocator: Allocator, c: Car) ![]u8 { return c.toEphemeral().writeAlloc(allocator); } const EphemeralCar = struct { roots: []const cbor.Cid, blocks: []const []const Block, fn initCar(c: *const Car) @This() { return .{ .roots = c.roots, .blocks = (&c.blocks)[0..1], }; } fn write(self: @This(), allocator: Allocator, writer: *std.Io.Writer) !void { // build header: {"roots": [...CID links...], "version": 1} const root_values = try allocator.alloc(cbor.Value, self.roots.len); defer allocator.free(root_values); for (self.roots, root_values) |root, *root_value| root_value.* = .{ .cid = root }; const header_value: cbor.Value = .{ .map = &.{ .{ .key = "roots", .value = .{ .array = root_values } }, .{ .key = "version", .value = .{ .unsigned = 1 } }, }, }; // encode header to bytes const header_bytes = try cbor.encodeAlloc(allocator, header_value); defer allocator.free(header_bytes); // write header length + header try cbor.writeUvarint(writer, header_bytes.len); try writer.writeAll(header_bytes); // write blocks for (self.blocks) |blocks| for (blocks) |block| { const block_len = block.cid_raw.len + block.data.len; try cbor.writeUvarint(writer, block_len); try writer.writeAll(block.cid_raw); try writer.writeAll(block.data); }; } fn writeAlloc( self: @This(), allocator: Allocator, ) Allocator.Error![]u8 { var aw: std.Io.Writer.Allocating = .init(allocator); errdefer aw.deinit(); // The sink is memory, so the writer's only failure mode is allocation. // std.Io.Writer reports that as WriteFailed, which reads to callers as a // problem with the data rather than with us -- and callers retire a source // permanently on a structural verdict. self.write(allocator, &aw.writer) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, else => return @errorCast(err), }; return aw.toOwnedSlice(); } }; pub fn writeEphemeral( allocator: Allocator, writer: *std.Io.Writer, c: EphemeralCar, ) (Allocator.Error || std.Io.Writer.Error)!void { return c.write(allocator, writer); } pub fn writeEphemeralAlloc( allocator: Allocator, c: EphemeralCar, ) Allocator.Error![]u8 { return c.writeAlloc(allocator); } // === tests === test "cidLength CIDv0" { // sha2-256 multihash: 0x12 0x20 + 32 bytes var data: [34]u8 = undefined; data[0] = 0x12; data[1] = 0x20; @memset(data[2..], 0xaa); try std.testing.expectEqual(@as(?usize, 34), cidLength(&data)); } test "cidLength CIDv1" { // CIDv1: version=1, codec=0x71 (dag-cbor), sha2-256 (0x12), 32-byte digest const data = [_]u8{ 0x01, // version varint 0x71, // codec varint (dag-cbor) 0x12, // hash fn varint (sha2-256) 0x20, // digest len varint (32) } ++ @as([32]u8, @splat(0xaa)); try std.testing.expectEqual(@as(?usize, 36), cidLength(&data)); } test "read minimal CAR" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); // create a block and compute its real CID const block_content = try cbor.encodeAlloc(alloc, .{ .map = &.{ .{ .key = "text", .value = .{ .text = "hi" } }, } }); const block_cid = try cbor.Cid.forDagCbor(alloc, block_content); // write a proper CAR via the writer, then read it back const original = Car{ .roots = &.{block_cid}, .blocks = &.{.{ .cid_raw = block_cid.raw, .data = block_content }}, }; const car_bytes = try writeAlloc(alloc, original); const car_file = try read(alloc, car_bytes); try std.testing.expectEqual(@as(usize, 1), car_file.roots.len); try std.testing.expectEqual(@as(usize, 1), car_file.blocks.len); // decode the block content as CBOR const val = try cbor.decodeAll(alloc, car_file.blocks[0].data); try std.testing.expectEqualStrings("hi", val.getString("text").?); } test "read CAR with roots" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); // create a CID to use as a root const root_cid = try cbor.Cid.forDagCbor(alloc, "root block data"); // build header with a root: {"roots": [CID], "version": 1} const header_value: cbor.Value = .{ .map = &.{ .{ .key = "roots", .value = .{ .array = &.{.{ .cid = root_cid }} } }, .{ .key = "version", .value = .{ .unsigned = 1 } }, } }; const header_bytes = try cbor.encodeAlloc(alloc, header_value); // assemble minimal CAR: header only, no blocks var car_aw: std.Io.Writer.Allocating = .init(alloc); defer car_aw.deinit(); try cbor.writeUvarint(&car_aw.writer, header_bytes.len); try car_aw.writer.writeAll(header_bytes); const car_file = try read(alloc, car_aw.written()); try std.testing.expectEqual(@as(usize, 1), car_file.roots.len); try std.testing.expectEqual(root_cid.version().?, car_file.roots[0].version().?); try std.testing.expectEqual(root_cid.codec().?, car_file.roots[0].codec().?); try std.testing.expectEqualSlices(u8, root_cid.digest().?, car_file.roots[0].digest().?); } test "write → read round-trip" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); // create some blocks const block1_data = "block one data"; const block2_data = "block two data"; const cid1 = try cbor.Cid.forDagCbor(alloc, block1_data); const cid2 = try cbor.Cid.forDagCbor(alloc, block2_data); const original = Car{ .roots = &.{cid1}, .blocks = &.{ .{ .cid_raw = cid1.raw, .data = block1_data }, .{ .cid_raw = cid2.raw, .data = block2_data }, }, }; // write then read const car_bytes = try writeAlloc(alloc, original); const parsed = try read(alloc, car_bytes); // verify roots try std.testing.expectEqual(@as(usize, 1), parsed.roots.len); try std.testing.expectEqualSlices(u8, cid1.digest().?, parsed.roots[0].digest().?); // verify blocks try std.testing.expectEqual(@as(usize, 2), parsed.blocks.len); try std.testing.expectEqualSlices(u8, block1_data, parsed.blocks[0].data); try std.testing.expectEqualSlices(u8, block2_data, parsed.blocks[1].data); // verify CID matching try std.testing.expectEqualSlices(u8, cid1.raw, parsed.blocks[0].cid_raw); try std.testing.expectEqualSlices(u8, cid2.raw, parsed.blocks[1].cid_raw); } test "write → read round-trip with CBOR block content" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); // encode a record as DAG-CBOR const record: cbor.Value = .{ .map = &.{ .{ .key = "$type", .value = .{ .text = "app.bsky.feed.post" } }, .{ .key = "text", .value = .{ .text = "hello from CAR writer" } }, } }; const record_bytes = try cbor.encodeAlloc(alloc, record); const cid = try cbor.Cid.forDagCbor(alloc, record_bytes); const original = Car{ .roots = &.{cid}, .blocks = &.{ .{ .cid_raw = cid.raw, .data = record_bytes }, }, }; const car_bytes = try writeAlloc(alloc, original); const parsed = try read(alloc, car_bytes); // find the block by CID and decode it const found = findBlock(parsed, cid.raw).?; const decoded = try cbor.decodeAll(alloc, found); try std.testing.expectEqualStrings("hello from CAR writer", decoded.getString("text").?); try std.testing.expectEqualStrings("app.bsky.feed.post", decoded.getString("$type").?); } test "read rejects block with bad hash" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); // create a valid CAR, then corrupt the block content const record_bytes = try cbor.encodeAlloc(alloc, .{ .map = &.{ .{ .key = "text", .value = .{ .text = "original" } }, } }); const cid = try cbor.Cid.forDagCbor(alloc, record_bytes); // write a CAR with the correct CID but wrong data const tampered_data = "tampered"; const tampered_car = Car{ .roots = &.{cid}, .blocks = &.{ .{ .cid_raw = cid.raw, .data = tampered_data }, }, }; const car_bytes = try writeAlloc(alloc, tampered_car); // should fail with verification on (default) try std.testing.expectError(error.BadBlockHash, read(alloc, car_bytes)); // should succeed with verification off const parsed = try readWithOptions(alloc, car_bytes, .{ .verify_block_hashes = false }); try std.testing.expectEqual(@as(usize, 1), parsed.blocks.len); } test "findBlock returns null for missing CID" { const c = Car{ .roots = &.{}, .blocks = &.{} }; try std.testing.expect(findBlock(c, "nonexistent") == null); } test "streamBlocks matches read output" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); // build a CAR with a handful of real DAG-CBOR blocks so the iterator has // something non-trivial to chew on const b1 = try cbor.encodeAlloc(alloc, .{ .map = &.{.{ .key = "k", .value = .{ .text = "v1" } }} }); const b2 = try cbor.encodeAlloc(alloc, .{ .map = &.{.{ .key = "k", .value = .{ .text = "v2" } }} }); const b3 = try cbor.encodeAlloc(alloc, .{ .map = &.{.{ .key = "k", .value = .{ .text = "v3" } }} }); const c1 = try cbor.Cid.forDagCbor(alloc, b1); const c2 = try cbor.Cid.forDagCbor(alloc, b2); const c3 = try cbor.Cid.forDagCbor(alloc, b3); const src = Car{ .roots = &.{c1}, .blocks = &.{ .{ .cid_raw = c1.raw, .data = b1 }, .{ .cid_raw = c2.raw, .data = b2 }, .{ .cid_raw = c3.raw, .data = b3 }, }, }; const car_bytes = try writeAlloc(alloc, src); // reference: full read const parsed = try read(alloc, car_bytes); // streaming: should see every block in order, with identical bytes var stream = try streamBlocks(alloc, car_bytes, .{}); defer alloc.free(stream.roots); try std.testing.expectEqual(@as(usize, 1), stream.roots.len); try std.testing.expectEqualSlices(u8, parsed.roots[0].raw, stream.roots[0].raw); var i: usize = 0; while (try stream.iter.next()) |block| : (i += 1) { try std.testing.expect(i < parsed.blocks.len); try std.testing.expectEqualSlices(u8, parsed.blocks[i].cid_raw, block.cid_raw); try std.testing.expectEqualSlices(u8, parsed.blocks[i].data, block.data); } try std.testing.expectEqual(parsed.blocks.len, i); } // stress test: iterate pfrazee.com's CAR via streamBlocks and compare // against the full `read` path. gated on ZAT_STRESS=1 and expects the // CAR cached at /tmp/pfrazee.car (fetch once via curl — see ken's // streaming CAR notes). not in CI: too slow, requires network fetch. test "streamBlocks: pfrazee.com stress" { const stress = std.testing.environ.getAlloc(std.testing.allocator, "ZAT_STRESS") catch return; defer std.testing.allocator.free(stress); if (!std.mem.eql(u8, stress, "1")) return; const io = std.Options.debug_io; const file = std.Io.Dir.openFileAbsolute(io, "/tmp/pfrazee.car", .{}) catch |err| { std.debug.print("pfrazee.car not found ({t}) — skip. fetch via:\n", .{err}); std.debug.print(" curl -L -o /tmp/pfrazee.car 'https://bsky.network/xrpc/com.atproto.sync.getRepo?did=did:plc:ragtjsm2j2vknwkz3zp4oxrd'\n", .{}); return; }; defer file.close(io); const file_len = try file.length(io); var mmap = try std.Io.File.MemoryMap.create(io, file, .{ .len = @intCast(file_len), .protection = .{ .read = true, .write = false }, .offset = 0, }); defer mmap.destroy(io); const bytes: []const u8 = mmap.memory[0..@intCast(file_len)]; std.debug.print("\npfrazee CAR: {d:.2} MB (mmap'd)\n", .{@as(f64, @floatFromInt(bytes.len)) / (1024.0 * 1024.0)}); // --- streaming path: iterate blocks, accumulate a few invariants --- var stream = try streamBlocks(std.testing.allocator, bytes, .{ .verify_block_hashes = true, .max_size = bytes.len, }); defer std.testing.allocator.free(stream.roots); var stream_block_count: usize = 0; var stream_total_bytes: usize = 0; var stream_cid_xor: u8 = 0; while (try stream.iter.next()) |block| { stream_block_count += 1; stream_total_bytes += block.data.len; for (block.cid_raw) |b| stream_cid_xor ^= b; } // --- reference path: full read (builds hashmap) --- var ref_arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer ref_arena.deinit(); const ref = try readWithOptions(ref_arena.allocator(), bytes, .{ .verify_block_hashes = true, .max_size = bytes.len, .max_blocks = bytes.len, }); var ref_total_bytes: usize = 0; var ref_cid_xor: u8 = 0; for (ref.blocks) |block| { ref_total_bytes += block.data.len; for (block.cid_raw) |b| ref_cid_xor ^= b; } std.debug.print( "stream: {d:>8} blocks, {d:>10} bytes, xor=0x{x:0>2}\n", .{ stream_block_count, stream_total_bytes, stream_cid_xor }, ); std.debug.print( "read: {d:>8} blocks, {d:>10} bytes, xor=0x{x:0>2}\n", .{ ref.blocks.len, ref_total_bytes, ref_cid_xor }, ); try std.testing.expectEqual(ref.blocks.len, stream_block_count); try std.testing.expectEqual(ref_total_bytes, stream_total_bytes); try std.testing.expectEqual(ref_cid_xor, stream_cid_xor); } test "streamBlocks rejects corrupted block with verify on" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const real = try cbor.encodeAlloc(alloc, .{ .map = &.{.{ .key = "k", .value = .{ .text = "original" } }} }); const cid = try cbor.Cid.forDagCbor(alloc, real); const tampered = Car{ .roots = &.{cid}, .blocks = &.{.{ .cid_raw = cid.raw, .data = "tampered" }}, }; const car_bytes = try writeAlloc(alloc, tampered); var stream = try streamBlocks(alloc, car_bytes, .{}); defer alloc.free(stream.roots); try std.testing.expectError(error.BadBlockHash, stream.iter.next()); } // Allocation failure must stay OutOfMemory rather than collapsing into a // structural verdict. Callers treat InvalidHeader as "this file is malformed" // and retire the source permanently, so an exhaustion wearing that name // discards good data and blames the remote for our own memory pressure. test "header allocation failure is not reported as an invalid header" { var fixture = std.heap.ArenaAllocator.init(std.testing.allocator); defer fixture.deinit(); const alloc = fixture.allocator(); const block = try cbor.encodeAlloc(alloc, .{ .map = &.{.{ .key = "k", .value = .{ .text = "v" } }} }); const cid = try cbor.Cid.forDagCbor(alloc, block); const car_bytes = try writeAlloc(alloc, Car{ .roots = &.{cid}, .blocks = &.{.{ .cid_raw = cid.raw, .data = block }}, }); var parsed: usize = 0; var exhausted: usize = 0; for (0..64) |fail_index| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_index }); var arena = std.heap.ArenaAllocator.init(failing.allocator()); defer arena.deinit(); if (read(arena.allocator(), car_bytes)) |_| { parsed += 1; } else |err| switch (err) { error.OutOfMemory => exhausted += 1, else => { std.debug.print( "fail_index {d}: exhaustion surfaced as {s}\n", .{ fail_index, @errorName(err) }, ); return error.ExhaustionMisclassified; }, } } try std.testing.expect(exhausted > 0); try std.testing.expect(parsed > 0); }