@mikeargento/bitgraph-verify 1.18.0 → 1.20.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.
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The sandwich: verifyStretch / verifyBetween check the SHAPE of a run of
3
+ * binds (two counts each, nonce count = previous payload count + 1, prevB64
4
+ * links). Signatures are verify()'s job, so these proofs are unsigned shapes.
5
+ * The real thing, minted by the enclave's own code, is checked end to end in
6
+ * server/commit-service/local-enclave/bind-v11.mts.
7
+ *
8
+ * cd packages/verify && npx tsc -p . && node --test dist/__tests__/stretch.test.js
9
+ */
10
+
11
+ import { test } from "node:test";
12
+ import { strict as assert } from "node:assert";
13
+ import { verifyStretch, verifyBetween } from "../stretch.js";
14
+ import { computeChainHash } from "../proof-hash.js";
15
+ import type { BitGraphProof } from "../types.js";
16
+
17
+ function run(startCount: number, n: number): BitGraphProof[] {
18
+ const out: BitGraphProof[] = [];
19
+ let count = startCount;
20
+ for (let i = 0; i < n; i++) {
21
+ const nonce = String(count);
22
+ const payload = String(count + 1);
23
+ count += 2;
24
+ const p = {
25
+ version: "bitgraph/1",
26
+ artifact: { hashAlg: "sha256", digestB64: Buffer.alloc(32, i).toString("base64") },
27
+ commit: {
28
+ nonceB64: Buffer.alloc(32, 100 + i).toString("base64"),
29
+ counter: payload,
30
+ slotCounter: nonce,
31
+ epochId: "epoch",
32
+ atomic: true,
33
+ ...(out.length > 0 ? { prevB64: computeChainHash(out[out.length - 1]!) } : {}),
34
+ },
35
+ signer: { publicKeyB64: "key", signatureB64: "sig" },
36
+ environment: { enforcement: "measured-tee", measurement: "m" },
37
+ slotAllocation: { version: "bitgraph/slot/1", nonceB64: Buffer.alloc(32, 100 + i).toString("base64"), counter: nonce, epochId: "epoch", publicKeyB64: "key", signatureB64: "s" },
38
+ } as unknown as BitGraphProof;
39
+ out.push(p);
40
+ }
41
+ return out;
42
+ }
43
+
44
+ test("A 2435-2436 → R → R → B 2441-2442 is one unbroken stretch", () => {
45
+ const s = run(2435, 4);
46
+ const r = verifyStretch(s);
47
+ assert.equal(r.ok, true, r.reasons.join("; "));
48
+ assert.equal(r.from, "2435");
49
+ assert.equal(r.to, "2442");
50
+ assert.equal(verifyBetween(s, s[1]!).ok, true);
51
+ assert.equal(verifyBetween(s, s[2]!).ok, true);
52
+ });
53
+
54
+ test("A and B themselves are not between A and B", () => {
55
+ const s = run(2435, 4);
56
+ assert.equal(verifyBetween(s, s[0]!).ok, false);
57
+ assert.equal(verifyBetween(s, s[3]!).ok, false);
58
+ });
59
+
60
+ test("a missing proof shows up as unaccounted counts", () => {
61
+ const s = run(2435, 4);
62
+ const r = verifyStretch([s[0]!, s[2]!, s[3]!]);
63
+ assert.equal(r.ok, false);
64
+ assert.ok(r.reasons.some((x) => /2437 to 2438 are unaccounted/.test(x)), r.reasons.join("; "));
65
+ });
66
+
67
+ test("a two-call proof (no commit.atomic) breaks the stretch", () => {
68
+ const s = run(2435, 3);
69
+ const mid = s[1]! as unknown as { commit: Record<string, unknown> };
70
+ delete mid.commit["atomic"];
71
+ const r = verifyStretch(s);
72
+ assert.equal(r.ok, false);
73
+ assert.ok(r.reasons.some((x) => /not a bind/.test(x)));
74
+ });
75
+
76
+ test("a payload count that is not nonce + 1 is refused", () => {
77
+ const s = run(2435, 2);
78
+ (s[1]! as unknown as { commit: { counter: string } }).commit.counter = "2439";
79
+ const r = verifyStretch(s);
80
+ assert.equal(r.ok, false);
81
+ assert.ok(r.reasons.some((x) => /not nonce count 2437 plus one/.test(x)), r.reasons.join("; "));
82
+ });
83
+
84
+ test("a broken prevB64 link is refused", () => {
85
+ const s = run(2435, 3);
86
+ (s[2]! as unknown as { commit: { prevB64: string } }).commit.prevB64 = "x";
87
+ const r = verifyStretch(s);
88
+ assert.equal(r.ok, false);
89
+ assert.ok(r.reasons.some((x) => /does not link/.test(x)));
90
+ });
91
+
92
+ test("another epoch or key is refused", () => {
93
+ const s = run(2435, 2);
94
+ (s[1]! as unknown as { commit: { epochId: string } }).commit.epochId = "other";
95
+ assert.equal(verifyStretch(s).ok, false);
96
+ });
@@ -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
@@ -39,6 +39,10 @@ export { computeProofHash, computeChainHash, buildSignedBody, computeSignedBodyH
39
39
 
40
40
  export { canonicalize, canonicalizeToString, constantTimeEqual } from "./canonical.js";
41
41
 
42
+ // The sandwich (enclave v11 binds): an unbroken stretch from A to B.
43
+ export { verifyStretch, verifyBetween } from "./stretch.js";
44
+ export type { StretchResult } from "./stretch.js";
45
+
42
46
  // BitGraph Fuse (profile bitgraph-fuse/1): construction, parsing, verification.
43
47
  export {
44
48
  FUSE_PROFILE,
@@ -36,6 +36,7 @@ export const PUBLISHED_ENCLAVE_MEASUREMENTS: readonly PublishedMeasurement[] = O
36
36
  { version: "v8", since: "2026-09-07", pcr0: "eccfc1c78006f4b74f929c992785575c908a0f60eca08ff638cd6c0842f993f182ebb002457b8ef3e732a6a10805c72b" },
37
37
  { version: "v9", since: "2026-09-30", pcr0: "934feb8bb6f4f7e2d2f85d902a7d5edd0981f706d9d2385638988ac096a05ea0583c3d00eef2a7947865ec66efc1fcf8" },
38
38
  { version: "v10", since: "2026-10-08", pcr0: "5a947cc66095adcceefa9e5ece5d1416dfe08c3470df1bcaa5b2bc5267b0480e6cdc172fe077cd06b0afb07614307973" },
39
+ { version: "v11", since: "2026-10-17", pcr0: "d9128d67c406a30f988f74ece8b5cced5c9a96491289037f50bddb5f10aac2bc9d1d315dd7bf65428899ccde72b95b86" },
39
40
  ].map((m) => Object.freeze(m)));
