@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
package/src/tot.ts ADDED
@@ -0,0 +1,268 @@
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
+ /** What a bitgraph/slot/1 TOT holds, its signature included. Anything else in the record is outside the signature. */
52
+ const SLOT_1_FIELDS: ReadonlySet<string> = new Set(["chainId", "counter", "epochId", "nonceB64", "publicKeyB64", "signatureB64", "version"]);
53
+
54
+ export interface TotVerdict {
55
+ verdict: "ACCEPT" | "REJECT";
56
+ /** Why it was refused; absent on ACCEPT. */
57
+ reason?: string;
58
+ /** Whether a file was compared with the receipt's digest. */
59
+ file: "compared" | "not-compared";
60
+ /** The attestation document's own time, when the receipt was accepted (ISO 8601). */
61
+ attestedAt?: string;
62
+ /** The attestation's checks, in order, when the document was read. */
63
+ checks: NitroCheck[];
64
+ /** The public floor signed into the TOT, when the receipt was accepted and its TOT carries one. Not yet looked up. */
65
+ floor?: SlotFloor;
66
+ /**
67
+ * On ACCEPT of a bitgraph/slot/1 TOT: the names of fields that sit in `slotAllocation` beside the ones the
68
+ * enclave signed. The format does not refuse them (a slot/2 TOT is refused for one). They are under no
69
+ * signature, carry no claim and are never read; they are named so that a tool does not show one as if the
70
+ * enclave had said it. Absent when there are none.
71
+ */
72
+ unsignedTotFields?: string[];
73
+ }
74
+
75
+ const B64_32 = (s: unknown): boolean => {
76
+ if (typeof s !== "string") return false;
77
+ {
78
+ const b = Buffer.from(s, "base64");
79
+ return b.length === 32 && b.toString("base64") === s;
80
+ }
81
+ };
82
+ const DEC = /^(0|[1-9][0-9]*)$/;
83
+ const HEX96 = /^[0-9a-f]{96}$/;
84
+ const isObject = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v);
85
+
86
+ /** R1, the receipt's form: every field this format requires, in the shape it requires. Null when it is in form. */
87
+ export function totFormProblem(receipt: unknown): string | null {
88
+ if (!isObject(receipt)) return "the receipt is not a JSON object";
89
+ const r = receipt;
90
+ if (r["version"] !== "bitgraph/1") return 'version must be "bitgraph/1"';
91
+ const a = r["artifact"];
92
+ if (!isObject(a) || a["hashAlg"] !== "sha256" || !B64_32(a["digestB64"])) return "artifact must be {hashAlg: \"sha256\", digestB64: 32 bytes in canonical base64}";
93
+ const c = r["commit"];
94
+ if (!isObject(c)) return "commit is missing";
95
+ if (c["atomic"] !== true) return "commit.atomic must be true";
96
+ if (!B64_32(c["nonceB64"])) return "commit.nonceB64 must be 32 bytes in canonical base64";
97
+ if (typeof c["counter"] !== "string" || !DEC.test(c["counter"])) return "commit.counter must be a decimal string";
98
+ if (typeof c["slotCounter"] !== "string" || !DEC.test(c["slotCounter"])) return "commit.slotCounter must be a decimal string";
99
+ if (!B64_32(c["slotHashB64"])) return "commit.slotHashB64 must be 32 bytes in canonical base64";
100
+ if (!B64_32(c["epochId"])) return "commit.epochId must be 32 bytes in canonical base64";
101
+ if (c["prevB64"] !== undefined && !B64_32(c["prevB64"])) return "commit.prevB64, when present, must be 32 bytes in canonical base64";
102
+ if (c["chainId"] !== "bitgraph:main") return 'commit.chainId must be "bitgraph:main"';
103
+ const s = r["signer"];
104
+ if (!isObject(s) || !B64_32(s["publicKeyB64"]) || typeof s["signatureB64"] !== "string") return "signer must carry publicKeyB64 (32 bytes) and signatureB64";
105
+ const e = r["environment"];
106
+ if (!isObject(e)) return "environment is missing";
107
+ if (e["enforcement"] !== "measured-tee") return 'environment.enforcement must be "measured-tee"';
108
+ if (typeof e["measurement"] !== "string" || !HEX96.test(e["measurement"])) return "environment.measurement must be 96 lowercase hex characters";
109
+ const at = e["attestation"];
110
+ if (!isObject(at) || at["format"] !== "aws-nitro" || typeof at["reportB64"] !== "string" || at["reportB64"].length === 0) return 'environment.attestation must be {format: "aws-nitro", reportB64}';
111
+ const t = r["slotAllocation"];
112
+ if (!isObject(t)) return "slotAllocation (the TOT) is missing";
113
+ if (t["version"] !== SLOT_1 && t["version"] !== SLOT_2) return 'slotAllocation.version must be "bitgraph/slot/1" or "bitgraph/slot/2"';
114
+ // A floor is signed in a slot/2 TOT and absent from a slot/1 TOT. A slot/2 TOT holds its listed fields and no others.
115
+ const floor = slotFloorProblem(t);
116
+ if (floor) return floor;
117
+ if (t["version"] === SLOT_2 && Object.keys(t).sort().join(",") !== SLOT_2_FIELDS) return "a bitgraph/slot/2 slotAllocation must hold exactly its listed fields";
118
+ if (typeof t["counter"] !== "string" || !DEC.test(t["counter"])) return "slotAllocation.counter must be a decimal string";
119
+ if (t["time"] !== undefined) return "slotAllocation.time must be absent";
120
+ if (!B64_32(t["nonceB64"]) || !B64_32(t["epochId"]) || !B64_32(t["publicKeyB64"])) return "slotAllocation.nonceB64, epochId and publicKeyB64 must each be 32 bytes in canonical base64";
121
+ if (t["chainId"] !== "bitgraph:main") return 'slotAllocation.chainId must be "bitgraph:main"';
122
+ if (typeof t["signatureB64"] !== "string") return "slotAllocation.signatureB64 is missing";
123
+ return null;
124
+ }
125
+
126
+ const PRINTABLE_ASCII = /^[\x20-\x7e]*$/;
127
+
128
+ /** R2: a signed record holds only strings, booleans and objects, with printable ASCII in every key and string. */
129
+ function recordProblem(value: unknown, path: string): string | null {
130
+ if (typeof value === "boolean") return null;
131
+ if (typeof value === "string") return PRINTABLE_ASCII.test(value) ? null : `${path} holds a character outside printable ASCII`;
132
+ if (!isObject(value)) return `${path} is not a string, boolean or object`;
133
+ for (const [k, v] of Object.entries(value)) {
134
+ if (!PRINTABLE_ASCII.test(k)) return `${path} has a key outside printable ASCII`;
135
+ const p = recordProblem(v, `${path}.${k}`);
136
+ if (p) return p;
137
+ }
138
+ return null;
139
+ }
140
+
141
+ /** The check of one receipt, with the file when it is given. */
142
+ export async function verifyTotReceipt(opts: {
143
+ receipt: unknown;
144
+ file?: Uint8Array;
145
+ /** The accepted measurements. Default: TOT_MEASUREMENTS, both formats'. */
146
+ measurements?: readonly string[];
147
+ /** A different root certificate (DER), for tests against a non-AWS chain. */
148
+ rootDer?: Uint8Array;
149
+ }): Promise<TotVerdict> {
150
+ const file = opts.file !== undefined ? "compared" : "not-compared";
151
+ const form = totFormProblem(opts.receipt);
152
+ if (form) return { verdict: "REJECT", reason: `R1 form: ${form}`, file, checks: [] };
153
+ const p = opts.receipt as BitGraphProof;
154
+ const { signatureB64: _sig, ...totBody } = p.slotAllocation as unknown as Record<string, unknown>;
155
+ const records = recordProblem(buildSignedBody(p), "the signed body") ?? recordProblem(totBody, "the TOT body");
156
+ if (records) return { verdict: "REJECT", reason: `R2 canonical records: ${records}`, file, checks: [] };
157
+ const r = await verifyAttested({
158
+ proof: opts.receipt as BitGraphProof,
159
+ ...(opts.file !== undefined ? { bytes: opts.file } : {}),
160
+ pcr0: opts.measurements ?? TOT_MEASUREMENTS,
161
+ ...(opts.rootDer ? { rootDer: opts.rootDer } : {}),
162
+ });
163
+ if (!r.valid) return { verdict: "REJECT", reason: r.reason ?? "the receipt does not verify", file, checks: r.checks };
164
+ // A slot/2 TOT was held to its exact fields by R1, so only a slot/1 TOT can carry anything beside them.
165
+ const tot = p.slotAllocation as unknown as Record<string, unknown>;
166
+ const unsigned = tot["version"] === SLOT_1 ? Object.keys(tot).filter((k) => !SLOT_1_FIELDS.has(k)).sort() : [];
167
+ return {
168
+ verdict: "ACCEPT",
169
+ file,
170
+ ...(r.attestedAtMs !== null ? { attestedAt: new Date(r.attestedAtMs).toISOString() } : {}),
171
+ checks: r.checks,
172
+ ...(totFloorOf(p) ? { floor: totFloorOf(p)! } : {}),
173
+ ...(unsigned.length > 0 ? { unsignedTotFields: unsigned } : {}),
174
+ };
175
+ }
176
+
177
+ /**
178
+ * The optional online step for a receipt whose TOT carries a floor (bitgraph-tot-v2, section 4): look the block up
179
+ * on its chain. It is run only on a receipt the offline check already accepted, and whatever it answers, that
180
+ * verdict stands.
181
+ *
182
+ * confirmed the chain holds that block: the TOT was made after it. The block's time and the gap from it to
183
+ * the attestation's time are reported; `stale` is set when maxFloorGapMs is given and exceeded.
184
+ * not-confirmed the chain has no such block, or another one at that number: the floor shows nothing.
185
+ * not-checked the lookup could not be made.
186
+ * none the TOT carries no floor.
187
+ *
188
+ * Pass `block` (what the chain says, or null for "no such block") to apply the rule with no network. The answer
189
+ * then carries `source: "supplied"`: it is as good as where the block came from, and a block that did not come
190
+ * from the chain shows nothing. Without `block` the chain is asked and the answer carries `source: "lookup"`.
191
+ */
192
+ export async function checkTotFloor(opts: {
193
+ receipt: unknown;
194
+ /** The accepted receipt's attestation time, from its verdict's attestedAt. */
195
+ attestedAt?: string;
196
+ /** Flag the floor as stale when the attestation is more than this long after the block. */
197
+ maxFloorGapMs?: number;
198
+ rpcUrl?: string;
199
+ fetcher?: typeof fetch;
200
+ block?: (Partial<RpcBlockHeader> & { timestampMs?: string }) | null;
201
+ }): Promise<FloorCheck> {
202
+ if (totFormProblem(opts.receipt) !== null) return { status: "none" };
203
+ const proof = opts.receipt as BitGraphProof;
204
+ const at = opts.attestedAt !== undefined ? Date.parse(opts.attestedAt) : NaN;
205
+ const common = {
206
+ proof,
207
+ ...(Number.isFinite(at) ? { attestedAtMs: at } : {}),
208
+ ...(opts.maxFloorGapMs !== undefined ? { maxGapMs: opts.maxFloorGapMs } : {}),
209
+ };
210
+ if (opts.block !== undefined) return checkFloorAgainstBlock({ ...common, block: opts.block });
211
+ return checkFloorOnline({ ...common, ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}), ...(opts.fetcher ? { fetcher: opts.fetcher } : {}) });
212
+ }
213
+
214
+ /** The set rule's reasons: two receipts spend one TOT, or two TOTs claim one position. */
215
+ export type SpentTwiceCode = "DUPLICATE_TOT" | "DUPLICATE_TOT_POSITION";
216
+
217
+ export interface SpentTwice {
218
+ /** DUPLICATE_TOT: the receipts carry the same TOT. DUPLICATE_TOT_POSITION: different TOTs at one position (the same
219
+ * key, epoch, chain and count). */
220
+ code: SpentTwiceCode;
221
+ /** The indexes, in the set given, of the receipts that spend it. */
222
+ receipts: number[];
223
+ }
224
+
225
+ /**
226
+ * The set check (section 8): every TOT is spent once. Two receipts that differ in their signed bodies and carry the same
227
+ * TOT, or two different TOTs at one position (the same key, epoch, chain and count), are refused together. The same
228
+ * receipt given twice is one receipt, not two. Only receipts whose signatures and TOT binding hold are counted.
229
+ */
230
+ export async function checkSpentOnce(receipts: readonly unknown[]): Promise<{ verdict: "ACCEPT" | "REJECT"; reason?: SpentTwiceCode; spentTwice: SpentTwice[]; counted: number[] }> {
231
+ const byTot = new Map<string, Map<string, number[]>>();
232
+ const byPosition = new Map<string, Map<string, number[]>>();
233
+ const add = (m: Map<string, Map<string, number[]>>, key: string, body: string, i: number): void => {
234
+ const bodies = m.get(key) ?? new Map<string, number[]>();
235
+ const list = bodies.get(body) ?? [];
236
+ list.push(i);
237
+ bodies.set(body, list);
238
+ m.set(key, bodies);
239
+ };
240
+ const counted: number[] = [];
241
+ for (const [i, r] of receipts.entries()) {
242
+ if (!isObject(r) || !isObject(r["slotAllocation"]) || !isObject(r["commit"]) || r["commit"]["atomic"] !== true) continue;
243
+ const p = r as unknown as BitGraphProof;
244
+ // R2: both signed records hold only what the format allows.
245
+ const { signatureB64: _sig, ...totBody } = r["slotAllocation"];
246
+ let inForm = false;
247
+ try { inForm = recordProblem(buildSignedBody(p), "the signed body") === null && recordProblem(totBody, "the TOT body") === null; } catch { inForm = false; }
248
+ if (!inForm) continue;
249
+ const ok = await verifyProofIntegrity({ proof: p, trustAnchors: { requireAtomic: true }, context: createVerificationContext() });
250
+ if (!ok.valid) continue;
251
+ counted.push(i);
252
+ const t = p.slotAllocation!;
253
+ const body = computeSignedBodyHash(p);
254
+ const totHash = Buffer.from(computeSlotRecordHash(t)).toString("base64");
255
+ add(byTot, totHash, body, i);
256
+ add(byPosition, `${t.publicKeyB64}|${t.epochId}|${t.chainId ?? ""}|${t.counter}`, `${totHash}|${body}`, i);
257
+ }
258
+ const spentTwice: SpentTwice[] = [];
259
+ for (const bodies of byTot.values()) {
260
+ if (bodies.size > 1) spentTwice.push({ code: "DUPLICATE_TOT", receipts: [...bodies.values()].map((l) => l[0]!).sort((a, b) => a - b) });
261
+ }
262
+ for (const bodies of byPosition.values()) {
263
+ const tots = new Set([...bodies.keys()].map((k) => k.split("|")[0]));
264
+ if (tots.size > 1) spentTwice.push({ code: "DUPLICATE_TOT_POSITION", receipts: [...bodies.values()].map((l) => l[0]!).sort((a, b) => a - b) });
265
+ }
266
+ const first = spentTwice[0];
267
+ return first ? { verdict: "REJECT", reason: first.code, spentTwice, counted } : { verdict: "ACCEPT", spentTwice, counted };
268
+ }