@mikeargento/bitgraph-verify 1.29.1 → 1.30.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 (50) hide show
  1. package/dist/__tests__/measurements-windows.test.js +5 -1
  2. package/dist/__tests__/measurements-windows.test.js.map +1 -1
  3. package/dist/__tests__/stretch.test.js +22 -0
  4. package/dist/__tests__/stretch.test.js.map +1 -1
  5. package/dist/__tests__/tot-floor.test.d.ts +2 -0
  6. package/dist/__tests__/tot-floor.test.d.ts.map +1 -0
  7. package/dist/__tests__/tot-floor.test.js +179 -0
  8. package/dist/__tests__/tot-floor.test.js.map +1 -0
  9. package/dist/carrier5.js +2 -2
  10. package/dist/carrier5.js.map +1 -1
  11. package/dist/fuse.d.ts +14 -0
  12. package/dist/fuse.d.ts.map +1 -1
  13. package/dist/fuse.js +37 -0
  14. package/dist/fuse.js.map +1 -1
  15. package/dist/index.d.ts +5 -3
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +4 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/measurements.d.ts +2 -0
  20. package/dist/measurements.d.ts.map +1 -1
  21. package/dist/measurements.js +3 -2
  22. package/dist/measurements.js.map +1 -1
  23. package/dist/proof-hash.d.ts +16 -0
  24. package/dist/proof-hash.d.ts.map +1 -1
  25. package/dist/proof-hash.js +34 -0
  26. package/dist/proof-hash.js.map +1 -1
  27. package/dist/stretch.js +4 -4
  28. package/dist/stretch.js.map +1 -1
  29. package/dist/tot-floor.d.ts +86 -0
  30. package/dist/tot-floor.d.ts.map +1 -0
  31. package/dist/tot-floor.js +107 -0
  32. package/dist/tot-floor.js.map +1 -0
  33. package/dist/types.d.ts +18 -2
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/verifier.d.ts.map +1 -1
  36. package/dist/verifier.js +10 -2
  37. package/dist/verifier.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/__tests__/measurements-windows.test.ts +5 -1
  40. package/src/__tests__/stretch.test.ts +25 -0
  41. package/src/__tests__/tot-floor.test.ts +197 -0
  42. package/src/carrier5.ts +2 -2
  43. package/src/fuse.ts +35 -0
  44. package/src/index.ts +8 -1
  45. package/src/measurements.ts +3 -3
  46. package/src/proof-hash.ts +32 -0
  47. package/src/stretch.ts +4 -4
  48. package/src/tot-floor.ts +165 -0
  49. package/src/types.ts +19 -2
  50. package/src/verifier.ts +9 -2
