@mikeargento/bitgraph-verify 1.15.2 → 1.17.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 (66) hide show
  1. package/README.md +24 -3
  2. package/dist/__tests__/carrier2.test.js +62 -3
  3. package/dist/__tests__/carrier2.test.js.map +1 -1
  4. package/dist/__tests__/ceiling.test.js +11 -4
  5. package/dist/__tests__/ceiling.test.js.map +1 -1
  6. package/dist/carrier-assemble.d.ts +12 -2
  7. package/dist/carrier-assemble.d.ts.map +1 -1
  8. package/dist/carrier-assemble.js +14 -3
  9. package/dist/carrier-assemble.js.map +1 -1
  10. package/dist/carrier-verify.d.ts +15 -4
  11. package/dist/carrier-verify.d.ts.map +1 -1
  12. package/dist/carrier-verify.js +201 -59
  13. package/dist/carrier-verify.js.map +1 -1
  14. package/dist/carrier.d.ts +48 -13
  15. package/dist/carrier.d.ts.map +1 -1
  16. package/dist/carrier.js +74 -16
  17. package/dist/carrier.js.map +1 -1
  18. package/dist/ceiling.d.ts +115 -6
  19. package/dist/ceiling.d.ts.map +1 -1
  20. package/dist/ceiling.js +189 -23
  21. package/dist/ceiling.js.map +1 -1
  22. package/dist/export.d.ts +122 -0
  23. package/dist/export.d.ts.map +1 -0
  24. package/dist/export.js +510 -0
  25. package/dist/export.js.map +1 -0
  26. package/dist/fuse.d.ts +45 -11
  27. package/dist/fuse.d.ts.map +1 -1
  28. package/dist/fuse.js +100 -18
  29. package/dist/fuse.js.map +1 -1
  30. package/dist/index.d.ts +20 -2
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +18 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/measurements.d.ts +30 -0
  35. package/dist/measurements.d.ts.map +1 -0
  36. package/dist/measurements.js +22 -0
  37. package/dist/measurements.js.map +1 -0
  38. package/dist/output-root.d.ts +88 -0
  39. package/dist/output-root.d.ts.map +1 -0
  40. package/dist/output-root.js +260 -0
  41. package/dist/output-root.js.map +1 -0
  42. package/dist/stream.d.ts +46 -0
  43. package/dist/stream.d.ts.map +1 -0
  44. package/dist/stream.js +290 -0
  45. package/dist/stream.js.map +1 -0
  46. package/dist/tree.d.ts +167 -0
  47. package/dist/tree.d.ts.map +1 -0
  48. package/dist/tree.js +485 -0
  49. package/dist/tree.js.map +1 -0
  50. package/dist/types.d.ts +21 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/package.json +1 -1
  53. package/src/__tests__/carrier2.test.ts +65 -3
  54. package/src/__tests__/ceiling.test.ts +12 -4
  55. package/src/carrier-assemble.ts +21 -3
  56. package/src/carrier-verify.ts +204 -61
  57. package/src/carrier.ts +95 -27
  58. package/src/ceiling.ts +217 -28
  59. package/src/export.ts +592 -0
  60. package/src/fuse.ts +126 -23
  61. package/src/index.ts +47 -1
  62. package/src/measurements.ts +49 -0
  63. package/src/output-root.ts +301 -0
  64. package/src/stream.ts +291 -0
  65. package/src/tree.ts +580 -0
  66. package/src/types.ts +22 -0
