@xfuel/verify 0.3.4 → 0.4.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 (99) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +82 -252
  3. package/cli.js +40 -0
  4. package/index.cjs +8 -0
  5. package/index.d.ts +5 -0
  6. package/index.js +7 -0
  7. package/package.json +61 -67
  8. package/dist/anchor-trust.d.ts +0 -129
  9. package/dist/anchor-trust.d.ts.map +0 -1
  10. package/dist/anchor-trust.js +0 -395
  11. package/dist/anchor-trust.js.map +0 -1
  12. package/dist/anchor-witness.d.ts +0 -265
  13. package/dist/anchor-witness.d.ts.map +0 -1
  14. package/dist/anchor-witness.js +0 -818
  15. package/dist/anchor-witness.js.map +0 -1
  16. package/dist/base-payer.d.ts +0 -65
  17. package/dist/base-payer.d.ts.map +0 -1
  18. package/dist/base-payer.js +0 -222
  19. package/dist/base-payer.js.map +0 -1
  20. package/dist/binding.d.ts +0 -52
  21. package/dist/binding.d.ts.map +0 -1
  22. package/dist/binding.js +0 -80
  23. package/dist/binding.js.map +0 -1
  24. package/dist/canonical-preimage.d.ts +0 -9
  25. package/dist/canonical-preimage.d.ts.map +0 -1
  26. package/dist/canonical-preimage.js +0 -25
  27. package/dist/canonical-preimage.js.map +0 -1
  28. package/dist/carry-forward.d.ts +0 -79
  29. package/dist/carry-forward.d.ts.map +0 -1
  30. package/dist/carry-forward.js +0 -184
  31. package/dist/carry-forward.js.map +0 -1
  32. package/dist/cli.d.ts +0 -19
  33. package/dist/cli.d.ts.map +0 -1
  34. package/dist/cli.js +0 -1479
  35. package/dist/cli.js.map +0 -1
  36. package/dist/epoch.d.ts +0 -143
  37. package/dist/epoch.d.ts.map +0 -1
  38. package/dist/epoch.js +0 -352
  39. package/dist/epoch.js.map +0 -1
  40. package/dist/head-binding.d.ts +0 -24
  41. package/dist/head-binding.d.ts.map +0 -1
  42. package/dist/head-binding.js +0 -61
  43. package/dist/head-binding.js.map +0 -1
  44. package/dist/index.d.ts +0 -569
  45. package/dist/index.d.ts.map +0 -1
  46. package/dist/index.js +0 -1597
  47. package/dist/index.js.map +0 -1
  48. package/dist/issuer-history.d.ts +0 -110
  49. package/dist/issuer-history.d.ts.map +0 -1
  50. package/dist/issuer-history.js +0 -348
  51. package/dist/issuer-history.js.map +0 -1
  52. package/dist/issuer-pin.d.ts +0 -126
  53. package/dist/issuer-pin.d.ts.map +0 -1
  54. package/dist/issuer-pin.js +0 -567
  55. package/dist/issuer-pin.js.map +0 -1
  56. package/dist/jcs.d.ts +0 -8
  57. package/dist/jcs.d.ts.map +0 -1
  58. package/dist/jcs.js +0 -64
  59. package/dist/jcs.js.map +0 -1
  60. package/dist/jws.d.ts +0 -46
  61. package/dist/jws.d.ts.map +0 -1
  62. package/dist/jws.js +0 -129
  63. package/dist/jws.js.map +0 -1
  64. package/dist/payer.d.ts +0 -65
  65. package/dist/payer.d.ts.map +0 -1
  66. package/dist/payer.js +0 -148
  67. package/dist/payer.js.map +0 -1
  68. package/dist/preimage.d.ts +0 -78
  69. package/dist/preimage.d.ts.map +0 -1
  70. package/dist/preimage.js +0 -363
  71. package/dist/preimage.js.map +0 -1
  72. package/dist/receipt-lane.d.ts +0 -235
  73. package/dist/receipt-lane.d.ts.map +0 -1
  74. package/dist/receipt-lane.js +0 -446
  75. package/dist/receipt-lane.js.map +0 -1
  76. package/dist/refusal.d.ts +0 -93
  77. package/dist/refusal.d.ts.map +0 -1
  78. package/dist/refusal.js +0 -248
  79. package/dist/refusal.js.map +0 -1
  80. package/dist/request-binding.d.ts +0 -7
  81. package/dist/request-binding.d.ts.map +0 -1
  82. package/dist/request-binding.js +0 -26
  83. package/dist/request-binding.js.map +0 -1
  84. package/dist/row-hash.d.ts +0 -22
  85. package/dist/row-hash.d.ts.map +0 -1
  86. package/dist/row-hash.js +0 -26
  87. package/dist/row-hash.js.map +0 -1
  88. package/dist/shell.d.ts +0 -65
  89. package/dist/shell.d.ts.map +0 -1
  90. package/dist/shell.js +0 -268
  91. package/dist/shell.js.map +0 -1
  92. package/dist/solana-payer.d.ts +0 -99
  93. package/dist/solana-payer.d.ts.map +0 -1
  94. package/dist/solana-payer.js +0 -258
  95. package/dist/solana-payer.js.map +0 -1
  96. package/dist/v11-receipt.d.ts +0 -21
  97. package/dist/v11-receipt.d.ts.map +0 -1
  98. package/dist/v11-receipt.js +0 -351
  99. package/dist/v11-receipt.js.map +0 -1
