@mikeargento/bitgraph-audit 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc.
2
+
3
+ /**
4
+ * A folder audit reads the proof inside each BitGraphed file, so a token spent twice shows the same way whether the
5
+ * two receipts are loose JSON files or carried inside the files they bind: in memory, in a directory, and in a tar.
6
+ * The bytes before each block are the artifact, so a carried receipt is checked at the full tier.
7
+ */
8
+
9
+ import { test } from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import { readFileSync, mkdtempSync, writeFileSync, rmSync } from "node:fs";
12
+ import { execFileSync } from "node:child_process";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { createHash } from "node:crypto";
16
+ import { buildBitGraphedFileV5, buildBitGraphedFileV6 } from "@mikeargento/bitgraph-verify";
17
+ import { ingestEntries, ingestBundle, auditIngest, computeExitFlags, type AuditResult } from "@mikeargento/bitgraph-audit";
18
+
19
+ const at = (p: string) => new URL(`../../../../${p}`, import.meta.url);
20
+ const V1 = JSON.parse(readFileSync(at("spec/vectors/bitgraph-tot-v1.json"), "utf8"));
21
+ const SET = V1.sets.find((x: { name: string }) => x.name === "spent-twice");
22
+ const FILES: Uint8Array[] = SET.filesB64.map((b: string) => new Uint8Array(Buffer.from(b, "base64")));
23
+ const REAL = JSON.parse(readFileSync(at("spec/vectors/bitgraph-tot-v2-real/receipt.json"), "utf8"));
24
+ const SPEC = new Uint8Array(readFileSync(at("spec/BITGRAPH-TOT-2.md")));
25
+ const STARTED = "2026-12-05T00:00:00.000Z";
26
+
27
+ const json = (v: unknown) => new TextEncoder().encode(JSON.stringify(v, null, 2));
28
+ const carried = (i: number) => buildBitGraphedFileV5(FILES[i] as Uint8Array, SET.receipts[i], null);
29
+ const inMemory = async (entries: Array<[string, Uint8Array]>) =>
30
+ auditIngest(await ingestEntries(entries.map(([path, bytes]) => ({ path, open: () => bytes }))), { startedAt: STARTED });
31
+ const onDisk = (entries: Array<[string, Uint8Array]>) => {
32
+ const dir = mkdtempSync(join(tmpdir(), "bitgraph-carrier-folder-"));
33
+ for (const [name, bytes] of entries) writeFileSync(join(dir, name), bytes);
34
+ return dir;
35
+ };
36
+ const codes = (r: AuditResult) => r.anomalies.anomalies.map((a) => a.code).sort();
37
+
38
+ test("baseline: two loose receipts that spend one token are flagged", async () => {
39
+ const r = await inMemory([["r0.json", json(SET.receipts[0])], ["r1.json", json(SET.receipts[1])]]);
40
+ assert.deepEqual(codes(r), ["counter-collision", "multiple-genesis", "slot-collision"]);
41
+ assert.equal(r.anomalies.divergences.length, 3);
42
+ });
43
+
44
+ test("the same two receipts carried inside their files are flagged the same way, read from <file>#proof", async () => {
45
+ const loose = await inMemory([["r0.json", json(SET.receipts[0])], ["r1.json", json(SET.receipts[1])]]);
46
+ const r = await inMemory([["doc-0.txt", carried(0)], ["doc-1.txt", carried(1)]]);
47
+ assert.deepEqual(codes(r), codes(loose));
48
+ assert.equal(r.anomalies.divergences.length, loose.anomalies.divergences.length);
49
+ assert.equal(r.ingest.counts.carriers, 2);
50
+ assert.equal(r.ingest.counts.proofFiles, 2);
51
+ assert.deepEqual(r.ingest.proofs.map((p) => p.sources[0]?.path).sort(), ["doc-0.txt#proof", "doc-1.txt#proof"]);
52
+ assert.equal(computeExitFlags(r).chainAnomaliesOrDivergences, true);
53
+ });
54
+
55
+ test("one carried file and one loose receipt: flagged", async () => {
56
+ const r = await inMemory([["doc-0.txt", carried(0)], ["r1.json", json(SET.receipts[1])]]);
57
+ assert.deepEqual(codes(r), ["counter-collision", "multiple-genesis", "slot-collision"]);
58
+ });
59
+
60
+ test("a directory and a tar of the carried files are flagged too", async () => {
61
+ const dir = onDisk([["doc-0.txt", carried(0)], ["doc-1.txt", carried(1)]]);
62
+ try {
63
+ const fromDir = await auditIngest(await ingestBundle(dir), { startedAt: STARTED });
64
+ assert.deepEqual(codes(fromDir), ["counter-collision", "multiple-genesis", "slot-collision"]);
65
+ const tar = join(dir, "bundle.tar");
66
+ execFileSync("tar", ["-cf", tar, "-C", dir, "doc-0.txt", "doc-1.txt"]);
67
+ const fromTar = await auditIngest(await ingestBundle(tar), { startedAt: STARTED });
68
+ assert.deepEqual(codes(fromTar), ["counter-collision", "multiple-genesis", "slot-collision"]);
69
+ assert.equal(fromTar.ingest.counts.carriers, 2);
70
+ } finally {
71
+ rmSync(dir, { recursive: true, force: true });
72
+ }
73
+ });
74
+
75
+ test("carrier/6 is read the same way", async () => {
76
+ const six = (i: number) => buildBitGraphedFileV6(FILES[i] as Uint8Array, SET.receipts[i], null, null);
77
+ const r = await inMemory([["a.bin", six(0)], ["b.bin", six(1)]]);
78
+ assert.deepEqual(codes(r), ["counter-collision", "multiple-genesis", "slot-collision"]);
79
+ });
80
+
81
+ test("the bytes before the block are the artifact, matched by the proof, never the whole file", async () => {
82
+ const file = carried(0);
83
+ const r = await inMemory([["doc-0.txt", file]]);
84
+ assert.deepEqual(codes(r), []);
85
+ assert.equal(r.ingest.artifacts.length, 1);
86
+ const a = r.ingest.artifacts[0]!;
87
+ assert.equal(a.sha256Hex, createHash("sha256").update(FILES[0] as Uint8Array).digest("hex"));
88
+ assert.equal(a.byteLength, (FILES[0] as Uint8Array).length);
89
+ assert.deepEqual(a.paths, ["doc-0.txt"]);
90
+ assert.deepEqual(a.carriedPaths, ["doc-0.txt"]);
91
+ assert.equal(a.matchedProofHashes.length, 1);
92
+ });
93
+
94
+ test("no false alarm: the real v14 receipt carried with the file it binds is checked at the full tier, in memory, on disk and in a tar", async () => {
95
+ const file = buildBitGraphedFileV5(SPEC, REAL, null);
96
+ const mem = await inMemory([["BITGRAPH-TOT-2.md", file]]);
97
+ const dir = onDisk([["BITGRAPH-TOT-2.md", file]]);
98
+ try {
99
+ const disk = await auditIngest(await ingestBundle(dir), { startedAt: STARTED });
100
+ const tar = join(dir, "bundle.tar");
101
+ execFileSync("tar", ["-cf", tar, "-C", dir, "BITGRAPH-TOT-2.md"]);
102
+ const fromTar = await auditIngest(await ingestBundle(tar), { startedAt: STARTED });
103
+ for (const r of [mem, disk, fromTar]) {
104
+ assert.deepEqual(codes(r), []);
105
+ assert.equal(r.anomalies.divergences.length, 0);
106
+ assert.equal(r.verification.verified, 1);
107
+ assert.equal(r.ingest.proofs[0]?.verification?.artifactPath, "BITGRAPH-TOT-2.md");
108
+ assert.equal(computeExitFlags(r).code, 0);
109
+ }
110
+ } finally {
111
+ rmSync(dir, { recursive: true, force: true });
112
+ }
113
+ });
114
+
115
+ test("the same receipt carried in two copies and loose is one proof seen three times, not a double spend", async () => {
116
+ const file = buildBitGraphedFileV5(SPEC, REAL, null);
117
+ const r = await inMemory([["a.md", file], ["b.md", file], ["receipt.json", json(REAL)]]);
118
+ assert.equal(r.ingest.proofs.length, 1);
119
+ assert.deepEqual(codes(r), []);
120
+ assert.equal(computeExitFlags(r).code, 0);
121
+ });
122
+
123
+ test("a block that cannot be read is reported and sets bit 2: its proof is not counted", async () => {
124
+ const file = carried(0);
125
+ const bad = file.slice();
126
+ bad[bad.length - 13] = 0x00; // inside the payload's JSON, before the trailing length and magic
127
+ const r = await inMemory([["doc-0.txt", bad]]);
128
+ assert.equal(r.ingest.proofs.length, 0);
129
+ assert.equal(r.ingest.counts.corruptCarriers, 1);
130
+ assert.ok(r.ingest.findings.some((f) => f.code === "carrier-corrupt" && f.path === "doc-0.txt"));
131
+ assert.equal(computeExitFlags(r).chainAnomaliesOrDivergences, true);
132
+ });
133
+
134
+ test("a folder with no BitGraphed files is read as before", async () => {
135
+ const r = await inMemory([["r0.json", json(SET.receipts[0])], ["notes.txt", new TextEncoder().encode("plain")]]);
136
+ assert.equal(r.ingest.counts.carriers, undefined);
137
+ assert.equal(r.ingest.artifacts.every((a) => a.carriedPaths === undefined), true);
138
+ });
@@ -11,7 +11,8 @@
11
11
  import { test } from "node:test";
