@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/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
+ }