package/dist/cli.js DELETED
@@ -1,1479 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /**
4
- * xfuel-verify CLI — Offline receipt verification.
5
- *
6
- * Usage:
7
- * xfuel-verify receipt.json
8
- * xfuel-verify receipt.json --check-nullifier
9
- * xfuel-verify receipt.json --rpc https://mainnet.base.org
10
- * xfuel-verify receipt.json inclusion.json head.json --rpc
11
- * cat receipt.json | xfuel-verify -
12
- *
13
- * Exit codes:
14
- * 0 = verified
15
- * 1 = verification failed
16
- * 2 = partial (binding ok, nullifier not checked or pending)
17
- * 3 = input error
18
- */
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- const node_module_1 = require("node:module");
21
- const node_fs_1 = require("node:fs");
22
- const index_js_1 = require("./index.js");
23
- const anchor_witness_js_1 = require("./anchor-witness.js");
24
- const jws_js_1 = require("./jws.js");
25
- const shell_js_1 = require("./shell.js");
26
- const preimage_js_1 = require("./preimage.js");
27
- const issuer_history_js_1 = require("./issuer-history.js");
28
- const canonical_preimage_js_1 = require("./canonical-preimage.js");
29
- const v11_receipt_js_1 = require("./v11-receipt.js");
30
- const issuer_pin_js_1 = require("./issuer-pin.js");
31
- const anchor_trust_js_1 = require("./anchor-trust.js");
32
- const HELP = `
33
- xfuel-verify — Offline verification for Chit402 receipts
34
-
35
- Usage:
36
- xfuel-verify <receipt.json> Verify binding locally
37
- xfuel-verify <refusal.json> Verify a chit402.refusal.v1 document
38
- (issuer refused; not a payment)
39
- xfuel-verify <receipt.json> --jwks-file <jwks.json>
40
- Verify issuer signature with a JWKS file
41
- xfuel-verify <receipt.json> --fetch-jwks
42
- Fetch JWKS from an allowlisted issuer jwks_uri
43
- xfuel-verify <receipt.json> --check-payer
44
- Confirm payer, payee, asset, and amount on-chain
45
- xfuel-verify - < receipt.json Read from stdin
46
- xfuel-verify --help Show this help
47
-
48
- Options:
49
- --jwks-file <path> JWKS file. Keys are trusted and matched by kid (no network)
50
- --jwks-url <url> Fetch this https JWKS and trust it (explicit; any host)
51
- --fetch-jwks Fetch receipt verification.jwks_uri when the host is allowlisted
52
- (default allowlist: api.chit402.com)
53
- --trusted-kid <kid> Replace the default offline pin with this RFC 7638 kid
54
- (repeatable). Default pin: ${index_js_1.DEFAULT_TRUSTED_ISSUER_KIDS[0]}
55
- --no-trusted-kid Do not use the default offline pin (JWKS only)
56
- --check-nullifier Query Base RPC for nullifier anchor (requires network)
57
- --check-payer Query Base or Solana RPC. Base confirms payer, payee, asset, amount
58
- --solana-rpc <url> Solana RPC URL (default: https://api.mainnet-beta.solana.com or SOLANA_RPC_URL)
59
- --rpc <url> Base RPC URL (default: https://mainnet.base.org)
60
- --version Print @xfuel/verify version and exit
61
- --rpc With a receipt, an inclusion proof, and a tree head: check the
62
- leaf, then the Solana memo and the Base calldata for that root.
63
- The tree head must carry a valid ES256 issuer signature, and
64
- the anchor wallets must match the signed head.
65
- A v2 head also needs the signed epoch record.
66
- A tree-head file with --rpc enters this mode.
67
- The same files without --rpc check the head signature and the
68
- index/size-bound inclusion offline. They do not call chain RPC.
69
- --epoch-record <f> Signed epoch record JSON. Skips the network fetch.
70
- --epoch-url <url> GET this epoch record. Default: the receipt verify_url
71
- origin plus /v1/receipts/tree/epoch
72
- --inclusion <file> Inclusion proof JSON (chit402.inclusion.v1)
73
- --head <file> Signed tree head JSON (chit402.tree_head.v1 or v2)
74
- --anchor-wallets-file <path>
75
- Signed chit402.anchor_wallets.v1 document. Wallets in a
76
- verified document are added to the package pin. A head
77
- that names any other wallet fails.
78
- --carry-old-head <file>
79
- --carry-old-inclusion <file>
80
- --carry-head <file>
81
- --carry-inclusion <file>
82
- Earlier signed head, its inclusion proof, the current
83
- signed head, and the current inclusion proof. Repeat
84
- --carry-inclusion for each current index of the leaf.
85
- The issued time and epoch are the earlier head's signed
86
- claims. The logged time, epoch, and leaf index are the
87
- current head's signed claims. A receipt in the current
88
- epoch does not use these flags.
89
- --json Output JSON instead of human-readable
90
- --quiet Only output errors
91
- --strict-issuer-history
92
- Fail if the issuer key history cannot be fetched
93
- --issuer-history-file <path>
94
- Read issuer history JSON instead of fetching it
95
- --canonical-preimage <path>
96
- SHA-256 this file and match the signed payload_hash
97
- --no-issuer-history Do not check the kid's not_before / not_after window
98
- --no-preimage Do not require published hash preimages
99
-
100
- Exit codes:
101
- 0 = verified
102
- 1 = verification failed
103
- 2 = partial verification
104
- 3 = input error
105
-
106
- Trust:
107
- A signature counts only when the verifying key is trusted. Trust is a JWKS
108
- entry matched by kid (file, --jwks-url, or --fetch-jwks), or an embedded
109
- issuer_jwk whose RFC 7638 thumbprint equals a pinned trusted kid. The
110
- embedded key alone is not a trust root. Untrusted keys report "key untrusted".
111
-
112
- Amount, payer, payee, and tx are read from verified signed claims. Every
113
- signed field is compared with the outer receipt at the same path. A mismatch
114
- fails. Outer fields the signature does not cover are printed as UNVERIFIED.
115
- The outer document schema is not a copy of the JWS schema. Log mode (a
116
- receipt, an inclusion proof, and a tree head) runs these receipt checks too.
117
-
118
- Network behavior:
119
- JWKS, nullifiers, and anchors are not fetched unless you pass a flag.
120
- Issuer history is fetched by default when the receipt names a history URL
121
- and neither --issuer-history-file nor --no-issuer-history is set. A payload
122
- v10 receipt fails (exit 1) when that fetch cannot run. Offline mode is
123
- --issuer-history-file <snapshot>, or --no-issuer-history to skip the window.
124
- Other network uses:
125
- - --fetch-jwks or --jwks-url
126
- - --check-nullifier (Base RPC)
127
- - --check-payer (Base or Solana RPC)
128
- - --rpc with a receipt, an inclusion proof, and a tree head
129
- - a v2 head, which fetches GET /v1/receipts/tree/epoch unless --epoch-record
130
-
131
- Solana payer verify uses SOLANA_RPC_URL when set, else the public mainnet RPC.
132
-
133
- Anchored root:
134
- xfuel-verify receipt.json inclusion.json head.json --rpc
135
- xfuel-verify receipt.json --inclusion inclusion.json --head head.json --rpc https://mainnet.base.org
136
-
137
- Also runs the single-receipt checks (issuer signature and signed-versus-outer
138
- comparison). Those must pass before Overall can be VERIFIED. Then it checks
139
- the tree head's ES256 issuer signature (production pin, issuer
140
- history, or JWKS, same rules as a receipt). The signed root, size, epoch,
141
- and anchors must match the head. Then it checks Merkle inclusion, requires
142
- the Solana memo and fee payer, and requires the Base calldata and sender.
143
- The sender and fee payer must be on the issuer anchor-wallet list (the
144
- package pin, plus a verified /.well-known/anchor-wallets.json or
145
- issuer-history anchor_wallets list). The on-chain issuer-root registry and
146
- the DNS anchor are not read. Prints what this proves and what it does not
147
- prove. Exit 0 when the receipt checks pass and both chains match, 2 when the
148
- leaf is included but an anchor is still pending, or when the leaf is past
149
- the anchored tree (PENDING, not a tamper failure), and the receipt checks
150
- did not fail, 1 when a check fails. A pending leaf must sit at an index
151
- at or past the anchored size, and PENDING applies only when the receipt
152
- itself verifies. A failed signature, field, or preimage is a failure.
153
- With --rpc, a claimed anchor must name a Solana fee payer that is on the
154
- anchor-wallet list, and the head root must equal the newest memo that
155
- payer actually paid. A memo from any other payer is ignored.
156
-
157
- A receipt or head with issuer_key_pin is a pinned era. Pass the pin file
158
- and its commit SHA plus SHA-256. The verifier does not fetch a branch.
159
- --issuer-pin <file> --issuer-pin-commit <40-hex> --issuer-pin-sha256 <64-hex>
160
- Optional with that pin: --issuer-pin-sig, --issuer-witnesses,
161
- --issuer-prior-pin, --issuer-prior-commit, --issuer-prior-sha256, --issuer-control.
162
- Those flags do not start the check on their own. A prior pin does not
163
- replace the published specimen key. Sepolia only (eip155:84532).
164
- See docs/product/issuer-key-pin.md.
165
-
166
- Receipt lane (unsigned, beside book_seq):
167
- settled_by is observed_transfer when the USDC transfer was checked on Base
168
- or Solana, and receipt when only the issuer asserts settlement. Unknown is
169
- null. Ordering is seq + settled_by + (anchor_changed AND not settled).
170
- Boundary: complete over registry marks, blind to payments the registry
171
- never joined. freeze is true only when book_seq is set, settled_by is
172
- receipt, the anchor changed after binding, and the row is not settled. An
173
- anchor change alone does not freeze, and freeze does not change the
174
- signature exit code. classification unverifiable_from_registry means the
175
- binding is past expiry and settled_by, receipt_id, observed_tx_hash, and
176
- observed_transfer_id are all null. That is not unpaid. local_check, when
177
- set, is a Base USDC payee and amount a stranger can check. It does not
178
- claim the row was paid. Design by Turbo on 1F916 (post 6579, comments
179
- 88201, 88403, and 88596).
180
-
181
- Examples:
182
- # Skip the issuer-history fetch. A v10 receipt otherwise needs that network call.
183
- xfuel-verify my-receipt.json --no-issuer-history
184
-
185
- # Verify issuer signature with JWKS file
186
- xfuel-verify my-receipt.json --jwks-file issuer-jwks.json
187
-
188
- # Full verification including on-chain nullifier
189
- xfuel-verify my-receipt.json --jwks-file issuer-jwks.json --check-nullifier
190
-
191
- # Pipe from curl
192
- curl -s https://api.chit402.com/receipt/task-123?format=json | xfuel-verify -
193
-
194
- # Public shell. INCLUDED_SHELL is not VERIFIED.
195
- xfuel-verify shell.json
196
-
197
- # Owner view. VERIFIED needs a trusted issuer key, an inclusion proof,
198
- # and a signed payment. The key inside the holder is not enough.
199
- xfuel-verify shell.json --jws owner-view.json --inclusion inclusion.json --head head.json
200
- `;
201
- function parseArgs(args) {
202
- const result = {
203
- file: null,
204
- jwksFile: null,
205
- jwksUrl: null,
206
- fetchJwks: false,
207
- trustedKids: null,
208
- noTrustedKid: false,
209
- checkNullifier: false,
210
- checkPayer: false,
211
- rpcUrl: null,
212
- solanaRpcUrl: null,
213
- sawRpc: false,
214
- anchorFlag: false,
215
- inclusionFile: null,
216
- headFile: null,
217
- epochRecordFile: null,
218
- epochUrl: null,
219
- carryOldHeadFile: null,
220
- carryOldInclusionFile: null,
221
- carryHeadFile: null,
222
- carryInclusionFiles: [],
223
- positionals: [],
224
- json: false,
225
- quiet: false,
226
- help: false,
227
- strictIssuerHistory: false,
228
- issuerHistoryFile: null,
229
- canonicalPreimageFile: null,
230
- noIssuerHistory: false,
231
- noPreimage: false,
232
- issuerPinFile: null,
233
- issuerPinCommit: null,
234
- issuerPinSha256: null,
235
- issuerPinSigFile: null,
236
- issuerWitnessesFile: null,
237
- issuerPriorPinFile: null,
238
- issuerPriorCommit: null,
239
- issuerPriorSha256: null,
240
- issuerControlFile: null,
241
- version: false,
242
- anchorWalletsFile: null,
243
- acceptShell: false,
244
- jwsFile: null,
245
- salt: null,
246
- open: [],
247
- url: null,
248
- };
249
- for (let i = 0; i < args.length; i++) {
250
- const arg = args[i];
251
- if (arg === '--version' || arg === '-V') {
252
- result.version = true;
253
- }
254
- else if (arg === '--help' || arg === '-h') {
255
- result.help = true;
256
- }
257
- else if (arg === '--check-nullifier') {
258
- result.checkNullifier = true;
259
- }
260
- else if (arg === '--check-payer') {
261
- result.checkPayer = true;
262
- }
263
- else if (arg === '--jwks-file' && args[i + 1]) {
264
- result.jwksFile = args[++i];
265
- }
266
- else if (arg === '--jwks-url' && args[i + 1]) {
267
- result.jwksUrl = args[++i];
268
- }
269
- else if (arg === '--fetch-jwks') {
270
- result.fetchJwks = true;
271
- }
272
- else if (arg === '--trusted-kid' && args[i + 1]) {
273
- result.trustedKids = result.trustedKids || [];
274
- result.trustedKids.push(args[++i]);
275
- }
276
- else if (arg === '--no-trusted-kid') {
277
- result.noTrustedKid = true;
278
- }
279
- else if (arg === '--rpc') {
280
- result.sawRpc = true;
281
- const next = args[i + 1];
282
- if (next && /^https?:\/\//i.test(next))
283
- result.rpcUrl = args[++i];
284
- else
285
- result.anchorFlag = true;
286
- }
287
- else if (arg === '--inclusion' && args[i + 1]) {
288
- result.inclusionFile = args[++i];
289
- }
290
- else if (arg === '--head' && args[i + 1]) {
291
- result.headFile = args[++i];
292
- }
293
- else if (arg === '--epoch-record' && args[i + 1]) {
294
- result.epochRecordFile = args[++i];
295
- }
296
- else if (arg === '--epoch-url' && args[i + 1]) {
297
- result.epochUrl = args[++i];
298
- }
299
- else if (arg === '--carry-old-head' && args[i + 1]) {
300
- result.carryOldHeadFile = args[++i];
301
- }
302
- else if (arg === '--carry-old-inclusion' && args[i + 1]) {
303
- result.carryOldInclusionFile = args[++i];
304
- }
305
- else if (arg === '--carry-head' && args[i + 1]) {
306
- result.carryHeadFile = args[++i];
307
- }
308
- else if (arg === '--carry-inclusion' && args[i + 1]) {
309
- result.carryInclusionFiles.push(args[++i]);
310
- }
311
- else if (arg === '--solana-rpc' && args[i + 1]) {
312
- result.solanaRpcUrl = args[++i];
313
- }
314
- else if (arg === '--strict-issuer-history') {
315
- result.strictIssuerHistory = true;
316
- }
317
- else if (arg === '--issuer-history-file' && args[i + 1]) {
318
- result.issuerHistoryFile = args[++i];
319
- }
320
- else if (arg === '--salt' && args[i + 1]) {
321
- result.salt = args[++i];
322
- }
323
- else if (arg === '--open' && args[i + 1]) {
324
- result.open.push(args[++i]);
325
- }
326
- else if (arg === '--canonical-preimage' && args[i + 1]) {
327
- result.canonicalPreimageFile = args[++i];
328
- }
329
- else if (arg === '--no-issuer-history') {
330
- result.noIssuerHistory = true;
331
- }
332
- else if (arg === '--anchor-wallets-file' && args[i + 1]) {
333
- result.anchorWalletsFile = args[++i];
334
- }
335
- else if (arg === '--no-preimage') {
336
- result.noPreimage = true;
337
- }
338
- else if (arg === '--accept-shell') {
339
- result.acceptShell = true;
340
- }
341
- else if (arg === '--jws' && args[i + 1]) {
342
- result.jwsFile = args[++i];
343
- }
344
- else if (arg === '--url' && args[i + 1]) {
345
- result.url = args[++i];
346
- }
347
- else if (arg === '--issuer-pin' && args[i + 1]) {
348
- result.issuerPinFile = args[++i];
349
- }
350
- else if (arg === '--issuer-pin-commit' && args[i + 1]) {
351
- result.issuerPinCommit = args[++i];
352
- }
353
- else if (arg === '--issuer-pin-sha256' && args[i + 1]) {
354
- result.issuerPinSha256 = args[++i];
355
- }
356
- else if (arg === '--issuer-pin-sig' && args[i + 1]) {
357
- result.issuerPinSigFile = args[++i];
358
- }
359
- else if (arg === '--issuer-witnesses' && args[i + 1]) {
360
- result.issuerWitnessesFile = args[++i];
361
- }
362
- else if (arg === '--issuer-prior-pin' && args[i + 1]) {
363
- result.issuerPriorPinFile = args[++i];
364
- }
365
- else if (arg === '--issuer-prior-commit' && args[i + 1]) {
366
- result.issuerPriorCommit = args[++i];
367
- }
368
- else if (arg === '--issuer-prior-sha256' && args[i + 1]) {
369
- result.issuerPriorSha256 = args[++i];
370
- }
371
- else if (arg === '--issuer-control' && args[i + 1]) {
372
- result.issuerControlFile = args[++i];
373
- }
374
- else if (arg === '--json') {
375
- result.json = true;
376
- }
377
- else if (arg === '--quiet' || arg === '-q') {
378
- result.quiet = true;
379
- }
380
- else if (!arg.startsWith('-')) {
381
- result.positionals.push(arg);
382
- if (!result.file)
383
- result.file = arg;
384
- }
385
- }
386
- return result;
387
- }
388
- function readReceipt(file) {
389
- let content;
390
- if (file === '-') {
391
- content = (0, node_fs_1.readFileSync)(0, 'utf8');
392
- }
393
- else {
394
- content = (0, node_fs_1.readFileSync)(file, 'utf8');
395
- }
396
- return JSON.parse(content);
397
- }
398
- function formatAmount(units) {
399
- if (!units)
400
- return '—';
401
- const n = Number(units);
402
- if (!Number.isFinite(n))
403
- return units;
404
- const usd = n / 1e6;
405
- return `$${usd.toFixed(usd >= 0.01 ? 2 : 6)} (${units} units)`;
406
- }
407
- function readJson(file) {
408
- const content = file === '-' ? (0, node_fs_1.readFileSync)(0, 'utf8') : (0, node_fs_1.readFileSync)(file, 'utf8');
409
- return JSON.parse(content);
410
- }
411
- function headStatus(file) {
412
- try {
413
- const doc = readJson(file);
414
- return typeof doc?.status === 'string' ? doc.status : null;
415
- }
416
- catch {
417
- return null;
418
- }
419
- }
420
- function printLane(lane) {
421
- const bit = (value) => (value == null ? 'unknown' : (value ? 'true' : 'false'));
422
- console.log(` Receipt lane (unsigned)`);
423
- console.log(` ─────────────────────────────────────────────────`);
424
- console.log(` book_seq: ${lane.book_seq ?? '—'}`);
425
- console.log(` settled_by: ${lane.settled_by ?? 'null'}`);
426
- console.log(` settled: ${bit(lane.settled)}`);
427
- console.log(` anchor_changed_since_binding: ${bit(lane.anchor_changed_since_binding)}`);
428
- console.log(` freeze: ${lane.freeze ? 'YES' : 'no'}`);
429
- if (lane.reason)
430
- console.log(` reason: ${lane.reason}`);
431
- console.log(` classification:${lane.classification}`);
432
- console.log(` ordering: ${lane.ordering}`);
433
- console.log(` boundary: ${lane.boundary}`);
434
- if (lane.local_check) {
435
- console.log(` local_check: payee ${lane.local_check.payee} amount ${lane.local_check.amount_atomic} (not a payment)`);
436
- }
437
- console.log(` ${lane.rule}`);
438
- console.log('');
439
- }
440
- function printAnchor(result, json, quiet) {
441
- if (json) {
442
- console.log(JSON.stringify(result, null, 2));
443
- return;
444
- }
445
- if (quiet && result.overall !== 'failed')
446
- return;
447
- const mark = (ok) => (ok ? '✓ YES' : '✗ NO');
448
- console.log('');
449
- console.log(' Anchored receipt root');
450
- console.log(' ─────────────────────────────────────────────────');
451
- console.log(` Root: ${result.root || '—'}`);
452
- console.log(` Head signature:${result.head_signature.valid ? ' ✓ YES' : ' ✗ NO'}${result.head_signature.trust ? ` (${result.head_signature.trust})` : ''}`);
453
- if (result.head_signature.kid)
454
- console.log(` Head kid: ${result.head_signature.kid}`);
455
- if (result.head_signature.message)
456
- console.log(` Head reason: ${result.head_signature.message}`);
457
- const unlogged = result.inclusion.unlogged_reason ? ` unlogged:${result.inclusion.unlogged_reason}` : '';
458
- if (result.overall === 'pending') {
459
- console.log(` Inclusion: PENDING${result.inclusion.reason ? ` (${result.inclusion.reason})` : ''}`);
460
- }
461
- else {
462
- console.log(` Inclusion: ${mark(result.inclusion.valid)}${result.inclusion.reason ? ` (${result.inclusion.reason})` : ''}${unlogged}`);
463
- }
464
- console.log(` Leaf source: ${result.inclusion.leaf_source}`);
465
- console.log(` Solana: ${result.solana.checked ? mark(result.solana.valid) : (result.solana.reason || 'not checked')}`);
466
- if (result.solana.signature)
467
- console.log(` Signature: ${result.solana.signature}`);
468
- if (result.solana.slot != null)
469
- console.log(` Slot: ${result.solana.slot}`);
470
- if (result.solana.cluster)
471
- console.log(` Cluster: ${result.solana.cluster}`);
472
- if (result.solana.fee_payer)
473
- console.log(` Fee payer: ${result.solana.fee_payer}`);
474
- if (result.solana.memo)
475
- console.log(` Memo: ${result.solana.memo}`);
476
- if (result.solana.reason && !result.solana.valid)
477
- console.log(` Solana reason: ${result.solana.reason}`);
478
- if (result.issuer_pin?.checked) {
479
- console.log(` Issuer pin: ${result.issuer_pin.ok ? '✓ YES' : '✗ NO'}${result.issuer_pin.code ? ` (${result.issuer_pin.code})` : ''}`);
480
- }
481
- console.log(` Base: ${result.base.checked ? mark(result.base.valid) : (result.base.reason || 'not checked')}`);
482
- if (result.base.from)
483
- console.log(` Base from: ${result.base.from}`);
484
- if (result.base.tx)
485
- console.log(` Base tx: ${result.base.tx}`);
486
- if (result.base.chain_id != null)
487
- console.log(` Chain id: ${result.base.chain_id}`);
488
- if (result.base.reason && !result.base.valid)
489
- console.log(` Base reason: ${result.base.reason}`);
490
- console.log('');
491
- console.log(' What this proves');
492
- console.log(' ─────────────────────────────────────────────────');
493
- for (const line of result.proves)
494
- console.log(` ${line}`);
495
- console.log('');
496
- console.log(' What this does not prove');
497
- console.log(' ─────────────────────────────────────────────────');
498
- for (const line of result.does_not_prove)
499
- console.log(` ${line}`);
500
- console.log('');
501
- if (result.overall === 'pending') {
502
- console.log(` Anchored size: ${result.inclusion.anchored_tree_size ?? '—'}`);
503
- console.log(` Live size: ${result.inclusion.live_tree_size ?? '—'}`);
504
- }
505
- console.log(` Overall: ${result.overall.toUpperCase()}`);
506
- if (result.errors.length > 0)
507
- console.log(` Errors: ${result.errors.join(', ')}`);
508
- if (result.errors.includes(anchor_trust_js_1.LEGACY_HEAD_UNPINNED_SIGNER)) {
509
- console.log(` ${anchor_trust_js_1.HEAD_TRUST_MESSAGES[anchor_trust_js_1.LEGACY_HEAD_UNPINNED_SIGNER]}`);
510
- }
511
- console.log('');
512
- }
513
- function headNeedsEpochRecord(head) {
514
- const schema = head.schema;
515
- const version = head.payload_version;
516
- return head.epoch != null || schema === 'chit402.tree_head.v2' || version === 2;
517
- }
518
- function epochUrlFromReceipt(receipt) {
519
- const raw = receipt?.verify_url;
520
- if (!raw)
521
- return null;
522
- try {
523
- return `${new URL(raw).origin}/v1/receipts/tree/epoch`;
524
- }
525
- catch {
526
- return null;
527
- }
528
- }
529
- async function loadEpochRecord(args, receipt) {
530
- if (args.epochRecordFile) {
531
- return JSON.parse((0, node_fs_1.readFileSync)(args.epochRecordFile, 'utf8'));
532
- }
533
- const url = args.epochUrl || epochUrlFromReceipt(receipt);
534
- if (!url)
535
- return null;
536
- const res = await fetch(url);
537
- if (!res.ok)
538
- return null;
539
- const body = await res.json();
540
- if (!body?.issuer_signature?.jws)
541
- return null;
542
- return body;
543
- }
544
- function epochSignatureOk(record, jws, jwks, trustedKids) {
545
- const sig = record.issuer_signature;
546
- const embedded = sig && 'issuer_jwk' in sig
547
- ? sig.issuer_jwk
548
- : undefined;
549
- const kid = (0, jws_js_1.readJwsHeader)(jws)?.kid;
550
- const keys = [];
551
- for (const key of jwks?.keys || []) {
552
- if (!key || key.kty !== 'EC')
553
- continue;
554
- const jwk = key;
555
- if (kid && jwk.kid !== kid)
556
- continue;
557
- keys.push(jwk);
558
- }
559
- if (embedded && trustedKids?.includes((0, jws_js_1.jwkThumbprint)(embedded)))
560
- keys.push(embedded);
561
- for (const key of keys) {
562
- const verified = (0, jws_js_1.verifyIssuerJws)(jws, key);
563
- if (!verified.valid || !verified.payload)
564
- continue;
565
- const payload = verified.payload;
566
- if (JSON.stringify(payload.epochs ?? null) !== JSON.stringify(record.epochs ?? null))
567
- return false;
568
- if (JSON.stringify(payload.orphans ?? []) !== JSON.stringify(record.orphans ?? []))
569
- return false;
570
- const payloadUnlogged = payload.unlogged === undefined ? null : payload.unlogged;
571
- const recordUnlogged = record.unlogged === undefined ? null : record.unlogged;
572
- if (JSON.stringify(payloadUnlogged) !== JSON.stringify(recordUnlogged))
573
- return false;
574
- return true;
575
- }
576
- return false;
577
- }
578
- function packageVersion() {
579
- const require = (0, node_module_1.createRequire)(__filename);
580
- const pkg = require('../package.json');
581
- return pkg.version || '0.0.0';
582
- }
583
- function looksLikeTreeHead(value) {
584
- if (!value || typeof value !== 'object')
585
- return false;
586
- const doc = value;
587
- if (doc.status === 'not_yet_published')
588
- return true;
589
- if (typeof doc.schema === 'string' && doc.schema.startsWith('chit402.tree_head.'))
590
- return true;
591
- return Boolean(doc.anchors && doc.root && !doc.task_id);
592
- }
593
- function readOfflineWitness(args) {
594
- let head = null;
595
- let inclusion = null;
596
- for (const file of args.positionals.slice(1)) {
597
- let doc;
598
- try {
599
- doc = readJson(file);
600
- }
601
- catch (err) {
602
- throw new Error(`Error reading ${file}: ${err instanceof Error ? err.message : String(err)}`);
603
- }
604
- const row = doc;
605
- if (looksLikeTreeHead(doc))
606
- head = doc;
607
- else if (doc && typeof doc === 'object' && (Array.isArray(row.proof) || row.leaf_index != null)) {
608
- inclusion = doc;
609
- }
610
- }
611
- return { head, inclusion };
612
- }
613
- function fileLooksLikeHead(file) {
614
- if (!file)
615
- return false;
616
- try {
617
- return looksLikeTreeHead(readJson(file));
618
- }
619
- catch {
620
- return false;
621
- }
622
- }
623
- function historyHostAllowed(url) {
624
- try {
625
- const parsed = new URL(url);
626
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
627
- return false;
628
- if (parsed.protocol === 'http:' && parsed.hostname !== '127.0.0.1' && parsed.hostname !== 'localhost')
629
- return false;
630
- if (parsed.protocol === 'https:') {
631
- return index_js_1.DEFAULT_TRUSTED_JWKS_HOSTS.some((host) => host.toLowerCase() === parsed.hostname.toLowerCase());
632
- }
633
- return true;
634
- }
635
- catch {
636
- return false;
637
- }
638
- }
639
- async function loadAnchorIssuerHistory(args, receipt) {
640
- if (args.issuerHistoryFile) {
641
- return JSON.parse((0, node_fs_1.readFileSync)(args.issuerHistoryFile, 'utf8'));
642
- }
643
- if (args.noIssuerHistory)
644
- return null;
645
- const url = (0, issuer_history_js_1.historyUrlFromReceipt)(receipt);
646
- if (!url || !historyHostAllowed(url))
647
- return null;
648
- try {
649
- const res = await fetch(url, { signal: AbortSignal.timeout(4000) });
650
- if (!res.ok)
651
- return null;
652
- return await res.json();
653
- }
654
- catch {
655
- return null;
656
- }
657
- }
658
- async function loadAnchorWalletDocument(args, receipt) {
659
- if (args.anchorWalletsFile) {
660
- return JSON.parse((0, node_fs_1.readFileSync)(args.anchorWalletsFile, 'utf8'));
661
- }
662
- if (args.noIssuerHistory)
663
- return null;
664
- const historyUrl = (0, issuer_history_js_1.historyUrlFromReceipt)(receipt);
665
- const epochOrigin = (() => {
666
- if (!args.epochUrl)
667
- return null;
668
- try {
669
- return new URL(args.epochUrl).origin;
670
- }
671
- catch {
672
- return null;
673
- }
674
- })();
675
- const origin = epochOrigin || (historyUrl ? new URL(historyUrl).origin : null);
676
- if (!origin)
677
- return null;
678
- const url = `${origin}/.well-known/anchor-wallets.json`;
679
- if (!historyHostAllowed(url))
680
- return null;
681
- try {
682
- const res = await fetch(url, { signal: AbortSignal.timeout(4000) });
683
- if (res.status === 404)
684
- return null;
685
- if (!res.ok)
686
- return null;
687
- return await res.json();
688
- }
689
- catch {
690
- return null;
691
- }
692
- }
693
- async function runAnchor(args) {
694
- const receiptPath = args.file;
695
- const inclusionPath = args.inclusionFile || args.positionals[1] || null;
696
- const headPath = args.headFile || (args.inclusionFile ? null : args.positionals[2]) || null;
697
- const headCandidates = [args.headFile, headPath, ...args.positionals];
698
- if (headCandidates.some((file) => file && headStatus(file) === 'not_yet_published')) {
699
- console.error('Tree head is not_yet_published.');
700
- return 3;
701
- }
702
- if (!receiptPath || !inclusionPath || !headPath) {
703
- console.error('Anchor check needs a receipt, an inclusion proof, and a tree head.');
704
- console.error(' xfuel-verify receipt.json inclusion.json head.json --rpc');
705
- return 3;
706
- }
707
- let receipt;
708
- let inclusion;
709
- let head;
710
- try {
711
- receipt = readJson(receiptPath);
712
- inclusion = readJson(inclusionPath);
713
- head = readJson(headPath);
714
- }
715
- catch (err) {
716
- console.error(`Error reading anchor inputs: ${err instanceof Error ? err.message : String(err)}`);
717
- return 3;
718
- }
719
- let fileJwks;
720
- if (args.jwksFile) {
721
- try {
722
- fileJwks = JSON.parse((0, node_fs_1.readFileSync)(args.jwksFile, 'utf8'));
723
- }
724
- catch (err) {
725
- console.error(`Error reading JWKS file: ${err instanceof Error ? err.message : String(err)}`);
726
- return 3;
727
- }
728
- }
729
- const loaded = await (0, index_js_1.loadIssuerJwks)(receipt, {
730
- jwks: fileJwks,
731
- jwksUri: args.jwksUrl || undefined,
732
- fetchJwks: args.fetchJwks,
733
- });
734
- const trustedKids = args.noTrustedKid
735
- ? []
736
- : (args.trustedKids ?? [...index_js_1.DEFAULT_TRUSTED_ISSUER_KIDS]);
737
- let issuerHistory = null;
738
- let anchorWalletDocument = null;
739
- try {
740
- issuerHistory = await loadAnchorIssuerHistory(args, receipt);
741
- anchorWalletDocument = await loadAnchorWalletDocument(args, receipt);
742
- }
743
- catch (err) {
744
- console.error(`Error reading issuer trust files: ${err instanceof Error ? err.message : String(err)}`);
745
- return 3;
746
- }
747
- let epochRecord = null;
748
- let verifyEpochSignature;
749
- if (headNeedsEpochRecord(head)) {
750
- try {
751
- epochRecord = await loadEpochRecord(args, receipt);
752
- }
753
- catch {
754
- epochRecord = null;
755
- }
756
- if (epochRecord?.issuer_signature?.jws) {
757
- verifyEpochSignature = (jws) => epochSignatureOk(epochRecord, jws, loaded.jwks, trustedKids);
758
- }
759
- }
760
- let issuerPin;
761
- const pinClaim = (0, issuer_pin_js_1.readIssuerPinClaim)(receipt).claimed || (0, issuer_pin_js_1.readIssuerPinClaim)(head).claimed;
762
- const pinRequested = Boolean(args.issuerPinFile) || pinClaim;
763
- if (pinRequested) {
764
- try {
765
- const claimRef = (0, issuer_pin_js_1.readIssuerPinClaim)(receipt).ref || (0, issuer_pin_js_1.readIssuerPinClaim)(head).ref;
766
- const ref = (args.issuerPinCommit || args.issuerPinSha256 || claimRef)
767
- ? {
768
- commit: args.issuerPinCommit || claimRef?.commit || '',
769
- path: claimRef?.path || 'docs/well-known/issuer-key.json',
770
- sha256: (args.issuerPinSha256 || claimRef?.sha256 || '').toLowerCase(),
771
- }
772
- : null;
773
- let witnesses;
774
- if (args.issuerWitnessesFile)
775
- witnesses = JSON.parse((0, node_fs_1.readFileSync)(args.issuerWitnessesFile, 'utf8'));
776
- const priorRef = args.issuerPriorPinFile
777
- ? {
778
- commit: args.issuerPriorCommit || '',
779
- path: 'docs/well-known/issuer-key.json',
780
- sha256: (args.issuerPriorSha256 || '').toLowerCase(),
781
- }
782
- : null;
783
- issuerPin = {
784
- pinBytes: args.issuerPinFile ? (0, node_fs_1.readFileSync)(args.issuerPinFile, 'utf8') : null,
785
- sigBytes: args.issuerPinSigFile ? (0, node_fs_1.readFileSync)(args.issuerPinSigFile, 'utf8') : null,
786
- ref,
787
- witnesses,
788
- priorPinBytes: args.issuerPriorPinFile ? (0, node_fs_1.readFileSync)(args.issuerPriorPinFile, 'utf8') : null,
789
- priorRef,
790
- controlJws: args.issuerControlFile ? (0, node_fs_1.readFileSync)(args.issuerControlFile, 'utf8').trim() : null,
791
- required: true,
792
- };
793
- }
794
- catch (err) {
795
- console.error(`Error reading issuer pin: ${err instanceof Error ? err.message : String(err)}`);
796
- return 3;
797
- }
798
- }
799
- const result = await (0, anchor_witness_js_1.verifyAnchoredRoot)({
800
- receipt,
801
- inclusion,
802
- head,
803
- baseRpcUrl: args.rpcUrl || undefined,
804
- solanaRpcUrl: args.solanaRpcUrl || undefined,
805
- checkNewestAnchor: args.sawRpc,
806
- epochRecord,
807
- verifyEpochSignature,
808
- issuerPin,
809
- jwks: loaded.jwks,
810
- trustedKids,
811
- issuerHistory,
812
- strictIssuerHistory: args.strictIssuerHistory,
813
- anchorWalletDocument: anchorWalletDocument,
814
- });
815
- let canonicalPreimage = null;
816
- if (args.canonicalPreimageFile) {
817
- canonicalPreimage = (0, node_fs_1.readFileSync)(args.canonicalPreimageFile, 'utf8');
818
- }
819
- const historyBytes = args.issuerHistoryFile ? (0, node_fs_1.readFileSync)(args.issuerHistoryFile, 'utf8') : null;
820
- const verified = await (0, index_js_1.verifyReceipt)(receipt, {
821
- jwks: loaded.jwks,
822
- jwksUri: args.jwksUrl || undefined,
823
- fetchJwks: args.fetchJwks,
824
- trustedKids,
825
- checkNullifier: args.checkNullifier,
826
- checkPayer: args.checkPayer,
827
- rpcUrl: args.rpcUrl || undefined,
828
- solanaRpcUrl: args.solanaRpcUrl || undefined,
829
- requirePreimages: !args.noPreimage,
830
- issuerHistory: args.issuerHistoryFile ? issuerHistory : null,
831
- issuerHistoryBytes: historyBytes,
832
- fetchIssuerHistory: !args.noIssuerHistory && !args.issuerHistoryFile,
833
- strictIssuerHistory: args.strictIssuerHistory,
834
- skipIssuerHistory: args.noIssuerHistory,
835
- canonicalPreimage,
836
- head,
837
- });
838
- // Inclusion was already checked above. Passing it again re-derives the leaf
839
- // from book_chain.row_hash only, which rejects a receipt that stores row_hash
840
- // at the top level. Log mode still requires the receipt itself. A missing or
841
- // stripped issuer signature, a partial check, or a signed-versus-outer
842
- // mismatch fails the combined result. An inclusion match is not VERIFIED.
843
- const issuerSig = receipt.issuer_signature;
844
- const signaturePresent = Boolean(issuerSig?.jws || issuerSig?.value);
845
- const receiptVerified = signaturePresent
846
- && verified.issuer_signature.valid === true
847
- && (verified.overall === 'verified' || verified.overall === 'verified_carried_forward')
848
- && verified.claim_mismatches.length === 0;
849
- const receiptFailed = !receiptVerified;
850
- const receiptErrors = [...verified.errors];
851
- if (!signaturePresent) {
852
- receiptErrors.push(verified.issuer_signature.reason || 'receipt_signature_missing');
853
- }
854
- else if (verified.overall === 'partial') {
855
- receiptErrors.push(verified.issuer_signature.reason || 'receipt_check_partial');
856
- }
857
- const errors = receiptFailed
858
- ? [...result.errors, ...receiptErrors.filter((err) => !result.errors.includes(err))]
859
- : result.errors;
860
- const combined = {
861
- ...result,
862
- errors,
863
- overall: receiptFailed ? 'failed' : result.overall,
864
- receipt_lane: verified.receipt_lane,
865
- receipt_check: {
866
- overall: result.overall === 'pending' && !receiptFailed ? 'pending' : verified.overall,
867
- verified_scope: verified.verified_scope,
868
- claim_mismatches: verified.claim_mismatches,
869
- unsigned_fields: verified.unsigned_fields,
870
- errors: verified.errors,
871
- },
872
- };
873
- if (args.json) {
874
- console.log(JSON.stringify(combined, null, 2));
875
- }
876
- else {
877
- printAnchor(combined, false, args.quiet);
878
- if (!args.quiet || receiptFailed) {
879
- const anchorPending = result.overall === 'pending';
880
- const receiptLabel = anchorPending && !receiptFailed
881
- ? 'PENDING'
882
- : verified.overall.toUpperCase();
883
- console.log(` Receipt checks: ${receiptLabel} (signed claims only)`);
884
- if (verified.claim_mismatches.length > 0) {
885
- for (const mismatch of verified.claim_mismatches) {
886
- console.log(` ${mismatch.field}: outer ${mismatch.outer} ≠ signed ${mismatch.signed}`);
887
- }
888
- }
889
- if (!(anchorPending && !receiptFailed))
890
- printUnsigned(verified.unsigned_fields);
891
- console.log('');
892
- }
893
- if (!args.quiet)
894
- printLane(verified.receipt_lane);
895
- }
896
- if (combined.overall === 'verified')
897
- return 0;
898
- if (combined.overall === 'partial' || combined.overall === 'pending')
899
- return 2;
900
- return 1;
901
- }
902
- function printUnsigned(fields) {
903
- console.log(' Scope: signed claims only. Unsigned fields are UNVERIFIED.');
904
- if (fields.length === 0)
905
- return;
906
- console.log(` Unsigned fields (${fields.length})`);
907
- console.log(' ─────────────────────────────────────────────────');
908
- for (const field of fields)
909
- console.log(` UNVERIFIED ${field}`);
910
- }
911
- async function runRefusal(doc, args) {
912
- const trustedKids = args.trustedKids ?? index_js_1.DEFAULT_TRUSTED_ISSUER_KIDS;
913
- const result = (0, index_js_1.verifyRefusal)(doc, {
914
- jwks: args.jwks,
915
- trustedKids,
916
- });
917
- const preimages = await (0, preimage_js_1.verifyPublishedPreimages)(doc, {
918
- requirePreimages: args.requirePreimages,
919
- });
920
- let canonicalFailed = false;
921
- if (args.canonicalPreimage != null) {
922
- const canonical = (0, canonical_preimage_js_1.verifyCanonicalPreimageBytes)(args.canonicalPreimage, result.payload_hash);
923
- canonicalFailed = !canonical.ok;
924
- if (canonicalFailed)
925
- preimages.errors.push(`canonical preimage: ${canonical.reason}`);
926
- if (canonicalFailed)
927
- preimages.ok = false;
928
- }
929
- const pin = result.valid ? (0, issuer_history_js_1.readIssuerHistoryPin)({
930
- issuer_history: result.issuer_history,
931
- }) : null;
932
- const history = args.skipIssuerHistory
933
- ? { checked: false, ok: true, unreachable: false, warning: null, reason: null, kid: result.kid ?? null, document: null, loaded: false }
934
- : await (0, issuer_history_js_1.checkReceiptIssuerHistory)(doc, {
935
- document: args.issuerHistory,
936
- documentBytes: args.issuerHistoryBytes,
937
- fetchHistory: args.fetchIssuerHistory,
938
- strict: args.strictIssuerHistory,
939
- jwks: args.jwks,
940
- trustedKids,
941
- issuedAt: doc.issued_at ?? null,
942
- kid: result.kid ?? doc.issuer_signature?.kid ?? null,
943
- pin,
944
- requirePin: result.valid && Number(result.payload_version) >= 2,
945
- });
946
- const historyFailed = history.checked && !history.ok;
947
- const failed = !result.valid || !preimages.ok || historyFailed || canonicalFailed;
948
- if (args.json) {
949
- console.log(JSON.stringify({ ...result, preimages, issuer_history: history }, null, 2));
950
- }
951
- else if (!args.quiet || failed) {
952
- console.log('');
953
- console.log(' Chit402 Refusal Verification');
954
- console.log(' ─────────────────────────────────────────────────');
955
- console.log(` Schema: ${result.schema}`);
956
- console.log(` Refusal ID: ${result.refusal_id || doc.refusal_id || '—'}`);
957
- console.log(` Code: ${result.refusal_code || doc.refusal_code || '—'}`);
958
- console.log(` Nonce: ${result.nonce || '—'}`);
959
- console.log(` Chain: ${result.chain_id ?? 'null'}`);
960
- console.log(` Charged: false`);
961
- console.log('');
962
- console.log(' Issuer Signature');
963
- console.log(' ─────────────────────────────────────────────────');
964
- console.log(` Valid: ${result.valid ? '✓ YES' : '✗ NO'}`);
965
- if (result.kid)
966
- console.log(` Kid: ${result.kid}`);
967
- if (!result.valid && result.reason)
968
- console.log(` Reason: ${result.reason}`);
969
- console.log('');
970
- console.log(' What this proves');
971
- console.log(' ─────────────────────────────────────────────────');
972
- for (const line of result.proves)
973
- console.log(` ${line}`);
974
- console.log('');
975
- console.log(' What this does not prove');
976
- console.log(' ─────────────────────────────────────────────────');
977
- for (const line of result.does_not_prove)
978
- console.log(` ${line}`);
979
- console.log('');
980
- console.log(` Overall: ${failed ? 'FAILED' : 'VERIFIED'}`);
981
- if (!preimages.ok)
982
- console.log(` Preimages: ${preimages.errors.join('; ')}`);
983
- if (history.warning)
984
- console.log(` Issuer history: ${history.warning}`);
985
- if (historyFailed && history.reason)
986
- console.log(` Issuer history: ${history.reason}`);
987
- console.log('');
988
- }
989
- return failed ? 1 : 0;
990
- }
991
- async function main() {
992
- const args = parseArgs(process.argv.slice(2));
993
- if (args.version) {
994
- console.log(`@xfuel/verify ${packageVersion()}`);
995
- return 0;
996
- }
997
- let anchorMode = args.anchorFlag
998
- || Boolean(args.inclusionFile || args.headFile)
999
- || (args.positionals.length >= 3 && args.sawRpc);
1000
- if (!anchorMode && args.sawRpc && args.positionals.some((file) => fileLooksLikeHead(file))) {
1001
- anchorMode = true;
1002
- }
1003
- if (args.help) {
1004
- console.log(HELP);
1005
- return 0;
1006
- }
1007
- if (args.url && !args.jwsFile) {
1008
- try {
1009
- const response = await fetch(args.url);
1010
- await response.arrayBuffer();
1011
- }
1012
- catch {
1013
- // A failed fetch is still not a pass.
1014
- }
1015
- console.log('owner_proof_required');
1016
- console.log(' Overall: OWNER_PROOF_REQUIRED');
1017
- return 1;
1018
- }
1019
- let offlineWitness = null;
1020
- if (!anchorMode) {
1021
- try {
1022
- offlineWitness = readOfflineWitness(args);
1023
- }
1024
- catch (err) {
1025
- console.error(err instanceof Error ? err.message : String(err));
1026
- return 3;
1027
- }
1028
- }
1029
- // A shell plus a holder is not anchor mode. Inclusion is checked with the
1030
- // holder. Anchor mode would verify the unsigned shell and skip the key.
1031
- if (anchorMode && !args.jwsFile && !args.acceptShell)
1032
- return runAnchor(args);
1033
- if (!args.file) {
1034
- console.log(HELP);
1035
- return 3;
1036
- }
1037
- let receipt;
1038
- try {
1039
- receipt = readReceipt(args.file);
1040
- }
1041
- catch (err) {
1042
- console.error(`Error reading receipt: ${err instanceof Error ? err.message : String(err)}`);
1043
- return 3;
1044
- }
1045
- if ((0, shell_js_1.isReceiptShell)(receipt) || args.acceptShell || args.jwsFile) {
1046
- if (!(0, shell_js_1.isReceiptShell)(receipt)) {
1047
- console.error('Invalid shell: schema is not chit402.receipt_shell.v1');
1048
- return 3;
1049
- }
1050
- if (!args.jwsFile) {
1051
- console.log(shell_js_1.INCLUDED_SHELL_LINE);
1052
- console.log(' Overall: INCLUDED_SHELL');
1053
- return args.acceptShell ? 0 : 1;
1054
- }
1055
- let holder;
1056
- try {
1057
- const text = (0, node_fs_1.readFileSync)(args.jwsFile, 'utf8');
1058
- let parsed = text;
1059
- try {
1060
- parsed = JSON.parse(text);
1061
- }
1062
- catch {
1063
- parsed = text;
1064
- }
1065
- holder = (0, shell_js_1.holderDocumentFromOwnerView)(parsed);
1066
- }
1067
- catch (err) {
1068
- console.error(`Error reading JWS: ${err instanceof Error ? err.message : String(err)}`);
1069
- return 3;
1070
- }
1071
- const shellDoc = receipt;
1072
- const compared = (0, shell_js_1.compareShellToJws)(shellDoc, holder);
1073
- if (!compared.ok) {
1074
- console.log('shell_jws_mismatch');
1075
- if (compared.field)
1076
- console.log(` Field: ${compared.field}`);
1077
- console.log(' Overall: FAILED');
1078
- return 1;
1079
- }
1080
- let jwks;
1081
- if (args.jwksFile) {
1082
- try {
1083
- jwks = JSON.parse((0, node_fs_1.readFileSync)(args.jwksFile, 'utf8'));
1084
- }
1085
- catch (err) {
1086
- console.error(`Error reading JWKS file: ${err instanceof Error ? err.message : String(err)}`);
1087
- return 3;
1088
- }
1089
- }
1090
- let inclusion = offlineWitness?.inclusion ?? null;
1091
- let head = offlineWitness?.head ?? null;
1092
- try {
1093
- if (args.inclusionFile)
1094
- inclusion = readJson(args.inclusionFile);
1095
- if (args.headFile)
1096
- head = readJson(args.headFile);
1097
- }
1098
- catch (err) {
1099
- console.error(`Error reading inclusion: ${err instanceof Error ? err.message : String(err)}`);
1100
- return 3;
1101
- }
1102
- const trustedKids = args.noTrustedKid
1103
- ? []
1104
- : (args.trustedKids ?? [...index_js_1.DEFAULT_TRUSTED_ISSUER_KIDS]);
1105
- const result = await (0, index_js_1.verifyReceipt)(holder, {
1106
- jwks,
1107
- jwksUri: args.jwksUrl || undefined,
1108
- fetchJwks: args.fetchJwks,
1109
- trustedKids,
1110
- checkPayer: args.checkPayer,
1111
- rpcUrl: args.rpcUrl || undefined,
1112
- solanaRpcUrl: args.solanaRpcUrl || undefined,
1113
- requirePreimages: false,
1114
- skipIssuerHistory: args.noIssuerHistory || !args.issuerHistoryFile,
1115
- issuerHistory: null,
1116
- fetchIssuerHistory: false,
1117
- salt: args.salt,
1118
- head: head ?? undefined,
1119
- inclusion: inclusion ?? undefined,
1120
- });
1121
- const inclusionErrors = result.errors.filter((err) => /inclusion|leaf|row_hash|bad_root|tree_size|tree_head|no_leaf/.test(err));
1122
- const shellLeaf = (shellDoc.inclusion && typeof shellDoc.inclusion === 'object')
1123
- ? shellDoc.inclusion.leaf_hash
1124
- : null;
1125
- const provedLeaf = inclusion && typeof inclusion.leaf === 'string'
1126
- ? inclusion.leaf
1127
- : null;
1128
- // A head the user wrote by hand ({root, tree_size}) is not a log. The
1129
- // inclusion only counts against a head that carries an issuer JWS;
1130
- // verifyReceipt() checks that JWS against the same trust set.
1131
- const headSig = head && typeof head === 'object'
1132
- ? head.issuer_signature
1133
- : null;
1134
- const headSigned = !!headSig && typeof headSig.jws === 'string' && headSig.jws.split('.').length === 3;
1135
- const verdict = (0, shell_js_1.shellHolderVerdict)({
1136
- signatureValid: result.issuer_signature.valid === true,
1137
- keyTrusted: result.issuer_signature.key_trusted === true,
1138
- signatureReason: result.issuer_signature.reason || (result.issuer_signature.key_trusted ? null : 'key untrusted'),
1139
- inclusionSupplied: inclusion != null,
1140
- inclusionOk: inclusion != null && inclusionErrors.length === 0,
1141
- inclusionReason: inclusion == null ? 'inclusion_missing' : (inclusionErrors[0] || null),
1142
- headSigned,
1143
- paymentRef: result.tx,
1144
- bindingExpected: !!result.binding.expected,
1145
- bindingMatches: result.binding.matches === true,
1146
- shellLeaf: shellLeaf == null ? null : String(shellLeaf),
1147
- provedLeaf,
1148
- });
1149
- if (!verdict.verified || (result.overall !== 'verified' && result.overall !== 'verified_carried_forward')) {
1150
- const reason = verdict.reason || result.errors[0] || 'failed';
1151
- console.log(reason);
1152
- console.log(' Overall: FAILED');
1153
- return 1;
1154
- }
1155
- if (args.checkPayer && !result.payer.valid) {
1156
- console.log(result.payer.reason || 'payment_unchecked');
1157
- console.log(' Overall: FAILED');
1158
- return 1;
1159
- }
1160
- const issuer = holder.issuer_signature;
1161
- if (args.salt) {
1162
- const opened = (0, shell_js_1.openV11Commitment)({
1163
- payload: (0, shell_js_1.decodeJwsPayload)(issuer?.jws),
1164
- saltHex: args.salt || '',
1165
- body: Buffer.alloc(0),
1166
- });
1167
- if (!opened.ok) {
1168
- console.log(opened.reason || 'commitment_mismatch');
1169
- console.log(' Overall: FAILED');
1170
- return 1;
1171
- }
1172
- }
1173
- console.log(' Overall: VERIFIED');
1174
- return 0;
1175
- }
1176
- const v11 = receipt.v === 11 || (receipt.issuer_signature?.jws
1177
- ? (() => {
1178
- try {
1179
- const part = String(receipt.issuer_signature.jws).split('.')[1];
1180
- const payload = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'));
1181
- return payload?.v === 11;
1182
- }
1183
- catch {
1184
- return false;
1185
- }
1186
- })()
1187
- : false);
1188
- if (!receipt.task_id && !v11) {
1189
- console.error('Invalid receipt: missing task_id');
1190
- return 3;
1191
- }
1192
- // Load JWKS if provided
1193
- let jwks;
1194
- if (args.jwksFile) {
1195
- try {
1196
- const jwksContent = (0, node_fs_1.readFileSync)(args.jwksFile, 'utf8');
1197
- jwks = JSON.parse(jwksContent);
1198
- }
1199
- catch (err) {
1200
- console.error(`Error reading JWKS file: ${err instanceof Error ? err.message : String(err)}`);
1201
- return 3;
1202
- }
1203
- }
1204
- const trustedKids = args.noTrustedKid
1205
- ? []
1206
- : (args.trustedKids ?? index_js_1.DEFAULT_TRUSTED_ISSUER_KIDS);
1207
- if ((0, index_js_1.isRefusalDocument)(receipt)) {
1208
- let issuerHistory = null;
1209
- let issuerHistoryBytes = null;
1210
- if (args.issuerHistoryFile) {
1211
- issuerHistoryBytes = (0, node_fs_1.readFileSync)(args.issuerHistoryFile, 'utf8');
1212
- issuerHistory = JSON.parse(issuerHistoryBytes);
1213
- }
1214
- let canonicalPreimage = null;
1215
- if (args.canonicalPreimageFile) {
1216
- canonicalPreimage = (0, node_fs_1.readFileSync)(args.canonicalPreimageFile, 'utf8');
1217
- }
1218
- return runRefusal(receipt, {
1219
- jwks,
1220
- trustedKids,
1221
- json: args.json,
1222
- quiet: args.quiet,
1223
- requirePreimages: !args.noPreimage,
1224
- issuerHistory,
1225
- issuerHistoryBytes,
1226
- fetchIssuerHistory: !args.noIssuerHistory && !issuerHistory,
1227
- strictIssuerHistory: args.strictIssuerHistory,
1228
- skipIssuerHistory: args.noIssuerHistory,
1229
- canonicalPreimage,
1230
- });
1231
- }
1232
- let issuerHistory = null;
1233
- let issuerHistoryBytes = null;
1234
- if (args.issuerHistoryFile) {
1235
- try {
1236
- issuerHistoryBytes = (0, node_fs_1.readFileSync)(args.issuerHistoryFile, 'utf8');
1237
- issuerHistory = JSON.parse(issuerHistoryBytes);
1238
- }
1239
- catch (err) {
1240
- console.error(`Error reading issuer history: ${err instanceof Error ? err.message : String(err)}`);
1241
- return 3;
1242
- }
1243
- }
1244
- let canonicalPreimage = null;
1245
- if (args.canonicalPreimageFile) {
1246
- try {
1247
- canonicalPreimage = (0, node_fs_1.readFileSync)(args.canonicalPreimageFile, 'utf8');
1248
- }
1249
- catch (err) {
1250
- console.error(`Error reading canonical preimage: ${err instanceof Error ? err.message : String(err)}`);
1251
- return 3;
1252
- }
1253
- }
1254
- const carryAsked = args.carryOldHeadFile || args.carryOldInclusionFile
1255
- || args.carryHeadFile || args.carryInclusionFiles.length > 0;
1256
- let carry = null;
1257
- if (carryAsked) {
1258
- try {
1259
- carry = {
1260
- oldHead: args.carryOldHeadFile ? readJson(args.carryOldHeadFile) : {},
1261
- oldInclusion: args.carryOldInclusionFile ? readJson(args.carryOldInclusionFile) : { error: 'not_in_tree' },
1262
- currentHead: args.carryHeadFile ? readJson(args.carryHeadFile) : {},
1263
- currentInclusions: args.carryInclusionFiles.length > 0
1264
- ? args.carryInclusionFiles.map((file) => readJson(file))
1265
- : [{ error: 'not_in_tree' }],
1266
- };
1267
- }
1268
- catch (err) {
1269
- console.error(`Error reading carry-forward files: ${err instanceof Error ? err.message : String(err)}`);
1270
- return 3;
1271
- }
1272
- }
1273
- let open;
1274
- if (args.open.length > 0) {
1275
- open = {};
1276
- try {
1277
- for (const spec of args.open) {
1278
- const opened = (0, v11_receipt_js_1.readOpenFile)(spec);
1279
- if (opened.kind === 'output')
1280
- open.output = opened.bytes;
1281
- else
1282
- open[opened.kind] = opened.text;
1283
- }
1284
- }
1285
- catch (err) {
1286
- console.error(err instanceof Error ? err.message : String(err));
1287
- return 3;
1288
- }
1289
- }
1290
- const result = await (0, index_js_1.verifyReceipt)(receipt, {
1291
- jwks,
1292
- jwksUri: args.jwksUrl || undefined,
1293
- fetchJwks: args.fetchJwks,
1294
- trustedKids,
1295
- checkNullifier: args.checkNullifier,
1296
- checkPayer: args.checkPayer,
1297
- rpcUrl: args.rpcUrl || undefined,
1298
- solanaRpcUrl: args.solanaRpcUrl || undefined,
1299
- requirePreimages: !args.noPreimage,
1300
- issuerHistory,
1301
- issuerHistoryBytes,
1302
- fetchIssuerHistory: !args.noIssuerHistory && !issuerHistory,
1303
- strictIssuerHistory: args.strictIssuerHistory,
1304
- skipIssuerHistory: args.noIssuerHistory,
1305
- canonicalPreimage,
1306
- salt: args.salt,
1307
- open,
1308
- head: offlineWitness?.head ?? undefined,
1309
- inclusion: offlineWitness?.inclusion ?? undefined,
1310
- carry,
1311
- });
1312
- if (args.json) {
1313
- console.log(JSON.stringify(result, null, 2));
1314
- }
1315
- else if (!args.quiet || result.overall === 'failed') {
1316
- console.log('');
1317
- console.log(` Chit402 Receipt Verification`);
1318
- console.log(` ─────────────────────────────────────────────────`);
1319
- console.log(` Receipt ID: ${result.receipt_id}`);
1320
- console.log(` Hub: ${result.hub || '—'}`);
1321
- console.log(` Model: ${result.model || '—'}`);
1322
- console.log(` Amount: ${result.issuer_signature.valid ? formatAmount(result.amount_usdc) : '— (not verified)'}`);
1323
- console.log(` TX: ${result.tx || '—'}`);
1324
- console.log(` Output Hash: ${result.output_hash ? result.output_hash.slice(0, 18) + '…' : '—'}`);
1325
- console.log('');
1326
- console.log(` Binding`);
1327
- console.log(` ─────────────────────────────────────────────────`);
1328
- if (result.binding.expected) {
1329
- console.log(` Expected: ${result.binding.expected.slice(0, 18)}…`);
1330
- console.log(` Recomputed: ${result.binding.recomputed?.slice(0, 18)}…`);
1331
- console.log(` Match: ${result.binding.matches ? '✓ YES' : '✗ NO'}`);
1332
- console.log(` Covers: ${result.binding.covers.join(', ')}`);
1333
- }
1334
- else {
1335
- console.log(` Status: ${result.binding.reason || 'No payment-binding commitment'}`);
1336
- }
1337
- console.log('');
1338
- console.log(` Issuer Signature`);
1339
- console.log(` ─────────────────────────────────────────────────`);
1340
- if (result.issuer_signature.checked) {
1341
- console.log(` Kid: ${result.issuer_signature.kid || '—'}`);
1342
- console.log(` Valid: ${result.issuer_signature.valid ? '✓ YES' : '✗ NO'}`);
1343
- console.log(` Key trusted: ${result.issuer_signature.key_trusted ? '✓ YES' : '✗ NO'}${result.issuer_signature.trust ? ` (${result.issuer_signature.trust})` : ''}`);
1344
- if (!result.issuer_signature.valid && result.issuer_signature.reason) {
1345
- console.log(` Reason: ${result.issuer_signature.reason}`);
1346
- }
1347
- }
1348
- else {
1349
- console.log(` Status: ${result.issuer_signature.reason || 'Not checked'}`);
1350
- if (receipt.issuer_signature && !args.jwksFile && !args.fetchJwks && !args.jwksUrl) {
1351
- console.log(` (pass --jwks-file, --fetch-jwks, or rely on the default trusted kid)`);
1352
- }
1353
- }
1354
- console.log('');
1355
- console.log(` Payer (on-chain)`);
1356
- console.log(` ─────────────────────────────────────────────────`);
1357
- if (result.payer.checked) {
1358
- console.log(` Rail: ${result.payer.rail || '—'}`);
1359
- console.log(` Payer: ${result.payer.payer_wallet || '—'}`);
1360
- console.log(` Payee: ${result.payer.payee || '—'}`);
1361
- console.log(` Asset: ${result.payer.asset || '—'}`);
1362
- console.log(` Amount: ${formatAmount(result.payer.amount || null)}`);
1363
- console.log(` Valid: ${result.payer.valid ? '✓ YES' : '✗ NO'}`);
1364
- if (!result.payer.valid && result.payer.reason) {
1365
- console.log(` Reason: ${result.payer.reason}`);
1366
- }
1367
- }
1368
- else {
1369
- console.log(` Status: ${result.payer.reason || 'Not checked'}`);
1370
- if (result.issuer_signature.valid && result.payer.payer_wallet && result.tx && !args.checkPayer) {
1371
- console.log(` (pass --check-payer to verify payer, payee, asset, and amount on-chain)`);
1372
- }
1373
- }
1374
- if (result.claim_mismatches.length > 0) {
1375
- console.log('');
1376
- console.log(` Outer / signed mismatches`);
1377
- console.log(` ─────────────────────────────────────────────────`);
1378
- for (const mismatch of result.claim_mismatches) {
1379
- console.log(` ${mismatch.field}: outer ${mismatch.outer} ≠ signed ${mismatch.signed}`);
1380
- }
1381
- }
1382
- console.log('');
1383
- printUnsigned(result.unsigned_fields);
1384
- console.log('');
1385
- console.log(` Nullifier`);
1386
- console.log(` ─────────────────────────────────────────────────`);
1387
- if (result.nullifier.nullifier) {
1388
- console.log(` Value: ${result.nullifier.nullifier.slice(0, 18)}…`);
1389
- if (args.checkNullifier) {
1390
- console.log(` On-chain: ${result.nullifier.anchored ? '✓ ANCHORED' : '✗ NOT FOUND'}`);
1391
- }
1392
- else {
1393
- console.log(` On-chain: (not checked — use --check-nullifier)`);
1394
- }
1395
- }
1396
- else {
1397
- console.log(` Status: No nullifier (Tier-1 receipt)`);
1398
- }
1399
- console.log('');
1400
- printLane(result.receipt_lane);
1401
- if (result.preimages.checked) {
1402
- console.log(` Preimages: ${result.preimages.ok ? '✓ MATCH' : '✗ ' + result.preimages.errors.join('; ')}`);
1403
- }
1404
- if (result.issuer_history.checked) {
1405
- console.log(` Issuer history: ${result.issuer_history.ok ? '✓ kid in window' : '✗ ' + (result.issuer_history.reason || 'failed')}`);
1406
- }
1407
- else if (result.issuer_history.warning) {
1408
- console.log(` Issuer history: ${result.issuer_history.warning}`);
1409
- }
1410
- if (result.carry_forward?.status === 'VERIFIED_CARRIED_FORWARD') {
1411
- const carried = result.carry_forward;
1412
- console.log(` Log`);
1413
- console.log(` ─────────────────────────────────────────────────`);
1414
- console.log(` Status: ${carried.status}`);
1415
- console.log(` Issued at: ${carried.issued_at}`);
1416
- console.log(` Issued epoch: ${carried.issued_epoch}`);
1417
- console.log(` Logged at: ${carried.logged_at}`);
1418
- console.log(` Logged epoch: ${carried.logged_epoch}`);
1419
- console.log(` Leaf index: ${carried.leaf_index}`);
1420
- console.log('');
1421
- }
1422
- console.log(` Overall: ${result.overall.toUpperCase()}`);
1423
- if (result.errors.length > 0) {
1424
- console.log(` Errors: ${result.errors.join(', ')}`);
1425
- }
1426
- console.log('');
1427
- }
1428
- switch (result.overall) {
1429
- case 'verified':
1430
- case 'verified_carried_forward':
1431
- return 0;
1432
- case 'failed':
1433
- return 1;
1434
- case 'partial':
1435
- return 2;
1436
- default:
1437
- return 1;
1438
- }
1439
- }
1440
- /**
1441
- * Node's fetch keeps its undici agent on this symbol after the first request.
1442
- * There is no public handle for that pool. Closing it lets the loop drain.
1443
- */
1444
- const UNDICI_GLOBAL_DISPATCHER = Symbol.for('undici.globalDispatcher.1');
1445
- function fetchDispatcher() {
1446
- const bag = globalThis;
1447
- return bag[UNDICI_GLOBAL_DISPATCHER];
1448
- }
1449
- /**
1450
- * process.exit() while a fetch keep-alive socket is already CLOSING aborts
1451
- * on Windows: Assertion failed: !(handle->flags & UV_HANDLE_CLOSING)
1452
- * (src/win/async.c). Set the code and close the pool so the loop can drain.
1453
- */
1454
- async function finish(code) {
1455
- process.exitCode = code;
1456
- const dispatcher = fetchDispatcher();
1457
- if (!dispatcher)
1458
- return;
1459
- try {
1460
- const closing = dispatcher.close?.();
1461
- if (closing)
1462
- await closing;
1463
- }
1464
- catch {
1465
- try {
1466
- await dispatcher.destroy?.();
1467
- }
1468
- catch {
1469
- // The verification result is already the exit code.
1470
- }
1471
- }
1472
- }
1473
- main()
1474
- .then((code) => finish(code))
1475
- .catch((err) => {
1476
- console.error('Unexpected error:', err);
1477
- return finish(3);
1478
- });
1479
- //# sourceMappingURL=cli.js.map