40
41
 
41
42
  /** PUBLISHED_ENCLAVE_MEASUREMENTS as the bare PCR0 list a verifier's pins take. */
package/src/stretch.ts ADDED
@@ -0,0 +1,108 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * The sandwich: a stretch of binds from BitGraph A to BitGraph B.
5
+ *
6
+ * A bind (enclave v11) takes exactly two counts: the nonce at N, the payload
7
+ * at N+1. When every proof on a chain is a bind, the counter runs straight
8
+ * through, so a stretch of proofs from A to B either accounts for every
9
+ * count in between or it does not:
10
+ *
11
+ * A 2435-2436 → R 2437-2438 → R 2439-2440 → B 2441-2442
12
+ *
13
+ * Each proof's nonce count is the previous proof's payload count plus one,
14
+ * and each proof links to the previous one by prevB64. Then every record in
15
+ * the stretch was bound after A and before B, and nothing else was.
16
+ *
17
+ * This checks the stretch's SHAPE. Each proof's own signature, attestation
18
+ * and measurement are verify()'s job; run it on every proof as well.
19
+ */
20
+
21
+ import { computeChainHash } from "./proof-hash.js";
22
+ import type { BitGraphProof } from "./types.js";
23
+
24
+ export interface StretchResult {
25
+ ok: boolean;
26
+ /** One line per failure; empty when ok. */
27
+ reasons: string[];
28
+ /** The first and last count the stretch covers, when it parses. */
29
+ from?: string;
30
+ to?: string;
31
+ }
32
+
33
+ function chainOf(p: BitGraphProof): string {
34
+ return (p.commit as { chainId?: string }).chainId ?? "global";
35
+ }
36
+
37
+ /**
38
+ * Check that `proofs` (in order, first = A, last = B) is one unbroken run of
39
+ * binds: same epoch, key and chain; every proof atomic; each nonce count the
40
+ * previous payload count plus one; each prevB64 the previous proof's chain hash.
41
+ */
42
+ export function verifyStretch(proofs: readonly BitGraphProof[]): StretchResult {
43
+ const reasons: string[] = [];
44
+ if (proofs.length < 2) return { ok: false, reasons: ["a stretch needs at least two proofs (A and B)"] };
45
+
46
+ const first = proofs[0]!;
47
+ for (let i = 0; i < proofs.length; i++) {
48
+ const p = proofs[i]!;
49
+ const at = `proof ${i} (counter ${p.commit.counter ?? "?"})`;
50
+ if (p.commit.atomic !== true || p.slotAllocation === undefined) {
51
+ reasons.push(`${at} is not a bind: its nonce and payload were not one action`);
52
+ continue;
53
+ }
54
+ let n: bigint;
55
+ let n1: bigint;
56
+ try {
57
+ n = BigInt(p.slotAllocation.counter);
58
+ n1 = BigInt(p.commit.counter ?? "");
59
+ } catch {
60
+ reasons.push(`${at} has a counter that does not parse`);
61
+ continue;
62
+ }
63
+ if (n1 !== n + 1n) reasons.push(`${at}: payload count ${n1} is not nonce count ${n} plus one`);
64
+ if (p.commit.epochId !== first.commit.epochId) reasons.push(`${at} is in another epoch`);
65
+ if (p.signer.publicKeyB64 !== first.signer.publicKeyB64) reasons.push(`${at} is signed by another key`);
66
+ if (chainOf(p) !== chainOf(first)) reasons.push(`${at} is on another chain`);
67
+ if (i === 0) continue;
68
+
69
+ const prev = proofs[i - 1]!;
70
+ try {
71
+ const prevEnd = BigInt(prev.commit.counter ?? "");
72
+ if (n !== prevEnd + 1n) {
73
+ reasons.push(`${at}: nonce count ${n} does not follow the previous payload count ${prevEnd} (counts ${prevEnd + 1n} to ${n - 1n} are unaccounted for)`);
74
+ }
75
+ } catch {
76
+ reasons.push(`proof ${i - 1} has a counter that does not parse`);
77
+ }
78
+ if (p.commit.prevB64 !== computeChainHash(prev)) {
79
+ reasons.push(`${at} does not link to the proof before it (prevB64)`);
80
+ }
81
+ }
82
+
83
+ const last = proofs[proofs.length - 1]!;
84
+ const from = first.slotAllocation?.counter;
85
+ const to = last.commit.counter;
86
+ return {
87
+ ok: reasons.length === 0,
88
+ reasons,
89
+ ...(from !== undefined ? { from } : {}),
90
+ ...(to !== undefined ? { to } : {}),
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Was `record` bound after A and before B? True when the stretch from A to B
96
+ * is unbroken (verifyStretch) and contains `record` strictly between them.
97
+ * `stretch` is every proof from A to B inclusive, in order.
98
+ */
99
+ export function verifyBetween(stretch: readonly BitGraphProof[], record: BitGraphProof): StretchResult {
100
+ const s = verifyStretch(stretch);
101
+ if (!s.ok) return s;
102
+ const target = computeChainHash(record);
103
+ const idx = stretch.findIndex((p) => computeChainHash(p) === target);
104
+ if (idx <= 0 || idx >= stretch.length - 1) {
105
+ return { ...s, ok: false, reasons: ["the record is not strictly between A and B in this stretch"] };
106
+ }
107
+ return s;
108
+ }
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
  }
package/src/types.ts CHANGED
@@ -154,6 +154,16 @@ export interface BitGraphProof {
154
154
  */
155
155
  slotHashB64?: string;
156
156
 
157
+ /**
158
+ * Enclave v11 (bind). SIGNED. Present and true when the nonce and the
159
+ * payload were taken in ONE atomic action inside the boundary: the nonce
160
+ * at slotCounter, the payload at counter = slotCounter + 1, nothing
161
+ * between them, and the nonce never left the enclave before it was bound.
162
+ * Absent on two-call proofs (allocate, then commit), whose nonce was
163
+ * handed out first and whose counts may have other work between them.
164
+ */
165
+ atomic?: true;
166
+
157
167
  /**
158
168
  * Enclave v7 (2026-09-06). Present on Ethereum anchor proofs only: the
159
169
  * block this proof anchors, written by the enclave after it verified the
@@ -556,6 +566,12 @@ export interface VerificationPolicy {
556
566
  * not just TEE-enforced signing with freshness.
557
567
  */
558
568
  requireSlot?: boolean;
569
+
570
+ /**
571
+ * Require a bind (enclave v11): commit.atomic is true, so the nonce and
572
+ * the payload were one action, the payload at the very next count.
573
+ */
574
+ requireAtomic?: boolean;
559
575
  }
560
576
 
561
577
  // ---------------------------------------------------------------------------
package/src/verifier.ts CHANGED
@@ -331,6 +331,19 @@ async function runChecks(
331
331
  return slotError;
332
332
  }
333
333
  }
