@useopentab/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,719 @@
1
+ import {
2
+ BUREAU_KINDS,
3
+ REGISTRY_ENTRYPOINTS,
4
+ drpAnchorRoot,
5
+ registryCall,
6
+ verifyDrpAnchor,
7
+ verifyTxWith
8
+ } from "./chunk-HTU7QRDF.js";
9
+ import {
10
+ HASH_RE,
11
+ attempt,
12
+ bureauCall,
13
+ bureauConfig,
14
+ bureauEvents,
15
+ ccd,
16
+ finalizedTx,
17
+ lineOf,
18
+ tabOf
19
+ } from "./chunk-QTI2WM44.js";
20
+ import {
21
+ agentBadge
22
+ } from "./chunk-HZHOKJIM.js";
23
+ import "./chunk-S5IAH7CT.js";
24
+ import {
25
+ ReportBuilder,
26
+ errorReport
27
+ } from "./chunk-GOEFQ62Z.js";
28
+ import {
29
+ CliError
30
+ } from "./chunk-MOZ4BFSB.js";
31
+ import {
32
+ TESTNET_CIS8,
33
+ TESTNET_CIS8004,
34
+ TESTNET_GENESIS_HEX,
35
+ accountAddressFromBase58,
36
+ accountAddressToBase58,
37
+ agreementHash,
38
+ attestationHash,
39
+ bytesEqual,
40
+ closeAckFor,
41
+ commitmentId,
42
+ contractAddressEqual,
43
+ decodeCis8004Event,
44
+ decodeCis8Event,
45
+ decodeOpenLineParams,
46
+ decodeOpenTabParams,
47
+ decodeReceiptV1,
48
+ decodeReportDefaultParams,
49
+ decodeSellerOfResult,
50
+ decodeSettleTabParams,
51
+ decodeVoucherV1,
52
+ ed25519Verify,
53
+ encodeCloseAckV1,
54
+ encodeCloseVoucherV1,
55
+ encodeConsentAttestationV1,
56
+ encodeSellerOfParams,
57
+ encodeTabAgreementV1,
58
+ encodeVoucherV1,
59
+ externalKeyIdEqual,
60
+ fromHex,
61
+ lineCommitment,
62
+ parseContractAddress,
63
+ receiptHash,
64
+ requestHash,
65
+ sessionKeyHash,
66
+ termsHash,
67
+ toHex,
68
+ vouchersHash
69
+ } from "./chunk-D3C7KAMJ.js";
70
+
71
+ // packages/cli/src/bundle.ts
72
+ import { z } from "zod";
73
+ var MAX_BUNDLE_BYTES = 16 * 1024 * 1024;
74
+ var hex32 = z.string().regex(/^[0-9a-f]{64}$/, "32 bytes of lowercase hex");
75
+ var hex64 = z.string().regex(/^[0-9a-f]{128}$/, "64 bytes of lowercase hex");
76
+ var hexBytes = (max) => z.string().regex(/^([0-9a-f]{2})*$/, "lowercase hex").max(max * 2);
77
+ var u64 = z.string().regex(/^(0|[1-9][0-9]{0,19})$/, "a u64 decimal string").refine((s) => BigInt(s) < 1n << 64n, "u64 out of range");
78
+ var contract = z.string().regex(/^<?\d{1,20},\d{1,20}>?$/, "`<index,subindex>`");
79
+ var address = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{50}$/, "a base58 account address");
80
+ var TX_KINDS = [
81
+ "deployModule",
82
+ "initContract",
83
+ "registerAgent",
84
+ "setAgentWallet",
85
+ "setAgentURI",
86
+ "registerExternalKey",
87
+ "registerSeller",
88
+ "openLine",
89
+ "openTab",
90
+ "settleTab",
91
+ "reportDefault",
92
+ "closeTab",
93
+ "closeLine",
94
+ "anchorVRA",
95
+ "anchorVAA",
96
+ "anchorDRP",
97
+ "exactPayment",
98
+ "other"
99
+ ];
100
+ var receiptCallSchema = z.object({
101
+ /** VoucherV1 signed bytes (tag ‖ body), hex. */
102
+ voucher: hexBytes(512),
103
+ voucherSig: hex64,
104
+ /** ReceiptV1 signed bytes (tag ‖ body), hex. */
105
+ receipt: hexBytes(512),
106
+ receiptSig: hex64,
107
+ /** The request, to recompute `request_hash`. */
108
+ request: z.object({ method: z.string().min(1).max(16), pathAndQuery: z.string().min(1).max(4096), bodyHex: hexBytes(1 << 20) }).strict().optional(),
109
+ /** SHA-256 of the response body, to compare with `response_hash`. */
110
+ responseSha256: hex32.optional()
111
+ }).strict();
112
+ var RECEIPT_LOG_FORMAT = "opentab-receipts/v1";
113
+ var receiptLogSchema = z.object({
114
+ format: z.literal(RECEIPT_LOG_FORMAT),
115
+ genesis: hex32,
116
+ bureau: contract,
117
+ tabId: u64,
118
+ /** The line's session public key (vouchers). */
119
+ buyerKey: hex32,
120
+ /** The seller's session public key (receipts). */
121
+ sellerKey: hex32,
122
+ calls: z.array(receiptCallSchema).max(1e5)
123
+ }).strict();
124
+ var bundleTxSchema = z.object({
125
+ hash: hex32,
126
+ kind: z.enum(TX_KINDS),
127
+ label: z.string().max(256).optional(),
128
+ expect: z.object({
129
+ sender: address.optional(),
130
+ tabId: u64.optional(),
131
+ lineId: u64.optional(),
132
+ amountMicroCcd: u64.optional(),
133
+ /**
134
+ * The transaction must have failed on chain: rejected by this kind's tab_bureau entrypoint
135
+ * with this reject code (spec §3.11, e.g. -7316 `Flagged`).
136
+ */
137
+ rejectCode: z.number().int().min(-(2 ** 31)).max(2 ** 31 - 1).optional(),
138
+ /** settleTab: whether it logged `CapStepped` (a ladder step) for the tab's line. */
139
+ capStepped: z.boolean().optional(),
140
+ /** anchorDRP: the DRP-1 pack root the RegisterData anchors (`"OTDRP1" ‖ root`). */
141
+ drpRoot: hex32.optional()
142
+ }).strict().optional()
143
+ }).strict();
144
+ var EVIDENCE_FORMAT = "opentab-evidence/v1";
145
+ var evidenceBundleSchema = z.object({
146
+ format: z.literal(EVIDENCE_FORMAT),
147
+ network: z.literal("testnet"),
148
+ genesis: hex32,
149
+ bureau: contract,
150
+ generatedAt: z.string().max(64),
151
+ run: z.object({ id: z.string().min(1).max(128), label: z.string().max(256).optional(), ci: z.boolean().optional() }).strict(),
152
+ transactions: z.array(bundleTxSchema).max(5e3),
153
+ lines: z.array(z.object({ lineId: u64, openTx: hex32 }).strict()).max(256),
154
+ tabs: z.array(z.object({ tabId: u64, openTx: hex32, settlements: z.array(hex32).max(1024) }).strict()).max(1024),
155
+ receipts: z.array(receiptLogSchema).max(256)
156
+ }).strict();
157
+ function parseWith(schema, bytes, what) {
158
+ if (bytes.length > MAX_BUNDLE_BYTES) throw new CliError("bad_bundle", `${what} is larger than ${MAX_BUNDLE_BYTES} bytes`);
159
+ let json;
160
+ try {
161
+ json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
162
+ } catch {
163
+ throw new CliError("bad_bundle", `${what} is not UTF-8 JSON`);
164
+ }
165
+ const r = schema.safeParse(json);
166
+ if (!r.success) {
167
+ const issue = r.error.issues[0];
168
+ throw new CliError("bad_bundle", `${what}: ${issue?.path.join(".") ?? ""} ${issue?.message ?? ""}`.trim());
169
+ }
170
+ return r.data;
171
+ }
172
+ function parseEvidenceBundle(bytes) {
173
+ const b = parseWith(evidenceBundleSchema, bytes, "evidence bundle");
174
+ if (b.genesis !== TESTNET_GENESIS_HEX) throw new CliError("wrong_network", "the bundle is not for testnet");
175
+ return b;
176
+ }
177
+ function parseReceiptLog(bytes) {
178
+ return parseWith(receiptLogSchema, bytes, "receipt log");
179
+ }
180
+
181
+ // packages/cli/src/verify/line.ts
182
+ import { VerificationAuditRecordV1, VerificationRequestV1 } from "@concordium/web-sdk";
183
+ async function checkAnchor(ctx, rb, kind, hash2, line) {
184
+ const anchor = await finalizedTx(ctx, hash2, rb, kind);
185
+ if (anchor === null) return;
186
+ rb.check(`${kind} is a RegisterData`, anchor.type === "registerData" && anchor.registeredData !== null, anchor.type);
187
+ rb.check(`${kind} sent by the verifier\u2019s anchor account`, anchor.sender === ctx.anchorAccount, anchor.sender);
188
+ rb.check(`${kind} finalized before the line`, anchor.blockHeight <= line.blockHeight, `block ${anchor.blockHeight}`);
189
+ if (anchor.registeredData === null) return;
190
+ const data = anchor.registeredData;
191
+ const decoded = attempt(
192
+ rb,
193
+ `${kind} payload decodes`,
194
+ () => kind === "CCDVRA" ? VerificationRequestV1.decodeAnchor(data) : VerificationAuditRecordV1.decodeAnchor(data)
195
+ );
196
+ if (decoded !== null) {
197
+ rb.check(`${kind} payload decodes`, true, `anchor hash ${toHex(decoded.hash)}`);
198
+ }
199
+ }
200
+ async function verifyLine(ctx, lineId, openTx) {
201
+ const rb = new ReportBuilder(`line ${lineId}`);
202
+ const tx = await finalizedTx(ctx, openTx, rb, "openLine");
203
+ if (tx === null) return rb.build();
204
+ const call = bureauCall(ctx, tx, "openLine");
205
+ if (!rb.check("calls tab_bureau.openLine on this bureau", call !== void 0) || call === void 0) return rb.build();
206
+ const params = attempt(rb, "openLine parameter decodes", () => decodeOpenLineParams(call.parameter));
207
+ if (params === null) return rb.build();
208
+ const { terms, attestation } = params;
209
+ const tHash = termsHash(terms);
210
+ const events = attempt(rb, "bureau events decode", () => bureauEvents(ctx, tx));
211
+ const opened = events?.find((e) => e.type === "LineOpened");
212
+ rb.check("logged LineOpened for this line", opened?.type === "LineOpened" && opened.lineId === lineId);
213
+ rb.check(
214
+ "commitment = H(terms_hash \u2016 H(attestation))",
215
+ opened?.type === "LineOpened" && bytesEqual(opened.commitment, lineCommitment(tHash, attestationHash(attestation)))
216
+ );
217
+ const owner = accountAddressToBase58(terms.owner);
218
+ rb.check("terms name this network and bureau", bytesEqual(terms.genesis, ctx.genesis) && contractAddressEqual(terms.bureau, ctx.bureau));
219
+ rb.check("sent by the owner the terms name", tx.sender === owner, tx.sender);
220
+ rb.check("terms pin this session key", bytesEqual(sessionKeyHash(params.sessionKey), terms.sessionKeyHash));
221
+ rb.check(
222
+ "attestation is for this owner, network, bureau and terms",
223
+ bytesEqual(attestation.owner, terms.owner) && bytesEqual(attestation.termsHash, tHash) && bytesEqual(attestation.genesis, ctx.genesis) && contractAddressEqual(attestation.bureau, ctx.bureau)
224
+ );
225
+ rb.check("attestation signature verifies", ed25519Verify(params.attestationSig, encodeConsentAttestationV1(attestation), params.attestorKey));
226
+ const config = await bureauConfig(ctx, tx.parentBlock);
227
+ const production = config.attestors.some((k) => bytesEqual(k, params.attestorKey));
228
+ const ci = config.ciAttestors.some((k) => bytesEqual(k, params.attestorKey));
229
+ rb.check("attestor is allow-listed in the bureau config", production || ci, toHex(params.attestorKey));
230
+ rb.fact("attestor", ci ? "CI attestor (flagged; excluded from metrics)" : production ? "production attestor" : "unknown");
231
+ const zero = new Uint8Array(32);
232
+ if (ci && !production && bytesEqual(attestation.vraTx, zero) && bytesEqual(attestation.vaaTx, zero)) {
233
+ rb.fact("identity proof", "none anchored: a CI line, attested by the flagged CI attestor without a CCDVRA/CCDVAA proof (excluded from metrics)");
234
+ } else {
235
+ await checkAnchor(ctx, rb, "CCDVRA", toHex(attestation.vraTx), tx);
236
+ await checkAnchor(ctx, rb, "CCDVAA", toHex(attestation.vaaTx), tx);
237
+ }
238
+ const line = await lineOf(ctx, lineId, tx.blockHash);
239
+ if (rb.check("lineOf has the line", line !== null) && line !== null) {
240
+ rb.check(
241
+ "stored line matches the terms",
242
+ line.buyerToken === terms.buyerToken && bytesEqual(line.owner, terms.owner) && bytesEqual(line.termsHash, tHash) && line.lineLimit === terms.lineLimit && line.perSellerMax === terms.perSellerMax && line.maxCycleMs === terms.maxCycleMs && line.validUntil === terms.validUntil
243
+ );
244
+ rb.check("stored line pins the session key and tier", externalKeyIdEqual(line.sessionKey, params.sessionKey) && line.tier === attestation.tier);
245
+ rb.check("stored CI flag matches the attestor", line.ci === ci);
246
+ }
247
+ rb.fact("owner", owner);
248
+ rb.fact("buyer token", terms.buyerToken);
249
+ rb.fact("tier", `T${attestation.tier}`);
250
+ rb.fact("line limit", ccd(terms.lineLimit));
251
+ rb.fact("per-seller max", ccd(terms.perSellerMax));
252
+ rb.fact("valid until", new Date(Number(terms.validUntil)).toISOString());
253
+ rb.fact("terms hash", toHex(tHash));
254
+ return rb.build();
255
+ }
256
+
257
+ // packages/cli/src/verify/receiptRules.ts
258
+ function checkReceiptLog(log, genesis, opts = {}) {
259
+ const signatures = opts.signatures ?? true;
260
+ const tabId = BigInt(log.tabId);
261
+ const bureau = parseContractAddress(log.bureau);
262
+ const buyerKey = fromHex(log.buyerKey, 32);
263
+ const sellerKey = fromHex(log.sellerKey, 32);
264
+ const decoded = [];
265
+ const failures = [];
266
+ const fail = (i, why) => {
267
+ failures.push(`call ${i + 1}: ${why}`);
268
+ };
269
+ log.calls.forEach((call, i) => {
270
+ let voucher;
271
+ let receipt;
272
+ try {
273
+ voucher = decodeVoucherV1(fromHex(call.voucher));
274
+ receipt = decodeReceiptV1(fromHex(call.receipt));
275
+ } catch (err) {
276
+ fail(i, `does not decode (${err.message})`);
277
+ return;
278
+ }
279
+ for (const [what, m] of [["voucher", voucher], ["receipt", receipt]]) {
280
+ if (!bytesEqual(m.genesis, genesis) || !contractAddressEqual(m.bureau, bureau) || m.tabId !== tabId) fail(i, `${what} names another network, bureau or tab`);
281
+ }
282
+ if (signatures) {
283
+ if (!ed25519Verify(fromHex(call.voucherSig, 64), fromHex(call.voucher), buyerKey)) fail(i, "voucher signature does not verify with the buyer key");
284
+ if (!ed25519Verify(fromHex(call.receiptSig, 64), fromHex(call.receipt), sellerKey)) fail(i, "receipt signature does not verify with the seller key");
285
+ }
286
+ if (!bytesEqual(receipt.voucherHash, commitmentId(voucher)) || receipt.lane !== voucher.lane || receipt.seq !== voucher.seq) fail(i, "receipt does not answer this voucher");
287
+ if (receipt.charged > voucher.maxPrice) fail(i, `charged ${receipt.charged} over max_price ${voucher.maxPrice}`);
288
+ if (receipt.chargedCumulative !== voucher.ackedCumulative + receipt.charged) fail(i, "charged_cumulative \u2260 acked_cumulative + charged");
289
+ if (call.request !== void 0 && !bytesEqual(requestHash(call.request.method, call.request.pathAndQuery, fromHex(call.request.bodyHex)), voucher.requestHash)) {
290
+ fail(i, "request_hash does not match the request");
291
+ }
292
+ if (call.responseSha256 !== void 0 && toHex(receipt.responseHash) !== call.responseSha256) fail(i, "response_hash does not match the response");
293
+ decoded.push({ index: i, voucher, receipt });
294
+ });
295
+ const lanes = /* @__PURE__ */ new Map();
296
+ for (const d of decoded) lanes.set(d.voucher.lane, [...lanes.get(d.voucher.lane) ?? [], d]);
297
+ let total = 0n;
298
+ for (const [lane, list] of [...lanes].sort((a, b) => a[0] - b[0])) {
299
+ list.sort((a, b) => a.voucher.seq < b.voucher.seq ? -1 : a.voucher.seq > b.voucher.seq ? 1 : 0);
300
+ let prev = null;
301
+ for (const d of list) {
302
+ const wantSeq = prev === null ? 1n : prev.seq + 1n;
303
+ if (d.voucher.seq !== wantSeq) fail(d.index, `lane ${lane} seq ${d.voucher.seq}, expected ${wantSeq}`);
304
+ const wantAck = prev === null ? 0n : prev.chargedCumulative;
305
+ if (d.voucher.ackedCumulative !== wantAck) fail(d.index, `lane ${lane} acked ${d.voucher.ackedCumulative}, expected ${wantAck}`);
306
+ const wantPrev = prev === null ? new Uint8Array(32) : receiptHash(prev);
307
+ if (!bytesEqual(d.voucher.prevReceiptHash, wantPrev)) fail(d.index, `lane ${lane} prev_receipt_hash does not chain`);
308
+ prev = d.receipt;
309
+ }
310
+ total += prev?.chargedCumulative ?? 0n;
311
+ }
312
+ return { failures, decoded, lanes, total };
313
+ }
314
+
315
+ // packages/cli/src/verify/receipts.ts
316
+ var MAX_LISTED = 20;
317
+ async function verifyReceipts(log, ctx, genesis) {
318
+ const tabId = BigInt(log.tabId);
319
+ const rb = new ReportBuilder(`receipts of tab ${tabId} (${log.calls.length} calls)`);
320
+ const bureau = parseContractAddress(log.bureau);
321
+ rb.check("log names this network", bytesEqual(fromHex(log.genesis, 32), genesis));
322
+ if (ctx !== null) rb.check("log names this bureau", contractAddressEqual(bureau, ctx.bureau));
323
+ const buyerKey = fromHex(log.buyerKey, 32);
324
+ const sellerKey = fromHex(log.sellerKey, 32);
325
+ const { failures, decoded, lanes, total } = checkReceiptLog(log, genesis);
326
+ rb.check("every voucher and receipt verifies", failures.length === 0, failures.length === 0 ? `${decoded.length} calls on ${lanes.size} lanes` : `${failures.length} problems`);
327
+ for (const f of failures.slice(0, MAX_LISTED)) rb.check("call", false, f);
328
+ if (failures.length > MAX_LISTED) rb.check("more problems", false, `${failures.length - MAX_LISTED} more not listed`);
329
+ rb.fact("lanes", lanes.size);
330
+ rb.fact("receipted total", ccd(total));
331
+ rb.fact("keys", ctx === null ? "taken from the log, not matched to the line and tab on chain (offline)" : "checked against the line and tab on chain (see the key checks)");
332
+ if (ctx !== null) {
333
+ const tab = await tabOf(ctx, tabId);
334
+ if (rb.check("the tab exists on chain", tab !== null) && tab !== null) {
335
+ const line = await lineOf(ctx, tab.lineId);
336
+ rb.check("buyer key is the line\u2019s pinned session key", line !== null && bytesEqual(line.sessionKey.publicKey, buyerKey));
337
+ rb.check("seller key is the tab\u2019s seller key", bytesEqual(tab.sellerKey, sellerKey));
338
+ const uncovered = tab.lanes.flatMap((rec, lane) => {
339
+ const last = lanes.get(lane)?.at(-1)?.receipt;
340
+ return rec.seq === 0n || last !== void 0 && last.seq >= rec.seq && last.chargedCumulative >= rec.chargedCumulative ? [] : [lane];
341
+ });
342
+ rb.check("every settled lane is covered by the receipts", uncovered.length === 0, uncovered.length === 0 ? `settled ${ccd(tab.settledTotal)}` : `lanes ${uncovered.join(", ")}`);
343
+ }
344
+ }
345
+ return rb.build();
346
+ }
347
+
348
+ // packages/cli/src/verify/settlement.ts
349
+ async function verifySettlement(ctx, hash2) {
350
+ const rb = new ReportBuilder(`settlement ${hash2}`);
351
+ const tx = await finalizedTx(ctx, hash2, rb, "settleTab");
352
+ if (tx === null) return rb.build();
353
+ const call = bureauCall(ctx, tx, "settleTab");
354
+ if (!rb.check("calls tab_bureau.settleTab on this bureau", call !== void 0, tx.calls.map((c) => c.receiveName).join(", ") || tx.type)) return rb.build();
355
+ if (call === void 0) return rb.build();
356
+ const params = attempt(rb, "settleTab parameter decodes", () => decodeSettleTabParams(call.parameter));
357
+ if (params === null) return rb.build();
358
+ const { close } = params;
359
+ rb.check("close names this network and bureau", bytesEqual(close.genesis, ctx.genesis) && contractAddressEqual(close.bureau, ctx.bureau));
360
+ rb.fact("tab", close.tabId);
361
+ rb.fact("cycle", close.cycle);
362
+ rb.fact("close total", ccd(close.total));
363
+ const events = attempt(rb, "bureau events decode", () => bureauEvents(ctx, tx));
364
+ const settled = events?.find((e) => e.type === "TabSettled" && e.tabId === close.tabId);
365
+ if (rb.check("logged TabSettled for the tab and cycle", settled?.type === "TabSettled" && settled.cycle === close.cycle)) {
366
+ if (settled?.type === "TabSettled") {
367
+ rb.fact("on time", settled.onTime);
368
+ rb.fact("acked", settled.acked);
369
+ }
370
+ }
371
+ const [before, after] = await Promise.all([tabOf(ctx, close.tabId, tx.parentBlock), tabOf(ctx, close.tabId, tx.blockHash)]);
372
+ if (!rb.check("the tab exists before and after", before !== null && after !== null) || before === null || after === null) return rb.build();
373
+ const due = close.total - before.settledTotal;
374
+ rb.check("attached amount = total \u2212 settled total before", call.amount === due && due > 0n, `attached ${ccd(call.amount)}, due ${ccd(due)}`);
375
+ rb.check("settled total after = close total", after.settledTotal === close.total);
376
+ const wallet = accountAddressToBase58(before.sellerWallet);
377
+ rb.fact("seller wallet (snapshot)", wallet);
378
+ rb.check("snapshot wallet unchanged by the settlement", bytesEqual(before.sellerWallet, after.sellerWallet));
379
+ const out = tx.transfers.filter((t) => contractAddressEqual(t.from, ctx.bureau));
380
+ rb.check(
381
+ "exactly the amount went to the snapshot seller wallet",
382
+ out.length === 1 && out[0]?.to === wallet && out[0].amount === call.amount,
383
+ out.map((t) => `${ccd(t.amount)} \u2192 ${t.to}`).join("; ") || "no transfer"
384
+ );
385
+ const balance = await ctx.chain.instanceBalance(ctx.bureau, tx.blockHash);
386
+ rb.check("bureau holds 0 CCD after the block", balance === 0n, ccd(balance));
387
+ const line = await lineOf(ctx, before.lineId, tx.blockHash);
388
+ if (rb.check("the tab\u2019s line exists", line !== null) && line !== null) {
389
+ rb.check("close signed by the line\u2019s pinned session key", ed25519Verify(params.buyerSig, encodeCloseVoucherV1(close), line.sessionKey.publicKey));
390
+ const payers = [line.owner, ...line.buyerWallet === null ? [] : [line.buyerWallet]].map(accountAddressToBase58);
391
+ rb.check("sent by the buyer wallet or the line owner", payers.includes(tx.sender), tx.sender);
392
+ }
393
+ const seller = decodeSellerOfResult(await ctx.chain.bureauView("sellerOf", encodeSellerOfParams(before.sellerToken), tx.parentBlock));
394
+ const ackKey = seller !== null && bytesEqual(seller.owner, before.sellerOwner) ? seller.sessionKey.publicKey : before.sellerKey;
395
+ const ackValid = params.ackSig !== null && ed25519Verify(params.ackSig, encodeCloseAckV1(closeAckFor(close)), ackKey);
396
+ if (settled?.type === "TabSettled") rb.check("TabSettled.acked matches the seller\u2019s CloseAck signature", settled.acked === ackValid);
397
+ rb.fact("sender", tx.sender);
398
+ rb.fact("sponsor", tx.sponsor);
399
+ rb.fact("fee", ccd(tx.costMicroCcd));
400
+ return rb.build();
401
+ }
402
+
403
+ // packages/cli/src/verify/tab.ts
404
+ async function verifyTab(ctx, tabId, openTx, settlements = []) {
405
+ const rb = new ReportBuilder(`tab ${tabId}`);
406
+ const tx = await finalizedTx(ctx, openTx, rb, "openTab");
407
+ if (tx !== null) {
408
+ const call = bureauCall(ctx, tx, "openTab");
409
+ const params = call === void 0 ? null : attempt(rb, "openTab parameter decodes", () => decodeOpenTabParams(call.parameter));
410
+ rb.check("calls tab_bureau.openTab on this bureau", call !== void 0);
411
+ if (params !== null) {
412
+ const a = params.agreement;
413
+ const events = attempt(rb, "bureau events decode", () => bureauEvents(ctx, tx));
414
+ const opened = events?.find((e) => e.type === "TabOpened");
415
+ rb.check(
416
+ "logged TabOpened for this tab, line and seller",
417
+ opened?.type === "TabOpened" && opened.tabId === tabId && opened.lineId === a.lineId && opened.sellerToken === a.sellerToken
418
+ );
419
+ rb.check("agreement names this network and bureau", bytesEqual(a.genesis, ctx.genesis) && contractAddressEqual(a.bureau, ctx.bureau));
420
+ const [tab, line] = await Promise.all([tabOf(ctx, tabId, tx.blockHash), lineOf(ctx, a.lineId, tx.blockHash)]);
421
+ const signed = encodeTabAgreementV1(a);
422
+ if (rb.check("the tab and its line exist", tab !== null && line !== null) && tab !== null && line !== null) {
423
+ rb.check("agreement hash = the tab\u2019s agreement_hash", bytesEqual(agreementHash(a), tab.agreementHash));
424
+ rb.check("buyer signed with the line\u2019s pinned session key", ed25519Verify(params.buyerSig, signed, line.sessionKey.publicKey));
425
+ rb.check("seller signed with the key the tab snapshotted", ed25519Verify(params.sellerSig, signed, tab.sellerKey));
426
+ rb.check(
427
+ "stored tab matches the agreement",
428
+ tab.lineId === a.lineId && tab.sellerToken === a.sellerToken && bytesEqual(tab.sellerWallet, a.sellerWallet) && tab.limit === a.limit && tab.cycleMs === a.cycleMs && tab.graceMs === a.graceMs && tab.maxLanes === a.maxLanes
429
+ );
430
+ rb.fact("line", a.lineId);
431
+ rb.fact("seller token", a.sellerToken);
432
+ rb.fact("seller wallet (snapshot)", accountAddressToBase58(a.sellerWallet));
433
+ rb.fact("limit", ccd(a.limit));
434
+ rb.fact("cycle", `${a.cycleMs} ms, grace ${a.graceMs} ms, ${a.maxLanes} lanes`);
435
+ rb.fact("agreement hash", toHex(tab.agreementHash));
436
+ }
437
+ }
438
+ }
439
+ const now = await tabOf(ctx, tabId);
440
+ if (now !== null) {
441
+ rb.fact("status now", now.status);
442
+ rb.fact("settled total now", ccd(now.settledTotal));
443
+ }
444
+ for (const s of settlements) {
445
+ const report = await verifySettlement(ctx, s);
446
+ rb.check(`settlement ${s.slice(0, 12)}\u2026 is for this tab`, report.facts.tab === tabId.toString());
447
+ rb.child(report);
448
+ }
449
+ return rb.build();
450
+ }
451
+
452
+ // packages/cli/src/verify/tx.ts
453
+ import { VerificationAuditRecordV1 as VerificationAuditRecordV12, VerificationRequestV1 as VerificationRequestV12 } from "@concordium/web-sdk";
454
+ function inferKind(tx) {
455
+ for (const { receiveName } of tx.calls) {
456
+ for (const [kind, name] of Object.entries(REGISTRY_ENTRYPOINTS)) if (name === receiveName) return kind;
457
+ const ep = receiveName.startsWith("tab_bureau.") ? receiveName.slice("tab_bureau.".length) : "";
458
+ if (BUREAU_KINDS.includes(ep)) return ep;
459
+ }
460
+ if (tx.type === "registerData" && tx.registeredData !== null) {
461
+ if (drpAnchorRoot(tx.registeredData) !== null) return "anchorDRP";
462
+ try {
463
+ VerificationRequestV12.decodeAnchor(tx.registeredData);
464
+ return "anchorVRA";
465
+ } catch {
466
+ try {
467
+ VerificationAuditRecordV12.decodeAnchor(tx.registeredData);
468
+ return "anchorVAA";
469
+ } catch {
470
+ return "other";
471
+ }
472
+ }
473
+ }
474
+ if (tx.type === "transfer" || tx.type === "transferWithMemo") return "exactPayment";
475
+ if (tx.type === "deployModule" || tx.type === "initContract") return tx.type;
476
+ return "other";
477
+ }
478
+ async function verifyDefault(ctx, tx, rb) {
479
+ const call = bureauCall(ctx, tx, "reportDefault");
480
+ const params = call === void 0 ? null : attempt(rb, "reportDefault parameter decodes", () => decodeReportDefaultParams(call.parameter));
481
+ if (params === null) return;
482
+ const events = attempt(rb, "bureau events decode", () => bureauEvents(ctx, tx));
483
+ const reported = events?.find((e) => e.type === "DefaultReported" && e.tabId === params.tabId);
484
+ rb.check(
485
+ "DefaultReported.evidence_hash = H(the reported vouchers)",
486
+ reported?.type === "DefaultReported" && bytesEqual(reported.evidenceHash, vouchersHash(params.vouchers))
487
+ );
488
+ const tab = await tabOf(ctx, params.tabId, tx.blockHash);
489
+ const line = tab === null ? null : await lineOf(ctx, tab.lineId, tx.blockHash);
490
+ if (!rb.check("the tab and its line exist", tab !== null && line !== null) || tab === null || line === null) return;
491
+ const start = tab.openedAt + BigInt(params.cycle) * tab.cycleMs;
492
+ const end = start + tab.cycleMs;
493
+ let proven = 0n;
494
+ params.vouchers.forEach(({ voucher, sig }, i) => {
495
+ rb.check(
496
+ `voucher ${i + 1} (lane ${voucher.lane}, seq ${voucher.seq}) signed by the line\u2019s session key`,
497
+ voucher.tabId === params.tabId && bytesEqual(voucher.genesis, ctx.genesis) && ed25519Verify(sig, encodeVoucherV1(voucher), line.sessionKey.publicKey)
498
+ );
499
+ rb.check(`voucher ${i + 1} belongs to the reported cycle`, voucher.issuedAt >= start && voucher.issuedAt < end);
500
+ proven += voucher.ackedCumulative;
501
+ });
502
+ rb.fact("tab", params.tabId);
503
+ rb.fact("cycle", params.cycle);
504
+ rb.fact("proven by the buyer\u2019s own vouchers", ccd(proven));
505
+ rb.fact("tab status after", tab.status);
506
+ }
507
+ async function verifyKind(ctx, tx, kind, rb) {
508
+ const registryName = REGISTRY_ENTRYPOINTS[kind];
509
+ if (registryName !== void 0) {
510
+ const isCis8 = kind === "registerExternalKey";
511
+ const contract2 = isCis8 ? TESTNET_CIS8 : TESTNET_CIS8004;
512
+ const call = registryCall(tx, kind);
513
+ if (!rb.check(`calls ${registryName} on <${contract2.index},${contract2.subindex}>`, call !== void 0) || call === void 0) return;
514
+ if (isCis8) {
515
+ const ev = call.events.map((e) => attempt(rb, "CIS-8 event decodes", () => decodeCis8Event(e))).find((e) => e?.type === "ExternalKeyRegistered");
516
+ rb.check("logged ExternalKeyRegistered for the sender", ev?.type === "ExternalKeyRegistered" && accountAddressToBase58(ev.owner) === tx.sender);
517
+ if (ev?.type === "ExternalKeyRegistered") rb.fact("key", `${ev.externalKey.namespace} ${toHex(ev.externalKey.publicKey)}`);
518
+ return;
519
+ }
520
+ const events = call.events.map((e) => {
521
+ try {
522
+ return decodeCis8004Event(e);
523
+ } catch {
524
+ return null;
525
+ }
526
+ });
527
+ if (kind === "registerAgent") {
528
+ const ev = events.find((e) => e?.type === "Registered");
529
+ if (rb.check("logged Registered to the sender", ev?.type === "Registered" && accountAddressToBase58(ev.ownerAccount) === tx.sender) && ev?.type === "Registered") {
530
+ rb.fact("token", ev.tokenId);
531
+ rb.fact("badge", agentBadge(ev.tokenId));
532
+ }
533
+ } else if (kind === "setAgentWallet") {
534
+ const ev = events.find((e) => e?.type === "AgentWalletSet");
535
+ rb.check("logged AgentWalletSet", ev?.type === "AgentWalletSet" && ev.newWallet !== null);
536
+ if (ev?.type === "AgentWalletSet" && ev.newWallet !== null) {
537
+ rb.check("agent wallet differs from the owner (sender)", !bytesEqual(ev.newWallet, accountAddressFromBase58(tx.sender)));
538
+ rb.fact("agent wallet", accountAddressToBase58(ev.newWallet));
539
+ }
540
+ } else {
541
+ const ev = events.find((e) => e?.type === "URIUpdated");
542
+ rb.check("logged URIUpdated", ev?.type === "URIUpdated");
543
+ if (ev?.type === "URIUpdated") rb.fact("agent_uri", ev.agentUri);
544
+ }
545
+ return;
546
+ }
547
+ if (BUREAU_KINDS.includes(kind)) {
548
+ if (!rb.check(`calls tab_bureau.${kind} on this bureau`, bureauCall(ctx, tx, kind) !== void 0)) return;
549
+ const events = attempt(rb, "bureau events decode", () => bureauEvents(ctx, tx)) ?? [];
550
+ if (kind === "settleTab") rb.child(await verifySettlement(ctx, tx.hash));
551
+ if (kind === "openLine") {
552
+ const opened = events.find((e) => e.type === "LineOpened");
553
+ if (rb.check("logged LineOpened", opened?.type === "LineOpened") && opened?.type === "LineOpened") rb.child(await verifyLine(ctx, opened.lineId, tx.hash));
554
+ }
555
+ if (kind === "openTab") {
556
+ const opened = events.find((e) => e.type === "TabOpened");
557
+ if (rb.check("logged TabOpened", opened?.type === "TabOpened") && opened?.type === "TabOpened") rb.child(await verifyTab(ctx, opened.tabId, tx.hash));
558
+ }
559
+ if (kind === "registerSeller") rb.check("logged SellerRegistered", events.some((e) => e.type === "SellerRegistered"));
560
+ if (kind === "reportDefault") await verifyDefault(ctx, tx, rb);
561
+ return;
562
+ }
563
+ if (kind === "anchorVRA" || kind === "anchorVAA") {
564
+ const data = tx.registeredData;
565
+ rb.check("is a RegisterData", tx.type === "registerData" && data !== null, tx.type);
566
+ rb.check("sent by the verifier\u2019s anchor account", tx.sender === ctx.anchorAccount, tx.sender);
567
+ if (data !== null) {
568
+ const decoded = attempt(
569
+ rb,
570
+ `${kind === "anchorVRA" ? "CCDVRA" : "CCDVAA"} payload decodes`,
571
+ () => kind === "anchorVRA" ? VerificationRequestV12.decodeAnchor(data) : VerificationAuditRecordV12.decodeAnchor(data)
572
+ );
573
+ if (decoded !== null) rb.fact("anchor hash", toHex(decoded.hash));
574
+ }
575
+ return;
576
+ }
577
+ if (kind === "anchorDRP") {
578
+ verifyDrpAnchor(ctx, tx, rb);
579
+ return;
580
+ }
581
+ if (kind === "exactPayment") {
582
+ rb.check("is a CCD transfer", tx.accountTransfer !== null, tx.type);
583
+ if (tx.accountTransfer !== null) rb.fact("paid", `${ccd(tx.accountTransfer.amount)} \u2192 ${tx.accountTransfer.to}`);
584
+ return;
585
+ }
586
+ if (kind === "deployModule" || kind === "initContract") rb.check(`is a ${kind}`, tx.type === kind, tx.type);
587
+ }
588
+ async function verifyTx(ctx, hash2, entry) {
589
+ return verifyTxWith(ctx, hash2, entry, verifyKind, inferKind);
590
+ }
591
+
592
+ // packages/cli/src/verify/demo.ts
593
+ async function verifyDemo(ctx, bundle, opts = {}) {
594
+ const now = opts.now ?? Date.now;
595
+ const deadlineMs = opts.deadlineMs ?? 6e4;
596
+ const started = opts.startedAt ?? now();
597
+ const rb = new ReportBuilder(`evidence bundle ${bundle.run.id}${bundle.run.label === void 0 ? "" : ` (${bundle.run.label})`}`);
598
+ rb.check("bundle names this bureau", contractAddressEqual(parseContractAddress(bundle.bureau), ctx.bureau), bundle.bureau);
599
+ rb.fact("generated", bundle.generatedAt);
600
+ if (bundle.run.ci === true) rb.fact("run", "CI run (flagged CI attestor; excluded from metrics)");
601
+ const tasks = [
602
+ ...bundle.transactions.map((t) => ({ subject: `tx ${t.hash}`, run: () => verifyTx(ctx, t.hash, t) })),
603
+ ...bundle.lines.map((l) => ({ subject: `line ${l.lineId}`, run: () => verifyLine(ctx, BigInt(l.lineId), l.openTx) })),
604
+ ...bundle.tabs.map((t) => ({ subject: `tab ${t.tabId}`, run: () => verifyTab(ctx, BigInt(t.tabId), t.openTx, t.settlements) })),
605
+ ...bundle.receipts.map((r) => ({ subject: `receipts of tab ${r.tabId}`, run: () => verifyReceipts(r, ctx, ctx.genesis) }))
606
+ ];
607
+ const results = new Array(tasks.length);
608
+ let next = 0;
609
+ let timedOut = 0;
610
+ const worker = async () => {
611
+ for (; ; ) {
612
+ const i = next++;
613
+ const task = tasks[i];
614
+ if (task === void 0) return;
615
+ if (now() - started > deadlineMs) {
616
+ timedOut++;
617
+ results[i] = errorReport(task.subject, `not checked: over the ${deadlineMs / 1e3} s limit`);
618
+ continue;
619
+ }
620
+ try {
621
+ results[i] = await task.run();
622
+ } catch (err) {
623
+ results[i] = errorReport(task.subject, err instanceof Error ? err.message : String(err));
624
+ }
625
+ }
626
+ };
627
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(opts.concurrency ?? 8, tasks.length)) }, worker));
628
+ for (const r of results) rb.child(r);
629
+ const elapsed = now() - started;
630
+ rb.check("bundle has something to check", tasks.length > 0, `${tasks.length} items`);
631
+ rb.check(`checked in under ${deadlineMs / 1e3} s`, timedOut === 0 && elapsed <= deadlineMs, `${(elapsed / 1e3).toFixed(1)} s`);
632
+ rb.fact("passed", `${results.filter((r) => r.ok).length} of ${results.length}`);
633
+ const retries = ctx.chain.retries?.() ?? 0;
634
+ if (retries > 0) rb.fact("node reads retried", retries);
635
+ return rb.build();
636
+ }
637
+
638
+ // packages/cli/src/commands/verify.ts
639
+ var ID_RE = /^(0|[1-9][0-9]{0,19})$/;
640
+ function id(text, what) {
641
+ if (text === void 0 || !ID_RE.test(text) || BigInt(text) >= 1n << 64n) throw new CliError("usage", `${what} must be a u64 decimal id`);
642
+ return BigInt(text);
643
+ }
644
+ function hash(text, what) {
645
+ const h = text?.toLowerCase();
646
+ if (h === void 0 || !HASH_RE.test(h)) throw new CliError("usage", `${what} must be a 64-hex-digit transaction hash`);
647
+ return h;
648
+ }
649
+ async function context(env, opts = {}) {
650
+ const chain = await env.verifyChain(opts);
651
+ const genesis = await chain.genesis();
652
+ if (genesis !== TESTNET_GENESIS_HEX) throw new CliError("wrong_network", `the node is not testnet (genesis ${genesis})`);
653
+ return { chain, bureau: env.config.bureau, anchorAccount: env.config.anchorAccount, drpAnchorAccounts: env.config.drpAnchorAccounts, genesis: fromHex(TESTNET_GENESIS_HEX, 32) };
654
+ }
655
+ async function load(env, source) {
656
+ if (/^https?:\/\//.test(source)) {
657
+ const u = new URL(source);
658
+ if (u.protocol !== "https:") throw new CliError("usage", "bundle URLs must be https");
659
+ const res = await env.io.fetch(u, { redirect: "follow", signal: AbortSignal.timeout(2e4) });
660
+ if (!res.ok) throw new CliError("bad_bundle", `${source}: HTTP ${res.status}`);
661
+ const declared = Number(res.headers.get("content-length") ?? "0");
662
+ if (declared > MAX_BUNDLE_BYTES) throw new CliError("bad_bundle", `${source} is larger than ${MAX_BUNDLE_BYTES} bytes`);
663
+ const body = new Uint8Array(await res.arrayBuffer());
664
+ if (body.length > MAX_BUNDLE_BYTES) throw new CliError("bad_bundle", `${source} is larger than ${MAX_BUNDLE_BYTES} bytes`);
665
+ return body;
666
+ }
667
+ return env.io.readFile(source);
668
+ }
669
+ async function locate(env, kind, which) {
670
+ const indexer = env.indexer();
671
+ if (indexer === null) throw new CliError("usage", `pass --tx <hash of the open${kind === "lines" ? "Line" : "Tab"} transaction>, or set INDEXER_URL to look it up`);
672
+ const events = await indexer.events(kind, which);
673
+ const open = events.find((e) => e.kind === (kind === "lines" ? "LineOpened" : "TabOpened"));
674
+ if (open === void 0) throw new CliError("not_found", `the indexer has no open event for ${kind === "lines" ? "line" : "tab"} ${which}`);
675
+ return { openTx: open.txHash, settlements: events.filter((e) => e.kind === "TabSettled").map((e) => e.txHash) };
676
+ }
677
+ async function runVerify(env, a) {
678
+ switch (a.sub) {
679
+ // Arguments are checked before the node is contacted, so a malformed one is a usage error even
680
+ // when the node is unreachable.
681
+ case "tx": {
682
+ const txHash = hash(a.target, "the transaction");
683
+ return verifyTx(await context(env), txHash);
684
+ }
685
+ case "settlement": {
686
+ const txHash = hash(a.target, "the settlement transaction");
687
+ return verifySettlement(await context(env), txHash);
688
+ }
689
+ case "line": {
690
+ const lineId = id(a.target, "the line");
691
+ const openTx = a.tx === void 0 ? (await locate(env, "lines", lineId)).openTx : hash(a.tx, "--tx");
692
+ return verifyLine(await context(env), lineId, openTx);
693
+ }
694
+ case "tab": {
695
+ const tabId = id(a.target, "the tab");
696
+ const found = a.tx === void 0 ? await locate(env, "tabs", tabId) : { openTx: hash(a.tx, "--tx"), settlements: [] };
697
+ const settlements = a.settlements.length > 0 ? a.settlements.map((s) => hash(s, "--settlement")) : found.settlements;
698
+ return verifyTab(await context(env), tabId, found.openTx, settlements);
699
+ }
700
+ case "receipts": {
701
+ if (a.target === void 0) throw new CliError("usage", "verify receipts <file>");
702
+ const log = parseReceiptLog(await load(env, a.target));
703
+ return verifyReceipts(log, a.offline ? null : await context(env), fromHex(TESTNET_GENESIS_HEX, 32));
704
+ }
705
+ case "demo": {
706
+ const startedAt = env.io.now();
707
+ const deadlineMs = a.timeoutS * 1e3;
708
+ const source = a.bundle ?? (env.config.publicBaseUrl === null ? void 0 : `${env.config.publicBaseUrl}/evidence/latest.json`);
709
+ if (source === void 0) throw new CliError("usage", "pass --bundle <path-or-url>, or set PUBLIC_BASE_URL to read <PUBLIC_BASE_URL>/evidence/latest.json");
710
+ const bundle = parseEvidenceBundle(await load(env, source));
711
+ return verifyDemo(await context(env, { deadlineAt: startedAt + deadlineMs }), bundle, { deadlineMs, startedAt, now: () => env.io.now() });
712
+ }
713
+ default:
714
+ throw new CliError("usage", "verify tx <hash> | tab <id> | line <id> | settlement <txHash> | receipts <file> | demo [--bundle <path-or-url>]");
715
+ }
716
+ }
717
+ export {
718
+ runVerify
719
+ };