@@ -0,0 +1,197 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * A TOT's public floor (bitgraph/slot/2): the record's form and signature, and the rule that looks the block up.
5
+ *
6
+ * The receipts are signed here with a throwaway key. The block is a real one, Base 66088566, as a node returned its
7
+ * header: its hash can be rebuilt from its fields, so the test needs no network.
8
+ *
9
+ * cd packages/verify && npx tsc -p . && node --test dist/__tests__/tot-floor.test.js
10
+ */
11
+
12
+ import { test } from "node:test";
13
+ import { strict as assert } from "node:assert";
14
+ import { getPublicKeyAsync, signAsync } from "@noble/ed25519";
15
+ import { sha256 } from "@noble/hashes/sha256";
16
+ import { canonicalize } from "../canonical.js";
17
+ import { verifyProofIntegrity, createVerificationContext } from "../verifier.js";
18
+ import { canonicalSlotBody, computeSlotRecordHash, slotFloorProblem, bytesToBase64 } from "../fuse.js";
19
+ import { buildSignedBody } from "../proof-hash.js";
20
+ import { totFloorOf, floorHashHex, checkFloorAgainstBlock, checkFloorOnline, FLOOR_NETWORKS } from "../tot-floor.js";
21
+ import type { BitGraphProof, SlotAllocation, SlotFloor } from "../types.js";
22
+
23
+ /** Base block 66088566, header fields as https://mainnet.base.org returned them on 2026-12-04. */
24
+ const BLOCK: Record<string, string> = {"hash":"0xbd6130b95b52264e50e2fb1e74f0168c89191c202ae0ce15a62414c15e4d01d6","parentHash":"0xac9581aa1851c9f1368cea45ec5451a15fd3348287cdf39f383bfaf9a756167d","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","miner":"0x4200000000000000000000000000000000000011","stateRoot":"0x55846798a21048527efd37d499ec491057e5a7d047e45c9ff6f5deff31c8abc3","transactionsRoot":"0x420b8c61001dd68559adec79ae5df4f76be3d1100bbd25225782d19f550249b2","receiptsRoot":"0x380c536b34ed35c580ebcc4c3266bb2755ee1ac5e4c6f5cfcec5dfe36901d7fb","logsBloom":"0x800204a80a02110800841000020800200568000c63041100420780090900340130400c000f09c048c106821020029087a040050c10003100021884020034242040000300040e810a1000041a010d808601101805308c108030500113a0041010049200002282000006254002820028000c0044284806a0008000021a000801401001000108040100808002035a000500212281c100208806544da000010002800202000090008080061000cc0011c000701c240200032408021210a0410041a30c2460060080107101100a20212940080284902010185910440200010a007024801098404704000a66040041c2400201000220180041804080220802620a0109","difficulty":"0x0","number":"0x3f06e76","gasLimit":"0x2625a00","gasUsed":"0x47aef9","timestamp":"0x6b130318","timestampMs":"0x1a2424418e0","extraData":"0x01000003e80000000500000000004c4b40","mixHash":"0xb782c05be76a203d41b7e3a6e6769f6e14d8395a823d75380b07a83f4bdcf059","nonce":"0x0000000000000000","baseFeePerGas":"0x93e206","withdrawalsRoot":"0x0628322cfb77711bb4d904ceaf62715a09971a80b87cc560436c0e729abb1b3c","blobGasUsed":"0x954d0","excessBlobGas":"0x0","parentBeaconBlockRoot":"0x2d530eab54966f8bcbd0a2f37d5f30fee307bc2942ecd8c09c8fe55e0f797aee","requestsHash":"0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"};
25
+ const BLOCK_NUMBER = "66088566";
26
+ const BLOCK_HASH_B64 = Buffer.from(BLOCK["hash"]!.slice(2), "hex").toString("base64");
27
+ const BLOCK_TIME_MS = 1796408088800;
28
+ const FLOOR: SlotFloor = { network: "eip155:8453", number: BLOCK_NUMBER, hashB64: BLOCK_HASH_B64 };
29
+
30
+ const KEY = sha256(new TextEncoder().encode("tot-floor test key"));
31
+ const b64 = (u: Uint8Array) => bytesToBase64(u);
32
+ const fill = (n: number) => b64(new Uint8Array(32).fill(n));
33
+
34
+ /** A receipt as the enclave makes one, signed with the test key: slot/2 with the floor, or slot/1 without. */
35
+ async function receipt(floor?: SlotFloor): Promise<BitGraphProof> {
36
+ const publicKeyB64 = b64(await getPublicKeyAsync(KEY));
37
+ const body = {
38
+ version: floor ? "bitgraph/slot/2" : "bitgraph/slot/1",
39
+ nonceB64: fill(7), counter: "41", epochId: fill(9), publicKeyB64, chainId: "bitgraph:main",
40
+ ...(floor ? { floor } : {}),
41
+ };
42
+ const slotCanonical = canonicalize(body as unknown as Record<string, unknown>);
43
+ const slot = { ...body, signatureB64: b64(await signAsync(slotCanonical, KEY)) } as unknown as SlotAllocation;
44
+ const proof = {
45
+ version: "bitgraph/1",
46
+ artifact: { hashAlg: "sha256", digestB64: fill(3) },
47
+ commit: { nonceB64: fill(7), counter: "42", slotCounter: "41", slotHashB64: b64(sha256(slotCanonical)), epochId: fill(9), atomic: true, chainId: "bitgraph:main" },
48
+ signer: { publicKeyB64, signatureB64: "" },
49
+ environment: { enforcement: "measured-tee", measurement: "ab".repeat(48), attestation: { format: "aws-nitro", reportB64: "AA==" } },
50
+ slotAllocation: slot,
51
+ } as unknown as BitGraphProof;
52
+ proof.signer.signatureB64 = b64(await signAsync(canonicalize(buildSignedBody(proof)), KEY));
53
+ return proof;
54
+ }
55
+ const integrity = (proof: BitGraphProof) => verifyProofIntegrity({ proof, trustAnchors: { requireAtomic: true }, context: createVerificationContext() });
56
+ const withSlot = (p: BitGraphProof, change: Record<string, unknown>): BitGraphProof => ({ ...p, slotAllocation: { ...p.slotAllocation!, ...change } as SlotAllocation });
57
+
58
+ test("a slot/2 TOT with its floor verifies, and the spend holds the hash of the body with the floor", async () => {
59
+ const p = await receipt(FLOOR);
60
+ const r = await integrity(p);
61
+ assert.equal(r.valid, true, r.reason);
62
+ assert.deepEqual(Object.keys(canonicalSlotBody(p.slotAllocation!)).sort(), ["chainId", "counter", "epochId", "floor", "nonceB64", "publicKeyB64", "version"]);
63
+ assert.equal(b64(computeSlotRecordHash(p.slotAllocation!)), p.commit.slotHashB64);
64
+ assert.deepEqual(totFloorOf(p), FLOOR);
65
+ });
66
+
67
+ test("a slot/1 TOT still verifies and carries no floor", async () => {
68
+ const p = await receipt();
69
+ assert.equal((await integrity(p)).valid, true);
70
+ assert.deepEqual(Object.keys(canonicalSlotBody(p.slotAllocation!)).sort(), ["chainId", "counter", "epochId", "nonceB64", "publicKeyB64", "version"]);
71
+ assert.equal(totFloorOf(p), null);
72
+ });
73
+
74
+ test("the floor is under the TOT's signature: any change to it breaks the receipt", async () => {
75
+ const p = await receipt(FLOOR);
76
+ for (const floor of [{ ...FLOOR, number: "66088567" }, { ...FLOOR, hashB64: fill(1) }, { ...FLOOR, network: "eip155:1" }]) {
77
+ const r = await integrity(withSlot(p, { floor }));
78
+ assert.equal(r.valid, false);
79
+ assert.match(String(r.reason), /signature verification failed/);
80
+ }
81
+ });
82
+
83
+ test("a floor on a slot/1 TOT is not signed, so the receipt is refused and no floor is read from it", async () => {
84
+ const p = withSlot(await receipt(), { floor: FLOOR });
85
+ const r = await integrity(p);
86
+ assert.equal(r.valid, false);
87
+ assert.match(String(r.reason), /only signed in a bitgraph\/slot\/2 record/);
88
+ assert.equal(totFloorOf(p), null);
89
+ });
90
+
91
+ test("a slot/2 TOT must carry one floor, in form", async () => {
92
+ const p = await receipt(FLOOR);
93
+ const { floor: _f, ...noFloor } = p.slotAllocation as unknown as Record<string, unknown>;
94
+ assert.match(String((await integrity({ ...p, slotAllocation: noFloor as unknown as SlotAllocation })).reason), /must carry a floor/);
95
+ const bad: Array<[unknown, RegExp]> = [
96
+ [null, /must carry a floor/],
97
+ ["eip155:8453", /must carry a floor/],
98
+ [{ ...FLOOR, extra: "x" }, /exactly network, number and hashB64/],
99
+ [{ network: FLOOR.network, number: FLOOR.number }, /exactly network, number and hashB64/],
100
+ [{ ...FLOOR, network: "Base" }, /CAIP-2/],
101
+ [{ ...FLOOR, number: "066088566" }, /decimal string/],
102
+ [{ ...FLOOR, number: 66088566 }, /decimal string/],
103
+ [{ ...FLOOR, hashB64: b64(new Uint8Array(31)) }, /32 bytes/],
104
+ [{ ...FLOOR, hashB64: BLOCK_HASH_B64.replace(/=$/, "") }, /32 bytes/],
105
+ ];
106
+ for (const [floor, why] of bad) {
107
+ assert.match(String(slotFloorProblem({ version: "bitgraph/slot/2", floor })), why);
108
+ const r = await integrity(withSlot(p, { floor }));
109
+ assert.equal(r.valid, false, JSON.stringify(floor));
110
+ assert.equal(totFloorOf(withSlot(p, { floor })), null);
111
+ }
112
+ });
113
+
114
+ test("the chain holds the block: confirmed, with the block's time and the gap to the attestation", async () => {
115
+ const p = await receipt(FLOOR);
116
+ const c = checkFloorAgainstBlock({ proof: p, block: BLOCK, attestedAtMs: BLOCK_TIME_MS + 412 });
117
+ assert.equal(c.status, "confirmed");
118
+ assert.equal(c.hashHex, BLOCK["hash"]);
119
+ assert.equal(c.networkName, "Base");
120
+ assert.equal(c.blockUrl, "https://basescan.org/block/66088566");
121
+ assert.equal(c.blockTimeMs, BLOCK_TIME_MS);
122
+ assert.equal(c.timeBoundByHash, true, "the header rebuilds to the floor's hash, so its second is covered by it");
123
+ assert.equal(c.gapMs, 412);
124
+ assert.equal(c.stale, undefined, "no limit was given, so nothing is flagged");
125
+ assert.equal(floorHashHex(FLOOR), BLOCK["hash"]);
126
+ assert.equal(FLOOR_NETWORKS["eip155:8453"]!.name, "Base");
127
+ });
128
+
129
+ test("two clocks: a block stamped after the attestation gives a negative gap, and that is not a failure", async () => {
130
+ const c = checkFloorAgainstBlock({ proof: await receipt(FLOOR), block: BLOCK, attestedAtMs: BLOCK_TIME_MS - 300, maxGapMs: 2000 });
131
+ assert.equal(c.status, "confirmed");
132
+ assert.equal(c.gapMs, -300);
133
+ assert.equal(c.stale, false);
134
+ });
135
+
136
+ test("a stale floor is flagged when a limit is given, and stays confirmed", async () => {
137
+ const p = await receipt(FLOOR);
138
+ const stale = checkFloorAgainstBlock({ proof: p, block: BLOCK, attestedAtMs: BLOCK_TIME_MS + 90_000, maxGapMs: 2000 });
139
+ assert.equal(stale.status, "confirmed");
140
+ assert.equal(stale.gapMs, 90_000);
141
+ assert.equal(stale.stale, true);
142
+ assert.equal(checkFloorAgainstBlock({ proof: p, block: BLOCK, attestedAtMs: BLOCK_TIME_MS + 2000, maxGapMs: 2000 }).stale, false);
143
+ });
144
+
145
+ test("a finer time is used only inside the header's own second; without one the second stands", async () => {
146
+ const p = await receipt(FLOOR);
147
+ assert.equal(checkFloorAgainstBlock({ proof: p, block: { ...BLOCK, timestampMs: "0x1" } }).blockTimeMs, 1796408088000);
148
+ const { timestampMs: _ms, ...seconds } = BLOCK;
149
+ assert.equal(checkFloorAgainstBlock({ proof: p, block: seconds }).blockTimeMs, 1796408088000);
150
+ });
151
+
152
+ test("the chain does not hold the block: not confirmed, and it says why", async () => {
153
+ const p = await receipt(FLOOR);
154
+ const unknown = checkFloorAgainstBlock({ proof: p, block: null, attestedAtMs: 5 });
155
+ assert.equal(unknown.status, "not-confirmed");
156
+ assert.match(String(unknown.detail), /has no block 66088566/);
157
+ const other = checkFloorAgainstBlock({ proof: p, block: { ...BLOCK, hash: "0x" + "11".repeat(32) } });
158
+ assert.equal(other.status, "not-confirmed");
159
+ assert.match(String(other.detail), /another hash/);
160
+ const wrong = checkFloorAgainstBlock({ proof: p, block: { ...BLOCK, number: "0x1" } });
161
+ assert.equal(wrong.status, "not-confirmed");
162
+ // A floor naming a block that is not this one.
163
+ const fake = await receipt({ ...FLOOR, hashB64: fill(5) });
164
+ assert.equal(checkFloorAgainstBlock({ proof: fake, block: BLOCK }).status, "not-confirmed");
165
+ assert.equal(unknown.blockTimeMs, undefined, "an unconfirmed floor reports no time");
166
+ });
167
+
168
+ test("a header whose fields do not rebuild to the hash is confirmed by the hash alone; its time is the node's word", async () => {
169
+ const c = checkFloorAgainstBlock({ proof: await receipt(FLOOR), block: { ...BLOCK, gasUsed: "0x1" } });
170
+ assert.equal(c.status, "confirmed");
171
+ assert.equal(c.timeBoundByHash, false);
172
+ });
173
+
174
+ test("no floor, nothing to check", async () => {
175
+ assert.deepEqual(checkFloorAgainstBlock({ proof: await receipt(), block: BLOCK }), { status: "none" });
176
+ assert.deepEqual(await checkFloorOnline({ proof: await receipt(), fetcher: (async () => { throw new Error("must not be called"); }) as unknown as typeof fetch }), { status: "none" });
177
+ });
178
+
179
+ test("the online step asks for the block by number and applies the same rule", async () => {
180
+ const p = await receipt(FLOOR);
181
+ const asked: unknown[] = [];
182
+ const node = (result: unknown, status = 200) => (async (_url: string, init: { body: string }) => {
183
+ asked.push(JSON.parse(init.body));
184
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: 1, result }), { status });
185
+ }) as unknown as typeof fetch;
186
+ const ok = await checkFloorOnline({ proof: p, attestedAtMs: BLOCK_TIME_MS + 100, maxGapMs: 2000, fetcher: node(BLOCK) });
187
+ assert.equal(ok.status, "confirmed");
188
+ assert.equal(ok.gapMs, 100);
189
+ assert.deepEqual((asked[0] as { method: string; params: unknown[] }).params, ["0x3f06e76", false]);
190
+ assert.equal((await checkFloorOnline({ proof: p, fetcher: node(null) })).status, "not-confirmed");
191
+ // A lookup that cannot be made is not a verdict on the floor.
192
+ assert.equal((await checkFloorOnline({ proof: p, fetcher: node(null, 502) })).status, "not-checked");
193
+ assert.equal((await checkFloorOnline({ proof: p, fetcher: (async () => { throw new Error("offline"); }) as unknown as typeof fetch })).status, "not-checked");
194
+ const elsewhere = await checkFloorOnline({ proof: await receipt({ ...FLOOR, network: "eip155:1" }), fetcher: node(BLOCK) });
195
+ assert.equal(elsewhere.status, "not-checked");
196
+ assert.match(String(elsewhere.detail), /does not know the network/);
197
+ });
package/src/carrier5.ts CHANGED
@@ -23,7 +23,7 @@
23
23
  import { sha256 } from "@noble/hashes/sha256";