12
12
  import assert from "node:assert/strict";
13
13
  import { readFileSync } from "node:fs";
14
- import { verifyTotReceipt, checkTotFloor } from "@mikeargento/bitgraph-audit";
14
+ import { verifyTotReceipt, checkTotFloor, checkSpentOnce, ingestEntries, auditIngest } from "@mikeargento/bitgraph-audit";
15
+ import { verifyAttested, verifyCarrier, buildBitGraphedFileV5, type BitGraphProof } from "@mikeargento/bitgraph-verify";
15
16
 
16
17
  const at = (p: string) => new URL(`../../../../${p}`, import.meta.url);
17
18
  const RECEIPT = JSON.parse(readFileSync(at("spec/vectors/bitgraph-tot-v2-real/receipt.json"), "utf8"));
@@ -96,3 +97,29 @@ test("a field beside a slot/1 TOT's signed ones is not refused, and is named as
96
97
  if (got.verdict === "ACCEPT") assert.equal(got.unsignedTotFields, undefined, x.name);
97
98
  }
98
99
  });
100
+
101
+ test("one rule for a slot/2 TOT's fields: the format's check, the main check and the carrier's all refuse an extra one", async () => {
102
+ const extra = { ...RECEIPT, slotAllocation: { ...RECEIPT.slotAllocation, note: "x" } };
103
+ const format = await verifyTotReceipt({ receipt: extra, file: SPEC });
104
+ assert.equal(format.verdict, "REJECT");
105
+ assert.equal(format.reason, "R1 form: a bitgraph/slot/2 slotAllocation must hold exactly its listed fields");
106
+ assert.equal((await verifyAttested({ proof: extra as unknown as BitGraphProof, bytes: SPEC })).valid, false);
107
+ assert.equal((await verifyCarrier(buildBitGraphedFileV5(SPEC, extra, null))).verdict, "FALSE");
108
+ // The receipt as made passes all three.
109
+ assert.equal((await verifyAttested({ proof: RECEIPT as BitGraphProof, bytes: SPEC })).valid, true);
110
+ assert.equal((await verifyCarrier(buildBitGraphedFileV5(SPEC, RECEIPT, null))).verdict, "TRUE");
111
+ });
112
+
113
+ test("an audit run over loose receipts reports a TOT consumed twice, under its own codes", async () => {
114
+ const set = V1.sets.find((s: { name: string }) => s.name === "spent-twice");
115
+ assert.equal((await checkSpentOnce(set.receipts)).reason, "DUPLICATE_TOT");
116
+ const enc = new TextEncoder();
117
+ const entries = set.receipts.map((r: unknown, i: number) => ({ path: `receipt-${i}.json`, open: () => enc.encode(JSON.stringify(r)) }));
118
+ const twice = await auditIngest(await ingestEntries(entries), { startedAt: "" });
119
+ const codes = twice.anomalies.anomalies.map((a) => a.code);
120
+ assert.ok(codes.includes("slot-collision"), codes.join(","));
121
+ assert.ok(codes.includes("counter-collision"), codes.join(","));
122
+ // One of them alone is clean.
123
+ const once = await auditIngest(await ingestEntries([entries[0]]), { startedAt: "" });
124
+ assert.deepEqual(once.anomalies.anomalies.map((a) => a.code), []);
125
+ });
package/src/audit.ts CHANGED
@@ -40,7 +40,7 @@ import type { AuditOptions, AuditResult, ExitFlags, IngestResult } from "./types
40
40
  * this equals package.json's version, so the constant cannot drift silently
