@mikeargento/bitgraph-audit 0.11.1 → 0.13.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 (36) hide show
  1. package/dist/audit.d.ts +1 -1
  2. package/dist/audit.js +1 -1
  3. package/dist/genesis.d.ts +141 -0
  4. package/dist/genesis.d.ts.map +1 -0
  5. package/dist/genesis.js +359 -0
  6. package/dist/genesis.js.map +1 -0
  7. package/dist/index.d.ts +6 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +5 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/publication.d.ts +148 -0
  12. package/dist/publication.d.ts.map +1 -0
  13. package/dist/publication.js +392 -0
  14. package/dist/publication.js.map +1 -0
  15. package/dist/tot.d.ts +108 -0
  16. package/dist/tot.d.ts.map +1 -0
  17. package/dist/tot.js +250 -0
  18. package/dist/tot.js.map +1 -0
  19. package/package.json +4 -3
  20. package/src/__tests__/{anchors.test.ts → archive/anchors.test.ts} +2 -2
  21. package/src/__tests__/{base-floor.test.ts → archive/base-floor.test.ts} +2 -2
  22. package/src/__tests__/{carrier-tree.test.ts → archive/carrier-tree.test.ts} +2 -2
  23. package/src/__tests__/archive/genesis.test.ts +256 -0
  24. package/src/__tests__/archive/publication.test.ts +210 -0
  25. package/src/__tests__/tot-v2-real.test.ts +98 -0
  26. package/src/__tests__/tot-v2-vectors.test.ts +87 -0
  27. package/src/__tests__/tot-vectors.test.ts +120 -0
  28. package/src/audit.ts +1 -1
  29. package/src/genesis.ts +382 -0
  30. package/src/index.ts +26 -0
  31. package/src/publication.ts +461 -0
  32. package/src/tot.ts +268 -0
  33. /package/src/__tests__/{fixtures → archive/fixtures}/settlement/0x018efc046e94610e2530344caf1574e507a3182e1a975fb25b032ec1434a3f5c.bin +0 -0
  34. /package/src/__tests__/{fixtures → archive/fixtures}/settlement/ceiling-51979918.json +0 -0
  35. /package/src/__tests__/{fixtures → archive/fixtures}/settlement/pointer-51979918.json +0 -0
  36. /package/src/__tests__/{settlement.test.ts → archive/settlement.test.ts} +0 -0
