@mikeargento/bitgraph-verify 1.13.1 → 1.15.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 (86) hide show
  1. package/README.md +1 -1
  2. package/dist/__tests__/carrier.test.js +19 -0
  3. package/dist/__tests__/carrier.test.js.map +1 -1
  4. package/dist/__tests__/carrier2.test.d.ts +2 -0
  5. package/dist/__tests__/carrier2.test.d.ts.map +1 -0
  6. package/dist/__tests__/carrier2.test.js +172 -0
  7. package/dist/__tests__/carrier2.test.js.map +1 -0
  8. package/dist/__tests__/ceiling.test.d.ts +8 -0
  9. package/dist/__tests__/ceiling.test.d.ts.map +1 -0
  10. package/dist/__tests__/ceiling.test.js +247 -0
  11. package/dist/__tests__/ceiling.test.js.map +1 -0
  12. package/dist/__tests__/settlement.test.d.ts +12 -0
  13. package/dist/__tests__/settlement.test.d.ts.map +1 -0
  14. package/dist/__tests__/settlement.test.js +185 -0
  15. package/dist/__tests__/settlement.test.js.map +1 -0
  16. package/dist/carrier-assemble.d.ts +33 -0
  17. package/dist/carrier-assemble.d.ts.map +1 -0
  18. package/dist/carrier-assemble.js +57 -0
  19. package/dist/carrier-assemble.js.map +1 -0
  20. package/dist/carrier-verify.d.ts +47 -1
  21. package/dist/carrier-verify.d.ts.map +1 -1
  22. package/dist/carrier-verify.js +292 -53
  23. package/dist/carrier-verify.js.map +1 -1
  24. package/dist/carrier.d.ts +93 -3
  25. package/dist/carrier.d.ts.map +1 -1
  26. package/dist/carrier.js +144 -19
  27. package/dist/carrier.js.map +1 -1
  28. package/dist/ceiling-evm.d.ts +49 -0
  29. package/dist/ceiling-evm.d.ts.map +1 -0
  30. package/dist/ceiling-evm.js +331 -0
  31. package/dist/ceiling-evm.js.map +1 -0
  32. package/dist/ceiling-trie.d.ts +9 -0
  33. package/dist/ceiling-trie.d.ts.map +1 -0
  34. package/dist/ceiling-trie.js +113 -0
  35. package/dist/ceiling-trie.js.map +1 -0
  36. package/dist/ceiling.d.ts +123 -0
  37. package/dist/ceiling.d.ts.map +1 -0
  38. package/dist/ceiling.js +247 -0
  39. package/dist/ceiling.js.map +1 -0
  40. package/dist/fuse-member.js +2 -2
  41. package/dist/fuse-member.js.map +1 -1
  42. package/dist/fuse-verify.js +3 -3
  43. package/dist/fuse-verify.js.map +1 -1
  44. package/dist/fuse.d.ts +34 -2
  45. package/dist/fuse.d.ts.map +1 -1
  46. package/dist/fuse.js +83 -6
  47. package/dist/fuse.js.map +1 -1
  48. package/dist/index.d.ts +15 -3
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +13 -2
  51. package/dist/index.js.map +1 -1
  52. package/dist/nitro.d.ts +128 -0
  53. package/dist/nitro.d.ts.map +1 -0
  54. package/dist/nitro.js +551 -0
  55. package/dist/nitro.js.map +1 -0
  56. package/dist/settlement.d.ts +114 -0
  57. package/dist/settlement.d.ts.map +1 -0
  58. package/dist/settlement.js +194 -0
  59. package/dist/settlement.js.map +1 -0
  60. package/package.json +2 -1
  61. package/src/__tests__/carrier.test.ts +18 -0
  62. package/src/__tests__/carrier2.test.ts +193 -0
  63. package/src/__tests__/ceiling.test.ts +281 -0
  64. package/src/__tests__/fixtures/carrier2/ceiling-26088459.witness.json +1 -0
  65. package/src/__tests__/fixtures/carrier2/ceiling-4548.anchor.json +1 -0
  66. package/src/__tests__/fixtures/carrier2/demo4546.ceiling.json +106 -0
  67. package/src/__tests__/fixtures/carrier2/demo4546.proof.json +47 -0
  68. package/src/__tests__/fixtures/carrier2/demo4546.txt +29 -0
  69. package/src/__tests__/fixtures/carrier2/floor-26088457.witness.json +1 -0
  70. package/src/__tests__/fixtures/carrier2/floor-4542.anchor.json +1 -0
  71. package/src/__tests__/fixtures/ceiling/floor-26037892.header.hex +1 -0
  72. package/src/__tests__/fixtures/settlement/pointer-51979918-tx1.json +39 -0
  73. package/src/__tests__/fixtures/settlement/pointer-51979918.json +69 -0
  74. package/src/__tests__/settlement.test.ts +215 -0
  75. package/src/carrier-assemble.ts +74 -0
  76. package/src/carrier-verify.ts +328 -47
  77. package/src/carrier.ts +174 -18
  78. package/src/ceiling-evm.ts +326 -0
  79. package/src/ceiling-trie.ts +112 -0
  80. package/src/ceiling.ts +333 -0
  81. package/src/fuse-member.ts +2 -2
  82. package/src/fuse-verify.ts +3 -3
  83. package/src/fuse.ts +93 -6
  84. package/src/index.ts +42 -2
  85. package/src/nitro.ts +602 -0
  86. package/src/settlement.ts +263 -0