41
41
  * across releases.
42
42
  */
43
- export const AUDIT_VERSION = "0.13.0";
43
+ export const AUDIT_VERSION = "0.15.0";
44
44
 
45
45
  /** The audit package's own version. */
46
46
  export function auditToolVersion(): string {
@@ -161,7 +161,8 @@ const WITNESS_VERIFICATION_FAILURE_CODES: ReadonlySet<string> = new Set([
161
161
  * claim or an export-shaped file that could not be checked), bit 2 is chain
162
162
  * or authority anomalies, divergences between valid proofs, anchor
163
163
  * witness verification failures, a failed ceiling, or a floor problem
164
- * (TemporalAnalysis.floorProblems). artifact-unavailable is never a failure by
164
+ * (TemporalAnalysis.floorProblems), or a BitGraphed file whose block cannot
165
+ * be read. artifact-unavailable is never a failure by
165
166
  * itself; the attestation stage's results and informational anchor findings
166
167
  * never set bits (an export's own attestation claims are part of its
167
168
  * verdict); benign ingest findings never set bits.
@@ -185,9 +186,13 @@ export function computeExitFlags(result: AuditResult): ExitFlags {
185
186
  // Base floor, a floor header that contradicts or matches no signed floor)
186
187
  // is bad evidence too: bit 2, never silently bounded.
187
188
  const floorProblems = (result.temporal.floorProblems ?? []).length > 0;
189
+ // A BitGraphed file whose block cannot be read hides the proof it holds:
190
+ // bit 2, as for a single corrupted carrier.
191
+ const corruptCarriers = (result.ingest.counts.corruptCarriers ?? 0) > 0;
188
192
  const chainAnomaliesOrDivergences =
189
193
  ceilingFailures ||
190
194
  floorProblems ||
195
+ corruptCarriers ||
191
196
  result.anomalies.anomalies.length > 0 ||
192
197
  result.anomalies.divergences.length > 0 ||
193
198
  result.authorities.anomalies.length > 0 ||
package/src/cli.ts CHANGED
@@ -78,6 +78,14 @@ function helpText(): string {
78
78
  "closing anchor: order after the record is the chain of proof hashes.",
79
79
  "The audit runs entirely offline: no RPC, no HTTP, no DNS.",
80
80
  "",
81
+ "BitGraphed files inside a directory or archive are read in place,",
82
+ "found by the block at their end: the proof inside each joins the",
83
+ "same checks as a loose proof file (counters, chains, a token spent",
84
+ "twice), reported as <file>#proof, and the bytes before the block are",
85
+ "the artifact. A block that cannot be read is a carrier-corrupt",
86
+ "finding and sets bit 2. Floor evidence inside a block is read only",
87
+ "when the file is audited on its own.",
88
+ "",
81
89
  "Floors. A proof's floor is the block the enclave signs into it: an",
82
90
  "Ethereum anchor (commit.slotAnchor, enclave v7 to v9) or a Base block",
83
91
  "(commit.slotFloor, enclave v10). A Base floor bounds its proof not",
package/src/ingest.ts CHANGED
@@ -24,6 +24,16 @@
24
24
  * is evidence too: the header of the Base block a proof signs as its floor
25
25
  * (commit.slotFloor, enclave v10), listed for the temporal stage.
26
26
  *
27
+ * A BitGraphed file (any bitgraph-carrier version, found by the block at its
28
+ * end, never by name) is read in place: the proof inside its block is recorded
29
+ * as an observed proof from "<path>#proof", exactly like a proof file, so a
30
+ * token spent twice shows in a folder of carried files as it does in a folder
31
+ * of loose receipts; and the bytes before the block are the artifact at
32
+ * <path>. The file's whole bytes are never an artifact. Other evidence a block
33
+ * may carry (floor witnesses, ceilings) is read only when the file is audited
34
+ * on its own. A block that is there but cannot be read is a carrier-corrupt
35
+ * finding: its proof cannot be counted.
36
+ *
27
37
  * Memory: archives are never unpacked to disk and never loaded whole.
28
38
  * Every entry is hashed incrementally as it streams. Only small JSON
29
39
  * candidates (at most MAX_CANDIDATE_JSON_BYTES) are buffered for parsing,
@@ -48,8 +58,17 @@ import { open, readdir, readFile, stat } from "node:fs/promises";
48
58
  import { join } from "node:path";
49
59
  import { createGunzip } from "node:zlib";
50
60
  import { sha256 } from "@noble/hashes/sha256";
51
- import { computeProofHash, computeChainHash, EXPORT_FORMAT, parseExport } from "@mikeargento/bitgraph-verify";
52
- import type { BitGraphProof } from "@mikeargento/bitgraph-verify";
61
+ import {
62
+ computeProofHash,
63
+ computeChainHash,
64
+ EXPORT_FORMAT,
65
+ parseExport,
66
+ parseCarrier,
67
+ CARRIER_MAGIC,
68
+ CARRIER_OVERHEAD,
69
+ MAX_CARRIER_PAYLOAD,
70
+ } from "@mikeargento/bitgraph-verify";
71
+ import type { BitGraphProof, CarrierPayload } from "@mikeargento/bitgraph-verify";
53
72
  import { readTarEntries } from "./tar.js";
54
73
  import { combineEntryDigests } from "./contents-hash.js";
55
74
  import type {
@@ -91,6 +110,19 @@ const MAX_CANDIDATE_JSON_BYTES = 8 * 1024 * 1024;
91
110
  const MAX_EXPORT_JSON_BYTES = 192 * 1024 * 1024;
92
111
  /** How many opening bytes decide whether an entry opens an export object. */
93
112
  const EXPORT_SNIFF_BYTES = 256;
113
+
114
+ /**
115
+ * The most of an entry's end that can hold a BitGraphed file's block: the
116
+ * largest payload a block may declare and the block's fixed bytes. Every
117
+ * entry keeps at most this much of its end while it streams, so a block is
118
+ * found in one pass without holding the file.
119
+ */
120
+ const CARRIER_WINDOW = MAX_CARRIER_PAYLOAD + CARRIER_OVERHEAD;
121
+
122
+ /** A block found at an entry's end. innerSha256Hex is filled by a second read of the bytes before it. */
123
+ type CarrierFound =
124
+ | { kind: "carrier"; payload: CarrierPayload; blockOffset: number; innerSha256Hex?: string }
125
+ | { kind: "corrupt"; reason: string };
94
126
  /** Producers write format first (buildExport); whitespace and one BOM are tolerated. */
95
127
  const EXPORT_OPENING = /^\s*\{\s*"format"\s*:\s*"(bitgraph-export\/[^"\\]{0,64})"/;
96
128
 
@@ -156,13 +188,25 @@ export async function ingestBundle(
156
188
  entriesScanned++;
157
189
  const stream = createReadStream(file.absPath);
158
190
  const hashed = await hashEntryStream(file.relPath, undefined, undefined, stream, exportCap);
191
+ if (hashed.carrier?.kind === "carrier") {
192
+ const n = hashed.carrier.blockOffset;
193
+ hashed.carrier.innerSha256Hex = await hashPrefix(
194
+ n === 0 ? [] : createReadStream(file.absPath, { start: 0, end: n - 1 }),
195
+ n
196
+ );
197
+ }
159
198
  scanned.push(makeScannedEntry(file.relPath, hashed));
160
199
  }
161
200
  } else {
201
+ // A BitGraphed file in an archive: the bytes before its block are hashed on
202
+ // a second pass over the archive, by the entry's place among its files.
203
+ const carriedByOrdinal = new Map<number, CarrierFound & { kind: "carrier" }>();
162
204
  const { stream, close } = openContainerByteStream(bundlePath, container);
163
205
  try {
206
+ let ordinal = -1;
164
207
  for await (const entry of readTarEntries(stream, limits)) {
165
208
  if (entry.kind !== "file") continue;
209
+ ordinal++;
166
210
  entriesScanned++;
167
211
  const normalized = normalizeEntryPath(entry.path);
168
212
  // Every file entry, safe or not, weighs on the bundle-root
@@ -181,11 +225,29 @@ export async function ingestBundle(
181
225
  const slash = normalized.path.indexOf("/");
182
226
  const strippedVariant = slash === -1 ? undefined : normalized.path.slice(slash + 1);
183
227
  const hashed = await hashEntryStream(normalized.path, strippedVariant, entry.size, entry.body, exportCap);
228
+ if (hashed.carrier?.kind === "carrier") carriedByOrdinal.set(ordinal, hashed.carrier);
184
229
  scanned.push(makeScannedEntry(normalized.path, hashed));
185
230
  }
186
231
  } finally {
187
232
  close();
188
233
  }
234
+ if (carriedByOrdinal.size > 0) {
235
+ const second = openContainerByteStream(bundlePath, container);
236
+ try {
237
+ let ordinal = -1;
238
+ for await (const entry of readTarEntries(second.stream, limits)) {
239
+ if (entry.kind !== "file") continue;
240
+ ordinal++;
241
+ const carrier = carriedByOrdinal.get(ordinal);
242
+ if (carrier === undefined) continue;
243
+ carrier.innerSha256Hex = await hashPrefix(entry.body, carrier.blockOffset);
244
+ carriedByOrdinal.delete(ordinal);
245
+ if (carriedByOrdinal.size === 0) break;
246
+ }
247
+ } finally {
248
+ second.close();
249
+ }
250
+ }
189
251
  }
190
252
 
191
253
  // ---------------------------------------------------------------------
@@ -271,6 +333,9 @@ export async function ingestEntries(
271
333
  openAsChunks(entry.open()),
272
334
  MAX_EXPORT_JSON_BYTES
273
335
  );
336
+ if (hashed.carrier?.kind === "carrier") {
337
+ hashed.carrier.innerSha256Hex = await hashPrefix(openAsChunks(entry.open()), hashed.carrier.blockOffset);
338
+ }
274
339
  scanned.push(makeScannedEntry(normalized.path, hashed));
275
340
  sources.set(normalized.path, entry);
276
341
  }
@@ -354,6 +419,7 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
354
419
  entryDigest,
355
420
  ...(entry.json !== undefined ? { json: entry.json } : {}),
356
421
  ...(entry.exportTooLarge !== undefined ? { exportTooLarge: entry.exportTooLarge } : {}),
422
+ ...(entry.carrier !== undefined ? { carrier: entry.carrier } : {}),
357
423
  });
358
424
  }
