@mikeargento/bitgraph-audit 0.11.0 → 0.12.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.
Files changed (91) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +7 -5
  3. package/dist/anchors.js +1 -1
  4. package/dist/anomalies.js +1 -1
  5. package/dist/attestation.js +1 -1
  6. package/dist/audit.d.ts +1 -1
  7. package/dist/audit.js +2 -2
  8. package/dist/authority.js +1 -1
  9. package/dist/aws-nitro-root-ca.js +1 -1
  10. package/dist/ceilings.js +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/contents-hash.js +1 -1
  13. package/dist/export.js +1 -1
  14. package/dist/exports.js +1 -1
  15. package/dist/floors.js +1 -1
  16. package/dist/genesis.d.ts +141 -0
  17. package/dist/genesis.d.ts.map +1 -0
  18. package/dist/genesis.js +359 -0
  19. package/dist/genesis.js.map +1 -0
  20. package/dist/index.d.ts +6 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +6 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/ingest.js +1 -1
  25. package/dist/publication.d.ts +148 -0
  26. package/dist/publication.d.ts.map +1 -0
  27. package/dist/publication.js +392 -0
  28. package/dist/publication.js.map +1 -0
  29. package/dist/reconstruct.js +1 -1
  30. package/dist/report-json.js +1 -1
  31. package/dist/report-md.js +1 -1
  32. package/dist/rlp.js +1 -1
  33. package/dist/rollup-schedule.d.ts +58 -0
  34. package/dist/rollup-schedule.d.ts.map +1 -0
  35. package/dist/rollup-schedule.js +105 -0
  36. package/dist/rollup-schedule.js.map +1 -0
  37. package/dist/settlement-blobs.d.ts +16 -19
  38. package/dist/settlement-blobs.d.ts.map +1 -1
  39. package/dist/settlement-blobs.js +37 -17
  40. package/dist/settlement-blobs.js.map +1 -1
  41. package/dist/tar.js +1 -1
  42. package/dist/temporal.js +1 -1
  43. package/dist/tot.d.ts +99 -0
  44. package/dist/tot.d.ts.map +1 -0
  45. package/dist/tot.js +242 -0
  46. package/dist/tot.js.map +1 -0
  47. package/dist/types.js +1 -1
  48. package/dist/validity.js +1 -1
  49. package/dist/verify-tiers.js +1 -1
  50. package/dist/witness.js +1 -1
  51. package/package.json +5 -4
  52. package/src/__tests__/{anchors.test.ts → archive/anchors.test.ts} +3 -3
  53. package/src/__tests__/{base-floor.test.ts → archive/base-floor.test.ts} +3 -3
  54. package/src/__tests__/{carrier-tree.test.ts → archive/carrier-tree.test.ts} +3 -3
  55. package/src/__tests__/archive/genesis.test.ts +256 -0
  56. package/src/__tests__/archive/publication.test.ts +210 -0
  57. package/src/__tests__/{settlement.test.ts → archive/settlement.test.ts} +1 -1
  58. package/src/__tests__/tot-v2-vectors.test.ts +87 -0
  59. package/src/__tests__/tot-vectors.test.ts +120 -0
  60. package/src/anchors.ts +1 -1
  61. package/src/anomalies.ts +1 -1
  62. package/src/attestation.ts +1 -1
  63. package/src/audit.ts +2 -2
  64. package/src/authority.ts +1 -1
  65. package/src/aws-nitro-root-ca.ts +1 -1
  66. package/src/ceilings.ts +1 -1
  67. package/src/cli.ts +1 -1
  68. package/src/contents-hash.ts +1 -1
  69. package/src/export.ts +1 -1
  70. package/src/exports.ts +1 -1
  71. package/src/floors.ts +1 -1
  72. package/src/genesis.ts +382 -0
  73. package/src/index.ts +27 -1
  74. package/src/ingest.ts +1 -1
  75. package/src/publication.ts +461 -0
  76. package/src/reconstruct.ts +1 -1
  77. package/src/report-json.ts +1 -1
  78. package/src/report-md.ts +1 -1
  79. package/src/rlp.ts +1 -1
  80. package/src/rollup-schedule.ts +105 -0
  81. package/src/settlement-blobs.ts +41 -21
  82. package/src/tar.ts +1 -1
  83. package/src/temporal.ts +1 -1
  84. package/src/tot.ts +253 -0
  85. package/src/types.ts +1 -1
  86. package/src/validity.ts +1 -1
  87. package/src/verify-tiers.ts +1 -1
  88. package/src/witness.ts +1 -1
  89. /package/src/__tests__/{fixtures → archive/fixtures}/settlement/0x018efc046e94610e2530344caf1574e507a3182e1a975fb25b032ec1434a3f5c.bin +0 -0
  90. /package/src/__tests__/{fixtures → archive/fixtures}/settlement/ceiling-51979918.json +0 -0
  91. /package/src/__tests__/{fixtures → archive/fixtures}/settlement/pointer-51979918.json +0 -0
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
2
 