package/src/carrier.ts CHANGED
@@ -22,14 +22,25 @@
22
22
  * the carrier as recorded — the bytes inside it are.
23
23
  *
24
24
  * THE TIME WINDOW. The payload always carries the floor: the anchor the
25
- * enclave signed into the slot (`commit.slotAnchor`, present since enclave
26
- * v7) plus that block's header, so "placed no earlier than this block" checks
27
- * offline by identity. The ceiling cannot exist when the carrier is written —
25
+ * enclave fixed at slot allocation and signed at commit (`commit.slotAnchor`,
26
+ * present since enclave v7) plus that block's header, so the header checks
27
+ * offline against the signed hash; that the block is on Ethereum is one
28
+ * lookup anywhere. The ceiling cannot exist when the carrier is written —
28
29
  * the anchor that follows the commit has not landed yet — so it is either
29
30
  * `present` (stamped in later from public data) or `unfetched`, stated in so
30
31
  * many words. There is no third state, and absence of the field is a corrupt
31
32
  * block, not a missing bound.
32
33
  *
34
+ * bitgraph-carrier/2 (2026-09-30) keeps everything above and adds, in the same
35
+ * block: the ceiling in TIME (the bitgraph-ceiling/1 sidecar: a Base block the
36
+ * record existed by), its settlement on Ethereum when known (a
37
+ * bitgraph-settlement/1 pointer: the Ethereum block that committed the batch
38
+ * data), the AWS attestation laid out as openssl-checkable evidence
39
+ * (aws-nitro-witness/1), and the pins the file was made under (PCR0, the
40
+ * ceiling writer, the chains), which a verifier compares with ITS OWN list and
41
+ * never reads as authority. A reader that knows only v1 reports an unknown
42
+ * version (UNDETERMINED), never a verdict.
43
+ *
33
44
  * ⚠️ TWO BYTE-IDENTICAL COPIES OF THIS FILE EXIST, on purpose:
34
45
  * packages/verify/src/carrier.ts (canonical, published with the package)
35
46
  * website/src/lib/carrier.ts (the site cannot import unpublished code)
@@ -51,10 +62,16 @@ export const CARRIER_OVERHEAD = 24;
51
62
  export const MAX_CARRIER_PAYLOAD = 8 * 1024 * 1024;
52
63
 
53
64
  export const CARRIER_VERSION = "bitgraph-carrier/1";
65
+ export const CARRIER_VERSION_2 = "bitgraph-carrier/2";
66
+ export type CarrierVersion = typeof CARRIER_VERSION | typeof CARRIER_VERSION_2;
67
+ /** The sidecar and pointer formats a v2 block carries; their shapes are checked by their own modules. */
68
+ export const CEILING_SIDECAR_VERSION = "bitgraph-ceiling/1";
69
+ export const SETTLEMENT_POINTER_VERSION = "bitgraph-settlement/1";
70
+ export const ATTESTATION_WITNESS_VERSION = "aws-nitro-witness/1";
54
71
 
55
72
  /* ── The payload ────────────────────────────────────────────────────────── */
56
73
 
57
- /** The raw Ethereum block header, so the block's identity and time check offline. */
74
+ /** The raw Ethereum block header: offline it matches the signed hash and gives the block's time; that it is Ethereum's own block is one lookup. */
58
75
  export interface CarrierWitness {
59
76
  headerRlpHex: string;
60
77
  blockNumber: number;
@@ -85,12 +102,39 @@ export type CarrierCeiling =
85
102
  witness: CarrierWitness;
86
103
  };
87
104
 
