@mikeargento/bitgraph-verify 1.15.2 → 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.
Files changed (56) hide show
  1. package/dist/__tests__/carrier2.test.js +61 -2
  2. package/dist/__tests__/carrier2.test.js.map +1 -1
  3. package/dist/__tests__/ceiling.test.js +11 -4
  4. package/dist/__tests__/ceiling.test.js.map +1 -1
  5. package/dist/carrier-verify.d.ts +10 -2
  6. package/dist/carrier-verify.d.ts.map +1 -1
  7. package/dist/carrier-verify.js +98 -23
  8. package/dist/carrier-verify.js.map +1 -1
  9. package/dist/carrier.d.ts +4 -2
  10. package/dist/carrier.d.ts.map +1 -1
  11. package/dist/carrier.js.map +1 -1
  12. package/dist/ceiling.d.ts +33 -3
  13. package/dist/ceiling.d.ts.map +1 -1
  14. package/dist/ceiling.js +55 -6
  15. package/dist/ceiling.js.map +1 -1
  16. package/dist/export.d.ts +112 -0
  17. package/dist/export.d.ts.map +1 -0
  18. package/dist/export.js +451 -0
  19. package/dist/export.js.map +1 -0
  20. package/dist/fuse.d.ts +2 -0
  21. package/dist/fuse.d.ts.map +1 -1
  22. package/dist/fuse.js +16 -1
  23. package/dist/fuse.js.map +1 -1
  24. package/dist/index.d.ts +12 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +12 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/measurements.d.ts +30 -0
  29. package/dist/measurements.d.ts.map +1 -0
  30. package/dist/measurements.js +21 -0
  31. package/dist/measurements.js.map +1 -0
  32. package/dist/output-root.d.ts +88 -0
  33. package/dist/output-root.d.ts.map +1 -0
  34. package/dist/output-root.js +260 -0
  35. package/dist/output-root.js.map +1 -0
  36. package/dist/stream.d.ts +46 -0
  37. package/dist/stream.d.ts.map +1 -0
  38. package/dist/stream.js +290 -0
  39. package/dist/stream.js.map +1 -0
  40. package/dist/tree.d.ts +155 -0
  41. package/dist/tree.d.ts.map +1 -0
  42. package/dist/tree.js +456 -0
  43. package/dist/tree.js.map +1 -0
  44. package/package.json +1 -1
  45. package/src/__tests__/carrier2.test.ts +64 -2
  46. package/src/__tests__/ceiling.test.ts +12 -4
  47. package/src/carrier-verify.ts +104 -23
  48. package/src/carrier.ts +4 -2
  49. package/src/ceiling.ts +70 -7
  50. package/src/export.ts +529 -0
  51. package/src/fuse.ts +13 -1
  52. package/src/index.ts +30 -0
  53. package/src/measurements.ts +48 -0
  54. package/src/output-root.ts +301 -0
  55. package/src/stream.ts +291 -0
  56. package/src/tree.ts +548 -0