24
24
  import { CARRIER_VERSION_5, CARRIER_VERSION_6, buildCarrier, type CarrierPayload, type CarrierBounds } from "./carrier.js";
25
25
  import { parseBlockReadFile } from "./block-read.js";
26
- import { computeChainHash } from "./proof-hash.js";
26
+ import { chainLinkMatches } from "./proof-hash.js";
27
27
  import { verifyAttested } from "./attested.js";
28
28
  import { verifyCeiling, type CeilingSidecar } from "./ceiling.js";
29
29
  import { checkTreeFloor, treeMemberOf } from "./tree-member.js";
@@ -108,7 +108,7 @@ export async function verifyCarrierV5(payloadIn: CarrierPayload, inner: Uint8Arr
108
108
  const f = parseBlockReadFile(fl.blockFile);
109
109
  const sameEpoch = fp.commit?.epochId === proof.commit?.epochId && f?.epochId === proof.commit?.epochId;
110
110
  const next = !!fp.commit?.counter && !!proof.commit?.slotCounter && BigInt(fp.commit.counter) + 1n === BigInt(proof.commit.slotCounter);
111
- const chained = proof.commit?.prevB64 === computeChainHash(fp);
111
+ const chained = chainLinkMatches(proof.commit?.prevB64, fp);
112
112
  const ok = fr.valid && f !== null && f.chain === "base" && f.chainId === "eip155:8453" && sameEpoch && next && chained;
113
113
  const why = !fr.valid ? `the floor's proof does not verify: ${fr.reason ?? "invalid"}` : f === null ? "the floor's block file is not a bitgraph-block-read/1 file" : f.chain !== "base" || f.chainId !== "eip155:8453" ? "the floor is not a Base mainnet block" : !sameEpoch ? "the floor is not of this file's epoch" : !next ? "the floor is not the record right before this file" : "this file's prevB64 is not the floor's hash";
114
114
  add("floor.read", "The floor is the Base block read bound right before this file", ok ? "TRUE" : "FALSE", "BitGraph's previous record, chained by prevB64", ok ? `BitGraph #${fp.commit.counter} bound Base block ${f!.number} (${f!.hash.slice(0, 12)}…), and this file's signed prevB64 is that record's hash: the bind came after the block existed` : why);
package/src/fuse.ts CHANGED
@@ -154,9 +154,44 @@ export function canonicalSlotBody(slot: SlotAllocation): Record<string, unknown>
154
154
  epochId: slot.epochId,
155
155
  publicKeyB64: slot.publicKeyB64,
156
156
  ...(slot.chainId ? { chainId: slot.chainId } : {}),
157
+ // bitgraph/slot/2: the floor is part of what the enclave signed. Rebuilt field by field, so nothing else that
158
+ // sits in the object is carried into the signed bytes.
159
+ ...(slot.version === SLOT_VERSION_2 && slot.floor
160
+ ? { floor: { network: slot.floor.network, number: slot.floor.number, hashB64: slot.floor.hashB64 } }
161
+ : {}),
157
162
  };
