@mikeargento/bitgraph-audit 0.9.0 → 0.11.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/README.md +5 -3
  2. package/dist/audit.d.ts +4 -3
  3. package/dist/audit.d.ts.map +1 -1
  4. package/dist/audit.js +9 -3
  5. package/dist/audit.js.map +1 -1
  6. package/dist/ceilings.d.ts.map +1 -1
  7. package/dist/ceilings.js +1 -0
  8. package/dist/ceilings.js.map +1 -1
  9. package/dist/cli.js +120 -21
  10. package/dist/cli.js.map +1 -1
  11. package/dist/exports.d.ts.map +1 -1
  12. package/dist/exports.js +6 -3
  13. package/dist/exports.js.map +1 -1
  14. package/dist/floors.d.ts +23 -0
  15. package/dist/floors.d.ts.map +1 -0
  16. package/dist/floors.js +203 -0
  17. package/dist/floors.js.map +1 -0
  18. package/dist/index.d.ts +4 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +3 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/ingest.d.ts +2 -0
  23. package/dist/ingest.d.ts.map +1 -1
  24. package/dist/ingest.js +14 -0
  25. package/dist/ingest.js.map +1 -1
  26. package/dist/report-json.d.ts.map +1 -1
  27. package/dist/report-json.js +15 -0
  28. package/dist/report-json.js.map +1 -1
  29. package/dist/report-md.js +95 -27
  30. package/dist/report-md.js.map +1 -1
  31. package/dist/temporal.d.ts +12 -0
  32. package/dist/temporal.d.ts.map +1 -1
  33. package/dist/temporal.js +245 -41
  34. package/dist/temporal.js.map +1 -1
  35. package/dist/types.d.ts +136 -5
  36. package/dist/types.d.ts.map +1 -1
  37. package/package.json +3 -2
  38. package/src/__tests__/base-floor.test.ts +405 -0
  39. package/src/__tests__/carrier-tree.test.ts +95 -0
  40. package/src/audit.ts +9 -3
  41. package/src/ceilings.ts +1 -0
  42. package/src/cli.ts +128 -22
  43. package/src/exports.ts +7 -3
  44. package/src/floors.ts +242 -0
  45. package/src/index.ts +8 -0
  46. package/src/ingest.ts +15 -0
  47. package/src/report-json.ts +15 -0
  48. package/src/report-md.ts +109 -31
  49. package/src/temporal.ts +279 -48
  50. package/src/types.ts +140 -6
package/src/cli.ts CHANGED
@@ -17,15 +17,16 @@
17
17
  * input error (no report was produced).
18
18
  */
19
19
 
20
- import { readFileSync } from "node:fs";
20
+ import { closeSync, openSync, readFileSync, readSync } from "node:fs";
21
21
  import { mkdir, mkdtemp, stat, writeFile } from "node:fs/promises";
22
22
  import { tmpdir } from "node:os";
23
23
  import { join, basename } from "node:path";
24
- import { parseCarrier, verifyCarrier } from "@mikeargento/bitgraph-verify";
25
- import type { VerificationPolicy } from "@mikeargento/bitgraph-verify";
24
+ import { CARRIER_MAGIC, CARRIER_VERSION_3, CARRIER_VERSION_4, baseHeaderFields, buildExport, parseCarrier, verifyCarrier } from "@mikeargento/bitgraph-verify";
25
+ import type { CarrierPayload, VerificationPolicy } from "@mikeargento/bitgraph-verify";
26
26
  import { auditToolVersion, computeExitFlags, runAudit } from "./audit.js";
27
27
  import { attestationTimestampMs } from "./attestation.js";
28
28
  import { exportRunClaims } from "./exports.js";
29
+ import { FLOOR_HEADER_VERSION } from "./ingest.js";
29
30
  import { buildJsonReport } from "./report-json.js";
30
31
  import { buildMarkdownReport } from "./report-md.js";
31
32
  import type { ExitFlags } from "./types.js";
