1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Reconstruct and verify one repository from Stream's real JSS archive.
//!
//! This is the Zig equivalent of upstream `internal/repoexport`: candidate
//! sealed segments are pruned by their resident-format DID blooms, the active
//! writer and its pending block are snapshotted under the archive lock before
//! sealed selection (closing the rotation race), and repository records are
//! folded last-writer-wins into a canonical AT Protocol MST.
const std = @import("std");
const zat = @import("zat");
const archive_mod = @import("../storage/archive.zig");
const gloom = @import("../storage/gloom.zig");
const segment = @import("../storage/segment.zig");
const writer_mod = @import("../storage/segment_writer.zig");
const cli = @import("../runtime/cli.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
pub const no_local_repo_message = "repoexport: no local commit events for DID";
pub const root_mismatch_message = "local reconstructed MST root does not match authoritative repo root";
pub const Snapshot = struct {
did: []const u8,
latest_rev: []const u8,
root: zat.cbor.Cid,
record_count: usize,
};
pub const VerifyReport = struct {
did: []const u8,
match: bool = false,
authoritative_rev: []const u8 = "",
authoritative_root: []const u8 = "",
local_latest_rev: []const u8 = "",
local_root: []const u8 = "",
local_record_count: usize = 0,
message: []const u8 = "",
};
/// Compare the PDS's signed commit data root with a reconstruction from the
/// local event archive. The authoritative side deliberately uses the same
/// two PDS-only Sync 1.1 calls as upstream: getLatestCommit, then getBlocks
/// for that commit CID. Only the matching, hash-valid commit block among the
/// first eight CAR blocks is accepted.
pub fn verify(
allocator: Allocator,
io: Io,
archive: *archive_mod.Archive,
data_dir: []const u8,
plc_url: []const u8,
did: []const u8,
) !VerifyReport {
const parsed_did = zat.Did.parse(did) orelse return error.InvalidDid;
var resolver = zat.DidResolver.init(io, allocator);
defer resolver.deinit();
resolver.plc_url = plc_url;
var doc = try resolver.resolve(parsed_did);
defer doc.deinit();
const endpoint = std.mem.trimEnd(u8, doc.pdsEndpoint() orelse return error.NoAuthoritativePDS, "/");
if (endpoint.len == 0) return error.NoAuthoritativePDS;
const latest_url = try xrpcUrlAlloc(allocator, endpoint, "com.atproto.sync.getLatestCommit", &.{.{ .name = "did", .value = did }});
defer allocator.free(latest_url);
var transport = zat.HttpTransport.initWithUserAgent(io, allocator, cli.userAgent());
defer transport.deinit();
const latest_response = try transport.fetch(.{ .url = latest_url, .max_response_size = 64 * 1024, .on_redirect = .refuse });
defer allocator.free(latest_response.body);
if (latest_response.status.class() != .success) return error.GetLatestCommitFailed;
const latest_json = try std.json.parseFromSlice(std.json.Value, allocator, latest_response.body, .{});
defer latest_json.deinit();
const rev_raw = zat.json.getString(latest_json.value, "rev") orelse return error.InvalidLatestCommit;
const cid_raw = zat.json.getString(latest_json.value, "cid") orelse return error.InvalidLatestCommit;
const rev = try allocator.dupe(u8, rev_raw);
const commit_cid_string = try allocator.dupe(u8, cid_raw);
const commit_cid = try zat.mst.parseCidString(allocator, commit_cid_string);
const blocks_url = try xrpcUrlAlloc(allocator, endpoint, "com.atproto.sync.getBlocks", &.{
.{ .name = "did", .value = did },
.{ .name = "cids", .value = commit_cid_string },
});
defer allocator.free(blocks_url);
const blocks_response = try transport.fetch(.{
.url = blocks_url,
.max_response_size = 8 * (1024 * 1024 + 128) + 64 * 1024,
.on_redirect = .refuse,
});
defer allocator.free(blocks_response.body);
if (blocks_response.status.class() != .success) return error.GetCommitBlockFailed;
const commit_data = try findAuthoritativeCommitBlock(allocator, blocks_response.body, commit_cid);
const roots = [_]zat.cbor.Cid{commit_cid};
const blocks = [_]zat.car.Block{.{ .cid_raw = commit_cid.raw, .data = commit_data }};
const single_car = try zat.car.writeAlloc(allocator, .{ .roots = &roots, .blocks = &blocks });
defer allocator.free(single_car);
const loaded = try zat.loadCommitFromCAR(allocator, single_car);
if (!std.mem.eql(u8, loaded.commit.did, did)) return error.AuthoritativeCommitDidMismatch;
if (!std.mem.eql(u8, loaded.commit.rev, rev)) return error.AuthoritativeCommitRevMismatch;
const authoritative_root = try zat.multibase.base32lower.encode(allocator, loaded.commit.data_cid);
var report: VerifyReport = .{
.did = did,
.authoritative_rev = rev,
.authoritative_root = authoritative_root,
};
const local = reconstruct(allocator, io, archive, data_dir, did) catch |err| switch (err) {
error.NoLocalRepo => {
report.message = try std.fmt.allocPrint(allocator, "{s}: {s}", .{ no_local_repo_message, did });
return report;
},
else => return err,
};
defer freeSnapshot(allocator, local);
report.local_latest_rev = try allocator.dupe(u8, local.latest_rev);
report.local_root = try zat.multibase.base32lower.encode(allocator, local.root.raw);
report.local_record_count = local.record_count;
report.match = std.mem.eql(u8, report.authoritative_root, report.local_root);
if (!report.match) report.message = root_mismatch_message;
return report;
}
const QueryParam = struct { name: []const u8, value: []const u8 };
fn xrpcUrlAlloc(allocator: Allocator, endpoint: []const u8, nsid: []const u8, params: []const QueryParam) ![]u8 {
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(allocator);
try out.print(allocator, "{s}/xrpc/{s}", .{ endpoint, nsid });
for (params, 0..) |param, index| {
try out.append(allocator, if (index == 0) '?' else '&');
try out.appendSlice(allocator, param.name);
try out.append(allocator, '=');
for (param.value) |byte| {
if (std.ascii.isAlphanumeric(byte) or byte == '-' or byte == '_' or byte == '.' or byte == '~')
try out.append(allocator, byte)
else
try out.print(allocator, "%{X:0>2}", .{byte});
}
}
return out.toOwnedSlice(allocator);
}
fn findAuthoritativeCommitBlock(allocator: Allocator, car_bytes: []const u8, wanted: zat.cbor.Cid) ![]const u8 {
var pos: usize = 0;
const header_len_u64 = zat.cbor.readUvarint(car_bytes, &pos) orelse return error.InvalidAuthoritativeCar;
const header_len = std.math.cast(usize, header_len_u64) orelse return error.InvalidAuthoritativeCar;
if (header_len > 1024 * 1024 or pos + header_len > car_bytes.len) return error.InvalidAuthoritativeCar;
var header_arena = std.heap.ArenaAllocator.init(allocator);
defer header_arena.deinit();
const header = try zat.cbor.decodeAll(header_arena.allocator(), car_bytes[pos..][0..header_len]);
if (header.getUint("version") != 1) return error.InvalidAuthoritativeCar;
pos += header_len;
var blocks_read: usize = 0;
while (pos < car_bytes.len and blocks_read < 8) : (blocks_read += 1) {
const block_len_u64 = zat.cbor.readUvarint(car_bytes, &pos) orelse return error.InvalidAuthoritativeCar;
const block_len = std.math.cast(usize, block_len_u64) orelse return error.InvalidAuthoritativeCar;
if (block_len == 0 or block_len > 1024 * 1024 or pos + block_len > car_bytes.len) return error.InvalidAuthoritativeCar;
const raw = car_bytes[pos..][0..block_len];
const cid_len = cidLength(raw) orelse return error.InvalidAuthoritativeCar;
if (cid_len > raw.len) return error.InvalidAuthoritativeCar;
const claimed: zat.cbor.Cid = .{ .raw = raw[0..cid_len] };
const data = raw[cid_len..];
if (claimed.version() != 1 or claimed.hashFn() != zat.cbor.HashFn.sha2_256) return error.InvalidAuthoritativeCar;
const computed = try zat.cbor.Cid.create(header_arena.allocator(), 1, claimed.codec() orelse return error.InvalidAuthoritativeCar, zat.cbor.HashFn.sha2_256, data);
if (!std.mem.eql(u8, computed.raw, claimed.raw)) return error.AuthoritativeBlockCidMismatch;
pos += block_len;
if (std.mem.eql(u8, claimed.raw, wanted.raw)) return data;
}
// Upstream classifies any eight non-matching blocks as the bounded-search
// limit, even when the eighth block is also the end of the response.
if (blocks_read >= 8) return error.AuthoritativeCommitBlockLimit;
return error.AuthoritativeCommitBlockNotFound;
}
fn cidLength(data: []const u8) ?usize {
if (data.len < 2) return null;
if (data[0] == 0x12 and data[1] == 0x20) return if (data.len >= 34) 34 else null;
var pos: usize = 0;
_ = zat.cbor.readUvarint(data, &pos) orelse return null;
_ = zat.cbor.readUvarint(data, &pos) orelse return null;
_ = zat.cbor.readUvarint(data, &pos) orelse return null;
const digest_len = zat.cbor.readUvarint(data, &pos) orelse return null;
const digest_len_usize = std.math.cast(usize, digest_len) orelse return null;
if (pos + digest_len_usize > data.len) return null;
return pos + digest_len_usize;
}
const ReplayState = struct {
allocator: Allocator,
did: []const u8,
records: std.StringHashMap([]const u8),
latest_rev: []const u8 = "",
seen_commit: bool = false,
fn init(allocator: Allocator, did: []const u8) ReplayState {
return .{ .allocator = allocator, .did = did, .records = std.StringHashMap([]const u8).init(allocator) };
}
fn deinit(self: *ReplayState) void {
var it = self.records.iterator();
while (it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
self.allocator.free(entry.value_ptr.*);
}
self.records.deinit();
if (self.latest_rev.len > 0) self.allocator.free(@constCast(self.latest_rev));
}
fn apply(self: *ReplayState, ev: segment.Event, watermark: []const u8) !void {
if (!std.mem.eql(u8, ev.did, self.did)) return;
switch (ev.kind) {
.create, .update, .create_resync => {
if (watermark.len > 0 and std.mem.order(u8, ev.rev, watermark) != .gt) return;
const key = try std.fmt.allocPrint(self.allocator, "{s}/{s}", .{ ev.collection, ev.rkey });
errdefer self.allocator.free(key);
const payload = try self.allocator.dupe(u8, ev.payload);
errdefer self.allocator.free(payload);
if (self.records.getPtr(key)) |old_payload| {
self.allocator.free(key);
self.allocator.free(@constCast(old_payload.*));
old_payload.* = payload;
} else {
try self.records.put(key, payload);
}
},
.delete => {
if (watermark.len > 0 and std.mem.order(u8, ev.rev, watermark) != .gt) return;
const key = try std.fmt.allocPrint(self.allocator, "{s}/{s}", .{ ev.collection, ev.rkey });
defer self.allocator.free(key);
if (self.records.fetchRemove(key)) |entry| {
self.allocator.free(entry.key);
self.allocator.free(entry.value);
}
},
else => return,
}
self.seen_commit = true;
if (self.latest_rev.len > 0) self.allocator.free(@constCast(self.latest_rev));
self.latest_rev = try self.allocator.dupe(u8, ev.rev);
}
};
const ActiveSnapshot = struct {
bytes: []u8,
pending: []segment.Event,
fn deinit(self: *ActiveSnapshot, allocator: Allocator) void {
allocator.free(self.bytes);
for (self.pending) |ev| {
allocator.free(@constCast(ev.did));
allocator.free(@constCast(ev.collection));
allocator.free(@constCast(ev.rkey));
allocator.free(@constCast(ev.rev));
allocator.free(@constCast(ev.payload));
}
allocator.free(self.pending);
}
};
/// Reconstruct at a rotation-safe point in time. `data_dir` is used only for
/// the bootstrap live archive, which is absent after steady-state cleanup.
pub fn reconstruct(allocator: Allocator, io: Io, archive: *archive_mod.Archive, data_dir: []const u8, did: []const u8) !Snapshot {
if (zat.Did.parse(did) == null) return error.InvalidDid;
var state = ReplayState.init(allocator, did);
defer state.deinit();
// Upstream's critical ordering: active paths before sealed selection. We
// make the boundary stronger by copying the active frames and pending rows
// together under the writer lock, then scan the sealed directory.
var active = try snapshotActive(allocator, io, archive);
defer active.deinit(allocator);
var names: std.ArrayList([]u8) = .empty;
defer {
for (names.items) |name| allocator.free(name);
names.deinit(allocator);
}
var it = archive.dir.iterate();
while (try it.next(io)) |entry| {
if (archive_mod.parseSegmentIndex(entry.name) == null) continue;
try names.append(allocator, try allocator.dupe(u8, entry.name));
}
std.mem.sort([]u8, names.items, {}, struct {
fn less(_: void, a: []u8, b: []u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
}.less);
for (names.items) |name| try replaySealedCandidate(allocator, io, archive.dir, name, &state);
try replayActiveBytes(allocator, active.bytes, "", &state);
const primary_watermark = if (state.latest_rev.len > 0) try allocator.dupe(u8, state.latest_rev) else "";
defer if (primary_watermark.len > 0) allocator.free(@constCast(primary_watermark));
try replayBootstrapLive(allocator, io, data_dir, primary_watermark, &state);
for (active.pending) |ev| try state.apply(ev, "");
if (!state.seen_commit) return error.NoLocalRepo;
var tree_arena = std.heap.ArenaAllocator.init(allocator);
defer tree_arena.deinit();
const tree_allocator = tree_arena.allocator();
var tree = zat.mst.Mst.init(tree_allocator);
var keys: std.ArrayList([]const u8) = .empty;
defer keys.deinit(allocator);
var key_it = state.records.keyIterator();
while (key_it.next()) |key| try keys.append(allocator, key.*);
std.mem.sort([]const u8, keys.items, {}, struct {
fn less(_: void, a: []const u8, b: []const u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
}.less);
for (keys.items) |key| {
const cid = try zat.cbor.Cid.forDagCbor(tree_allocator, state.records.get(key).?);
try tree.putBorrowed(key, cid);
}
const root = try tree.rootCid();
return .{
.did = try allocator.dupe(u8, did),
.latest_rev = try allocator.dupe(u8, state.latest_rev),
.root = .{ .raw = try allocator.dupe(u8, root.raw) },
.record_count = state.records.count(),
};
}
pub fn freeSnapshot(allocator: Allocator, snapshot: Snapshot) void {
allocator.free(snapshot.did);
allocator.free(snapshot.latest_rev);
allocator.free(snapshot.root.raw);
}
fn snapshotActive(allocator: Allocator, io: Io, archive: *archive_mod.Archive) !ActiveSnapshot {
archive.mu.lockUncancelable(io);
defer archive.mu.unlock(io);
const bytes = try allocator.dupe(u8, archive.writer.bytes());
errdefer allocator.free(bytes);
const pending = try allocator.alloc(segment.Event, archive.writer.pending.items.len);
errdefer allocator.free(pending);
var copied: usize = 0;
errdefer for (pending[0..copied]) |ev| {
allocator.free(@constCast(ev.did));
allocator.free(@constCast(ev.collection));
allocator.free(@constCast(ev.rkey));
allocator.free(@constCast(ev.rev));
allocator.free(@constCast(ev.payload));
};
for (archive.writer.pending.items, 0..) |ev, index| {
pending[index] = try dupeEvent(allocator, ev);
copied += 1;
}
return .{ .bytes = bytes, .pending = pending };
}
fn dupeEvent(allocator: Allocator, ev: segment.Event) !segment.Event {
const did = try allocator.dupe(u8, ev.did);
errdefer allocator.free(did);
const collection = try allocator.dupe(u8, ev.collection);
errdefer allocator.free(collection);
const rkey = try allocator.dupe(u8, ev.rkey);
errdefer allocator.free(rkey);
const rev = try allocator.dupe(u8, ev.rev);
errdefer allocator.free(rev);
const payload = try allocator.dupe(u8, ev.payload);
return .{
.seq = ev.seq,
.witnessed_at = ev.witnessed_at,
.indexed_at = ev.indexed_at,
.kind = ev.kind,
.did = did,
.collection = collection,
.rkey = rkey,
.rev = rev,
.payload = payload,
};
}
fn replaySealedCandidate(allocator: Allocator, io: Io, dir: Io.Dir, name: []const u8, state: *ReplayState) !void {
var file = try dir.openFile(io, name, .{});
defer file.close(io);
var header_bytes: [segment.header_size]u8 = undefined;
if (try file.readPositionalAll(io, &header_bytes, 0) != header_bytes.len) return error.Truncated;
const header = segment.Header.decode(&header_bytes) catch |err| switch (err) {
error.ActiveSegment => return,
else => return err,
};
if (header.block_did_bloom_offset < header.did_bloom_offset) return error.BadFooter;
const bloom_len = header.block_did_bloom_offset - header.did_bloom_offset;
if (bloom_len > 1 << 30) return error.LimitExceeded;
const bloom_bytes = try allocator.alloc(u8, @intCast(bloom_len));
defer allocator.free(bloom_bytes);
if (try file.readPositionalAll(io, bloom_bytes, header.did_bloom_offset) != bloom_bytes.len) return error.Truncated;
var filter = try gloom.unmarshal(allocator, bloom_bytes);
defer filter.deinit(allocator);
if (!filter.contains(state.did)) return;
const bytes = try dir.readFileAlloc(io, name, allocator, .limited(1 << 31));
defer allocator.free(bytes);
var sealed = try segment.Sealed.parse(allocator, bytes);
defer sealed.deinit(allocator);
const blobs = try sealed.blockBloomBlobs(allocator);
defer allocator.free(blobs);
for (blobs, 0..) |blob, index| {
var block_filter = gloom.unmarshal(allocator, blob) catch null;
if (block_filter) |*candidate| {
defer candidate.deinit(allocator);
if (!candidate.contains(state.did)) continue;
}
var block = try sealed.readBlock(allocator, index);
defer block.deinit(allocator);
for (block.events) |ev| try state.apply(ev, "");
}
}
fn replayActiveBytes(allocator: Allocator, bytes: []const u8, watermark: []const u8, state: *ReplayState) !void {
var it: writer_mod.ActiveIterator = .{ .bytes = bytes };
while (try it.next(allocator)) |block_value| {
var block = block_value;
defer block.deinit(allocator);
for (block.events) |ev| try state.apply(ev, watermark);
}
}
fn replayBootstrapLive(allocator: Allocator, io: Io, data_dir: []const u8, watermark: []const u8, state: *ReplayState) !void {
var path_buf: [Io.Dir.max_path_bytes]u8 = undefined;
const path = std.fmt.bufPrint(&path_buf, "{s}/backfill/live/segments", .{data_dir}) catch return error.NameTooLong;
var dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch |err| switch (err) {
error.FileNotFound => return,
else => return err,
};
defer dir.close(io);
var names: std.ArrayList([]u8) = .empty;
defer {
for (names.items) |name| allocator.free(name);
names.deinit(allocator);
}
var it = dir.iterate();
while (try it.next(io)) |entry| if (archive_mod.parseSegmentIndex(entry.name) != null)
try names.append(allocator, try allocator.dupe(u8, entry.name));
std.mem.sort([]u8, names.items, {}, struct {
fn less(_: void, a: []u8, b: []u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
}.less);
for (names.items) |name| {
const bytes = try dir.readFileAlloc(io, name, allocator, .limited(1 << 31));
defer allocator.free(bytes);
if (segment.Header.decode(bytes)) |_| {
var sealed = try segment.Sealed.parse(allocator, bytes);
defer sealed.deinit(allocator);
for (sealed.block_index, 0..) |_, index| {
var block = try sealed.readBlock(allocator, index);
defer block.deinit(allocator);
for (block.events) |ev| try state.apply(ev, watermark);
}
} else |err| switch (err) {
error.ActiveSegment => try replayActiveBytes(allocator, bytes, watermark, state),
else => return err,
}
}
}
const testing = std.testing;
fn fixtureEvent(did: []const u8, kind: segment.Kind, rkey: []const u8, rev: []const u8, payload: []const u8) segment.Event {
return .{
.seq = 0,
.witnessed_at = 1_750_000_000_000_000,
.indexed_at = 0,
.kind = kind,
.did = did,
.collection = "app.bsky.feed.post",
.rkey = rkey,
.rev = rev,
.payload = payload,
};
}
test "reconstruct prunes real sealed JSS and includes flushed active plus pending events" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [Io.Dir.max_path_bytes]u8 = undefined;
const root_len = try tmp.dir.realPath(io, &root_buf);
const data_dir = root_buf[0..root_len];
var archive = try archive_mod.Archive.init(testing.allocator, io, data_dir);
defer archive.deinit();
archive.max_events_per_block = 2;
archive.writer.max_events_per_block = 2;
const did = "did:plc:reconstructfixture";
const other = "did:plc:otherfixture";
const first = "\xa1\x64text\x65first";
const second = "\xa1\x64text\x66second";
const latest = "\xa1\x64text\x66latest";
_ = try archive.append(fixtureEvent(did, .create, "one", "3la", first), 1);
_ = try archive.append(fixtureEvent(other, .create, "other", "3la", second), 1);
try archive.rotate();
// This pair flushes into the active file. The final row stays only in the
// writer's pending block, exercising all three production sources.
_ = try archive.append(fixtureEvent(did, .update, "one", "3lb", second), 2);
_ = try archive.append(fixtureEvent(other, .update, "other", "3lb", first), 2);
_ = try archive.append(fixtureEvent(did, .create, "two", "3lc", latest), 2);
_ = try archive.append(fixtureEvent(did, .delete, "one", "3ld", ""), 2);
const snapshot = try reconstruct(testing.allocator, io, &archive, data_dir, did);
defer freeSnapshot(testing.allocator, snapshot);
try testing.expectEqualStrings("3ld", snapshot.latest_rev);
try testing.expectEqual(@as(usize, 1), snapshot.record_count);
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
var expected = zat.mst.Mst.init(alloc);
const record_cid = try zat.cbor.Cid.forDagCbor(alloc, latest);
try expected.put("app.bsky.feed.post/two", record_cid);
const expected_root = try expected.rootCid();
try testing.expectEqualSlices(u8, expected_root.raw, snapshot.root.raw);
}
test "reconstruct distinguishes an absent DID from an empty repository" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [Io.Dir.max_path_bytes]u8 = undefined;
const root_len = try tmp.dir.realPath(io, &root_buf);
const data_dir = root_buf[0..root_len];
var archive = try archive_mod.Archive.init(testing.allocator, io, data_dir);
defer archive.deinit();
try testing.expectError(error.NoLocalRepo, reconstruct(testing.allocator, io, &archive, data_dir, "did:plc:absentfixture"));
const did = "did:plc:emptyfixture";
_ = try archive.append(fixtureEvent(did, .delete, "gone", "3la", ""), 1);
const snapshot = try reconstruct(testing.allocator, io, &archive, data_dir, did);
defer freeSnapshot(testing.allocator, snapshot);
try testing.expectEqual(@as(usize, 0), snapshot.record_count);
try testing.expectEqualStrings("3la", snapshot.latest_rev);
}
test "verify compares a real JSS reconstruction with real PLC and PDS Sync responses offline" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var fixture_arena = std.heap.ArenaAllocator.init(testing.allocator);
defer fixture_arena.deinit();
const alloc = fixture_arena.allocator();
const did = "did:plc:verifyfixture";
const rev = "3k2abcdefghij";
const record = try zat.cbor.encodeAlloc(alloc, .{ .map = &.{
.{ .key = "$type", .value = .{ .text = "app.bsky.feed.post" } },
.{ .key = "text", .value = .{ .text = "offline verification" } },
} });
const record_cid = try zat.cbor.Cid.forDagCbor(alloc, record);
var authoritative_tree = zat.mst.Mst.init(alloc);
try authoritative_tree.put("app.bsky.feed.post/fixture", record_cid);
const data_root = try authoritative_tree.rootCid();
const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(41));
const signed = try zat.signCommit(alloc, .{ .did = did, .rev = rev, .data = data_root }, &keypair);
const commit_cid_string = try zat.multibase.base32lower.encode(alloc, signed.cid.raw);
const decoy_data = "decoy";
const decoy_cid = try zat.cbor.Cid.forDagCbor(alloc, decoy_data);
// PDS getBlocks legitimately uses an empty-roots CAR; put a valid decoy
// first to prove the verifier searches rather than trusting block zero.
const get_blocks_car = try zat.car.writeAlloc(alloc, .{
.roots = &.{},
.blocks = &.{
.{ .cid_raw = decoy_cid.raw, .data = decoy_data },
.{ .cid_raw = signed.cid.raw, .data = signed.bytes },
},
});
var listener = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
defer listener.deinit(io);
var endpoint_buf: [96]u8 = undefined;
const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}", .{listener.socket.address.getPort()});
const did_doc = try std.fmt.allocPrint(alloc,
\\{{"id":"{s}","alsoKnownAs":["at://verify.example"],"verificationMethod":[],"service":[{{"id":"#atproto_pds","type":"AtprotoPersonalDataServer","serviceEndpoint":"{s}"}}]}}
, .{ did, endpoint });
const latest_json = try std.fmt.allocPrint(alloc, "{{\"cid\":\"{s}\",\"rev\":\"{s}\"}}", .{ commit_cid_string, rev });
const Fixture = struct {
fn run(server: *Io.net.Server, task_io: Io, doc: []const u8, latest: []const u8, blocks_car: []const u8) !void {
for (0..3) |_| {
var stream = try server.accept(task_io);
defer stream.close(task_io);
var read_buf: [4096]u8 = undefined;
var write_buf: [4096]u8 = undefined;
var reader = stream.reader(task_io, &read_buf);
var writer = stream.writer(task_io, &write_buf);
var http = std.http.Server.init(&reader.interface, &writer.interface);
var request = try http.receiveHead();
const target = request.head.target;
const body, const content_type = if (std.mem.indexOf(u8, target, "getLatestCommit") != null)
.{ latest, "application/json" }
else if (std.mem.indexOf(u8, target, "getBlocks") != null)
.{ blocks_car, "application/vnd.ipld.car" }
else
.{ doc, "application/json" };
try request.respond(body, .{
.status = .ok,
.keep_alive = false,
.extra_headers = &.{.{ .name = "content-type", .value = content_type }},
});
}
}
};
var server_future = try io.concurrent(Fixture.run, .{ &listener, io, did_doc, latest_json, get_blocks_car });
defer _ = server_future.cancel(io) catch {};
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [Io.Dir.max_path_bytes]u8 = undefined;
const root_len = try tmp.dir.realPath(io, &root_buf);
const data_dir = root_buf[0..root_len];
var archive = try archive_mod.Archive.init(testing.allocator, io, data_dir);
defer archive.deinit();
_ = try archive.append(fixtureEvent(did, .create, "fixture", rev, record), 1);
var verify_arena = std.heap.ArenaAllocator.init(testing.allocator);
defer verify_arena.deinit();
const report = try verify(verify_arena.allocator(), io, &archive, data_dir, endpoint, did);
try testing.expect(report.match);
try testing.expectEqualStrings(rev, report.authoritative_rev);
try testing.expectEqualStrings(rev, report.local_latest_rev);
try testing.expectEqual(@as(usize, 1), report.local_record_count);
try testing.expectEqualStrings(report.authoritative_root, report.local_root);
try testing.expectEqualStrings("", report.message);
_ = try server_future.await(io);
}
test "authoritative commit search matches upstream eight-block boundary" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
var blocks: [8]zat.car.Block = undefined;
for (&blocks, 0..) |*block, index| {
const data = try std.fmt.allocPrint(alloc, "decoy-{d}", .{index});
const cid = try zat.cbor.Cid.forDagCbor(alloc, data);
block.* = .{ .cid_raw = cid.raw, .data = data };
}
const wanted = try zat.cbor.Cid.forDagCbor(alloc, "wanted");
const seven = try zat.car.writeAlloc(alloc, .{ .roots = &.{}, .blocks = blocks[0..7] });
try testing.expectError(error.AuthoritativeCommitBlockNotFound, findAuthoritativeCommitBlock(alloc, seven, wanted));
const eight = try zat.car.writeAlloc(alloc, .{ .roots = &.{}, .blocks = &blocks });
try testing.expectError(error.AuthoritativeCommitBlockLimit, findAuthoritativeCommitBlock(alloc, eight, wanted));
}