158
163
  }
159
164
 
165
+ /** The slot record version that carries a floor. */
166
+ export const SLOT_VERSION_2 = "bitgraph/slot/2";
167
+ /** Base mainnet, as a CAIP-2 id: the floor network the enclave accepts. */
168
+ export const FLOOR_NETWORK_BASE = "eip155:8453";
169
+
170
+ const FLOOR_NETWORK = /^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/;
171
+ const FLOOR_NUMBER = /^(0|[1-9][0-9]{0,19})$/;
172
+
173
+ /**
174
+ * Why a slot record's floor is not in form, or null when it is. A bitgraph/slot/2 record carries exactly one floor:
175
+ * { network, number, hashB64 } and nothing else, the network a CAIP-2 id, the number a decimal string of at most 20
176
+ * digits, the hash 32 bytes in canonical base64. A bitgraph/slot/1 record carries none: a floor on one is not signed,
177
+ * so it is refused, never shown.
178
+ */
179
+ export function slotFloorProblem(slot: { version?: unknown; floor?: unknown }): string | null {
180
+ const f = slot.floor;
181
+ if (slot.version !== SLOT_VERSION_2) {
182
+ return f === undefined ? null : "slotAllocation.floor is only signed in a bitgraph/slot/2 record; this record is not one";
183
+ }
184
+ if (f === null || typeof f !== "object" || Array.isArray(f)) return "a bitgraph/slot/2 record must carry a floor object";
185
+ const o = f as Record<string, unknown>;
186
+ const keys = Object.keys(o).sort().join(",");
187
+ if (keys !== "hashB64,network,number") return "slotAllocation.floor must hold exactly network, number and hashB64";
188
+ if (typeof o["network"] !== "string" || !FLOOR_NETWORK.test(o["network"])) return "slotAllocation.floor.network must be a CAIP-2 chain id";
189
+ if (typeof o["number"] !== "string" || !FLOOR_NUMBER.test(o["number"])) return "slotAllocation.floor.number must be a decimal string";
190
+ const h = typeof o["hashB64"] === "string" ? base64ToBytes(o["hashB64"]) : null;
191
+ if (h === null || h.length !== 32 || bytesToBase64(h) !== o["hashB64"]) return "slotAllocation.floor.hashB64 must be 32 bytes in canonical base64";
192
+ return null;
193
+ }
194
+
160
195
  /** SHA-256 of the canonical slot body; equals the proof's commit.slotHashB64. */
