@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/tree.ts ADDED
@@ -0,0 +1,580 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * tree/1: every BitGraph is a Merkle tree under one position (2026-10-03).
5
+ *
6
+ * One format from one file to 1,000,000. Each file is a fixed 65-byte LEAF
7
+ * (placement code, artifact digest, origin digest); the leaves, sorted by
8
+ * artifact digest, form an RFC 6962 tree (fuse-merkle.ts, the same rules the
9
+ * ceiling uses); and the committed artifact is a fixed 84-byte ROOT DOCUMENT
10
+ * (domain, count, root, commitment) whose SHA-256 the enclave signs. A single
11
+ * file is a tree of one: an empty path, the root equal to its leaf hash.
12
+ *
13
+ * The signed attribution is { name: "bitgraph-fuse/2", title: "tree/1",
14
+ * message: base64 SHA-256 of the SPEC this proof follows }. The origin lives
15
+ * in the leaf, which frees the message to pin the spec; a verifier accepts
16
+ * only spec hashes it already knows (KNOWN_TREE_SPEC_HASHES).
17
+ *
18
+ * What each part proves, kept apart on purpose:
19
+ * - A member's leaf and path prove that leaf is in the committed tree. They
20
+ * say nothing about the other leaves, so sorting and uniqueness are checked
21
+ * only where the whole list is seen (producers, verifyTreeLeaves).
22
+ * - Two floors (SPEC 8.6). Every member has the RECORD floor: the root
23
+ * document, and so every leaf, was signed after the floor block. Placements
24
+ * 0x01 to 0x03 also have the CONTENT floor: the committed bytes carry the
25
+ * commitment, so they were finished after that block. The original inside
26
+ * them, and an as-is file (0x00), carry no commitment: recorded after the
27
+ * block, the bytes themselves are not dated.
28
+ *
29
+ * Byte layouts (all integers big-endian, all digests raw 32 bytes):
30
+ * leaf = placement (1) || artifact (32) || origin (32) 65 bytes
31
+ * leaf hash = SHA-256(0x00 || leaf)
32
+ * node hash = SHA-256(0x01 || left || right)
33
+ * root document = "bitgraph-tree/1" 0x00 (16) || count u32 (4) || root (32) || commitment (32) 84 bytes
34
+ */
35
+
36
+ import { sha256 } from "@noble/hashes/sha256";
37
+ import { streamLeafCheck, type ByteSource, type StreamPlacement } from "./stream.js";
38
+ import { merkleLeafHash, merkleRootFromPath, MerkleTree } from "./fuse-merkle.js";
39
+ import {
40
+ base64ToBytes,
41
+ bytesEqual,
42
+ bytesToBase64,
43
+ bytesToHex,
44
+ commitmentForProof,
45
+ FUSE2_ATTRIBUTION_NAME,
46
+ FUSE3_ATTRIBUTION_NAME,
47
+ fuseVersionOfName,
48
+ getPlacement,
49
+ hexToBytes,
50
+ PLACEMENTS,
51
+ } from "./fuse.js";
52
+ import { spanOf, type FuseSpan } from "./fuse-verify.js";
53
+ import { verifyProofIntegrity } from "./verifier.js";
54
+ import type { Attribution, BitGraphProof, VerificationPolicy } from "./types.js";
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Constants
58
+ // ---------------------------------------------------------------------------
59
+
60
+ export const TREE_PLACEMENT_ID = "tree/1" as const;
61
+ export const TREE_PROFILE = "bitgraph-tree/1" as const;
62
+
63
+ /** "bitgraph-tree/1" followed by one zero byte: 16 bytes. */
64
+ export const TREE_DOMAIN: Uint8Array = (() => {
65
+ const label = new TextEncoder().encode(TREE_PROFILE);
66
+ const out = new Uint8Array(label.length + 1);
67
+ out.set(label, 0);
68
+ return out;
69
+ })();
70
+
71
+ export const TREE_LEAF_BYTES = 65;
72
+ export const TREE_ROOT_DOCUMENT_BYTES = 84;
73
+ /** The most leaves one tree lists. A stated limit; the layout allows up to 2^32 - 1. */
74
+ export const MAX_TREE_LEAVES = 1_000_000;
75
+
76
+ /** proof.metadata key carrying the root document as lowercase hex. Unsigned; bound only by hashing to the signed digest. */
77
+ export const TREE_METADATA_KEY = TREE_PROFILE;
78
+
79
+ /**
80
+ * The spec hashes this verifier knows: base64 SHA-256 of each SPEC.md
81
+ * version. A tree/1 proof's signed attribution.message must be one of them.
82
+ * Appending a revised spec here is how a verifier learns it; nothing is ever
83
+ * removed, so every proof made under an earlier spec keeps verifying.
84
+ */
85
+ /** SPEC.md v1 (spec/SPEC.md). Frozen 2026-10-04 (spec/FROZEN.json): tree/1 under bitgraph-fuse/2, an Ethereum floor. */
86
+ export const TREE_SPEC_V1_HASH = "QazdIR0JYtHQwQuIISo7bvH1gxUvTS2cY+tW6BjUIRs=";
87
+ /** SPEC v2 (spec/SPEC-v2.md): tree/1 under bitgraph-fuse/3, a Base floor (enclave v10). */
88
+ export const TREE_SPEC_V2_HASH = "9O3sqlxqi6IQPVJd50NfjJtwWWoslZ9gpIIzbrRzAiU=";
89
+
90
+ export const KNOWN_TREE_SPEC_HASHES: readonly string[] = Object.freeze([
91
+ // Each spec never changes; a later spec is added beside it, never in its place.
92
+ TREE_SPEC_V1_HASH,
93
+ TREE_SPEC_V2_HASH,
94
+ ]);
95
+
96
+ /**
97
+ * The marker each spec requires: v1 defines tree/1 under fuse/2 (the floor an
98
+ * Ethereum anchor), v2 under fuse/3 (the floor a Base block). A tree proof
99
+ * whose marker and spec disagree is refused, so neither spec's meaning moves.
100
+ */
101
+ const TREE_SPEC_FUSE_VERSION: ReadonlyMap<string, 2 | 3> = new Map([
102
+ [TREE_SPEC_V1_HASH, 2],
103
+ [TREE_SPEC_V2_HASH, 3],
104
+ ]);
105
+
106
+ /** Placement codes: the first byte of a leaf. */
107
+ export const LEAF_AS_IS = 0x00;
108
+ export const LEAF_PLACEMENTS: Readonly<Record<number, "as-is" | "trailer/1" | "container/1" | "container/2">> = Object.freeze({
109
+ 0x00: "as-is",
110
+ 0x01: "trailer/1",
111
+ 0x02: "container/1",
112
+ 0x03: "container/2",
113
+ });
114
+
115
+ export function leafCodeOf(placement: string): number | null {
116
+ for (const [code, id] of Object.entries(LEAF_PLACEMENTS)) if (id === placement) return Number(code);
117
+ return null;
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Leaves
122
+ // ---------------------------------------------------------------------------
123
+
124
+ export interface TreeLeaf {
125
+ /** 0x00 as is, 0x01 trailer/1, 0x02 container/1, 0x03 container/2. */
126
+ placement: number;
127
+ /** SHA-256 of the committed bytes (for 0x00, the file itself). */
128
+ artifact: Uint8Array;
129
+ /** SHA-256 of the file as dropped (for 0x00, equal to artifact). */
130
+ origin: Uint8Array;
131
+ }
132
+
133
+ function checkLeaf(l: TreeLeaf): void {
134
+ if (!(l.placement in LEAF_PLACEMENTS)) throw new TypeError(`leaf placement code 0x${l.placement.toString(16).padStart(2, "0")} is not registered`);
135
+ if (l.artifact.length !== 32 || l.origin.length !== 32) throw new TypeError("leaf digests are 32 bytes");
136
+ if (l.placement === LEAF_AS_IS && !bytesEqual(l.artifact, l.origin)) throw new TypeError("an as-is leaf's artifact and origin are the same digest");
137
+ }
138
+
139
+ export function encodeTreeLeaf(l: TreeLeaf): Uint8Array {
140
+ checkLeaf(l);
141
+ const out = new Uint8Array(TREE_LEAF_BYTES);
142
+ out[0] = l.placement;
143
+ out.set(l.artifact, 1);
144
+ out.set(l.origin, 33);
145
+ return out;
146
+ }
147
+
148
+ /** Strict: 65 bytes, a registered code, and for 0x00 artifact = origin. Null otherwise. */
149
+ export function decodeTreeLeaf(bytes: Uint8Array): TreeLeaf | null {
150
+ if (bytes.length !== TREE_LEAF_BYTES) return null;
151
+ const leaf: TreeLeaf = { placement: bytes[0]!, artifact: bytes.slice(1, 33), origin: bytes.slice(33, 65) };
152
+ try {
153
+ checkLeaf(leaf);
154
+ } catch {
155
+ return null;
156
+ }
157
+ return leaf;
158
+ }
159
+
160
+ export function treeLeafHash(l: TreeLeaf): Uint8Array {
161
+ return merkleLeafHash(encodeTreeLeaf(l));
162
+ }
163
+
164
+ function compareBytes(a: Uint8Array, b: Uint8Array): number {
165
+ for (let i = 0; i < a.length && i < b.length; i++) if (a[i] !== b[i]) return a[i]! - b[i]!;
166
+ return a.length - b.length;
167
+ }
168
+
169
+ /** Tree order: strictly ascending by artifact digest. Throws on an empty list, too many leaves, a bad leaf or a duplicate artifact. */
170
+ export function sortTreeLeaves(leaves: readonly TreeLeaf[]): TreeLeaf[] {
171
+ if (leaves.length === 0) throw new TypeError("a tree lists at least one leaf");
172
+ if (leaves.length > MAX_TREE_LEAVES) throw new TypeError(`a tree lists at most ${MAX_TREE_LEAVES} leaves`);
173
+ for (const l of leaves) checkLeaf(l);
174
+ const sorted = [...leaves].sort((a, b) => compareBytes(a.artifact, b.artifact));
175
+ for (let i = 1; i < sorted.length; i++) {
176
+ if (bytesEqual(sorted[i]!.artifact, sorted[i - 1]!.artifact)) throw new TypeError(`duplicate leaf artifact digest ${bytesToHex(sorted[i]!.artifact)}`);
177
+ }
178
+ return sorted;
179
+ }
180
+
181
+ export interface BuiltTree {
182
+ sorted: TreeLeaf[];
183
+ leafHashes: Uint8Array[];
184
+ root: Uint8Array;
185
+ tree: MerkleTree;
186
+ }
187
+
188
+ export function buildTree(leaves: readonly TreeLeaf[]): BuiltTree {
189
+ const sorted = sortTreeLeaves(leaves);
190
+ const leafHashes = sorted.map(treeLeafHash);
191
+ const tree = new MerkleTree(leafHashes);
192
+ return { sorted, leafHashes, root: tree.root, tree };
193
+ }
194
+
195
+ // ---------------------------------------------------------------------------
196
+ // Root document
197
+ // ---------------------------------------------------------------------------
198
+
199
+ export function buildTreeRootDocument(commitment: Uint8Array, count: number, root: Uint8Array): Uint8Array {
200
+ if (commitment.length !== 32 || root.length !== 32) throw new TypeError("commitment and root are 32 bytes");
201
+ if (!Number.isInteger(count) || count < 1 || count > MAX_TREE_LEAVES) throw new TypeError(`count must be an integer from 1 to ${MAX_TREE_LEAVES}`);
202
+ const out = new Uint8Array(TREE_ROOT_DOCUMENT_BYTES);
203
+ out.set(TREE_DOMAIN, 0);
204
+ new DataView(out.buffer).setUint32(16, count, false);
205
+ out.set(root, 20);
206
+ out.set(commitment, 52);
207
+ return out;
208
+ }
209
+
210
+ /** Strict: 84 bytes, the domain, a count from 1 to MAX_TREE_LEAVES. Null otherwise. */
211
+ export function parseTreeRootDocument(bytes: Uint8Array): { count: number; root: Uint8Array; commitment: Uint8Array } | null {
212
+ if (bytes.length !== TREE_ROOT_DOCUMENT_BYTES) return null;
213
+ if (!bytesEqual(bytes.subarray(0, 16), TREE_DOMAIN)) return null;
214
+ const count = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(16, false);
215
+ if (count < 1 || count > MAX_TREE_LEAVES) return null;
216
+ return { count, root: bytes.slice(20, 52), commitment: bytes.slice(52, 84) };
217
+ }
218
+
219
+ /** The root document a proof carries in its unsigned metadata, as bytes; null when absent or malformed hex. */
220
+ export function readTreeMetadata(proof: BitGraphProof): Uint8Array | null {
221
+ const v = proof.metadata?.[TREE_METADATA_KEY];
222
+ if (typeof v !== "string") return null;
223
+ return hexToBytes(v);
224
+ }
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // The signed marker
228
+ // ---------------------------------------------------------------------------
229
+
230
+ /**
231
+ * The attribution a producer sends for a tree/1 commit. specHash is the 32-byte
232
+ * SHA-256 of the spec the producer follows; the marker is the one that spec
233
+ * requires (fuse/2 for v1, fuse/3 for v2).
234
+ */
235
+ export function treeAttribution(specHash: Uint8Array): Attribution {
236
+ if (specHash.length !== 32) throw new TypeError("the spec hash is 32 bytes");
237
+ const b64 = bytesToBase64(specHash);
238
+ const version = TREE_SPEC_FUSE_VERSION.get(b64) ?? 2;
239
+ return { name: version === 3 ? FUSE3_ATTRIBUTION_NAME : FUSE2_ATTRIBUTION_NAME, title: TREE_PLACEMENT_ID, message: b64 };
240
+ }
241
+
242
+ /**
243
+ * The spec hash a producer pins, as raw bytes, for the floor its allocation
244
+ * returned: a Base floor (fuse/3) follows SPEC v2, an Ethereum floor anchor
245
+ * (fuse/2) follows SPEC v1. Throws while the requested spec hash is a placeholder.
246
+ */
247
+ export function currentTreeSpecHash(fuseVersion: 2 | 3 = 2): Uint8Array {
248
+ const hash = fuseVersion === 3 ? TREE_SPEC_V2_HASH : TREE_SPEC_V1_HASH;
249
+ const b = base64ToBytes(hash);
250
+ if (b === null || b.length !== 32) throw new Error("the tree/1 spec hash has not been set");
251
+ return b;
252
+ }
253
+
254
+ export function isTreeProof(proof: { attribution?: unknown } | null | undefined): boolean {
255
+ const a = (proof as { attribution?: { title?: unknown } } | null | undefined)?.attribution;
256
+ return a?.title === TREE_PLACEMENT_ID;
257
+ }
258
+
259
+ // ---------------------------------------------------------------------------
260
+ // A member's evidence, and the owner's full list
261
+ // ---------------------------------------------------------------------------
262
+
263
+ /** One member's evidence as JSON: its leaf (lowercase hex, 130 chars), its index, the tree size, and its sibling path from the leaf up. */
264
+ export interface TreeMemberEvidence {
265
+ index: number;
266
+ count: number;
267
+ leaf: string;
268
+ path: string[];
269
+ }
270
+
271
+ export function buildTreeMemberEvidence(leaf: TreeLeaf, index: number, count: number, path: readonly Uint8Array[]): TreeMemberEvidence {
272
+ if (!Number.isInteger(index) || !Number.isInteger(count) || count < 1 || index < 0 || index >= count) throw new RangeError("member index out of range");
273
+ return {
274
+ index,
275
+ count,
276
+ leaf: bytesToHex(encodeTreeLeaf(leaf)),
277
+ path: path.map((p) => {
278
+ if (p.length !== 32) throw new TypeError("a path node is 32 bytes");
279
+ return bytesToHex(p);
280
+ }),
281
+ };
282
+ }
283
+
284
+ /** Strict read: exactly the four keys, integers in range, a valid leaf, 32-byte lowercase-hex path nodes. Null on any deviation. Unbound. */
285
+ export function parseTreeMemberEvidence(value: unknown): { leaf: TreeLeaf; index: number; count: number; path: Uint8Array[] } | null {
286
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
287
+ const v = value as Record<string, unknown>;
288
+ if (Object.keys(v).sort().join(",") !== "count,index,leaf,path") return null;
289
+ const { count, index } = v;
290
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 1 || count > MAX_TREE_LEAVES) return null;
291
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= count) return null;
292
+ if (typeof v["leaf"] !== "string") return null;
293
+ const leafBytes = hexToBytes(v["leaf"]);
294
+ if (leafBytes === null) return null;
295
+ const leaf = decodeTreeLeaf(leafBytes);
296
+ if (leaf === null) return null;
297
+ if (!Array.isArray(v["path"])) return null;
298
+ const path: Uint8Array[] = [];
299
+ for (const n of v["path"] as unknown[]) {
300
+ if (typeof n !== "string") return null;
301
+ const b = hexToBytes(n);
302
+ if (b === null || b.length !== 32) return null;
303
+ path.push(b);
304
+ }
305
+ return { leaf, index, count, path };
306
+ }
307
+
308
+ /** The root a member's leaf and path reach, or null when the path does not fit the index and count. */
309
+ export function treeRootFromMember(leaf: TreeLeaf, index: number, count: number, path: readonly Uint8Array[]): Uint8Array | null {
310
+ return merkleRootFromPath(treeLeafHash(leaf), index, count, path);
311
+ }
312
+
313
+ /** The owner's list: every leaf in tree order, concatenated (count x 65 bytes). */
314
+ export function encodeTreeLeaves(sorted: readonly TreeLeaf[]): Uint8Array {
315
+ const out = new Uint8Array(sorted.length * TREE_LEAF_BYTES);
316
+ sorted.forEach((l, i) => out.set(encodeTreeLeaf(l), i * TREE_LEAF_BYTES));
317
+ return out;
318
+ }
319
+
320
+ export function decodeTreeLeaves(bytes: Uint8Array): TreeLeaf[] | null {
321
+ if (bytes.length === 0 || bytes.length % TREE_LEAF_BYTES !== 0) return null;
322
+ const out: TreeLeaf[] = [];
323
+ for (let o = 0; o < bytes.length; o += TREE_LEAF_BYTES) {
324
+ const l = decodeTreeLeaf(bytes.subarray(o, o + TREE_LEAF_BYTES));
325
+ if (l === null) return null;
326
+ out.push(l);
327
+ }
328
+ return out;
329
+ }
330
+
331
+ export interface TreeLeavesCheck {
332
+ ok: boolean;
333
+ reason?: string;
334
+ count?: number;
335
+ }
336
+
337
+ /**
338
+ * The whole list against a root document: the count matches, the leaves are
339
+ * strictly ascending by artifact digest with no duplicate, every leaf is
340
+ * valid, and the rebuilt root equals the document's. This is the only check
341
+ * that establishes ordering and uniqueness; a single member's path cannot.
342
+ */
343
+ export function verifyTreeLeaves(rootDocument: Uint8Array, leavesBytes: Uint8Array): TreeLeavesCheck {
344
+ const doc = parseTreeRootDocument(rootDocument);
345
+ if (doc === null) return { ok: false, reason: "the root document is not a tree/1 root document" };
346
+ const leaves = decodeTreeLeaves(leavesBytes);
347
+ if (leaves === null) return { ok: false, reason: "the leaves are not a whole number of valid 65-byte leaves" };
348
+ if (leaves.length !== doc.count) return { ok: false, reason: `the list holds ${leaves.length} leaves; the root document states ${doc.count}` };
349
+ for (let i = 1; i < leaves.length; i++) {
350
+ const c = compareBytes(leaves[i - 1]!.artifact, leaves[i]!.artifact);
351
+ if (c === 0) return { ok: false, reason: `duplicate artifact digest at leaves ${i - 1} and ${i}` };
352
+ if (c > 0) return { ok: false, reason: `leaves ${i - 1} and ${i} are out of order` };
353
+ }
354
+ const root = new MerkleTree(leaves.map(treeLeafHash)).root;
355
+ if (!bytesEqual(root, doc.root)) return { ok: false, reason: "the leaves do not rebuild the committed root" };
356
+ return { ok: true, count: doc.count };
357
+ }
358
+
359
+ // ---------------------------------------------------------------------------
360
+ // Committed bytes for a leaf
361
+ // ---------------------------------------------------------------------------
362
+
363
+ /** The committed bytes a placement makes from an original. For 0x00 the original is the committed bytes. */
364
+ export function committedBytesFor(code: number, original: Uint8Array, commitment: Uint8Array): Uint8Array {
365
+ const id = LEAF_PLACEMENTS[code];
366
+ if (id === undefined) throw new TypeError("unregistered leaf placement code");
367
+ if (id === "as-is") return original;
368
+ const p = getPlacement(id)!;
369
+ return p.build({ original, originDigest: sha256(original), commitment });
370
+ }
371
+
372
+ /** A leaf for an original under a placement and a commitment. */
373
+ export function leafFor(code: number, original: Uint8Array, commitment: Uint8Array): { leaf: TreeLeaf; committed: Uint8Array } {
374
+ const committed = committedBytesFor(code, original, commitment);
375
+ const origin = sha256(original);
376
+ return { leaf: { placement: code, artifact: code === LEAF_AS_IS ? origin : sha256(committed), origin }, committed };
377
+ }
378
+
379
+ // ---------------------------------------------------------------------------
380
+ // Verifying a member
381
+ // ---------------------------------------------------------------------------
382
+
383
+ export type TreeCategory =
384
+ | "TREE_MEMBER_DIRECT"
385
+ | "TREE_MEMBER_FROM_ORIGIN"
386
+ | "TREE_MEMBER_AS_IS"
387
+ | "TREE_PATH_VALID"
388
+ | "TREE_ROOT_VALID"
389
+ | "TREE_MEMBERSHIP_UNPROVEN"
390
+ | "NO_MATCH"
391
+ | "RECONSTRUCTION_MISMATCH"
392
+ | "INVALID_ORIGIN"
393
+ | "INVALID_TREE_PATH"
394
+ | "INVALID_TREE_ROOT"
395
+ | "INVALID_SLOT_COMMITMENT"
396
+ | "INVALID_TREE_MARKER"
397
+ | "UNKNOWN_SPEC"
398
+ | "INVALID_UNDERLYING_PROOF"
399
+ | "NOT_TREE";
400
+
401
+ /** The categories that mean the supplied file is a member of the committed tree. */
402
+ export const TREE_MEMBER_CATEGORIES: readonly TreeCategory[] = ["TREE_MEMBER_DIRECT", "TREE_MEMBER_FROM_ORIGIN", "TREE_MEMBER_AS_IS"];
403
+
404
+ export interface TreeVerifyOptions {
405
+ proof: BitGraphProof;
406
+ /** The file in hand: the original or the committed bytes. Omit to check the proof, the root and the path alone. */
407
+ bytes?: Uint8Array;
408
+ /** The file in hand as a stream (stream.ts), for a file of any size: the same judgment as `bytes`, in constant memory. One of the two. */
409
+ source?: ByteSource;
410
+ /** The member's evidence (TreeMemberEvidence JSON). Omit to check the proof and the root alone. */
411
+ member?: unknown;
412
+ /** The 84-byte root document; when omitted it is read from proof.metadata. */
413
+ rootDocument?: Uint8Array | null;
414
+ trustAnchors?: VerificationPolicy;
415
+ /** Spec hashes (base64) to accept in addition to KNOWN_TREE_SPEC_HASHES. */
416
+ extraSpecHashes?: readonly string[];
417
+ /** Skip the proof's own checks (only when the caller already ran them on this exact proof). */
418
+ proofAlreadyVerified?: boolean;
419
+ }
420
+
421
+ export interface TreeVerifyResult {
422
+ category: TreeCategory;
423
+ /** One sentence: what was established, or why not. */
424
+ reason: string;
425
+ proof: { valid: boolean; reason?: string };
426
+ /** The spec hash the proof pins (base64), when it has one. */
427
+ specHashB64: string | null;
428
+ /** Present once the root document is bound to the signed digest and to the slot. */
429
+ tree: { count: number; rootHex: string; commitmentHex: string } | null;
430
+ /** Present once the member's path reaches the bound root. */
431
+ member: { index: number; count: number; placement: string; artifactHex: string; originHex: string } | null;
432
+ /**
433
+ * What the floor covers for THIS file. "content": the committed bytes carry
434
+ * the commitment, so they were finished after the floor block (the original
435
+ * inside them is not dated by it). "record": an as-is leaf; the record was
436
+ * made after the floor block, and the bytes themselves are not dated.
437
+ */
438
+ floorCovers: "content" | "record" | null;
439
+ span: FuseSpan | null;
440
+ }
441
+
442
+ export async function verifyTreeMember(opts: TreeVerifyOptions): Promise<TreeVerifyResult> {
443
+ const { proof } = opts;
444
+ const span = proof?.commit ? spanOf(proof) : null;
445
+ const base = (category: TreeCategory, reason: string, extra: Partial<TreeVerifyResult> = {}): TreeVerifyResult => ({
446
+ category, reason, proof: { valid: false }, specHashB64: null, tree: null, member: null, floorCovers: null, span, ...extra,
447
+ });
448
+
449
+ if (!isTreeProof(proof)) return base("NOT_TREE", "the proof's signed title is not tree/1");
450
+
451
+ // 1. The proof itself.
452
+ let proofResult: { valid: boolean; reason?: string } = { valid: true };
453
+ if (!opts.proofAlreadyVerified) {
454
+ const v = await verifyProofIntegrity({ proof, ...(opts.trustAnchors ? { trustAnchors: opts.trustAnchors } : {}) });
455
+ proofResult = v.valid ? { valid: true } : { valid: false, ...(v.reason ? { reason: v.reason } : {}) };
456
+ if (!v.valid) return base("INVALID_UNDERLYING_PROOF", `the proof does not verify (${v.reason ?? "invalid"})`, { proof: proofResult });
457
+ }
458
+
459
+ // 2. The signed marker: fuse/2 or fuse/3 (the floor is bound) and a known spec that requires it.
460
+ const a = proof.attribution!;
461
+ const markerVersion = fuseVersionOfName(a.name);
462
+ if (markerVersion !== 2 && markerVersion !== 3) return base("INVALID_TREE_MARKER", "a tree/1 proof must be marked bitgraph-fuse/2 or bitgraph-fuse/3, which bind the floor block into the commitment", { proof: proofResult });
463
+ const specBytes = typeof a.message === "string" ? base64ToBytes(a.message) : null;
464
+ if (specBytes === null || specBytes.length !== 32) return base("INVALID_TREE_MARKER", "a tree/1 proof must pin its spec: the signed message is the base64 SHA-256 of SPEC.md", { proof: proofResult });
465
+ const specHashB64 = a.message as string;
466
+ const known = new Set([...KNOWN_TREE_SPEC_HASHES, ...(opts.extraSpecHashes ?? [])]);
467
+ if (!known.has(specHashB64)) return base("UNKNOWN_SPEC", `the proof follows a spec this verifier does not know (${specHashB64})`, { proof: proofResult, specHashB64 });
468
+ const required = TREE_SPEC_FUSE_VERSION.get(specHashB64);
469
+ if (required !== undefined && required !== markerVersion) {
470
+ return base("INVALID_TREE_MARKER", `the proof pins a spec that defines tree/1 under bitgraph-fuse/${required}, but is marked bitgraph-fuse/${markerVersion}`, { proof: proofResult, specHashB64 });
471
+ }
472
+
473
+ // 3. The commitment, from the proof's own slot record and signed floor block.
474
+ if (!proof.slotAllocation) return base("INVALID_SLOT_COMMITMENT", "the proof carries no slot record, so no commitment can be recomputed", { proof: proofResult, specHashB64 });
475
+ let commitment: Uint8Array;
476
+ try {
477
+ commitment = commitmentForProof(proof, proof.slotAllocation);
478
+ } catch (e) {
479
+ return base("INVALID_SLOT_COMMITMENT", `the commitment could not be recomputed: ${(e as Error).message}`, { proof: proofResult, specHashB64 });
480
+ }
481
+
482
+ // 4. The root document: hashes to the signed digest, carries this commitment.
483
+ const docBytes = opts.rootDocument ?? readTreeMetadata(proof);
484
+ if (docBytes === null || docBytes === undefined) return base("INVALID_TREE_ROOT", "no root document is in hand (neither supplied nor in the proof's metadata)", { proof: proofResult, specHashB64 });
485
+ const doc = parseTreeRootDocument(docBytes);
486
+ if (doc === null) return base("INVALID_TREE_ROOT", "the root document is not 84 bytes of tree/1", { proof: proofResult, specHashB64 });
487
+ const signed = base64ToBytes(proof.artifact.digestB64);
488
+ if (signed === null || !bytesEqual(sha256(docBytes), signed)) return base("INVALID_TREE_ROOT", "the root document does not hash to the signed artifact digest", { proof: proofResult, specHashB64 });
489
+ if (!bytesEqual(doc.commitment, commitment)) return base("INVALID_SLOT_COMMITMENT", "the root document's commitment is not the one recomputed from the proof's slot record and floor block", { proof: proofResult, specHashB64 });
490
+ const tree = { count: doc.count, rootHex: bytesToHex(doc.root), commitmentHex: bytesToHex(commitment) };
491
+
492
+ // 5. The member's path to that root.
493
+ if (opts.bytes !== undefined && opts.source !== undefined) throw new TypeError("pass the file as bytes or as a source, not both");
494
+ const haveFile = opts.bytes !== undefined || opts.source !== undefined;
495
+ if (opts.member === undefined || opts.member === null) {
496
+ const carries = opts.bytes !== undefined
497
+ ? carriesCommitment(opts.bytes, commitment)
498
+ : opts.source !== undefined ? (await streamLeafCheck(opts.source, { placement: null, commitment, origin: null })).carriesCommitment : false;
499
+ if (carries) {
500
+ return base("TREE_MEMBERSHIP_UNPROVEN", "these bytes carry this position's commitment, so they were finished after the floor block, but no member evidence is in hand to show they are in the tree", { proof: proofResult, specHashB64, tree });
501
+ }
502
+ if (haveFile) return base("NO_MATCH", "no member evidence is in hand and the bytes carry no commitment to this position", { proof: proofResult, specHashB64, tree });
503
+ return base("TREE_ROOT_VALID", `the proof is valid and commits a tree of ${doc.count} leaves`, { proof: proofResult, specHashB64, tree });
504
+ }
505
+ const ev = parseTreeMemberEvidence(opts.member);
506
+ if (ev === null) return base("INVALID_TREE_PATH", "the member evidence is not well-formed tree/1 evidence", { proof: proofResult, specHashB64, tree });
507
+ if (ev.count !== doc.count) return base("INVALID_TREE_PATH", `the evidence names a tree of ${ev.count} leaves; the root document states ${doc.count}`, { proof: proofResult, specHashB64, tree });
508
+ const reached = treeRootFromMember(ev.leaf, ev.index, ev.count, ev.path);
509
+ if (reached === null || !bytesEqual(reached, doc.root)) return base("INVALID_TREE_PATH", "the leaf and path do not recompute the committed root", { proof: proofResult, specHashB64, tree });
510
+ const placementId = LEAF_PLACEMENTS[ev.leaf.placement]!;
511
+ const member = { index: ev.index, count: ev.count, placement: placementId, artifactHex: bytesToHex(ev.leaf.artifact), originHex: bytesToHex(ev.leaf.origin) };
512
+ const ok = { proof: proofResult, specHashB64, tree, member };
513
+
514
+ if (!haveFile) return base("TREE_PATH_VALID", `leaf ${ev.index} of ${ev.count} is in the committed tree; no file was checked`, ok);
515
+
516
+ // 6. The file against the leaf. Streamed when the file came as a source: the
517
+ // same three outcomes, from one pass in constant memory (stream.ts).
518
+ if (opts.source !== undefined) {
519
+ const scan = await streamLeafCheck(opts.source, { placement: ev.leaf.placement === LEAF_AS_IS ? null : (placementId as StreamPlacement), commitment, origin: ev.leaf.origin });
520
+ if (bytesEqual(scan.digest, ev.leaf.artifact)) {
521
+ if (ev.leaf.placement === LEAF_AS_IS) {
522
+ return base("TREE_MEMBER_AS_IS", `this file is leaf ${ev.index} of ${ev.count}, recorded as is: the record was made after the floor block; the bytes themselves are not dated`, { ...ok, floorCovers: "record" });
523
+ }
524
+ if (scan.direct === null || !scan.direct.ok) {
525
+ return base("INVALID_SLOT_COMMITMENT", `the bytes match leaf ${ev.index} but are not a valid ${placementId} carrying this position's commitment (${scan.direct?.ok === false ? scan.direct.reason : "no layout was checked"})`, ok);
526
+ }
527
+ if (!bytesEqual(scan.direct.embeddedOrigin, ev.leaf.origin)) {
528
+ return base("INVALID_ORIGIN", "the origin inside the committed bytes does not match the leaf's origin", ok);
529
+ }
530
+ return base("TREE_MEMBER_DIRECT", `these are the committed bytes of leaf ${ev.index} of ${ev.count}; they were finished after the floor block`, { ...ok, floorCovers: "content" });
531
+ }
532
+ if (bytesEqual(scan.digest, ev.leaf.origin) && ev.leaf.placement !== LEAF_AS_IS) {
533
+ if (scan.fusedFromOrigin === null || !bytesEqual(scan.fusedFromOrigin, ev.leaf.artifact)) {
534
+ return base("RECONSTRUCTION_MISMATCH", `this file is leaf ${ev.index}'s origin, but placing the commitment in it does not reproduce the committed digest`, ok);
535
+ }
536
+ return base("TREE_MEMBER_FROM_ORIGIN", `this file rebuilds the committed bytes of leaf ${ev.index} of ${ev.count}; the committed bytes were finished after the floor block, and this original is not dated by it`, { ...ok, floorCovers: "content" });
537
+ }
538
+ if (scan.carriesCommitment) {
539
+ return base("TREE_MEMBERSHIP_UNPROVEN", "these bytes carry this position's commitment, but the evidence in hand describes a different leaf", ok);
540
+ }
541
+ return base("NO_MATCH", "the file is neither this leaf's committed bytes nor its origin", ok);
542
+ }
543
+ const fileBytes = opts.bytes!;
544
+ const fileDigest = sha256(fileBytes);
545
+ if (bytesEqual(fileDigest, ev.leaf.artifact)) {
546
+ if (ev.leaf.placement === LEAF_AS_IS) {
547
+ return base("TREE_MEMBER_AS_IS", `this file is leaf ${ev.index} of ${ev.count}, recorded as is: the record was made after the floor block; the bytes themselves are not dated`, { ...ok, floorCovers: "record" });
548
+ }
549
+ const located = getPlacement(placementId)!.locate(fileBytes);
550
+ if (located === null || !bytesEqual(located.commitment, commitment)) {
551
+ return base("INVALID_SLOT_COMMITMENT", `the bytes match leaf ${ev.index} but are not a valid ${placementId} carrying this position's commitment (its structure, the original's digest or the commitment does not hold)`, ok);
552
+ }
553
+ const embedded = located.originDigest ?? (located.originalBytes !== undefined ? sha256(located.originalBytes) : undefined);
554
+ if (embedded !== undefined && !bytesEqual(embedded, ev.leaf.origin)) {
555
+ return base("INVALID_ORIGIN", "the origin inside the committed bytes does not match the leaf's origin", ok);
556
+ }
557
+ return base("TREE_MEMBER_DIRECT", `these are the committed bytes of leaf ${ev.index} of ${ev.count}; they were finished after the floor block`, { ...ok, floorCovers: "content" });
558
+ }
559
+ if (bytesEqual(fileDigest, ev.leaf.origin) && ev.leaf.placement !== LEAF_AS_IS) {
560
+ const rebuilt = committedBytesFor(ev.leaf.placement, fileBytes, commitment);
561
+ if (!bytesEqual(sha256(rebuilt), ev.leaf.artifact)) {
562
+ return base("RECONSTRUCTION_MISMATCH", `this file is leaf ${ev.index}'s origin, but placing the commitment in it does not reproduce the committed digest`, ok);
563
+ }
564
+ return base("TREE_MEMBER_FROM_ORIGIN", `this file rebuilds the committed bytes of leaf ${ev.index} of ${ev.count}; the committed bytes were finished after the floor block, and this original is not dated by it`, { ...ok, floorCovers: "content" });
565
+ }
566
+ // The evidence holds (its path reaches the root), so the member is known; the file is not it.
567
+ if (carriesCommitment(fileBytes, commitment)) {
568
+ return base("TREE_MEMBERSHIP_UNPROVEN", "these bytes carry this position's commitment, but the evidence in hand describes a different leaf", ok);
569
+ }
570
+ return base("NO_MATCH", "the file is neither this leaf's committed bytes nor its origin", ok);
571
+ }
572
+
573
+ function carriesCommitment(bytes: Uint8Array, commitment: Uint8Array): boolean {
574
+ for (const p of PLACEMENTS) {
575
+ if (p.id === "produced/1") continue;
576
+ const located = p.locate(bytes);
577
+ if (located !== null && bytesEqual(located.commitment, commitment)) return true;
578
+ }
579
+ return false;
580
+ }
package/src/types.ts CHANGED
@@ -183,6 +183,28 @@ export interface BitGraphProof {
183
183
  blockHash: string;
184
184
  };