105
+ /** v2: the ceiling in time, a Base block the record existed by, carried as the bitgraph-ceiling/1 sidecar. */
106
+ export type CarrierCeilingInTime =
107
+ | { status: "unfetched"; searched?: { at: string } }
108
+ | { status: "present"; sidecar: Record<string, unknown> };
109
+
110
+ /** v2: the Ethereum block that committed the Base batch data, as a bitgraph-settlement/1 pointer. Blob bytes travel beside the package, not here. */
111
+ export type CarrierSettlement =
112
+ | { status: "unfetched" }
113
+ | { status: "present"; pointer: Record<string, unknown> };
114
+
115
+ /** v2: what the file was made under. Declared only; a verifier compares with its own pins. */
116
+ export interface CarrierPins {
117
+ pcr0?: string;
118
+ enclave?: string;
119
+ ceilingWriter?: string;
120
+ chains?: { ethereum?: number; base?: number };
121
+ }
122
+
88
123
  export interface CarrierPayload {
89
- carrier: typeof CARRIER_VERSION;
124
+ carrier: CarrierVersion;
90
125
  /** The bitgraph/1 proof exactly as the commit returned it. */
91
126
  proof: CarrierProof;
92
127
  floor: CarrierFloor;
128
+ /** The ceiling in position: the next anchor in the chain. Every proof ever made has one. */
93
129
  ceiling: CarrierCeiling;
130
+ /** v2 only. Required on a v2 block, so absence reads as a corrupt block, never as "no ceiling". */
131
+ ceilingInTime?: CarrierCeilingInTime;
132
+ /** v2 only, optional. */
133
+ settlement?: CarrierSettlement;
134
+ /** v2 only, optional. */
135
+ pins?: CarrierPins;
136
+ /** v2 only, optional: the proof's attestation as aws-nitro-witness/1 evidence. */
137
+ attestation?: Record<string, unknown>;
94
138
  }
95
139
 
96
140
  export type CarrierParse =