161
196
  export function computeSlotRecordHash(slot: SlotAllocation): Uint8Array {
162
197
  return sha256(canonicalize(canonicalSlotBody(slot) as unknown as BitGraphProof));
package/src/index.ts CHANGED
@@ -26,6 +26,7 @@ export type {
26
26
  Attribution,
27
27
  PolicyBinding,
28
28
  SlotAllocation,
29
+ SlotFloor,
29
30
  ActorIdentity,
30
31
  AuthorizationPayload,
31
32
  WebAuthnAuthorization,
@@ -35,7 +36,7 @@ export type {
35
36
  export { verify, verifyProofIntegrity, resetEpochLinkState, createVerificationContext } from "./verifier.js";
36
37
  export type { VerifyResult, ProofIntegrityResult, VerificationContext } from "./verifier.js";
37
38
 
38
- export { computeProofHash, computeChainHash, buildSignedBody, computeSignedBodyHash } from "./proof-hash.js";
39
+ export { computeProofHash, computeChainHash, chainLinkMatches, computeChainHashWithoutMetadata, buildSignedBody, computeSignedBodyHash } from "./proof-hash.js";
39
40
 
40
41
  export { canonicalize, canonicalizeToString, constantTimeEqual } from "./canonical.js";
41
42
 
@@ -46,6 +47,9 @@ export { verifyAttested } from "./attested.js";
46
47
  // A file of a tree, checked by its own hash (bitgraph-tree-member/1, 2026-10-20). verifyAttested applies it.
47
48
  export { TREE_MEMBER_METADATA_KEY, treeMemberOf, checkTreeMember, treeRootFromPath, digestTreeRootText, parseDigestTreeRootText, treeRootTextBytes, type TreeMemberBlock } from "./tree-member.js";
48
49
  export type { AttestedOptions, AttestedResult } from "./attested.js";
50
+ /* A TOT's public floor (bitgraph/slot/2): the signed floor, and the optional step that looks its block up. */
51
+ export { FLOOR_NETWORKS, totFloorOf, floorHashHex, checkFloorAgainstBlock, checkFloorOnline } from "./tot-floor.js";
52
+ export type { FloorCheck } from "./tot-floor.js";
49
53
  export type { StretchResult } from "./stretch.js";
50
54
 
51
55
  // BitGraph Fuse (profile bitgraph-fuse/1): construction, parsing, verification.
@@ -65,6 +69,9 @@ export {
65
69
  parseSetManifest,
66
70
  readSetMetadata,
67
71
  canonicalSlotBody,
72
+ SLOT_VERSION_2,
73
+ FLOOR_NETWORK_BASE,
74
+ slotFloorProblem,
68
75
  computeSlotRecordHash,
69
76
  slotCommitmentPreimage,
70
77
  computeSlotCommitment,
@@ -39,6 +39,7 @@ export const PUBLISHED_ENCLAVE_MEASUREMENTS: readonly PublishedMeasurement[] = O
39
39
  { version: "v11", since: "2026-10-17", pcr0: "d9128d67c406a30f988f74ece8b5cced5c9a96491289037f50bddb5f10aac2bc9d1d315dd7bf65428899ccde72b95b86" },
40
40
  { version: "v12", since: "2026-10-18", pcr0: "cf1ca497e1c3f678cce99ec2215f3991c72fd1b54f083a1f58563e88f5fe742e5190c7ebaf27f3aa98622605687e27c9" },
41
41
  { version: "v13", since: "2026-10-19", pcr0: "adaad0bef62292d35197ae8db19e40685229f1a1e6070a7c77a148c4ada88ee66a1ca50819eebc2017c6716a49f2692f" },
42
+ { version: "v14", since: "2026-12-04", pcr0: "10273c68951dd81156364b4b86d240208f37a1999dac27d54ebf3fc7a2fc723a1e2e852b91528d0a24aaf0544af6c52f" },
42
43
  ].map((m) => Object.freeze(m)));
43
44
 
44
45
  /** PUBLISHED_ENCLAVE_MEASUREMENTS as the bare PCR0 list a verifier's pins take. */
@@ -53,10 +54,9 @@ export function publishedMeasurement(pcr0: unknown): PublishedMeasurement | null
53
54
 
54
55
  /** Images from v11 on bind atomically: the nonce at N and the digest at N+1 in one action. Earlier images could hand
55
56
  * out a position before its content arrived. */
56
- const ATOMIC_IMAGES: ReadonlySet<string> = new Set(["v11", "v12", "v13"]);
57
-
58
57
  export function imageIsAtomic(version: string): boolean {
59
- return ATOMIC_IMAGES.has(version);
58
+ const m = /^v([0-9]+)$/.exec(version);
59
+ return m !== null && Number(m[1]) >= 11;
60
60
  }
61
61
 
62
62
  /**
package/src/proof-hash.ts CHANGED
@@ -162,6 +162,38 @@ export function computeChainHash(proof: BitGraphProof | Record<string, unknown>)
162
162
  return base64(sha256(bytes));
163
163
  }
164
164
 
165
+ /**
166
+ * Does `prevB64` name `predecessor`? True when it is the predecessor's chain hash, taken with or without the
167
+ * predecessor's `metadata`.
168
+ *
169
+ * `metadata` is unsigned and is added to a copy of a proof after the enclave made it (a tree member's block, the hourly
170
+ * publication block), so the enclave's link was computed over the proof without it. A copy that has since gained
171
+ * metadata must still link. The hash with metadata is tried as well, because a proof made with metadata already in
172
+ * place is linked over the whole of it.
173
+ */
174
+ export function chainLinkMatches(prevB64: string | undefined, predecessor: BitGraphProof | Record<string, unknown>): boolean {
175
+ if (prevB64 === undefined) return false;
176
+ if (prevB64 === computeChainHash(predecessor)) return true;
177
+ if (!Object.prototype.hasOwnProperty.call(predecessor, "metadata")) return false;
178
+ return prevB64 === computeChainHash(withoutMetadata(predecessor));
179
+ }
180
+
181
+ /** A shallow copy of a proof without its unsigned `metadata`. */
182
+ function withoutMetadata(proof: BitGraphProof | Record<string, unknown>): Record<string, unknown> {
183
+ const out: Record<string, unknown> = {};
184
+ for (const [k, v] of Object.entries(proof as Record<string, unknown>)) if (k !== "metadata") out[k] = v;
185
+ return out;
186
+ }
187
+
188
+ /**
189
+ * The chain hash of a proof with its unsigned `metadata` left out: the same value for every copy of one proof,
190
+ * whatever metadata a copy has gained. For telling whether two copies are the same record, not for checking a link
191
+ * (use chainLinkMatches for that).
192
+ */
193
+ export function computeChainHashWithoutMetadata(proof: BitGraphProof | Record<string, unknown>): string {
194
+ return computeChainHash(withoutMetadata(proof));
195
+ }
196
+
165
197
  // Base64-standard encode (works in both Node.js and browser).
166
198
  function base64(hash: Uint8Array): string {
167
199
  if (typeof Buffer !== "undefined") {
package/src/stretch.ts CHANGED
@@ -18,7 +18,7 @@
18
18
  * and measurement are verify()'s job; run it on every proof as well.
19
19
  */
20
20
 
21
- import { computeChainHash } from "./proof-hash.js";
21
+ import { chainLinkMatches, computeChainHashWithoutMetadata } from "./proof-hash.js";
22
22
  import type { BitGraphProof } from "./types.js";
23
23
 
24
24
  export interface StretchResult {
@@ -75,7 +75,7 @@ export function verifyStretch(proofs: readonly BitGraphProof[]): StretchResult {
75
75
  } catch {
76
76
  reasons.push(`proof ${i - 1} has a counter that does not parse`);
77
77
  }
78
- if (p.commit.prevB64 !== computeChainHash(prev)) {
78
+ if (!chainLinkMatches(p.commit.prevB64, prev)) {
79
79
  reasons.push(`${at} does not link to the proof before it (prevB64)`);
80
80
  }
81
81
  }
@@ -99,8 +99,8 @@ export function verifyStretch(proofs: readonly BitGraphProof[]): StretchResult {
99
99
  export function verifyBetween(stretch: readonly BitGraphProof[], record: BitGraphProof): StretchResult {
100
100
  const s = verifyStretch(stretch);
101
101
  if (!s.ok) return s;
102
- const target = computeChainHash(record);
103
- const idx = stretch.findIndex((p) => computeChainHash(p) === target);
102
+ const target = computeChainHashWithoutMetadata(record);
103
+ const idx = stretch.findIndex((p) => computeChainHashWithoutMetadata(p) === target);
104
104
  if (idx <= 0 || idx >= stretch.length - 1) {
105
105
  return { ...s, ok: false, reasons: ["the record is not strictly between A and B in this stretch"] };
106
106
  }
@@ -0,0 +1,165 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * A TOT's public floor (record version bitgraph/slot/2), and the optional online step that looks it up.
5
+ *
6
+ * The floor is a block of a public chain: its network, number and hash, signed into the TOT body with the random
7
+ * value. The host that ran the enclave named it; the enclave has no network and did not check it. So the floor is
8
+ * a claim until someone looks: when that chain holds a block with that number and that hash, the TOT was made after
9
+ * the block existed, because nobody can know a block's hash before the block. That is all a floor shows, and it is
10
+ * a statement about order, not a clock reading of the receipt.
11
+ *
12
+ * Looking is optional and never changes whether a receipt is valid. Three answers:
13
+ *
14
+ * confirmed the chain holds that block. The block's time is reported, with the gap from it to the
15
+ * attestation document's time. The two times come from two clocks that know nothing of each
16
+ * other (the chain's sequencer and AWS's hardware), so the gap can come out negative.
17
+ * not-confirmed the chain holds no block of that number, or one with another hash. The floor shows nothing.
18
+ * The receipt is exactly as valid as one with no floor.
19
+ * not-checked the lookup could not be made (no network, a chain this checker does not know).
20
+ *
21
+ * `checkFloorAgainstBlock` is the whole rule and fetches nothing: the caller supplies what the chain says.
22
+ * `checkFloorOnline` asks a node and then applies it.
23
+ */
24
+
25
+ import type { BitGraphProof, SlotFloor } from "./types.js";
26
+ import { base64ToBytes, slotFloorProblem, SLOT_VERSION_2, FLOOR_NETWORK_BASE } from "./fuse.js";
27
+ import { headerRlpFromRpc, type RpcBlockHeader } from "./ceiling.js";
28
+ import { bytesToHex } from "./ceiling-evm.js";
29
+
30
+ /** What each known floor network is called, where its blocks can be read, and where a person can look one up. */
31
+ export const FLOOR_NETWORKS: Readonly<Record<string, { name: string; rpcUrl: string; blockUrl: (number: string) => string }>> = Object.freeze({
32
+ [FLOOR_NETWORK_BASE]: { name: "Base", rpcUrl: "https://mainnet.base.org", blockUrl: (n: string) => `https://basescan.org/block/${n}` },
33
+ });
34
+
35
+ export interface FloorCheck {
36
+ /** "none": the TOT carries no signed floor. */
37
+ status: "none" | "confirmed" | "not-confirmed" | "not-checked";
38
+ floor?: SlotFloor;
39
+ /** The floor's block hash as the chain writes it: 0x and 64 lowercase hex. */
40
+ hashHex?: string;
41
+ /** The network's plain name, when this checker knows it. */
42
+ networkName?: string;
43
+ /** A page where a person can look the block up, when this checker knows the network. */
44
+ blockUrl?: string;
45
+ /** Why it is not confirmed, or why it was not checked. */
46
+ detail?: string;
47
+ /** confirmed: the block's own time, milliseconds since 1970. */
48
+ blockTimeMs?: number;
49
+ /**
50
+ * confirmed: whether the block's time is bound by its hash. True when the header the node returned rebuilds to
51
+ * the floor's hash: its whole-second time is then part of what the hash covers, and any finer part is as the
52
+ * node reports. False when the header could not be rebuilt and the time is the node's word alone.
53
+ */
54
+ timeBoundByHash?: boolean;
55
+ /** The attestation document's time, when the caller gave it. */
56
+ attestedAtMs?: number;
57
+ /** confirmed, with attestedAtMs: the attestation's time minus the block's. Negative when the two clocks disagree. */
58
+ gapMs?: number;
59
+ /** With maxGapMs: whether the gap is larger than it. A flag for the reader; it never makes a receipt invalid. */
60
+ stale?: boolean;
61
+ }
62
+
63
+ /** The floor a receipt's TOT carries under its signature, or null: no floor, not a slot/2 record, or not in form. */
64
+ export function totFloorOf(proof: Pick<BitGraphProof, "slotAllocation"> | null | undefined): SlotFloor | null {
65
+ const slot = proof?.slotAllocation;
66
+ if (!slot || slot.version !== SLOT_VERSION_2 || slotFloorProblem(slot) !== null) return null;
67
+ const f = slot.floor!;
68
+ return { network: f.network, number: f.number, hashB64: f.hashB64 };
69
+ }
70
+
71
+ /** The floor's hash as 0x hex, or null when it is not 32 bytes. */
72
+ export function floorHashHex(floor: SlotFloor): string | null {
73
+ const b = base64ToBytes(floor.hashB64);
74
+ return b !== null && b.length === 32 ? bytesToHex(b) : null; // bytesToHex writes the 0x itself
75
+ }
76
+
77
+ function describe(floor: SlotFloor): Pick<FloorCheck, "floor" | "hashHex" | "networkName" | "blockUrl"> {
78
+ const known = FLOOR_NETWORKS[floor.network];
79
+ const hashHex = floorHashHex(floor);
80
+ return {
81
+ floor,
82
+ ...(hashHex ? { hashHex } : {}),
83
+ ...(known ? { networkName: known.name, blockUrl: known.blockUrl(floor.number) } : {}),
84
+ };
85
+ }
86
+
87
+ /**
88
+ * The rule, with what the chain says supplied by the caller. `block` is the chain's block at the floor's number as
89
+ * a node returns it (eth_getBlockByNumber), or null when the chain has no block of that number.
90
+ */
91
+ export function checkFloorAgainstBlock(args: {
92
+ proof: Pick<BitGraphProof, "slotAllocation">;
93
+ block: (Partial<RpcBlockHeader> & { timestampMs?: string }) | null;
94
+ attestedAtMs?: number | null;
95
+ maxGapMs?: number;
96
+ }): FloorCheck {
97
+ const floor = totFloorOf(args.proof);
98
+ if (floor === null) return { status: "none" };
99
+ const d = describe(floor);
100
+ const attested = typeof args.attestedAtMs === "number" ? { attestedAtMs: args.attestedAtMs } : {};
101
+ if (args.block === null) return { status: "not-confirmed", ...d, ...attested, detail: `${d.networkName ?? floor.network} has no block ${floor.number}` };
102
+ const b = args.block;
103
+ const got = typeof b.hash === "string" ? b.hash.toLowerCase() : "";
104
+ const numberMatches = typeof b.number === "string" && /^0x[0-9a-f]+$/i.test(b.number) && BigInt(b.number).toString(10) === floor.number;
105
+ if (!numberMatches) return { status: "not-confirmed", ...d, ...attested, detail: "the block returned is not the block asked for" };
106
+ if (got !== d.hashHex) return { status: "not-confirmed", ...d, ...attested, detail: `block ${floor.number} on ${d.networkName ?? floor.network} has another hash` };
107
+
108
+ // The block is there. Its time: the whole seconds are part of the header the hash covers, when the header rebuilds.
109
+ const seconds = typeof b.timestamp === "string" && /^0x[0-9a-f]+$/i.test(b.timestamp) ? Number(BigInt(b.timestamp)) : null;
110
+ if (seconds === null || !Number.isSafeInteger(seconds)) return { status: "confirmed", ...d, ...attested };
111
+ const timeBoundByHash = headerRlpFromRpc(b as RpcBlockHeader, d.hashHex!) !== null;
112
+ const finer = typeof b.timestampMs === "string" && /^0x[0-9a-f]+$/i.test(b.timestampMs) ? Number(BigInt(b.timestampMs)) : null;
113
+ // A finer time is used only when it falls inside the header's own second.
114
+ const blockTimeMs = finer !== null && Number.isSafeInteger(finer) && Math.floor(finer / 1000) === seconds ? finer : seconds * 1000;
115
+ const out: FloorCheck = { status: "confirmed", ...d, ...attested, blockTimeMs, timeBoundByHash };
116
+ if (typeof args.attestedAtMs === "number") {
117
+ out.gapMs = args.attestedAtMs - blockTimeMs;
118
+ if (typeof args.maxGapMs === "number") out.stale = out.gapMs > args.maxGapMs;
119
+ }
120
+ return out;
121
+ }
122
+
123
+ /**
124
+ * The online step: ask a node of the floor's network for the block at the floor's number, then apply the rule.
125
+ * A lookup that cannot be made is "not-checked", never a verdict on the floor.
126
+ */
127
+ export async function checkFloorOnline(args: {
128
+ proof: Pick<BitGraphProof, "slotAllocation">;
129
+ attestedAtMs?: number | null;
130
+ maxGapMs?: number;
131
+ /** A node to ask. Default: the network's public node. */
132
+ rpcUrl?: string;
133
+ fetcher?: typeof fetch;
134
+ timeoutMs?: number;
135
+ }): Promise<FloorCheck> {
136
+ const floor = totFloorOf(args.proof);
137
+ if (floor === null) return { status: "none" };
138
+ const d = describe(floor);
139
+ const attested = typeof args.attestedAtMs === "number" ? { attestedAtMs: args.attestedAtMs } : {};
140
+ const known = FLOOR_NETWORKS[floor.network];
141
+ const url = args.rpcUrl ?? known?.rpcUrl;
142
+ if (!url) return { status: "not-checked", ...d, ...attested, detail: `this checker does not know the network ${floor.network}` };
143
+ let block: unknown;
144
+ try {
145
+ const r = await (args.fetcher ?? fetch)(url, {
146
+ method: "POST",
147
+ headers: { "content-type": "application/json" },
148
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_getBlockByNumber", params: [`0x${BigInt(floor.number).toString(16)}`, false] }),
149
+ signal: AbortSignal.timeout(args.timeoutMs ?? 8000),
150
+ });
151
+ if (!r.ok) return { status: "not-checked", ...d, ...attested, detail: `the node answered HTTP ${r.status}` };
152
+ const j = (await r.json()) as { result?: unknown; error?: unknown };
153
+ if (j.error !== undefined || !("result" in j)) return { status: "not-checked", ...d, ...attested, detail: "the node did not answer the lookup" };
154
+ block = j.result;
155
+ } catch (e) {
156
+ return { status: "not-checked", ...d, ...attested, detail: `the lookup failed: ${e instanceof Error ? e.message : String(e)}` };
157
+ }
158
+ if (block !== null && (typeof block !== "object" || Array.isArray(block))) return { status: "not-checked", ...d, ...attested, detail: "the node's answer is not a block" };
159
+ return checkFloorAgainstBlock({
160
+ proof: args.proof,
161
+ block: block as (Partial<RpcBlockHeader> & { timestampMs?: string }) | null,
162
+ ...(typeof args.attestedAtMs === "number" ? { attestedAtMs: args.attestedAtMs } : {}),
163
+ ...(typeof args.maxGapMs === "number" ? { maxGapMs: args.maxGapMs } : {}),
164
+ });
165
+ }
package/src/types.ts CHANGED
@@ -778,9 +778,24 @@ export interface AgencyEnvelope {
778
778
  * Together these checks prove the nonce existed before the artifact was
779
779
  * bound to it — the BitGraph atomic causality invariant.
780
780
  */
781
+ /**
782
+ * A public floor inside a TOT (bitgraph/slot/2): a block of a public chain, named by the host that ran the enclave
783
+ * and signed into the TOT body with the random value. The enclave has no network and does not check it. When the
784
+ * block is found on that chain with this hash, the TOT was made after that block existed, because nobody can know a
785
+ * block's hash earlier. When it is not found, the floor says nothing and the receipt is as valid as one without it.
786
+ */
787
+ export interface SlotFloor {
788
+ /** The chain, as a CAIP-2 id. Base is "eip155:8453". */
789
+ network: string;
790
+ /** The block's number, a decimal string. */
791
+ number: string;
792
+ /** The block's 32-byte hash, standard base64 with padding. */
793
+ hashB64: string;
794
+ }
795
+
781
796
  export interface SlotAllocation {
782
- /** Schema version for slot records. Domain separation from proof bodies. */
783
- version: "bitgraph/slot/1";
797
+ /** Schema version for slot records. Domain separation from proof bodies. slot/2 is slot/1 plus a signed floor. */
798
+ version: "bitgraph/slot/1" | "bitgraph/slot/2";
784
799
  /** NSM-generated nonce. Becomes commit.nonceB64 when consumed. */
785
800
  nonceB64: string;
786
801
  /** Monotonic counter at allocation time. Must be < commit counter. */
@@ -793,6 +808,8 @@ export interface SlotAllocation {
793
808
  publicKeyB64: string;
794
809
  /** Chain isolation identifier. Omitted for the default "global" chain. */
795
810
  chainId?: string;
811
+ /** The public floor: present on every bitgraph/slot/2 record and never on a bitgraph/slot/1 record. */
812
+ floor?: SlotFloor;
796
813
  /** Ed25519 signature over canonical slot body (all fields above). */
797
814
  signatureB64: string;
798
815
  }
package/src/verifier.ts CHANGED
@@ -83,6 +83,7 @@ import { createVerify, createHash } from "node:crypto";
83
83
  import { verifyAsync as ed25519VerifyAsync } from "@noble/ed25519";
84
84
  import { sha256 } from "@noble/hashes/sha256";
85
85
  import { canonicalize, constantTimeEqual } from "./canonical.js";
86
+ import { SLOT_VERSION_2, slotFloorProblem } from "./fuse.js";
86
87
  import type { EnforcementTier, BitGraphProof, SignedBody, SlotAllocation, VerificationPolicy, AgencyEnvelope, AuthorizationPayload, WebAuthnAuthorization } from "./types.js";
87
88
 
88
89
  // ---------------------------------------------------------------------------
@@ -897,9 +898,12 @@ async function verifySlotAllocation(proof: BitGraphProof): Promise<string | null
897
898
  const slot = proof.slotAllocation!;
898
899
 
899
900
  // 1. Validate slot structure
900
- if (slot.version !== "bitgraph/slot/1") {
901
- return `slotAllocation.version must be "bitgraph/slot/1", got "${String(slot.version)}"`;
901
+ if (slot.version !== "bitgraph/slot/1" && slot.version !== SLOT_VERSION_2) {
902
+ return `slotAllocation.version must be "bitgraph/slot/1" or "bitgraph/slot/2", got "${String(slot.version)}"`;
902
903
  }
904
+ // A floor is signed in a slot/2 record and absent from a slot/1 record.
905
+ const floorProblem = slotFloorProblem(slot);
906
+ if (floorProblem) return floorProblem;
903
907
  if (typeof slot.nonceB64 !== "string" || slot.nonceB64.length === 0) {
904
908
  return "slotAllocation.nonceB64 must be a non-empty string";
905
909
  }
@@ -934,6 +938,9 @@ async function verifySlotAllocation(proof: BitGraphProof): Promise<string | null
934
938
  epochId: slot.epochId,
935
939
  publicKeyB64: slot.publicKeyB64,
936
940
  ...(slot.chainId ? { chainId: slot.chainId } : {}),
941
+ ...(slot.version === SLOT_VERSION_2 && slot.floor
942
+ ? { floor: { network: slot.floor.network, number: slot.floor.number, hashB64: slot.floor.hashB64 } }
943
+ : {}),
937
944
  };
938
945
  const slotCanonicalBytes = canonicalize(slotBody);
939
946