@@ -62,11 +63,28 @@ function helpText(): string {
62
63
  USAGE_LINE,
63
64
  "",
64
65
  "The bundle may be a directory, a .tar archive, a .tar.gz/.tgz,",
65
- "or a single bitgraph-carrier/1 file (a file with its proof inside):",
66
- "a carrier is unpacked and audited as the bundle it carries, and its",
67
- "own verdict (TRUE / FALSE / UNDETERMINED, with the time window) is",
68
- "printed first.",
69
- "archive. The audit runs entirely offline: no RPC, no HTTP, no DNS.",
66
+ "or a single BitGraphed file (bitgraph-carrier/1, /2, /3 or /4: a file",
67
+ "with its proof inside; /4 is one member of a tree/1 BitGraph, unpacked",
68
+ "as the file and its own bitgraph-export/1): a carrier is unpacked and audited as the",
69
+ "bundle it carries, and its own verdict (TRUE / FALSE / UNDETERMINED,",
70
+ "with the time window) is printed first. The unpacked bundle holds the",
71
+ "committed bytes and proof.json, and the floor: for /1 and /2 the",
72
+ "Ethereum anchor proofs and their witnesses under ethereum-anchors/",
73
+ "(anchor-floor.json, anchor-floor.witness.json, and the closing",
74
+ "anchor's pair when the file carries it); for /3 the Base block the",
75
+ "proof signs as its floor, as base-floor/floor-header.json",
76
+ "(bitgraph-floor-header/1: chain, evmChainId, blockNumber, blockHash,",
77
+ "blockTimestamp, and the header's RLP as 0x hex). A /3 file has no",
78
+ "closing anchor: order after the record is the chain of proof hashes.",
79
+ "The audit runs entirely offline: no RPC, no HTTP, no DNS.",
80
+ "",
81
+ "Floors. A proof's floor is the block the enclave signs into it: an",
82
+ "Ethereum anchor (commit.slotAnchor, enclave v7 to v9) or a Base block",
83
+ "(commit.slotFloor, enclave v10). A Base floor bounds its proof not",
84
+ "before the block's time, never after anything. A floor header file",
85
+ "(bitgraph-floor-header/1) anywhere in the bundle is checked against",
86
+ "the floor a proof signs; without one, the time is the signed one and",
87
+ "confirming the block needs a Base lookup.",
70
88
  "",
71
89
  "Exports (bitgraph-export/1) anywhere in the bundle are found by their",
72
90
  "format field. Each is checked with verifyExport once per file in the",
@@ -122,6 +140,10 @@ function helpText(): string {
122
140
  " RLP malformation, an invalid candidate anchor, or an unmatched",
123
141
  " witness), or a ceiling in time (bitgraph-ceiling/1) that fails",
124
142
  " its check against its proof (wrong writer, root, block, header).",
143
+ " Also a floor problem: a proof that signs two floors (an Ethereum",
144
+ " anchor and a Base block), a Base floor that is malformed or off",
145
+ " Base mainnet's schedule, or a floor header file that contradicts",
146
+ " the floor a proof signs or matches none.",
125
147
  " A pending ceiling or a ceiling status note never sets a bit.",
126
148
  " Benign findings are reported but never set exit bits:",
127
149
  " duplicate copies, manifest advisories, unsafe paths, embedded",
@@ -256,6 +278,80 @@ function exitMeaning(flags: ExitFlags): string {
256
278
  return parts.join("; ");
257
279
  }
258
280
 
281
+ /**
282
+ * Write a carrier's floor into the unpacked bundle. /1 and /2: the Ethereum
283
+ * anchor proofs and witnesses under ethereum-anchors/, exactly as before.
284
+ * /3: the Base block the proof signs as its floor, as
285
+ * base-floor/floor-header.json (bitgraph-floor-header/1); no anchor proof
286
+ * stands under it and there is no closing anchor to write.
287
+ */
288
+ async function writeCarrierFloor(dir: string, payload: CarrierPayload): Promise<void> {
289
+ const floor = payload.floor;
290
+ if (floor.basis === "base-header") {
291
+ const fields = baseHeaderFields(floor.header);
292
+ const out = join(dir, "base-floor");
293
+ await mkdir(out);
294
+ await writeFile(
295
+ join(out, "floor-header.json"),
296
+ JSON.stringify(
297
+ {
298
+ version: FLOOR_HEADER_VERSION,
299
+ chain: "base",
300
+ evmChainId: 8453,
301
+ ...(fields !== null ? { blockNumber: fields.blockNumber, blockHash: fields.blockHash, blockTimestamp: fields.timestamp } : {}),
302
+ header: floor.header,
303
+ },
304
+ null,
305
+ 2
306
+ )
307
+ );
308
+ return;
309
+ }
310
+ const anchors = join(dir, "ethereum-anchors");
311
+ await mkdir(anchors);
312
+ await writeFile(join(anchors, "anchor-floor.json"), JSON.stringify(floor.anchor, null, 2));
313
+ await writeFile(join(anchors, "anchor-floor.witness.json"), JSON.stringify({ version: "bitgraph-anchor-witness/1", ...floor.witness }, null, 2));
314
+ if (payload.ceiling.status === "present") {
315
+ await writeFile(join(anchors, "anchor-ceiling.json"), JSON.stringify(payload.ceiling.anchor, null, 2));
316
+ await writeFile(join(anchors, "anchor-ceiling.witness.json"), JSON.stringify({ version: "bitgraph-anchor-witness/1", ...payload.ceiling.witness }, null, 2));
317
+ }
318
+ }
319
+
320
+ /**
321
+ * carrier/4: a tree member's file unpacks as the member and its own
322
+ * bitgraph-export/1, the shape a tree member always travels in, so the audit
323
+ * checks it with verifyExport like any export beside its file. The export
324
+ * carries the floor header (from the anchor's witness or the Base header) and
325
+ * the ceiling in time; the closing anchor and the settlement pointer have no
326
+ * place in export/1 and are judged in the carrier's own verdict printed above.
327
+ */
328
+ function memberExportOf(payload: CarrierPayload): string {
329
+ const floor = payload.floor;
330
+ const fields = floor.basis === "base-header" ? baseHeaderFields(floor.header) : null;
331
+ const exp = buildExport({
332
+ proof: payload.proof as never,
333
+ tree: { rootDocument: payload.tree!.rootDocument, member: payload.tree!.member },
334
+ floor: floor.basis === "base-header"
335
+ ? (fields !== null ? { chain: "base", blockNumber: fields.blockNumber, blockHash: fields.blockHash, header: floor.header.toLowerCase() } : null)
336
+ : { blockNumber: floor.witness.blockNumber, blockHash: floor.witness.blockHash.toLowerCase(), header: floor.witness.headerRlpHex.toLowerCase() },
337
+ ceiling: payload.ceilingInTime?.status === "present" ? (payload.ceilingInTime.sidecar as never) : { status: "pending" },
338
+ settlement: null,
339
+ });
340
+ return JSON.stringify(exp, null, 2) + "\n";
341
+ }
342
+
343
+ /** True when the file's last eight bytes are the BitGraphed file's magic. One positioned read. */
344
+ function tailIsCarrier(path: string, size: number): boolean {
345
+ const fd = openSync(path, "r");
346
+ try {
347
+ const tail = Buffer.alloc(CARRIER_MAGIC.length);
348
+ readSync(fd, tail, 0, tail.length, size - tail.length);
349
+ return tail.equals(Buffer.from(CARRIER_MAGIC));
350
+ } finally {
351
+ closeSync(fd);
352
+ }
353
+ }
354
+
259
355
  async function main(): Promise<number> {
260
356
  let parsed: ParsedArgs | "help";
261
357
  try {
@@ -286,8 +382,8 @@ async function main(): Promise<number> {
286
382
  }
287
383
 
288
384
  /* A single carrier file: unpack it to a temp bundle (the committed bytes,
289
- the proof, the floor anchor and witness, the ceiling pair when present)
290
- and audit THAT, after printing the carrier's own offline verdict. The
385
+ the proof, and the floor: for /1 and /2 the floor anchor and witness and
386
+ the ceiling pair when present; for /3 the Base floor header) and audit THAT, after printing the carrier's own offline verdict. The
291
387
  temp dir is the audit's input, so the reports describe exactly what the
292
388
  file carries; everything else about the run is unchanged. Detection is
293
389
  from the last 8 bytes only, so no ordinary bundle path changes behaviour. */
@@ -297,7 +393,10 @@ async function main(): Promise<number> {
297
393
  const info = await stat(parsed.bundlePath);
298
394
  const lower = parsed.bundlePath.toLowerCase();
299
395
  const isArchive = lower.endsWith(".tar") || lower.endsWith(".tar.gz") || lower.endsWith(".tgz");
300
- if (info.isFile() && !isArchive && info.size >= 26) {
396
+ // A tree member placed in a container is a tar, and its BitGraphed file (carrier/4) is named
397
+ // as one: the carrier's tail decides before the extension does. A bundle tar never ends in it.
398
+ const endsInCarrier = info.isFile() && info.size >= 26 && tailIsCarrier(parsed.bundlePath, info.size);
399
+ if (info.isFile() && (!isArchive || endsInCarrier) && info.size >= 26) {
301
400
  const bytes = new Uint8Array(readFileSync(parsed.bundlePath));
302
401
  const parsedCarrier = parseCarrier(bytes);
303
402
  if (parsedCarrier.kind !== "none") {
@@ -316,11 +415,19 @@ async function main(): Promise<number> {
316
415
  ((verdict.payload.proof as { environment?: { attestation?: { reportB64?: string } } }).environment?.attestation?.reportB64) ?? ""
317
416
  )
318
417
  : null;
418
+ // carrier/3 (enclave v10): the floor is a Base block and no closing
419
+ // anchor exists; order after the record is the chain of proof hashes.
420
+ const v3 = verdict.payload?.carrier === CARRIER_VERSION_3 || b?.notBefore.chain === "base";
421
+ const member = verdict.member ?? null;
422
+ const chainWord = b?.notBefore.chain === "base" ? "Base" : "Ethereum";
319
423
  const lines = [
320
424
  `carrier: ${verdict.verdict}${verdict.carrier === "corrupt" ? " (block unreadable: corrupted, not judged)" : ""}`,
321
- b ? ` no earlier than: block ${b.notBefore.blockNumber}${b.notBefore.timestamp !== null ? ` (mined ${new Date(b.notBefore.timestamp * 1000).toISOString()})` : ""}` : null,
425
+ member ? ` tree member: leaf ${member.index} of ${member.count}${member.placement === "as-is" ? " (kept as is: recorded after the floor, the bytes themselves are not dated)" : ` (${member.placement})`}` : null,
426
+ b ? ` no earlier than: ${chainWord} block ${b.notBefore.blockNumber}${b.notBefore.timestamp !== null ? ` (${v3 ? "stamped" : "mined"} ${new Date(b.notBefore.timestamp * 1000).toISOString()})` : ""}` : null,
322
427
  attestedMs !== null ? ` committed: ${new Date(attestedMs).toISOString()} per the enclave platform's signed clock` : null,
323
- b ? ` committed before: ${b.notAfter === null ? "NOT FETCHED (the closing anchor is not inside this file)" : `the anchoring of block ${b.notAfter.blockNumber}${b.notAfter.timestamp !== null ? ` (that block mined ${new Date(b.notAfter.timestamp * 1000).toISOString()})` : ""}`}` : null,
428
+ b && v3
429
+ ? " committed before: no ceiling in position (none exists for a Base floor: order after the record is the chain of proof hashes)"
430
+ : b ? ` committed before: ${b.notAfter === null ? "NOT FETCHED (the closing anchor is not inside this file)" : `the anchoring of block ${b.notAfter.blockNumber}${b.notAfter.timestamp !== null ? ` (that block mined ${new Date(b.notAfter.timestamp * 1000).toISOString()})` : ""}`}` : null,
324
431
  ...verdict.reasons.map((r) => ` - ${r}`),
325
432
  ].filter((l): l is string => l !== null);
326
433
  process.stdout.write(lines.join("\n") + "\n");
@@ -330,14 +437,12 @@ async function main(): Promise<number> {
330
437
  const dir = await mkdtemp(join(tmpdir(), "bitgraph-carrier-"));
331
438
  const name = basename(parsed.bundlePath).replace(/\.bitgraph(\.[^.]+)$/i, "$1").replace(/\.bitgraph$/i, "") || "artifact";
332
439
  await writeFile(join(dir, name), parsedCarrier.inner);
333
- await writeFile(join(dir, "proof.json"), JSON.stringify(parsedCarrier.payload.proof, null, 2));
334
- const anchors = join(dir, "ethereum-anchors");
335
- await mkdir(anchors);
336
- await writeFile(join(anchors, "anchor-floor.json"), JSON.stringify(parsedCarrier.payload.floor.anchor, null, 2));
337
- await writeFile(join(anchors, "anchor-floor.witness.json"), JSON.stringify({ version: "bitgraph-anchor-witness/1", ...parsedCarrier.payload.floor.witness }, null, 2));
338
- if (parsedCarrier.payload.ceiling.status === "present") {
339
- await writeFile(join(anchors, "anchor-ceiling.json"), JSON.stringify(parsedCarrier.payload.ceiling.anchor, null, 2));
340
- await writeFile(join(anchors, "anchor-ceiling.witness.json"), JSON.stringify({ version: "bitgraph-anchor-witness/1", ...parsedCarrier.payload.ceiling.witness }, null, 2));
440
+ if (parsedCarrier.payload.carrier === CARRIER_VERSION_4) {
441
+ // A tree member: its signed digest names the root document, so it travels as the file and its own export.
442
+ await writeFile(join(dir, `${name}.bitgraph.json`), memberExportOf(parsedCarrier.payload));
443
+ } else {
444
+ await writeFile(join(dir, "proof.json"), JSON.stringify(parsedCarrier.payload.proof, null, 2));
445
+ await writeCarrierFloor(dir, parsedCarrier.payload);
341
446
  }
342
447
  bundlePath = dir;
343
448
  }
@@ -393,6 +498,7 @@ async function main(): Promise<number> {
393
498
  for (const line of c.settlement?.lines ?? []) process.stdout.write(` ${line}\n`);
394
499
  }
395
500
  for (const s of result.ceilings?.statuses ?? []) process.stdout.write(`ceiling ${s.status} ${s.path}: ${s.note}\n`);
501
+ for (const p of result.temporal.floorProblems ?? []) process.stdout.write(`floor PROBLEM ${p.code}${p.path !== undefined ? ` ${p.path}` : ""}: ${p.message}\n`);
396
502
  for (const e of result.exports?.checks ?? []) {
397
503
  if (e.status !== "checked") {
398
504
  process.stdout.write(`export NOT CHECKED ${e.path}: ${e.reason ?? e.status}\n`);
@@ -409,7 +515,7 @@ async function main(): Promise<number> {
409
515
  const c = firstClaims.find((x) => x.id === id);
410
516
  return c ? `not established (${c.result}: ${c.detail})` : "not established";
411
517
  };
412
- process.stdout.write(` floor: ${t.floor ? `committed bytes finished after Ethereum block ${t.floor.blockNumber} (mined ${when(t.floor.blockTimestamp)})` : why("floor.header")}\n`);
518
+ process.stdout.write(` floor: ${t.floor ? `committed bytes finished after ${t.floor.chain === "base" ? "Base" : "Ethereum"} block ${t.floor.blockNumber} (${t.floor.chain === "base" ? "stamped" : "mined"} ${when(t.floor.blockTimestamp)})` : why("floor.header")}\n`);
413
519
  process.stdout.write(` ceiling on Base: ${t.ceilingBase ? `existed by Base block ${t.ceilingBase.blockNumber} (${when(t.ceilingBase.blockTimestamp)})${t.ceilingBase.provisional ? ", provisional until checked against Base" : ""}` : why("ceiling.base")}\n`);
414
520
  process.stdout.write(` ceiling on Ethereum: ${t.ceilingEthereum ? `existed by Ethereum block ${t.ceilingEthereum.blockNumber} (${when(t.ceilingEthereum.blockTimestamp)})` : why("ceiling.ethereum")}\n`);
415
521
  }
package/src/exports.ts CHANGED
@@ -24,8 +24,9 @@
24
24
  * about its file) with their places in verifyExport's order, and
25
25
  * exportRunClaims puts a run's whole list back together. The three time
26
26
  * claims are kept apart, never merged: the floor (the committed bytes were
27
- * finished after Ethereum block N; an as-is leaf has no floor), the ceiling
28
- * on Base (the record existed by Base block B, provisional until B is
27
+ * finished after the block the proof signs: Ethereum block N for an anchor
28
+ * floor, Base block N for a Base floor, enclave v10; an as-is leaf has no
29
+ * floor), the ceiling on Base (the record existed by Base block B, provisional until B is
29
30
  * checked against Base) and the ceiling on Ethereum (the record existed by
30
31
  * Ethereum block H). An export with any FALSE claim fails the audit (exit
31
32
  * bit 1), as a bad proof does; its attestation claims count, because an
@@ -394,7 +395,10 @@ function claimKey(c: ExportClaimRecord): string {
394
395
 
395
396
  function copyTimes(t: ExportVerifyResult["times"]): ExportTimes {
396
397
  return {
397
- floor: t.floor === null ? null : { blockNumber: t.floor.blockNumber, blockHash: t.floor.blockHash, blockTimestamp: t.floor.blockTimestamp },
398
+ floor:
399
+ t.floor === null
400
+ ? null
401
+ : { ...(t.floor.chain === "base" ? { chain: "base" as const } : {}), blockNumber: t.floor.blockNumber, blockHash: t.floor.blockHash, blockTimestamp: t.floor.blockTimestamp },
398
402
  ceilingBase:
399
403
  t.ceilingBase === null
400
404
  ? null
package/src/floors.ts ADDED
@@ -0,0 +1,242 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * bitgraph-audit signed floors (enclave v10)
5
+ *
6
+ * From enclave v10 a proof's floor is a Base block the enclave signs into the
7
+ * proof as commit.slotFloor { chain: "base", evmChainId: 8453, blockNumber,
8
+ * blockHash, blockTimestamp }, one per proof, instead of an Ethereum anchor
9
+ * (commit.slotAnchor, read through the anchor proofs of the chain). Every
10
+ * floor is read through signedFloorOf from bitgraph-verify, which refuses a
11
+ * proof that signs both kinds: such a proof is ambiguous and nothing is read
12
+ * from it as a floor.
13
+ *
14
+ * What a Base floor gives the temporal stage: a NOT-BEFORE for the proof that
15
+ * signs it, grounded in block-hash unpredictability (the block hash did not
16
+ * exist before the block, and the proof signs it). Never a not-after: a later
17
+ * proof's floor block can predate this proof, so a floor bounds nothing
18
+ * before it.
19
+ *
20
+ * The block time. Base mainnet stamps every block by its height, and the
21
+ * enclave signs the time it read from a header it hashed itself. When the
22
+ * bundle carries that header (a floor header file, bitgraph-floor-header/1,
23
+ * as the carrier/3 unpacker writes it; or the floor inside a ceiling file or
24
+ * an export) it is checked with checkFloorHeader: keccak-256 to the signed
25
+ * hash, the signed number and time, Base mainnet's schedule. Without one the
26
+ * time is the signed one, which must still be on Base mainnet's schedule for
27
+ * the signed number, and confirming the block itself needs a Base lookup,
28
+ * which this offline audit never makes.
29
+ *
30
+ * A floor stamped after the proof's own attestation document is withheld as a
31
+ * bound (floorTimeIsBound): the record did not exist before that block, but
32
+ * the block's time cannot be a "not before" for a record already attested.
33
+ *
34
+ * Proofs with no slotFloor are not read here at all: bundles from before the
35
+ * cutover audit exactly as before.
36
+ */
37
+
38
+ import {
39
+ baseHeaderFields,
40
+ checkFloorHeader,
41
+ evmHexToBytes,
42
+ floorTimeIsBound,
43
+ onBaseSchedule,
44
+ signedFloorOf,
45
+ } from "@mikeargento/bitgraph-verify";
46
+ import type { SignedFloor } from "@mikeargento/bitgraph-verify";
47
+ import { attestationTimestampMs } from "./attestation.js";
48
+ import type { FloorProblem, IngestResult, ObservedProof, SignedFloorRecord } from "./types.js";
49
+
50
+ /** A Base floor that bounds the proof signing it. */
51
+ export interface FloorEvidence {
52
+ /** The proof that signs the floor. */
53
+ proofHash: string;
54
+ blockNumber: number;
55
+ blockHash: string;
56
+ /** Unix seconds: the signed time, equal to the checked header's when one was carried. */
57
+ timestamp: number;
58
+ timeSource: "header" | "signed";
59
+ }
60
+
61
+ export interface FloorReading {
62
+ /** Base floors usable as not-before bounds, keyed by the proof that signs them. */
63
+ bounds: Map<string, FloorEvidence>;
64
+ /** Every Base floor a proof signs, bounding or withheld, in observation order. */
65
+ records: SignedFloorRecord[];
66
+ problems: FloorProblem[];
67
+ }
68
+
69
+ interface HeaderCandidate {
70
+ path: string;
71
+ raw: Uint8Array;
72
+ /** Only floor header files are judged here; ceilings and exports are judged by their own stages. */
73
+ fromFloorFile: boolean;
74
+ }
75
+
76
+ function record(value: unknown): Record<string, unknown> | null {
77
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
78
+ }
79
+
80
+ function iso(unix: number): string {
81
+ return new Date(unix * 1000).toISOString();
82
+ }
83
+
84
+ function firstPath(p: ObservedProof): string | undefined {
85
+ return p.sources[0]?.path;
86
+ }
87
+
88
+ /** Read every Base floor the bundle's proofs sign, and the headers that check them. */
89
+ export function readSignedFloors(ingest: IngestResult): FloorReading {
90
+ const problems: FloorProblem[] = [];
91
+ const records: SignedFloorRecord[] = [];
92
+ const bounds = new Map<string, FloorEvidence>();
93
+
94
+ // The Base floors the proofs sign, by block hash (to match header files).
95
+ const signedHashes = new Set<string>();
96
+ for (const p of ingest.proofs) {
97
+ const f = p.proof.commit?.slotFloor as { blockHash?: unknown } | undefined;
98
+ if (f !== undefined && typeof f.blockHash === "string") signedHashes.add(f.blockHash.toLowerCase());
99
+ }
100
+
101
+ // Headers in the bundle, by the hash their bytes compute to.
102
+ const headers = new Map<string, HeaderCandidate[]>();
103
+ const add = (hash: string, c: HeaderCandidate): void => {
104
+ const list = headers.get(hash) ?? [];
105
+ list.push(c);
106
+ headers.set(hash, list);
107
+ };
108
+ for (const file of ingest.floorHeaders ?? []) {
109
+ const json = file.json;
110
+ const header = json["header"];
111
+ const fields = typeof header === "string" ? baseHeaderFields(header) : null;
112
+ if (json["chain"] !== "base" || fields === null) {
113
+ problems.push({
114
+ code: "floor-header-malformed",
115
+ path: file.path,
116
+ message:
117
+ json["chain"] !== "base"
118
+ ? `the floor header file names chain ${JSON.stringify(json["chain"])}; only a Base header (chain "base") is a floor header`
119
+ : "the floor header file carries no readable Base block header",
120
+ });
121
+ continue;
122
+ }
123
+ const declared = typeof json["blockHash"] === "string" ? (json["blockHash"] as string).toLowerCase() : undefined;
124
+ if (declared !== undefined && declared !== fields.blockHash) {
125
+ problems.push({
126
+ code: "floor-header-mismatch",
127
+ path: file.path,
128
+ message: `the header in this file hashes to ${fields.blockHash}, not to the block it names (${declared})`,
129
+ });
130
+ continue;
131
+ }
132
+ if (!signedHashes.has(fields.blockHash)) {
133
+ problems.push({
134
+ code: "floor-header-unmatched",
135
+ path: file.path,
136
+ message: `the header is Base block ${fields.blockNumber} (${fields.blockHash}), which no proof in this bundle signs as its floor`,
137
+ });
138
+ continue;
139
+ }
140
+ add(fields.blockHash, { path: file.path, raw: evmHexToBytes(header as string), fromFloorFile: true });
141
+ }
142
+ // The floor a ceiling file or an export carries, when it is a Base header.
143
+ const carried = (path: string, floor: Record<string, unknown> | null, field: string): void => {
144
+ if (floor === null || floor["chain"] !== "base" || typeof floor[field] !== "string") return;
145
+ const fields = baseHeaderFields(floor[field] as string);
146
+ if (fields === null || !signedHashes.has(fields.blockHash)) return;
147
+ add(fields.blockHash, { path, raw: evmHexToBytes(floor[field] as string), fromFloorFile: false });
148
+ };
149
+ for (const c of ingest.ceilings ?? []) carried(c.path, record(c.json["floor"]), "blockHeader");
150
+ for (const e of ingest.exports ?? []) if (e.status === "ok") carried(e.path, record(e.json["floor"]), "header");
151
+
152
+ for (const p of ingest.proofs) {
153
+ const commit = p.proof.commit as unknown as Record<string, unknown> | undefined;
154
+ if (commit === undefined || commit["slotFloor"] === undefined) continue;
155
+ const path = firstPath(p);
156
+ let floor: SignedFloor | null;
157
+ try {
158
+ floor = signedFloorOf(p.proof);
159
+ } catch (e) {
160
+ const both = commit["slotAnchor"] !== undefined;
161
+ problems.push({
162
+ code: both ? "floor-ambiguous" : "floor-malformed",
163
+ proofHash: p.proofHash,
164
+ ...(path !== undefined ? { path } : {}),
165
+ message: both
166
+ ? "the proof signs two floors (commit.slotAnchor, an Ethereum anchor, and commit.slotFloor, a Base block); it is ambiguous and neither is read as its floor"
167
+ : `the proof's commit.slotFloor is not a Base floor: ${(e as Error).message}`,
168
+ });
169
+ continue;
170
+ }
171
+ if (floor === null || floor.chain !== "base" || floor.blockTimestamp === undefined) continue;
172
+ const base = {
173
+ proofHash: p.proofHash,
174
+ chain: "base" as const,
175
+ blockNumber: floor.blockNumber,
176
+ blockHash: floor.blockHash,
177
+ blockTimestamp: floor.blockTimestamp,
178
+ };
179
+ const withheld = (reason: string, header: SignedFloorRecord["header"], headerPath?: string): void => {
180
+ records.push({ ...base, header, ...(headerPath !== undefined ? { headerPath } : {}), bound: "withheld", withheldReason: reason });
181
+ };
182
+
183
+ if (!onBaseSchedule(floor.blockNumber, floor.blockTimestamp)) {
184
+ const reason = `the signed time of Base block ${floor.blockNumber} (${floor.blockTimestamp}) is not Base mainnet's schedule for that block`;
185
+ problems.push({ code: "floor-off-schedule", proofHash: p.proofHash, ...(path !== undefined ? { path } : {}), message: reason });
186
+ withheld(reason, "not-carried");
187
+ continue;
188
+ }
189
+
190
+ // A header in the bundle for the signed block: every floor header file
191
+ // naming it must hold; the first that holds dates the floor.
192
+ let checkedPath: string | undefined;
193
+ let mismatch: string | undefined;
194
+ for (const c of headers.get(floor.blockHash) ?? []) {
195
+ const r = checkFloorHeader(floor, c.raw, "base");
196
+ if (r.ok) {
197
+ checkedPath ??= c.path;
198
+ } else if (c.fromFloorFile) {
199
+ mismatch = `${c.path}: ${r.reason}`;
200
+ problems.push({
201
+ code: "floor-header-mismatch",
202
+ proofHash: p.proofHash,
203
+ path: c.path,
204
+ message: `the floor header does not match the Base floor the proof signs: ${r.reason}`,
205
+ });
206
+ }
207
+ }
208
+ const header: SignedFloorRecord["header"] = checkedPath !== undefined ? "checked" : "not-carried";
209
+ if (mismatch !== undefined) {
210
+ withheld(`a floor header in the bundle contradicts the signed floor (${mismatch})`, header, checkedPath);
211
+ continue;
212
+ }
213
+ if (p.verification?.status === "failed") {
214
+ withheld("the proof does not verify, so the floor in it is not a signed one", header, checkedPath);
215
+ continue;
216
+ }
217
+ const attestedMs = attestationTimestampMs(
218
+ ((p.proof as { environment?: { attestation?: { reportB64?: string } } }).environment?.attestation?.reportB64) ?? ""
219
+ );
220
+ const timeOk = floorTimeIsBound(floor.blockTimestamp, attestedMs);
221
+ if (!timeOk.ok) {
222
+ withheld(timeOk.reason, header, checkedPath);
223
+ continue;
224
+ }
225
+ records.push({ ...base, header, ...(checkedPath !== undefined ? { headerPath: checkedPath } : {}), bound: "not-before" });
226
+ bounds.set(p.proofHash, {
227
+ proofHash: p.proofHash,
228
+ blockNumber: floor.blockNumber,
229
+ blockHash: floor.blockHash,
230
+ timestamp: floor.blockTimestamp,
231
+ timeSource: checkedPath !== undefined ? "header" : "signed",
232
+ });
233
+ }
234
+ return { bounds, records, problems };
235
+ }
236
+
237
+ /** The sentence a Base floor bound states about its block time, shared by the reports. */
238
+ export function baseFloorTimeSentence(blockNumber: number | string, timestamp: number, timeSource: "header" | "signed"): string {
239
+ return timeSource === "header"
240
+ ? `Base block ${blockNumber} is stamped ${iso(timestamp)}; its header is in the bundle and was checked against the signed block hash, number and time.`
241
+ : `Base block ${blockNumber} is stamped ${iso(timestamp)} as the proof signs it, on Base mainnet's schedule for that block; no header for it is in the bundle, so confirming the block needs a Base lookup.`;
242
+ }
package/src/index.ts CHANGED
@@ -65,6 +65,10 @@ export type {
65
65
  TemporalSegment,
66
66
  AnchorOrderedPair,
67
67
  TemporalAnalysis,
68
+ SignedFloorRecord,
69
+ FloorProblem,
70
+ FloorProblemCode,
71
+ FloorHeaderFile,
68
72
  AttestationCheck,
69
73
  NitroValidationOptions,
70
74
  NitroValidationResult,
@@ -109,6 +113,10 @@ export { identifyAnchors } from "./anchors.js";
109
113
  export { verifyAnchorWitnesses, verifyAnchorWitness } from "./witness.js";
110
114
 
111
115
  export { deriveTemporalBounds } from "./temporal.js";
116
+ // Base floors (enclave v10): the floor each proof signs, read through signedFloorOf.
117
+ export { readSignedFloors } from "./floors.js";
118
+ export type { FloorEvidence, FloorReading } from "./floors.js";
119
+ export { FLOOR_HEADER_VERSION } from "./ingest.js";
112
120
  export { verifyCeilings, BITGRAPH_CEILING_WRITER, BASE_MAINNET_CHAIN_ID } from "./ceilings.js";
113
121
  export type { CeilingAuditOptions } from "./ceilings.js";
114
122
 
package/src/ingest.ts CHANGED
@@ -20,6 +20,10 @@
20
20
  * exactly like a proof file. A file that declares another bitgraph-export
21
21
  * format, or lacks an export's structure, is listed as rejected.
22
22
  *
23
+ * A floor header file (bitgraph-floor-header/1, found by its version field)
24
+ * is evidence too: the header of the Base block a proof signs as its floor
25
+ * (commit.slotFloor, enclave v10), listed for the temporal stage.
26
+ *
23
27
  * Memory: archives are never unpacked to disk and never loaded whole.
24
28
  * Every entry is hashed incrementally as it streams. Only small JSON
25
29
  * candidates (at most MAX_CANDIDATE_JSON_BYTES) are buffered for parsing,
@@ -51,6 +55,7 @@ import { combineEntryDigests } from "./contents-hash.js";
51
55
  import type {
52
56
  AnchorWitnessFile,
53
57
  CeilingFile,
58
+ FloorHeaderFile,
54
59
  ArtifactRecord,
55
60
  AuditFinding,
56
61
  BundleManifest,
@@ -108,6 +113,8 @@ const BUNDLE_VERSION = "bitgraph-bundle/1";
108
113
  const WITNESS_VERSION = "bitgraph-anchor-witness/1";
109
114
  const CEILING_VERSION_TAG = "bitgraph-ceiling/1";
110
115
  const CEILING_STATUS_VERSION_TAG = "bitgraph-ceiling-status/1";
116
+ /** A Base floor block's header, beside the proof that signs it (the carrier/3 unpacker writes these). */
117
+ export const FLOOR_HEADER_VERSION = "bitgraph-floor-header/1";
111
118
  /** Every export format starts with this; only EXPORT_FORMAT ("bitgraph-export/1") is checked. */
112
119
  const EXPORT_FORMAT_PREFIX = "bitgraph-export/";
113
120
 
@@ -369,6 +376,7 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
369
376
  const witnesses: AnchorWitnessFile[] = [];
370
377
  const ceilings: CeilingFile[] = [];
371
378
  const ceilingStatuses: CeilingFile[] = [];
379
+ const floorHeaders: FloorHeaderFile[] = [];
372
380
  const exportFiles: ExportFile[] = [];
373
381
  const artifactsByHex = new Map<string, ArtifactRecord>();
374
382
  let manifest: ManifestReport | undefined;
@@ -481,6 +489,11 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
481
489
 
482
490
  // A ceiling in time travels beside its proof: evidence, never an artifact.
483
491
  const pv = parsed !== undefined ? (parsed as Record<string, unknown>)["version"] : undefined;
492
+ // So does a Base floor block's header: evidence for the temporal stage.
493
+ if (pv === FLOOR_HEADER_VERSION) {
494
+ floorHeaders.push({ path: entry.path, fileSha256Hex: entry.sha256Hex, json: parsed as Record<string, unknown> });
495
+ continue;
496
+ }
484
497
  if (pv === CEILING_VERSION_TAG || pv === CEILING_STATUS_VERSION_TAG) {
485
498
  (pv === CEILING_VERSION_TAG ? ceilings : ceilingStatuses).push({
486
499
  path: entry.path,
@@ -517,6 +530,7 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
517
530
  unsupportedVersion: unsupportedVersions.length,
518
531
  artifacts: artifacts.length,
519
532
  witnesses: witnesses.length,
533
+ ...(floorHeaders.length > 0 ? { floorHeaders: floorHeaders.length } : {}),
520
534
  ceilings: ceilings.length + ceilingStatuses.length,
521
535
  exports: exportFiles.length,
522
536
  skippedUnsafePaths,
@@ -531,6 +545,7 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
531
545
  unsupportedVersions,
532
546
  artifacts,
533
547
  witnesses,
548
+ ...(floorHeaders.length > 0 ? { floorHeaders } : {}),
534
549
  ceilings,
535
550
  ceilingStatuses,
536
551
  exports: exportFiles,
@@ -128,6 +128,8 @@ export function buildJsonReport(result: AuditResult): AuditJsonReport {
128
128
  segments: result.temporal.segments,
129
129
  verifiedAnchorProofHashes: result.temporal.verifiedAnchorProofHashes,
130
130
  unverifiedAnchorProofHashes: result.temporal.unverifiedAnchorProofHashes,
131
+ ...(result.temporal.signedFloors !== undefined ? { signedFloors: result.temporal.signedFloors } : {}),
132
+ ...(result.temporal.floorProblems !== undefined ? { floorProblems: result.temporal.floorProblems } : {}),
131
133
  },
132
134
  summary,
133
135
  };
@@ -287,6 +289,8 @@ function buildSummary(
287
289
  if (proof.measurement !== undefined) measurements.add(proof.measurement);
288
290
  }
289
291
 
292
+ const floors = result.temporal.signedFloors ?? [];
293
+ const floorProblems = result.temporal.floorProblems ?? [];
290
294
  const segmentCount = (status: TemporalSegmentStatus): number =>
291
295
  result.temporal.segments.filter((s) => s.status === status).length;
292
296
 
@@ -333,6 +337,17 @@ function buildSummary(
333
337
  segmentsLowerBounded: segmentCount("lower-bounded"),
334
338
  segmentsUpperBounded: segmentCount("upper-bounded"),
335
339
  segmentsUnanchored: segmentCount("ordered-but-unanchored"),
340
+ ...(floors.length > 0 || floorProblems.length > 0
341
+ ? {
342
+ baseFloors: {
343
+ signed: floors.length,
344
+ bounding: floors.filter((f) => f.bound === "not-before").length,
345
+ headersChecked: floors.filter((f) => f.header === "checked").length,
346
+ withheld: floors.filter((f) => f.bound === "withheld").length,
347
+ problems: floorProblems.length,
348
+ },
349
+ }
350
+ : {}),
336
351
  },
337
352
  ...(exportChecks.length > 0
338
353
  ? {