@@ -0,0 +1,256 @@
1
+ // Copyright (c) 2025-2026 Argento Computing Inc.
2
+
3
+ /**
4
+ * Epoch genesis: the note, the write (a receipt as JSON text), and the offline check of a BitGraph's
5
+ * bitgraph-publication/2 block against real signed transactions in real headers and transaction tries (built here,
6
+ * not mocked). The receipts are stand-ins, so these tests use the checks that do not verify signatures; one test runs
7
+ * the full check over a real v13 receipt.
8
+ */
9
+
10
+ import { test, describe } from "node:test";
11
+ import assert from "node:assert/strict";
12
+ import { readFileSync } from "node:fs";
13
+ import { Transaction, addr } from "micro-eth-signer";
14
+ import { rlpEncode, keccak256, txTrieProof, evmBytesToHex, evmHexToBytes, bytesToB64 } from "@mikeargento/bitgraph-verify";
15
+ import {
16
+ hourTree, publishedChainHash, type WriteEvidence,
17
+ genesisNoteText, parseGenesisNote, genesisNoteDigestB64, encodeGenesisCalldata, decodeGenesisCalldata, genesisLink,
18
+ checkGenesis, verifyGenesis, checkEpochPublication, checkGenesisChain, GENESIS_FORMAT, EPOCH_PUBLICATION_KEY,
19
+ type EpochPublicationBlock, type GenesisRecord, type GenesisNote,
20
+ } from "@mikeargento/bitgraph-audit";
21
+
22
+ const epoch = (n: number): string => bytesToB64(new Uint8Array(32).fill(n));
23
+ const EA = epoch(1), EB = epoch(2), EC = epoch(3);
24
+ const keyOf = (e: string): string => bytesToB64(new Uint8Array(32).fill(e === EA ? 11 : e === EB ? 12 : 13));
25
+ const ZERO = "0".repeat(64);
26
+ const writer = addr.random();
27
+ const stranger = addr.random();
28
+ const after = (n: number): GenesisNote["after"] => ({ blockNumber: n, blockHash: "0x" + n.toString(16).padStart(64, "0"), blockTimestamp: 1_794_000_000 + n });
29
+
30
+ function fakeProof(counter: number, epochId: string, digestB64 = bytesToB64(new Uint8Array(32).fill(counter & 255))): Record<string, unknown> {
31
+ return {
32
+ version: "bitgraph/1",
33
+ artifact: { hashAlg: "sha256", digestB64 },
34
+ commit: { nonceB64: bytesToB64(new Uint8Array(32).fill((counter * 3) & 255)), counter: String(counter), slotCounter: String(counter - 1), epochId, atomic: true },
35
+ signer: { publicKeyB64: keyOf(epochId), signatureB64: "AA==" },
36
+ };
37
+ }
38
+
39
+ /** A signed self-addressed write, in a block with a neighbor, with header and trie evidence. */
40
+ function publish(calldata: Uint8Array, opts: { from?: { privateKey: string; address: string }; blockNumber?: number } = {}): WriteEvidence {
41
+ const from = opts.from ?? writer;
42
+ const tx = Transaction.prepare({ to: from.address, value: 0n, nonce: 0n, maxFeePerGas: 1_000_000n, maxPriorityFeePerGas: 1n, gasLimit: 600_000n, chainId: 8453n, data: evmBytesToHex(calldata) } as never);
43
+ const raw = evmHexToBytes(tx.signBy(from.privateKey).toHex(true));
44
+ const neighbor = evmHexToBytes(Transaction.prepare({ to: stranger.address, value: 1n, nonce: 4n, maxFeePerGas: 1_000_000n, maxPriorityFeePerGas: 1n, gasLimit: 21_000n, chainId: 8453n } as never).signBy(stranger.privateKey).toHex(true));
45
+ const { root, proof } = txTrieProof([neighbor, raw], 1);
46
+ const number = opts.blockNumber ?? 64_000_000;
47
+ const timestamp = 1_794_000_000 + number;
48
+ const n = (v: number): Uint8Array => { const h = v.toString(16); return evmHexToBytes((h.length % 2 ? "0" : "") + h); };
49
+ const header = rlpEncode([
50
+ new Uint8Array(32).fill(1), new Uint8Array(32).fill(2), new Uint8Array(20).fill(4), new Uint8Array(32).fill(5), root,
51
+ new Uint8Array(32).fill(6), new Uint8Array(256), new Uint8Array(0), n(number), n(30_000_000), n(100_000), n(timestamp),
52
+ new Uint8Array(0), new Uint8Array(32).fill(8), new Uint8Array(8), n(1000),
53
+ ]);
54
+ return {
55
+ chain: "base", chainId: 8453, writer: from.address.toLowerCase(),
56
+ txHash: evmBytesToHex(keccak256(raw)), blockNumber: number, blockHash: evmBytesToHex(keccak256(header)), blockTimestamp: timestamp,
57
+ headerRlp: evmBytesToHex(header), txIndex: 1, txInclusionProof: proof.map(evmBytesToHex), rawTx: evmBytesToHex(raw),
58
+ };
59
+ }
60
+
61
+ /** One genesis: a note closing `closed`, bound as the first BitGraph of `opens`, written to Base. */
62
+ function genesis(opens: string, closes: string | null, closed: Array<Record<string, unknown>>, prevLinkHex: string, blockNumber: number, counter = 2) {
63
+ const tree = hourTree(closed.map(publishedChainHash));
64
+ const counts = closed.map((p) => Number((p["commit"] as { counter: string }).counter));
65
+ const note = genesisNoteText({
66
+ chainId: 8453, prevLinkHex,
67
+ closes: closes === null ? null : { epochId: closes, first: counts[0] ?? 0, last: counts.at(-1) ?? 0, leaves: closed.length, rootHex: tree.rootHex },
68
+ after: after(blockNumber - 10),
69
+ });
70
+ const receipt = fakeProof(counter, opens, genesisNoteDigestB64(note));
71
+ const calldata = encodeGenesisCalldata(receipt, note);
72
+ return { note, receipt, calldata, link: genesisLink(calldata), write: publish(calldata, { blockNumber }), tree, members: closed };
73
+ }
74
+
75
+ /** Epoch A (three BitGraphs) is closed by the genesis that opens B; B (its genesis and two more) by the one that opens C. */
76
+ function scenario() {
77
+ const a = [2, 4, 6].map((c) => fakeProof(c, EA));
78
+ const gB = genesis(EB, EA, a, ZERO, 64_000_000);
79
+ const b = [gB.receipt, fakeProof(4, EB), fakeProof(6, EB)];
80
+ const gC = genesis(EC, EB, b, gB.link, 64_400_000);
81
+ return { a, gB, b, gC };
82
+ }
83
+
84
+ function blockFor(proof: Record<string, unknown>, index: number, closing: ReturnType<typeof genesis>, opening: ReturnType<typeof genesis> | null, withRaw = true): EpochPublicationBlock {
85
+ const c = proof["commit"] as { epochId: string; counter: string };
86
+ const { rawTx, ...rest } = closing.write;
87
+ return {
88
+ format: EPOCH_PUBLICATION_KEY, epochId: c.epochId, counter: c.counter, chainHashB64: publishedChainHash(proof), leafIndex: index, path: closing.tree.paths[index]!,
89
+ closedBy: withRaw ? { ...rest, rawTx } : rest,
90
+ openedBy: opening ? { calldata: evmBytesToHex(opening.calldata) } : null,
91
+ };
92
+ }
93
+ const attach = (proof: Record<string, unknown>, block: EpochPublicationBlock): Record<string, unknown> => ({ ...proof, metadata: { ...((proof["metadata"] as object | undefined) ?? {}), [EPOCH_PUBLICATION_KEY]: block } });
94
+ const check = (proof: Record<string, unknown>, block: EpochPublicationBlock) => checkEpochPublication(attach(proof, block), { writer: writer.address.toLowerCase() });
95
+
96
+ describe("the genesis note and write", () => {
97
+ test("the note round-trips, with and without an epoch to close", () => {
98
+ const n: GenesisNote = { chainId: 8453, prevLinkHex: "ab".repeat(32), closes: { epochId: EA, first: 2, last: 6, leaves: 3, rootHex: "cd".repeat(32) }, after: after(64_000_000) };
99
+ assert.deepEqual(parseGenesisNote(genesisNoteText(n)), n);
100
+ const first: GenesisNote = { chainId: 8453, prevLinkHex: ZERO, closes: null, after: after(5) };
101
+ assert.deepEqual(parseGenesisNote(genesisNoteText(first)), first);
102
+ const empty: GenesisNote = { ...n, closes: { epochId: EA, first: 0, last: 0, leaves: 0, rootHex: ZERO } };
103
+ assert.deepEqual(parseGenesisNote(genesisNoteText(empty)), empty);
104
+ });
105
+
106
+ test("a note that disagrees with itself, or has anything added, does not parse", () => {
107
+ const n: GenesisNote = { chainId: 8453, prevLinkHex: ZERO, closes: { epochId: EA, first: 2, last: 6, leaves: 3, rootHex: "cd".repeat(32) }, after: after(9) };
108
+ const text = genesisNoteText(n);
109
+ assert.equal(parseGenesisNote(text + "extra\n"), null);
110
+ assert.equal(parseGenesisNote(text.replace("bitgraphs: 3", "bitgraphs: 0")), null, "no BitGraphs with a nonzero root");
111
+ assert.equal(parseGenesisNote(text.replace("last count: 6", "last count: 0")), null, "a range that runs backward");
112
+ assert.equal(parseGenesisNote(text.replace(`closes epoch: ${EA}`, "closes epoch: none")), null, "nothing closed, yet a root");
113
+ });
114
+
115
+ test("the write is the receipt's JSON as text, and it carries the note it binds", () => {
116
+ const { gB } = scenario();
117
+ const text = new TextDecoder().decode(gB.calldata);
118
+ assert.ok(text.startsWith('{"version":"bitgraph/1"'), "the transaction's data reads as a receipt");
119
+ const w = decodeGenesisCalldata(gB.calldata)!;
120
+ assert.equal(w.note, gB.note);
121
+ assert.equal((w.receipt["artifact"] as { digestB64: string }).digestB64, genesisNoteDigestB64(gB.note));
122
+ assert.equal((w.receipt["metadata"] as Record<string, { format: string }>)[GENESIS_FORMAT]!.format, GENESIS_FORMAT);
123
+ const g = checkGenesis(gB.calldata);
124
+ assert.deepEqual(g.problems, []);
125
+ assert.equal(g.epochId, EB);
126
+ assert.equal(g.publicKeyB64, keyOf(EB));
127
+ assert.equal(g.note!.closes!.epochId, EA);
128
+ });
129
+
130
+ test("unsigned metadata the receipt already had is kept beside the note", () => {
131
+ const { gB } = scenario();
132
+ const cd = encodeGenesisCalldata({ ...gB.receipt, metadata: { other: { a: 1 } } }, gB.note);
133
+ const w = decodeGenesisCalldata(cd)!;
134
+ assert.deepEqual((w.receipt["metadata"] as Record<string, unknown>)["other"], { a: 1 });
135
+ assert.deepEqual(checkGenesis(cd).problems, []);
136
+ });
137
+
138
+ test("anything else does not decode, and a changed note is caught", () => {
139
+ assert.equal(decodeGenesisCalldata(new Uint8Array([0xff, 0xfe])), null);
140
+ assert.equal(decodeGenesisCalldata(new TextEncoder().encode("[1,2]")), null);
141
+ assert.equal(decodeGenesisCalldata(new TextEncoder().encode(JSON.stringify(fakeProof(2, EB)))), null, "a receipt with no note");
142
+ const { gB } = scenario();
143
+ const changed = encodeGenesisCalldata(gB.receipt, gB.note.replace("bitgraphs: 3", "bitgraphs: 2"));
144
+ assert.ok(checkGenesis(changed).problems.includes("the genesis BitGraph does not bind its note"));
145
+ const self = genesis(EA, EA, [], ZERO, 64_000_000);
146
+ assert.ok(checkGenesis(self.calldata).problems.includes("the genesis BitGraph is in the epoch it closes"));
147
+ });
148
+
149
+ test("the full check runs the verifier over the receipt: a real v13 receipt verifies, though it binds no note", async () => {
150
+ const real = JSON.parse(readFileSync(new URL("../../../../verify/src/__tests__/fixtures/v13/proof-4.json", import.meta.url), "utf8")) as Record<string, unknown>;
151
+ delete real["proofHash"];
152
+ const note = genesisNoteText({ chainId: 8453, prevLinkHex: ZERO, closes: null, after: after(7) });
153
+ const g = await verifyGenesis(encodeGenesisCalldata(real, note));
154
+ assert.deepEqual(g.problems, ["the genesis BitGraph does not bind its note"], "its signatures and attestation pass; only the binding fails");
155
+ const forged = await verifyGenesis(encodeGenesisCalldata({ ...real, signer: { ...(real["signer"] as object), signatureB64: "AA==" } }, note));
156
+ assert.ok(forged.problems.some((p) => p.startsWith("the genesis BitGraph does not verify")));
157
+ });
158
+ });
159
+
160
+ describe("a BitGraph's epoch publication block", () => {
161
+ test("a BitGraph of an epoch with no genesis of its own checks, with a ceiling and no floor", () => {
162
+ const { a, gB } = scenario();
163
+ a.forEach((p, i) => {
164
+ const r = check(p, blockFor(p, i, gB, null));
165
+ assert.deepEqual(r.problems, []);
166
+ assert.equal(r.ceiling!.blockNumber, gB.write.blockNumber);
167
+ assert.equal(r.floor, null);
168
+ assert.equal(r.nextEpochId, EB);
169
+ });
170
+ });
171
+
172
+ test("a BitGraph after its epoch's genesis checks, with the Base block the genesis names as its floor", () => {
173
+ const { b, gB, gC } = scenario();
174
+ for (const i of [1, 2]) {
175
+ const r = check(b[i]!, blockFor(b[i]!, i, gC, gB));
176
+ assert.deepEqual(r.problems, []);
177
+ assert.equal(r.ceiling!.blockNumber, 64_400_000);
178
+ assert.equal(r.floor!.blockNumber, 64_000_000 - 10);
179
+ assert.equal(r.floor!.genesisCounter, "2");
180
+ assert.equal(r.nextEpochId, EC);
181
+ }
182
+ });
183
+
184
+ test("the genesis BitGraph itself is under the next genesis's root, and has no floor", () => {
185
+ const { b, gC, gB } = scenario();
186
+ assert.deepEqual(check(b[0]!, blockFor(b[0]!, 0, gC, null)).problems, []);
187
+ assert.ok(check(b[0]!, blockFor(b[0]!, 0, gC, gB)).problems.includes("the opening genesis does not come before the proof"));
188
+ });
189
+
190
+ test("the raw transaction may be left out: it is read from the block's transaction trie", () => {
191
+ const { b, gB, gC } = scenario();
192
+ assert.deepEqual(check(b[1]!, blockFor(b[1]!, 1, gC, gB, false)).problems, []);
193
+ const wrongRaw = blockFor(b[1]!, 1, gC, gB);
194
+ wrongRaw.closedBy.rawTx = gB.write.rawTx;
195
+ assert.ok(check(b[1]!, wrongRaw).problems.includes("the raw transaction is not the one in the block"));
196
+ });
197
+
198
+ test("tampering anywhere is caught", () => {
199
+ const { a, b, gB, gC } = scenario();
200
+ const good = (): EpochPublicationBlock => blockFor(b[1]!, 1, gC, gB);
201
+ const has = (block: EpochPublicationBlock, problem: string, proof = b[1]!) => assert.ok(check(proof, block).problems.includes(problem), `${problem}: ${JSON.stringify(check(proof, block).problems)}`);
202
+
203
+ has({ ...good(), path: gC.tree.paths[2]! }, "the path does not reach the closing genesis's root");
204
+ has({ ...good(), leafIndex: 9 }, "the leaf index is outside the tree");
205
+ has({ ...good(), chainHashB64: publishedChainHash(b[2]!) }, "the block's chain hash is not this proof's");
206
+ has({ ...good(), counter: "6" }, "the block names a different epoch or count");
207
+ has({ ...good(), closedBy: { ...gC.write, blockHash: "0x" + "00".repeat(32) } }, "the header does not hash to the block hash");
208
+ has({ ...good(), closedBy: { ...gC.write, txIndex: 0 } }, "the transaction is not in the block's transaction trie at that index");
209
+ // A genesis that closes another epoch cannot stand in.
210
+ has(blockFor(b[1]!, 1, gB, null), "the closing genesis closes a different epoch");
211
+ // A BitGraph outside the closed range.
212
+ const late = fakeProof(8, EB);
213
+ has({ ...blockFor(late, 1, gC, gB) }, "the proof's count is outside the closed range", late);
214
+ // The opening genesis must be this epoch's, signed by its key, and the write the closing one links back to.
215
+ const elsewhere = genesis(EC, EB, b, gB.link, 64_400_000);
216
+ has({ ...good(), openedBy: { calldata: evmBytesToHex(elsewhere.calldata) } }, "the opening genesis is in a different epoch");
217
+ const lookalike = genesis(EB, EA, a, "ee".repeat(32), 64_000_000);
218
+ has({ ...good(), openedBy: { calldata: evmBytesToHex(lookalike.calldata) } }, "the opening genesis is not the write the closing genesis links back to");
219
+ has({ ...good(), openedBy: { calldata: "0x00" } }, "the opening genesis does not decode");
220
+ });
221
+
222
+ test("a write from anyone but the expected writer is refused", () => {
223
+ const { b, gB } = scenario();
224
+ const other = addr.random();
225
+ const tree = hourTree(b.map(publishedChainHash));
226
+ const note = genesisNoteText({ chainId: 8453, prevLinkHex: gB.link, closes: { epochId: EB, first: 2, last: 6, leaves: 3, rootHex: tree.rootHex }, after: after(64_399_990) });
227
+ const calldata = encodeGenesisCalldata(fakeProof(2, EC, genesisNoteDigestB64(note)), note);
228
+ const theirs = { note, receipt: {}, calldata, link: genesisLink(calldata), write: publish(calldata, { from: other, blockNumber: 64_400_000 }), tree, members: b };
229
+ const block = blockFor(b[1]!, 1, theirs as ReturnType<typeof genesis>, gB);
230
+ assert.ok(check(b[1]!, block).problems.includes("the transaction is not from the expected writer"));
231
+ assert.deepEqual(checkEpochPublication(attach(b[1]!, block)).problems, [], "with no writer named, the evidence itself holds together");
232
+ });
233
+
234
+ test("no block, no check", () => {
235
+ assert.deepEqual(checkEpochPublication(fakeProof(4, EB)).problems, ["the proof carries no bitgraph-publication/2 block"]);
236
+ });
237
+ });
238
+
239
+ describe("the chain of genesis writes", () => {
240
+ const record = (g: ReturnType<typeof genesis>, opens: string): GenesisRecord => ({
241
+ format: GENESIS_FORMAT, epochId: opens, counter: "2", calldata: evmBytesToHex(g.calldata), link: g.link, note: g.note, write: g.write,
242
+ members: g.members.map((p) => ({ counter: (p["commit"] as { counter: string }).counter, chainHashB64: publishedChainHash(p) })), missing: [], writtenAt: "2026-12-01T00:02:00.000Z",
243
+ });
244
+
245
+ test("each genesis links to the one before and closes the epoch it opened; a break or wrong members show", () => {
246
+ const { gB, gC } = scenario();
247
+ const recs = [record(gB, EB), record(gC, EC)];
248
+ assert.deepEqual(checkGenesisChain(recs, ZERO), { ok: true, problems: [], writes: 2 });
249
+ assert.ok(checkGenesisChain(recs, "aa".repeat(32)).problems.includes("genesis 0: does not link to the write before it"));
250
+ assert.ok(checkGenesisChain([recs[1]!, recs[0]!]).problems.includes("genesis 1: does not close the epoch the one before it opened"));
251
+ const short = { ...recs[1]!, members: recs[1]!.members.slice(0, 2) };
252
+ assert.ok(checkGenesisChain([recs[0]!, short]).problems.includes("genesis 1: leaf count differs from its members"));
253
+ const swapped = { ...recs[1]!, members: [...recs[1]!.members].reverse() };
254
+ assert.ok(checkGenesisChain([recs[0]!, swapped]).problems.includes("genesis 1: members do not make its root"));
255
+ });
256
+ });
@@ -0,0 +1,210 @@
1
+ // Copyright (c) 2025-2026 Argento Computing Inc.
2
+
3
+ /**
4
+ * Hourly publication: the write's calldata, the hour's tree, the floor note, and the offline check of a proof's
5
+ * publication block against a real signed transaction in a real header and transaction trie (built here, not mocked).
6
+ */
7
+
8
+ import { test, describe } from "node:test";
9
+ import assert from "node:assert/strict";
10
+ import { Transaction, addr } from "micro-eth-signer";
11
+ import { rlpEncode, keccak256, txTrieProof, evmBytesToHex, evmHexToBytes, bytesToB64 } from "@mikeargento/bitgraph-verify";
12
+ import {
13
+ encodeHourCalldata, decodeHourCalldata, hourLink, hourTree, floorNoteText, parseFloorNote, floorNoteDigestB64,
14
+ publishedChainHash, checkPublication, checkHourChain, PUBLICATION_METADATA_KEY, HOUR_RECORD_FORMAT,
15
+ type HourWrite, type PublicationBlock, type WriteEvidence, type HourRecord,
16
+ } from "../../publication.ts";
17
+
18
+ const EPOCH = bytesToB64(new Uint8Array(32).fill(7));
19
+ const OTHER_EPOCH = bytesToB64(new Uint8Array(32).fill(9));
20
+ const KEY = bytesToB64(new Uint8Array(32).fill(3));
21
+ const ZERO = "0".repeat(64);
22
+ const writer = addr.random();
23
+ const stranger = addr.random();
24
+
25
+ function fakeProof(counter: number, epochId = EPOCH, digestB64 = bytesToB64(new Uint8Array(32).fill(counter & 255))): Record<string, unknown> {
26
+ return {
27
+ version: "bitgraph/1",
28
+ artifact: { hashAlg: "sha256", digestB64 },
29
+ commit: { nonceB64: bytesToB64(new Uint8Array(32).fill((counter * 3) & 255)), counter: String(counter), slotCounter: String(counter - 1), epochId, atomic: true },
30
+ signer: { publicKeyB64: KEY, signatureB64: "AA==" },
31
+ };
32
+ }
33
+
34
+ /** A signed self-addressed write, in a block of its own plus a neighbor, with header and trie evidence. */
35
+ function publish(calldata: Uint8Array, opts: { from?: { privateKey: string; address: string }; chainId?: bigint; blockNumber?: number } = {}): WriteEvidence {
36
+ const from = opts.from ?? writer;
37
+ const tx = Transaction.prepare({ to: from.address, value: 0n, nonce: 0n, maxFeePerGas: 1_000_000n, maxPriorityFeePerGas: 1n, gasLimit: 60_000n, chainId: opts.chainId ?? 8453n, data: evmBytesToHex(calldata) } as never);
38
+ const raw = evmHexToBytes(tx.signBy(from.privateKey).toHex(true));
39
+ const neighbor = evmHexToBytes(Transaction.prepare({ to: stranger.address, value: 1n, nonce: 4n, maxFeePerGas: 1_000_000n, maxPriorityFeePerGas: 1n, gasLimit: 21_000n, chainId: 8453n } as never).signBy(stranger.privateKey).toHex(true));
40
+ const txs = [neighbor, raw];
41
+ const { root, proof } = txTrieProof(txs, 1);
42
+ const number = opts.blockNumber ?? 38_000_000;
43
+ const timestamp = 1_794_000_000 + number;
44
+ const n = (v: number): Uint8Array => { const h = v.toString(16); return evmHexToBytes((h.length % 2 ? "0" : "") + h); };
45
+ const header = rlpEncode([
46
+ new Uint8Array(32).fill(1), new Uint8Array(32).fill(2), new Uint8Array(20).fill(4), new Uint8Array(32).fill(5), root,
47
+ new Uint8Array(32).fill(6), new Uint8Array(256), new Uint8Array(0), n(number), n(30_000_000), n(100_000), n(timestamp),
48
+ new Uint8Array(0), new Uint8Array(32).fill(8), new Uint8Array(8), n(1000),
49
+ ]);
50
+ return {
51
+ chain: "base", chainId: 8453, writer: from.address.toLowerCase(),
52
+ txHash: evmBytesToHex(keccak256(raw)), blockNumber: number, blockHash: evmBytesToHex(keccak256(header)), blockTimestamp: timestamp,
53
+ headerRlp: evmBytesToHex(header), txIndex: 1, txInclusionProof: proof.map(evmBytesToHex), rawTx: evmBytesToHex(raw),
54
+ };
55
+ }
56
+
57
+ function attach(proof: Record<string, unknown>, block: PublicationBlock): Record<string, unknown> {
58
+ return { ...proof, metadata: { ...((proof["metadata"] as object | undefined) ?? {}), [PUBLICATION_METADATA_KEY]: block } };
59
+ }
60
+
61
+ /** Two published hours of one epoch: hour A covers 2..6, its floor is #8, hour B covers 8..12. */
62
+ function scenario() {
63
+ const a = [2, 4, 6].map((c) => fakeProof(c));
64
+ const treeA = hourTree(a.map(publishedChainHash));
65
+ const wA: HourWrite = { epochId: EPOCH, first: 2, last: 6, leaves: 3, rootHex: treeA.rootHex, prevLinkHex: ZERO, epochPublicKeyB64: KEY };
66
+ const cdA = encodeHourCalldata(wA);
67
+ const evA = publish(cdA, { blockNumber: 38_000_000 });
68
+ const note = floorNoteText({ chainId: 8453, blockNumber: evA.blockNumber, blockHash: evA.blockHash, blockTimestamp: evA.blockTimestamp, txHash: evA.txHash, writeLinkHex: hourLink(cdA) });
69
+ const floor = fakeProof(8, EPOCH, floorNoteDigestB64(note));
70
+ const b = [floor, fakeProof(10), fakeProof(12)];
71
+ const treeB = hourTree(b.map(publishedChainHash));
72
+ const wB: HourWrite = { epochId: EPOCH, first: 8, last: 12, leaves: 3, rootHex: treeB.rootHex, prevLinkHex: hourLink(cdA) };
73
+ const cdB = encodeHourCalldata(wB);
74
+ const evB = publish(cdB, { blockNumber: 38_001_800 });
75
+ return { a, treeA, cdA, evA, note, floor, b, treeB, cdB, evB };
76
+ }
77
+
78
+ function blockFor(proof: Record<string, unknown>, index: number, tree: { paths: string[] }, calldata: Uint8Array, write: WriteEvidence, floor: PublicationBlock["floor"]): PublicationBlock {
79
+ const c = proof["commit"] as { epochId: string; counter: string };
80
+ return { format: PUBLICATION_METADATA_KEY, epochId: c.epochId, counter: c.counter, chainHashB64: publishedChainHash(proof), leafIndex: index, path: tree.paths[index]!, calldata: evmBytesToHex(calldata), write, floor };
81
+ }
82
+
83
+ describe("the hourly write", () => {
84
+ test("calldata round-trips, with and without the epoch key", () => {
85
+ const w: HourWrite = { epochId: EPOCH, first: 2, last: 40, leaves: 20, rootHex: "ab".repeat(32), prevLinkHex: "cd".repeat(32) };
86
+ const cd = encodeHourCalldata(w);
87
+ assert.equal(cd.length, 121);
88
+ assert.deepEqual(decodeHourCalldata(cd), w);
89
+ const wk = { ...w, epochPublicKeyB64: KEY };
90
+ const cdk = encodeHourCalldata(wk);
91
+ assert.equal(cdk.length, 153);
92
+ assert.deepEqual(decodeHourCalldata(cdk), wk);
93
+ });
94
+
95
+ test("a quiet hour has no leaves and a zero root; a nonzero root with no leaves is refused", () => {
96
+ const q: HourWrite = { epochId: EPOCH, first: 40, last: 40, leaves: 0, rootHex: ZERO, prevLinkHex: "cd".repeat(32) };
97
+ assert.deepEqual(decodeHourCalldata(encodeHourCalldata(q)), q);
98
+ assert.throws(() => encodeHourCalldata({ ...q, rootHex: "ab".repeat(32) }));
99
+ });
100
+
101
+ test("anything else does not decode", () => {
102
+ const cd = encodeHourCalldata({ epochId: EPOCH, first: 2, last: 4, leaves: 2, rootHex: "ab".repeat(32), prevLinkHex: ZERO });
103
+ const bad = cd.slice(); bad[0] = 0x41;
104
+ assert.equal(decodeHourCalldata(bad), null);
105
+ const flag = cd.slice(); flag[4] = 1; // says it carries a key but is 121 bytes
106
+ assert.equal(decodeHourCalldata(flag), null);
107
+ assert.equal(decodeHourCalldata(cd.subarray(0, 120)), null);
108
+ });
109
+
110
+ test("the floor note round-trips and its digest is SHA-256 of its text", () => {
111
+ const n = { chainId: 8453, blockNumber: 38_000_000, blockHash: "0x" + "ab".repeat(32), blockTimestamp: 1_794_000_000, txHash: "0x" + "cd".repeat(32), writeLinkHex: "ef".repeat(32) };
112
+ const t = floorNoteText(n);
113
+ assert.deepEqual(parseFloorNote(t), n);
114
+ assert.equal(parseFloorNote(t.replace("block: ", "block: ")), null);
115
+ assert.equal(floorNoteDigestB64(t).length, 44);
116
+ });
117
+
118
+ test("a proof publishes under the same leaf with or without unsigned metadata", () => {
119
+ const p = fakeProof(10);
120
+ const withMember = { ...p, metadata: { "bitgraph-tree-member/1": { format: "bitgraph-tree-member/1", files: 2, index: 0, path: "", rootText: "x" } } };
121
+ assert.equal(publishedChainHash(withMember), publishedChainHash(p));
122
+ });
123
+ });
124
+
125
+ describe("a proof's publication block", () => {
126
+ test("a proof in the first hour of an epoch checks, with no floor", () => {
127
+ const s = scenario();
128
+ const p = attach(s.a[1]!, blockFor(s.a[1]!, 1, s.treeA, s.cdA, s.evA, null));
129
+ const r = checkPublication(p, { writer: writer.address.toLowerCase() });
130
+ assert.deepEqual(r.problems, []);
131
+ assert.equal(r.ok, true);
132
+ assert.equal(r.ceiling?.blockNumber, 38_000_000);
133
+ assert.equal(r.floor, null);
134
+ });
135
+
136
+ test("a proof after the floor checks, with the floor in the same tree", () => {
137
+ const s = scenario();
138
+ const floor = { proof: s.floor, note: s.note, hourCalldata: evmBytesToHex(s.cdB), leafIndex: 0, path: s.treeB.paths[0]! };
139
+ const p = attach(s.b[2]!, blockFor(s.b[2]!, 2, s.treeB, s.cdB, s.evB, floor));
140
+ const r = checkPublication(p, { writer: writer.address.toLowerCase() });
141
+ assert.deepEqual(r.problems, []);
142
+ assert.equal(r.floor?.blockNumber, 38_000_000, "after the first hour's block");
143
+ assert.equal(r.ceiling?.blockNumber, 38_001_800, "by the second hour's block");
144
+ });
145
+
146
+ test("a floor in the tree the write links back to also checks", () => {
147
+ // A third hour whose proof's floor is #8, published in hour B's tree.
148
+ const s = scenario();
149
+ const c = [fakeProof(14)];
150
+ const treeC = hourTree(c.map(publishedChainHash));
151
+ const cdC = encodeHourCalldata({ epochId: EPOCH, first: 14, last: 14, leaves: 1, rootHex: treeC.rootHex, prevLinkHex: hourLink(s.cdB) });
152
+ const evC = publish(cdC, { blockNumber: 38_003_600 });
153
+ const floor = { proof: s.floor, note: s.note, hourCalldata: evmBytesToHex(s.cdB), leafIndex: 0, path: s.treeB.paths[0]! };
154
+ const r = checkPublication(attach(c[0]!, blockFor(c[0]!, 0, treeC, cdC, evC, floor)), { writer: writer.address.toLowerCase() });
155
+ assert.deepEqual(r.problems, []);
156
+ });
157
+
158
+ test("tampering anywhere is caught", () => {
159
+ const s = scenario();
160
+ const floor = { proof: s.floor, note: s.note, hourCalldata: evmBytesToHex(s.cdB), leafIndex: 0, path: s.treeB.paths[0]! };
161
+ const good = blockFor(s.b[2]!, 2, s.treeB, s.cdB, s.evB, floor);
162
+ const w = writer.address.toLowerCase();
163
+ const bad = (blk: PublicationBlock, proof = s.b[2]!, o: { writer?: string } = { writer: w }) => checkPublication(attach(proof, blk), o);
164
+
165
+ assert.equal(bad({ ...good, path: s.treeB.paths[1]! }).ok, false, "a wrong path");
166
+ assert.equal(bad(good, s.b[1]!).ok, false, "another proof under this block");
167
+ assert.equal(bad({ ...good, calldata: evmBytesToHex(s.cdA) }).ok, false, "another write's calldata");
168
+ assert.equal(bad({ ...good, write: { ...good.write, txIndex: 0 } }).ok, false, "the wrong trie position");
169
+ assert.equal(bad({ ...good, write: { ...good.write, blockTimestamp: good.write.blockTimestamp + 1 } }).ok, false, "a time the header does not say");
170
+ assert.equal(bad({ ...good, write: { ...good.write, headerRlp: s.evA.headerRlp } }).ok, false, "another block's header");
171
+ assert.equal(bad(good, s.b[2]!, { writer: stranger.address.toLowerCase() }).ok, false, "a different expected writer");
172
+ const forged = publish(s.cdB, { from: stranger });
173
+ assert.equal(bad({ ...good, write: forged }, s.b[2]!).ok, false, "the same calldata sent by someone else");
174
+ assert.equal(bad({ ...good, floor: { ...floor, note: s.note.replace("block: 38000000", "block: 37999999") } }).ok, false, "a floor note that is not what the floor binds");
175
+ assert.equal(bad({ ...good, floor: { ...floor, proof: fakeProof(14, EPOCH, floorNoteDigestB64(s.note)) } }).ok, false, "a floor after the proof");
176
+ assert.equal(bad({ ...good, floor: { ...floor, proof: fakeProof(8, OTHER_EPOCH, floorNoteDigestB64(s.note)) } }).ok, false, "a floor from another epoch");
177
+ assert.equal(bad({ ...good, floor: { ...floor, hourCalldata: evmBytesToHex(s.cdA) } }).ok, false, "a floor in a tree that is not this write's nor the one before");
178
+ const otherKey = { ...s.floor, signer: { publicKeyB64: bytesToB64(new Uint8Array(32).fill(5)), signatureB64: "AA==" } };
179
+ assert.equal(bad({ ...good, floor: { ...floor, proof: otherKey } }).ok, false, "a floor signed by another key (anyone can make one)");
180
+ assert.deepEqual(bad({ ...good, floor: { ...floor, proof: null as never } }).problems, ["the floor is malformed"], "a malformed floor is a problem, not a throw");
181
+ assert.deepEqual(bad(good).problems, [], "and the untouched block still checks");
182
+ });
183
+
184
+ test("a proof outside the write's range is refused", () => {
185
+ const s = scenario();
186
+ const outside = attach(s.b[2]!, { ...blockFor(s.b[2]!, 2, s.treeB, s.cdB, s.evB, null), calldata: evmBytesToHex(encodeHourCalldata({ epochId: EPOCH, first: 8, last: 10, leaves: 3, rootHex: s.treeB.rootHex, prevLinkHex: hourLink(s.cdA) })) });
187
+ assert.equal(checkPublication(outside).ok, false);
188
+ });
189
+
190
+ test("no block, no check", () => {
191
+ assert.equal(checkPublication(fakeProof(2)).ok, false);
192
+ });
193
+ });
194
+
195
+ describe("the chain of hourly writes", () => {
196
+ test("writes link in order, quiet hours count, and a broken link or wrong members show", () => {
197
+ const s = scenario();
198
+ const quiet = encodeHourCalldata({ epochId: EPOCH, first: 12, last: 12, leaves: 0, rootHex: ZERO, prevLinkHex: hourLink(s.cdB) });
199
+ const rec = (cd: Uint8Array, ev: WriteEvidence, members: Record<string, unknown>[]): HourRecord => ({
200
+ format: HOUR_RECORD_FORMAT, calldata: evmBytesToHex(cd), link: hourLink(cd), write: ev,
201
+ members: members.map((m) => ({ counter: (m["commit"] as { counter: string }).counter, chainHashB64: publishedChainHash(m) })), missing: [], writtenAt: "2026-11-13T00:00:00.000Z",
202
+ });
203
+ const run = [rec(s.cdA, s.evA, s.a), rec(s.cdB, s.evB, s.b), rec(quiet, publish(quiet), [])];
204
+ const ok = checkHourChain(run);
205
+ assert.deepEqual(ok.problems, []);
206
+ assert.equal(ok.quietHours, 1);
207
+ assert.equal(checkHourChain([run[0]!, run[2]!]).ok, false, "a missing hour breaks the links");
208
+ assert.equal(checkHourChain([run[0]!, { ...run[1]!, members: run[1]!.members.slice(1) }]).ok, false, "members that do not make the root");
209
+ });
210
+ });
@@ -0,0 +1,98 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc.
2
+
3
+ /**
4
+ * A real bitgraph-tot-v2 receipt (spec/vectors/bitgraph-tot-v2-real/), checked with the real inputs: the first
5
+ * receipt of enclave image v14, which binds spec/BITGRAPH-TOT-2.md. The released version 2 vectors are made under
6
+ * test inputs with definite-length attestation documents; this one carries what AWS's hardware writes.
7
+ *
8
+ * Also here: what the check says of fields that sit in a TOT beside the signed ones.
9
+ */
10
+
11
+ import { test } from "node:test";
12
+ import assert from "node:assert/strict";
13
+ import { readFileSync } from "node:fs";
14
+ import { verifyTotReceipt, checkTotFloor } from "@mikeargento/bitgraph-audit";
15
+
16
+ const at = (p: string) => new URL(`../../../../${p}`, import.meta.url);
17
+ const RECEIPT = JSON.parse(readFileSync(at("spec/vectors/bitgraph-tot-v2-real/receipt.json"), "utf8"));
18
+ const BLOCK = JSON.parse(readFileSync(at("spec/vectors/bitgraph-tot-v2-real/base-block-66095720.json"), "utf8"));
19
+ const SPEC = new Uint8Array(readFileSync(at("spec/BITGRAPH-TOT-2.md")));
20
+ const V2 = JSON.parse(readFileSync(at("spec/vectors/bitgraph-tot-v2.json"), "utf8"));
21
+ const V1 = JSON.parse(readFileSync(at("spec/vectors/bitgraph-tot-v1.json"), "utf8"));
22
+ const testInputs = { rootDer: new Uint8Array(Buffer.from(V2.testTrustInputs.rootDerB64, "base64")), measurements: V2.testTrustInputs.acceptedMeasurements as string[] };
23
+
24
+ /** The first byte of a COSE_Sign1 document's payload: [protected, unprotected, payload, signature]. */
25
+ function payloadFirstByte(reportB64: string): number {
26
+ const d = Buffer.from(reportB64, "base64");
27
+ let i = d[0] === 0xd2 ? 1 : 0; // an optional tag 18
28
+ assert.equal(d[i], 0x84, "an array of four");
29
+ i += 1;
30
+ const skipBstr = (): void => {
31
+ const b = d[i]!;
32
+ assert.equal(b >> 5, 2, "a byte string");
33
+ const n = b & 0x1f;
34
+ if (n < 24) i += 1 + n;
35
+ else if (n === 24) i += 2 + d[i + 1]!;
36
+ else if (n === 25) i += 3 + d.readUInt16BE(i + 1);
37
+ else throw new Error("unexpected length");
38
+ };
39
+ skipBstr(); // protected
40
+ assert.equal(d[i], 0xa0, "an empty unprotected map");
41
+ i += 1;
42
+ const b = d[i]!;
43
+ assert.equal(b >> 5, 2, "the payload is a byte string");
44
+ const n = b & 0x1f;
45
+ return d[i + (n < 24 ? 1 : n === 24 ? 2 : 3)]!;
46
+ }
47
+
48
+ test("the real v14 receipt is accepted with the real inputs, with its file and without", async () => {
49
+ const withFile = await verifyTotReceipt({ receipt: RECEIPT, file: SPEC });
50
+ assert.equal(withFile.verdict, "ACCEPT", withFile.reason);
51
+ assert.equal(withFile.file, "compared");
52
+ assert.equal(withFile.attestedAt, "2026-12-04T18:38:39.740Z");
53
+ assert.deepEqual(withFile.floor, { network: "eip155:8453", number: "66095720", hashB64: "G9xjlrSMxrcJ6qaehB3xwqagBThiViOlXCUo+Q+Lg/k=" });
54
+ assert.equal(withFile.unsignedTotFields, undefined);
55
+ assert.equal((await verifyTotReceipt({ receipt: RECEIPT })).verdict, "ACCEPT");
56
+ // Another file is not the one it binds, and the test inputs do not accept it.
57
+ assert.equal((await verifyTotReceipt({ receipt: RECEIPT, file: new Uint8Array([1, 2, 3]) })).verdict, "REJECT");
58
+ assert.equal((await verifyTotReceipt({ receipt: RECEIPT, ...testInputs })).verdict, "REJECT");
59
+ });
60
+
61
+ test("a real attestation document is a CBOR map of indefinite length; the test documents are not", () => {
62
+ assert.equal(payloadFirstByte(RECEIPT.environment.attestation.reportB64), 0xbf);
63
+ assert.equal(payloadFirstByte(V1.receipts.find((r: { name: string }) => r.name === "valid").receipt.environment.attestation.reportB64), 0xbf);
64
+ for (const v of V2.receipts) assert.notEqual(payloadFirstByte(v.receipt.environment.attestation.reportB64), 0xbf, v.name);
65
+ });
66
+
67
+ test("its floor against the block Base returned: confirmed for a supplied block, 140 ms before the attestation", async () => {
68
+ const c = await checkTotFloor({ receipt: RECEIPT, attestedAt: "2026-12-04T18:38:39.740Z", maxFloorGapMs: 2000, block: BLOCK });
69
+ assert.equal(c.status, "confirmed");
70
+ assert.equal(c.source, "supplied", "the block came from a file here, not from the chain");
71
+ assert.equal(c.timeBoundByHash, true);
72
+ assert.equal(c.blockTimeMs, 1796409519600);
73
+ assert.equal(c.gapMs, 140);
74
+ assert.equal(c.stale, false);
75
+ });
76
+
77
+ test("a field beside a slot/1 TOT's signed ones is not refused, and is named as unsigned", async () => {
78
+ const v = V2.receipts.find((r: { name: string }) => r.name === "without-floor");
79
+ assert.equal(v.receipt.slotAllocation.version, "bitgraph/slot/1");
80
+ const plain = await verifyTotReceipt({ receipt: v.receipt, ...testInputs });
81
+ assert.equal(plain.verdict, "ACCEPT");
82
+ assert.equal(plain.unsignedTotFields, undefined);
83
+ const noted = { ...v.receipt, slotAllocation: { ...v.receipt.slotAllocation, note: "made after block 1", zeta: "x" } };
84
+ const r = await verifyTotReceipt({ receipt: noted, ...testInputs });
85
+ assert.equal(r.verdict, "ACCEPT", "version 1 of the format does not refuse it");
86
+ assert.deepEqual(r.unsignedTotFields, ["note", "zeta"]);
87
+ assert.equal(r.floor, undefined, "nothing unsigned is read as a floor");
88
+ // The same field beside a slot/2 TOT is refused outright.
89
+ const w = V2.receipts.find((x: { name: string }) => x.name === "with-floor");
90
+ const refused = await verifyTotReceipt({ receipt: { ...w.receipt, slotAllocation: { ...w.receipt.slotAllocation, note: "x" } }, ...testInputs });
91
+ assert.equal(refused.verdict, "REJECT");
92
+ assert.match(String(refused.reason), /^R1 form: /);
93
+ // No real receipt of version 1 carries one.
94
+ for (const x of V1.receipts) {
95
+ const got = await verifyTotReceipt({ receipt: x.receipt });
96
+ if (got.verdict === "ACCEPT") assert.equal(got.unsignedTotFields, undefined, x.name);
97
+ }
98
+ });