ckb-cycle-tools 0.0.0-stage → 1.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.
- package/CHANGELOG.md +180 -0
- package/LICENSE +21 -0
- package/README.md +652 -3
- package/dist/analyze.d.ts +50 -0
- package/dist/analyze.js +95 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +405 -0
- package/dist/debugger.d.ts +28 -0
- package/dist/debugger.js +56 -0
- package/dist/diff.d.ts +218 -0
- package/dist/diff.js +441 -0
- package/dist/elf.d.ts +18 -0
- package/dist/elf.js +209 -0
- package/dist/flame.d.ts +65 -0
- package/dist/flame.js +199 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +11 -0
- package/dist/mock.d.ts +109 -0
- package/dist/mock.js +197 -0
- package/dist/profile.d.ts +72 -0
- package/dist/profile.js +144 -0
- package/dist/replay.d.ts +167 -0
- package/dist/replay.js +296 -0
- package/dist/report.d.ts +90 -0
- package/dist/report.js +445 -0
- package/dist/scan.d.ts +46 -0
- package/dist/scan.js +122 -0
- package/dist/substitute.d.ts +48 -0
- package/dist/substitute.js +143 -0
- package/dist/wasm.d.ts +22 -0
- package/dist/wasm.js +58 -0
- package/package.json +75 -6
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ccc } from "@ckb-ccc/core";
|
|
2
|
+
/**
|
|
3
|
+
* What ran when a transaction was verified, and what it cost.
|
|
4
|
+
*
|
|
5
|
+
* CKB executes each script once per *script group*, not once per cell:
|
|
6
|
+
* - every input lock runs, grouped by lock script hash;
|
|
7
|
+
* - every type script runs, grouped by type script hash across inputs AND outputs;
|
|
8
|
+
* - output locks do not run at all.
|
|
9
|
+
*
|
|
10
|
+
* The total cycle count comes from the node. A per-group cycle breakdown needs
|
|
11
|
+
* ckb-debugger, which is what the CLI is for.
|
|
12
|
+
*/
|
|
13
|
+
export interface ScriptGroup {
|
|
14
|
+
role: "lock" | "type";
|
|
15
|
+
scriptHash: ccc.Hex;
|
|
16
|
+
codeHash: ccc.Hex;
|
|
17
|
+
hashType: ccc.HashType;
|
|
18
|
+
args: ccc.Hex;
|
|
19
|
+
/** Human name for well-known scripts (e.g. "Secp256k1Blake160"), if recognised. */
|
|
20
|
+
name?: string;
|
|
21
|
+
/** Input indices in this group. */
|
|
22
|
+
inputs: number[];
|
|
23
|
+
/** Output indices in this group (type scripts only). */
|
|
24
|
+
outputs: number[];
|
|
25
|
+
}
|
|
26
|
+
export interface TxAnalysis {
|
|
27
|
+
hash: ccc.Hex;
|
|
28
|
+
status: string;
|
|
29
|
+
/** Total verification cycles as reported by the node; absent if unknown. */
|
|
30
|
+
cycles?: bigint;
|
|
31
|
+
blockNumber?: bigint;
|
|
32
|
+
inputCount: number;
|
|
33
|
+
outputCount: number;
|
|
34
|
+
/** True for a cellbase (block reward) transaction, which runs no input scripts. */
|
|
35
|
+
cellbase: boolean;
|
|
36
|
+
groups: ScriptGroup[];
|
|
37
|
+
}
|
|
38
|
+
type CellScripts = {
|
|
39
|
+
lock: ccc.ScriptLike;
|
|
40
|
+
type?: ccc.ScriptLike | null;
|
|
41
|
+
};
|
|
42
|
+
/** Pure grouping step — no network. Group order follows first appearance. */
|
|
43
|
+
export declare function groupScripts(inputs: CellScripts[], outputs: CellScripts[]): ScriptGroup[];
|
|
44
|
+
/** codeHash:hashType → KnownScript name, for the client's network. */
|
|
45
|
+
export declare function knownScriptNames(client: ccc.Client): Promise<Map<string, string>>;
|
|
46
|
+
export declare class TransactionNotFoundError extends Error {
|
|
47
|
+
constructor(hash: string);
|
|
48
|
+
}
|
|
49
|
+
export declare function analyzeTransaction(client: ccc.Client, hash: ccc.HexLike): Promise<TxAnalysis>;
|
|
50
|
+
export {};
|
package/dist/analyze.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { ccc } from "@ckb-ccc/core";
|
|
2
|
+
/** Pure grouping step — no network. Group order follows first appearance. */
|
|
3
|
+
export function groupScripts(inputs, outputs) {
|
|
4
|
+
const groups = new Map();
|
|
5
|
+
const add = (role, like, side, index) => {
|
|
6
|
+
const script = ccc.Script.from(like);
|
|
7
|
+
const scriptHash = script.hash();
|
|
8
|
+
const key = `${role}:${scriptHash}`;
|
|
9
|
+
let g = groups.get(key);
|
|
10
|
+
if (!g) {
|
|
11
|
+
g = {
|
|
12
|
+
role,
|
|
13
|
+
scriptHash,
|
|
14
|
+
codeHash: script.codeHash,
|
|
15
|
+
hashType: script.hashType,
|
|
16
|
+
args: script.args,
|
|
17
|
+
inputs: [],
|
|
18
|
+
outputs: [],
|
|
19
|
+
};
|
|
20
|
+
groups.set(key, g);
|
|
21
|
+
}
|
|
22
|
+
g[side].push(index);
|
|
23
|
+
};
|
|
24
|
+
inputs.forEach((cell, i) => {
|
|
25
|
+
add("lock", cell.lock, "inputs", i);
|
|
26
|
+
if (cell.type)
|
|
27
|
+
add("type", cell.type, "inputs", i);
|
|
28
|
+
});
|
|
29
|
+
outputs.forEach((cell, i) => {
|
|
30
|
+
if (cell.type)
|
|
31
|
+
add("type", cell.type, "outputs", i);
|
|
32
|
+
});
|
|
33
|
+
return [...groups.values()];
|
|
34
|
+
}
|
|
35
|
+
const scriptKey = (codeHash, hashType) => `${codeHash}:${hashType}`;
|
|
36
|
+
/** codeHash:hashType → KnownScript name, for the client's network. */
|
|
37
|
+
export async function knownScriptNames(client) {
|
|
38
|
+
const names = new Map();
|
|
39
|
+
await Promise.all(Object.values(ccc.KnownScript).map(async (name) => {
|
|
40
|
+
try {
|
|
41
|
+
const info = await client.getKnownScript(name);
|
|
42
|
+
names.set(scriptKey(info.codeHash, info.hashType), name);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// Not deployed on this network.
|
|
46
|
+
}
|
|
47
|
+
}));
|
|
48
|
+
return names;
|
|
49
|
+
}
|
|
50
|
+
export class TransactionNotFoundError extends Error {
|
|
51
|
+
constructor(hash) {
|
|
52
|
+
super(`transaction not found: ${hash}`);
|
|
53
|
+
this.name = "TransactionNotFoundError";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export async function analyzeTransaction(client, hash) {
|
|
57
|
+
const txHash = ccc.hexFrom(hash);
|
|
58
|
+
const res = await client.getTransaction(txHash);
|
|
59
|
+
if (!res?.transaction)
|
|
60
|
+
throw new TransactionNotFoundError(txHash);
|
|
61
|
+
const tx = res.transaction;
|
|
62
|
+
const cellbase = tx.inputs.length === 1 &&
|
|
63
|
+
tx.inputs[0].previousOutput.txHash === "0x" + "00".repeat(32) &&
|
|
64
|
+
tx.inputs[0].previousOutput.index === ccc.numFrom("0xffffffff");
|
|
65
|
+
const inputCells = cellbase
|
|
66
|
+
? []
|
|
67
|
+
: await Promise.all(tx.inputs.map(async (input) => {
|
|
68
|
+
const cell = await client.getCell(input.previousOutput);
|
|
69
|
+
if (!cell)
|
|
70
|
+
throw new Error(`input cell not found: ${input.previousOutput.txHash}`);
|
|
71
|
+
return cell.cellOutput;
|
|
72
|
+
}));
|
|
73
|
+
const [groups, names] = await Promise.all([
|
|
74
|
+
Promise.resolve(groupScripts(inputCells, tx.outputs)),
|
|
75
|
+
knownScriptNames(client),
|
|
76
|
+
]);
|
|
77
|
+
for (const g of groups) {
|
|
78
|
+
const name = names.get(scriptKey(g.codeHash, g.hashType));
|
|
79
|
+
if (name)
|
|
80
|
+
g.name = name;
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
hash: txHash,
|
|
84
|
+
status: res.status,
|
|
85
|
+
// Some public nodes report 0x0 for older blocks: unknown, not zero (only a cellbase costs 0).
|
|
86
|
+
...(res.cycles !== undefined &&
|
|
87
|
+
res.cycles !== null &&
|
|
88
|
+
(ccc.numFrom(res.cycles) > 0n || cellbase) && { cycles: ccc.numFrom(res.cycles) }),
|
|
89
|
+
...(res.blockNumber !== undefined && res.blockNumber !== null && { blockNumber: ccc.numFrom(res.blockNumber) }),
|
|
90
|
+
inputCount: tx.inputs.length,
|
|
91
|
+
outputCount: tx.outputs.length,
|
|
92
|
+
cellbase,
|
|
93
|
+
groups,
|
|
94
|
+
};
|
|
95
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { diffFailed, diffReports, formatMarkdown, formatText, termLine, termLines } from "./diff.js";
|
|
6
|
+
import { buildMockTransaction, httpRpc, mockFromTransaction } from "./mock.js";
|
|
7
|
+
import { flameTree, foldedTotal, formatFolded, functionCosts, renderFlameSvg } from "./flame.js";
|
|
8
|
+
import { flameTransaction, parseNames, profileTransaction, readTransactionJson } from "./profile.js";
|
|
9
|
+
import { PUBLIC_RPC } from "./replay.js";
|
|
10
|
+
import { formatReport, runReport } from "./report.js";
|
|
11
|
+
import { formatScan, scanTestMocks } from "./scan.js";
|
|
12
|
+
const USAGE = `usage: ckb-cycles <tx-hash> [--mainnet] [--rpc <url>] [--timeout <s>] [--debugger <path>]
|
|
13
|
+
[--json] [--name <code-hash>[:<hash-type>]=<label> ...]
|
|
14
|
+
ckb-cycles --file <tx.json> [same options]
|
|
15
|
+
ckb-cycles report <cycles.json> [--json <out.json>] [--binaries-from <dir>]
|
|
16
|
+
[--root <dir> ...] [--rpc <url>] [--timeout <s>] [--debugger <path>]
|
|
17
|
+
ckb-cycles diff <base.json> <head.json> [--markdown] [--fail-above <percent>]
|
|
18
|
+
[--fail-on-result-change] [--allow-removed] [--title <s>]
|
|
19
|
+
[--base-label <s>] [--head-label <s>]
|
|
20
|
+
ckb-cycles mock <tx-hash> | --file <tx.json> [-o <mock.json>] [--mainnet] [--rpc <url>]
|
|
21
|
+
[--timeout <s>]
|
|
22
|
+
ckb-cycles scan <mocks-dir> [--binaries <dir>] [-o <cycles.json>] [--functions]
|
|
23
|
+
ckb-cycles flame <tx-hash> | --file <tx.json> [-o <dir>] [--script <selector> ...]
|
|
24
|
+
[--bin <code-hash>=<elf> ...] [--top <n>] [--mainnet] [--rpc <url>] [--debugger <path>]
|
|
25
|
+
|
|
26
|
+
Replays a CKB transaction in ckb-debugger, one run per script group, and prints
|
|
27
|
+
the cycles each group cost.
|
|
28
|
+
|
|
29
|
+
<tx-hash> a committed transaction; the sum is checked against the node
|
|
30
|
+
--file a transaction that is not on chain: one about to be sent, or one
|
|
31
|
+
the node rejected. Shows which script refuses it and why. JSON in
|
|
32
|
+
the node's RPC shape, a get_transaction result, or ccc.stringify(tx)
|
|
33
|
+
--rpc the node to ask. Its chain and hardfork epochs (get_consensus)
|
|
34
|
+
decide the CKB-VM version, whatever the flags say; --mainnet with
|
|
35
|
+
a node that serves another chain stops with an error
|
|
36
|
+
--timeout seconds to wait for each RPC answer (default 30)
|
|
37
|
+
--name a label for your own script, shown instead of its code hash;
|
|
38
|
+
repeat for several. Without :<hash-type> it applies to all of them
|
|
39
|
+
|
|
40
|
+
Exit codes: 0 every script accepts (and the sum matches the node's)
|
|
41
|
+
1 a script rejects, or the sum differs from the node's
|
|
42
|
+
2 usage or environment error: bad arguments, node unreachable,
|
|
43
|
+
transaction not found, ckb-debugger missing or unreadable output
|
|
44
|
+
|
|
45
|
+
report runs every scenario in a cycles.json (see README) and records each
|
|
46
|
+
script group's result and cycles; --json writes them for diff.
|
|
47
|
+
--binaries-from <dir> reads the binaries from another checkout
|
|
48
|
+
(the PR's base). A binary with "symbols" in a scenario with
|
|
49
|
+
"functions" also records the group's costliest functions.
|
|
50
|
+
--root <dir> (repeatable) refuses any file the config names
|
|
51
|
+
outside those directories, symlinks resolved: for CI, where
|
|
52
|
+
the cycles.json comes from a pull request;
|
|
53
|
+
its "rpc" is then ignored (--rpc still applies)
|
|
54
|
+
Exits 2 if a scenario could not run, or a binary matched no
|
|
55
|
+
cell dep in any scenario (both also in the JSON's "errors"):
|
|
56
|
+
a rejection is a result, not an error. A binary missing from
|
|
57
|
+
--binaries-from is left as the mock has it: only the groups
|
|
58
|
+
whose code it is are marked, and not compared
|
|
59
|
+
diff compares two reports group by group: Δ cycles, Δ%, and any group
|
|
60
|
+
whose result changed (ok → exit 12, or back). --fail-above exits 1
|
|
61
|
+
when a group grows by more than that percentage (a new group
|
|
62
|
+
has no base, so no percentage: it is never over the threshold),
|
|
63
|
+
--fail-on-result-change when a result changed, including a new
|
|
64
|
+
group that does not accept, or a group the VM stopped (also
|
|
65
|
+
over any --fail-above). A scenario the head could not run
|
|
66
|
+
always exits 1. With either flag set, so does anything left
|
|
67
|
+
unchecked: a scenario the base could not run, an error in
|
|
68
|
+
either report, a base group with nothing in the head to
|
|
69
|
+
compare with (removed, renamed, moved, or its binary not built
|
|
70
|
+
on the base); --allow-removed accepts the last
|
|
71
|
+
mock saves a transaction as a ckb-debugger mock transaction, every cell
|
|
72
|
+
it touches included, so a scenario can replay it with no node
|
|
73
|
+
scan writes a cycles.json from the mock transactions a test suite wrote
|
|
74
|
+
(ckb-testtool with CKB_CYCLES_MOCKS set, see integrations/ckb-testtool):
|
|
75
|
+
one scenario per file, and each file in --binaries (default
|
|
76
|
+
build/release) that a test deployed, matched by its data hash, with
|
|
77
|
+
<name>.debug as its symbols build. --functions records each group's
|
|
78
|
+
costliest functions. -o defaults to cycles.json
|
|
79
|
+
flame where inside each script the cycles go: ckb-debugger's flamegraph
|
|
80
|
+
mode per script group. Prints the costliest functions and writes
|
|
81
|
+
<dir>/<selector>.svg and .folded (for speedscope or inferno), in
|
|
82
|
+
./flame by default. A deployed binary is usually stripped, so it is
|
|
83
|
+
one frame: --bin gives an unstripped build of the same code (its
|
|
84
|
+
cycles are checked against the deployed binary's). The profile
|
|
85
|
+
leaves out loading the binary, so it is a little under the group's
|
|
86
|
+
cycles`;
|
|
87
|
+
const fmt = (n) => n.toLocaleString("en-US");
|
|
88
|
+
const short = (h, n = 6) => (h.length > 2 * n + 2 ? `${h.slice(0, n + 2)}…${h.slice(-n)}` : h);
|
|
89
|
+
function table(p) {
|
|
90
|
+
const total = p.measuredCycles || 1n;
|
|
91
|
+
const rows = p.groups.map((g) => [
|
|
92
|
+
g.role,
|
|
93
|
+
termLine(g.name ?? short(g.codeHash)),
|
|
94
|
+
g.selector,
|
|
95
|
+
g.error ? "error" : g.result === 0 ? "ok" : `exit ${g.result}`,
|
|
96
|
+
fmt(g.cycles),
|
|
97
|
+
`${((Number(g.cycles) / Number(total)) * 100).toFixed(1)}%`,
|
|
98
|
+
]);
|
|
99
|
+
const head = ["GROUP", "SCRIPT", "RUN AT", "RESULT", "CYCLES", "SHARE"];
|
|
100
|
+
const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
101
|
+
const line = (cells) => cells.map((c, i) => (i >= 4 ? c.padStart(widths[i]) : c.padEnd(widths[i]))).join(" ");
|
|
102
|
+
const title = p.nodeCycles === undefined && p.status === "not on chain" ? "tx not on chain" : `tx ${p.hash} (${p.status})`;
|
|
103
|
+
const out = [title, "", line(head), ...rows.map(line), ""];
|
|
104
|
+
out.push(`measured (sum of groups) ${fmt(p.measuredCycles)}`);
|
|
105
|
+
if (p.nodeCycles !== undefined) {
|
|
106
|
+
const match = p.nodeCycles === p.measuredCycles;
|
|
107
|
+
out.push(`reported by node ${fmt(p.nodeCycles)} ${match ? "✓ match" : "✗ MISMATCH"}`);
|
|
108
|
+
}
|
|
109
|
+
else if (p.status === "committed") {
|
|
110
|
+
out.push("reported by node not recorded by this node (try another with --rpc)");
|
|
111
|
+
}
|
|
112
|
+
out.push(`${termLine(p.env.debugger)} · CKB-VM v${p.env.scriptVersion} for type scripts · ${p.env.network} · ${p.env.rpcUrl}`);
|
|
113
|
+
for (const g of p.groups.filter((g) => g.error))
|
|
114
|
+
out.push("", `${g.selector} stopped: ${termLine(g.error)}`);
|
|
115
|
+
for (const g of p.groups.filter((g) => g.logs.length)) {
|
|
116
|
+
out.push("", `${g.selector} logged:`, ...g.logs.map((l) => ` ${termLine(l)}`));
|
|
117
|
+
}
|
|
118
|
+
return out.join("\n");
|
|
119
|
+
}
|
|
120
|
+
/** `--timeout <seconds>` → milliseconds; usage error (exit 2) for anything but a positive number. */
|
|
121
|
+
function timeoutOf(value) {
|
|
122
|
+
if (value === undefined)
|
|
123
|
+
return {};
|
|
124
|
+
const seconds = Number(value);
|
|
125
|
+
if (!(seconds > 0))
|
|
126
|
+
throw new Error("--timeout expects a number of seconds, e.g. 30");
|
|
127
|
+
return { timeoutMs: seconds * 1000 };
|
|
128
|
+
}
|
|
129
|
+
const toJson = (v) => JSON.stringify(v, (_, x) => (typeof x === "bigint" ? x.toString() : x), 2);
|
|
130
|
+
async function reportCommand(args) {
|
|
131
|
+
const { values, positionals } = parseArgs({
|
|
132
|
+
args,
|
|
133
|
+
allowPositionals: true,
|
|
134
|
+
options: {
|
|
135
|
+
json: { type: "string" },
|
|
136
|
+
rpc: { type: "string" },
|
|
137
|
+
timeout: { type: "string" },
|
|
138
|
+
debugger: { type: "string" },
|
|
139
|
+
"binaries-from": { type: "string" },
|
|
140
|
+
root: { type: "string", multiple: true },
|
|
141
|
+
},
|
|
142
|
+
});
|
|
143
|
+
if (positionals.length !== 1) {
|
|
144
|
+
console.log(USAGE);
|
|
145
|
+
return 2;
|
|
146
|
+
}
|
|
147
|
+
const report = await runReport(positionals[0], {
|
|
148
|
+
...(values.rpc && { rpcUrl: values.rpc }),
|
|
149
|
+
...timeoutOf(values.timeout),
|
|
150
|
+
...(values.debugger && { debuggerPath: values.debugger }),
|
|
151
|
+
...(values["binaries-from"] && { binariesRoot: values["binaries-from"] }),
|
|
152
|
+
...(values.root && { roots: values.root }),
|
|
153
|
+
onScenario: (s) => console.error(`${s.error ? "✗" : "·"} ${termLine(s.name)}`),
|
|
154
|
+
});
|
|
155
|
+
const { errors, notices, ...data } = report;
|
|
156
|
+
// The errors go in the JSON too: a gated diff fails on them, so a CI step that
|
|
157
|
+
// ignores this exit code (the Action's `|| true`) still gets the verdict.
|
|
158
|
+
if (values.json)
|
|
159
|
+
await writeFile(values.json, toJson({ ...data, ...(errors.length && { errors }) }) + "\n");
|
|
160
|
+
console.log(formatReport(data));
|
|
161
|
+
for (const n of notices ?? [])
|
|
162
|
+
console.error(`warning: ${termLine(n)}`);
|
|
163
|
+
for (const e of errors)
|
|
164
|
+
console.error(`error: ${termLines(e)}`);
|
|
165
|
+
return errors.length ? 2 : 0;
|
|
166
|
+
}
|
|
167
|
+
async function readReport(path) {
|
|
168
|
+
const r = JSON.parse(await readFile(path, "utf8"));
|
|
169
|
+
if (r?.tool !== "ckb-cycles" || !Array.isArray(r.scenarios))
|
|
170
|
+
throw new Error(`${path} is not a ckb-cycles report`);
|
|
171
|
+
return r;
|
|
172
|
+
}
|
|
173
|
+
async function diffCommand(args) {
|
|
174
|
+
const { values, positionals } = parseArgs({
|
|
175
|
+
args,
|
|
176
|
+
allowPositionals: true,
|
|
177
|
+
options: {
|
|
178
|
+
markdown: { type: "boolean" },
|
|
179
|
+
"fail-above": { type: "string" },
|
|
180
|
+
"fail-on-result-change": { type: "boolean" },
|
|
181
|
+
"allow-removed": { type: "boolean" },
|
|
182
|
+
"base-label": { type: "string" },
|
|
183
|
+
"head-label": { type: "string" },
|
|
184
|
+
title: { type: "string" },
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
if (positionals.length !== 2) {
|
|
188
|
+
console.log(USAGE);
|
|
189
|
+
return 2;
|
|
190
|
+
}
|
|
191
|
+
const failAbove = values["fail-above"] === undefined ? undefined : Number(values["fail-above"]);
|
|
192
|
+
if (failAbove !== undefined && !(failAbove >= 0)) {
|
|
193
|
+
console.error("error: --fail-above expects a percentage, e.g. 5");
|
|
194
|
+
return 2;
|
|
195
|
+
}
|
|
196
|
+
const options = {
|
|
197
|
+
...(failAbove !== undefined && { failAbove }),
|
|
198
|
+
failOnResultChange: values["fail-on-result-change"],
|
|
199
|
+
allowRemoved: values["allow-removed"],
|
|
200
|
+
};
|
|
201
|
+
const diff = diffReports(await readReport(positionals[0]), await readReport(positionals[1]), options);
|
|
202
|
+
console.log(values.markdown
|
|
203
|
+
? formatMarkdown(diff, {
|
|
204
|
+
...(values.title && { title: values.title }),
|
|
205
|
+
...(values["base-label"] && { baseLabel: values["base-label"] }),
|
|
206
|
+
...(values["head-label"] && { headLabel: values["head-label"] }),
|
|
207
|
+
})
|
|
208
|
+
: formatText(diff));
|
|
209
|
+
return diffFailed(diff, options) ? 1 : 0;
|
|
210
|
+
}
|
|
211
|
+
async function mockCommand(args) {
|
|
212
|
+
const { values, positionals } = parseArgs({
|
|
213
|
+
args,
|
|
214
|
+
allowPositionals: true,
|
|
215
|
+
options: {
|
|
216
|
+
file: { type: "string" },
|
|
217
|
+
out: { type: "string", short: "o" },
|
|
218
|
+
mainnet: { type: "boolean" },
|
|
219
|
+
rpc: { type: "string" },
|
|
220
|
+
timeout: { type: "string" },
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
const [hash] = positionals;
|
|
224
|
+
if (positionals.length > 1 || !hash === !values.file || (hash && !/^0x[0-9a-fA-F]{64}$/.test(hash))) {
|
|
225
|
+
console.log(USAGE);
|
|
226
|
+
return 2;
|
|
227
|
+
}
|
|
228
|
+
const rpc = httpRpc(values.rpc ?? PUBLIC_RPC[values.mainnet ? "mainnet" : "testnet"], timeoutOf(values.timeout));
|
|
229
|
+
const mock = values.file
|
|
230
|
+
? await mockFromTransaction(rpc, readTransactionJson(await readFile(values.file, "utf8")))
|
|
231
|
+
: (await buildMockTransaction(rpc, hash)).mock;
|
|
232
|
+
if (values.out)
|
|
233
|
+
await writeFile(values.out, toJson(mock) + "\n");
|
|
234
|
+
else
|
|
235
|
+
console.log(toJson(mock));
|
|
236
|
+
return 0;
|
|
237
|
+
}
|
|
238
|
+
async function scanCommand(args) {
|
|
239
|
+
const { values, positionals } = parseArgs({
|
|
240
|
+
args,
|
|
241
|
+
allowPositionals: true,
|
|
242
|
+
options: {
|
|
243
|
+
binaries: { type: "string" },
|
|
244
|
+
out: { type: "string", short: "o" },
|
|
245
|
+
functions: { type: "boolean" },
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
if (positionals.length !== 1) {
|
|
249
|
+
console.log(USAGE);
|
|
250
|
+
return 2;
|
|
251
|
+
}
|
|
252
|
+
const binariesDir = values.binaries ?? "build/release";
|
|
253
|
+
const r = await scanTestMocks(positionals[0], {
|
|
254
|
+
binariesDir,
|
|
255
|
+
...(values.out && { out: values.out }),
|
|
256
|
+
...(values.functions && { functions: true }),
|
|
257
|
+
});
|
|
258
|
+
console.error(formatScan(r, binariesDir));
|
|
259
|
+
return 0;
|
|
260
|
+
}
|
|
261
|
+
/** `--bin 0xabc…=target/release/my-script` → flameTransaction's bins. */
|
|
262
|
+
function parseBins(flags) {
|
|
263
|
+
const bins = {};
|
|
264
|
+
for (const flag of flags) {
|
|
265
|
+
const m = /^(0x[0-9a-fA-F]{64})=(.+)$/.exec(flag);
|
|
266
|
+
if (!m)
|
|
267
|
+
throw new Error(`--bin expects <code-hash>=<path to an ELF>, got "${flag}"`);
|
|
268
|
+
bins[m[1].toLowerCase()] = m[2];
|
|
269
|
+
}
|
|
270
|
+
return bins;
|
|
271
|
+
}
|
|
272
|
+
async function flameCommand(args) {
|
|
273
|
+
const { values, positionals } = parseArgs({
|
|
274
|
+
args,
|
|
275
|
+
allowPositionals: true,
|
|
276
|
+
options: {
|
|
277
|
+
file: { type: "string" },
|
|
278
|
+
out: { type: "string", short: "o" },
|
|
279
|
+
script: { type: "string", multiple: true },
|
|
280
|
+
bin: { type: "string", multiple: true },
|
|
281
|
+
top: { type: "string" },
|
|
282
|
+
mainnet: { type: "boolean" },
|
|
283
|
+
rpc: { type: "string" },
|
|
284
|
+
timeout: { type: "string" },
|
|
285
|
+
debugger: { type: "string" },
|
|
286
|
+
name: { type: "string", multiple: true },
|
|
287
|
+
},
|
|
288
|
+
});
|
|
289
|
+
const [hash] = positionals;
|
|
290
|
+
if (positionals.length > 1 || !hash === !values.file || (hash && !/^0x[0-9a-fA-F]{64}$/.test(hash))) {
|
|
291
|
+
console.log(USAGE);
|
|
292
|
+
return 2;
|
|
293
|
+
}
|
|
294
|
+
const top = values.top === undefined ? 8 : Number(values.top);
|
|
295
|
+
if (!(Number.isInteger(top) && top > 0))
|
|
296
|
+
throw new Error("--top expects a positive whole number");
|
|
297
|
+
const target = values.file ? readTransactionJson(await readFile(values.file, "utf8")) : hash;
|
|
298
|
+
const { plan, groups, debugger: version } = await flameTransaction(target, {
|
|
299
|
+
...(values.mainnet && { network: "mainnet" }),
|
|
300
|
+
...(values.rpc && { rpcUrl: values.rpc }),
|
|
301
|
+
...timeoutOf(values.timeout),
|
|
302
|
+
...(values.debugger && { debuggerPath: values.debugger }),
|
|
303
|
+
scriptNames: parseNames(values.name ?? []),
|
|
304
|
+
bins: parseBins(values.bin ?? []),
|
|
305
|
+
...(values.script && { scripts: values.script }),
|
|
306
|
+
readFile: (path) => readFile(path, "utf8"),
|
|
307
|
+
});
|
|
308
|
+
if (!groups.length) {
|
|
309
|
+
console.error("error: no script group to profile (check --script)");
|
|
310
|
+
return 2;
|
|
311
|
+
}
|
|
312
|
+
const dir = values.out ?? "flame";
|
|
313
|
+
await mkdir(dir, { recursive: true });
|
|
314
|
+
const out = [`tx ${plan.hash} (${plan.status})`, ""];
|
|
315
|
+
let bad = false;
|
|
316
|
+
for (const g of groups) {
|
|
317
|
+
const label = termLine(g.name ?? short(g.codeHash));
|
|
318
|
+
const profiled = foldedTotal(g.folded);
|
|
319
|
+
out.push(`${g.selector} ${label} ${g.error ? "error" : g.result === 0 ? "ok" : `exit ${g.result}`} ${fmt(g.cycles)} cycles`);
|
|
320
|
+
if (g.bin) {
|
|
321
|
+
// Same cycles and the same verdict, and neither run stopped by the VM: two stopped
|
|
322
|
+
// runs both report 0 cycles, which proves nothing (review, 27 Oct).
|
|
323
|
+
const same = g.deployedCycles === g.cycles && g.deployedResult === g.result && !g.error && !g.deployedError;
|
|
324
|
+
out.push(` --bin ${termLine(g.bin)}: ${same ? "same cycles as the deployed binary" : `✗ ${fmt(g.deployedCycles ?? 0n)} cycles, result ${g.deployedError ? "vm error" : g.deployedResult} with the deployed binary: this build is not that code`}`);
|
|
325
|
+
bad ||= !same;
|
|
326
|
+
}
|
|
327
|
+
if (!g.folded.size) {
|
|
328
|
+
out.push(" no profile written (the run stopped before it could be profiled?)", "");
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
const costs = functionCosts(g.folded);
|
|
332
|
+
if (costs.length === 1)
|
|
333
|
+
out.push(" one frame: the binary has no symbols. Pass an unstripped build with --bin <code-hash>=<elf>");
|
|
334
|
+
out.push(` profiled ${fmt(profiled)} cycles (loading the binary is not profiled)`, " SELF TOTAL FUNCTION");
|
|
335
|
+
for (const c of costs.slice(0, top))
|
|
336
|
+
out.push(` ${fmt(c.self).padStart(10)} ${fmt(c.total).padStart(10)} ${termLine(c.name)}`);
|
|
337
|
+
const base = join(dir, g.selector);
|
|
338
|
+
await writeFile(`${base}.folded`, formatFolded(g.folded) + "\n");
|
|
339
|
+
await writeFile(`${base}.svg`, renderFlameSvg(flameTree(g.folded, g.selector), { title: `${g.selector} · ${label}` }));
|
|
340
|
+
out.push(` → ${base}.svg, ${base}.folded`, "");
|
|
341
|
+
}
|
|
342
|
+
out.push(`${termLine(version)} · CKB-VM v${plan.scriptVersion} for type scripts · ${plan.network} · ${plan.rpcUrl}`);
|
|
343
|
+
console.log(out.join("\n"));
|
|
344
|
+
return bad || groups.some((g) => g.result !== 0) ? 1 : 0;
|
|
345
|
+
}
|
|
346
|
+
async function main() {
|
|
347
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
348
|
+
if (command === "report")
|
|
349
|
+
return reportCommand(rest);
|
|
350
|
+
if (command === "diff")
|
|
351
|
+
return diffCommand(rest);
|
|
352
|
+
if (command === "mock")
|
|
353
|
+
return mockCommand(rest);
|
|
354
|
+
if (command === "flame")
|
|
355
|
+
return flameCommand(rest);
|
|
356
|
+
if (command === "scan")
|
|
357
|
+
return scanCommand(rest);
|
|
358
|
+
const { values, positionals } = parseArgs({
|
|
359
|
+
allowPositionals: true,
|
|
360
|
+
options: {
|
|
361
|
+
mainnet: { type: "boolean" },
|
|
362
|
+
rpc: { type: "string" },
|
|
363
|
+
timeout: { type: "string" },
|
|
364
|
+
debugger: { type: "string" },
|
|
365
|
+
json: { type: "boolean" },
|
|
366
|
+
file: { type: "string" },
|
|
367
|
+
name: { type: "string", multiple: true },
|
|
368
|
+
help: { type: "boolean", short: "h" },
|
|
369
|
+
},
|
|
370
|
+
});
|
|
371
|
+
const [hash] = positionals;
|
|
372
|
+
if (values.help || (!hash && !values.file) || (hash && values.file)) {
|
|
373
|
+
console.log(USAGE);
|
|
374
|
+
return values.help ? 0 : 2;
|
|
375
|
+
}
|
|
376
|
+
if (hash && !/^0x[0-9a-fA-F]{64}$/.test(hash)) {
|
|
377
|
+
console.error("error: expected a transaction hash: 0x followed by 64 hex characters");
|
|
378
|
+
return 2;
|
|
379
|
+
}
|
|
380
|
+
const target = values.file ? readTransactionJson(await readFile(values.file, "utf8")) : hash;
|
|
381
|
+
const p = await profileTransaction(target, {
|
|
382
|
+
// Only an explicit --mainnet is passed on, and checked against the node;
|
|
383
|
+
// without it, the node itself says which chain it serves.
|
|
384
|
+
...(values.mainnet && { network: "mainnet" }),
|
|
385
|
+
...(values.rpc && { rpcUrl: values.rpc }),
|
|
386
|
+
...timeoutOf(values.timeout),
|
|
387
|
+
...(values.debugger && { debuggerPath: values.debugger }),
|
|
388
|
+
scriptNames: parseNames(values.name ?? []),
|
|
389
|
+
});
|
|
390
|
+
if (values.json) {
|
|
391
|
+
console.log(JSON.stringify(p, (_, v) => (typeof v === "bigint" ? v.toString() : v), 2));
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
console.log(table(p));
|
|
395
|
+
}
|
|
396
|
+
const mismatch = p.nodeCycles !== undefined && p.nodeCycles !== p.measuredCycles;
|
|
397
|
+
return mismatch || p.groups.some((g) => g.result !== 0) ? 1 : 0;
|
|
398
|
+
}
|
|
399
|
+
// 1 is a verdict (a script rejects, a sum differs, a diff over its thresholds);
|
|
400
|
+
// anything thrown is the tool not getting that far: 2, so a CI job asserting a
|
|
401
|
+
// rejection with `test $? = 1` does not pass when the node is down.
|
|
402
|
+
main().then((code) => process.exit(code), (e) => {
|
|
403
|
+
console.error(`error: ${termLines(e instanceof Error ? e.message : String(e))}`);
|
|
404
|
+
process.exit(2);
|
|
405
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finds the native `ckb-debugger` executable.
|
|
3
|
+
*
|
|
4
|
+
* On Windows, offckb installs the real binary into its own data directory and
|
|
5
|
+
* puts only a `ckb-debugger.cmd` shim on PATH. A shell-less `child_process`
|
|
6
|
+
* spawn cannot resolve a bare name to a `.cmd` file, so tools that spawn
|
|
7
|
+
* `ckb-debugger` directly fail there. This resolver returns a path to the real
|
|
8
|
+
* `.exe` instead, so callers can spawn it without a shell.
|
|
9
|
+
*
|
|
10
|
+
* Order: `CKB_DEBUGGER_PATH`, then PATH (executables only, never `.cmd`), then
|
|
11
|
+
* offckb's tools directory on Windows.
|
|
12
|
+
*/
|
|
13
|
+
export interface ResolveOptions {
|
|
14
|
+
env?: NodeJS.ProcessEnv;
|
|
15
|
+
platform?: NodeJS.Platform;
|
|
16
|
+
exists?: (path: string) => boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare class DebuggerNotFoundError extends Error {
|
|
19
|
+
readonly searched: string[];
|
|
20
|
+
constructor(searched: string[]);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Checks a path given explicitly (`CKB_DEBUGGER_PATH`, `--debugger`): it must
|
|
24
|
+
* exist, and must not be a `.cmd`/`.bat` shim, which Node cannot spawn without
|
|
25
|
+
* a shell (it fails with a bare `spawn EINVAL`).
|
|
26
|
+
*/
|
|
27
|
+
export declare function checkDebuggerPath(path: string, exists?: (path: string) => boolean): string;
|
|
28
|
+
export declare function resolveDebugger(options?: ResolveOptions): string;
|
package/dist/debugger.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { delimiter, join } from "node:path";
|
|
3
|
+
export class DebuggerNotFoundError extends Error {
|
|
4
|
+
searched;
|
|
5
|
+
constructor(searched) {
|
|
6
|
+
super(`ckb-debugger not found. Set CKB_DEBUGGER_PATH (or pass --debugger), or install it with ` +
|
|
7
|
+
`\`offckb debugger\` or from the ckb-standalone-debugger releases. ` +
|
|
8
|
+
`Searched:\n ${searched.join("\n ")}`);
|
|
9
|
+
this.searched = searched;
|
|
10
|
+
this.name = "DebuggerNotFoundError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Checks a path given explicitly (`CKB_DEBUGGER_PATH`, `--debugger`): it must
|
|
15
|
+
* exist, and must not be a `.cmd`/`.bat` shim, which Node cannot spawn without
|
|
16
|
+
* a shell (it fails with a bare `spawn EINVAL`).
|
|
17
|
+
*/
|
|
18
|
+
export function checkDebuggerPath(path, exists = existsSync) {
|
|
19
|
+
if (/\.(cmd|bat)$/i.test(path)) {
|
|
20
|
+
throw new Error(`${path} is a Windows shim, which cannot be run without a shell. Point to the real ckb-debugger.exe ` +
|
|
21
|
+
`instead: offckb installs it in %LOCALAPPDATA%\\offckb-nodejs\\Data\\tools\\ckb-debugger.exe`);
|
|
22
|
+
}
|
|
23
|
+
// An explicit path that does not exist is a configuration error, not
|
|
24
|
+
// something to silently fall past.
|
|
25
|
+
if (!exists(path))
|
|
26
|
+
throw new DebuggerNotFoundError([path]);
|
|
27
|
+
return path;
|
|
28
|
+
}
|
|
29
|
+
export function resolveDebugger(options = {}) {
|
|
30
|
+
const env = options.env ?? process.env;
|
|
31
|
+
const platform = options.platform ?? process.platform;
|
|
32
|
+
const exists = options.exists ?? existsSync;
|
|
33
|
+
const isWindows = platform === "win32";
|
|
34
|
+
const binary = isWindows ? "ckb-debugger.exe" : "ckb-debugger";
|
|
35
|
+
const searched = [];
|
|
36
|
+
const explicit = env.CKB_DEBUGGER_PATH;
|
|
37
|
+
if (explicit)
|
|
38
|
+
return checkDebuggerPath(explicit, exists);
|
|
39
|
+
const pathVar = env.PATH ?? env.Path ?? "";
|
|
40
|
+
// On Windows, path.delimiter is ";" — but resolve with the target platform's
|
|
41
|
+
// delimiter so the function can be tested for either platform anywhere.
|
|
42
|
+
const sep = isWindows ? ";" : platform === process.platform ? delimiter : ":";
|
|
43
|
+
for (const dir of pathVar.split(sep).filter(Boolean)) {
|
|
44
|
+
const candidate = join(dir, binary);
|
|
45
|
+
searched.push(candidate);
|
|
46
|
+
if (exists(candidate))
|
|
47
|
+
return candidate;
|
|
48
|
+
}
|
|
49
|
+
if (isWindows && env.LOCALAPPDATA) {
|
|
50
|
+
const offckb = join(env.LOCALAPPDATA, "offckb-nodejs", "Data", "tools", binary);
|
|
51
|
+
searched.push(offckb);
|
|
52
|
+
if (exists(offckb))
|
|
53
|
+
return offckb;
|
|
54
|
+
}
|
|
55
|
+
throw new DebuggerNotFoundError(searched);
|
|
56
|
+
}
|