@@ -0,0 +1,48 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * The enclave images BitGraph has published (SPEC.md section 16), oldest
5
+ * first: every PCR0 a real BitGraph proof can carry.
6
+ *
7
+ * An attestation that chains to the AWS Nitro root shows that SOME Nitro
8
+ * enclave signed; anyone can run one. Which image is BitGraph's is a
9
+ * measurement policy, and this list is that policy by default:
10
+ * verifyExport and verifyCarrier judge `attestation.pins` against it when
11
+ * the caller names no list of their own, and a proof from any other image is
12
+ * not a BitGraph. A caller who rebuilt an image from its tagged source and
13
+ * wants to accept exactly that passes their own list instead.
14
+ *
15
+ * Keep in step with SPEC.md section 16, the site's
16
+ * website/src/lib/enclave-measurements.ts and the player's
17
+ * KNOWN_ENCLAVE_MEASUREMENTS; a root test checks all of them against this.
18
+ */
19
+
20
+ export interface PublishedMeasurement {
21
+ /** The image's name in BitGraph's history: "genesis", "v2", ... */
22
+ version: string;
23
+ /** The UTC day it went live (YYYY-MM-DD). */
24
+ since: string;
25
+ /** PCR0, 96 lowercase hex characters. */
26
+ pcr0: string;
27
+ }
28
+
29
+ export const PUBLISHED_ENCLAVE_MEASUREMENTS: readonly PublishedMeasurement[] = Object.freeze([
30
+ { version: "genesis", since: "2026-05-15", pcr0: "8530a6399399c4f23d89f5a1faa2e8bf2e09a5959f117070fca08148377f92c902c695fc926c17f67f35f110327dca92" },
31
+ { version: "v2", since: "2026-06-27", pcr0: "bb9dd158703603ec222fe565495ceaa7edc08f665da5c1cddad91442ac2211731390267036d79deb720d13fb704f648a" },
32
+ { version: "v4", since: "2026-07-05", pcr0: "e2fccbae77ee40aac4830e84f195e05d69eb4547bbd961f4d3459feba10807140424aca42ad03810354982598c86b9cb" },
33
+ { version: "v5", since: "2026-07-29", pcr0: "6483cedffed74680ffb287507744a398b288c3fb943eb3f2e4fe889f8b60b3d575ad8942350360b69a1bd7bf713df27f" },
34
+ { version: "v6", since: "2026-09-05", pcr0: "cd8ba52d340fb1be78610b59953ded2ceca23be1cfcc7ab504a26b8fdcd7ba92090f49e28a32d008df046ec4212f77bf" },
35
+ { version: "v7", since: "2026-09-06", pcr0: "394c3cf515651dc27187d85e4716c12dfeb99c1227f1fe0eacfaa427d80018e1a28ebba9469e99c7936601f901d74e1d" },
36
+ { version: "v8", since: "2026-09-07", pcr0: "eccfc1c78006f4b74f929c992785575c908a0f60eca08ff638cd6c0842f993f182ebb002457b8ef3e732a6a10805c72b" },
37
+ { version: "v9", since: "2026-09-30", pcr0: "934feb8bb6f4f7e2d2f85d902a7d5edd0981f706d9d2385638988ac096a05ea0583c3d00eef2a7947865ec66efc1fcf8" },
38
+ ].map((m) => Object.freeze(m)));
39
+
40
+ /** PUBLISHED_ENCLAVE_MEASUREMENTS as the bare PCR0 list a verifier's pins take. */
41
+ export const PUBLISHED_PCR0S: readonly string[] = Object.freeze(PUBLISHED_ENCLAVE_MEASUREMENTS.map((m) => m.pcr0));
42
+
43
+ /** The published image a PCR0 names, or null when it is not one of BitGraph's. Case-insensitive. */
44
+ export function publishedMeasurement(pcr0: unknown): PublishedMeasurement | null {
45
+ if (typeof pcr0 !== "string") return null;
46
+ const want = pcr0.toLowerCase();
47
+ return PUBLISHED_ENCLAVE_MEASUREMENTS.find((m) => m.pcr0 === want) ?? null;
48
+ }
@@ -0,0 +1,301 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * bitgraph-output-root/1: settling a Base ceiling on Ethereum without blobs
5
+ * (2026-10-03).
6
+ *
7
+ * A Base ceiling is a transaction in Base block B. Base posts an OUTPUT ROOT
8
+ * for one of its blocks P to Ethereum about every 600 Base blocks, as the
9
+ * rootClaim of a dispute game:
10
+ *
11
+ * outputRoot = keccak256(version (32 zero bytes) || stateRoot_P || messagePasserStorageRoot_P || blockHash_P)
12
+ *
13
+ * Base runs the EIP-2935 history contract, which keeps the hashes of the
14
+ * previous 8,191 blocks in its storage, so B's hash is provable from P's state
15
+ * when 1 <= P - B <= 8,191 (the contract holds earlier blocks only). When
16
+ * B = P the output root names P's hash directly.
17
+ *
18
+ * The chain this module checks, every link by hash:
19
+ * Ethereum tx in block H carries outputRoot
20
+ * -> outputRoot preimage (stateRoot_P, blockHash_P)
21
+ * -> B's hash (from P's state by storage proof, or blockHash_P when B = P)
22
+ * -> B's header (checked by the ceiling sidecar)
23
+ *
24
+ * What it proves: the ceiling transaction, and so the root it carries, existed
25
+ * by Ethereum block H. Any Ethereum transaction whose bytes commit to the
26
+ * output root by hash proves that, whoever sent it and whether or not Base's
27
+ * claim is ever upheld; so the sender and the game's outcome are not checked.
28
+ * What it does NOT prove: that B is canonical on Base, or B's timestamp. Those
29
+ * need Base itself (checkCeilingOnline). Whether H is canonical is the one
30
+ * outside lookup this leaves.
31
+ */
32
+
33
+ import { bytesEqual, decodeHeader, hexToBytes, bytesToHex, keccak256, mptVerify, rlpDecode, txTrieKey, type RlpItem } from "./ceiling-evm.js";
34
+
35
+ export const OUTPUT_ROOT_VERSION = "bitgraph-output-root/1" as const;
36
+ /** EIP-2935 history storage contract (the same address on Ethereum and on OP Stack chains). */
37
+ export const HISTORY_STORAGE_ADDRESS = "0x0000f90827f1c53a10cb7a02335b175320002935" as const;
38
+ /** EIP-2935 ring buffer size: the contract keeps the previous 8,191 block hashes. */
39
+ export const HISTORY_SERVE_WINDOW = 8191;
40
+ /** Base mainnet's dispute game factory on Ethereum (OptimismPortal 0x49048044D57e1C92A77f79988d21Fa8fAF74E97e). Informational. */
41
+ export const BASE_DISPUTE_GAME_FACTORY = "0x43edb88c4b80fdd2adff2412a7bebf9df42cb40e" as const;
42
+
43
+ export interface OutputRootSettlement {
44
+ version: typeof OUTPUT_ROOT_VERSION;
45
+ /** The ceiling's Base block: number and hash (the hash is also the ceiling sidecar's). */
46
+ base: { chainId: number; blockNumber: number; blockHash: string };
47
+ /** The output-root preimage for Base block P. */
48
+ outputRoot: {
49
+ blockNumber: number;
50
+ /** 32 bytes, all zero for output-root version 0. */
51
+ version: string;
52
+ stateRoot: string;
53
+ messagePasserStorageRoot: string;
54
+ blockHash: string;
55
+ };
56
+ /** B's hash in P's state. Null exactly when B = P. */
57
+ history: {
58
+ address: string;
59
+ /** uint256(B mod 8191), 32 bytes. */
60
+ slot: string;
61
+ accountProof: string[];
62
+ storageProof: string[];
63
+ } | null;
64
+ /** The Ethereum transaction that carries the output root, and its block. */
65
+ ethereum: {
66
+ chainId: number;
67
+ blockNumber: number;
68
+ blockHash: string;
69
+ blockTimestamp: number;
70
+ header: string;
71
+ txHash: string;
72
+ txIndex: number;
73
+ rawTx: string;
74
+ txInclusionProof: string[];
75
+ };
76
+ /** Informational, never verified: which dispute game this was. */
77
+ game?: { factory: string; gameType: number; index: number; proxy: string };
78
+ }
79
+
80
+ export interface OutputRootCheck { name: string; ok: boolean; detail?: string }
81
+
82
+ export interface OutputRootVerifyResult {
83
+ ok: boolean;
84
+ reason?: string;
85
+ checks: OutputRootCheck[];
86
+ /** On success: the ceiling transaction existed by this Ethereum block. Canonicality of the block is not checked here. */
87
+ existedBy?: { chainId: number; blockNumber: number; blockHash: string; blockTimestamp: number };
88
+ /** The output root that was recomputed (0x hex). */
89
+ outputRootHex?: string;
90
+ }
91
+
92
+ const ZERO32 = new Uint8Array(32);
93
+
94
+ function b32(hex: string, name: string): Uint8Array {
95
+ const b = hexToBytes(hex);
96
+ if (b.length !== 32) throw new TypeError(`${name} must be 32 bytes`);
97
+ return b;
98
+ }
99
+
100
+ /** keccak256(version || stateRoot || messagePasserStorageRoot || blockHash). */
101
+ export function computeOutputRoot(o: OutputRootSettlement["outputRoot"]): Uint8Array {
102
+ const parts = [b32(o.version, "outputRoot.version"), b32(o.stateRoot, "outputRoot.stateRoot"), b32(o.messagePasserStorageRoot, "outputRoot.messagePasserStorageRoot"), b32(o.blockHash, "outputRoot.blockHash")];
103
+ const pre = new Uint8Array(128);
104
+ parts.forEach((p, i) => pre.set(p, i * 32));
105
+ return keccak256(pre);
106
+ }
107
+
108
+ /** The EIP-2935 storage slot holding block n's hash: uint256(n mod 8191), big-endian. */
109
+ export function historySlot(blockNumber: number): Uint8Array {
110
+ const slot = new Uint8Array(32);
111
+ let v = blockNumber % HISTORY_SERVE_WINDOW;
112
+ for (let i = 31; i >= 0 && v > 0; i--) {
113
+ slot[i] = v & 0xff;
114
+ v = Math.floor(v / 256);
115
+ }
116
+ return slot;
117
+ }
118
+
119
+ function indexOfBytes(hay: Uint8Array, needle: Uint8Array): number {
120
+ outer: for (let i = 0; i + needle.length <= hay.length; i++) {
121
+ for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
122
+ return i;
123
+ }
124
+ return -1;
125
+ }
126
+
127
+ /** RLP bytes as an unsigned integer value padded to 32 bytes (storage values are RLP of the minimal big-endian bytes). */
128
+ function storageWord(item: RlpItem): Uint8Array | null {
129
+ if (!(item instanceof Uint8Array) || item.length > 32) return null;
130
+ const out = new Uint8Array(32);
131
+ out.set(item, 32 - item.length);
132
+ return out;
133
+ }
134
+
135
+ /**
136
+ * Verify an output-root settlement, offline. Every link is recomputed from
137
+ * bytes; the result names the Ethereum block whose canonicality is the one
138
+ * remaining lookup.
139
+ */
140
+ export interface OutputRootVerifyOptions {
141
+ /** The chain the ceiling is on. Default Base mainnet, 8453. */
142
+ baseChainId?: number;
143
+ /** The chain the settlement is on. Default Ethereum mainnet, 1. */
144
+ ethereumChainId?: number;
145
+ }
146
+
147
+ /** The chain a raw Ethereum transaction is signed for: field 0 of a typed transaction, or EIP-155's v. Null when it names none. */
148
+ function transactionChainId(raw: Uint8Array): bigint | null {
149
+ if (raw.length === 0) return null;
150
+ const big = (b: Uint8Array) => b.reduce((n, x) => (n << 8n) | BigInt(x), 0n);
151
+ try {
152
+ if (raw[0]! <= 0x7f) {
153
+ const item = rlpDecode(raw.subarray(1));
154
+ return Array.isArray(item) && item[0] instanceof Uint8Array ? big(item[0]) : null;
155
+ }
156
+ const item = rlpDecode(raw);
157
+ if (!Array.isArray(item) || item.length !== 9 || !(item[6] instanceof Uint8Array)) return null;
158
+ const v = big(item[6]);
159
+ return v >= 35n ? (v - 35n) / 2n : null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ export function verifyOutputRootSettlement(s: OutputRootSettlement, opts: OutputRootVerifyOptions = {}): OutputRootVerifyResult {
166
+ const checks: OutputRootCheck[] = [];
167
+ const fail = (name: string, detail: string): OutputRootVerifyResult => {
168
+ checks.push({ name, ok: false, detail });
169
+ return { ok: false, reason: `${name}: ${detail}`, checks };
170
+ };
171
+ // A malformed field anywhere is a failed check, never an exception.
172
+ try {
173
+ return verifyOutputRootChecks(s, opts, checks, fail);
174
+ } catch (e) {
175
+ return fail("malformed", `a field of the settlement is malformed: ${e instanceof Error ? e.message : String(e)}`);
176
+ }
177
+ }
178
+
179
+ function verifyOutputRootChecks(
180
+ s: OutputRootSettlement,
181
+ opts: OutputRootVerifyOptions,
182
+ checks: OutputRootCheck[],
183
+ fail: (name: string, detail: string) => OutputRootVerifyResult,
184
+ ): OutputRootVerifyResult {
185
+ const pass = (name: string, detail?: string) => checks.push(detail === undefined ? { name, ok: true } : { name, ok: true, detail });
186
+
187
+ if (s?.version !== OUTPUT_ROOT_VERSION) return fail("format", `not a ${OUTPUT_ROOT_VERSION} settlement`);
188
+
189
+ // 0. The chains: the labels are part of what the result reports, so they are checked, never echoed.
190
+ const baseChain = opts.baseChainId ?? 8453;
191
+ const l1Chain = opts.ethereumChainId ?? 1;
192
+ if (s.base?.chainId !== baseChain) return fail("chain", `the settlement is for chain ${String(s.base?.chainId)}; this verifier settles Base ${baseChain}`);
193
+ if (s.ethereum?.chainId !== l1Chain) return fail("chain", `the settlement names chain ${String(s.ethereum?.chainId)}; this verifier settles on Ethereum ${l1Chain}`);
194
+
195
+ // 1. The output root from its preimage.
196
+ let outputRoot: Uint8Array;
197
+ try {
198
+ if (!bytesEqual(b32(s.outputRoot.version, "outputRoot.version"), ZERO32)) return fail("output-root", "only output-root version 0 (32 zero bytes) is defined");
199
+ outputRoot = computeOutputRoot(s.outputRoot);
200
+ } catch (e) {
201
+ return fail("output-root", (e as Error).message);
202
+ }
203
+ pass("output-root", `${bytesToHex(outputRoot)} for Base block ${s.outputRoot.blockNumber}`);
204
+
205
+ // 2. B's hash from P: directly when B = P, else by EIP-2935 storage proof.
206
+ const B = s.base.blockNumber;
207
+ const P = s.outputRoot.blockNumber;
208
+ let bHash: Uint8Array;
209
+ try {
210
+ bHash = b32(s.base.blockHash, "base.blockHash");
211
+ } catch (e) {
212
+ return fail("base", (e as Error).message);
213
+ }
214
+ if (!Number.isInteger(B) || !Number.isInteger(P) || B < 0) return fail("base", "block numbers must be non-negative integers");
215
+ if (B === P) {
216
+ if (s.history !== null) return fail("history", "B = P needs no history proof, and one was given");
217
+ if (!bytesEqual(b32(s.outputRoot.blockHash, "outputRoot.blockHash"), bHash)) return fail("history", "B = P, but the output root names a different block hash");
218
+ pass("history", `B = P: the output root names block ${B}'s hash directly`);
219
+ } else {
220
+ const d = P - B;
221
+ if (d < 1 || d > HISTORY_SERVE_WINDOW) return fail("history", `P - B is ${d}; the history contract holds blocks 1 to ${HISTORY_SERVE_WINDOW} before P`);
222
+ const h = s.history;
223
+ if (!h) return fail("history", "B < P needs a history storage proof");
224
+ if (h.address.toLowerCase() !== HISTORY_STORAGE_ADDRESS) return fail("history", `the proof is for ${h.address}, not the EIP-2935 contract`);
225
+ let slot: Uint8Array;
226
+ try {
227
+ slot = b32(h.slot, "history.slot");
228
+ } catch (e) {
229
+ return fail("history", (e as Error).message);
230
+ }
231
+ if (!bytesEqual(slot, historySlot(B))) return fail("history", `the slot is not B mod ${HISTORY_SERVE_WINDOW}`);
232
+ let account: Uint8Array | null;
233
+ try {
234
+ account = mptVerify(b32(s.outputRoot.stateRoot, "outputRoot.stateRoot"), keccak256(hexToBytes(HISTORY_STORAGE_ADDRESS)), h.accountProof.map(hexToBytes));
235
+ } catch {
236
+ account = null;
237
+ }
238
+ if (!account) return fail("history", "the account proof does not reach P's state root");
239
+ let storageRoot: Uint8Array;
240
+ try {
241
+ const fields = rlpDecode(account);
242
+ if (!Array.isArray(fields) || fields.length !== 4 || !(fields[2] instanceof Uint8Array) || fields[2].length !== 32) throw new TypeError("account");
243
+ storageRoot = fields[2];
244
+ } catch {
245
+ return fail("history", "the account record is not [nonce, balance, storageRoot, codeHash]");
246
+ }
247
+ let raw: Uint8Array | null;
248
+ try {
249
+ raw = mptVerify(storageRoot, keccak256(slot), h.storageProof.map(hexToBytes));
250
+ } catch {
251
+ raw = null;
252
+ }
253
+ if (!raw) return fail("history", "the storage proof does not reach the contract's storage root");
254
+ let word: Uint8Array | null;
255
+ try {
256
+ word = storageWord(rlpDecode(raw));
257
+ } catch {
258
+ word = null;
259
+ }
260
+ if (!word || !bytesEqual(word, bHash)) return fail("history", `P's state does not hold block ${B}'s hash at that slot`);
261
+ pass("history", `block ${B}'s hash is in block ${P}'s state (${d} blocks back)`);
262
+ }
263
+
264
+ // 3. The Ethereum transaction carries the output root, and is in block H.
265
+ const e = s.ethereum;
266
+ let header;
267
+ try {
268
+ header = decodeHeader(hexToBytes(e.header));
269
+ } catch (err) {
270
+ return fail("ethereum", `header: ${(err as Error).message}`);
271
+ }
272
+ if (header.hash !== e.blockHash.toLowerCase()) return fail("ethereum", "the header does not hash to blockHash");
273
+ if (header.number !== e.blockNumber) return fail("ethereum", `the header is block ${header.number}, the settlement says ${e.blockNumber}`);
274
+ if (header.timestamp !== e.blockTimestamp) return fail("ethereum", `the header's timestamp is ${header.timestamp}, the settlement says ${e.blockTimestamp}`);
275
+ let rawTx: Uint8Array;
276
+ try {
277
+ rawTx = hexToBytes(e.rawTx);
278
+ } catch {
279
+ return fail("ethereum", "rawTx is not hex");
280
+ }
281
+ if (bytesToHex(keccak256(rawTx)) !== e.txHash.toLowerCase()) return fail("ethereum", "the raw transaction does not hash to txHash");
282
+ const txChain = transactionChainId(rawTx);
283
+ if (txChain === null) return fail("ethereum", "the transaction names no chain (a legacy transaction without EIP-155)");
284
+ if (txChain !== BigInt(l1Chain)) return fail("ethereum", `the transaction is signed for chain ${txChain}, not Ethereum ${l1Chain}`);
285
+ let inBlock: Uint8Array | null;
286
+ try {
287
+ inBlock = mptVerify(hexToBytes(header.transactionsRoot), txTrieKey(e.txIndex), e.txInclusionProof.map(hexToBytes));
288
+ } catch {
289
+ inBlock = null;
290
+ }
291
+ if (!inBlock || !bytesEqual(inBlock, rawTx)) return fail("ethereum", "the transaction is not in this block");
292
+ if (indexOfBytes(rawTx, outputRoot) < 0) return fail("ethereum", "the transaction's bytes do not contain the output root");
293
+ pass("ethereum", `transaction ${e.txIndex} of Ethereum block ${header.number} carries the output root`);
294
+
295
+ return {
296
+ ok: true,
297
+ checks,
298
+ existedBy: { chainId: e.chainId, blockNumber: header.number, blockHash: header.hash, blockTimestamp: header.timestamp },
299
+ outputRootHex: bytesToHex(outputRoot),
300
+ };
301
+ }
package/src/stream.ts ADDED
@@ -0,0 +1,291 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * Streaming checks of a file against a tree leaf (2026-10-03): constant
5
+ * memory, one pass over the bytes, any size. The tree/1 format needs nothing
6
+ * for this; it is how a verifier judges a 40 GB file on a laptop or in a
7
+ * browser tab, where reading it whole is impossible. The in-memory path
8
+ * (verifyTreeMember with `bytes`) and this one give the same category for the
9
+ * same bytes; a test holds them equal over every placement.
10
+ *
11
+ * Three hypotheses run in the same pass, each with its own hasher:
12
+ * - the bytes are the file as handed in, the ORIGIN of a placed leaf:
13
+ * SHA-256(prefix || bytes || suffix) for the leaf's placement, the frame
14
+ * built exactly as a producer builds it (the origin a container's
15
+ * manifest names is the leaf's);
16
+ * - the bytes are the COMMITTED bytes of a placed leaf: the stream must be
17
+ * exactly prefix || original || suffix for that placement. The original's
18
+ * length comes from the layout (the ustar header for a container, the
19
+ * last 48 bytes for the trailer), the manifest is parsed where it lies
20
+ * and the frame rebuilt from it, and the original inside is hashed as it
21
+ * passes;
22
+ * - the plain SHA-256 of every byte, which decides which hypothesis applies.
23
+ * A fourth pass-along asks whether the bytes carry this commitment under
24
+ * ANY placement (the in-memory check tries every placement's locate), for
25
+ * the "carries the commitment but is not this leaf" verdict: the last 48
26
+ * bytes as a trailer, or the container layout the first block announces,
27
+ * whose original inside is hashed by a second small machine when it is not
28
+ * the placement already being checked.
29
+ */
30
+
31
+ import { sha256 } from "@noble/hashes/sha256";
32
+ import { bytesEqual, getPlacement, parseFusePayload, CONTAINER_MANIFEST_PATH, CONTAINER_ORIGINAL_PATH, TRAILER_LENGTH, TRAILER_MAGIC, type Placement } from "./fuse.js";
33
+
34
+ /** Bytes that can be read as chunks, more than once. A File, a Blob, or a path opened each time. */
35
+ export interface ByteSource {
36
+ size: number;
37
+ stream(): AsyncIterable<Uint8Array>;
38
+ }
39
+
40
+ export function bytesSource(bytes: Uint8Array): ByteSource {
41
+ return {
42
+ size: bytes.length,
43
+ async *stream() {
44
+ yield bytes;
45
+ },
46
+ };
47
+ }
48
+
49
+ /** A Blob or File (browser or Node) as a source. */
50
+ export function blobSource(blob: { size: number; stream(): ReadableStream<Uint8Array> }): ByteSource {
51
+ return {
52
+ size: blob.size,
53
+ async *stream() {
54
+ const reader = blob.stream().getReader();
55
+ try {
56
+ for (;;) {
57
+ const { done, value } = await reader.read();
58
+ if (done) return;
59
+ if (value !== undefined && value.length > 0) yield value;
60
+ }
61
+ } finally {
62
+ reader.releaseLock();
63
+ }
64
+ },
65
+ };
66
+ }
67
+
68
+ export type StreamPlacement = "trailer/1" | "container/1" | "container/2";
69
+
70
+ export interface StreamLeafCheck {
71
+ /** Bytes streamed; the source's size must agree. */
72
+ size: number;
73
+ /** SHA-256 of every byte. */
74
+ digest: Uint8Array;
75
+ /** The first 64 bytes (or fewer): what a placement choice reads. */
76
+ head: Uint8Array;
77
+ /** The origin hypothesis: SHA-256 of the placement's frame around these bytes. Null when no placement was asked, or container/1 was asked without an origin (its prefix carries it). */
78
+ fusedFromOrigin: Uint8Array | null;
79
+ /** The committed-bytes hypothesis for the placement asked: the layout held and the original inside hashes to embeddedOrigin, or why not. Null when no placement was asked. */
80
+ direct: { ok: true; embeddedOrigin: Uint8Array; originalSize: number } | { ok: false; reason: string } | null;
81
+ /** True when the bytes carry this commitment under some placement: a trailer at their end, or a container whose manifest names it and whose original inside hashes to the origin it names. */
82
+ carriesCommitment: boolean;
83
+ }
84
+
85
+ const HEAD = 64;
86
+ const BLOCK = 512;
87
+ const MANIFEST_BYTES = 250;
88
+ const padTo = (n: number) => (BLOCK - (n % BLOCK)) % BLOCK;
89
+
90
+ /** The original's length from a ustar header's size field: 11 octal digits at offset 124. */
91
+ function ustarSize(header: Uint8Array): number | null {
92
+ if (header.length < BLOCK) return null;
93
+ let n = 0;
94
+ for (let i = 124; i < 135; i++) {
95
+ const c = header[i]!;
96
+ if (c < 0x30 || c > 0x37) return null;
97
+ n = n * 8 + (c - 0x30);
98
+ }
99
+ return header[135] === 0 ? n : null;
100
+ }
101
+
102
+ /** Where the manifest and the original's header sit, and how long the prefix is, for each container layout. */
103
+ const LAYOUT = {
104
+ "container/1": { prefixLength: BLOCK + MANIFEST_BYTES + padTo(MANIFEST_BYTES) + BLOCK, manifestAt: BLOCK, originalHeaderAt: BLOCK + MANIFEST_BYTES + padTo(MANIFEST_BYTES) },
105
+ "container/2": { prefixLength: BLOCK, manifestAt: null, originalHeaderAt: 0 },
106
+ } as const;
107
+
108
+ function concat(a: Uint8Array, b: Uint8Array): Uint8Array<ArrayBuffer> {
109
+ const out = new Uint8Array(a.length + b.length);
110
+ out.set(a, 0);
111
+ out.set(b, a.length);
112
+ return out;
113
+ }
114
+
115
+ /** SHA-256 of a source, streamed. */
116
+ export async function streamDigest(source: ByteSource): Promise<Uint8Array> {
117
+ const h = sha256.create();
118
+ for await (const chunk of source.stream()) h.update(chunk);
119
+ return h.digest();
120
+ }
121
+
122
+ /**
123
+ * One pass over a source for the hypotheses above. `origin` is the leaf's
124
+ * origin when a leaf is in hand (the origin a producer wrote into a
125
+ * container's manifest); null when only the bytes' own digest will do.
126
+ */
127
+ export async function streamLeafCheck(source: ByteSource, opts: { placement: StreamPlacement | null; commitment: Uint8Array; origin: Uint8Array | null }): Promise<StreamLeafCheck> {
128
+ const { placement, commitment } = opts;
129
+ if (commitment.length !== 32) throw new TypeError("commitment must be 32 bytes");
130
+ const size = source.size;
131
+ if (!Number.isSafeInteger(size) || size < 0) throw new TypeError("the source's size must be a non-negative integer");
132
+ const p: Placement | null = placement === null ? null : getPlacement(placement) ?? null;
133
+ if (placement !== null && (p === null || p.frame === undefined)) throw new TypeError(`${placement} is not a streamable placement`);
134
+
135
+ const whole = sha256.create();
136
+ let head: Uint8Array = new Uint8Array(0);
137
+
138
+ // The origin hypothesis: the frame around a file of exactly `size` bytes.
139
+ let fused: ReturnType<typeof sha256.create> | null = null;
140
+ let fusedSuffix: Uint8Array | null = null;
141
+ if (p !== null) {
142
+ const originForFrame = opts.origin ?? (placement === "container/1" ? null : new Uint8Array(32));
143
+ if (originForFrame !== null) {
144
+ const frame = p.frame!({ originalSize: size, originDigest: originForFrame, commitment });
145
+ fused = sha256.create();
146
+ fused.update(frame.prefix);
147
+ fusedSuffix = frame.suffix;
148
+ }
149
+ }
150
+
151
+ // The committed-bytes hypothesis: prefix || original || suffix, read in
152
+ // place. One machine for the placement asked; a second for the layout the
153
+ // first block announces, when that differs, so "carries the commitment"
154
+ // is judged the way the in-memory locate judges it.
155
+ class Machine {
156
+ readonly p: Placement;
157
+ readonly prefixLength: number;
158
+ originalSize: number | null = null;
159
+ prefix: Uint8Array = new Uint8Array(0);
160
+ suffix: Uint8Array = new Uint8Array(0);
161
+ readonly embedded = sha256.create();
162
+ failed: string | null = null;
163
+ constructor(readonly id: StreamPlacement) {
164
+ this.p = getPlacement(id)!;
165
+ this.prefixLength = id === "trailer/1" ? 0 : LAYOUT[id].prefixLength;
166
+ if (id === "trailer/1") {
167
+ if (size < TRAILER_LENGTH) this.failed = "shorter than a trailer";
168
+ else this.originalSize = size - TRAILER_LENGTH;
169
+ } else if (size < this.prefixLength) {
170
+ this.failed = "shorter than the container's headers";
171
+ }
172
+ }
173
+ /** The prefix is in hand: the original's length from its header, and the size must fit the layout. */
174
+ private settle(): void {
175
+ const headerAt = LAYOUT[this.id as "container/1" | "container/2"].originalHeaderAt;
176
+ const n = ustarSize(this.prefix.subarray(headerAt, headerAt + BLOCK));
177
+ if (n === null) { this.failed = "the original's ustar header does not carry a size"; return; }
178
+ const frame = this.p.frame!({ originalSize: n, originDigest: new Uint8Array(32), commitment });
179
+ if (size !== frame.prefix.length + n + frame.suffix.length) { this.failed = "the file's length does not fit the container layout its header states"; return; }
180
+ this.originalSize = n;
181
+ }
182
+ feed(chunk: Uint8Array, at: number): void {
183
+ if (this.failed !== null) return;
184
+ let off = 0;
185
+ if (at < this.prefixLength) {
186
+ const take = Math.min(chunk.length, this.prefixLength - at);
187
+ this.prefix = concat(this.prefix, chunk.subarray(0, take));
188
+ off = take;
189
+ if (this.prefix.length === this.prefixLength && this.originalSize === null) this.settle();
190
+ }
191
+ if (this.failed === null && this.originalSize !== null && off < chunk.length) {
192
+ const originalEnd = this.prefixLength + this.originalSize;
193
+ const here = at + off;
194
+ if (here < originalEnd) {
195
+ const take = Math.min(chunk.length - off, originalEnd - here);
196
+ this.embedded.update(chunk.subarray(off, off + take));
197
+ off += take;
198
+ }
199
+ if (off < chunk.length) this.suffix = concat(this.suffix, chunk.subarray(off));
200
+ }
201
+ }
202
+ finish(): StreamLeafCheck["direct"] {
203
+ if (this.failed !== null) return { ok: false, reason: this.failed };
204
+ if (this.originalSize === null) return { ok: false, reason: "the stream ended inside the container's headers" };
205
+ const embeddedOrigin = this.embedded.digest();
206
+ let manifestOrigin: Uint8Array | null = null;
207
+ let frameOk = false;
208
+ if (this.id === "trailer/1") {
209
+ frameOk = bytesEqual(this.suffix, this.p.frame!({ originalSize: this.originalSize, originDigest: embeddedOrigin, commitment }).suffix);
210
+ manifestOrigin = embeddedOrigin;
211
+ } else {
212
+ const manifestBytes = this.id === "container/1"
213
+ ? this.prefix.subarray(LAYOUT["container/1"].manifestAt, LAYOUT["container/1"].manifestAt + MANIFEST_BYTES)
214
+ : this.suffix.subarray(padTo(this.originalSize) + BLOCK, padTo(this.originalSize) + BLOCK + MANIFEST_BYTES);
215
+ const manifest = parseFusePayload(manifestBytes);
216
+ if (manifest !== null && manifest.originDigest !== undefined && bytesEqual(manifest.commitment, commitment)) {
217
+ manifestOrigin = manifest.originDigest;
218
+ const expected = this.p.frame!({ originalSize: this.originalSize, originDigest: manifestOrigin, commitment });
219
+ frameOk = bytesEqual(this.prefix, expected.prefix) && bytesEqual(this.suffix, expected.suffix);
220
+ }
221
+ }
222
+ if (!frameOk) return { ok: false, reason: `the bytes are not a ${this.id} carrying this position's commitment` };
223
+ if (manifestOrigin === null || !bytesEqual(manifestOrigin, embeddedOrigin)) return { ok: false, reason: `the original inside the ${this.id} does not hash to the origin its manifest names` };
224
+ return { ok: true, embeddedOrigin, originalSize: this.originalSize };
225
+ }
226
+ }
227
+ const asked: Machine | null = placement === null ? null : new Machine(placement);
228
+ let guessed: Machine | null = null;
229
+ // Bytes seen before the first block is whole, replayed into a machine made late.
230
+ let early: Uint8Array = new Uint8Array(0);
231
+ let decided = false;
232
+ const trailerMagic = new TextEncoder().encode(TRAILER_MAGIC);
233
+ let tail: Uint8Array = new Uint8Array(0);
234
+
235
+ let pos = 0;
236
+ for await (const chunk of source.stream()) {
237
+ if (chunk.length === 0) continue;
238
+ if (pos + chunk.length > size) throw new RangeError("the source yielded more bytes than its size");
239
+ whole.update(chunk);
240
+ if (fused !== null) fused.update(chunk);
241
+ if (head.length < HEAD) head = concat(head, chunk.subarray(0, HEAD - head.length));
242
+ tail = concat(tail, chunk).subarray(-TRAILER_LENGTH);
243
+ if (asked !== null) asked.feed(chunk, pos);
244
+ if (!decided) {
245
+ early = concat(early, chunk);
246
+ if (early.length >= BLOCK || pos + chunk.length === size) {
247
+ decided = true;
248
+ const layout = containerLayoutOf(early.subarray(0, BLOCK));
249
+ if (layout !== null && layout !== placement) {
250
+ guessed = new Machine(layout);
251
+ guessed.feed(early, 0);
252
+ }
253
+ early = new Uint8Array(0);
254
+ }
255
+ } else if (guessed !== null) {
256
+ guessed.feed(chunk, pos);
257
+ }
258
+ pos += chunk.length;
259
+ }
260
+ if (pos !== size) throw new RangeError(`the source yielded ${pos} bytes; its size says ${size}`);
261
+
262
+ const digest = whole.digest();
263
+ let fusedFromOrigin: Uint8Array | null = null;
264
+ if (fused !== null && fusedSuffix !== null) {
265
+ fused.update(fusedSuffix);
266
+ fusedFromOrigin = fused.digest();
267
+ }
268
+ const directResult = asked === null ? null : asked.finish();
269
+
270
+ // Carries this commitment under some placement: a trailer at the end (as the
271
+ // in-memory locate, no origin check), or the announced container layout.
272
+ const trailerCarries = size >= TRAILER_LENGTH
273
+ && bytesEqual(tail.subarray(0, 8), trailerMagic)
274
+ && tail.subarray(8, 16).every((b) => b === 0)
275
+ && bytesEqual(tail.subarray(16, 48), commitment);
276
+ const containerCarries = (placement !== "trailer/1" && directResult?.ok === true) || (guessed !== null && guessed.finish()?.ok === true);
277
+ const carries = trailerCarries || containerCarries;
278
+
279
+ return { size, digest, head, fusedFromOrigin, direct: directResult, carriesCommitment: carries };
280
+ }
281
+
282
+ /** The container layout a first block announces, by its ustar magic and entry name; null for anything else (a trailer file, or no placement). */
283
+ function containerLayoutOf(block: Uint8Array): "container/1" | "container/2" | null {
284
+ if (block.length < BLOCK) return null;
285
+ if (new TextDecoder().decode(block.subarray(257, 263)) !== "ustar\0") return null;
286
+ const end = block.subarray(0, 100).indexOf(0);
287
+ const name = new TextDecoder().decode(block.subarray(0, end < 0 ? 100 : end));
288
+ if (name === CONTAINER_MANIFEST_PATH) return "container/1";
289
+ if (name === CONTAINER_ORIGINAL_PATH) return "container/2";
290
+ return null;
291
+ }