334
+ // A bind (enclave v11) claims two counts in one action: the nonce at N,
335
+ // the payload at N+1. The claim is signed; the counters must say the same.
336
+ if (proof.commit.atomic !== undefined) {
337
+ if (proof.commit.atomic !== true) return "commit.atomic must be true when present";
338
+ if (proof.slotAllocation === undefined) return "commit.atomic requires slotAllocation (the nonce's own record)";
339
+ try {
340
+ if (BigInt(proof.commit.counter ?? "-1") !== BigInt(proof.slotAllocation.counter) + 1n) {
341
+ return `commit.atomic: the payload count (${proof.commit.counter}) must be the nonce count (${proof.slotAllocation.counter}) plus one`;
342
+ }
343
+ } catch {
344
+ return "commit.atomic: could not parse the nonce or payload counter as an integer";
345
+ }
346
+ }
334
347
 
335
348
  // ------------------------------------------------------------------
336
349
  // 4d. Epoch link verification (cross-epoch lineage)
@@ -624,6 +637,10 @@ function checkPolicy(proof: BitGraphProof, policy: VerificationPolicy): string |
624
637
  // so by this point the slot has already been validated if present.
625
638
  }
626
639
 
640
+ if (policy.requireAtomic === true && proof.commit.atomic !== true) {
641
+ return "policy requires a bind (commit.atomic: the nonce and the payload in one action) but proof has none";
642
+ }
643
+
627
644
  return null;
628
645
  }
629
646