package/src/export.ts ADDED
@@ -0,0 +1,592 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * bitgraph-export/1: one JSON file that, with the file it is about, checks a
5
+ * tree/1 BitGraph with nothing of BitGraph's required (2026-10-03).
6
+ *
7
+ * {
8
+ * "format": "bitgraph-export/1",
9
+ * "spec": base64 SHA-256 of SPEC.md (informational; the proof's SIGNED attribution.message is authoritative),
10
+ * "proof": the signed bitgraph/1 proof,
11
+ * "tree": { "rootDocument": hex(84 bytes),
12
+ * "member": TreeMemberEvidence one file's export
13
+ * or "leaves": base64(count x 65 bytes), the owner's export
14
+ * "names"?: [file name per leaf] }, unsigned, informational
15
+ * "floor": { "chain"?, "blockNumber", "blockHash", "header" } | null, chain: "ethereum" (absent) or "base"
16
+ * "ceiling": a bitgraph-ceiling/1 sidecar | { "status": "pending" } | null,
17
+ * "settlement": a bitgraph-output-root/1 settlement | { "status": "pending", "baseBlock"? } | null
18
+ * }
19
+ *
20
+ * verifyExport answers one line per claim, each saying what it rests on, at
21
+ * two levels: OFFLINE (every link recomputed from the bytes, block headers
22
+ * taken as the ones matching their hashes) and CONFIRMED (the caller's own
23
+ * lookups say those blocks are the chains' own). This module never fetches.
24
+ *
25
+ * Three time claims, never merged:
26
+ * floor the committed bytes were finished after the floor block N, on the chain the
27
+ * proof signs: an Ethereum anchor (commit.slotAnchor, enclave v7 to v9) or a Base
28
+ * block (commit.slotFloor, enclave v10) (needs N canonical on that chain)
29
+ * ceiling.base the record existed by Base block B, at B's time (needs B canonical on Base; provisional until then)
30
+ * ceiling.ethereum the record existed by Ethereum block H (needs H canonical; Base's honesty not needed)
31
+ */
32
+
33
+ import { sha256 } from "@noble/hashes/sha256";
34
+ import { verifyProofIntegrity, createVerificationContext } from "./verifier.js";
35
+ import { computeSignedBodyHash } from "./proof-hash.js";
36
+ import { verifyNitroAttestation } from "./nitro.js";
37
+ import { CEILING_VERSION, baseTimeIsBound, checkFloorHeader, floorTimeIsBound, verifyCeiling, type CeilingSidecar } from "./ceiling.js";
38
+ import { hexToBytes as evmHex } from "./ceiling-evm.js";
39
+ import { base64ToBytes, bytesEqual, hexToBytes, signedFloorOf, type SignedFloor } from "./fuse.js";
40
+ import { OUTPUT_ROOT_VERSION, verifyOutputRootSettlement, type OutputRootSettlement } from "./output-root.js";
41
+ import { MerkleTree } from "./fuse-merkle.js";
42
+ import { streamDigest, type ByteSource } from "./stream.js";
43
+ import { PUBLISHED_PCR0S, publishedMeasurement } from "./measurements.js";
44
+ import {
45
+ buildTreeMemberEvidence,
46
+ decodeTreeLeaves,
47
+ TREE_MEMBER_CATEGORIES,
48
+ treeLeafHash,
49
+ verifyTreeLeaves,
50
+ verifyTreeMember,
51
+ type TreeMemberEvidence,
52
+ type TreeVerifyResult,
53
+ } from "./tree.js";
54
+ import type { BitGraphProof } from "./types.js";
55
+
56
+ export const EXPORT_FORMAT = "bitgraph-export/1" as const;
57
+
58
+ export interface BitGraphExport {
59
+ format: typeof EXPORT_FORMAT;
60
+ spec: string;
61
+ proof: BitGraphProof;
62
+ tree: {
63
+ rootDocument: string;
64
+ member?: TreeMemberEvidence;
65
+ leaves?: string;
66
+ names?: string[];
67
+ };
68
+ /** The floor block's header. `chain` absent is Ethereum (every export before enclave v10); "base" a Base floor. */
69
+ floor: { chain?: "ethereum" | "base"; blockNumber: number; blockHash: string; header: string } | null;
70
+ ceiling: CeilingSidecar | { status: "pending" } | null;
71
+ settlement: OutputRootSettlement | { status: "pending"; baseBlock?: number } | null;
72
+ }
73
+
74
+ export type ExportClaimResult = "TRUE" | "FALSE" | "UNDETERMINED" | "NOT_CARRIED";
75
+
76
+ export interface ExportClaim {
77
+ id: string;
78
+ name: string;
79
+ result: ExportClaimResult;
80
+ restsOn: string;
81
+ detail: string;
82
+ level: "offline" | "confirmed";
83
+ }
84
+
85
+ export interface ExportLookups {
86
+ /** Ethereum mainnet: the chain's block hash at a height, or null. */
87
+ ethereumBlockHash?: (blockNumber: number) => Promise<string | null>;
88
+ /** Base mainnet: the chain's block hash at a height, or null. */
89
+ baseBlockHash?: (blockNumber: number) => Promise<string | null>;
90
+ }
91
+
92
+ export interface ExportVerifyOptions {
93
+ /** The file in hand (the original or the committed bytes). Without it, the claims about the file are NOT_CARRIED. */
94
+ bytes?: Uint8Array;
95
+ /** The file in hand as a stream (stream.ts): the same judgment as `bytes` for a file of any size. An owner's export reads it twice (once to find the leaf). */
96
+ source?: ByteSource;
97
+ lookups?: ExportLookups;
98
+ pins?: {
99
+ /**
100
+ * PCR0 values the verifier accepts. Default: BitGraph's published images
101
+ * (SPEC section 16, PUBLISHED_PCR0S), so a proof from any other enclave
102
+ * image is not a BitGraph. An empty list accepts nothing and leaves the
103
+ * claim, and so the verdict, undetermined.
104
+ */
105
+ pcr0?: readonly string[];
106
+ ceilingWriter?: string;
107
+ baseChainId?: number;
108
+ /** The chain the settlement is on. Default Ethereum mainnet, 1. */
109
+ ethereumChainId?: number;
110
+ /** Another attestation trust root, DER, for a verifier that pins its own (tests use this). Default: the embedded AWS Nitro root. */
111
+ rootDer?: Uint8Array;
112
+ };
113
+ /** Spec hashes (base64) to accept beyond the ones this verifier knows. */
114
+ extraSpecHashes?: readonly string[];
115
+ }
116
+
117
+ export interface ExportVerifyResult {
118
+ verdict: "TRUE" | "FALSE" | "UNDETERMINED";
119
+ reasons: string[];
120
+ claims: ExportClaim[];
121
+ /** The member the file matched (or the export's own member), when one did. */
122
+ member: TreeVerifyResult["member"];
123
+ /** What the floor covers for the file in hand: "content" (placements 0x01-0x03: the committed bytes), "record" (as is: the record only), or null when no file was matched. */
124
+ floorCovers: TreeVerifyResult["floorCovers"];
125
+ /** The three time claims, as established. Null fields were not established. */
126
+ times: {
127
+ /** `chain` is present only for a Base floor, so an Ethereum floor's result is exactly what it was before enclave v10. */
128
+ floor: { chain?: "base"; blockNumber: number; blockHash: string; blockTimestamp: number } | null;
129
+ ceilingBase: { chainId: number; blockNumber: number; blockHash: string; blockTimestamp: number; provisional: boolean } | null;
130
+ ceilingEthereum: { chainId: number; blockNumber: number; blockHash: string; blockTimestamp: number } | null;
131
+ };
132
+ /**
133
+ * Why the Base block's time is not stated as a bound, when it is not: the
134
+ * block was stamped earlier than the floor block or the attestation
135
+ * document (see baseTimeIsBound). The inclusion itself still holds.
136
+ */
137
+ baseTimeWithheld: string | null;
138
+ /**
139
+ * Why the floor block's time is not stated as a bound, when it is not: the
140
+ * block is stamped after the attestation document (see floorTimeIsBound).
141
+ * The floor itself still holds: the record was made after that block.
142
+ */
143
+ floorTimeWithheld: string | null;
144
+ /** Plain language, written from the claims. */
145
+ reading: string;
146
+ }
147
+
148
+ /** Parse an export from JSON text or a parsed object. Structural only; null when it is not export/1. */
149
+ export function parseExport(input: unknown): BitGraphExport | null {
150
+ let v: unknown = input;
151
+ if (typeof input === "string") {
152
+ try {
153
+ v = JSON.parse(input);
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return null;
159
+ const e = v as Record<string, unknown>;
160
+ if (e["format"] !== EXPORT_FORMAT) return null;
161
+ if (typeof e["proof"] !== "object" || e["proof"] === null) return null;
162
+ const tree = e["tree"] as Record<string, unknown> | undefined;
163
+ if (!tree || typeof tree !== "object" || typeof tree["rootDocument"] !== "string") return null;
164
+ return v as BitGraphExport;
165
+ }
166
+
167
+ const iso = (unix: number) => new Date(unix * 1000).toISOString().replace(".000Z", "Z");
168
+ export async function verifyExport(input: unknown, opts: ExportVerifyOptions = {}): Promise<ExportVerifyResult> {
169
+ const claims: ExportClaim[] = [];
170
+ const add = (id: string, name: string, result: ExportClaimResult, restsOn: string, detail: string, level: "offline" | "confirmed" = "offline") =>
171
+ claims.push({ id, name, result, restsOn, detail, level });
172
+ const times: ExportVerifyResult["times"] = { floor: null, ceilingBase: null, ceilingEthereum: null };
173
+ let member: TreeVerifyResult["member"] = null;
174
+
175
+ let baseTimeWithheld: string | null = null;
176
+ let floorTimeWithheld: string | null = null;
177
+
178
+ const exp = parseExport(input);
179
+ if (exp === null) {
180
+ // A document that says it is export/1 and lacks its parts is broken; one
181
+ // in another format is not judged here.
182
+ let declared: unknown;
183
+ try {
184
+ declared = ((typeof input === "string" ? JSON.parse(input) : input) as { format?: unknown } | null)?.format;
185
+ } catch {
186
+ declared = undefined;
187
+ }
188
+ if (declared === EXPORT_FORMAT) add("format", "This is a bitgraph-export/1 file", "FALSE", "its structure", "it says bitgraph-export/1 but lacks the parts that format requires (proof, tree.rootDocument)");
189
+ else if (typeof declared === "string" && declared.startsWith("bitgraph-export/")) add("format", "This is a bitgraph-export/1 file", "UNDETERMINED", "", `not judged: a format this verifier does not know (${declared})`);
190
+ else add("format", "This is a bitgraph-export/1 file", "UNDETERMINED", "", "not a bitgraph-export/1 document");
191
+ return finish(claims, null, times, member, null, null, null);
192
+ }
193
+ add("format", "This is a bitgraph-export/1 file", "TRUE", "its structure", "format, proof and tree present");
194
+ const proof = exp.proof;
195
+ // The floor the proof signs, whichever chain it is on. A proof that signs two is ambiguous: no floor is read from it.
196
+ let signedFloor: SignedFloor | null = null;
197
+ let floorAmbiguous: string | null = null;
198
+ try {
199
+ signedFloor = signedFloorOf(proof);
200
+ } catch (e) {
201
+ floorAmbiguous = (e as Error).message;
202
+ }
203
+ const chainName = (c: "ethereum" | "base") => (c === "base" ? "Base" : "Ethereum");
204
+
205
+ // An optional part is absent (null or missing) or an object of its format;
206
+ // anything else is a malformed part, never read as "not carried".
207
+ const isAbsent = (v: unknown) => v === null || v === undefined;
208
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
209
+
210
+ // Every part below is read defensively, and anything that still throws on
211
+ // a malformed part of a known format becomes a FALSE claim, never an
212
+ // exception (formats it does not know are UNDETERMINED, above and below).
213
+ const run = async (): Promise<ExportVerifyResult> => {
214
+
215
+ // 1. The proof, and the attestation bound to it.
216
+ const integrity = await verifyProofIntegrity({ proof, context: createVerificationContext() });
217
+ add("proof.signature", "The proof is signed and its position record is bound to it", integrity.valid ? "TRUE" : "FALSE", "Ed25519",
218
+ integrity.valid ? "the enclave's signature over the canonical signed body verifies, and the position record's checks pass" : `the proof does not verify: ${integrity.reason ?? "unspecified"}`);
219
+ // The measurement is signed; a proof whose measurement is not hex is broken, not unknown.
220
+ const env = (proof as { environment?: { measurement?: unknown; attestation?: { format?: unknown; reportB64?: unknown } } }).environment;
221
+ const measurement = typeof env?.measurement === "string" && /^[0-9a-fA-F]+$/.test(env.measurement) ? env.measurement.toLowerCase() : null;
222
+ // The attestation document's own time, kept only when the document is AWS's (signature, chain and root all hold).
223
+ let attestedAtMs: number | null = null;
224
+ const att = env?.attestation;
225
+ if (att && att.format === "aws-nitro" && typeof att.reportB64 === "string") {
226
+ const n = verifyNitroAttestation(att.reportB64, { ...(measurement !== null ? { expectedPcr0: measurement } : {}), expectedUserDataB64: computeSignedBodyHash(proof), ...(opts.pins?.rootDer ? { rootDer: opts.pins.rootDer } : {}) });
227
+ if (n.doc === null) {
228
+ // Not a Nitro document at all: that contradicts the proof's own claim to carry one.
229
+ add("attestation.signature", "AWS hardware signed the attestation", "FALSE", "", `the attestation does not decode as an AWS Nitro document (${n.checks[0]?.detail ?? "unreadable"})`);
230
+ }
231
+ const byName = (prefix: string) => n.checks.find((c) => c.name.startsWith(prefix));
232
+ const r = (c: { pass: boolean } | undefined): ExportClaimResult => (c === undefined ? "UNDETERMINED" : c.pass ? "TRUE" : "FALSE");
233
+ const sig = byName("AWS signature"), chain = byName("Certificate chain"), root = byName("Chains to") ?? byName("Trust root"), validity = byName("Certificate validity"), pcr0 = byName("PCR0"), bound = byName("Bound to this proof");
234
+ if (n.doc !== null) add("attestation.signature", "AWS hardware signed the attestation", r(sig), "ES384 (P-384)", sig?.detail ?? "not reached");
235
+ add("attestation.chain", "The certificate chain holds together", r(chain), "ES384 (P-384)", chain?.detail ?? "not reached");
236
+ add("attestation.root", "The chain reaches the AWS Nitro root", r(root), `the AWS Nitro Enclaves Root CA G1 (${n.rootSha256.slice(0, 8)}…)`, root?.detail ?? "not reached");
237
+ add("attestation.validity", "Every certificate was valid at the document's own instant (archival policy, not freshness)", r(validity), "the document's signed timestamp", validity?.detail ?? "not reached");
238
+ if (measurement === null) add("attestation.pcr0", "The attested image is the one the proof names", "FALSE", "", "the proof's environment.measurement is not a hex string, so it names no image");
239
+ else add("attestation.pcr0", "The attested image is the one the proof names", r(pcr0), "PCR0 inside the signed document", pcr0?.detail ?? "not reached");
240
+ add("attestation.binding", "The attestation is bound to this proof (user_data = SHA-256 of the signed body)", r(bound), "user_data inside the signed document", bound?.detail ?? "not reached");
241
+ const hardwareOk = n.doc !== null && measurement !== null && [sig, chain, root, validity, pcr0, bound].every((c) => c?.pass === true);
242
+ if (sig?.pass && chain?.pass && root?.pass && typeof n.doc?.timestampMs === "number") attestedAtMs = n.doc.timestampMs;
243
+
244
+ // Which image is BitGraph's is a measurement policy: BitGraph's published images unless the caller names its own.
245
+ // The image judged is the one the DOCUMENT attests, and only once the hardware's word verified in full.
246
+ const docPcr0 = (n.doc?.pcrs as Record<number, unknown> | undefined)?.[0];
247
+ const measured = typeof docPcr0 === "string" ? docPcr0.toLowerCase() : null;
248
+ const usingDefault = opts.pins?.pcr0 === undefined;
249
+ const policy = (opts.pins?.pcr0 ?? PUBLISHED_PCR0S).map((x) => String(x).toLowerCase());
250
+ if (!hardwareOk || measured === null) {
251
+ add("attestation.pins", "The image is one the verifier accepts", "UNDETERMINED", "", "not judged: the attestation did not verify in full, and a declared measurement is not hardware evidence");
252
+ } else if (policy.length === 0) {
253
+ add("attestation.pins", "The image is one the verifier accepts", "UNDETERMINED", "", `no accepted images were given: PCR0 is ${measured}; any AWS Nitro enclave can produce a valid attestation, and only a measurement policy says whose this is`);
254
+ } else {
255
+ const ok = policy.includes(measured);
256
+ const pub = publishedMeasurement(measured);
257
+ add("attestation.pins", "The image is one the verifier accepts", ok ? "TRUE" : "FALSE",
258
+ usingDefault ? "BitGraph's published enclave images (SPEC section 16)" : "the verifier's own list",
259
+ ok
260
+ ? usingDefault && pub ? `PCR0 ${measured.slice(0, 16)}… is BitGraph's published ${pub.version} image (since ${pub.since})` : `PCR0 ${measured.slice(0, 16)}… is on the verifier's list`
261
+ : usingDefault ? `PCR0 ${measured.slice(0, 16)}… is not an image BitGraph published, so this proof is not BitGraph's` : `PCR0 ${measured.slice(0, 16)}… is not on the verifier's list`);
262
+ }
263
+ } else {
264
+ add("attestation.signature", "AWS hardware signed the attestation", "FALSE", "", "the proof carries no aws-nitro attestation");
265
+ }
266
+
267
+ // 2. The tree: the spec pin, the root document, and the member or the whole list.
268
+ const rootDoc = hexToBytes(exp.tree.rootDocument);
269
+ const extra = opts.extraSpecHashes ?? [];
270
+ let memberEvidence: unknown = exp.tree.member;
271
+ let ownerList: { ok: boolean; found: boolean } | null = null;
272
+ const leavesBytes = typeof exp.tree.leaves === "string" ? base64ToBytes(exp.tree.leaves) : null;
273
+ if (exp.tree.leaves !== undefined) {
274
+ const lc = rootDoc === null ? { ok: false, reason: "the root document is not hex" } : leavesBytes === null ? { ok: false, reason: "the leaves are not base64" } : verifyTreeLeaves(rootDoc, leavesBytes);
275
+ add("tree.leaves", "The whole list rebuilds the committed root, sorted and without duplicates", lc.ok ? "TRUE" : "FALSE", "SHA-256 (RFC 6962 tree)", lc.ok ? `${lc.count} leaves` : lc.reason ?? "invalid");
276
+ // The owner's export: find the file's leaf in the list and build its path here.
277
+ ownerList = { ok: lc.ok, found: false };
278
+ if (lc.ok && (opts.bytes !== undefined || opts.source !== undefined) && leavesBytes !== null && rootDoc !== null) {
279
+ const leaves = decodeTreeLeaves(leavesBytes)!;
280
+ const d = opts.bytes !== undefined ? sha256(opts.bytes) : await streamDigest(opts.source!);
281
+ const k = leaves.findIndex((l) => bytesEqual(l.artifact, d) || bytesEqual(l.origin, d));
282
+ if (k >= 0) {
283
+ const t = new MerkleTree(leaves.map(treeLeafHash));
284
+ memberEvidence = buildTreeMemberEvidence(leaves[k]!, k, leaves.length, t.path(k));
285
+ ownerList.found = true;
286
+ }
287
+ }
288
+ }
289
+ const haveFile = opts.bytes !== undefined || opts.source !== undefined;
290
+ const tr = await verifyTreeMember({
291
+ proof,
292
+ ...(opts.bytes !== undefined ? { bytes: opts.bytes } : {}),
293
+ ...(opts.source !== undefined ? { source: opts.source } : {}),
294
+ ...(memberEvidence !== undefined ? { member: memberEvidence } : {}),
295
+ // The export's own root document, never the proof's unsigned echo: a malformed one fails.
296
+ rootDocument: rootDoc ?? new Uint8Array(0),
297
+ extraSpecHashes: extra,
298
+ proofAlreadyVerified: integrity.valid,
299
+ });
300
+ // A spec this verifier does not know is not judged: its rules may differ
301
+ // from every rule here, so neither TRUE nor FALSE is earned (SPEC 8.4).
302
+ const unknownSpec = tr.category === "UNKNOWN_SPEC";
303
+ const specOk = !unknownSpec && tr.category !== "INVALID_TREE_MARKER" && tr.category !== "NOT_TREE";
304
+ add("spec.pin", "The proof pins a spec this verifier knows", specOk ? "TRUE" : unknownSpec ? "UNDETERMINED" : "FALSE", "the signed attribution.message",
305
+ (specOk ? `SPEC.md SHA-256 ${tr.specHashB64}` : unknownSpec ? `${tr.reason}; a verifier that knows that spec can judge the tree` : tr.reason) + (exp.spec !== proof.attribution?.message ? `; note: the export's unsigned "spec" label (${String(exp.spec)}) differs, and only the signed value counts` : ""));
306
+ if (unknownSpec) {
307
+ // The owner's list was read under this verifier's rules before the pin was known: not judged either.
308
+ const leavesClaim = claims.find((c) => c.id === "tree.leaves");
309
+ if (leavesClaim) {
310
+ leavesClaim.result = "UNDETERMINED";
311
+ leavesClaim.detail = `not judged: the proof follows a spec this verifier does not know (under this verifier's rules: ${leavesClaim.detail})`;
312
+ }
313
+ }
314
+ const rootOk = tr.tree !== null;
315
+ add("tree.root", "The root document is the signed one and carries this position's commitment", rootOk ? "TRUE" : specOk || rootDoc === null ? "FALSE" : "UNDETERMINED", "SHA-256 over the signed position record, its nonce and the signed floor block hash",
316
+ rootOk ? `a tree of ${tr.tree!.count} leaves, root ${tr.tree!.rootHex.slice(0, 16)}…` : tr.reason);
317
+ member = tr.member;
318
+ if (memberEvidence === undefined) {
319
+ const why = ownerList === null
320
+ ? "the export carries no member evidence"
321
+ : !ownerList.ok
322
+ ? "the owner's list did not verify, so no member can be read from it"
323
+ : !haveFile
324
+ ? "no file in hand to look up in the owner's list"
325
+ : "the file in hand is not in the owner's list";
326
+ add("tree.member", "The file's leaf is in the committed tree", "NOT_CARRIED", "", why);
327
+ } else {
328
+ const pathOk = tr.member !== null;
329
+ add("tree.member", "The file's leaf is in the committed tree", pathOk ? "TRUE" : rootOk ? "FALSE" : "UNDETERMINED", "SHA-256 (RFC 9162 path)",
330
+ pathOk ? `leaf ${tr.member!.index} of ${tr.member!.count}; a path proves this leaf only, not the order of the others` : tr.reason);
331
+ }
332
+ if (!haveFile) {
333
+ add("bytes.member", "The file in hand is that member", "NOT_CARRIED", "", "the file is not in hand");
334
+ } else if (ownerList !== null && ownerList.ok && !ownerList.found && tr.tree !== null) {
335
+ // The whole list is verified (sorted, unique, rebuilds the signed root), so its absence from it is a finding, not a gap.
336
+ add("bytes.member", "The file in hand is that member", "FALSE", "the verified complete list of the committed tree",
337
+ tr.category === "TREE_MEMBERSHIP_UNPROVEN"
338
+ ? "these bytes carry this position's commitment, so they were made after the position existed, but they are not in the committed tree"
339
+ : "the file is not among the committed tree's leaves");
340
+ } else {
341
+ const isMember = (TREE_MEMBER_CATEGORIES as readonly string[]).includes(tr.category);
342
+ add("bytes.member", "The file in hand is that member", isMember ? "TRUE" : tr.member !== null ? "FALSE" : "UNDETERMINED", tr.category === "TREE_MEMBER_FROM_ORIGIN" ? "the placement rule, rebuilt here" : "SHA-256",
343
+ `${tr.category}: ${tr.reason}`);
344
+ if (isMember) {
345
+ // Two floors, stated apart (SPEC 8.6). The record floor is every member's:
346
+ // the root document was signed after the floor block. The content floor
347
+ // is a placed member's: its committed bytes carry the commitment.
348
+ const block = signedFloor ? `${chainName(signedFloor.chain)} block ${signedFloor.blockNumber}` : "the signed floor block";
349
+ add("floor.record", "The record was made after the floor block", "TRUE", "the signed root document, which carries the commitment to the floor block",
350
+ `recorded after ${block}: the tree this file is a leaf of was signed after it`);
351
+ if (tr.floorCovers === "content") {
352
+ add("floor.content", "The committed bytes were finished after the floor block", "TRUE", "SHA-256: the commitment is inside the committed bytes",
353
+ `the committed bytes carry the commitment to ${block}, so they were finished after it; the original inside them is not dated by it`);
354
+ } else {
355
+ add("floor.content", "The committed bytes were finished after the floor block", "NOT_CARRIED", "",
356
+ "recorded as is: the bytes carry no commitment, so the bytes themselves are not dated");
357
+ }
358
+ }
359
+ }
360
+
361
+ // 3. The floor: the header hashes to the SIGNED floor block hash, on the chain the proof signs.
362
+ let floorBlock: { chain: "ethereum" | "base"; blockNumber: number; blockHash: string } | null = null;
363
+ let floorHeaderTs: number | null = null;
364
+ const fname = "The floor block's header is the one the proof signs";
365
+ if (isAbsent(exp.floor)) {
366
+ add("floor.header", fname, "NOT_CARRIED", "", "no floor header in the export");
367
+ } else if (!isObject(exp.floor)) {
368
+ add("floor.header", fname, "FALSE", "", "the export's floor is neither absent nor a { blockNumber, blockHash, header } object");
369
+ } else if (floorAmbiguous !== null) {
370
+ add("floor.header", fname, "FALSE", "", floorAmbiguous);
371
+ } else if (!signedFloor) {
372
+ add("floor.header", fname, "FALSE", "", "the proof signs no floor block (commit.slotAnchor or commit.slotFloor)");
373
+ } else {
374
+ const f = exp.floor as Record<string, unknown>;
375
+ const chain = chainName(signedFloor.chain);
376
+ let raw: Uint8Array | null = null;
377
+ try {
378
+ raw = evmHex(String(f["header"]));
379
+ } catch {
380
+ raw = null;
381
+ }
382
+ const fh = raw === null ? { ok: false as const, reason: "the header is not hex" } : checkFloorHeader(signedFloor, raw, f["chain"]);
383
+ if (!fh.ok) {
384
+ add("floor.header", fname, "FALSE", "", `floor header: ${fh.reason}`);
385
+ } else if (String(f["blockHash"]).toLowerCase() !== fh.header.hash || f["blockNumber"] !== fh.header.number) {
386
+ add("floor.header", fname, "FALSE", "", "the export's floor names a different block than its header");
387
+ } else {
388
+ const h = fh.header;
389
+ floorBlock = { chain: signedFloor.chain, blockNumber: h.number, blockHash: h.hash };
390
+ floorHeaderTs = h.timestamp;
391
+ // The floor's time is a bound only when it is no later than the attestation document.
392
+ const bound = floorTimeIsBound(h.timestamp, attestedAtMs);
393
+ if (bound.ok) {
394
+ times.floor = { ...(signedFloor.chain === "base" ? { chain: "base" as const } : {}), blockNumber: h.number, blockHash: h.hash, blockTimestamp: h.timestamp };
395
+ add("floor.header", fname, "TRUE", `${chain} block ${h.number}, header as given`,
396
+ `keccak-256 of the header equals the signed block hash${signedFloor.chain === "base" ? ", and its time is the signed one, on Base mainnet's schedule" : ""}; its time is ${iso(h.timestamp)}`);
397
+ } else {
398
+ floorTimeWithheld = bound.reason;
399
+ add("floor.header", fname, "TRUE", `${chain} block ${h.number}, header as given`,
400
+ `keccak-256 of the header equals the signed block hash; ${bound.reason}, so its time is not used as a bound`);
401
+ }
402
+ }
403
+ }
404
+
405
+ // 4. The ceiling on Base: the record is under a root in a Base transaction in block B.
406
+ const writer = opts.pins?.ceilingWriter ?? "0xf3972408D853c975F86351C311f4310220bbF2a3";
407
+ const baseChainId = opts.pins?.baseChainId ?? 8453;
408
+ let ceilingB: { blockNumber: number; blockHash: string } | null = null;
409
+ const c = exp.ceiling;
410
+ const ceilingVersion = (c as { version?: unknown } | null)?.version;
411
+ const ceilingUnknown = typeof ceilingVersion === "string" && ceilingVersion !== CEILING_VERSION;
412
+ if (ceilingUnknown) {
413
+ add("ceiling.base", "The record is in a Base block", "UNDETERMINED", "", `not judged: a ceiling format this verifier does not know (${ceilingVersion})`);
414
+ } else if (isAbsent(c)) {
415
+ add("ceiling.base", "The record is in a Base block", "NOT_CARRIED", "", "no ceiling in the export");
416
+ } else if (!isObject(c) || (!(c as Record<string, unknown>)["anchor"] && (c as Record<string, unknown>)["status"] !== "pending")) {
417
+ add("ceiling.base", "The record is in a Base block", "FALSE", "", "the export's ceiling is neither absent, pending, nor a sidecar with its transaction");
418
+ } else if (!(c as Record<string, unknown>)["anchor"]) {
419
+ // Pending means no transaction to check. With a transaction, the
420
+ // sidecar's status is the writer's report and is never read as evidence.
421
+ add("ceiling.base", "The record is in a Base block", "NOT_CARRIED", "", "ceiling pending: the Base write had not landed when this export was made");
422
+ } else {
423
+ let r: Awaited<ReturnType<typeof verifyCeiling>>;
424
+ try {
425
+ r = await verifyCeiling(proof, c as CeilingSidecar, { writerAddress: writer, chainId: baseChainId, proofAlreadyVerified: integrity.valid });
426
+ } catch (e) {
427
+ r = { ok: false, reason: `the ceiling is malformed (${(e as Error).message})`, checks: [], headerCheckedAgainstChain: false };
428
+ }
429
+ if (r.ok && r.window) {
430
+ ceilingB = { blockNumber: r.window.ceiling.blockNumber, blockHash: r.window.ceiling.blockHash };
431
+ const where = `under the root in transaction ${(c as CeilingSidecar).anchor!.txIndex} of Base block ${r.window.ceiling.blockNumber}`;
432
+ // The floor's time: the export's own header, else the verified header the sidecar carries.
433
+ const stamp = baseTimeIsBound(r.window.ceiling.blockTimestamp, { floorTimestampSec: floorHeaderTs ?? r.window.floor.blockTimestamp ?? null, attestedAtMs });
434
+ if (stamp.ok) {
435
+ times.ceilingBase = { ...r.window.ceiling, provisional: true };
436
+ add("ceiling.base", "The record is in a Base block", "TRUE", `SHA-256 path, the BGC1 payload, secp256k1, Merkle-Patricia; Base block ${r.window.ceiling.blockNumber}, header as given`,
437
+ `${where}; its time ${iso(r.window.ceiling.blockTimestamp)} is provisional until the block is checked against Base`);
438
+ } else {
439
+ // The inclusion holds; only the stamp is withheld as a bound.
440
+ baseTimeWithheld = stamp.reason;
441
+ add("ceiling.base", "The record is in a Base block", "TRUE", `SHA-256 path, the BGC1 payload, secp256k1, Merkle-Patricia; Base block ${r.window.ceiling.blockNumber}, header as given`,
442
+ `${where}; ${stamp.reason}, so its time is not used as a bound`);
443
+ }
444
+ } else {
445
+ add("ceiling.base", "The record is in a Base block", "FALSE", "", r.reason ?? "the ceiling does not verify");
446
+ }
447
+ }
448
+
449
+ // 5. The settlement: the Base transaction existed by Ethereum block H.
450
+ const s = exp.settlement;
451
+ const settlementVersion = (s as { version?: unknown } | null)?.version;
452
+ if (typeof settlementVersion === "string" && settlementVersion !== OUTPUT_ROOT_VERSION) {
453
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "UNDETERMINED", "", `not judged: a settlement format this verifier does not take in an export (${settlementVersion})`);
454
+ } else if (isAbsent(s)) {
455
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "NOT_CARRIED", "", "no settlement in the export");
456
+ } else if (!isObject(s)) {
457
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "FALSE", "", "the export's settlement is neither absent, pending, nor a settlement object");
458
+ } else if ((s as Record<string, unknown>)["status"] === "pending" && (s as Record<string, unknown>)["version"] === undefined) {
459
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "NOT_CARRIED", "", "settlement pending: Base's claim for this block had not reached Ethereum when this export was made");
460
+ } else {
461
+ const so = s as unknown as OutputRootSettlement;
462
+ let r: ReturnType<typeof verifyOutputRootSettlement>;
463
+ try {
464
+ r = verifyOutputRootSettlement(so, { baseChainId, ethereumChainId: opts.pins?.ethereumChainId ?? 1 });
465
+ } catch (e) {
466
+ r = { ok: false, reason: `the settlement is malformed (${(e as Error).message})`, checks: [] };
467
+ }
468
+ const linked = ceilingB !== null && so.base?.blockNumber === ceilingB.blockNumber && typeof so.base?.blockHash === "string" && so.base.blockHash.toLowerCase() === ceilingB.blockHash.toLowerCase();
469
+ if (r.ok && linked) {
470
+ times.ceilingEthereum = r.existedBy!;
471
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "TRUE", `keccak-256 output root, EIP-2935 storage proof, Merkle-Patricia; Ethereum block ${r.existedBy!.blockNumber}, header as given`,
472
+ `Base's output root for block ${so.outputRoot.blockNumber} commits to the ceiling's Base block and is carried by transaction ${so.ethereum.txIndex} of Ethereum block ${r.existedBy!.blockNumber} (${iso(r.existedBy!.blockTimestamp)}); this holds whatever Base's claim turns out to be`);
473
+ } else if (r.ok && !linked && ceilingUnknown) {
474
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "UNDETERMINED", "", "the settlement verifies, but the ceiling it settles is in a format this verifier does not know, so the link is not judged");
475
+ } else if (r.ok && !linked) {
476
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "FALSE", "", ceilingB === null ? "the settlement settles a Base block, but the ceiling did not verify" : "the settlement is for a different Base block than the ceiling");
477
+ } else {
478
+ add("ceiling.ethereum", "The record existed by an Ethereum block", "FALSE", "", r.reason ?? "the settlement does not verify");
479
+ }
480
+ }
481
+
482
+ // 6. Confirmed: the caller's lookups say the blocks are the chains' own.
483
+ const confirm = async (id: string, name: string, chain: "ethereum" | "base", at: { blockNumber: number; blockHash: string } | null) => {
484
+ if (at === null) return;
485
+ const ask = chain === "ethereum" ? opts.lookups?.ethereumBlockHash : opts.lookups?.baseBlockHash;
486
+ if (!ask) {
487
+ add(id, name, "UNDETERMINED", "", `not checked: no ${chain === "ethereum" ? "Ethereum" : "Base"} lookup was given (block ${at.blockNumber}, ${at.blockHash})`, "confirmed");
488
+ return;
489
+ }
490
+ try {
491
+ const got = (await ask(at.blockNumber))?.toLowerCase() ?? null;
492
+ if (got === null) add(id, name, "UNDETERMINED", "", `the lookup did not return block ${at.blockNumber}`, "confirmed");
493
+ else add(id, name, got === at.blockHash.toLowerCase() ? "TRUE" : "FALSE", `the caller's ${chain === "ethereum" ? "Ethereum" : "Base"} node`, got === at.blockHash.toLowerCase() ? `block ${at.blockNumber} is the chain's own` : `the chain's block ${at.blockNumber} is ${got}`, "confirmed");
494
+ } catch (e) {
495
+ add(id, name, "UNDETERMINED", "", `lookup failed: ${(e as Error).message}`, "confirmed");
496
+ }
497
+ };
498
+ // The floor is asked of its own chain, by height: the chain's block at N must be the signed one.
499
+ if (floorBlock !== null) await confirm("confirmed.floor", `The floor block is ${chainName(floorBlock.chain)}'s own`, floorBlock.chain, floorBlock);
500
+ await confirm("confirmed.ceiling.base", "The ceiling block is Base's own (makes its time final)", "base", ceilingB);
501
+ await confirm("confirmed.ceiling.ethereum", "The settlement block is Ethereum's own", "ethereum", times.ceilingEthereum);
502
+ const baseConfirmed = claims.find((x) => x.id === "confirmed.ceiling.base")?.result === "TRUE";
503
+ if (times.ceilingBase) times.ceilingBase.provisional = !baseConfirmed;
504
+
505
+ return finish(claims, exp, times, member, tr.floorCovers, baseTimeWithheld, floorTimeWithheld, floorBlock);
506
+ };
507
+ try {
508
+ return await run();
509
+ } catch (e) {
510
+ add("wellformed", "Every part of the export is well formed", "FALSE", "", `a part of this export is malformed: ${(e as Error).message}`);
511
+ return finish(claims, exp, times, member, null, baseTimeWithheld, floorTimeWithheld);
512
+ }
513
+ }
514
+
515
+ /**
516
+ * The verdict and the reading, from the claims (SPEC section 12.1).
517
+ *
518
+ * FALSE when any claim is FALSE, a lookup the reader made included: a block
519
+ * a node says is not the chain's own refutes every time read from it.
520
+ * UNDETERMINED when any offline claim is undetermined, the measurement
521
+ * policy included. Otherwise TRUE. The reading states a time as fact only
522
+ * when nothing refutes it, says when a header is taken as given, and never
523
+ * states a Base time that was withheld as a bound.
524
+ */
525
+ function finish(
526
+ claims: ExportClaim[],
527
+ exp: BitGraphExport | null,
528
+ times: ExportVerifyResult["times"],
529
+ member: TreeVerifyResult["member"],
530
+ floorCovers: TreeVerifyResult["floorCovers"] = null,
531
+ baseTimeWithheld: string | null = null,
532
+ floorTimeWithheld: string | null = null,
533
+ floorBlock: { chain: "ethereum" | "base"; blockNumber: number } | null = null,
534
+ ): ExportVerifyResult {
535
+ const offline = claims.filter((c) => c.level === "offline");
536
+ const failed = claims.filter((c) => c.result === "FALSE");
537
+ const reasons = claims.filter((c) => c.result === "FALSE" || c.result === "UNDETERMINED").map((c) => `${c.id}: ${c.detail}`);
538
+ const unjudged = offline.filter((c) => c.result === "UNDETERMINED");
539
+ const verdict = failed.length > 0 ? "FALSE" : exp === null || unjudged.length > 0 ? "UNDETERMINED" : "TRUE";
540
+ const confirmedTrue = (id: string) => claims.find((c) => c.id === id)?.result === "TRUE";
541
+ const parts: string[] = [];
542
+ if (verdict === "FALSE") {
543
+ if (failed.every((c) => c.level === "confirmed")) {
544
+ parts.push(`A lookup refutes this export: ${failed.map((c) => c.detail).join("; ")}. A block it names is not the chain's own, so the times it states do not hold.`);
545
+ } else {
546
+ parts.push("Something in this export contradicts the proof; see the failed claims.");
547
+ }
548
+ } else if (exp === null) {
549
+ parts.push("This is not a bitgraph-export/1 file.");
550
+ } else {
551
+ const lc1 = (t: string) => t.charAt(0).toLowerCase() + t.slice(1);
552
+ if (unjudged.length > 0) parts.push(`Not judged in full: ${unjudged.map((c) => lc1(c.name)).join("; ")}.`);
553
+ const givenEth = "; that block's header is taken as given until it is checked against Ethereum";
554
+ const floorRead = floorBlock ?? (times.floor ? { chain: times.floor.chain ?? "ethereum", blockNumber: times.floor.blockNumber } : null);
555
+ if (floorRead) {
556
+ const chain = floorRead.chain === "base" ? "Base" : "Ethereum";
557
+ const time = times.floor ? ` (${iso(times.floor.blockTimestamp)})` : "";
558
+ const given = confirmedTrue("confirmed.floor") ? "" : `; that block's header is taken as given until it is checked against ${chain}`;
559
+ const at = `${chain} block ${floorRead.blockNumber}${time}${given}`;
560
+ parts.push(floorCovers === "record"
561
+ ? `Recorded after ${at}; this file was kept as is, so the bytes themselves are not dated.`
562
+ : floorCovers === "content"
563
+ ? `Recorded after ${at}, and these committed bytes were finished after that block; an original inside them is not dated by it.`
564
+ : `Recorded after ${at}.`);
565
+ if (!times.floor && floorTimeWithheld) parts.push(`The floor block's time is not used as a bound: ${floorTimeWithheld}.`);
566
+ }
567
+ if (times.ceilingBase) parts.push(`The record existed by Base block ${times.ceilingBase.blockNumber} (${iso(times.ceilingBase.blockTimestamp)}${times.ceilingBase.provisional ? ", provisional until checked against Base" : ""}).`);
568
+ else if (baseTimeWithheld) parts.push(`The record is in a Base block, but its time is not used as a bound: ${baseTimeWithheld}.`);
569
+ if (times.ceilingEthereum) parts.push(`It existed by Ethereum block ${times.ceilingEthereum.blockNumber} (${iso(times.ceilingEthereum.blockTimestamp)})${confirmedTrue("confirmed.ceiling.ethereum") ? "" : givenEth}.`);
570
+ if (member) parts.push(`The file is leaf ${member.index} of ${member.count} in the committed tree.`);
571
+ }
572
+ return { verdict, reasons, claims, member, floorCovers, times, baseTimeWithheld, floorTimeWithheld, reading: parts.join(" ") };
573
+ }
574
+
575
+
576
+ /** Build an export object from its parts (producers). Fields are written in the order the spec lists them. */
577
+ export function buildExport(parts: Omit<BitGraphExport, "format" | "spec">): BitGraphExport {
578
+ const spec = parts.proof.attribution?.message;
579
+ if (typeof spec !== "string") throw new TypeError("a tree/1 proof pins its spec in attribution.message");
580
+ // A Base floor names its chain; an Ethereum floor leaves it out, so exports made before enclave v10 stay byte for byte what they were.
581
+ let floor = parts.floor;
582
+ if (floor && floor.chain === undefined) {
583
+ let chain: "ethereum" | "base" | undefined;
584
+ try {
585
+ chain = signedFloorOf(parts.proof)?.chain;
586
+ } catch {
587
+ chain = undefined;
588
+ }
589
+ if (chain === "base") floor = { chain: "base", blockNumber: floor.blockNumber, blockHash: floor.blockHash, header: floor.header };
590
+ }
591
+ return { format: EXPORT_FORMAT, spec, proof: parts.proof, tree: parts.tree, floor, ceiling: parts.ceiling, settlement: parts.settlement };
592
+ }