nirium-avalanche 0.3.0 → 0.4.1

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.
@@ -1,159 +1,192 @@
1
- // verify-evm-core.mjs - read-only check of a Nirium EVM payment binding.
2
- //
3
- // The one verifier: the CLI (verify-evm-receipt.mjs), verifyReceipt() and the browser all run
4
- // this file. It has no Node-only imports (no node:crypto, no fs), so it also runs in a browser:
5
- // sha256 comes from viem (built on @noble/hashes).
6
- //
7
- // Format "nirium-payment-binding-v1" (fixed 26-nov-2026):
8
- // {
9
- // "version": "nirium-payment-binding-v1",
10
- // "content_sha256": "<hex sha256 of canonical(record)>",
11
- // "record": {
12
- // "labels": ["selftest"],
13
- // "payment": {
14
- // "amount": "10000", "asset": "0x...", "decimals": 6,
15
- // "from": "0x..payer", "to": "0x..payTo", "tx": "0x..",
16
- // "locator": { "index": 17, "kind": "evm-log" }, // block-level log index
17
- // "network": "eip155:43113",
18
- // "x402": { "nonce": "0x..authNonce", "resource": "https://...", "scheme": "exact" }
19
- // },
20
- // "purpose": { "note": "...", "ref": "..." }
21
- // },
22
- // "agent": { "alg": "eip191-secp256k1", "key": "0x..payer",
23
- // "signature": "0x..", "statement": "nirium-audit-v1:<content_sha256>" },
24
- // "network": "eip155:43113"
25
- // }
26
- //
27
- // canonical() = keys sorted recursively, no whitespace, values as JSON.stringify
28
- // writes them; applied ONLY to `record`.
29
- // --no-sig skips the `agent` block entirely (used for third-party txs we did
30
- // not sign); the record hash and every on-chain check still run.
31
- //
32
- // Not supported yet: payers that are smart wallets (ERC-1271/6492)
33
- // need publicClient.verifyMessage instead of the standalone ECDSA verifyMessage.
34
- // Not supported yet: seller-signed bindings (agent.key == payment.to) once that role exists.
35
- //
36
- // No keys, no writes: only eth_chainId and eth_getTransactionReceipt.
37
-
38
- import {
39
- createPublicClient, http, decodeEventLog, parseAbi, getAddress,
40
- isAddressEqual, verifyMessage, sha256, stringToBytes,
41
- } from "viem";
42
- import { avalanche, avalancheFuji } from "viem/chains";
43
-
44
- export const VERSION = "nirium-payment-binding-v1";
45
- export const STATEMENT_PREFIX = "nirium-audit-v1:";
46
-
47
- const CHAINS = {
48
- "eip155:43114": { chain: avalanche, usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" },
49
- "eip155:43113": { chain: avalancheFuji, usdc: "0x5425890298aed601595a70AB815c96711a31Bc65" },
50
- };
51
-
52
- const ABI = parseAbi([
53
- "event Transfer(address indexed from, address indexed to, uint256 value)",
54
- "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)",
55
- ]);
56
-
57
- export function canonicalize(v) {
58
- if (v === null || typeof v !== "object") return JSON.stringify(v);
59
- if (Array.isArray(v)) return "[" + v.map(canonicalize).join(",") + "]";
60
- return "{" + Object.keys(v).sort()
61
- .filter((k) => v[k] !== undefined)
62
- .map((k) => JSON.stringify(k) + ":" + canonicalize(v[k])).join(",") + "}";
63
- }
64
-
65
- /** sha256 of the UTF-8 bytes of a string, as lowercase hex without 0x. */
66
- export function sha256Hex(s) {
67
- return sha256(stringToBytes(s)).slice(2);
68
- }
69
-
70
- export function contentSha256(record) {
71
- return sha256Hex(canonicalize(record));
72
- }
73
-
74
- const eqAddr = (a, b) => { try { return isAddressEqual(a, b); } catch { return false; } };
75
-
76
- export async function verifyBinding(doc, { requireSig = true, rpc } = {}) {
77
- const checks = [];
78
- const add = (name, ok, detail = "") => checks.push({ name, ok: !!ok, detail });
79
-
80
- const p = doc?.record?.payment;
81
- if (!p) throw new Error("missing record.payment");
82
- for (const k of ["amount", "asset", "from", "to", "tx", "network"]) {
83
- if (p[k] === undefined || p[k] === null || p[k] === "") throw new Error(`missing record.payment.${k}`);
84
- }
85
- if (!p.locator || p.locator.index === undefined) throw new Error("missing record.payment.locator.index");
86
- if (!p.x402?.nonce) throw new Error("missing record.payment.x402.nonce");
87
- const net = CHAINS[p.network];
88
- if (!net) throw new Error(`unsupported network ${p.network}`);
89
-
90
- // Document-level consistency.
91
- add("version == nirium-payment-binding-v1", doc.version === VERSION, `version=${doc.version}`);
92
- add("network == record.payment.network", doc.network === p.network, `doc=${doc.network} payment=${p.network}`);
93
- add("locator.kind == evm-log", p.locator.kind === "evm-log", `kind=${p.locator.kind}`);
94
- const computed = contentSha256(doc.record);
95
- add("content_sha256 == sha256(canonical(record))", doc.content_sha256 === computed,
96
- `doc=${doc.content_sha256} computed=${computed}`);
97
- add("asset is Circle USDC for this network", eqAddr(p.asset, net.usdc), `asset=${p.asset} expected=${net.usdc}`);
98
- add("decimals == 6", p.decimals === 6, `decimals=${p.decimals}`);
99
-
100
- // Chain.
101
- const client = createPublicClient({ chain: net.chain, transport: http(rpc) });
102
- const chainId = await client.getChainId();
103
- add("network == eip155:<RPC chainId>", p.network === `eip155:${chainId}`, `rpc chainId=${chainId}`);
104
-
105
- let receipt = null;
106
- try {
107
- receipt = await client.getTransactionReceipt({ hash: p.tx });
108
- } catch (e) {
109
- add("tx receipt found", false, e.shortMessage || e.message);
110
- }
111
- if (receipt) {
112
- add("tx status success (1)", receipt.status === "success", `status=${receipt.status} block=${receipt.blockNumber}`);
113
-
114
- const idx = Number(p.locator.index);
115
- const amount = BigInt(p.amount);
116
- const log = receipt.logs.find((l) => l.logIndex === idx);
117
- if (!log) {
118
- add(`log ${idx} exists in tx`, false, `tx log indexes: ${receipt.logs.map((l) => l.logIndex).join(",")}`);
119
- } else {
120
- add(`log ${idx} emitted by asset`, eqAddr(log.address, p.asset), `emitter=${log.address}`);
121
- let ev = null;
122
- try { ev = decodeEventLog({ abi: ABI, data: log.data, topics: log.topics }); } catch {}
123
- const isTransfer = ev?.eventName === "Transfer";
124
- add(`log ${idx} is Transfer`, isTransfer, ev ? `event=${ev.eventName}` : "not decodable");
125
- if (isTransfer) {
126
- add("Transfer.from == payment.from", eqAddr(ev.args.from, p.from), `log=${ev.args.from}`);
127
- add("Transfer.to == payment.to", eqAddr(ev.args.to, p.to), `log=${ev.args.to}`);
128
- add("Transfer.value == payment.amount", ev.args.value === amount, `log=${ev.args.value} record=${amount}`);
129
- }
130
- }
131
-
132
- const auths = receipt.logs
133
- .filter((l) => eqAddr(l.address, p.asset))
134
- .map((l) => { try { return decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }); } catch { return null; } })
135
- .filter((e) => e?.eventName === "AuthorizationUsed");
136
- const match = auths.find((e) => eqAddr(e.args.authorizer, p.from)
137
- && e.args.nonce.toLowerCase() === String(p.x402.nonce).toLowerCase());
138
- add("AuthorizationUsed(payment.from, x402.nonce) in same tx", match,
139
- `found ${auths.length}: ${auths.map((e) => `${e.args.authorizer}/${e.args.nonce}`).join(" ; ") || "none"}`);
140
- }
141
-
142
- // Agent signature (payer).
143
- if (!requireSig) {
144
- add("agent signature (skipped: --no-sig)", true, "NOT checked");
145
- } else if (!doc.agent?.signature || !doc.agent?.key || !doc.agent?.statement) {
146
- add("agent block present", false, "agent.key, agent.statement and agent.signature are required");
147
- } else {
148
- const a = doc.agent;
149
- add("agent.alg == eip191-secp256k1", a.alg === "eip191-secp256k1", `alg=${a.alg}`);
150
- add("agent.statement == nirium-audit-v1:<content_sha256>", a.statement === STATEMENT_PREFIX + doc.content_sha256,
151
- `statement=${a.statement}`);
152
- add("agent.key == payment.from (payer signs)", eqAddr(a.key, p.from), `key=${a.key}`);
153
- let valid = false;
154
- try { valid = await verifyMessage({ address: a.key, message: a.statement, signature: a.signature }); } catch {}
155
- add("EIP-191 signature by agent.key over agent.statement", valid);
156
- }
157
-
158
- return { ok: checks.every((c) => c.ok), checks };
159
- }
1
+ // verify-evm-core.mjs - read-only check of a Nirium EVM payment binding.
2
+ //
3
+ // The one verifier: the CLI (verify-evm-receipt.mjs), verifyReceipt() and the browser all run
4
+ // this file. It has no Node-only imports (no node:crypto, no fs), so it also runs in a browser:
5
+ // sha256 comes from viem (built on @noble/hashes).
6
+ //
7
+ // Format "nirium-payment-binding-v1" (fixed 26-nov-2026):
8
+ // {
9
+ // "version": "nirium-payment-binding-v1",
10
+ // "content_sha256": "<hex sha256 of canonical(record)>",
11
+ // "record": {
12
+ // "labels": ["selftest"],
13
+ // "payment": {
14
+ // "amount": "10000", "asset": "0x...", "decimals": 6,
15
+ // "from": "0x..payer", "to": "0x..payTo", "tx": "0x..",
16
+ // "locator": { "index": 17, "kind": "evm-log" }, // block-level log index
17
+ // "network": "eip155:43113",
18
+ // "x402": { "nonce": "0x..authNonce", "resource": "https://...", "scheme": "exact" }
19
+ // },
20
+ // "purpose": { "note": "...", "ref": "..." }
21
+ // },
22
+ // "agent": { "alg": "eip191-secp256k1", "key": "0x..payer",
23
+ // "signature": "0x..", "statement": "nirium-audit-v1:<content_sha256>" },
24
+ // "network": "eip155:43113"
25
+ // }
26
+ //
27
+ // canonical() = keys sorted recursively, no whitespace, values as JSON.stringify
28
+ // writes them; applied ONLY to `record`.
29
+ // --no-sig skips the `agent` block entirely (used for third-party txs we did
30
+ // not sign); the record hash and every on-chain check still run.
31
+ //
32
+ // Not supported yet: payers that are smart wallets (ERC-1271/6492)
33
+ // need publicClient.verifyMessage instead of the standalone ECDSA verifyMessage.
34
+ // Not supported yet: seller-signed bindings (agent.key == payment.to) once that role exists.
35
+ //
36
+ // Optional "pq" block (post-quantum, ML-DSA-65): see verify-evm-pq.mjs. When present it is always
37
+ // checked; --require-pq (requirePq) also fails a receipt without one.
38
+ //
39
+ // No keys, no writes: only eth_chainId, eth_getTransactionReceipt and, for `pq`, one eth_call.
40
+
41
+ import {
42
+ createPublicClient, http, decodeEventLog, parseAbi, getAddress,
43
+ isAddressEqual, verifyMessage, sha256, stringToBytes,
44
+ } from "viem";
45
+ import { avalanche, avalancheFuji } from "viem/chains";
46
+ import { verifyPqSignature, checkPqRegistration, PQ_REGISTRY } from "./verify-evm-pq.mjs";
47
+
48
+ export const VERSION = "nirium-payment-binding-v1";
49
+ export const STATEMENT_PREFIX = "nirium-audit-v1:";
50
+
51
+ const CHAINS = {
52
+ "eip155:43114": { chain: avalanche, usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" },
53
+ "eip155:43113": { chain: avalancheFuji, usdc: "0x5425890298aed601595a70AB815c96711a31Bc65" },
54
+ };
55
+
56
+ const ABI = parseAbi([
57
+ "event Transfer(address indexed from, address indexed to, uint256 value)",
58
+ "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)",
59
+ ]);
60
+
61
+ export function canonicalize(v) {
62
+ if (v === null || typeof v !== "object") return JSON.stringify(v);
63
+ if (Array.isArray(v)) return "[" + v.map(canonicalize).join(",") + "]";
64
+ return "{" + Object.keys(v).sort()
65
+ .filter((k) => v[k] !== undefined)
66
+ .map((k) => JSON.stringify(k) + ":" + canonicalize(v[k])).join(",") + "}";
67
+ }
68
+
69
+ /** sha256 of the UTF-8 bytes of a string, as lowercase hex without 0x. */
70
+ export function sha256Hex(s) {
71
+ return sha256(stringToBytes(s)).slice(2);
72
+ }
73
+
74
+ export function contentSha256(record) {
75
+ return sha256Hex(canonicalize(record));
76
+ }
77
+
78
+ const eqAddr = (a, b) => { try { return isAddressEqual(a, b); } catch { return false; } };
79
+
80
+ export async function verifyBinding(doc, { requireSig = true, requirePq = false, rpc } = {}) {
81
+ const checks = [];
82
+ const add = (name, ok, detail = "") => checks.push({ name, ok: !!ok, detail });
83
+
84
+ const p = doc?.record?.payment;
85
+ if (!p) throw new Error("missing record.payment");
86
+ for (const k of ["amount", "asset", "from", "to", "tx", "network"]) {
87
+ if (p[k] === undefined || p[k] === null || p[k] === "") throw new Error(`missing record.payment.${k}`);
88
+ }
89
+ if (!p.locator || p.locator.index === undefined) throw new Error("missing record.payment.locator.index");
90
+ if (!p.x402?.nonce) throw new Error("missing record.payment.x402.nonce");
91
+ const net = CHAINS[p.network];
92
+ if (!net) throw new Error(`unsupported network ${p.network}`);
93
+
94
+ // Document-level consistency.
95
+ add("version == nirium-payment-binding-v1", doc.version === VERSION, `version=${doc.version}`);
96
+ add("network == record.payment.network", doc.network === p.network, `doc=${doc.network} payment=${p.network}`);
97
+ add("locator.kind == evm-log", p.locator.kind === "evm-log", `kind=${p.locator.kind}`);
98
+ const computed = contentSha256(doc.record);
99
+ add("content_sha256 == sha256(canonical(record))", doc.content_sha256 === computed,
100
+ `doc=${doc.content_sha256} computed=${computed}`);
101
+ add("asset is Circle USDC for this network", eqAddr(p.asset, net.usdc), `asset=${p.asset} expected=${net.usdc}`);
102
+ add("decimals == 6", p.decimals === 6, `decimals=${p.decimals}`);
103
+
104
+ // Chain.
105
+ const client = createPublicClient({ chain: net.chain, transport: http(rpc) });
106
+ const chainId = await client.getChainId();
107
+ add("network == eip155:<RPC chainId>", p.network === `eip155:${chainId}`, `rpc chainId=${chainId}`);
108
+
109
+ let receipt = null;
110
+ try {
111
+ receipt = await client.getTransactionReceipt({ hash: p.tx });
112
+ } catch (e) {
113
+ add("tx receipt found", false, e.shortMessage || e.message);
114
+ }
115
+ if (receipt) {
116
+ add("tx status success (1)", receipt.status === "success", `status=${receipt.status} block=${receipt.blockNumber}`);
117
+
118
+ const idx = Number(p.locator.index);
119
+ const amount = BigInt(p.amount);
120
+ const log = receipt.logs.find((l) => l.logIndex === idx);
121
+ if (!log) {
122
+ add(`log ${idx} exists in tx`, false, `tx log indexes: ${receipt.logs.map((l) => l.logIndex).join(",")}`);
123
+ } else {
124
+ add(`log ${idx} emitted by asset`, eqAddr(log.address, p.asset), `emitter=${log.address}`);
125
+ let ev = null;
126
+ try { ev = decodeEventLog({ abi: ABI, data: log.data, topics: log.topics }); } catch {}
127
+ const isTransfer = ev?.eventName === "Transfer";
128
+ add(`log ${idx} is Transfer`, isTransfer, ev ? `event=${ev.eventName}` : "not decodable");
129
+ if (isTransfer) {
130
+ add("Transfer.from == payment.from", eqAddr(ev.args.from, p.from), `log=${ev.args.from}`);
131
+ add("Transfer.to == payment.to", eqAddr(ev.args.to, p.to), `log=${ev.args.to}`);
132
+ add("Transfer.value == payment.amount", ev.args.value === amount, `log=${ev.args.value} record=${amount}`);
133
+ }
134
+ }
135
+
136
+ const auths = receipt.logs
137
+ .filter((l) => eqAddr(l.address, p.asset))
138
+ .map((l) => { try { return decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }); } catch { return null; } })
139
+ .filter((e) => e?.eventName === "AuthorizationUsed");
140
+ const match = auths.find((e) => eqAddr(e.args.authorizer, p.from)
141
+ && e.args.nonce.toLowerCase() === String(p.x402.nonce).toLowerCase());
142
+ add("AuthorizationUsed(payment.from, x402.nonce) in same tx", match,
143
+ `found ${auths.length}: ${auths.map((e) => `${e.args.authorizer}/${e.args.nonce}`).join(" ; ") || "none"}`);
144
+ }
145
+
146
+ // Agent signature (payer).
147
+ if (!requireSig) {
148
+ add("agent signature (skipped: --no-sig)", true, "NOT checked");
149
+ } else if (!doc.agent?.signature || !doc.agent?.key || !doc.agent?.statement) {
150
+ add("agent block present", false, "agent.key, agent.statement and agent.signature are required");
151
+ } else {
152
+ const a = doc.agent;
153
+ add("agent.alg == eip191-secp256k1", a.alg === "eip191-secp256k1", `alg=${a.alg}`);
154
+ add("agent.statement == nirium-audit-v1:<content_sha256>", a.statement === STATEMENT_PREFIX + doc.content_sha256,
155
+ `statement=${a.statement}`);
156
+ add("agent.key == payment.from (payer signs)", eqAddr(a.key, p.from), `key=${a.key}`);
157
+ let valid = false;
158
+ try { valid = await verifyMessage({ address: a.key, message: a.statement, signature: a.signature }); } catch {}
159
+ add("EIP-191 signature by agent.key over agent.statement", valid);
160
+ }
161
+
162
+ // Post-quantum signature (optional unless requirePq): same statement as `agent`, key registered
163
+ // by the payer in NiriumPqKeyRegistry in a block before the payment.
164
+ const hasPq = Object.prototype.hasOwnProperty.call(doc, "pq");
165
+ if (requirePq && !hasPq) {
166
+ add("pq block present (--require-pq)", false, "this receipt has no post-quantum signature");
167
+ } else if (hasPq) {
168
+ const sig = verifyPqSignature(doc.pq, doc.content_sha256);
169
+ add("pq: ML-DSA-65 signature over nirium-audit-v1:<content_sha256>", sig.ok, sig.error ?? "NIST FIPS 204");
170
+ if (!PQ_REGISTRY[p.network]) {
171
+ add("pq: key registered by the payer before the payment", false, `no NiriumPqKeyRegistry on ${p.network} yet`);
172
+ } else if (!receipt) {
173
+ add("pq: key registered by the payer before the payment", false, "payment tx not found");
174
+ } else {
175
+ let reg = null;
176
+ try { reg = await checkPqRegistration(client, p.network, p.from, doc.pq.key, receipt.blockNumber); }
177
+ catch (e) { add("pq: key registered by the payer before the payment", false, e.shortMessage || e.message); }
178
+ if (reg) {
179
+ const r = reg.registration;
180
+ const detail = {
181
+ "registered-before": `registry ${r?.registry} block ${r?.blockNumber} < payment block ${receipt.blockNumber}`,
182
+ "registered-after": `registered in block ${r?.blockNumber}, not before the payment (block ${receipt.blockNumber})`,
183
+ "other-key": `the payer registered a different key (${r?.keyId})`,
184
+ "not-registered": "the payer never registered a post-quantum key",
185
+ }[reg.status];
186
+ add("pq: key registered by the payer before the payment", reg.status === "registered-before", detail);
187
+ }
188
+ }
189
+ }
190
+
191
+ return { ok: checks.every((c) => c.ok), checks };
192
+ }
@@ -0,0 +1,113 @@
1
+ // verify-evm-pq.mjs - the post-quantum part of a Nirium EVM receipt.
2
+ //
3
+ // A receipt may carry, next to the payer's EIP-191 `agent` signature, a second signature `pq`:
4
+ // "pq": { "alg": "ml-dsa-65", "key": "<base64, 1952 bytes>", "signature": "<base64, 3309 bytes>" }
5
+ // ML-DSA-65 (NIST FIPS 204), pure, empty context, over the SAME statement `agent` signs:
6
+ // nirium-audit-v1:<content_sha256>
7
+ // Same format as the Stellar SDK (`nirium`, packages/sdk/src/pq.ts), so one key and one statement
8
+ // work on both chains.
9
+ //
10
+ // It protects the receipt, not the payment: the payment is still signed with secp256k1.
11
+ //
12
+ // The signature alone does not say whose key it is. NiriumPqKeyRegistry (pq-registry/) does: the
13
+ // payer registers sha-256 of the key from its own address, once, and verifiers accept the key only
14
+ // if it is that registration and it landed in a block before the payment.
15
+ //
16
+ // No Node-only APIs (runs in the browser like verify-evm-core.mjs). No keys, no writes.
17
+
18
+ import { ml_dsa65 } from "@noble/post-quantum/ml-dsa.js";
19
+ import { sha256, stringToBytes, parseAbi } from "viem";
20
+
21
+ export const PQ_ALG = "ml-dsa-65";
22
+ export const PQ_PUBLIC_KEY_BYTES = 1952;
23
+ export const PQ_SIGNATURE_BYTES = 3309;
24
+ const STATEMENT_PREFIX = "nirium-audit-v1:";
25
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
26
+
27
+ /** NiriumPqKeyRegistry per network. */
28
+ export const PQ_REGISTRY = Object.freeze({
29
+ // Fuji, deployed 4-dic-2026: tx 0xf8257751da2de50611bfc7eb558dfed84cb94034f5c5ffd72882747690e8187f, block 62126784
30
+ "eip155:43113": "0x3aE0F4004bb67B8f754DE1fa8EA666A1B301D5b3",
31
+ // C-Chain mainnet, deployed 5-dic-2026: tx 0x4f28ae73fffeea3008582975b41e13b5bee3047db7dd62ed52754145a2f75a46, block 102260794
32
+ "eip155:43114": "0xE7791Fa06FE503AacE8fa4f6FC2DFdc3922ba0a0",
33
+ });
34
+
35
+ export const PQ_REGISTRY_ABI = parseAbi([
36
+ "function register(bytes32 keyId)",
37
+ "function registrationOf(address account) view returns (bytes32 keyId, uint64 blockNumber, uint64 timestamp)",
38
+ "event PqKeyRegistered(address indexed account, bytes32 indexed keyId, uint64 blockNumber)",
39
+ "error AlreadyRegistered(bytes32 keyId)",
40
+ "error EmptyKeyId()",
41
+ ]);
42
+
43
+ export function base64ToBytes(s, label = "value") {
44
+ if (typeof s !== "string" || s.length % 4 !== 0 || !BASE64.test(s)) throw new Error(`${label} must be base64`);
45
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
46
+ return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
47
+ }
48
+
49
+ export function bytesToBase64(b) {
50
+ if (typeof Buffer !== "undefined") return Buffer.from(b).toString("base64");
51
+ let s = ""; for (const x of b) s += String.fromCharCode(x); return btoa(s);
52
+ }
53
+
54
+ function asBytes(v, label) {
55
+ if (v instanceof Uint8Array) return v;
56
+ if (typeof v === "string" && /^0x[0-9a-fA-F]*$/.test(v)) return Uint8Array.from(v.slice(2).match(/../g) ?? [], (h) => parseInt(h, 16));
57
+ return base64ToBytes(v, label);
58
+ }
59
+
60
+ /** sha-256 of the raw ML-DSA-65 public key, as 0x-prefixed bytes32 (what the registry stores). */
61
+ export function pqKeyId(publicKey) {
62
+ return sha256(asBytes(publicKey, "publicKey"));
63
+ }
64
+
65
+ export function pqStatement(contentSha256) {
66
+ if (typeof contentSha256 !== "string" || !/^[0-9a-fA-F]{64}$/.test(contentSha256)) throw new Error("content_sha256 must be 64 hex chars");
67
+ return STATEMENT_PREFIX + contentSha256.toLowerCase();
68
+ }
69
+
70
+ /** Checks only the ML-DSA-65 signature of a `pq` block. Returns { ok, error? }. */
71
+ export function verifyPqSignature(pq, contentSha256) {
72
+ if (typeof pq !== "object" || pq === null || Array.isArray(pq)) return { ok: false, error: "`pq` must be an object { alg, key, signature }" };
73
+ if (pq.alg !== PQ_ALG) return { ok: false, error: `pq.alg must be "${PQ_ALG}"` };
74
+ let pk, sig, statement;
75
+ try {
76
+ pk = base64ToBytes(pq.key, "pq.key");
77
+ sig = base64ToBytes(pq.signature, "pq.signature");
78
+ statement = pqStatement(contentSha256);
79
+ } catch (e) { return { ok: false, error: e.message }; }
80
+ if (pk.length !== PQ_PUBLIC_KEY_BYTES) return { ok: false, error: `pq.key must be ${PQ_PUBLIC_KEY_BYTES} bytes, got ${pk.length}` };
81
+ if (sig.length !== PQ_SIGNATURE_BYTES) return { ok: false, error: `pq.signature must be ${PQ_SIGNATURE_BYTES} bytes, got ${sig.length}` };
82
+ let good = false;
83
+ try { good = ml_dsa65.verify(sig, stringToBytes(statement), pk); } catch { good = false; }
84
+ return good ? { ok: true } : { ok: false, error: `pq.signature does not verify over "${statement}"` };
85
+ }
86
+
87
+ /**
88
+ * The payer's registration, read from NiriumPqKeyRegistry.
89
+ * @returns {Promise<{ registry, keyId, blockNumber, timestamp } | null>} null when not registered
90
+ */
91
+ export async function readPqRegistration(client, network, account) {
92
+ const registry = PQ_REGISTRY[network];
93
+ if (!registry) throw new Error(`no NiriumPqKeyRegistry on ${network} yet`);
94
+ const [keyId, blockNumber, timestamp] = await client.readContract({
95
+ address: registry, abi: PQ_REGISTRY_ABI, functionName: "registrationOf", args: [account],
96
+ });
97
+ if (/^0x0{64}$/.test(keyId)) return null;
98
+ return { registry, keyId, blockNumber: Number(blockNumber), timestamp: Number(timestamp) };
99
+ }
100
+
101
+ /**
102
+ * Whether `publicKey` is the key `account` registered, before `beforeBlock`.
103
+ * status: "registered-before" | "registered-after" | "other-key" | "not-registered"
104
+ */
105
+ export async function checkPqRegistration(client, network, account, publicKey, beforeBlock) {
106
+ const reg = await readPqRegistration(client, network, account);
107
+ if (!reg) return { status: "not-registered", registration: null };
108
+ const keyId = pqKeyId(publicKey);
109
+ if (reg.keyId.toLowerCase() !== keyId.toLowerCase()) return { status: "other-key", registration: reg };
110
+ if (beforeBlock !== undefined && !(reg.blockNumber < Number(beforeBlock))) return { status: "registered-after", registration: reg };
111
+ return { status: "registered-before", registration: reg };
112
+ }
113
+
@@ -1,38 +1,38 @@
1
- #!/usr/bin/env node
2
- // verify-evm-receipt.mjs - command line for the EVM receipt verifier.
3
- //
4
- // Usage:
5
- // node verify-evm-receipt.mjs <binding.json> [--no-sig] [--rpc <url>] [--json]
6
- //
7
- // Every check lives in verify-evm-core.mjs, the same file verifyReceipt() and the browser run.
8
- // This file only reads the receipt, prints the checks and sets the exit code:
9
- // 0 = every check passed, 1 = at least one failed, 2 = bad input.
10
-
11
- import { readFileSync, realpathSync } from "node:fs";
12
- import { fileURLToPath } from "node:url";
13
- import { verifyBinding } from "./verify-evm-core.mjs";
14
-
15
- export * from "./verify-evm-core.mjs";
16
-
17
- async function main() {
18
- const args = process.argv.slice(2);
19
- const rpcIdx = args.indexOf("--rpc");
20
- const file = args.find((a, i) => !a.startsWith("--") && (rpcIdx < 0 || i !== rpcIdx + 1));
21
- if (!file) { console.error("usage: node verify-evm-receipt.mjs <binding.json> [--no-sig] [--rpc url] [--json]"); process.exit(2); }
22
- const opts = { requireSig: !args.includes("--no-sig"), rpc: rpcIdx >= 0 ? args[rpcIdx + 1] : undefined };
23
- let doc;
24
- try { doc = JSON.parse(readFileSync(file, "utf8")); } catch (e) { console.error(`bad binding file: ${e.message}`); process.exit(2); }
25
- let res;
26
- try { res = await verifyBinding(doc, opts); } catch (e) { console.error(`bad input: ${e.message}`); process.exit(2); }
27
- if (args.includes("--json")) console.log(JSON.stringify(res, null, 2));
28
- else {
29
- for (const c of res.checks) console.log(`${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? " [" + c.detail + "]" : ""}`);
30
- console.log(res.ok ? "RESULT: VALID" : "RESULT: INVALID");
31
- }
32
- process.exit(res.ok ? 0 : 1);
33
- }
34
-
35
- // Run main() when executed directly, including through the npm bin symlink: compare real paths,
36
- // or a symlinked call would skip main() and exit 0 without checking anything.
37
- const invokedPath = (() => { try { return realpathSync(process.argv[1]); } catch { return undefined; } })();
38
- if (invokedPath && realpathSync(fileURLToPath(import.meta.url)) === invokedPath) main();
1
+ #!/usr/bin/env node
2
+ // verify-evm-receipt.mjs - command line for the EVM receipt verifier.
3
+ //
4
+ // Usage:
5
+ // node verify-evm-receipt.mjs <binding.json> [--no-sig] [--require-pq] [--rpc <url>] [--json]
6
+ //
7
+ // Every check lives in verify-evm-core.mjs, the same file verifyReceipt() and the browser run.
8
+ // This file only reads the receipt, prints the checks and sets the exit code:
9
+ // 0 = every check passed, 1 = at least one failed, 2 = bad input.
10
+
11
+ import { readFileSync, realpathSync } from "node:fs";
12
+ import { fileURLToPath } from "node:url";
13
+ import { verifyBinding } from "./verify-evm-core.mjs";
14
+
15
+ export * from "./verify-evm-core.mjs";
16
+
17
+ async function main() {
18
+ const args = process.argv.slice(2);
19
+ const rpcIdx = args.indexOf("--rpc");
20
+ const file = args.find((a, i) => !a.startsWith("--") && (rpcIdx < 0 || i !== rpcIdx + 1));
21
+ if (!file) { console.error("usage: node verify-evm-receipt.mjs <binding.json> [--no-sig] [--require-pq] [--rpc url] [--json]"); process.exit(2); }
22
+ const opts = { requireSig: !args.includes("--no-sig"), requirePq: args.includes("--require-pq"), rpc: rpcIdx >= 0 ? args[rpcIdx + 1] : undefined };
23
+ let doc;
24
+ try { doc = JSON.parse(readFileSync(file, "utf8")); } catch (e) { console.error(`bad binding file: ${e.message}`); process.exit(2); }
25
+ let res;
26
+ try { res = await verifyBinding(doc, opts); } catch (e) { console.error(`bad input: ${e.message}`); process.exit(2); }
27
+ if (args.includes("--json")) console.log(JSON.stringify(res, null, 2));
28
+ else {
29
+ for (const c of res.checks) console.log(`${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? " [" + c.detail + "]" : ""}`);
30
+ console.log(res.ok ? "RESULT: VALID" : "RESULT: INVALID");
31
+ }
32
+ process.exit(res.ok ? 0 : 1);
33
+ }
34
+
35
+ // Run main() when executed directly, including through the npm bin symlink: compare real paths,
36
+ // or a symlinked call would skip main() and exit 0 without checking anything.
37
+ const invokedPath = (() => { try { return realpathSync(process.argv[1]); } catch { return undefined; } })();
38
+ if (invokedPath && realpathSync(fileURLToPath(import.meta.url)) === invokedPath) main();