3
3
  /**
4
4
  * The BLOB layer of a Base ceiling's settlement on Ethereum
@@ -39,8 +39,9 @@ import {
39
39
  type SettlementPointer, type RlpItem,
40
40
  } from "@mikeargento/bitgraph-verify";
41
41
 
42
- /** Base mainnet: block number = (timestamp - l2GenesisTime) / blockTime. */
43
- export const BASE_MAINNET_ROLLUP = Object.freeze({ l2GenesisTime: 1686789347, blockTime: 2 });
42
+ import { BASE_MAINNET_ROLLUP, blocksAt, numberSingularBatches, type RollupSchedule } from "./rollup-schedule.js";
43
+
44
+ export { BASE_MAINNET_ROLLUP, type RollupSchedule };
44
45
 
45
46
  export const BLOB_BYTES = 131072;
46
47
  /** OP Stack blob encoding version 0: (4 * 31 + 3) * 1024 - 4 bytes of data per blob. */
@@ -55,7 +56,7 @@ export interface SettlementBlobsCheck {
55
56
  }
56
57
 
57
58
  export interface SettlementLocated {
58
- /** The Base block the batch places the transaction in, read from the batch's timestamp. */
59
+ /** The Base block the batch places the transaction in: its timestamp's second, and its place among the batches of that second. */
59
60
  baseBlockNumber: number;
60
61
  baseBlockTimestamp: number;
61
62
  /** The batch's parent_hash (the hash of the block before), when the batch form carries one. */
@@ -89,8 +90,8 @@ export interface SettlementBlobsResult {
89
90
  }
90
91
 
91
92
  export interface SettlementBlobsOptions {
92
- /** How the rollup turns a batch timestamp into a block number. Base mainnet by default. */
93
- rollup?: { l2GenesisTime: number; blockTime: number };
93
+ /** When the rollup's blocks are stamped, which places a batch by its timestamp. Base mainnet by default. */
94
+ rollup?: RollupSchedule;
94
95
  /** The L2 chain id, for rebuilding transactions out of span batches. Base mainnet by default. */
95
96
  chainId?: bigint;
96
97
  /** What the ceiling record says, each matched against what the batch says when given. */
@@ -292,18 +293,26 @@ export interface DecodedBatch {
292
293
  blocks: Array<{ number: number; timestamp: number; parentHash: string | null; txs: BatchTx[]; complete: boolean }>;
293
294
  }
294
295
 
296
+ /** A batch already identified by hash, to number a channel that cannot be numbered from its own bytes. */
297
+ export interface BatchPin { number: number; parentHash?: string; txHash?: string }
298
+
295
299
  /**
296
300
  * Batches out of a decompressed channel. Each is an RLP byte string
297
301
  * `batch_version ++ content`. When `complete` is false the stream may be cut:
298
302
  * the last batch is then read as far as it goes and marked incomplete.
303
+ * Singular batches are numbered together once all are read
304
+ * (numberSingularBatches says how); `pin` is used only where the channel
305
+ * alone cannot say.
299
306
  */
300
307
  export function decodeBatches(
301
308
  channel: Uint8Array,
302
309
  complete: boolean,
303
- rollup: { l2GenesisTime: number; blockTime: number },
310
+ rollup: RollupSchedule,
304
311
  chainId: bigint,
312
+ pin?: BatchPin,
305
313
  ): DecodedBatch[] {
306
314
  const out: DecodedBatch[] = [];
315
+ const singular: Array<DecodedBatch["blocks"][number]> = [];
307
316
  const limit = channel.length;
308
317
  let p = 0;
309
318
  while (p < limit) {
@@ -321,8 +330,8 @@ export function decodeBatches(
321
330
  const contentStart = s.start + 1;
322
331
  const contentEnd = Math.min(s.end, limit);
323
332
  if (type === 0) {
324
- const sb = parseSingularBatch(channel, contentStart, contentEnd, !cut, rollup);
325
- if (sb) out.push({ type, offset: p, blocks: [sb] });
333
+ const sb = parseSingularBatch(channel, contentStart, contentEnd, !cut);
334
+ if (sb) { singular.push(sb); out.push({ type, offset: p, blocks: [sb] }); }
326
335
  } else if (type === 1) {
327
336
  if (!cut) out.push({ type, offset: p, blocks: decodeSpanBatch(channel.subarray(contentStart, contentEnd), rollup, chainId) });
328
337
  } else if (!cut) {
@@ -331,6 +340,12 @@ export function decodeBatches(
331
340
  if (cut) break;
332
341
  p = s.end;
333
342
  }
343
+ if (singular.length > 0) {
344
+ const want = pin && { parent: pin.parentHash?.toLowerCase(), tx: pin.txHash?.toLowerCase() };
345
+ const at = want ? singular.findIndex((b) => (want.parent !== undefined && b.parentHash === want.parent) || (want.tx !== undefined && b.txs.some((t) => t.hash === want.tx))) : -1;
346
+ const numbers = numberSingularBatches(singular.map((b) => b.timestamp), rollup, at >= 0 ? { index: at, number: pin!.number } : undefined);
347
+ for (const [k, b] of singular.entries()) b.number = numbers[k]!;
348
+ }
334
349
  return out;
335
350
  }
336
351
 
@@ -338,9 +353,10 @@ export function decodeBatches(
338
353
  * rlp([parent_hash, epoch_number, epoch_hash, timestamp, transaction_list]).
339
354
  * `limit` is where readable bytes end; with `complete` the list must end
340
355
  * exactly there. Returns null when not even the header fields are readable.
356
+ * The block's number is set by decodeBatches.
341
357
  */
342
358
  function parseSingularBatch(
343
- buf: Uint8Array, start: number, limit: number, complete: boolean, rollup: { l2GenesisTime: number; blockTime: number },
359
+ buf: Uint8Array, start: number, limit: number, complete: boolean,
344
360
  ): DecodedBatch["blocks"][number] | null {
345
361
  const outer = rlpSpan(buf, start, limit);
346
362
  if (!outer) return null;
@@ -382,14 +398,7 @@ function parseSingularBatch(
382
398
  }
383
399
  if (listComplete && q !== list.end) throw new TypeError("singular batch: transaction_list overran its length");
384
400
  if (complete && list.end !== outer.end) throw new TypeError("singular batch: bytes after transaction_list");
385
- const number = blockNumberOf(Number(timestamp), rollup);
386
- return { number, timestamp: Number(timestamp), parentHash: bytesToHex(parent.bytes), txs, complete: listComplete };
387
- }
388
-
389
- function blockNumberOf(timestamp: number, rollup: { l2GenesisTime: number; blockTime: number }): number {
390
- const n = (timestamp - rollup.l2GenesisTime) / rollup.blockTime;
391
- if (!Number.isInteger(n) || n < 0) throw new TypeError(`batch timestamp ${timestamp} is not on the rollup's block grid`);
392
- return n;
401
+ return { number: -1, timestamp: Number(timestamp), parentHash: bytesToHex(parent.bytes), txs, complete: listComplete };
393
402
  }
394
403
 
395
404
  // ── Span batches (type 1), rebuilt into raw transactions ───────────────────
@@ -434,7 +443,7 @@ class Reader {
434
443
  * here into their raw form so they can be hashed.
435
444
  */
436
445
  export function decodeSpanBatch(
437
- data: Uint8Array, rollup: { l2GenesisTime: number; blockTime: number }, chainId: bigint,
446
+ data: Uint8Array, rollup: RollupSchedule, chainId: bigint,
438
447
  ): DecodedBatch["blocks"] {
439
448
  const r = new Reader(data);
440
449
  const relTimestamp = r.uvarint();
@@ -500,8 +509,14 @@ export function decodeSpanBatch(
500
509
  }
501
510
  return { raw, hash: bytesToHex(keccak256(raw)) };
502
511
  });
512
+ // A span batch counts on from its first block's time one block time apiece, which only describes
513
+ // blocks that each have a timestamp of their own; one reaching into shared seconds is refused.
503
514
  const firstTimestamp = rollup.l2GenesisTime + Number(relTimestamp);
504
- const firstBlock = blockNumberOf(firstTimestamp, rollup);
515
+ const first = blocksAt(firstTimestamp, rollup);
516
+ if (!first) throw new TypeError(`batch timestamp ${firstTimestamp} is not on the rollup's schedule`);
517
+ const lastTimestamp = firstTimestamp + (blockCount - 1) * rollup.blockTime;
518
+ if (first.count !== 1 || blocksAt(lastTimestamp, rollup)?.count !== 1) throw new TypeError(`span batch: its blocks from ${firstTimestamp} to ${lastTimestamp} share their seconds, so their numbers cannot be read from it`);
519
+ const firstBlock = first.first;
505
520
  const blocks: DecodedBatch["blocks"] = [];
506
521
  let k = 0;
507
522
  for (let b = 0; b < blockCount; b++) {
@@ -635,7 +650,12 @@ export async function verifySettlementBlobs(
635
650
  if (pointer.channel?.compression && pointer.channel.compression !== decomp.compression) return fail("decompress", `the channel is ${decomp.compression}, the pointer says ${pointer.channel.compression}`);
636
651
  let batches: DecodedBatch[];
637
652
  try {
638
- batches = decodeBatches(decomp.bytes, complete, rollup, chainId);
653
+ const pinTx = (options.expect?.txHash ?? pointer.located?.txHash)?.toLowerCase();
654
+ batches = decodeBatches(decomp.bytes, complete, rollup, chainId, {
655
+ number: pointer.baseBlockNumber,
656
+ ...(options.expect?.baseParentHash ? { parentHash: options.expect.baseParentHash } : {}),
657
+ ...(pinTx ? { txHash: pinTx } : {}),
658
+ });
639
659
  } catch (e) {
640
660
  return fail("batches", (e as Error).message);
641
661
  }
package/src/tar.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
2
 
3
3
  /**
4
4
  * Minimal streaming tar reader.
package/src/temporal.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
2
 
3
3
  /**
4
4
  * bitgraph-audit temporal bounds
package/src/tot.ts ADDED
@@ -0,0 +1,253 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * The reference check for the TOT receipt formats: bitgraph-tot-v1 (spec/BITGRAPH-TOT-1.md) and bitgraph-tot-v2
5
+ * (spec/BITGRAPH-TOT-2.md), which is v1 with one addition: the TOT may carry a public floor, a block of a public
6
+ * chain signed into the TOT body (record version bitgraph/slot/2). Every offline check is v1's. Looking the floor's
7
+ * block up is a separate, optional step (checkTotFloor) that needs the network and never changes a verdict.
8
+ *
9
+ * Two checks, as the spec defines them:
10
+ *
11
+ * verifyTotReceipt one receipt: its form (section 7, R1), then the full attested check that every BitGraph tool
12
+ * runs (verifyAttested in @mikeargento/bitgraph-verify: the TOT and its binding, the count order,
13
+ * both signatures, the Nitro document, its binding to this receipt, the measurement, and the
14
+ * file when given), limited to the measurements this format accepts.
15
+ * checkSpentOnce a set of receipts: refused when two different receipts spend one TOT (section 8). One receipt
16
+ * on its own cannot show this, so it is a check over the set. It counts every receipt whose two
17
+ * signatures and TOT binding hold (R2 to R6), attested or not: a key that signed one TOT into two
18
+ * receipts has spent it twice whoever holds the key, and a receipt whose signatures fail is
19
+ * nobody's and cannot refuse another.
20
+ */
21
+
22
+ import {
23
+ verifyAttested, verifyProofIntegrity, createVerificationContext, computeSignedBodyHash, computeSlotRecordHash, buildSignedBody,
24
+ slotFloorProblem, totFloorOf, checkFloorOnline, checkFloorAgainstBlock,
25
+ type BitGraphProof, type NitroCheck, type SlotFloor, type FloorCheck, type RpcBlockHeader,
26
+ } from "@mikeargento/bitgraph-verify";
27
+
28
+ /** The first format's name. */
29
+ export const TOT_FORMAT = "bitgraph-tot-v1";
30
+ /** The second format's name: v1, and a TOT may carry a public floor. */
31
+ export const TOT_FORMAT_V2 = "bitgraph-tot-v2";
32
+
33
+ /** The enclave measurements (PCR0, lowercase hex) bitgraph-tot-v1 accepts by default: the v13 image. */
34
+ export const TOT_V1_MEASUREMENTS: readonly string[] = Object.freeze([
35
+ "adaad0bef62292d35197ae8db19e40685229f1a1e6070a7c77a148c4ada88ee66a1ca50819eebc2017c6716a49f2692f",
36
+ ]);
37
+
38
+ /** The enclave measurements bitgraph-tot-v2 accepts by default: the v14 image, the first that signs a floor. */
39
+ export const TOT_V2_MEASUREMENTS: readonly string[] = Object.freeze([
40
+ "10273c68951dd81156364b4b86d240208f37a1999dac27d54ebf3fc7a2fc723a1e2e852b91528d0a24aaf0544af6c52f",
41
+ ]);
42
+
43
+ /** Every measurement the reference check accepts by default: both formats'. */
44
+ export const TOT_MEASUREMENTS: readonly string[] = Object.freeze([...TOT_V1_MEASUREMENTS, ...TOT_V2_MEASUREMENTS]);
45
+
46
+ /** The two TOT record versions. */
47
+ const SLOT_1 = "bitgraph/slot/1";
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";
51
+
52
+ export interface TotVerdict {
53
+ verdict: "ACCEPT" | "REJECT";
54
+ /** Why it was refused; absent on ACCEPT. */
55
+ reason?: string;
56
+ /** Whether a file was compared with the receipt's digest. */
57
+ file: "compared" | "not-compared";
58
+ /** The attestation document's own time, when the receipt was accepted (ISO 8601). */
59
+ attestedAt?: string;
60
+ /** The attestation's checks, in order, when the document was read. */
61
+ checks: NitroCheck[];
62
+ /** The public floor signed into the TOT, when the receipt was accepted and its TOT carries one. Not yet looked up. */
63
+ floor?: SlotFloor;
64
+ }
65
+
66
+ const B64_32 = (s: unknown): boolean => {
67
+ if (typeof s !== "string") return false;
68
+ {
69
+ const b = Buffer.from(s, "base64");
70
+ return b.length === 32 && b.toString("base64") === s;
71
+ }
72
+ };
73
+ const DEC = /^(0|[1-9][0-9]*)$/;
74
+ const HEX96 = /^[0-9a-f]{96}$/;
75
+ const isObject = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v);
76
+
77
+ /** R1, the receipt's form: every field this format requires, in the shape it requires. Null when it is in form. */
78
+ export function totFormProblem(receipt: unknown): string | null {
79
+ if (!isObject(receipt)) return "the receipt is not a JSON object";
80
+ const r = receipt;
81
+ if (r["version"] !== "bitgraph/1") return 'version must be "bitgraph/1"';
82
+ const a = r["artifact"];
83
+ if (!isObject(a) || a["hashAlg"] !== "sha256" || !B64_32(a["digestB64"])) return "artifact must be {hashAlg: \"sha256\", digestB64: 32 bytes in canonical base64}";
84
+ const c = r["commit"];
85
+ if (!isObject(c)) return "commit is missing";
86
+ if (c["atomic"] !== true) return "commit.atomic must be true";
87
+ if (!B64_32(c["nonceB64"])) return "commit.nonceB64 must be 32 bytes in canonical base64";
88
+ if (typeof c["counter"] !== "string" || !DEC.test(c["counter"])) return "commit.counter must be a decimal string";
89
+ if (typeof c["slotCounter"] !== "string" || !DEC.test(c["slotCounter"])) return "commit.slotCounter must be a decimal string";
90
+ if (!B64_32(c["slotHashB64"])) return "commit.slotHashB64 must be 32 bytes in canonical base64";
91
+ if (!B64_32(c["epochId"])) return "commit.epochId must be 32 bytes in canonical base64";
92
+ if (c["prevB64"] !== undefined && !B64_32(c["prevB64"])) return "commit.prevB64, when present, must be 32 bytes in canonical base64";
93
+ if (c["chainId"] !== "bitgraph:main") return 'commit.chainId must be "bitgraph:main"';
94
+ const s = r["signer"];
95
+ if (!isObject(s) || !B64_32(s["publicKeyB64"]) || typeof s["signatureB64"] !== "string") return "signer must carry publicKeyB64 (32 bytes) and signatureB64";
96
+ const e = r["environment"];
97
+ if (!isObject(e)) return "environment is missing";
98
+ if (e["enforcement"] !== "measured-tee") return 'environment.enforcement must be "measured-tee"';
99
+ if (typeof e["measurement"] !== "string" || !HEX96.test(e["measurement"])) return "environment.measurement must be 96 lowercase hex characters";
100
+ const at = e["attestation"];
101
+ if (!isObject(at) || at["format"] !== "aws-nitro" || typeof at["reportB64"] !== "string" || at["reportB64"].length === 0) return 'environment.attestation must be {format: "aws-nitro", reportB64}';
102
+ const t = r["slotAllocation"];
103
+ if (!isObject(t)) return "slotAllocation (the TOT) is missing";
104
+ if (t["version"] !== SLOT_1 && t["version"] !== SLOT_2) return 'slotAllocation.version must be "bitgraph/slot/1" or "bitgraph/slot/2"';
105
+ // 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.
106
+ const floor = slotFloorProblem(t);
107
+ if (floor) return floor;
108
+ 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";
109
+ if (typeof t["counter"] !== "string" || !DEC.test(t["counter"])) return "slotAllocation.counter must be a decimal string";
110
+ if (t["time"] !== undefined) return "slotAllocation.time must be absent";
111
+ 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";
112
+ if (t["chainId"] !== "bitgraph:main") return 'slotAllocation.chainId must be "bitgraph:main"';
113
+ if (typeof t["signatureB64"] !== "string") return "slotAllocation.signatureB64 is missing";
114
+ return null;
115
+ }
116
+
117
+ const PRINTABLE_ASCII = /^[\x20-\x7e]*$/;
118
+
119
+ /** R2: a signed record holds only strings, booleans and objects, with printable ASCII in every key and string. */
120
+ function recordProblem(value: unknown, path: string): string | null {
121
+ if (typeof value === "boolean") return null;
122
+ if (typeof value === "string") return PRINTABLE_ASCII.test(value) ? null : `${path} holds a character outside printable ASCII`;
123
+ if (!isObject(value)) return `${path} is not a string, boolean or object`;
124
+ for (const [k, v] of Object.entries(value)) {
125
+ if (!PRINTABLE_ASCII.test(k)) return `${path} has a key outside printable ASCII`;
126
+ const p = recordProblem(v, `${path}.${k}`);
127
+ if (p) return p;
128
+ }
129
+ return null;
130
+ }
131
+
132
+ /** The check of one receipt, with the file when it is given. */
133
+ export async function verifyTotReceipt(opts: {
134
+ receipt: unknown;
135
+ file?: Uint8Array;
136
+ /** The accepted measurements. Default: TOT_MEASUREMENTS, both formats'. */
137
+ measurements?: readonly string[];
138
+ /** A different root certificate (DER), for tests against a non-AWS chain. */
139
+ rootDer?: Uint8Array;
140
+ }): Promise<TotVerdict> {
141
+ const file = opts.file !== undefined ? "compared" : "not-compared";
142
+ const form = totFormProblem(opts.receipt);
143
+ if (form) return { verdict: "REJECT", reason: `R1 form: ${form}`, file, checks: [] };
144
+ const p = opts.receipt as BitGraphProof;
145
+ const { signatureB64: _sig, ...totBody } = p.slotAllocation as unknown as Record<string, unknown>;
146
+ const records = recordProblem(buildSignedBody(p), "the signed body") ?? recordProblem(totBody, "the TOT body");
147
+ if (records) return { verdict: "REJECT", reason: `R2 canonical records: ${records}`, file, checks: [] };
148
+ const r = await verifyAttested({
149
+ proof: opts.receipt as BitGraphProof,
150
+ ...(opts.file !== undefined ? { bytes: opts.file } : {}),
151
+ pcr0: opts.measurements ?? TOT_MEASUREMENTS,
152
+ ...(opts.rootDer ? { rootDer: opts.rootDer } : {}),
153
+ });
154
+ if (!r.valid) return { verdict: "REJECT", reason: r.reason ?? "the receipt does not verify", file, checks: r.checks };
155
+ return {
156
+ verdict: "ACCEPT",
157
+ file,
158
+ ...(r.attestedAtMs !== null ? { attestedAt: new Date(r.attestedAtMs).toISOString() } : {}),
159
+ checks: r.checks,
160
+ ...(totFloorOf(p) ? { floor: totFloorOf(p)! } : {}),
161
+ };
162
+ }
163
+
164
+ /**
165
+ * The optional online step for a receipt whose TOT carries a floor (bitgraph-tot-v2, section 4): look the block up
166
+ * on its chain. It is run only on a receipt the offline check already accepted, and whatever it answers, that
167
+ * verdict stands.
168
+ *
169
+ * confirmed the chain holds that block: the TOT was made after it. The block's time and the gap from it to
170
+ * the attestation's time are reported; `stale` is set when maxFloorGapMs is given and exceeded.
171
+ * not-confirmed the chain has no such block, or another one at that number: the floor shows nothing.
172
+ * not-checked the lookup could not be made.
173
+ * none the TOT carries no floor.
174
+ *
175
+ * Pass `block` (what the chain says, or null for "no such block") to apply the rule with no network.
176
+ */
177
+ export async function checkTotFloor(opts: {
178
+ receipt: unknown;
179
+ /** The accepted receipt's attestation time, from its verdict's attestedAt. */
180
+ attestedAt?: string;
181
+ /** Flag the floor as stale when the attestation is more than this long after the block. */
182
+ maxFloorGapMs?: number;
183
+ rpcUrl?: string;
184
+ fetcher?: typeof fetch;
185
+ block?: (Partial<RpcBlockHeader> & { timestampMs?: string }) | null;
186
+ }): Promise<FloorCheck> {
187
+ if (totFormProblem(opts.receipt) !== null) return { status: "none" };
188
+ const proof = opts.receipt as BitGraphProof;
189
+ const at = opts.attestedAt !== undefined ? Date.parse(opts.attestedAt) : NaN;
190
+ const common = {
191
+ proof,
192
+ ...(Number.isFinite(at) ? { attestedAtMs: at } : {}),
193
+ ...(opts.maxFloorGapMs !== undefined ? { maxGapMs: opts.maxFloorGapMs } : {}),
194
+ };
195
+ if (opts.block !== undefined) return checkFloorAgainstBlock({ ...common, block: opts.block });
196
+ return checkFloorOnline({ ...common, ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}), ...(opts.fetcher ? { fetcher: opts.fetcher } : {}) });
197
+ }
198
+
199
+ /** The set rule's reasons: two receipts spend one TOT, or two TOTs claim one position. */
200
+ export type SpentTwiceCode = "DUPLICATE_TOT" | "DUPLICATE_TOT_POSITION";
201
+
202
+ export interface SpentTwice {
203
+ /** DUPLICATE_TOT: the receipts carry the same TOT. DUPLICATE_TOT_POSITION: different TOTs at one position (the same
204
+ * key, epoch, chain and count). */
205
+ code: SpentTwiceCode;
206
+ /** The indexes, in the set given, of the receipts that spend it. */
207
+ receipts: number[];
208
+ }
209
+
210
+ /**
211
+ * The set check (section 8): every TOT is spent once. Two receipts that differ in their signed bodies and carry the same
212
+ * TOT, or two different TOTs at one position (the same key, epoch, chain and count), are refused together. The same
213
+ * receipt given twice is one receipt, not two. Only receipts whose signatures and TOT binding hold are counted.
214
+ */
215
+ export async function checkSpentOnce(receipts: readonly unknown[]): Promise<{ verdict: "ACCEPT" | "REJECT"; reason?: SpentTwiceCode; spentTwice: SpentTwice[]; counted: number[] }> {
216
+ const byTot = new Map<string, Map<string, number[]>>();
217
+ const byPosition = new Map<string, Map<string, number[]>>();
218
+ const add = (m: Map<string, Map<string, number[]>>, key: string, body: string, i: number): void => {
219
+ const bodies = m.get(key) ?? new Map<string, number[]>();
220
+ const list = bodies.get(body) ?? [];
221
+ list.push(i);
222
+ bodies.set(body, list);
223
+ m.set(key, bodies);
224
+ };
225
+ const counted: number[] = [];
226
+ for (const [i, r] of receipts.entries()) {
227
+ if (!isObject(r) || !isObject(r["slotAllocation"]) || !isObject(r["commit"]) || r["commit"]["atomic"] !== true) continue;
228
+ const p = r as unknown as BitGraphProof;
229
+ // R2: both signed records hold only what the format allows.
230
+ const { signatureB64: _sig, ...totBody } = r["slotAllocation"];
231
+ let inForm = false;
232
+ try { inForm = recordProblem(buildSignedBody(p), "the signed body") === null && recordProblem(totBody, "the TOT body") === null; } catch { inForm = false; }
233
+ if (!inForm) continue;
234
+ const ok = await verifyProofIntegrity({ proof: p, trustAnchors: { requireAtomic: true }, context: createVerificationContext() });
235
+ if (!ok.valid) continue;
236
+ counted.push(i);
237
+ const t = p.slotAllocation!;
238
+ const body = computeSignedBodyHash(p);
239
+ const totHash = Buffer.from(computeSlotRecordHash(t)).toString("base64");
240
+ add(byTot, totHash, body, i);
241
+ add(byPosition, `${t.publicKeyB64}|${t.epochId}|${t.chainId ?? ""}|${t.counter}`, `${totHash}|${body}`, i);
242
+ }
243
+ const spentTwice: SpentTwice[] = [];
244
+ for (const bodies of byTot.values()) {
245
+ if (bodies.size > 1) spentTwice.push({ code: "DUPLICATE_TOT", receipts: [...bodies.values()].map((l) => l[0]!).sort((a, b) => a - b) });
246
+ }
247
+ for (const bodies of byPosition.values()) {
248
+ const tots = new Set([...bodies.keys()].map((k) => k.split("|")[0]));
249
+ if (tots.size > 1) spentTwice.push({ code: "DUPLICATE_TOT_POSITION", receipts: [...bodies.values()].map((l) => l[0]!).sort((a, b) => a - b) });
250
+ }
251
+ const first = spentTwice[0];
252
+ return first ? { verdict: "REJECT", reason: first.code, spentTwice, counted } : { verdict: "ACCEPT", spentTwice, counted };
253
+ }
package/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
2
 
3
3
  /**
4
4
  * bitgraph-audit types
package/src/validity.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
2
 
3
3
  /**
4
4
  * bitgraph-audit intrinsic validity (internal)
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
2
 
3
3
  /**
4
4
  * bitgraph-audit verification tiers
package/src/witness.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
2
 
3
3
  /**
4
4
  * bitgraph-audit anchor witness verification