359
425
  const finalEntries = Array.from(finalByPath.values());
@@ -383,6 +449,8 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
383
449
  let proofFiles = 0;
384
450
  let exactDuplicates = 0;
385
451
  let semanticDuplicates = 0;
452
+ let carriers = 0;
453
+ let corruptCarriers = 0;
386
454
 
387
455
  for (const entry of finalEntries) {
388
456
  if (entry.path === MANIFEST_PATH) {
@@ -390,6 +458,47 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
390
458
  continue;
391
459
  }
392
460
 
461
+ // A BitGraphed file: its proof joins the proof analysis from
462
+ // "<path>#proof", and the bytes before its block are the artifact.
463
+ if (entry.carrier !== undefined) {
464
+ carriers++;
465
+ if (entry.carrier.kind === "corrupt") {
466
+ corruptCarriers++;
467
+ findings.push({
468
+ code: "carrier-corrupt",
469
+ path: entry.path,
470
+ message: `the file ends in a BitGraphed file's block that cannot be read (${entry.carrier.reason}); the proof it holds is not counted`,
471
+ });
472
+ indexArtifact(entry, artifactsByHex);
473
+ continue;
474
+ }
475
+ const proofEntry: FinalEntry = { ...entry, path: `${entry.path}#proof` };
476
+ const carried = entry.carrier.payload.proof as unknown;
477
+ if (isProofShaped(carried)) {
478
+ const version = (carried as Record<string, unknown>)["version"] as string;
479
+ if (version === "bitgraph/1") {
480
+ proofFiles++;
481
+ const outcome = recordMemberProof(proofEntry, carried as Record<string, unknown>, proofsByHash, proofs, findings);
482
+ if (outcome === "exact-duplicate") exactDuplicates++;
483
+ if (outcome === "semantic-duplicate") semanticDuplicates++;
484
+ } else {
485
+ unsupportedVersions.push({ code: "unsupported-version", path: proofEntry.path, version, fileSha256Hex: entry.sha256Hex });
486
+ findings.push({
487
+ code: "unsupported-version",
488
+ path: proofEntry.path,
489
+ message: `the proof inside this BitGraphed file is rejected: version "${version}" is not "bitgraph/1"`,
490
+ details: { version },
491
+ });
492
+ }
493
+ }
494
+ indexArtifact(
495
+ { ...entry, sha256Hex: entry.carrier.innerSha256Hex as string, byteLength: entry.carrier.blockOffset },
496
+ artifactsByHex,
497
+ true
498
+ );
499
+ continue;
500
+ }
501
+
393
502
  // An export too large to parse is still an export: reported, never an
394
503
  // artifact, and never silently checked as nothing.
395
504
  if (entry.exportTooLarge !== undefined) {
@@ -533,6 +642,8 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
533
642
  ...(floorHeaders.length > 0 ? { floorHeaders: floorHeaders.length } : {}),
534
643
  ceilings: ceilings.length + ceilingStatuses.length,
535
644
  exports: exportFiles.length,
645
+ ...(carriers > 0 ? { carriers } : {}),
646
+ ...(corruptCarriers > 0 ? { corruptCarriers } : {}),
536
647
  skippedUnsafePaths,
537
648
  };
538
649
 
@@ -609,7 +720,7 @@ async function* streamArtifactsFor(
609
720
  if (source === undefined) continue;
610
721
  let bytes: Uint8Array;
611
722
  try {
612
- bytes = await readSourceWhole(source);
723
+ bytes = artifactBytesAt(artifact, relPath, await readSourceWhole(source));
613
724
  } catch {
614
725
  continue;
615
726
  }
@@ -626,7 +737,7 @@ async function* streamArtifactsFor(
626
737
  for (const relPath of artifact.paths) {
627
738
  let bytes: Uint8Array;
628
739
  try {
629
- bytes = new Uint8Array(await readFile(join(ingest.bundlePath, ...relPath.split("/"))));
740
+ bytes = artifactBytesAt(artifact, relPath, new Uint8Array(await readFile(join(ingest.bundlePath, ...relPath.split("/")))));
630
741
  } catch {
631
742
  continue;
632
743
  }
@@ -663,7 +774,7 @@ async function* streamArtifactsFor(
663
774
  chunks.push(chunk.slice());
664
775
  total += chunk.length;
665
776
  }
666
- const bytes = concatBytes(chunks, total);
777
+ const bytes = artifactBytesAt(artifact, finalPath, concatBytes(chunks, total));
667
778
  if (toHex(sha256(bytes)) !== artifact.sha256Hex) continue;
668
779
  satisfied.add(artifact.sha256Hex);
669
780
  yield { sha256Hex: artifact.sha256Hex, path: finalPath, bytes };
@@ -768,6 +879,8 @@ interface ScannedEntry {
768
879
  json?: unknown;
769
880
  /** The format an entry opening an export declared, when it ran past the export JSON cap. */
770
881
  exportTooLarge?: string;
882
+ /** A BitGraphed file's block at the entry's end. */
883
+ carrier?: CarrierFound;
771
884
  }
772
885
 
773
886
  interface FinalEntry {
@@ -777,6 +890,7 @@ interface FinalEntry {
777
890
  entryDigest: Uint8Array;
778
891
  json?: unknown;
779
892
  exportTooLarge?: string;
893
+ carrier?: CarrierFound;
780
894
  }
781
895
 
782
896
  interface HashedEntry {
@@ -786,6 +900,7 @@ interface HashedEntry {
786
900
  entryDigestStripped?: Uint8Array;
787
901
  buffered?: Uint8Array;
788
902
  exportTooLarge?: string;
903
+ carrier?: CarrierFound;
789
904
  }
790
905
 
791
906
  /**
@@ -826,6 +941,9 @@ async function hashEntryStream(
826
941
  let headLength = 0;
827
942
  const buffered: Uint8Array[] = [];
828
943
  let total = 0;
944
+ // The entry's end, at most CARRIER_WINDOW bytes past the first chunk kept.
945
+ const tail: Uint8Array[] = [];
946
+ let tailLength = 0;
829
947
  const stop = (): "off" => {
830
948
  buffered.length = 0;
831
949
  return "off";
@@ -845,14 +963,20 @@ async function hashEntryStream(
845
963
  head.set(chunk.subarray(0, take), headLength);
846
964
  headLength += take;
847
965
  }
966
+ // Copy: tar body chunks are views into the container's stream
967
+ // buffers and are not stable after iteration continues.
968
+ const kept = chunk.slice();
969
+ tail.push(kept);
970
+ tailLength += kept.length;
971
+ while (tail.length > 1 && tailLength - (tail[0] as Uint8Array).length >= CARRIER_WINDOW) {
972
+ tailLength -= (tail.shift() as Uint8Array).length;
973
+ }
848
974
  if (mode === "off") continue;
849
975
  if (mode === "sniff" && headLength === head.length) {
850
976
  mode = exportOpening(head) === undefined ? stop() : declaredSize !== undefined && declaredSize > exportCap ? tooLarge() : "export";
851
977
  if (mode === "off") continue;
852
978
  }
853
- // Copy: tar body chunks are views into the container's stream
854
- // buffers and are not stable after iteration continues.
855
- buffered.push(chunk.slice());
979
+ buffered.push(kept);
856
980
  if (mode === "json" && total > MAX_CANDIDATE_JSON_BYTES) {
857
981
  mode = exportOpening(head.subarray(0, headLength)) === undefined ? stop() : "export";
858
982
  }
@@ -864,6 +988,7 @@ async function hashEntryStream(
864
988
  }
865
989
 
866
990
  const keep = mode === "json" || mode === "export";
991
+ const carrier = carrierAtEnd(tail, tailLength, total);
867
992
  return {
868
993
  sha256Hex: toHex(contentHasher.digest()),
869
994
  byteLength: total,
@@ -871,9 +996,41 @@ async function hashEntryStream(
871
996
  ...(strippedHasher !== undefined ? { entryDigestStripped: strippedHasher.digest() } : {}),
872
997
  ...(keep ? { buffered: concatBytes(buffered, total) } : {}),
873
998
  ...(exportTooLarge !== undefined ? { exportTooLarge } : {}),
999
+ ...(carrier !== undefined ? { carrier } : {}),
874
1000
  };
875
1001
  }
876
1002
 
1003
+ /**
1004
+ * The BitGraphed file's block at an entry's end, if its last eight bytes are
1005
+ * the block's magic. The kept end holds the whole block whenever the block is
1006
+ * one a reader accepts, so it is parsed exactly as the whole file would be,
1007
+ * and the block's offset is moved back to the entry's own count.
1008
+ */
1009
+ function carrierAtEnd(tail: Uint8Array[], tailLength: number, total: number): CarrierFound | undefined {
1010
+ const magic = CARRIER_MAGIC.length;
1011
+ if (tailLength < magic) return undefined;
1012
+ const last = tail[tail.length - 1] as Uint8Array;
1013
+ const end = last.length >= magic ? last.subarray(last.length - magic) : concatBytes(tail, tailLength).subarray(tailLength - magic);
1014
+ for (let i = 0; i < magic; i++) if (end[i] !== CARRIER_MAGIC[i]) return undefined;
1015
+ const window = concatBytes(tail, tailLength);
1016
+ const parsed = parseCarrier(window);
1017
+ if (parsed.kind === "none") return undefined;
1018
+ if (parsed.kind === "corrupt") return { kind: "corrupt", reason: parsed.reason };
1019
+ return { kind: "carrier", payload: parsed.payload, blockOffset: total - tailLength + parsed.blockOffset };
1020
+ }
1021
+
1022
+ /** SHA-256 of an entry's first n bytes, reading the rest through. Refuses an entry shorter than n. */
1023
+ async function hashPrefix(chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array>, n: number): Promise<string> {
1024
+ const hasher = sha256.create();
1025
+ let seen = 0;
1026
+ for await (const chunk of chunks) {
1027
+ if (seen < n) hasher.update(chunk.subarray(0, Math.min(n - seen, chunk.length)));
1028
+ seen += chunk.length;
1029
+ }
1030
+ if (seen < n) throw new Error(`bitgraph-audit: an entry was shorter on its second read (${seen} of ${n} bytes)`);
1031
+ return toHex(hasher.digest());
1032
+ }
1033
+
877
1034
  /** The export format an entry's opening bytes declare ({"format": "bitgraph-export/..."), or undefined. */
878
1035
  function exportOpening(head: Uint8Array): string | undefined {
879
1036
  const start = head.length >= 3 && head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0;
@@ -893,6 +1050,7 @@ function makeScannedEntry(rawPath: string, hashed: HashedEntry): ScannedEntry {
893
1050
  : {}),
894
1051
  ...(json !== undefined ? { json } : {}),
895
1052
  ...(hashed.exportTooLarge !== undefined ? { exportTooLarge: hashed.exportTooLarge } : {}),
1053
+ ...(hashed.carrier !== undefined ? { carrier: hashed.carrier } : {}),
896
1054
  };
897
1055
  }
898
1056
 
@@ -1171,10 +1329,11 @@ function asString(value: unknown): string | undefined {
1171
1329
  // Artifact indexing and matching
1172
1330
  // ---------------------------------------------------------------------------
1173
1331
 
1174
- function indexArtifact(entry: FinalEntry, artifactsByHex: Map<string, ArtifactRecord>): void {
1332
+ function indexArtifact(entry: FinalEntry, artifactsByHex: Map<string, ArtifactRecord>, carried = false): void {
1175
1333
  const existing = artifactsByHex.get(entry.sha256Hex);
1176
1334
  if (existing !== undefined) {
1177
1335
  existing.paths.push(entry.path);
1336
+ if (carried) (existing.carriedPaths ??= []).push(entry.path);
1178
1337
  return;
1179
1338
  }
1180
1339
  artifactsByHex.set(entry.sha256Hex, {
@@ -1182,10 +1341,16 @@ function indexArtifact(entry: FinalEntry, artifactsByHex: Map<string, ArtifactRe
1182
1341
  sha256B64: Buffer.from(entry.sha256Hex, "hex").toString("base64"),
1183
1342
  byteLength: entry.byteLength,
1184
1343
  paths: [entry.path],
1344
+ ...(carried ? { carriedPaths: [entry.path] } : {}),
1185
1345
  matchedProofHashes: [],
1186
1346
  });
1187
1347
  }
1188
1348
 
1349
+ /** An artifact's bytes as read from one of its paths: for a BitGraphed file, the bytes before its block. */
1350
+ function artifactBytesAt(artifact: ArtifactRecord, path: string, bytes: Uint8Array): Uint8Array {
1351
+ return artifact.carriedPaths?.includes(path) === true ? bytes.subarray(0, artifact.byteLength) : bytes;
1352
+ }
1353
+
1189
1354
  /**
1190
1355
  * Strict base64 digest decoding per spec section 6.3: RFC 4648 section 4
1191
1356
  * alphabet with the round-trip property, decoding to exactly 32 bytes.
package/src/tot.ts CHANGED
@@ -21,7 +21,7 @@
21
21
 
22
22
  import {
23
23
  verifyAttested, verifyProofIntegrity, createVerificationContext, computeSignedBodyHash, computeSlotRecordHash, buildSignedBody,
24
- slotFloorProblem, totFloorOf, checkFloorOnline, checkFloorAgainstBlock,
24
+ slotFormProblem, totFloorOf, checkFloorOnline, checkFloorAgainstBlock,
25
25
  type BitGraphProof, type NitroCheck, type SlotFloor, type FloorCheck, type RpcBlockHeader,
26
26
  } from "@mikeargento/bitgraph-verify";
27
27
 
@@ -46,8 +46,8 @@ export const TOT_MEASUREMENTS: readonly string[] = Object.freeze([...TOT_V1_MEAS
46
46
  /** The two TOT record versions. */
47
47
  const SLOT_1 = "bitgraph/slot/1";
48
48
  const SLOT_2 = "bitgraph/slot/2";
49
- /** Exactly what a bitgraph/slot/2 TOT holds, its signature included. Nothing else may sit in the record. */
50
- const SLOT_2_FIELDS = "chainId,counter,epochId,floor,nonceB64,publicKeyB64,signatureB64,version";
49
+ /** What a bitgraph/slot/2 TOT holds, its signature included. */
50
+ const SLOT_2_FIELDS = ["chainId", "counter", "epochId", "floor", "nonceB64", "publicKeyB64", "signatureB64", "version"] as const;
51
51
  /** What a bitgraph/slot/1 TOT holds, its signature included. Anything else in the record is outside the signature. */
52
52
  const SLOT_1_FIELDS: ReadonlySet<string> = new Set(["chainId", "counter", "epochId", "nonceB64", "publicKeyB64", "signatureB64", "version"]);
53
53
 
@@ -111,10 +111,10 @@ export function totFormProblem(receipt: unknown): string | null {
111
111
  const t = r["slotAllocation"];
112
112
  if (!isObject(t)) return "slotAllocation (the TOT) is missing";
113
113
  if (t["version"] !== SLOT_1 && t["version"] !== SLOT_2) return 'slotAllocation.version must be "bitgraph/slot/1" or "bitgraph/slot/2"';
114
- // A floor is signed in a slot/2 TOT and absent from a slot/1 TOT. A slot/2 TOT holds its listed fields and no others.
115
- const floor = slotFloorProblem(t);
116
- if (floor) return floor;
117
- if (t["version"] === SLOT_2 && Object.keys(t).sort().join(",") !== SLOT_2_FIELDS) return "a bitgraph/slot/2 slotAllocation must hold exactly its listed fields";
114
+ // A floor is signed in a slot/2 TOT and absent from a slot/1 TOT. A slot/2 TOT holds its listed fields and no
115
+ // others. The rule is the checker library's, so every tool refuses the same records.
116
+ const form = slotFormProblem(t);
117
+ if (form) return form;
118
118
  if (typeof t["counter"] !== "string" || !DEC.test(t["counter"])) return "slotAllocation.counter must be a decimal string";
119
119
  if (t["time"] !== undefined) return "slotAllocation.time must be absent";
120
120
  if (!B64_32(t["nonceB64"]) || !B64_32(t["epochId"]) || !B64_32(t["publicKeyB64"])) return "slotAllocation.nonceB64, epochId and publicKeyB64 must each be 32 bytes in canonical base64";
@@ -211,6 +211,15 @@ export async function checkTotFloor(opts: {
211
211
  return checkFloorOnline({ ...common, ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}), ...(opts.fetcher ? { fetcher: opts.fetcher } : {}) });
212
212
  }
213
213
 
214
+ /** A receipt whose slot/2 TOT is cut down to its listed fields. Anything else in the record is under no signature. */
215
+ function withSignedTotFieldsOnly(p: BitGraphProof): BitGraphProof {
216
+ const t = p.slotAllocation as unknown as Record<string, unknown> | undefined;
217
+ if (!t || t["version"] !== SLOT_2) return p;
218
+ const kept: Record<string, unknown> = {};
219
+ for (const k of SLOT_2_FIELDS) if (t[k] !== undefined) kept[k] = t[k];
220
+ return { ...p, slotAllocation: kept as unknown as NonNullable<BitGraphProof["slotAllocation"]> };
221
+ }
222
+
214
223
  /** The set rule's reasons: two receipts spend one TOT, or two TOTs claim one position. */
215
224
  export type SpentTwiceCode = "DUPLICATE_TOT" | "DUPLICATE_TOT_POSITION";
216
225
 
@@ -246,7 +255,11 @@ export async function checkSpentOnce(receipts: readonly unknown[]): Promise<{ ve
246
255
  let inForm = false;
247
256
  try { inForm = recordProblem(buildSignedBody(p), "the signed body") === null && recordProblem(totBody, "the TOT body") === null; } catch { inForm = false; }
248
257
  if (!inForm) continue;
249
- const ok = await verifyProofIntegrity({ proof: p, trustAnchors: { requireAtomic: true }, context: createVerificationContext() });
258
+ // The set rule counts a receipt by its signatures and its TOT binding, not by its form. A slot/2 TOT with a
259
+ // field beside its signed ones is refused on its own (R1), and it still stands at its position: the released
260
+ // vectors count it, and a field added to a copy must not take that copy out of this check. So the signatures
261
+ // are checked over the TOT's signed fields alone.
262
+ const ok = await verifyProofIntegrity({ proof: withSignedTotFieldsOnly(p), trustAnchors: { requireAtomic: true }, context: createVerificationContext() });
250
263
  if (!ok.valid) continue;
251
264
  counted.push(i);
252
265
  const t = p.slotAllocation!;