@@ -187,7 +231,8 @@ export function buildCarrier(inner: Uint8Array, payload: CarrierPayload): Uint8A
187
231
  function payloadShapeError(p: unknown): string | null {
188
232
  const o = record(p);
189
233
  if (o === null) return "payload is not an object";
190
- if (o["carrier"] !== CARRIER_VERSION) return `unknown carrier version ${JSON.stringify(o["carrier"])}`;
234
+ const v2 = o["carrier"] === CARRIER_VERSION_2;
235
+ if (o["carrier"] !== CARRIER_VERSION && !v2) return `unknown carrier version ${JSON.stringify(o["carrier"])}`;
191
236
  if (record(o["proof"]) === null) return "payload carries no proof object";
192
237
  const floor = record(o["floor"]);
193
238
  if (floor === null || floor["status"] !== "present") return "floor must be present: a floorless carrier is not a not-before";
@@ -198,17 +243,44 @@ function payloadShapeError(p: unknown): string | null {
198
243
  }
199
244
  const ceil = record(o["ceiling"]);
200
245
  if (ceil === null) return "ceiling is missing: absence must be a stated fact, not a missing key";
201
- if (ceil["status"] === "unfetched") return null;
202
- if (ceil["status"] !== "present") return `ceiling status must be "unfetched" or "present", got ${JSON.stringify(ceil["status"])}`;
203
- if (ceil["basis"] !== "counter-order") return `unknown ceiling basis ${JSON.stringify(ceil["basis"])}`;
204
- if (record(ceil["anchor"]) === null) return "ceiling carries no anchor proof";
205
- const cw = record(ceil["witness"]);
206
- if (cw === null || typeof cw["headerRlpHex"] !== "string" || typeof cw["blockNumber"] !== "number" || typeof cw["blockHash"] !== "string") {
207
- return "ceiling carries no readable block-header witness";
246
+ if (ceil["status"] !== "unfetched") {
247
+ if (ceil["status"] !== "present") return `ceiling status must be "unfetched" or "present", got ${JSON.stringify(ceil["status"])}`;
248
+ if (ceil["basis"] !== "counter-order") return `unknown ceiling basis ${JSON.stringify(ceil["basis"])}`;
249
+ if (record(ceil["anchor"]) === null) return "ceiling carries no anchor proof";
250
+ const cw = record(ceil["witness"]);
251
+ if (cw === null || typeof cw["headerRlpHex"] !== "string" || typeof cw["blockNumber"] !== "number" || typeof cw["blockHash"] !== "string") {
252
+ return "ceiling carries no readable block-header witness";
253
+ }
254
+ }
255
+ if (!v2) return null;
256
+ // v2: the ceiling in time is stated either way; settlement, pins and the attestation witness are optional.
257
+ const ct = record(o["ceilingInTime"]);
258
+ if (ct === null) return "ceilingInTime is missing: a v2 block states the ceiling in time or that it was not fetched";
259
+ if (ct["status"] === "present") {
260
+ const sc = record(ct["sidecar"]);
261
+ if (sc === null || sc["version"] !== CEILING_SIDECAR_VERSION) return `ceilingInTime carries no ${CEILING_SIDECAR_VERSION} sidecar`;
262
+ } else if (ct["status"] !== "unfetched") return `ceilingInTime status must be "unfetched" or "present", got ${JSON.stringify(ct["status"])}`;
263
+ if (o["settlement"] !== undefined) {
264
+ const st = record(o["settlement"]);
265
+ if (st === null) return "settlement is not an object";
266
+ if (st["status"] === "present") {
267
+ const pt = record(st["pointer"]);
268
+ if (pt === null || pt["version"] !== SETTLEMENT_POINTER_VERSION) return `settlement carries no ${SETTLEMENT_POINTER_VERSION} pointer`;
269
+ } else if (st["status"] !== "unfetched") return `settlement status must be "unfetched" or "present", got ${JSON.stringify(st["status"])}`;
270
+ }
271
+ if (o["pins"] !== undefined && record(o["pins"]) === null) return "pins is not an object";
272
+ if (o["attestation"] !== undefined) {
273
+ const at = record(o["attestation"]);
274
+ if (at === null || at["format"] !== ATTESTATION_WITNESS_VERSION) return `attestation is not an ${ATTESTATION_WITNESS_VERSION} witness`;
208
275
  }
209
276
  return null;
210
277
  }
211
278
 
279
+ /** 1 or 2, from a parsed payload. */
280
+ export function carrierVersionOf(payload: CarrierPayload): 1 | 2 {
281
+ return payload.carrier === CARRIER_VERSION_2 ? 2 : 1;
282
+ }
283
+
212
284
  export function parseCarrier(bytes: Uint8Array): CarrierParse {
213
285
  if (bytes.length < CARRIER_OVERHEAD + 2) return { kind: "none" };
214
286
  if (!magicAt(bytes, bytes.length - 8)) return { kind: "none" };
@@ -260,6 +332,64 @@ export function completeCarrier(
260
332
  return { changed: true, bytes: buildCarrier(p.inner, payload) };
261
333
  }
262
334
 
335
+ /**
336
+ * v2: stamp the ceiling in time (a verified bitgraph-ceiling/1 sidecar) into a
337
+ * carrier, or record that a completion looked and found none yet. Pure; the
338
+ * caller verifies the sidecar BEFORE stamping. Never overwrites a present one
339
+ * that differs (a conflicting embedded ceiling is evidence worth keeping); the
340
+ * same one again is a no-op. A v1 block is left alone: it has no such field.
341
+ */
342
+ export function completeCarrierInTime(
343
+ bytes: Uint8Array,
344
+ sidecar: Record<string, unknown> | null,
345
+ searched?: { at: string },
346
+ ): { changed: boolean; bytes: Uint8Array; error?: string } {
347
+ const p = parseCarrier(bytes);
348
+ if (p.kind !== "carrier") return { changed: false, bytes, error: p.kind === "none" ? "not a carrier" : `corrupt block: ${p.reason}` };
349
+ if (carrierVersionOf(p.payload) !== 2) return { changed: false, bytes, error: "a bitgraph-carrier/1 block has no ceiling in time; rebuild the file as carrier/2" };
350
+ const cur = p.payload.ceilingInTime;
351
+ if (cur && cur.status === "present") {
352
+ if (sidecar === null) return { changed: false, bytes };
353
+ const a = record(cur.sidecar["anchor"]), b = record(sidecar["anchor"]);
354
+ const same = a !== null && b !== null && a["txHash"] === b["txHash"] && String(a["blockHash"] ?? "").toLowerCase() === String(b["blockHash"] ?? "").toLowerCase();
355
+ return same ? { changed: false, bytes } : { changed: false, bytes, error: "carrier already holds a different ceiling in time; refusing to overwrite it" };
356
+ }
357
+ if (sidecar === null && !searched) return { changed: false, bytes };
358
+ const payload: CarrierPayload = {
359
+ ...p.payload,
360
+ ceilingInTime: sidecar === null ? { status: "unfetched", ...(searched ? { searched } : {}) } : { status: "present", sidecar },
361
+ };
362
+ return { changed: true, bytes: buildCarrier(p.inner, payload) };
363
+ }
364
+
365
+ /**
366
+ * v2: the settlement part a verified bitgraph-ceiling/1 sidecar carries, when
367
+ * the writer has attached its bitgraph-settlement/1 pointer; undefined before
368
+ * that. Builders and completions call this so the pointer travels with the
369
+ * ceiling it settles.
370
+ */
371
+ export function settlementFromSidecar(sidecar: Record<string, unknown> | null | undefined): Extract<CarrierSettlement, { status: "present" }> | undefined {
372
+ const p = sidecar ? record(sidecar["settlement"]) : null;
373
+ return p !== null && p["version"] === SETTLEMENT_POINTER_VERSION ? { status: "present", pointer: p } : undefined;
374
+ }
375
+
376
+ /** v2: stamp a verified settlement pointer. Never overwrites a present one that differs. */
377
+ export function completeCarrierSettlement(
378
+ bytes: Uint8Array,
379
+ pointer: Record<string, unknown>,
380
+ ): { changed: boolean; bytes: Uint8Array; error?: string } {
381
+ const p = parseCarrier(bytes);
382
+ if (p.kind !== "carrier") return { changed: false, bytes, error: p.kind === "none" ? "not a carrier" : `corrupt block: ${p.reason}` };
383
+ if (carrierVersionOf(p.payload) !== 2) return { changed: false, bytes, error: "a bitgraph-carrier/1 block has no settlement; rebuild the file as carrier/2" };
384
+ const cur = p.payload.settlement;
385
+ if (cur && cur.status === "present") {
386
+ const a = record(cur.pointer["l1"]), b = record(pointer["l1"]);
387
+ const same = a !== null && b !== null && a["txHash"] === b["txHash"] && String(a["blockHash"] ?? "").toLowerCase() === String(b["blockHash"] ?? "").toLowerCase();
388
+ return same ? { changed: false, bytes } : { changed: false, bytes, error: "carrier already holds a different settlement; refusing to overwrite it" };
389
+ }
390
+ return { changed: true, bytes: buildCarrier(p.inner, { ...p.payload, settlement: { status: "present", pointer } }) };
391
+ }
392
+
263
393
  /* ── Consistency checks (no network, no signatures — bindings only) ─────── */
264
394
 
265
395
  /** The identity an authenticated anchor proof claims: enclave-signed since v7. */
@@ -457,18 +587,44 @@ export function verifyWitnessHeader(w: CarrierWitness): WitnessCheck {
457
587
 
458
588
  export interface CarrierBounds {
459
589
  notBefore: { blockNumber: number; blockHash: string; timestamp: number | null };
460
- /** null means NOT FETCHED — say so in those words — never "none exists". */
590
+ /** The ceiling in POSITION: the next anchor. null means NOT FETCHED — say so in those words — never "none exists". */
461
591
  notAfter: { blockNumber: number; blockHash: string; timestamp: number | null } | null;
592
+ /**
593
+ * v2: the ceiling in TIME, as the sidecar states it (verifyCarrier recomputes
594
+ * it from the header). null on a v1 block or when not fetched.
595
+ */
596
+ existedBy: { chain: "base"; blockNumber: number; blockHash: string; timestamp: number } | null;
597
+ /** v2: the Ethereum block that committed the Base batch data, as the pointer states it. */
598
+ settledBy: { chain: "ethereum"; blockNumber: number; blockHash: string; timestamp: number } | null;
462
599
  }
463
600
 
464
601
  export function carrierBounds(payload: CarrierPayload): CarrierBounds {
465
602
  const f = payload.floor.witness;
466
603
  const floorTs = verifyWitnessHeader(f);
467
604
  const notBefore = { blockNumber: f.blockNumber, blockHash: f.blockHash.toLowerCase(), timestamp: floorTs.ok ? floorTs.timestamp : null };
468
- if (payload.ceiling.status !== "present") return { notBefore, notAfter: null };
469
- const c = payload.ceiling.witness;
470
- const ceilTs = verifyWitnessHeader(c);
471
- return { notBefore, notAfter: { blockNumber: c.blockNumber, blockHash: c.blockHash.toLowerCase(), timestamp: ceilTs.ok ? ceilTs.timestamp : null } };
605
+ let notAfter: CarrierBounds["notAfter"] = null;
606
+ if (payload.ceiling.status === "present") {
607
+ const c = payload.ceiling.witness;
608
+ const ceilTs = verifyWitnessHeader(c);
609
+ notAfter = { blockNumber: c.blockNumber, blockHash: c.blockHash.toLowerCase(), timestamp: ceilTs.ok ? ceilTs.timestamp : null };
610
+ }
611
+ let existedBy: CarrierBounds["existedBy"] = null;
612
+ const ct = payload.ceilingInTime;
613
+ if (ct && ct.status === "present") {
614
+ const a = record(ct.sidecar["anchor"]);
615
+ if (a && typeof a["blockNumber"] === "number" && typeof a["blockHash"] === "string" && typeof a["blockTimestamp"] === "number") {
616
+ existedBy = { chain: "base", blockNumber: a["blockNumber"], blockHash: a["blockHash"].toLowerCase(), timestamp: a["blockTimestamp"] };
617
+ }
618
+ }
619
+ let settledBy: CarrierBounds["settledBy"] = null;
620
+ const st = payload.settlement;
621
+ if (st && st.status === "present") {
622
+ const l1 = record(st.pointer["l1"]);
623
+ if (l1 && typeof l1["blockNumber"] === "number" && typeof l1["blockHash"] === "string" && typeof l1["blockTimestamp"] === "number") {
624
+ settledBy = { chain: "ethereum", blockNumber: l1["blockNumber"], blockHash: l1["blockHash"].toLowerCase(), timestamp: l1["blockTimestamp"] };
625
+ }
626
+ }
627
+ return { notBefore, notAfter, existedBy, settledBy };
472
628
  }
473
629
 
474
630
  /** SHA-256 of the committed bytes, compared to the carried proof's artifact digest. */
@@ -0,0 +1,326 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * The EVM pieces a ceiling check needs, written out so the check runs offline
5
+ * with nothing but @noble: RLP, keccak256, a block header's fields, an
6
+ * EIP-1559 transaction and its sender, and a Merkle-Patricia inclusion proof
7
+ * against a header's transactionsRoot.
8
+ *
9
+ * Decoding is STRICT. A non-canonical RLP length, trailing bytes, or a proof
10
+ * node that does not hash to the reference that points at it is a refusal,
11
+ * never a best effort: every value this file returns is bound to a 32-byte
12
+ * hash the caller already holds.
13
+ */
14
+
15
+ import { keccak_256 } from "@noble/hashes/sha3";
16
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
17
+
18
+ export type RlpItem = Uint8Array | RlpItem[];
19
+
20
+ export function hexToBytes(hex: string): Uint8Array {
21
+ let h = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
22
+ if (h.length % 2) h = "0" + h;
23
+ if (!/^[0-9a-fA-F]*$/.test(h)) throw new TypeError("not hex");
24
+ const out = new Uint8Array(h.length / 2);
25
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
26
+ return out;
27
+ }
28
+
29
+ export function bytesToHex(bytes: Uint8Array): string {
30
+ let s = "0x";
31
+ for (const b of bytes) s += b.toString(16).padStart(2, "0");
32
+ return s;
33
+ }
34
+
35
+ export function keccak256(bytes: Uint8Array): Uint8Array {
36
+ return keccak_256(bytes);
37
+ }
38
+
39
+ function concat(...parts: Uint8Array[]): Uint8Array {
40
+ let n = 0;
41
+ for (const p of parts) n += p.length;
42
+ const out = new Uint8Array(n);
43
+ let o = 0;
44
+ for (const p of parts) { out.set(p, o); o += p.length; }
45
+ return out;
46
+ }
47
+
48
+ export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
49
+ if (a.length !== b.length) return false;
50
+ let d = 0;
51
+ for (let i = 0; i < a.length; i++) d |= a[i]! ^ b[i]!;
52
+ return d === 0;
53
+ }
54
+
55
+ // ── RLP ────────────────────────────────────────────────────────────────────
56
+
57
+ function encodeLength(len: number, offset: number): Uint8Array {
58
+ if (len < 56) return Uint8Array.of(offset + len);
59
+ const lenBytes: number[] = [];
60
+ for (let n = len; n > 0; n = Math.floor(n / 256)) lenBytes.unshift(n % 256);
61
+ return Uint8Array.of(offset + 55 + lenBytes.length, ...lenBytes);
62
+ }
63
+
64
+ export function rlpEncode(item: RlpItem): Uint8Array {
65
+ if (item instanceof Uint8Array) {
66
+ if (item.length === 1 && item[0]! < 0x80) return item;
67
+ return concat(encodeLength(item.length, 0x80), item);
68
+ }
69
+ const body = concat(...item.map(rlpEncode));
70
+ return concat(encodeLength(body.length, 0xc0), body);
71
+ }
72
+
73
+ /** Decode exactly one RLP item filling all of `bytes`; throws on anything non-canonical. */
74
+ export function rlpDecode(bytes: Uint8Array): RlpItem {
75
+ const [item, end] = decodeAt(bytes, 0);
76
+ if (end !== bytes.length) throw new TypeError("rlp: trailing bytes");
77
+ return item;
78
+ }
79
+
80
+ function readLength(bytes: Uint8Array, pos: number, lenOfLen: number): number {
81
+ if (pos + lenOfLen > bytes.length) throw new TypeError("rlp: truncated length");
82
+ if (bytes[pos] === 0) throw new TypeError("rlp: length with a leading zero");
83
+ let n = 0;
84
+ for (let i = 0; i < lenOfLen; i++) n = n * 256 + bytes[pos + i]!;
85
+ if (n < 56) throw new TypeError("rlp: long form for a short length");
86
+ return n;
87
+ }
88
+
89
+ function decodeAt(bytes: Uint8Array, pos: number): [RlpItem, number] {
90
+ if (pos >= bytes.length) throw new TypeError("rlp: truncated");
91
+ const b = bytes[pos]!;
92
+ if (b < 0x80) return [bytes.slice(pos, pos + 1), pos + 1];
93
+ if (b <= 0xb7) {
94
+ const len = b - 0x80;
95
+ const end = pos + 1 + len;
96
+ if (end > bytes.length) throw new TypeError("rlp: truncated string");
97
+ if (len === 1 && bytes[pos + 1]! < 0x80) throw new TypeError("rlp: single byte should encode as itself");
98
+ return [bytes.slice(pos + 1, end), end];
99
+ }
100
+ if (b <= 0xbf) {
101
+ const lenOfLen = b - 0xb7;
102
+ const len = readLength(bytes, pos + 1, lenOfLen);
103
+ const start = pos + 1 + lenOfLen;
104
+ if (start + len > bytes.length) throw new TypeError("rlp: truncated string");
105
+ return [bytes.slice(start, start + len), start + len];
106
+ }
107
+ let start: number;
108
+ let len: number;
109
+ if (b <= 0xf7) {
110
+ len = b - 0xc0;
111
+ start = pos + 1;
112
+ } else {
113
+ const lenOfLen = b - 0xf7;
114
+ len = readLength(bytes, pos + 1, lenOfLen);
115
+ start = pos + 1 + lenOfLen;
116
+ }
117
+ const end = start + len;
118
+ if (end > bytes.length) throw new TypeError("rlp: truncated list");
119
+ const items: RlpItem[] = [];
120
+ let p = start;
121
+ while (p < end) {
122
+ const [it, next] = decodeAt(bytes, p);
123
+ items.push(it);
124
+ p = next;
125
+ }
126
+ if (p !== end) throw new TypeError("rlp: list overran its length");
127
+ return [items, end];
128
+ }
129
+
130
+ function asBytes(item: RlpItem | undefined, what: string): Uint8Array {
131
+ if (!(item instanceof Uint8Array)) throw new TypeError(`${what}: expected a byte string`);
132
+ return item;
133
+ }
134
+
135
+ function asList(item: RlpItem | undefined, what: string): RlpItem[] {
136
+ if (!Array.isArray(item)) throw new TypeError(`${what}: expected a list`);
137
+ return item;
138
+ }
139
+
140
+ /** An RLP scalar (big-endian, no leading zeros) as a bigint. */
141
+ export function rlpUint(item: RlpItem | undefined, what: string): bigint {
142
+ const b = asBytes(item, what);
143
+ if (b.length > 0 && b[0] === 0) throw new TypeError(`${what}: integer with a leading zero`);
144
+ let n = 0n;
145
+ for (const x of b) n = (n << 8n) | BigInt(x);
146
+ return n;
147
+ }
148
+
149
+ // ── Block header ───────────────────────────────────────────────────────────
150
+
151
+ export interface DecodedHeader {
152
+ /** keccak256 of the header RLP: the block hash. */
153
+ hash: string;
154
+ parentHash: string;
155
+ transactionsRoot: string;
156
+ number: number;
157
+ timestamp: number;
158
+ }
159
+
160
+ /** Decode the fields a ceiling reads from a header RLP, and hash it. */
161
+ export function decodeHeader(headerRlp: Uint8Array): DecodedHeader {
162
+ const f = asList(rlpDecode(headerRlp), "header");
163
+ if (f.length < 15) throw new TypeError("header: too few fields");
164
+ const num = rlpUint(f[8], "header.number");
165
+ const ts = rlpUint(f[11], "header.timestamp");
166
+ if (num > BigInt(Number.MAX_SAFE_INTEGER) || ts > BigInt(Number.MAX_SAFE_INTEGER)) throw new TypeError("header: number out of range");
167
+ const txRoot = asBytes(f[4], "header.transactionsRoot");
168
+ const parent = asBytes(f[0], "header.parentHash");
169
+ if (txRoot.length !== 32 || parent.length !== 32) throw new TypeError("header: bad root length");
170
+ return {
171
+ hash: bytesToHex(keccak256(headerRlp)),
172
+ parentHash: bytesToHex(parent),
173
+ transactionsRoot: bytesToHex(txRoot),
174
+ number: Number(num),
175
+ timestamp: Number(ts),
176
+ };
177
+ }
178
+
179
+ // ── EIP-1559 transaction ───────────────────────────────────────────────────
180
+
181
+ export interface DecodedTx {
182
+ type: 2;
183
+ chainId: bigint;
184
+ nonce: bigint;
185
+ to: string | null;
186
+ value: bigint;
187
+ data: Uint8Array;
188
+ /** Address recovered from the signature, lowercase 0x hex. */
189
+ from: string;
190
+ /** keccak256 of the raw transaction: its hash on chain. */
191
+ hash: string;
192
+ }
193
+
194
+ /**
195
+ * Decode a signed type-2 transaction and recover its sender. Only type 2 is
196
+ * accepted: the writer sends nothing else, and a narrower decoder is a
197
+ * smaller thing to get wrong.
198
+ */
199
+ export function decodeEip1559(raw: Uint8Array): DecodedTx {
200
+ if (raw.length < 2 || raw[0] !== 0x02) throw new TypeError("tx: not an EIP-1559 (type 2) transaction");
201
+ const f = asList(rlpDecode(raw.slice(1)), "tx");
202
+ if (f.length !== 12) throw new TypeError("tx: a type-2 transaction has 12 fields");
203
+ const chainId = rlpUint(f[0], "tx.chainId");
204
+ const nonce = rlpUint(f[1], "tx.nonce");
205
+ const toBytes = asBytes(f[5], "tx.to");
206
+ if (toBytes.length !== 0 && toBytes.length !== 20) throw new TypeError("tx: bad recipient length");
207
+ const value = rlpUint(f[6], "tx.value");
208
+ const data = asBytes(f[7], "tx.data");
209
+ asList(f[8], "tx.accessList");
210
+ const yParity = rlpUint(f[9], "tx.yParity");
211
+ const r = rlpUint(f[10], "tx.r");
212
+ const s = rlpUint(f[11], "tx.s");
213
+ if (yParity > 1n) throw new TypeError("tx: yParity must be 0 or 1");
214
+ const signingHash = keccak256(concat(Uint8Array.of(0x02), rlpEncode(f.slice(0, 9))));
215
+ const compact = hexToBytes(r.toString(16).padStart(64, "0") + s.toString(16).padStart(64, "0"));
216
+ const sig = secp256k1.Signature.fromBytes(compact, "compact");
217
+ // Ethereum rejects high-s signatures (EIP-2); so do we.
218
+ if (sig.hasHighS()) throw new TypeError("tx: high-s signature");
219
+ const pub = sig.addRecoveryBit(Number(yParity)).recoverPublicKey(signingHash).toBytes(false);
220
+ const from = bytesToHex(keccak256(pub.slice(1)).slice(12));
221
+ return {
222
+ type: 2,
223
+ chainId,
224
+ nonce,
225
+ to: toBytes.length === 0 ? null : bytesToHex(toBytes),
226
+ value,
227
+ data,
228
+ from,
229
+ hash: bytesToHex(keccak256(raw)),
230
+ };
231
+ }
232
+
233
+ // ── Merkle-Patricia inclusion proof ────────────────────────────────────────
234
+
235
+ function toNibbles(bytes: Uint8Array): number[] {
236
+ const out: number[] = [];
237
+ for (const b of bytes) out.push(b >> 4, b & 0x0f);
238
+ return out;
239
+ }
240
+
241
+ /** Hex-prefix decode: [nibbles, isLeaf]. */
242
+ function hexPrefix(encoded: Uint8Array): [number[], boolean] {
243
+ if (encoded.length === 0) throw new TypeError("mpt: empty path");
244
+ const nib = toNibbles(encoded);
245
+ const flag = nib[0]!;
246
+ if (flag > 3) throw new TypeError("mpt: bad path flag");
247
+ const isLeaf = flag >= 2;
248
+ const odd = flag % 2 === 1;
249
+ if (!odd && nib[1] !== 0) throw new TypeError("mpt: even path must pad with zero");
250
+ return [nib.slice(odd ? 1 : 2), isLeaf];
251
+ }
252
+
253
+ /**
254
+ * Walk an inclusion proof for `key` from `root`. Returns the stored value, or
255
+ * null when the proof shows the key absent or does not hold together (a node
256
+ * that does not hash to the reference pointing at it, a path that diverges).
257
+ * Every node is bound to its parent's reference, so the value is bound to
258
+ * `root` and to nothing the prover could choose.
259
+ */
260
+ export function mptVerify(root: Uint8Array, key: Uint8Array, proof: readonly Uint8Array[]): Uint8Array | null {
261
+ const path = toNibbles(key);
262
+ let want: Uint8Array = root; // a 32-byte hash, or an inline node's own RLP
263
+ let depth = 0;
264
+ let i = 0;
265
+ while (true) {
266
+ let nodeRlp: Uint8Array;
267
+ if (want.length === 32) {
268
+ const next = proof[i++];
269
+ if (!next || !bytesEqual(keccak256(next), want)) return null;
270
+ nodeRlp = next;
271
+ } else {
272
+ nodeRlp = want; // inline node (<32 bytes), embedded in its parent
273
+ }
274
+ let node: RlpItem[];
275
+ try {
276
+ node = asList(rlpDecode(nodeRlp), "mpt node");
277
+ } catch {
278
+ return null;
279
+ }
280
+ if (node.length === 17) {
281
+ if (depth === path.length) {
282
+ const v = node[16];
283
+ return v instanceof Uint8Array && v.length > 0 ? v : null;
284
+ }
285
+ const child = node[path[depth]!];
286
+ depth += 1;
287
+ if (child === undefined) return null;
288
+ if (child instanceof Uint8Array) {
289
+ if (child.length === 0) return null;
290
+ want = child;
291
+ } else {
292
+ want = rlpEncode(child);
293
+ }
294
+ continue;
295
+ }
296
+ if (node.length === 2) {
297
+ let seg: number[];
298
+ let isLeaf: boolean;
299
+ try {
300
+ [seg, isLeaf] = hexPrefix(asBytes(node[0], "mpt path"));
301
+ } catch {
302
+ return null;
303
+ }
304
+ for (let k = 0; k < seg.length; k++) if (path[depth + k] !== seg[k]) return null;
305
+ depth += seg.length;
306
+ if (isLeaf) {
307
+ if (depth !== path.length) return null;
308
+ const v = node[1];
309
+ return v instanceof Uint8Array ? v : null;
310
+ }
311
+ const child = node[1]!;
312
+ want = child instanceof Uint8Array ? child : rlpEncode(child);
313
+ continue;
314
+ }
315
+ return null;
316
+ }
317
+ }
318
+
319
+ /** The trie key of transaction `index` in a block: rlp(index). */
320
+ export function txTrieKey(index: number): Uint8Array {
321
+ if (!Number.isInteger(index) || index < 0) throw new RangeError("tx index");
322
+ if (index === 0) return rlpEncode(new Uint8Array(0));
323
+ const b: number[] = [];
324
+ for (let n = index; n > 0; n = Math.floor(n / 256)) b.unshift(n % 256);
325
+ return rlpEncode(Uint8Array.from(b));
326
+ }