@mikeargento/bitgraph-verify 1.17.0 → 1.19.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/src/carrier.ts CHANGED
@@ -52,6 +52,26 @@
52
52
  * Everything else (ceiling in time, settlement, pins, attestation witness) is
53
53
  * /2's. Ethereum-floor proofs keep travelling as /1 and /2.
54
54
  *
55
+ * bitgraph-carrier/4 (2026-10-11) is the BitGraphed file of ONE MEMBER of a
56
+ * tree/1 BitGraph. In a tree the signed digest is the SHA-256 of the tree's
57
+ * 84-byte root document, not of any file, so the committed bytes before the
58
+ * block are a LEAF's committed bytes (the bytes whose SHA-256 is the leaf's
59
+ * artifact digest: the file itself for a leaf kept as is, the file with the
60
+ * commitment placed in it otherwise), and the block carries what reaches the
61
+ * signed digest from them, exactly the tree part a one-file export/1 carries:
62
+ * `tree: { rootDocument, member: { index, count, leaf, path } }`. A reader
63
+ * hashes the bytes before the block, requires that digest to be the leaf's
64
+ * artifact (and, for a placed leaf, the commitment to be inside the bytes),
65
+ * walks the path to the root, and requires the root document to hold that
66
+ * root and the position's commitment and to hash to the signed digest. The
67
+ * floor is the one the proof signs, in its own shape: an Ethereum anchor and
68
+ * header (as /2, with the ceiling in position unfetched or present) or a Base
69
+ * header (as /3, with no ceiling in position). Ceiling in time, settlement,
70
+ * pins and attestation witness are /2's. A new version and not a field added
71
+ * to /2 or /3, on purpose: a reader that knows only /1 to /3 would hash the
72
+ * bytes against the root document's digest and call a good file FALSE, so it
73
+ * must see a version it does not know and say UNDETERMINED instead.
74
+ *
55
75
  * ⚠️ TWO BYTE-IDENTICAL COPIES OF THIS FILE EXIST, on purpose:
56
76
  * packages/verify/src/carrier.ts (canonical, published with the package)
57
77
  * website/src/lib/carrier.ts (the site cannot import unpublished code)
@@ -75,7 +95,8 @@ export const MAX_CARRIER_PAYLOAD = 8 * 1024 * 1024;
75
95
  export const CARRIER_VERSION = "bitgraph-carrier/1";
76
96
  export const CARRIER_VERSION_2 = "bitgraph-carrier/2";
77
97
  export const CARRIER_VERSION_3 = "bitgraph-carrier/3";
78
- export type CarrierVersion = typeof CARRIER_VERSION | typeof CARRIER_VERSION_2 | typeof CARRIER_VERSION_3;
98
+ export const CARRIER_VERSION_4 = "bitgraph-carrier/4";
99
+ export type CarrierVersion = typeof CARRIER_VERSION | typeof CARRIER_VERSION_2 | typeof CARRIER_VERSION_3 | typeof CARRIER_VERSION_4;
79
100
  /** The sidecar and pointer formats a v2 block carries; their shapes are checked by their own modules. */
80
101
  export const CEILING_SIDECAR_VERSION = "bitgraph-ceiling/1";
81
102
  export const SETTLEMENT_POINTER_VERSION = "bitgraph-settlement/1";
@@ -136,6 +157,19 @@ export type CarrierSettlement =
136
157
  | { status: "unfetched" }
137
158
  | { status: "present"; pointer: Record<string, unknown> };
138
159
 
160
+ /**
161
+ * v4: the tree member the committed bytes are, in export/1's words: the
162
+ * tree's root document and the member's evidence, both lowercase hex. Bound
163
+ * to nothing until a verifier walks it: the leaf must be the bytes, the path
164
+ * must reach the root, the root document must hash to the signed digest.
165
+ */
166
+ export interface CarrierTree {
167
+ /** The 84-byte root document (168 hex characters); its SHA-256 is the proof's artifact digest. */
168
+ rootDocument: string;
169
+ /** The member's evidence, exactly export/1's `tree.member`: the 65-byte leaf, its index, the tree's size and the sibling path from the leaf up. */
170
+ member: { index: number; count: number; leaf: string; path: string[] };
171
+ }
172
+
139
173
  /** v2: what the file was made under. Declared only; a verifier compares with its own pins. */
