@mikeargento/bitgraph-verify 1.26.0 → 1.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/block-read.test.d.ts +8 -0
- package/dist/__tests__/block-read.test.d.ts.map +1 -0
- package/dist/__tests__/block-read.test.js +104 -0
- package/dist/__tests__/block-read.test.js.map +1 -0
- package/dist/__tests__/epoch-genesis.test.js +8 -1
- package/dist/__tests__/epoch-genesis.test.js.map +1 -1
- package/dist/__tests__/measurements-windows.test.d.ts +7 -0
- package/dist/__tests__/measurements-windows.test.d.ts.map +1 -0
- package/dist/__tests__/measurements-windows.test.js +27 -0
- package/dist/__tests__/measurements-windows.test.js.map +1 -0
- package/dist/__tests__/timeline-bundle.test.d.ts +14 -0
- package/dist/__tests__/timeline-bundle.test.d.ts.map +1 -0
- package/dist/__tests__/timeline-bundle.test.js +448 -0
- package/dist/__tests__/timeline-bundle.test.js.map +1 -0
- package/dist/attested.d.ts +4 -2
- package/dist/attested.d.ts.map +1 -1
- package/dist/attested.js +40 -6
- package/dist/attested.js.map +1 -1
- package/dist/block-read.d.ts +66 -0
- package/dist/block-read.d.ts.map +1 -0
- package/dist/block-read.js +151 -0
- package/dist/block-read.js.map +1 -0
- package/dist/ceiling.d.ts +2 -2
- package/dist/ceiling.d.ts.map +1 -1
- package/dist/ceiling.js +8 -4
- package/dist/ceiling.js.map +1 -1
- package/dist/epoch-genesis.d.ts +8 -0
- package/dist/epoch-genesis.d.ts.map +1 -1
- package/dist/epoch-genesis.js +11 -1
- package/dist/epoch-genesis.js.map +1 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/measurements.d.ts +25 -0
- package/dist/measurements.d.ts.map +1 -1
- package/dist/measurements.js +34 -0
- package/dist/measurements.js.map +1 -1
- package/dist/timeline-bundle.d.ts +129 -0
- package/dist/timeline-bundle.d.ts.map +1 -0
- package/dist/timeline-bundle.js +271 -0
- package/dist/timeline-bundle.js.map +1 -0
- package/dist/timeline-export.d.ts +47 -0
- package/dist/timeline-export.d.ts.map +1 -0
- package/dist/timeline-export.js +102 -0
- package/dist/timeline-export.js.map +1 -0
- package/package.json +1 -1
- package/src/__tests__/block-read.test.ts +119 -0
- package/src/__tests__/epoch-genesis.test.ts +9 -1
- package/src/__tests__/fixtures/v13/genesis-file.json +12 -0
- package/src/__tests__/fixtures/v13/proof-2.json +37 -0
- package/src/__tests__/fixtures/v13/proof-4.json +38 -0
- package/src/__tests__/fixtures/v13/proof-6.json +38 -0
- package/src/__tests__/measurements-windows.test.ts +31 -0
- package/src/__tests__/timeline-bundle.test.ts +495 -0
- package/src/attested.ts +39 -9
- package/src/block-read.ts +177 -0
- package/src/ceiling.ts +9 -6
- package/src/epoch-genesis.ts +12 -2
- package/src/index.ts +12 -2
- package/src/measurements.ts +51 -0
- package/src/timeline-bundle.ts +351 -0
- package/src/timeline-export.ts +121 -0
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
// Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* bitgraph-timeline-bundle/1: everything a file's place on the block timeline rests on, in one object.
|
|
5
|
+
*
|
|
6
|
+
* Block reads (block-read.ts) and files are bound on one counter sequence. A bundle holds an unbroken run of proofs
|
|
7
|
+
* around the file's, in counter order, the block files of the block reads in it, and the epoch's genesis record,
|
|
8
|
+
* wherever it falls in the epoch. Each proof carries its own AWS Nitro attestation, so nothing else about the enclave
|
|
9
|
+
* is needed. The first proof is a block read; its chain is the chain the file is bracketed on.
|
|
10
|
+
*
|
|
11
|
+
* The bracket is chosen by the verifier, on that chain, from reads the chain confirms (hash on its canonical chain,
|
|
12
|
+
* and every field of the block file equal to the chain's answer):
|
|
13
|
+
*
|
|
14
|
+
* floor of the confirmed reads before the file whose block timestamp, on the canonical chain, is at or before
|
|
15
|
+
* the file's own Nitro time, the one with the highest block number. Position does not decide it, so a
|
|
16
|
+
* file of an ancient block bound just before the file cannot loosen its floor, and a read stamped a little
|
|
17
|
+
* ahead is passed over rather than failing the bundle. A stale floor is allowed: looser, still true. The
|
|
18
|
+
* claim is causal: the file was bound after block A was produced, because A's hash cannot be known before
|
|
19
|
+
* A exists.
|
|
20
|
+
* ceiling the first confirmed read after the file whose block timestamp, on the canonical chain, is strictly after
|
|
21
|
+
* the file's own Nitro time (no allowance), whose block number is above the floor's, and whose own lag is
|
|
22
|
+
* within the chain's limits. The claim is: the file was bound at Nitro hardware time T, before block B's
|
|
23
|
+
* timestamp; the Nitro clock was checked against the chain at block B's read (lag within limits).
|
|
24
|
+
*
|
|
25
|
+
* Anyone can bind a block file, of any block, at any time, and a bundle need not show every read. The ceiling rule
|
|
26
|
+
* holds anyway: it compares the chain's own timestamp for B with the hardware time of the file, so a re-bound or
|
|
27
|
+
* injected file of an older block is never a ceiling, whatever reads are shown or hidden. Reads that fail the rule
|
|
28
|
+
* are passed over and the next one qualifies (a wider bracket, still true); when none does, the ceiling is
|
|
29
|
+
* unconfirmed. A floor outside the lag limits is flagged and still used.
|
|
30
|
+
*
|
|
31
|
+
* Only Base and Ethereum are read: their block timestamps follow real time closely. Ethereum is the fallback that keeps
|
|
32
|
+
* brackets coming while Base is down. Lag is signed: a read's own Nitro time minus its block's timestamp, from 2 s
|
|
33
|
+
* early (timestamps are whole seconds) to 5 s late on Base and 60 s late on Ethereum. A read outside that is flagged
|
|
34
|
+
* and is never a ceiling.
|
|
35
|
+
*
|
|
36
|
+
* Also checked, without any network: every proof in full (verifyAttested); the run unbroken (verifyStretch); every
|
|
37
|
+
* block file binds to its proof and names its epoch; the floor's, the file's and the ceiling's Nitro times in order;
|
|
38
|
+
* the genesis record of this epoch, under the same key. With lookups, the genesis write must be on Base. A file bound
|
|
39
|
+
* before its epoch's genesis record is pre-genesis: until then its clock check rests on Nitro alone. A bundle without
|
|
40
|
+
* its epoch's genesis record is never verified.
|
|
41
|
+
*
|
|
42
|
+
* Status: "verified" when everything was checked and passed; "unconfirmed" when nothing failed but something could
|
|
43
|
+
* not be settled (a chain not asked or not answering, no qualifying ceiling in the bundle, no genesis record);
|
|
44
|
+
* "failed" otherwise.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
import type { BitGraphProof } from "./types.js";
|
|
48
|
+
import { verifyAttested, type AttestedOptions, type AttestedResult } from "./attested.js";
|
|
49
|
+
import { createVerificationContext } from "./verifier.js";
|
|
50
|
+
import { verifyStretch } from "./stretch.js";
|
|
51
|
+
import { checkBlockRead, type BlockReadChain, type BlockReadFile, type ChainBlock } from "./block-read.js";
|
|
52
|
+
import { checkEpochGenesis, type EpochGenesisBlock, type EpochGenesisTx } from "./epoch-genesis.js";
|
|
53
|
+
|
|
54
|
+
export const TIMELINE_BUNDLE_FORMAT = "bitgraph-timeline-bundle/1" as const;
|
|
55
|
+
|
|
56
|
+
export interface TimelineBundle {
|
|
57
|
+
format: typeof TIMELINE_BUNDLE_FORMAT;
|
|
58
|
+
/** An unbroken run of proofs, in counter order. The first is a block read. */
|
|
59
|
+
proofs: BitGraphProof[];
|
|
60
|
+
/** The index in `proofs` of the file's proof: strictly after the first. */
|
|
61
|
+
target: number;
|
|
62
|
+
/** The block files of the block reads in the run, by their index in `proofs` (as a decimal string). Index 0 is required. */
|
|
63
|
+
blockFiles: Record<string, string>;
|
|
64
|
+
/** The epoch's genesis record, wherever it falls in the epoch, before or after the file. Absent: unconfirmed. */
|
|
65
|
+
genesis?: { proof: BitGraphProof; file: string };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Lag limits in seconds: a read is outside them when Nitro time minus block time is above maxS or below minS. */
|
|
69
|
+
export interface LagLimit {
|
|
70
|
+
maxS: number;
|
|
71
|
+
minS: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Defaults: Base 2 s early to 5 s late, Ethereum 2 s early to 60 s late. */
|
|
75
|
+
export const DEFAULT_LAG_LIMITS: Readonly<Record<BlockReadChain, LagLimit>> = {
|
|
76
|
+
base: { maxS: 5, minS: -2 },
|
|
77
|
+
ethereum: { maxS: 60, minS: -2 },
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** The chains' answers. Each returns null when the chain does not know the hash, and throws when it could not be asked. */
|
|
81
|
+
export interface TimelineLookups {
|
|
82
|
+
block(chain: BlockReadChain, chainId: string, hash: string): Promise<ChainBlock | null>;
|
|
83
|
+
genesisTx?(txHash: string): Promise<EpochGenesisTx | null>;
|
|
84
|
+
genesisBlock?(blockHash: string): Promise<EpochGenesisBlock | null>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface TimelineBundleOptions {
|
|
88
|
+
bundle: unknown;
|
|
89
|
+
/** The file's bytes; when given they must hash to the file proof's digest. */
|
|
90
|
+
fileBytes?: Uint8Array;
|
|
91
|
+
lookups?: TimelineLookups;
|
|
92
|
+
lagLimits?: Partial<Record<BlockReadChain, LagLimit>>;
|
|
93
|
+
/** The enclave images accepted, by PCR0. Default: every image BitGraph published. */
|
|
94
|
+
pcr0?: readonly string[];
|
|
95
|
+
/** The per-proof check. Default verifyAttested; tests replace it, since they cannot make Nitro documents. */
|
|
96
|
+
attested?: (opts: AttestedOptions) => Promise<AttestedResult>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface TimelineBound {
|
|
100
|
+
/** The read's index in the bundle's proofs. */
|
|
101
|
+
index: number;
|
|
102
|
+
chain: BlockReadChain;
|
|
103
|
+
chainId: string;
|
|
104
|
+
hash: string;
|
|
105
|
+
/** From the chain, never from the block file. */
|
|
106
|
+
number: number;
|
|
107
|
+
/** From the chain, Unix seconds. */
|
|
108
|
+
timestamp: number;
|
|
109
|
+
/** The block read's own count (its payload's). */
|
|
110
|
+
counter: string;
|
|
111
|
+
/** The block read's Nitro time, ms. */
|
|
112
|
+
attestedAtMs: number;
|
|
113
|
+
/** Signed: attestedAtMs / 1000 minus timestamp. */
|
|
114
|
+
lagS: number;
|
|
115
|
+
/** What the bound means, in words. */
|
|
116
|
+
claim: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface TimelineBundleResult {
|
|
120
|
+
status: "verified" | "unconfirmed" | "failed";
|
|
121
|
+
/** What failed. */
|
|
122
|
+
reasons: string[];
|
|
123
|
+
/** What could not be settled. */
|
|
124
|
+
unconfirmed: string[];
|
|
125
|
+
/** Lags outside the limits, on the floor or on reads passed over as ceilings. Flags never fail a bundle. */
|
|
126
|
+
flags: string[];
|
|
127
|
+
/** Reads passed over when choosing the bracket, and why. */
|
|
128
|
+
passedOver: string[];
|
|
129
|
+
file: { counter: string; digestB64: string; attestedAtMs: number | null } | null;
|
|
130
|
+
floor: TimelineBound | null;
|
|
131
|
+
ceiling: TimelineBound | null;
|
|
132
|
+
/** confirmed: the epoch's genesis write is on Base; unconfirmed: given, Base not asked; missing: not in the bundle. */
|
|
133
|
+
genesis: "confirmed" | "unconfirmed" | "missing";
|
|
134
|
+
/** True when the file was bound before its epoch's genesis record (or none is shown): its clock check rests on Nitro alone. */
|
|
135
|
+
preGenesis: boolean;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const enc = new TextEncoder();
|
|
139
|
+
|
|
140
|
+
export async function verifyTimelineBundle(opts: TimelineBundleOptions): Promise<TimelineBundleResult> {
|
|
141
|
+
const reasons: string[] = [];
|
|
142
|
+
const unconfirmed: string[] = [];
|
|
143
|
+
const flags: string[] = [];
|
|
144
|
+
const passedOver: string[] = [];
|
|
145
|
+
const failed = (why: string): TimelineBundleResult => ({ status: "failed", reasons: [why], unconfirmed, flags, passedOver, file: null, floor: null, ceiling: null, genesis: "missing", preGenesis: true });
|
|
146
|
+
|
|
147
|
+
const shape = bundleShape(opts.bundle);
|
|
148
|
+
if (typeof shape === "string") return failed(shape);
|
|
149
|
+
const b = shape;
|
|
150
|
+
const attested = opts.attested ?? verifyAttested;
|
|
151
|
+
const limits = { ...DEFAULT_LAG_LIMITS, ...(opts.lagLimits ?? {}) };
|
|
152
|
+
const pcr0 = opts.pcr0 ? { pcr0: opts.pcr0 } : {};
|
|
153
|
+
const fileAt = (i: number): string | undefined => b.blockFiles[String(i)];
|
|
154
|
+
|
|
155
|
+
// The run: unbroken, so nothing was bound inside it that the bundle does not show.
|
|
156
|
+
reasons.push(...verifyStretch(b.proofs).reasons);
|
|
157
|
+
|
|
158
|
+
// Every proof in full, with one fork-detecting context across the bundle. A block read is checked against its file.
|
|
159
|
+
const context = createVerificationContext();
|
|
160
|
+
const times: (number | null)[] = [];
|
|
161
|
+
for (let i = 0; i < b.proofs.length; i++) {
|
|
162
|
+
const proof = b.proofs[i]!;
|
|
163
|
+
const text = fileAt(i);
|
|
164
|
+
const bytes = text !== undefined ? enc.encode(text) : i === b.target ? opts.fileBytes : undefined;
|
|
165
|
+
const r = await attested({ proof, ...(bytes !== undefined ? { bytes } : {}), ...pcr0, context });
|
|
166
|
+
times.push(r.valid ? r.attestedAtMs : null);
|
|
167
|
+
const role = i === b.target ? "the file's proof" : `proof ${i}`;
|
|
168
|
+
if (!r.valid) reasons.push(`${role} (counter ${proof.commit?.counter ?? "?"}) does not verify: ${r.reason ?? "invalid"}`);
|
|
169
|
+
else if (r.attestedAtMs === null) reasons.push(`${role} has no Nitro time`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Every block file, offline: it must be a block read of this proof's epoch.
|
|
173
|
+
const reads = new Map<number, BlockReadFile>();
|
|
174
|
+
for (const [k, text] of Object.entries(b.blockFiles)) {
|
|
175
|
+
const i = Number(k);
|
|
176
|
+
const r = checkBlockRead({ file: text, proof: b.proofs[i]! });
|
|
177
|
+
if (r.status === "failed" || !r.file) reasons.push(...r.reasons.map((x) => `proof ${i}'s block file: ${x}`));
|
|
178
|
+
else reads.set(i, r.file);
|
|
179
|
+
}
|
|
180
|
+
const chain = reads.get(0)?.chain;
|
|
181
|
+
|
|
182
|
+
// The bracket, on the first read's chain. Each candidate is asked of the chain; only its answer gives time.
|
|
183
|
+
type Asked = { kind: "bound"; bound: TimelineBound } | { kind: "skip" } | { kind: "stop" };
|
|
184
|
+
const ask = async (i: number): Promise<Asked> => {
|
|
185
|
+
const f = reads.get(i)!;
|
|
186
|
+
if (!opts.lookups) {
|
|
187
|
+
unconfirmed.push(`block ${f.hash} (proof ${i}) was not looked up on ${f.chain}`);
|
|
188
|
+
return { kind: "stop" };
|
|
189
|
+
}
|
|
190
|
+
let answer: ChainBlock | null;
|
|
191
|
+
try {
|
|
192
|
+
answer = await opts.lookups.block(f.chain, f.chainId, f.hash);
|
|
193
|
+
} catch (e) {
|
|
194
|
+
unconfirmed.push(`${f.chain} could not be asked about block ${f.hash} (proof ${i}): ${e instanceof Error ? e.message : String(e)}`);
|
|
195
|
+
return { kind: "stop" };
|
|
196
|
+
}
|
|
197
|
+
if (answer === null || answer.hash.toLowerCase() !== f.hash) {
|
|
198
|
+
passedOver.push(`proof ${i}: ${f.chain} does not know block ${f.hash}`);
|
|
199
|
+
return { kind: "skip" };
|
|
200
|
+
}
|
|
201
|
+
if (!answer.canonical) {
|
|
202
|
+
passedOver.push(`proof ${i}: block ${f.hash} is not on ${f.chain}'s canonical chain`);
|
|
203
|
+
return { kind: "skip" };
|
|
204
|
+
}
|
|
205
|
+
const r = checkBlockRead({ file: b.blockFiles[String(i)]!, proof: b.proofs[i]!, chain: answer });
|
|
206
|
+
if (r.status !== "confirmed" || !r.block) {
|
|
207
|
+
// The chain knows the block and the file mislabels it: the host misreported a block.
|
|
208
|
+
reasons.push(...r.reasons.map((x) => `proof ${i}: ${x}`));
|
|
209
|
+
return { kind: "stop" };
|
|
210
|
+
}
|
|
211
|
+
const at = times[i];
|
|
212
|
+
if (typeof at !== "number") return { kind: "stop" };
|
|
213
|
+
return { kind: "bound", bound: { index: i, ...r.block, counter: String(b.proofs[i]!.commit?.counter ?? ""), attestedAtMs: at, lagS: (at - r.block.timestamp * 1000) / 1000, claim: "" } };
|
|
214
|
+
};
|
|
215
|
+
const outside = (x: TimelineBound): string | null => {
|
|
216
|
+
const lim = limits[x.chain];
|
|
217
|
+
if (x.lagS > lim.maxS) return `${x.chain} block ${x.number} was read ${x.lagS.toFixed(1)} s after its timestamp (limit ${lim.maxS} s)`;
|
|
218
|
+
if (x.lagS < lim.minS) return `${x.chain} block ${x.number} was read ${(-x.lagS).toFixed(1)} s before its timestamp (limit ${-lim.minS} s)`;
|
|
219
|
+
return null;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
let floor: TimelineBound | null = null;
|
|
223
|
+
let ceiling: TimelineBound | null = null;
|
|
224
|
+
const fileMs = times[b.target];
|
|
225
|
+
const sameChain = [...reads.keys()].filter((i) => reads.get(i)!.chain === chain).sort((x, y) => x - y);
|
|
226
|
+
if (chain !== undefined && reasons.length === 0) {
|
|
227
|
+
// Every read before the file is asked; the floor is the highest-numbered one stamped at or before the file.
|
|
228
|
+
for (const i of sameChain.filter((i) => i < b.target)) {
|
|
229
|
+
const a = await ask(i);
|
|
230
|
+
if (a.kind === "stop") { floor = null; break; }
|
|
231
|
+
if (a.kind === "skip") continue;
|
|
232
|
+
if (typeof fileMs !== "number") break;
|
|
233
|
+
if (a.bound.timestamp * 1000 > fileMs) { passedOver.push(`proof ${i}: block ${a.bound.number}'s timestamp ${a.bound.timestamp} is after the file's Nitro time ${(fileMs / 1000).toFixed(3)}, so it is not a floor`); continue; }
|
|
234
|
+
if (!floor || a.bound.number > floor.number) floor = a.bound;
|
|
235
|
+
}
|
|
236
|
+
if (floor) {
|
|
237
|
+
floor.claim = `bound after ${floor.chain} block ${floor.number} (${floor.hash}) was produced`;
|
|
238
|
+
const lag = outside(floor);
|
|
239
|
+
if (lag) flags.push(`the floor: ${lag}`);
|
|
240
|
+
for (const i of sameChain.filter((i) => i > b.target)) {
|
|
241
|
+
const a = await ask(i);
|
|
242
|
+
if (a.kind === "stop") break;
|
|
243
|
+
if (a.kind === "skip") continue;
|
|
244
|
+
const c = a.bound;
|
|
245
|
+
if (typeof fileMs !== "number") break;
|
|
246
|
+
if (c.timestamp * 1000 <= fileMs) { passedOver.push(`proof ${i}: block ${c.number}'s timestamp ${c.timestamp} is not after the file's Nitro time ${(fileMs / 1000).toFixed(3)}, so it is not a ceiling`); continue; }
|
|
247
|
+
if (c.number <= floor.number) { passedOver.push(`proof ${i}: block ${c.number} is not above the floor's ${floor.number}, so it is not a ceiling`); continue; }
|
|
248
|
+
const lag = outside(c);
|
|
249
|
+
if (lag) { flags.push(`proof ${i}, passed over as a ceiling: ${lag}`); passedOver.push(`proof ${i}: its lag is outside the limits, so it is not a ceiling`); continue; }
|
|
250
|
+
c.claim = `bound at Nitro hardware time ${new Date(fileMs).toISOString()}, before ${c.chain} block ${c.number}'s timestamp ${new Date(c.timestamp * 1000).toISOString()}; the Nitro clock was checked against the chain at block ${c.number}'s read (lag ${c.lagS.toFixed(1)} s, within limits)`;
|
|
251
|
+
ceiling = c;
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
} else if (unconfirmed.length === 0 && reasons.length === 0) {
|
|
255
|
+
unconfirmed.push(`no read before the file is a confirmed ${chain} block, so there is no floor`);
|
|
256
|
+
}
|
|
257
|
+
if (floor && !ceiling && unconfirmed.length === 0 && reasons.length === 0) {
|
|
258
|
+
unconfirmed.push(`no read after the file in this bundle qualifies as a ${chain} ceiling`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// The hardware's clock must agree with the order.
|
|
263
|
+
if (typeof fileMs === "number") {
|
|
264
|
+
if (floor && floor.attestedAtMs > fileMs) reasons.push("the floor read's Nitro time is after the file's");
|
|
265
|
+
if (ceiling && ceiling.attestedAtMs < fileMs) reasons.push("the ceiling read's Nitro time is before the file's");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Genesis: this epoch's, under the same key, before or after the file, and, when Base is asked, on Base.
|
|
269
|
+
let genesis: TimelineBundleResult["genesis"] = "missing";
|
|
270
|
+
let preGenesis = true;
|
|
271
|
+
const target = b.proofs[b.target]!;
|
|
272
|
+
if (b.genesis) {
|
|
273
|
+
const g = b.genesis;
|
|
274
|
+
const gr = await attested({ proof: g.proof, bytes: enc.encode(g.file), ...pcr0, context });
|
|
275
|
+
const before = reasons.length;
|
|
276
|
+
if (!gr.valid) reasons.push(`the genesis record does not verify: ${gr.reason ?? "invalid"}`);
|
|
277
|
+
if (g.proof.signer?.publicKeyB64 !== target.signer?.publicKeyB64) reasons.push("the genesis record is signed by another key");
|
|
278
|
+
try {
|
|
279
|
+
const gc = BigInt(g.proof.commit?.counter ?? "");
|
|
280
|
+
const tc = BigInt(target.commit?.counter ?? "");
|
|
281
|
+
if (gc === tc) reasons.push("the genesis record is the file's own proof");
|
|
282
|
+
preGenesis = gc > tc;
|
|
283
|
+
} catch {
|
|
284
|
+
reasons.push("the genesis record's counter does not parse");
|
|
285
|
+
}
|
|
286
|
+
const offline = checkEpochGenesis({ file: g.file, proof: g.proof, position: "any" });
|
|
287
|
+
if (!offline.ok) reasons.push(...offline.reasons.map((x) => `genesis: ${x}`));
|
|
288
|
+
if (offline.genesis && offline.genesis.epochId !== target.commit?.epochId) reasons.push("the genesis record is of another epoch");
|
|
289
|
+
if (reasons.length === before && offline.genesis) {
|
|
290
|
+
genesis = "unconfirmed";
|
|
291
|
+
const gf = offline.genesis;
|
|
292
|
+
if (opts.lookups?.genesisTx && opts.lookups.genesisBlock) {
|
|
293
|
+
try {
|
|
294
|
+
const tx = await opts.lookups.genesisTx(gf.txHash);
|
|
295
|
+
const block = await opts.lookups.genesisBlock(gf.blockHash);
|
|
296
|
+
if (!tx) reasons.push(`Base does not know the genesis transaction ${gf.txHash}`);
|
|
297
|
+
if (!block) reasons.push(`Base does not know the genesis block ${gf.blockHash}`);
|
|
298
|
+
if (tx && block) {
|
|
299
|
+
const online = checkEpochGenesis({ file: g.file, proof: g.proof, tx, block, position: "any" });
|
|
300
|
+
if (online.ok) genesis = "confirmed";
|
|
301
|
+
else reasons.push(...online.reasons.map((x) => `genesis: ${x}`));
|
|
302
|
+
}
|
|
303
|
+
} catch (e) {
|
|
304
|
+
unconfirmed.push(`genesis: Base could not be asked (${e instanceof Error ? e.message : String(e)})`);
|
|
305
|
+
}
|
|
306
|
+
} else {
|
|
307
|
+
unconfirmed.push("genesis: the transaction was not looked up on Base");
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
} else {
|
|
311
|
+
unconfirmed.push("the bundle does not carry its epoch's genesis record");
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const status = reasons.length > 0 ? "failed" : unconfirmed.length > 0 ? "unconfirmed" : "verified";
|
|
315
|
+
return {
|
|
316
|
+
status,
|
|
317
|
+
reasons,
|
|
318
|
+
unconfirmed,
|
|
319
|
+
flags,
|
|
320
|
+
passedOver,
|
|
321
|
+
file: { counter: String(target.commit?.counter ?? ""), digestB64: target.artifact?.digestB64 ?? "", attestedAtMs: fileMs ?? null },
|
|
322
|
+
floor: status === "failed" ? null : floor,
|
|
323
|
+
ceiling: status === "failed" ? null : ceiling,
|
|
324
|
+
genesis,
|
|
325
|
+
preGenesis,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** The bundle, or why it is not one. */
|
|
330
|
+
function bundleShape(v: unknown): TimelineBundle | string {
|
|
331
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) return "a bundle is a JSON object";
|
|
332
|
+
const o = v as Record<string, unknown>;
|
|
333
|
+
if (o["format"] !== TIMELINE_BUNDLE_FORMAT) return `not ${TIMELINE_BUNDLE_FORMAT}`;
|
|
334
|
+
const proofs = o["proofs"];
|
|
335
|
+
if (!Array.isArray(proofs) || proofs.length < 2 || proofs.some((p) => !p || typeof p !== "object")) return "a bundle holds at least a block read and the file";
|
|
336
|
+
const target = o["target"];
|
|
337
|
+
if (!Number.isSafeInteger(target) || (target as number) <= 0 || (target as number) >= proofs.length) return "the file's proof must come after the first block read";
|
|
338
|
+
const files = o["blockFiles"];
|
|
339
|
+
if (!files || typeof files !== "object" || Array.isArray(files)) return "a bundle carries the block files of its block reads";
|
|
340
|
+
for (const [k, text] of Object.entries(files as Record<string, unknown>)) {
|
|
341
|
+
if (!/^(0|[1-9][0-9]*)$/.test(k) || Number(k) >= proofs.length || typeof text !== "string") return `block file ${JSON.stringify(k)} names no proof of the bundle`;
|
|
342
|
+
if (Number(k) === target) return "the file's proof is not a block read";
|
|
343
|
+
}
|
|
344
|
+
if (typeof (files as Record<string, unknown>)["0"] !== "string") return "the first proof of a bundle is a block read, with its block file";
|
|
345
|
+
const g = o["genesis"];
|
|
346
|
+
if (g !== undefined) {
|
|
347
|
+
const gg = g as Record<string, unknown> | null;
|
|
348
|
+
if (!gg || typeof gg !== "object" || !gg["proof"] || typeof gg["proof"] !== "object" || typeof gg["file"] !== "string") return "the genesis entry holds a proof and its file";
|
|
349
|
+
}
|
|
350
|
+
return o as unknown as TimelineBundle;
|
|
351
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Building a bitgraph-timeline-bundle/1 for a file from the timeline's records (the journal's lines: each proof, and
|
|
5
|
+
* for a block read or the genesis record the file it binds).
|
|
6
|
+
*
|
|
7
|
+
* The builder chooses the bracket by the verifier's own rules (timeline-bundle.ts), reading the block files' labels
|
|
8
|
+
* and the attestations' times, and cuts the run from the floor read to the ceiling read. Base first; Ethereum when
|
|
9
|
+
* Base has no qualifying ceiling (Base down). The labels are the host's own word, so the builder only proposes:
|
|
10
|
+
* verifyTimelineBundle with chain lookups is what settles the bracket, and a bundle whose labels lie fails there.
|
|
11
|
+
*
|
|
12
|
+
* Not ready yet (retryable) when the file has no qualifying ceiling read after it in the records given: a ceiling
|
|
13
|
+
* needs a block stamped after the file, read within the lag limits, so a bundle can be made a few seconds after the
|
|
14
|
+
* file is bound. A gap in the records (a lost record) cannot be bridged and is not retryable.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { BitGraphProof } from "./types.js";
|
|
18
|
+
import { decodeNitroAttestation } from "./nitro.js";
|
|
19
|
+
import { verifyStretch } from "./stretch.js";
|
|
20
|
+
import { parseBlockReadFile, type BlockReadChain, type BlockReadFile } from "./block-read.js";
|
|
21
|
+
import { DEFAULT_LAG_LIMITS, TIMELINE_BUNDLE_FORMAT, type LagLimit, type TimelineBundle } from "./timeline-bundle.js";
|
|
22
|
+
|
|
23
|
+
/** One record of the timeline, as the parent's journal keeps it. */
|
|
24
|
+
export interface TimelineRecordLine {
|
|
25
|
+
kind: "block" | "file" | "genesis";
|
|
26
|
+
proof: BitGraphProof;
|
|
27
|
+
blockFile?: string;
|
|
28
|
+
genesisFile?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type BuildTimelineBundleResult =
|
|
32
|
+
| { ok: true; bundle: TimelineBundle; chain: BlockReadChain; notes: string[] }
|
|
33
|
+
| { ok: false; retryable: boolean; reason: string };
|
|
34
|
+
|
|
35
|
+
/** The attestation's own time, ms, read without verifying it (verifyTimelineBundle verifies it). Null when unreadable. */
|
|
36
|
+
export function attestationTimeMs(proof: BitGraphProof): number | null {
|
|
37
|
+
const r = proof.environment?.attestation?.reportB64;
|
|
38
|
+
if (typeof r !== "string") return null;
|
|
39
|
+
try { return decodeNitroAttestation(r).doc.timestampMs; } catch { return null; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function buildTimelineBundle(args: {
|
|
43
|
+
/** Records of the file's epoch around it, in any order. */
|
|
44
|
+
lines: readonly TimelineRecordLine[];
|
|
45
|
+
/** The file's payload count. */
|
|
46
|
+
counter: string;
|
|
47
|
+
/** The epoch's genesis record, wherever it is. */
|
|
48
|
+
genesis?: TimelineRecordLine | null;
|
|
49
|
+
lagLimits?: Partial<Record<BlockReadChain, LagLimit>>;
|
|
50
|
+
/** For records whose attestation is not a Nitro document (the local harness). Default attestationTimeMs. */
|
|
51
|
+
nitroTimeMs?: (proof: BitGraphProof) => number | null;
|
|
52
|
+
}): BuildTimelineBundleResult {
|
|
53
|
+
const nitro = args.nitroTimeMs ?? attestationTimeMs;
|
|
54
|
+
const limits = { ...DEFAULT_LAG_LIMITS, ...(args.lagLimits ?? {}) };
|
|
55
|
+
const target = args.lines.find((l) => l.proof.commit?.counter === args.counter);
|
|
56
|
+
if (!target) return { ok: false, retryable: false, reason: `no record at count ${args.counter} in the records given` };
|
|
57
|
+
if (target.kind === "block") return { ok: false, retryable: false, reason: "that record is a block read, not a file" };
|
|
58
|
+
const epochId = target.proof.commit?.epochId;
|
|
59
|
+
const lines = args.lines
|
|
60
|
+
.filter((l) => l.proof.commit?.epochId === epochId)
|
|
61
|
+
.slice()
|
|
62
|
+
.sort((a, b) => (BigInt(a.proof.commit.counter ?? "0") < BigInt(b.proof.commit.counter ?? "0") ? -1 : 1));
|
|
63
|
+
const t = lines.findIndex((l) => l.proof.commit?.counter === args.counter);
|
|
64
|
+
const fileMs = nitro(target.proof);
|
|
65
|
+
if (fileMs === null) return { ok: false, retryable: false, reason: "the file's attestation time cannot be read" };
|
|
66
|
+
|
|
67
|
+
const reads = new Map<number, BlockReadFile>();
|
|
68
|
+
lines.forEach((l, i) => {
|
|
69
|
+
if (l.kind === "block" && l.blockFile !== undefined) {
|
|
70
|
+
const f = parseBlockReadFile(l.blockFile);
|
|
71
|
+
if (f) reads.set(i, f);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const pick = (chain: BlockReadChain): { floor: number; ceiling: number } | { floor: number | null; ceiling: null } => {
|
|
76
|
+
let floor: number | null = null;
|
|
77
|
+
for (const [i, f] of reads) {
|
|
78
|
+
if (i >= t || f.chain !== chain || f.timestamp * 1000 > fileMs) continue;
|
|
79
|
+
if (floor === null || f.number > reads.get(floor)!.number) floor = i;
|
|
80
|
+
}
|
|
81
|
+
if (floor === null) return { floor: null, ceiling: null };
|
|
82
|
+
const lim = limits[chain];
|
|
83
|
+
for (let i = t + 1; i < lines.length; i++) {
|
|
84
|
+
const f = reads.get(i);
|
|
85
|
+
if (!f || f.chain !== chain) continue;
|
|
86
|
+
const at = nitro(lines[i]!.proof);
|
|
87
|
+
if (at === null) continue;
|
|
88
|
+
const lagS = (at - f.timestamp * 1000) / 1000;
|
|
89
|
+
if (f.timestamp * 1000 > fileMs && f.number > reads.get(floor)!.number && lagS <= lim.maxS && lagS >= lim.minS) return { floor, ceiling: i };
|
|
90
|
+
}
|
|
91
|
+
return { floor, ceiling: null };
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const notes: string[] = [];
|
|
95
|
+
let chosen: { chain: BlockReadChain; floor: number; ceiling: number } | null = null;
|
|
96
|
+
for (const chain of ["base", "ethereum"] as const) {
|
|
97
|
+
const p = pick(chain);
|
|
98
|
+
if (p.ceiling !== null) { chosen = { chain, floor: p.floor!, ceiling: p.ceiling }; break; }
|
|
99
|
+
notes.push(p.floor === null ? `no ${chain} read before the file in these records` : `no qualifying ${chain} ceiling after the file yet`);
|
|
100
|
+
}
|
|
101
|
+
if (!chosen) return { ok: false, retryable: true, reason: `not ready: ${notes.join("; ")}` };
|
|
102
|
+
if (chosen.chain !== "base") notes.unshift("bracketed on Ethereum: Base had no qualifying ceiling");
|
|
103
|
+
else notes.length = 0;
|
|
104
|
+
|
|
105
|
+
const run = lines.slice(chosen.floor, chosen.ceiling + 1);
|
|
106
|
+
const s = verifyStretch(run.map((l) => l.proof));
|
|
107
|
+
if (!s.ok) return { ok: false, retryable: false, reason: `the records are not one unbroken run: ${s.reasons[0]}` };
|
|
108
|
+
|
|
109
|
+
const blockFiles: Record<string, string> = {};
|
|
110
|
+
run.forEach((l, i) => { if (l.kind === "block" && l.blockFile !== undefined) blockFiles[String(i)] = l.blockFile; });
|
|
111
|
+
const g = args.genesis;
|
|
112
|
+
if (!g || g.kind !== "genesis" || g.genesisFile === undefined) notes.push("no genesis record for this epoch: the bundle cannot verify fully");
|
|
113
|
+
const bundle: TimelineBundle = {
|
|
114
|
+
format: TIMELINE_BUNDLE_FORMAT,
|
|
115
|
+
proofs: run.map((l) => l.proof),
|
|
116
|
+
target: t - chosen.floor,
|
|
117
|
+
blockFiles,
|
|
118
|
+
...(g && g.kind === "genesis" && g.genesisFile !== undefined ? { genesis: { proof: g.proof, file: g.genesisFile } } : {}),
|
|
119
|
+
};
|
|
120
|
+
return { ok: true, bundle, chain: chosen.chain, notes };
|
|
121
|
+
}
|