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