@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
@@ -0,0 +1,461 @@
1
+ // Copyright (c) 2025-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * Hourly publication: the formats and the offline check.
5
+ *
6
+ * Every hour the operator writes one small transaction to Base (an "hourly write") holding the root of a tree over the
7
+ * chain hashes of that hour's BitGraphs and a link to the previous hourly write. Right after the write lands, the
8
+ * operator binds a short note naming the write's block as an ordinary BitGraph (the "floor"): it is provably after that
9
+ * block, and every later BitGraph of the epoch is after it by its count. Each proof can then carry, in its unsigned
10
+ * metadata, a `bitgraph-publication/1` block linking it to its hour's write.
11
+ *
12
+ * hourly write calldata (bitgraph-hour/1), big-endian:
13
+ * "BGH1" | flags (1: bit 0 = carries the epoch's public key) | epoch id (32) | first count (8) | last count (8)
14
+ * | leaves (4) | root (32, zeros when leaves = 0) | previous link (32, zeros for the first write ever)
15
+ * | epoch public key (32, only when flag bit 0 is set)
16
+ * link = SHA-256(calldata)
17
+ * tree = RFC 6962 over leaf = SHA-256(0x00 || published chain hash), in count order (the tree BitGraph uses for
18
+ * files); the published chain hash is computeChainHash over the proof without its unsigned metadata
19
+ *
20
+ * A write covers one epoch's counts first..last. An hour in which nothing was made still gets a write, with leaves = 0,
21
+ * so the record shows the quiet hour. The first write of an epoch carries the epoch's public key.
22
+ *
23
+ * checkPublication() needs nothing live. It checks: the proof's chain hash walks up its path to the root in the write;
24
+ * the write's transaction is the one the evidence names, sits in the block's transaction trie, and the block header
25
+ * hashes to the block hash; the proof's count is inside the write's range; and, when there is a floor, that the floor
26
+ * BitGraph is in a published tree, binds the note it names, and comes before the proof in the same epoch. What it
27
+ * cannot check offline is that the block is on Base's canonical chain: compare `ceiling.blockHash` (and the floor's
28
+ * block hash) with Base from any source you trust.
29
+ */
30
+
31
+ import { sha256 } from "@noble/hashes/sha256";
32
+ import {
33
+ computeChainHash,
34
+ verifyProofIntegrity,
35
+ createVerificationContext,
36
+ merkleLeafHash,
37
+ merkleRoot,
38
+ merklePath,
39
+ merkleRootFromPath,
40
+ decodeHeader,
41
+ decodeEip1559,
42
+ mptVerify,
43
+ txTrieKey,
44
+ evmHexToBytes,
45
+ evmBytesToHex,
46
+ b64ToBytes,
47
+ bytesToB64,
48
+ } from "@mikeargento/bitgraph-verify";
49
+
50
+ export const PUBLICATION_METADATA_KEY = "bitgraph-publication/1" as const;
51
+ export const HOUR_RECORD_FORMAT = "bitgraph-hour/1" as const;
52
+ export const FLOOR_NOTE_FORMAT = "bitgraph-hour-floor/1" as const;
53
+ /** "BGH1": BitGraph hourly write, version 1. */
54
+ export const HOUR_MAGIC = new Uint8Array([0x42, 0x47, 0x48, 0x31]);
55
+ const FLAG_KEY = 1;
56
+
57
+ // ── small byte helpers ──────────────────────────────────────────────────────
58
+
59
+ const HEX = "0123456789abcdef";
60
+ export function toHex(b: Uint8Array): string { let s = ""; for (const x of b) s += HEX[x >> 4]! + HEX[x & 15]!; return s; }
61
+ function fromHex(h: string): Uint8Array | null {
62
+ const t = h.replace(/^0x/, "");
63
+ if (t.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(t)) return null;
64
+ const out = new Uint8Array(t.length / 2);
65
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(t.slice(i * 2, i * 2 + 2), 16);
66
+ return out;
67
+ }
68
+ function b64To32(b64: string, what: string): Uint8Array {
69
+ const b = b64ToBytes(b64);
70
+ if (!b || b.length !== 32) throw new TypeError(`${what} is not 32 bytes of base64`);
71
+ return b;
72
+ }
73
+ function eq(a: Uint8Array, b: Uint8Array): boolean {
74
+ if (a.length !== b.length) return false;
75
+ let d = 0;
76
+ for (let i = 0; i < a.length; i++) d |= a[i]! ^ b[i]!;
77
+ return d === 0;
78
+ }
79
+ function u64(n: number): Uint8Array {
80
+ if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count out of range");
81
+ const out = new Uint8Array(8);
82
+ let v = BigInt(n);
83
+ for (let i = 7; i >= 0; i--) { out[i] = Number(v & 0xffn); v >>= 8n; }
84
+ return out;
85
+ }
86
+ function readU64(b: Uint8Array, at: number): number {
87
+ let v = 0n;
88
+ for (let i = 0; i < 8; i++) v = (v << 8n) | BigInt(b[at + i]!);
89
+ if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new RangeError("count out of range");
90
+ return Number(v);
91
+ }
92
+ function u32(n: number): Uint8Array {
93
+ if (!Number.isInteger(n) || n < 0 || n > 0xffffffff) throw new RangeError("leaf count out of range");
94
+ return new Uint8Array([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);
95
+ }
96
+ const readU32 = (b: Uint8Array, at: number): number => ((b[at]! << 24) >>> 0) + (b[at + 1]! << 16) + (b[at + 2]! << 8) + b[at + 3]!;
97
+
98
+ // ── the hourly write ────────────────────────────────────────────────────────
99
+
100
+ export interface HourWrite {
101
+ epochId: string; // standard base64, 32 bytes
102
+ first: number; // first count covered (0 with leaves = 0 when the epoch has none yet)
103
+ last: number; // last count covered
104
+ leaves: number; // how many BitGraphs the tree holds
105
+ rootHex: string; // 64 hex, zeros when leaves = 0
106
+ prevLinkHex: string; // 64 hex, zeros for the first write ever
107
+ epochPublicKeyB64?: string; // only on an epoch's first write
108
+ }
109
+
110
+ export function encodeHourCalldata(w: HourWrite): Uint8Array {
111
+ const root = fromHex(w.rootHex), prev = fromHex(w.prevLinkHex);
112
+ if (!root || root.length !== 32) throw new TypeError("root is not 32 bytes of hex");
113
+ if (!prev || prev.length !== 32) throw new TypeError("previous link is not 32 bytes of hex");
114
+ if (w.leaves === 0 ? !eq(root, new Uint8Array(32)) : w.last < w.first) throw new RangeError("range and leaves disagree");
115
+ const key = w.epochPublicKeyB64 !== undefined ? b64To32(w.epochPublicKeyB64, "the epoch public key") : null;
116
+ const out = new Uint8Array(121 + (key ? 32 : 0));
117
+ out.set(HOUR_MAGIC, 0);
118
+ out[4] = key ? FLAG_KEY : 0;
119
+ out.set(b64To32(w.epochId, "the epoch id"), 5);
120
+ out.set(u64(w.first), 37);
121
+ out.set(u64(w.last), 45);
122
+ out.set(u32(w.leaves), 53);
123
+ out.set(root, 57);
124
+ out.set(prev, 89);
125
+ if (key) out.set(key, 121);
126
+ return out;
127
+ }
128
+
129
+ export function decodeHourCalldata(b: Uint8Array): HourWrite | null {
130
+ if (b.length !== 121 && b.length !== 153) return null;
131
+ if (!eq(b.subarray(0, 4), HOUR_MAGIC)) return null;
132
+ const flags = b[4]!;
133
+ if ((flags & ~FLAG_KEY) !== 0) return null;
134
+ const hasKey = (flags & FLAG_KEY) !== 0;
135
+ if (hasKey !== (b.length === 153)) return null;
136
+ try {
137
+ const w: HourWrite = {
138
+ epochId: bytesToB64(b.subarray(5, 37)),
139
+ first: readU64(b, 37),
140
+ last: readU64(b, 45),
141
+ leaves: readU32(b, 53),
142
+ rootHex: toHex(b.subarray(57, 89)),
143
+ prevLinkHex: toHex(b.subarray(89, 121)),
144
+ };
145
+ if (hasKey) w.epochPublicKeyB64 = bytesToB64(b.subarray(121, 153));
146
+ if (w.leaves > 0 && w.last < w.first) return null;
147
+ return w;
148
+ } catch {
149
+ return null;
150
+ }
151
+ }
152
+
153
+ /** The link the next write names: SHA-256 of this write's calldata, hex. */
154
+ export const hourLink = (calldata: Uint8Array): string => toHex(sha256(calldata));
155
+
156
+ // ── the hour's tree ─────────────────────────────────────────────────────────
157
+
158
+ /** A BitGraph's leaf in its hour's tree: SHA-256(0x00 || its published chain hash). */
159
+ export function hourLeaf(chainHashB64: string): Uint8Array {
160
+ return merkleLeafHash(b64To32(chainHashB64, "the chain hash"));
161
+ }
162
+
163
+ export interface HourTree { rootHex: string; paths: string[] }
164
+
165
+ /** The root over chain hashes in count order, and each one's path (siblings from the leaf up, concatenated, base64). */
166
+ export function hourTree(chainHashesB64: readonly string[]): HourTree {
167
+ if (chainHashesB64.length === 0) return { rootHex: "0".repeat(64), paths: [] };
168
+ const leaves = chainHashesB64.map(hourLeaf);
169
+ const rootHex = toHex(merkleRoot(leaves));
170
+ const paths = leaves.map((_, i) => {
171
+ const p = merklePath(leaves, i);
172
+ const cat = new Uint8Array(p.length * 32);
173
+ p.forEach((s, j) => cat.set(s, j * 32));
174
+ return bytesToB64(cat);
175
+ });
176
+ return { rootHex, paths };
177
+ }
178
+
179
+ /** The root a chain hash reaches by its path (siblings concatenated, base64) in a tree of `leaves`; null when the path is malformed. */
180
+ export function pathRoot(chainHashB64: string, index: number, leaves: number, pathB64: string): string | null {
181
+ return rootFromPath(chainHashB64, index, leaves, pathB64);
182
+ }
183
+
184
+ function rootFromPath(chainHashB64: string, index: number, leaves: number, pathB64: string): string | null {
185
+ const cat = pathB64 === "" ? new Uint8Array(0) : b64ToBytes(pathB64);
186
+ if (!cat || cat.length % 32 !== 0) return null;
187
+ const sibs: Uint8Array[] = [];
188
+ for (let i = 0; i < cat.length; i += 32) sibs.push(cat.subarray(i, i + 32));
189
+ let leaf: Uint8Array;
190
+ try { leaf = hourLeaf(chainHashB64); } catch { return null; }
191
+ const r = merkleRootFromPath(leaf, index, leaves, sibs);
192
+ return r ? toHex(r) : null;
193
+ }
194
+
195
+ // ── the floor note ──────────────────────────────────────────────────────────
196
+
197
+ export interface FloorNote {
198
+ chainId: number;
199
+ blockNumber: number;
200
+ blockHash: string; // 0x + 64 hex, lowercase
201
+ blockTimestamp: number; // unix seconds, from the block header
202
+ txHash: string; // 0x + 64 hex, lowercase
203
+ writeLinkHex: string; // the link of the write it binds back
204
+ }
205
+
206
+ export function floorNoteText(n: FloorNote): string {
207
+ return [
208
+ `BitGraph hourly publication floor (${FLOOR_NOTE_FORMAT})`,
209
+ `chain: base ${n.chainId}`,
210
+ `block: ${n.blockNumber}`,
211
+ `block hash: ${n.blockHash.toLowerCase()}`,
212
+ `block time: ${n.blockTimestamp}`,
213
+ `transaction: ${n.txHash.toLowerCase()}`,
214
+ `write: ${n.writeLinkHex.toLowerCase()}`,
215
+ "",
216
+ ].join("\n");
217
+ }
218
+
219
+ export function parseFloorNote(text: string): FloorNote | null {
220
+ const m = /^BitGraph hourly publication floor \(bitgraph-hour-floor\/1\)\nchain: base (\d+)\nblock: (\d+)\nblock hash: (0x[0-9a-f]{64})\nblock time: (\d+)\ntransaction: (0x[0-9a-f]{64})\nwrite: ([0-9a-f]{64})\n$/.exec(text);
221
+ if (!m) return null;
222
+ const n: FloorNote = { chainId: Number(m[1]), blockNumber: Number(m[2]), blockHash: m[3]!, blockTimestamp: Number(m[4]), txHash: m[5]!, writeLinkHex: m[6]! };
223
+ return Number.isSafeInteger(n.chainId) && Number.isSafeInteger(n.blockNumber) && Number.isSafeInteger(n.blockTimestamp) ? n : null;
224
+ }
225
+
226
+ /** The digest a floor BitGraph binds: SHA-256 of the note's UTF-8 bytes, standard base64. */
227
+ export const floorNoteDigestB64 = (text: string): string => bytesToB64(sha256(new TextEncoder().encode(text)));
228
+
229
+ // ── what a proof carries ────────────────────────────────────────────────────
230
+
231
+ /** The write's evidence: enough to tie the calldata to a block without asking anyone. */
232
+ export interface WriteEvidence {
233
+ chain: "base";
234
+ chainId: number;
235
+ writer: string; // 0x address, lowercase
236
+ txHash: string; // 0x + 64 hex
237
+ blockNumber: number;
238
+ blockHash: string; // 0x + 64 hex
239
+ blockTimestamp: number;
240
+ headerRlp: string; // 0x hex; keccak256 of it is the block hash
241
+ txIndex: number;
242
+ txInclusionProof: string[]; // 0x hex trie nodes, from the header's transactionsRoot to the transaction
243
+ rawTx: string; // 0x hex, the signed transaction; keccak256 of it is txHash
244
+ }
245
+
246
+ export interface PublicationFloor {
247
+ /** The floor BitGraph itself, whole. */
248
+ proof: Record<string, unknown>;
249
+ /** The note it binds. */
250
+ note: string;
251
+ /** Where the floor sits: in the tree of the write whose calldata this is (the proof's own write, or the one it links back to). */
252
+ hourCalldata: string; // 0x hex
253
+ leafIndex: number;
254
+ path: string; // base64, siblings concatenated
255
+ }
256
+
257
+ export interface PublicationBlock {
258
+ format: typeof PUBLICATION_METADATA_KEY;
259
+ epochId: string;
260
+ counter: string;
261
+ chainHashB64: string;
262
+ leafIndex: number;
263
+ path: string;
264
+ calldata: string; // 0x hex, the hourly write's calldata
265
+ write: WriteEvidence;
266
+ /** Null when the proof came before its epoch's first floor. */
267
+ floor: PublicationFloor | null;
268
+ }
269
+
270
+ export function publicationOf(proof: unknown): PublicationBlock | null {
271
+ const md = (proof as { metadata?: Record<string, unknown> } | null)?.metadata;
272
+ const b = md?.[PUBLICATION_METADATA_KEY] as PublicationBlock | undefined;
273
+ if (!b || typeof b !== "object" || b.format !== PUBLICATION_METADATA_KEY) return null;
274
+ return b;
275
+ }
276
+
277
+ // ── the check ───────────────────────────────────────────────────────────────
278
+
279
+ export interface PublicationCheck {
280
+ ok: boolean;
281
+ problems: string[];
282
+ /** The block that published the proof's hour: the proof existed by it. Confirm the hash is on Base. */
283
+ ceiling: { chainId: number; blockNumber: number; blockHash: string; blockTimestamp: number; txHash: string } | null;
284
+ /** The block the proof is provably after, when it has a floor. Confirm the hash is on Base. */
285
+ floor: { chainId: number; blockNumber: number; blockHash: string; blockTimestamp: number; floorCounter: string } | null;
286
+ write: HourWrite | null;
287
+ }
288
+
289
+ export interface PublicationCheckOptions {
290
+ /** The writer address to accept (lowercase 0x). When given, the transaction must be signed by it and sent to itself. */
291
+ writer?: string;
292
+ /** The chain id to accept; default 8453 (Base mainnet). */
293
+ chainId?: number;
294
+ }
295
+
296
+ /**
297
+ * The fingerprint a BitGraph is published under: its chain hash (computeChainHash) taken over the proof without its
298
+ * `metadata`. Metadata is unsigned and added after the fact (a tree member's block, this publication block), so a copy
299
+ * of a proof with or without it publishes under the same leaf.
300
+ */
301
+ export function publishedChainHash(proof: Record<string, unknown>): string {
302
+ if (!("metadata" in proof)) return computeChainHash(proof);
303
+ const out: Record<string, unknown> = {};
304
+ for (const [k, v] of Object.entries(proof)) if (k !== "metadata") out[k] = v;
305
+ return computeChainHash(out);
306
+ }
307
+
308
+ export function checkPublication(proofIn: unknown, opts: PublicationCheckOptions = {}): PublicationCheck {
309
+ const problems: string[] = [];
310
+ const out: PublicationCheck = { ok: false, problems, ceiling: null, floor: null, write: null };
311
+ const proof = proofIn as Record<string, unknown>;
312
+ const b = publicationOf(proof);
313
+ if (!b) { problems.push("the proof carries no bitgraph-publication/1 block"); return out; }
314
+ const commit = (proof["commit"] ?? {}) as { epochId?: string; counter?: string };
315
+ const wantChain = opts.chainId ?? 8453;
316
+
317
+ // The proof is the one the block is about.
318
+ const chainHash = publishedChainHash(proof);
319
+ if (chainHash !== b.chainHashB64) problems.push("the block's chain hash is not this proof's");
320
+ if (commit.epochId !== b.epochId || commit.counter !== b.counter) problems.push("the block names a different epoch or count");
321
+
322
+ // The write's calldata.
323
+ const calldata = evmHexToBytesSafe(b.calldata);
324
+ const w = calldata ? decodeHourCalldata(calldata) : null;
325
+ if (!calldata || !w) { problems.push("the hourly write's calldata does not decode"); return out; }
326
+ out.write = w;
327
+ if (w.epochId !== b.epochId) problems.push("the write is for a different epoch");
328
+ const count = Number(b.counter);
329
+ if (!(w.leaves > 0 && count >= w.first && count <= w.last)) problems.push("the proof's count is outside the write's range");
330
+ if (!(Number.isInteger(b.leafIndex) && b.leafIndex >= 0 && b.leafIndex < w.leaves)) problems.push("the leaf index is outside the tree");
331
+ else if (rootFromPath(b.chainHashB64, b.leafIndex, w.leaves, b.path) !== w.rootHex) problems.push("the path does not reach the write's root");
332
+
333
+ // The write's transaction, its block, and the block's transaction trie.
334
+ const e = b.write;
335
+ try {
336
+ const raw = evmHexToBytes(e.rawTx);
337
+ const tx = decodeEip1559(raw);
338
+ if (tx.hash !== e.txHash.toLowerCase()) problems.push("the raw transaction does not hash to the transaction hash");
339
+ if (evmBytesToHex(tx.data) !== evmBytesToHex(calldata)) problems.push("the transaction does not carry this calldata");
340
+ if (Number(tx.chainId) !== wantChain || e.chainId !== wantChain) problems.push(`the transaction is not on chain ${wantChain}`);
341
+ if (opts.writer !== undefined) {
342
+ if (tx.from !== opts.writer.toLowerCase()) problems.push("the transaction is not from the expected writer");
343
+ if ((tx.to ?? "") !== opts.writer.toLowerCase()) problems.push("the transaction is not sent to the writer itself");
344
+ }
345
+ const header = decodeHeader(evmHexToBytes(e.headerRlp));
346
+ if (header.hash !== e.blockHash.toLowerCase()) problems.push("the header does not hash to the block hash");
347
+ if (header.number !== e.blockNumber || header.timestamp !== e.blockTimestamp) problems.push("the header's number or time differs from the evidence");
348
+ const leaf = mptVerify(evmHexToBytes(header.transactionsRoot), txTrieKey(e.txIndex), e.txInclusionProof.map(evmHexToBytes));
349
+ if (!leaf || evmBytesToHex(leaf) !== evmBytesToHex(raw)) problems.push("the transaction is not in the block's transaction trie at that index");
350
+ out.ceiling = { chainId: e.chainId, blockNumber: header.number, blockHash: header.hash, blockTimestamp: header.timestamp, txHash: tx.hash };
351
+ } catch (err) {
352
+ problems.push(`the write's evidence does not hold together: ${(err as Error).message}`);
353
+ }
354
+
355
+ // The floor.
356
+ if (b.floor && (typeof b.floor.proof !== "object" || b.floor.proof === null || typeof b.floor.note !== "string")) {
357
+ problems.push("the floor is malformed");
358
+ } else if (b.floor) {
359
+ const f = b.floor;
360
+ const fp = f.proof;
361
+ // The floor must be a BitGraph of the same epoch, made by the same enclave key. Its own signature and attestation
362
+ // are checked like any proof's: verifyPublication() does both.
363
+ const fKey = (fp["signer"] as { publicKeyB64?: unknown } | undefined)?.publicKeyB64;
364
+ const pKey = (proof["signer"] as { publicKeyB64?: unknown } | undefined)?.publicKeyB64;
365
+ if (typeof fKey !== "string" || fKey !== pKey) problems.push("the floor is not signed by the proof's epoch key");
366
+ const fc = (fp["commit"] ?? {}) as { epochId?: string; counter?: string };
367
+ const fArtifact = (fp["artifact"] ?? {}) as { digestB64?: string };
368
+ const note = parseFloorNote(f.note);
369
+ const fCalldata = evmHexToBytesSafe(f.hourCalldata);
370
+ const fw = fCalldata ? decodeHourCalldata(fCalldata) : null;
371
+ if (!note) problems.push("the floor note does not parse");
372
+ else if (note.chainId !== wantChain) problems.push(`the floor's block is not on chain ${wantChain}`);
373
+ if (fArtifact.digestB64 !== floorNoteDigestB64(f.note)) problems.push("the floor BitGraph does not bind its note");
374
+ if (fc.epochId !== b.epochId) problems.push("the floor is in a different epoch");
375
+ if (!(Number(fc.counter) < count)) problems.push("the floor does not come before the proof");
376
+ if (!fCalldata || !fw) problems.push("the floor's hourly write does not decode");
377
+ else {
378
+ const same = evmBytesToHex(fCalldata) === evmBytesToHex(calldata);
379
+ if (!same && hourLink(fCalldata) !== w.prevLinkHex) problems.push("the floor's write is neither this write nor the one it links back to");
380
+ const fHash = publishedChainHash(fp);
381
+ if (!(Number.isInteger(f.leafIndex) && f.leafIndex >= 0 && f.leafIndex < fw.leaves) || rootFromPath(fHash, f.leafIndex, fw.leaves, f.path) !== fw.rootHex) {
382
+ problems.push("the floor BitGraph is not in its write's tree");
383
+ }
384
+ if (note && note.writeLinkHex !== fw.prevLinkHex) problems.push("the floor names a write other than the one before its tree");
385
+ }
386
+ if (note) out.floor = { chainId: note.chainId, blockNumber: note.blockNumber, blockHash: note.blockHash, blockTimestamp: note.blockTimestamp, floorCounter: String(fc.counter) };
387
+ }
388
+
389
+ out.ok = problems.length === 0;
390
+ return out;
391
+ }
392
+
393
+ export interface PublicationVerifyOptions extends PublicationCheckOptions {
394
+ /** Passed to the verifier for both proofs: the accepted measurements, as for any proof. */
395
+ trustAnchors?: Parameters<typeof verifyProofIntegrity>[0]["trustAnchors"];
396
+ }
397
+
398
+ /**
399
+ * checkPublication(), plus the signatures and attestations of the proof and of its floor BitGraph, through the
400
+ * verifier's integrity check. A publication block says nothing unless both proofs are sound, so this is the check to use.
401
+ */
402
+ export async function verifyPublication(proofIn: unknown, opts: PublicationVerifyOptions = {}): Promise<PublicationCheck> {
403
+ const out = checkPublication(proofIn, opts);
404
+ const proof = proofIn as Record<string, unknown>;
405
+ const integrity = async (p: Record<string, unknown>, what: string): Promise<void> => {
406
+ try {
407
+ const r = await verifyProofIntegrity({ proof: p as never, ...(opts.trustAnchors ? { trustAnchors: opts.trustAnchors } : {}), context: createVerificationContext() });
408
+ if (!r.valid) out.problems.push(`${what} does not verify: ${(r as { reason?: string }).reason ?? "invalid"}`);
409
+ } catch (e) {
410
+ out.problems.push(`${what} does not verify: ${(e as Error).message}`);
411
+ }
412
+ };
413
+ await integrity(proof, "the proof");
414
+ const b = publicationOf(proof);
415
+ if (b?.floor && typeof b.floor.proof === "object" && b.floor.proof !== null) await integrity(b.floor.proof, "the floor BitGraph");
416
+ out.ok = out.problems.length === 0;
417
+ return out;
418
+ }
419
+
420
+ function evmHexToBytesSafe(h: string): Uint8Array | null {
421
+ if (typeof h !== "string") return null;
422
+ return fromHex(h);
423
+ }
424
+
425
+ // ── the operator's record of each write, and the chain of writes ────────────
426
+
427
+ /** One hourly write as the operator stores it (publication/hours/... in the ledger). */
428
+ export interface HourRecord {
429
+ format: typeof HOUR_RECORD_FORMAT;
430
+ calldata: string; // 0x hex
431
+ link: string; // hex, SHA-256 of the calldata
432
+ write: WriteEvidence;
433
+ /** The BitGraphs the tree holds, in count order. */
434
+ members: Array<{ counter: string; chainHashB64: string }>;
435
+ /** Counts in the range with no BitGraph found when the write was made. */
436
+ missing: string[];
437
+ /** The floor bound right after this write landed, once it exists. */
438
+ floorCounter?: string;
439
+ writtenAt: string;
440
+ }
441
+
442
+ export interface HourChainCheck { ok: boolean; problems: string[]; writes: number; quietHours: number }
443
+
444
+ /** Check a run of hour records in order: each calldata decodes, its tree is its members, and each links to the one before. */
445
+ export function checkHourChain(records: readonly HourRecord[]): HourChainCheck {
446
+ const problems: string[] = [];
447
+ let quiet = 0;
448
+ let prevLink: string | null = null;
449
+ records.forEach((r, i) => {
450
+ const cd = fromHex(r.calldata);
451
+ const w = cd ? decodeHourCalldata(cd) : null;
452
+ if (!cd || !w) { problems.push(`write ${i}: calldata does not decode`); prevLink = null; return; }
453
+ if (hourLink(cd) !== r.link) problems.push(`write ${i}: link is not the calldata's hash`);
454
+ if (prevLink !== null && w.prevLinkHex !== prevLink) problems.push(`write ${i}: does not link to the write before it`);
455
+ if (w.leaves !== r.members.length) problems.push(`write ${i}: leaf count differs from its members`);
456
+ if (w.leaves === 0) quiet++;
457
+ else if (hourTree(r.members.map((m) => m.chainHashB64)).rootHex !== w.rootHex) problems.push(`write ${i}: members do not make its root`);
458
+ prevLink = r.link;
459
+ });
460
+ return { ok: problems.length === 0, problems, writes: records.length, quietHours: quiet };
461
+ }
@@ -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 causal reconstruction
@@ -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
  * JSON report builder: turns an AuditResult into the audit-report.json
package/src/report-md.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
  * Markdown report builder: turns an AuditResult into audit-report.md.
package/src/rlp.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 minimal RLP decoder (internal)
@@ -0,0 +1,105 @@
1
+ /**
2
+ * When a rollup's blocks are stamped.
3
+ *
4
+ * Base made one block every two seconds through block 53,556,126, so a
5
+ * block's time was genesis + 2 * number and a timestamp named one block.
6
+ * From block 53,556,127 (stamped 1,793,901,601, 2026-11-05 18:00:01 UTC) it
7
+ * makes five blocks a second. A block's timestamp is still whole seconds, so
8
+ * five consecutive blocks share each one: a timestamp names a second, and a
9
+ * block is one of the five in it.
10
+ *
11
+ * Both facts were read from Base itself: blocks 53,556,127 to 53,556,131 are
12
+ * stamped 1,793,901,601 and block 53,556,132 is stamped 1,793,901,602.
13
+ *
14
+ * Nothing here is trusted for what a record proves. The schedule only says
15
+ * when to look and where a batch sits among its neighbours; what is found is
16
+ * then checked by hash.
17
+ */
18
+
19
+ export interface RollupSchedule {
20
+ l2GenesisTime: number;
21
+ /** Seconds per block before `subSecond` starts, and always for a rollup that has none. */
22
+ blockTime: number;
23
+ /** From `fromBlock`, stamped `fromTime`, each whole second holds `blocksPerSecond` blocks. */
24
+ subSecond?: { fromBlock: number; fromTime: number; blocksPerSecond: number };
25
+ }
26
+
27
+ export const BASE_MAINNET_ROLLUP: RollupSchedule = Object.freeze({
28
+ l2GenesisTime: 1686789347,
29
+ blockTime: 2,
30
+ subSecond: Object.freeze({ fromBlock: 53_556_127, fromTime: 1_793_901_601, blocksPerSecond: 5 }),
31
+ });
32
+
33
+ /** The timestamp the schedule gives block `blockNumber`, in seconds. */
34
+ export function timeOfBlock(blockNumber: number, s: RollupSchedule): number {
35
+ const sub = s.subSecond;
36
+ if (sub && blockNumber >= sub.fromBlock) return sub.fromTime + Math.floor((blockNumber - sub.fromBlock) / sub.blocksPerSecond);
37
+ return s.l2GenesisTime + blockNumber * s.blockTime;
38
+ }
39
+
40
+ /** The blocks stamped `timestamp`: the first one and how many. Null when the schedule stamps no block with it. */
41
+ export function blocksAt(timestamp: number, s: RollupSchedule): { first: number; count: number } | null {
42
+ const sub = s.subSecond;
43
+ if (sub && timestamp >= sub.fromTime) {
44
+ if (!Number.isInteger(timestamp)) return null;
45
+ return { first: sub.fromBlock + (timestamp - sub.fromTime) * sub.blocksPerSecond, count: sub.blocksPerSecond };
46
+ }
47
+ const n = (timestamp - s.l2GenesisTime) / s.blockTime;
48
+ if (!Number.isInteger(n) || n < 0) return null;
49
+ return { first: n, count: 1 };
50
+ }
51
+
52
+ /** The newest block the schedule has stamped by `timestamp` (the head, by the clock alone). */
53
+ export function headAt(timestamp: number, s: RollupSchedule): number {
54
+ const sub = s.subSecond;
55
+ if (sub && timestamp >= sub.fromTime) return sub.fromBlock + (Math.floor(timestamp) - sub.fromTime + 1) * sub.blocksPerSecond - 1;
56
+ return Math.max(0, Math.floor((timestamp - s.l2GenesisTime) / s.blockTime));
57
+ }
58
+
59
+ /**
60
+ * Block numbers for the singular batches of one channel, in the channel's
61
+ * order. A singular batch carries its block's timestamp and its parent's
62
+ * hash, never its number. Where a timestamp names one block the number is
63
+ * read from it. Where it names several, the batches sharing it are counted
64
+ * off in order: a channel holds consecutive blocks, so a second in the
65
+ * middle holds all of its blocks, the channel's last second holds the first
66
+ * of its blocks, and the channel's first second holds the last of its
67
+ * blocks.
68
+ *
69
+ * One case has no answer from the channel alone: every batch shares one
70
+ * second and there are fewer than the second holds. `pin` then places them:
71
+ * the index of a batch already identified by hash, and its block's number.
72
+ * Without it they are counted from the second's first block.
73
+ */
74
+ export function numberSingularBatches(timestamps: readonly number[], s: RollupSchedule, pin?: { index: number; number: number }): number[] {
75
+ const out: number[] = [];
76
+ let i = 0;
77
+ while (i < timestamps.length) {
78
+ const t = timestamps[i]!;
79
+ const at = blocksAt(t, s);
80
+ if (!at) throw new TypeError(`batch timestamp ${t} is not on the rollup's schedule`);
81
+ let j = i;
82
+ while (j < timestamps.length && timestamps[j] === t) j++;
83
+ const run = j - i;
84
+ if (run > at.count) throw new TypeError(`${run} batches are stamped ${t}, which holds ${at.count} block${at.count === 1 ? "" : "s"}`);
85
+ const opens = i === 0;
86
+ const closes = j === timestamps.length;
87
+ let offset = 0;
88
+ if (run < at.count) {
89
+ if (!opens && !closes) throw new TypeError(`${run} batches are stamped ${t} in the middle of a channel, which holds ${at.count} blocks`);
90
+ if (opens && !closes) offset = at.count - run;
91
+ else if (opens && closes && pin && pin.index >= i && pin.index < j) {
92
+ offset = pin.number - pin.index - at.first;
93
+ if (offset < 0 || offset + run > at.count) throw new TypeError(`block ${pin.number} is not stamped ${t} on the rollup's schedule`);
94
+ }
95
+ }
96
+ for (let k = 0; k < run; k++) out.push(at.first + offset + k);
97
+ i = j;
98
+ }
99
+ // Counting off is only right for consecutive blocks, so a gap where seconds are shared is refused.
100
+ const shared = s.subSecond?.fromTime ?? Number.POSITIVE_INFINITY;
101
+ for (let k = 1; k < out.length; k++) {
102
+ if (timestamps[k]! >= shared && out[k] !== out[k - 1]! + 1) throw new TypeError(`the batches stamped ${timestamps[k - 1]} and ${timestamps[k]} are not consecutive blocks`);
103
+ }
104
+ return out;
105
+ }