140
174
  export interface CarrierPins {
141
175
  pcr0?: string;
@@ -148,17 +182,19 @@ export interface CarrierPayload {
148
182
  carrier: CarrierVersion;
149
183
  /** The bitgraph/1 proof exactly as the commit returned it. */
150
184
  proof: CarrierProof;
151
- /** v1 and v2: the Ethereum anchor proof and its header. v3: the Base header. */
185
+ /** v4, required there: the tree member the committed bytes are. */
186
+ tree?: CarrierTree;
187
+ /** v1 and v2: the Ethereum anchor proof and its header. v3: the Base header. v4: whichever the proof signs. */
152
188
  floor: CarrierFloor | CarrierBaseFloor;
153
- /** The ceiling in position: the next anchor in the chain (v1, v2), or on v3 the statement that there is none. */
189
+ /** The ceiling in position: the next anchor in the chain (v1, v2, v4 on an Ethereum floor), or on a Base floor the statement that there is none. */
154
190
  ceiling: CarrierCeiling;
155
- /** v2 and v3. Required there, so absence reads as a corrupt block, never as "no ceiling". */
191
+ /** v2, v3 and v4. Required there, so absence reads as a corrupt block, never as "no ceiling". */
156
192
  ceilingInTime?: CarrierCeilingInTime;
157
- /** v2 and v3, optional. */
193
+ /** v2, v3 and v4, optional. */
158
194
  settlement?: CarrierSettlement;
159
- /** v2 and v3, optional. */
195
+ /** v2, v3 and v4, optional. */
160
196
  pins?: CarrierPins;
161
- /** v2 and v3, optional: the proof's attestation as aws-nitro-witness/1 evidence. */
197
+ /** v2, v3 and v4, optional: the proof's attestation as aws-nitro-witness/1 evidence. */
162
198
  attestation?: Record<string, unknown>;
163
199
  }
164
200
 
@@ -252,24 +288,46 @@ export function buildCarrier(inner: Uint8Array, payload: CarrierPayload): Uint8A
252
288
  return out;
253
289
  }
254
290
 
291
+ /** v4: the tree part's shape (export/1's one-file tree), lowercase hex throughout. Whether it holds is verifyCarrier's question. */
292
+ function treeShapeError(t: unknown): string | null {
293
+ const o = record(t);
294
+ if (o === null) return `a ${CARRIER_VERSION_4} block carries its tree member: "tree" is missing`;
295
+ if (Object.keys(o).sort().join(",") !== "member,rootDocument") return "tree must hold exactly rootDocument and member";
296
+ if (typeof o["rootDocument"] !== "string" || !/^[0-9a-f]{168}$/.test(o["rootDocument"])) return "tree.rootDocument is not 84 bytes of lowercase hex";
297
+ const m = record(o["member"]);
298
+ if (m === null || Object.keys(m).sort().join(",") !== "count,index,leaf,path") return "tree.member must hold exactly index, count, leaf and path";
299
+ const { index, count } = m;
300
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 1) return "tree.member.count is not a whole number of leaves";
301
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= count) return "tree.member.index is not a leaf of the tree";
302
+ if (typeof m["leaf"] !== "string" || !/^[0-9a-f]{130}$/.test(m["leaf"])) return "tree.member.leaf is not 65 bytes of lowercase hex";
303
+ if (!Array.isArray(m["path"]) || !(m["path"] as unknown[]).every((n) => typeof n === "string" && /^[0-9a-f]{64}$/.test(n))) return "tree.member.path is not a list of 32-byte lowercase-hex nodes";
304
+ return null;
305
+ }
306
+
255
307
  /** Structural payload check: is this object a readable bitgraph-carrier/1 payload? */
