@mikeargento/bitgraph-verify 1.13.1 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
@@ -0,0 +1,112 @@
1
+ // Copyright (c) 2024-2026 Argento Computing Inc. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * Build a block's transaction trie and the inclusion proof for one
5
+ * transaction. The result is only ever used after its root has been compared
6
+ * with the block header's transactionsRoot, so a construction bug shows up
7
+ * as a refusal to write the proof, never as a wrong proof.
8
+ */
9
+
10
+ import { keccak256, rlpEncode, txTrieKey, type RlpItem } from "./ceiling-evm.js";
11
+
12
+ type Node =
13
+ | { kind: "leaf"; path: number[]; value: Uint8Array }
14
+ | { kind: "ext"; path: number[]; child: Node }
15
+ | { kind: "branch"; children: (Node | null)[]; value: Uint8Array };
16
+
17
+ interface Entry { key: number[]; value: Uint8Array }
18
+
19
+ function nibbles(bytes: Uint8Array): number[] {
20
+ const out: number[] = [];
21
+ for (const b of bytes) out.push(b >> 4, b & 0x0f);
22
+ return out;
23
+ }
24
+
25
+ function hexPrefix(nib: number[], leaf: boolean): Uint8Array {
26
+ const odd = nib.length % 2 === 1;
27
+ const flag = (leaf ? 2 : 0) + (odd ? 1 : 0);
28
+ const all = odd ? [flag, ...nib] : [flag, 0, ...nib];
29
+ const out = new Uint8Array(all.length / 2);
30
+ for (let i = 0; i < out.length; i++) out[i] = (all[2 * i]! << 4) | all[2 * i + 1]!;
31
+ return out;
32
+ }
33
+
34
+ function buildNode(entries: Entry[], depth: number): Node {
35
+ if (entries.length === 1) {
36
+ const e = entries[0]!;
37
+ return { kind: "leaf", path: e.key.slice(depth), value: e.value };
38
+ }
39
+ let common = 0;
40
+ const first = entries[0]!.key;
41
+ outer: while (true) {
42
+ const n = first[depth + common];
43
+ if (n === undefined) break;
44
+ for (const e of entries) if (e.key[depth + common] !== n) break outer;
45
+ common++;
46
+ }
47
+ if (common > 0) {
48
+ return { kind: "ext", path: first.slice(depth, depth + common), child: buildNode(entries, depth + common) };
49
+ }
50
+ const groups: Entry[][] = Array.from({ length: 16 }, () => []);
51
+ let value: Uint8Array = new Uint8Array(0);
52
+ for (const e of entries) {
53
+ if (e.key.length === depth) value = e.value;
54
+ else groups[e.key[depth]!]!.push(e);
55
+ }
56
+ return { kind: "branch", children: groups.map((g) => (g.length ? buildNode(g, depth + 1) : null)), value };
57
+ }
58
+
59
+ class Encoder {
60
+ private readonly memo = new Map<Node, Uint8Array>();
61
+ rlp(node: Node): Uint8Array {
62
+ const known = this.memo.get(node);
63
+ if (known) return known;
64
+ const enc = rlpEncode(this.item(node));
65
+ this.memo.set(node, enc);
66
+ return enc;
67
+ }
68
+ item(node: Node): RlpItem {
69
+ switch (node.kind) {
70
+ case "leaf": return [hexPrefix(node.path, true), node.value];
71
+ case "ext": return [hexPrefix(node.path, false), this.ref(node.child)];
72
+ case "branch": return [...node.children.map((c) => (c ? this.ref(c) : new Uint8Array(0))), node.value];
73
+ }
74
+ }
75
+ /** A child as its parent holds it: inline when its RLP is under 32 bytes, else its hash. */
76
+ ref(node: Node): RlpItem {
77
+ const enc = this.rlp(node);
78
+ return enc.length < 32 ? this.item(node) : keccak256(enc);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * The trie root over `values` keyed by rlp(index), and the proof for `index`:
84
+ * the root node, then every node on the path its parent references by hash.
85
+ */
86
+ export function txTrieProof(values: readonly Uint8Array[], index: number): { root: Uint8Array; proof: Uint8Array[] } {
87
+ if (values.length === 0) throw new TypeError("an empty block has no transaction to prove");
88
+ if (index < 0 || index >= values.length) throw new RangeError("transaction index out of range");
89
+ const entries: Entry[] = values.map((v, i) => ({ key: nibbles(txTrieKey(i)), value: v }));
90
+ const root = buildNode(entries, 0);
91
+ const enc = new Encoder();
92
+ const target = nibbles(txTrieKey(index));
93
+ const proof: Uint8Array[] = [enc.rlp(root)];
94
+ let node: Node = root;
95
+ let depth = 0;
96
+ while (node.kind !== "leaf") {
97
+ let next: Node | null;
98
+ if (node.kind === "ext") {
99
+ depth += node.path.length;
100
+ next = node.child;
101
+ } else {
102
+ if (depth === target.length) break;
103
+ next = node.children[target[depth]!] ?? null;
104
+ depth += 1;
105
+ }
106
+ if (!next) throw new Error("target not in trie");
107
+ const r = enc.rlp(next);
108
+ if (r.length >= 32) proof.push(r);
109
+ node = next;
110
+ }
111
+ return { root: keccak256(proof[0]!), proof };
112
+ }