185
185
 
186
+ /**
187
+ * Enclave v10 (2026-10-06). The Base block fixed as this proof's floor
188
+ * when its slot was ALLOCATED: the parent hands the enclave the newest Base
189
+ * header, and the enclave hashes it (keccak-256), reads the number and time
190
+ * from the same bytes, refuses a block lower than the chain's last floor or
191
+ * stamped ahead of its own clock or off Base's 2 s schedule, and SIGNS the result here. It names its
192
+ * chain, so a verifier never reads it as an Ethereum floor. Proofs with
193
+ * slotAnchor and no slotFloor have an Ethereum floor. Verify it with the
194
+ * Base header: keccak(header) must equal blockHash and the block must be
195
+ * on Base (one lookup).
196
+ */
197
+ slotFloor?: {
198
+ chain: "base";
199
+ /** The EVM chain id, not BitGraph's chain id (commit.chainId). */
200
+ evmChainId: 8453;
201
+ blockNumber: number;
202
+ /** 0x-prefixed lowercase hex, 32 bytes. */
203
+ blockHash: string;
204
+ /** Unix seconds, read from the header. */
205
+ blockTimestamp: number;
206
+ };
207
+
186
208
  /**
187
209
  * Epoch lineage link — present only on the FIRST proof of a new epoch.
188
210
  *