256
308
  function payloadShapeError(p: unknown): string | null {
257
309
  const o = record(p);
258
310
  if (o === null) return "payload is not an object";
311
+ const v4 = o["carrier"] === CARRIER_VERSION_4;
259
312
  const v3 = o["carrier"] === CARRIER_VERSION_3;
260
- const v2 = o["carrier"] === CARRIER_VERSION_2 || v3;
313
+ const v2 = o["carrier"] === CARRIER_VERSION_2 || v3 || v4;
261
314
  if (o["carrier"] !== CARRIER_VERSION && !v2) return `unknown carrier version ${JSON.stringify(o["carrier"])}`;
262
315
  if (record(o["proof"]) === null) return "payload carries no proof object";
316
+ if (v4) {
317
+ const te = treeShapeError(o["tree"]);
318
+ if (te !== null) return te;
319
+ }
263
320
  const floor = record(o["floor"]);
264
321
  if (floor === null || floor["status"] !== "present") return "floor must be present: a floorless carrier is not a not-before";
265
322
  const ceil = record(o["ceiling"]);
266
323
  if (ceil === null) return "ceiling is missing: absence must be a stated fact, not a missing key";
267
- if (v3) {
268
- // v3: the floor is a Base header, and no ceiling in position exists.
324
+ // v3, and v4 over a Base floor: the floor is a Base header, and no ceiling in position exists.
325
+ const baseFloor = v3 || (v4 && floor["basis"] === "base-header");
326
+ if (baseFloor) {
269
327
  if (floor["basis"] !== "base-header") return `a ${CARRIER_VERSION_3} floor must be a Base header (basis "base-header"), got ${JSON.stringify(floor["basis"])}`;
270
328
  if (typeof floor["header"] !== "string" || baseHeaderFields(floor["header"]) === null) return "floor carries no readable Base block header";
271
- if (floor["anchor"] !== undefined || floor["witness"] !== undefined) return `a ${CARRIER_VERSION_3} floor carries no anchor proof`;
272
- if (ceil["status"] !== "none" || ceil["basis"] !== "hash-chain") return `a ${CARRIER_VERSION_3} block states no ceiling in position ({ status: "none", basis: "hash-chain" })`;
329
+ if (floor["anchor"] !== undefined || floor["witness"] !== undefined) return `a ${String(o["carrier"])} ${v4 ? "Base " : ""}floor carries no anchor proof`;
330
+ if (ceil["status"] !== "none" || ceil["basis"] !== "hash-chain") return `a ${String(o["carrier"])} block ${v4 ? "over a Base floor " : ""}states no ceiling in position ({ status: "none", basis: "hash-chain" })`;
273
331
  } else {
274
332
  if (floor["basis"] !== undefined) return `unknown floor basis ${JSON.stringify(floor["basis"])} on ${String(o["carrier"])}`;
275
333
  if (record(floor["anchor"]) === null) return "floor carries no anchor proof";
@@ -278,7 +336,7 @@ function payloadShapeError(p: unknown): string | null {
278
336
  return "floor carries no readable block-header witness";
279
337
  }
280
338
  }
281
- if (!v3 && ceil["status"] !== "unfetched") {
339
+ if (!baseFloor && ceil["status"] !== "unfetched") {
282
340
  if (ceil["status"] !== "present") return `ceiling status must be "unfetched" or "present", got ${JSON.stringify(ceil["status"])}`;
283
341
  if (ceil["basis"] !== "counter-order") return `unknown ceiling basis ${JSON.stringify(ceil["basis"])}`;
284
342
  if (record(ceil["anchor"]) === null) return "ceiling carries no anchor proof";
@@ -288,7 +346,7 @@ function payloadShapeError(p: unknown): string | null {
288
346
  }
289
347
  }
290
348
  if (!v2) return null;
291
- // v2 and v3: the ceiling in time is stated either way; settlement, pins and the attestation witness are optional.
349
+ // v2, v3 and v4: the ceiling in time is stated either way; settlement, pins and the attestation witness are optional.
292
350
  const ct = record(o["ceilingInTime"]);
293
351
  if (ct === null) return "ceilingInTime is missing: a v2 block states the ceiling in time or that it was not fetched";
294
352
  if (ct["status"] === "present") {
@@ -311,9 +369,9 @@ function payloadShapeError(p: unknown): string | null {
311
369
  return null;
312
370
  }
313
371
 
314
- /** 1, 2 or 3, from a parsed payload. */
315
- export function carrierVersionOf(payload: CarrierPayload): 1 | 2 | 3 {
316
- return payload.carrier === CARRIER_VERSION_3 ? 3 : payload.carrier === CARRIER_VERSION_2 ? 2 : 1;
372
+ /** 1, 2, 3 or 4, from a parsed payload. */
373
+ export function carrierVersionOf(payload: CarrierPayload): 1 | 2 | 3 | 4 {
374
+ return payload.carrier === CARRIER_VERSION_4 ? 4 : payload.carrier === CARRIER_VERSION_3 ? 3 : payload.carrier === CARRIER_VERSION_2 ? 2 : 1;
317
375
  }
318
376
 
319
377
  export function parseCarrier(bytes: Uint8Array): CarrierParse {
@@ -350,7 +408,7 @@ export function completeCarrier(
350
408
  const p = parseCarrier(bytes);
351
409
  if (p.kind !== "carrier") return { changed: false, bytes, error: p.kind === "none" ? "not a carrier" : `corrupt block: ${p.reason}` };
352
410
  const cur = p.payload.ceiling;
353
- if (cur.status === "none") return { changed: false, bytes, error: `a ${CARRIER_VERSION_3} block has no ceiling in position: its order is the chain of proof hashes` };
411
+ if (cur.status === "none") return { changed: false, bytes, error: `${p.payload.carrier === CARRIER_VERSION_3 ? `a ${CARRIER_VERSION_3} block` : "a block over a Base floor"} has no ceiling in position: its order is the chain of proof hashes` };
354
412
  if (cur.status === "present") {
355
413
  if (ceiling === null) return { changed: false, bytes };
356
414
  const a = record(record(cur.anchor)?.["commit"]);
@@ -695,8 +753,29 @@ export function carrierBounds(payload: CarrierPayload): CarrierBounds {
695
753
  return { notBefore, notAfter, existedBy, settledBy };
696
754
  }
697
755
 
698
- /** SHA-256 of the committed bytes, compared to the carried proof's artifact digest. */
756
+ /**
757
+ * v4: the leaf's artifact digest, the SHA-256 the committed bytes must have,
758
+ * read from the carried leaf (bytes 1 to 33 of its 65). Null when the block
759
+ * carries no readable leaf. That the leaf is in the signed tree is
760
+ * verifyCarrier's check, not this one.
761
+ */
762
+ export function memberArtifactDigest(payload: CarrierPayload): Uint8Array | null {
763
+ const leaf = payload.tree?.member?.leaf;
764
+ const raw = typeof leaf === "string" && /^[0-9a-f]{130}$/.test(leaf) ? hexToBytes(leaf) : null;
765
+ return raw === null ? null : raw.slice(1, 33);
766
+ }
767
+
768
+ /**
769
+ * SHA-256 of the committed bytes, compared to the carried proof's artifact
770
+ * digest; on v4, to the carried leaf's artifact digest (a tree's signed digest
771
+ * names its root document, which no file is). A digest match only: the
772
+ * verifier does the rest.
773
+ */
699
774
  export function innerDigestMatches(inner: Uint8Array, payload: CarrierPayload): boolean {
775
+ if (payload.carrier === CARRIER_VERSION_4) {
776
+ const want = memberArtifactDigest(payload);
777
+ return want !== null && sameDigest(bytesToB64(sha256(inner)), bytesToB64(want));
778
+ }
700
779
  const artifact = record(payload.proof["artifact"]);
701
780
  return sameDigest(bytesToB64(sha256(inner)), artifact?.["digestB64"] as string);
702
781
  }
@@ -132,25 +132,41 @@ export class MerkleTree {
132
132
  readonly size: number;
133
133
  readonly root: Uint8Array;
134
134
  private readonly leafHashes: readonly Uint8Array[];
135
- /** Subtree root by "lo:hi". */
136
- private readonly memo = new Map<string, Uint8Array>();
135
+ /** Subtree root by lo * (size + 1) + hi: a number key, not a string (a million-leaf tree builds ~40% faster, 2026-10-12). */
136
+ private readonly memo = new Map<number, Uint8Array>();
137
+ /** One reusable 0x01 || left || right buffer: SHA-256 reads it before it is written again. */
138
+ private readonly nodeBuf = new Uint8Array(65);
137
139
 
138
- constructor(leafHashes: readonly Uint8Array[]) {
140
+ /**
141
+ * `known`: subtree roots computed elsewhere (another thread), each for the leaf range [lo, hi) of this tree's own
142
+ * split; they stand in for computing those subtrees here. A wrong one gives a wrong root, which the commit and every
143
+ * verifier would catch, so callers pass only roots they computed over these same leaf hashes.
144
+ */
145
+ constructor(leafHashes: readonly Uint8Array[], known: ReadonlyArray<{ lo: number; hi: number; hash: Uint8Array }> = []) {
139
146
  if (leafHashes.length === 0) throw new TypeError("a Merkle tree needs at least one leaf");
140
147
  for (const h of leafHashes) if (h.length !== 32) throw new TypeError("a leaf hash is 32 bytes");
141
148
  this.leafHashes = leafHashes;
142
149
  this.size = leafHashes.length;
150
+ this.nodeBuf[0] = 0x01;
151
+ for (const k of known) {
152
+ if (k.hash.length !== 32 || !(k.lo >= 0 && k.hi <= this.size && k.hi - k.lo >= 2)) throw new TypeError("a known subtree root is 32 bytes over a range of at least two leaves inside the tree");
153
+ this.memo.set(k.lo * (this.size + 1) + k.hi, k.hash);
154
+ }
143
155
  this.root = this.subtree(0, this.size);
144
156
  }
145
157
 
146
158
  private subtree(lo: number, hi: number): Uint8Array {
147
159
  const n = hi - lo;
148
160
  if (n === 1) return this.leafHashes[lo]!;
149
- const key = `${lo}:${hi}`;
161
+ const key = lo * (this.size + 1) + hi;
150
162
  const known = this.memo.get(key);
151
163
  if (known !== undefined) return known;
152
164
  const k = split(n);
153
- const h = merkleNodeHash(this.subtree(lo, lo + k), this.subtree(lo + k, hi));
165
+ const left = this.subtree(lo, lo + k);
166
+ const right = this.subtree(lo + k, hi);
167
+ this.nodeBuf.set(left, 1);
168
+ this.nodeBuf.set(right, 33);
169
+ const h = sha256(this.nodeBuf);
154
170
  this.memo.set(key, h);
155
171
  return h;
156
172
  }
package/src/fuse.ts CHANGED
@@ -437,7 +437,23 @@ function octal(n: number, width: number): Uint8Array {
437
437
  return utf8(s);
438
438
  }
439
439
 
440
+ /**
441
+ * A header depends only on the name and the size, and a batch of files has few distinct sizes, so each is built once
442
+ * and reused (2026-10-12: the header was a third of the time to fuse a million files). Callers only copy a header into
443
+ * a new archive or a hash, never write to it. Bounded, so a stream of many sizes cannot grow it without limit.
444
+ */
445
+ const headerCache = new Map<string, Uint8Array>();
440
446
  function ustarHeader(name: string, size: number): Uint8Array {
447
+ const key = `${size}:${name}`;
448
+ const cached = headerCache.get(key);
449
+ if (cached !== undefined) return cached;
450
+ const built = buildUstarHeader(name, size);
451
+ if (headerCache.size >= 4096) headerCache.clear();
452
+ headerCache.set(key, built);
453
+ return built;
454
+ }
455
+
456
+ function buildUstarHeader(name: string, size: number): Uint8Array {
441
457
  if (size > MAX_ENTRY) throw new RangeError("container entries are limited to 8 GiB");
442
458
  const h = new Uint8Array(BLOCK);
443
459
  const nameBytes = utf8(name);
@@ -649,12 +665,12 @@ const container2: Placement = {
649
665
  frame({ originalSize, originDigest, commitment }) {
650
666
  const manifest = buildFusePayload(commitment, originDigest);
651
667
  return {
652
- prefix: ustarHeader(CONTAINER_ORIGINAL_PATH, originalSize),
668
+ prefix: ustarHeader(CONTAINER_ORIGINAL_PATH, originalSize).slice(), // a copy: the cached header is never handed out to be written
653
669
  suffix: concat(new Uint8Array(padTo(originalSize)), ustarHeader(CONTAINER_MANIFEST_PATH, manifest.length), manifest, new Uint8Array(padTo(manifest.length)), new Uint8Array(BLOCK * 2)),
654
670
  };
655
671
  },
656
672
  scanPrefix(originalSize) {
657
- return ustarHeader(CONTAINER_ORIGINAL_PATH, originalSize);
673
+ return ustarHeader(CONTAINER_ORIGINAL_PATH, originalSize).slice(); // a copy, as in frame()
658
674
  },
659
675
  };
660
676
 
package/src/index.ts CHANGED
@@ -138,6 +138,12 @@ export type { CarrierBaseFloor } from "./carrier.js";
138
138
  export { assembleCarrierV3Payload } from "./carrier-assemble.js";
139
139
  export type { CarrierV3Parts } from "./carrier-assemble.js";
140
140
 
141
+ /* bitgraph-carrier/4 (2026-10-11): one member of a tree/1 BitGraph carries its own proof: the bytes are the leaf's, the block walks them to the signed root document. */
142
+ export { CARRIER_VERSION_4, memberArtifactDigest } from "./carrier.js";
143
+ export type { CarrierTree } from "./carrier.js";
144
+ export { assembleCarrierV4Payload } from "./carrier-assemble.js";
145
+ export type { CarrierV4Parts } from "./carrier-assemble.js";
146
+
141
147
  /* AWS Nitro attestation: decode, verify (chain to the AWS root, validity at the document's instant), and the openssl-checkable witness. */
142
148
  export {
143
149
  AWS_NITRO_ROOT_CA_PEM, awsNitroRootDer, awsNitroRootSha256, decodeNitroAttestation, verifyNitroAttestation,
package/src/tree.ts CHANGED
@@ -171,7 +171,21 @@ export function sortTreeLeaves(leaves: readonly TreeLeaf[]): TreeLeaf[] {
171
171
  if (leaves.length === 0) throw new TypeError("a tree lists at least one leaf");
172
172
  if (leaves.length > MAX_TREE_LEAVES) throw new TypeError(`a tree lists at most ${MAX_TREE_LEAVES} leaves`);
173
173
  for (const l of leaves) checkLeaf(l);
174
- const sorted = [...leaves].sort((a, b) => compareBytes(a.artifact, b.artifact));
174
+ // Bucket by the first two bytes, then sort each bucket on the rest: the same strictly ascending order as a
175
+ // byte-by-byte sort of the whole list, about twice as fast for a million leaves (2026-10-12).
176
+ const buckets = new Map<number, TreeLeaf[]>();
177
+ for (const l of leaves) {
178
+ const key = (l.artifact[0]! << 8) | l.artifact[1]!;
179
+ const b = buckets.get(key);
180
+ if (b === undefined) buckets.set(key, [l]);
181
+ else b.push(l);
182
+ }
183
+ const sorted: TreeLeaf[] = [];
184
+ for (const key of [...buckets.keys()].sort((a, b) => a - b)) {
185
+ const b = buckets.get(key)!;
186
+ if (b.length > 1) b.sort((x, y) => compareBytes(x.artifact, y.artifact));
187
+ for (const l of b) sorted.push(l);
188
+ }
175
189
  for (let i = 1; i < sorted.length; i++) {
176
190
  if (bytesEqual(sorted[i]!.artifact, sorted[i - 1]!.artifact)) throw new TypeError(`duplicate leaf artifact digest ${bytesToHex(sorted[i]!.artifact)}`);
177
191
  }
@@ -187,7 +201,14 @@ export interface BuiltTree {
187
201
 
188
202
  export function buildTree(leaves: readonly TreeLeaf[]): BuiltTree {
189
203
  const sorted = sortTreeLeaves(leaves);
190
- const leafHashes = sorted.map(treeLeafHash);
204
+ // treeLeafHash without the per-leaf allocations: one reusable 0x00 || leaf buffer (the leaves were checked by the sort).
205
+ const buf = new Uint8Array(1 + TREE_LEAF_BYTES);
206
+ const leafHashes = sorted.map((l) => {
207
+ buf[1] = l.placement;
208
+ buf.set(l.artifact, 2);
209
+ buf.set(l.origin, 2 + 32);
210
+ return sha256(buf);
211
+ });
191
212
  const tree = new MerkleTree(leafHashes);
192
213
  return { sorted, leafHashes, root: tree.root, tree };
193
214
  }