ckb-cycle-tools 0.0.0-stage → 1.0.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 +44 -0
- package/LICENSE +21 -0
- package/README.md +394 -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 +354 -0
- package/dist/debugger.d.ts +28 -0
- package/dist/debugger.js +56 -0
- package/dist/diff.d.ts +152 -0
- package/dist/diff.js +325 -0
- package/dist/flame.d.ts +59 -0
- package/dist/flame.js +179 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +10 -0
- package/dist/mock.d.ts +109 -0
- package/dist/mock.js +197 -0
- package/dist/profile.d.ts +68 -0
- package/dist/profile.js +130 -0
- package/dist/replay.d.ts +154 -0
- package/dist/replay.js +254 -0
- package/dist/report.d.ts +85 -0
- package/dist/report.js +396 -0
- package/dist/substitute.d.ts +41 -0
- package/dist/substitute.js +122 -0
- package/dist/wasm.d.ts +22 -0
- package/dist/wasm.js +51 -0
- package/package.json +68 -6
package/dist/mock.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds a ckb-debugger "mock transaction" for any transaction, by
|
|
3
|
+
* fetching every cell it touches from a node: input cells, cell deps (with
|
|
4
|
+
* dep groups expanded into the cells they point to), and header deps.
|
|
5
|
+
*
|
|
6
|
+
* Everything stays in the node's JSON-RPC format, which is what ckb-debugger
|
|
7
|
+
* reads, so nothing is converted and nothing can drift in conversion.
|
|
8
|
+
*/
|
|
9
|
+
type Hex = string;
|
|
10
|
+
export interface RpcOutPoint {
|
|
11
|
+
tx_hash: Hex;
|
|
12
|
+
index: Hex;
|
|
13
|
+
}
|
|
14
|
+
export interface RpcCellOutput {
|
|
15
|
+
capacity: Hex;
|
|
16
|
+
lock: RpcScript;
|
|
17
|
+
type: RpcScript | null;
|
|
18
|
+
}
|
|
19
|
+
export interface RpcScript {
|
|
20
|
+
code_hash: Hex;
|
|
21
|
+
hash_type: string;
|
|
22
|
+
args: Hex;
|
|
23
|
+
}
|
|
24
|
+
export interface RpcTransaction {
|
|
25
|
+
version: Hex;
|
|
26
|
+
cell_deps: {
|
|
27
|
+
out_point: RpcOutPoint;
|
|
28
|
+
dep_type: "code" | "dep_group";
|
|
29
|
+
}[];
|
|
30
|
+
header_deps: Hex[];
|
|
31
|
+
inputs: {
|
|
32
|
+
since: Hex;
|
|
33
|
+
previous_output: RpcOutPoint;
|
|
34
|
+
}[];
|
|
35
|
+
outputs: RpcCellOutput[];
|
|
36
|
+
outputs_data: Hex[];
|
|
37
|
+
witnesses: Hex[];
|
|
38
|
+
hash?: Hex;
|
|
39
|
+
}
|
|
40
|
+
export interface MockTransaction {
|
|
41
|
+
mock_info: {
|
|
42
|
+
inputs: {
|
|
43
|
+
input: {
|
|
44
|
+
since: Hex;
|
|
45
|
+
previous_output: RpcOutPoint;
|
|
46
|
+
};
|
|
47
|
+
output: RpcCellOutput;
|
|
48
|
+
data: Hex;
|
|
49
|
+
header: Hex | null;
|
|
50
|
+
}[];
|
|
51
|
+
cell_deps: {
|
|
52
|
+
cell_dep: {
|
|
53
|
+
out_point: RpcOutPoint;
|
|
54
|
+
dep_type: "code" | "dep_group";
|
|
55
|
+
};
|
|
56
|
+
output: RpcCellOutput;
|
|
57
|
+
data: Hex;
|
|
58
|
+
header: Hex | null;
|
|
59
|
+
}[];
|
|
60
|
+
header_deps: unknown[];
|
|
61
|
+
};
|
|
62
|
+
tx: RpcTransaction;
|
|
63
|
+
}
|
|
64
|
+
export type Rpc = <T>(method: string, params: unknown[]) => Promise<T>;
|
|
65
|
+
export interface HttpRpcOptions {
|
|
66
|
+
/** How long one request may take before it is abandoned. Default 30 s. */
|
|
67
|
+
timeoutMs?: number;
|
|
68
|
+
/** Requests in flight at once; the rest wait. Default 16, so a big transaction does not trip a rate limit. */
|
|
69
|
+
concurrency?: number;
|
|
70
|
+
}
|
|
71
|
+
export declare const DEFAULT_RPC_TIMEOUT_MS = 30000;
|
|
72
|
+
export declare function httpRpc(url: string, options?: HttpRpcOptions): Rpc;
|
|
73
|
+
/** A cellbase (block reward) transaction: one input, the null out point. No scripts run. */
|
|
74
|
+
export declare function isCellbase(tx: RpcTransaction): boolean;
|
|
75
|
+
/** The epochs CKB-VM v1 and v2 took effect on one chain. `Infinity`: not scheduled there. */
|
|
76
|
+
export type VmEpochs = readonly [v1: number, v2: number];
|
|
77
|
+
export declare function scriptVersionAt(chain: "mainnet" | "testnet" | VmEpochs, epoch: number): 0 | 1 | 2;
|
|
78
|
+
/** A node's chain and VM epochs, from `get_consensus`. */
|
|
79
|
+
export interface NodeConsensus {
|
|
80
|
+
/** The chain id: "ckb" (mainnet), "ckb_testnet", or a devnet's own. */
|
|
81
|
+
chain: string;
|
|
82
|
+
/** "mainnet", "testnet", or the chain id for any other chain. */
|
|
83
|
+
network: string;
|
|
84
|
+
vmEpochs: VmEpochs;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Asks the node which chain it serves and when its hardforks took effect, so a
|
|
88
|
+
* replay never depends on a network flag matching the node: RFC 0032 brought
|
|
89
|
+
* CKB-VM v1 (Mirana), RFC 0049 CKB-VM v2 (Meepo).
|
|
90
|
+
*/
|
|
91
|
+
export declare function nodeConsensus(rpc: Rpc): Promise<NodeConsensus>;
|
|
92
|
+
/** Parses a molecule OutPointVec: u32 LE count, then 36-byte out points. */
|
|
93
|
+
export declare function parseOutPointVec(data: Hex): RpcOutPoint[];
|
|
94
|
+
/**
|
|
95
|
+
* A committed (or pending) transaction, fetched by hash, with the epoch of the
|
|
96
|
+
* block that committed it (absent while pending).
|
|
97
|
+
*/
|
|
98
|
+
export declare function buildMockTransaction(rpc: Rpc, txHash: Hex): Promise<{
|
|
99
|
+
mock: MockTransaction;
|
|
100
|
+
cycles?: bigint;
|
|
101
|
+
status: string;
|
|
102
|
+
epoch?: number;
|
|
103
|
+
}>;
|
|
104
|
+
/**
|
|
105
|
+
* Any transaction in RPC shape — including one that was never sent, or that
|
|
106
|
+
* the node would reject — as long as the cells it spends and depends on exist.
|
|
107
|
+
*/
|
|
108
|
+
export declare function mockFromTransaction(rpc: Rpc, tx: RpcTransaction): Promise<MockTransaction>;
|
|
109
|
+
export {};
|
package/dist/mock.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds a ckb-debugger "mock transaction" for any transaction, by
|
|
3
|
+
* fetching every cell it touches from a node: input cells, cell deps (with
|
|
4
|
+
* dep groups expanded into the cells they point to), and header deps.
|
|
5
|
+
*
|
|
6
|
+
* Everything stays in the node's JSON-RPC format, which is what ckb-debugger
|
|
7
|
+
* reads, so nothing is converted and nothing can drift in conversion.
|
|
8
|
+
*/
|
|
9
|
+
import { ccc } from "@ckb-ccc/core";
|
|
10
|
+
export const DEFAULT_RPC_TIMEOUT_MS = 30_000;
|
|
11
|
+
const RETRY_STATUS = new Set([429, 502, 503, 504]);
|
|
12
|
+
export function httpRpc(url, options = {}) {
|
|
13
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_RPC_TIMEOUT_MS;
|
|
14
|
+
const limit = Math.max(1, options.concurrency ?? 16);
|
|
15
|
+
let id = 0;
|
|
16
|
+
let active = 0;
|
|
17
|
+
const queue = [];
|
|
18
|
+
const acquire = () => active < limit ? (active++, Promise.resolve()) : new Promise((resolve) => queue.push(resolve));
|
|
19
|
+
// A waiting request takes over the slot directly, so `active` never overshoots.
|
|
20
|
+
const release = () => (queue.length ? queue.shift()() : active--);
|
|
21
|
+
const post = async (method, body) => {
|
|
22
|
+
try {
|
|
23
|
+
return await fetch(url, {
|
|
24
|
+
method: "POST",
|
|
25
|
+
headers: { "content-type": "application/json" },
|
|
26
|
+
body,
|
|
27
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
const err = e;
|
|
32
|
+
if (err.name === "TimeoutError")
|
|
33
|
+
throw new Error(`${method}: no answer from ${url} within ${timeoutMs / 1000} s`);
|
|
34
|
+
// fetch says only "fetch failed"; the reason (ECONNREFUSED, ENOTFOUND…) is in its cause.
|
|
35
|
+
const why = err.cause?.code ?? err.cause?.message ?? (e instanceof Error ? e.message : String(e));
|
|
36
|
+
throw new Error(`${method}: cannot reach ${url} (${why})`);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
return async (method, params) => {
|
|
40
|
+
await acquire();
|
|
41
|
+
try {
|
|
42
|
+
const body = JSON.stringify({ id: ++id, jsonrpc: "2.0", method, params });
|
|
43
|
+
let res = await post(method, body);
|
|
44
|
+
// One retry for a rate limit or a busy gateway: a single 429 should not end a replay.
|
|
45
|
+
if (RETRY_STATUS.has(res.status)) {
|
|
46
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
47
|
+
res = await post(method, body);
|
|
48
|
+
}
|
|
49
|
+
if (!res.ok)
|
|
50
|
+
throw new Error(`${method}: HTTP ${res.status} from ${url}`);
|
|
51
|
+
let json;
|
|
52
|
+
try {
|
|
53
|
+
json = await res.json();
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw new Error(`${method}: ${url} did not answer with JSON-RPC`);
|
|
57
|
+
}
|
|
58
|
+
if (json.error)
|
|
59
|
+
throw new Error(`${method}: ${json.error.message}`);
|
|
60
|
+
return json.result;
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
release();
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/** A cellbase (block reward) transaction: one input, the null out point. No scripts run. */
|
|
68
|
+
export function isCellbase(tx) {
|
|
69
|
+
const o = tx.inputs.length === 1 ? tx.inputs[0].previous_output : undefined;
|
|
70
|
+
return o !== undefined && /^0x0{64}$/.test(o.tx_hash) && Number(o.index) === 0xffffffff;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The epoch each CKB-VM version took effect (Mirana: v1, Meepo: v2), per public
|
|
74
|
+
* network. A `hash_type: "type"` script runs on the version current at its
|
|
75
|
+
* block; data, data1 and data2 name their version themselves. Only a fallback:
|
|
76
|
+
* the epochs of the node actually asked come from its `get_consensus`.
|
|
77
|
+
*/
|
|
78
|
+
const VM_VERSION_EPOCHS = { mainnet: [5414, 12293], testnet: [3113, 9690] };
|
|
79
|
+
export function scriptVersionAt(chain, epoch) {
|
|
80
|
+
const [mirana, meepo] = typeof chain === "string" ? VM_VERSION_EPOCHS[chain] : chain;
|
|
81
|
+
return epoch >= meepo ? 2 : epoch >= mirana ? 1 : 0;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Asks the node which chain it serves and when its hardforks took effect, so a
|
|
85
|
+
* replay never depends on a network flag matching the node: RFC 0032 brought
|
|
86
|
+
* CKB-VM v1 (Mirana), RFC 0049 CKB-VM v2 (Meepo).
|
|
87
|
+
*/
|
|
88
|
+
export async function nodeConsensus(rpc) {
|
|
89
|
+
const c = await rpc("get_consensus", []);
|
|
90
|
+
const epochOf = (rfc) => {
|
|
91
|
+
const f = c.hardfork_features?.find((h) => h.rfc === rfc);
|
|
92
|
+
if (!f)
|
|
93
|
+
throw new Error(`get_consensus: no hardfork feature ${rfc}`);
|
|
94
|
+
return f.epoch_number === null ? Infinity : Number(f.epoch_number);
|
|
95
|
+
};
|
|
96
|
+
const network = c.id === "ckb" ? "mainnet" : c.id === "ckb_testnet" ? "testnet" : c.id;
|
|
97
|
+
return { chain: c.id, network, vmEpochs: [epochOf("0032"), epochOf("0049")] };
|
|
98
|
+
}
|
|
99
|
+
/** Parses a molecule OutPointVec: u32 LE count, then 36-byte out points. */
|
|
100
|
+
export function parseOutPointVec(data) {
|
|
101
|
+
// No Buffer: this module also runs in the browser.
|
|
102
|
+
const bytes = ccc.bytesFrom(data);
|
|
103
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
104
|
+
if (bytes.length < 4)
|
|
105
|
+
throw new Error("dep group data too short");
|
|
106
|
+
const count = view.getUint32(0, true);
|
|
107
|
+
if (bytes.length !== 4 + count * 36)
|
|
108
|
+
throw new Error("dep group data has the wrong length");
|
|
109
|
+
const out = [];
|
|
110
|
+
for (let i = 0; i < count; i++) {
|
|
111
|
+
const at = 4 + i * 36;
|
|
112
|
+
out.push({
|
|
113
|
+
tx_hash: ccc.hexFrom(bytes.subarray(at, at + 32)),
|
|
114
|
+
index: "0x" + view.getUint32(at + 32, true).toString(16),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
const key = (o) => `${o.tx_hash}:${Number(o.index)}`;
|
|
120
|
+
/**
|
|
121
|
+
* A committed (or pending) transaction, fetched by hash, with the epoch of the
|
|
122
|
+
* block that committed it (absent while pending).
|
|
123
|
+
*/
|
|
124
|
+
export async function buildMockTransaction(rpc, txHash) {
|
|
125
|
+
const root = await rpc("get_transaction", [txHash]);
|
|
126
|
+
// A rejected transaction is not in the chain either; the node still says why.
|
|
127
|
+
if (root?.tx_status.status === "rejected") {
|
|
128
|
+
throw new Error(`transaction rejected by the node: ${txHash}${root.tx_status.reason ? ` (${root.tx_status.reason})` : ""}`);
|
|
129
|
+
}
|
|
130
|
+
if (!root?.transaction)
|
|
131
|
+
throw new Error(`transaction not found: ${txHash}`);
|
|
132
|
+
const blockHash = root.tx_status.block_hash;
|
|
133
|
+
const header = blockHash ? await rpc("get_header", [blockHash]) : null;
|
|
134
|
+
return {
|
|
135
|
+
mock: await mockFromTransaction(rpc, root.transaction),
|
|
136
|
+
// Some public nodes report 0x0 for older blocks: unknown, not zero, since an
|
|
137
|
+
// input lock always runs. Only a cellbase really costs 0.
|
|
138
|
+
...(root.cycles &&
|
|
139
|
+
(BigInt(root.cycles) > 0n || isCellbase(root.transaction)) && { cycles: BigInt(root.cycles) }),
|
|
140
|
+
status: root.tx_status.status,
|
|
141
|
+
// The epoch number is the low 24 bits of the packed epoch.
|
|
142
|
+
...(header && { epoch: Number(BigInt(header.epoch) & 0xffffffn) }),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Any transaction in RPC shape — including one that was never sent, or that
|
|
147
|
+
* the node would reject — as long as the cells it spends and depends on exist.
|
|
148
|
+
*/
|
|
149
|
+
export async function mockFromTransaction(rpc, tx) {
|
|
150
|
+
const txs = new Map();
|
|
151
|
+
const getTx = (hash) => {
|
|
152
|
+
let p = txs.get(hash);
|
|
153
|
+
if (!p) {
|
|
154
|
+
p = rpc("get_transaction", [hash]);
|
|
155
|
+
txs.set(hash, p);
|
|
156
|
+
}
|
|
157
|
+
return p;
|
|
158
|
+
};
|
|
159
|
+
const getCell = async (o) => {
|
|
160
|
+
const res = await getTx(o.tx_hash);
|
|
161
|
+
const i = Number(o.index);
|
|
162
|
+
const output = res?.transaction?.outputs[i];
|
|
163
|
+
if (!output)
|
|
164
|
+
throw new Error(`cell not found: ${key(o)}`);
|
|
165
|
+
// The block the cell was created in. A script reading this cell's header
|
|
166
|
+
// (load_header with Source::Input, e.g. a Nervos DAO withdrawal) gets that
|
|
167
|
+
// block, provided the transaction lists it in header_deps — as on the node.
|
|
168
|
+
return { output, data: res.transaction.outputs_data[i], header: res.tx_status.block_hash ?? null };
|
|
169
|
+
};
|
|
170
|
+
if (isCellbase(tx)) {
|
|
171
|
+
const { hash: _hash, ...plainTx } = tx;
|
|
172
|
+
return { mock_info: { inputs: [], cell_deps: [], header_deps: [] }, tx: plainTx };
|
|
173
|
+
}
|
|
174
|
+
const inputs = await Promise.all(tx.inputs.map(async (input) => ({ input, ...(await getCell(input.previous_output)) })));
|
|
175
|
+
// Declared deps first, then the cells each dep group points to, de-duplicated.
|
|
176
|
+
// A cell may appear as code and as a dep group; each needs its own entry.
|
|
177
|
+
const deps = [];
|
|
178
|
+
const seen = new Set();
|
|
179
|
+
const addDep = async (cell_dep) => {
|
|
180
|
+
const id = `${key(cell_dep.out_point)}:${cell_dep.dep_type}`;
|
|
181
|
+
if (seen.has(id))
|
|
182
|
+
return;
|
|
183
|
+
seen.add(id);
|
|
184
|
+
const cell = await getCell(cell_dep.out_point);
|
|
185
|
+
deps.push({ cell_dep, ...cell });
|
|
186
|
+
if (cell_dep.dep_type === "dep_group") {
|
|
187
|
+
for (const out_point of parseOutPointVec(cell.data))
|
|
188
|
+
await addDep({ out_point, dep_type: "code" });
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
for (const d of tx.cell_deps)
|
|
192
|
+
await addDep(d);
|
|
193
|
+
const header_deps = await Promise.all(tx.header_deps.map((h) => rpc("get_header", [h])));
|
|
194
|
+
// ckb-debugger reads the RPC transaction shape without the hash field.
|
|
195
|
+
const { hash: _hash, ...plainTx } = tx;
|
|
196
|
+
return { mock_info: { inputs, cell_deps: deps, header_deps }, tx: plainTx };
|
|
197
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { MockTransaction, RpcTransaction } from "./mock.js";
|
|
2
|
+
import { type Folded } from "./flame.js";
|
|
3
|
+
import { type DebuggerOutput, type Profile, type ReplayOptions, type ReplayPlan } from "./replay.js";
|
|
4
|
+
export { checkTypeId, parseDebuggerOutput, parseDebuggerRun, parseNames, readTransactionJson, selectorFor, TYPE_ID_CODE_HASH, TYPE_ID_CYCLES, } from "./replay.js";
|
|
5
|
+
export type { DebuggerOutput, GroupRun, Profile, ProfiledGroup } from "./replay.js";
|
|
6
|
+
/** The most a run may print. More is a script flooding its logs: the run is an error, not a result. */
|
|
7
|
+
export declare const MAX_DEBUGGER_OUTPUT: number;
|
|
8
|
+
export interface ProfileOptions extends ReplayOptions {
|
|
9
|
+
debuggerPath?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Runs ckb-debugger instead of the native binary (`--version` included):
|
|
12
|
+
* for tests, or another way to run it. `debuggerPath` is then not used.
|
|
13
|
+
*/
|
|
14
|
+
runDebugger?: (args: string[]) => Promise<DebuggerOutput>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Runs the native ckb-debugger once and keeps what a parser needs to trust the
|
|
18
|
+
* output: the exit code, and whether the output was complete. A debugger that
|
|
19
|
+
* cannot be started at all is an error (thrown), not a script result.
|
|
20
|
+
*/
|
|
21
|
+
export declare function runNativeDebugger(debuggerPath: string, args: string[], maxBuffer?: number): Promise<DebuggerOutput>;
|
|
22
|
+
/**
|
|
23
|
+
* Profiles a transaction per script group: a committed one by hash (and checks
|
|
24
|
+
* the node's total), or any transaction in RPC shape — e.g. one about to be sent,
|
|
25
|
+
* or one the node rejected — to see which script refuses it, with what exit code,
|
|
26
|
+
* and what it cost to get there. A ready ckb-debugger mock transaction (every
|
|
27
|
+
* cell already in it) needs no node at all.
|
|
28
|
+
*/
|
|
29
|
+
export declare function profileTransaction(target: string | RpcTransaction | MockTransaction, options?: ProfileOptions): Promise<Profile>;
|
|
30
|
+
export interface FlameGroup {
|
|
31
|
+
selector: string;
|
|
32
|
+
name?: string;
|
|
33
|
+
codeHash: string;
|
|
34
|
+
role: string;
|
|
35
|
+
/** Exit code and cycles of the profiled run, as in a profile. */
|
|
36
|
+
result: number;
|
|
37
|
+
error?: string;
|
|
38
|
+
cycles: bigint;
|
|
39
|
+
/** Merged folded stacks, frames named by function. */
|
|
40
|
+
folded: Folded;
|
|
41
|
+
/** The binary used instead of the one in the transaction (`--bin`), if any. */
|
|
42
|
+
bin?: string;
|
|
43
|
+
/**
|
|
44
|
+
* With `bin`: the cycles of the same group run with the transaction's own
|
|
45
|
+
* binary. Different cycles mean the build is not the deployed code, and the
|
|
46
|
+
* flamegraph describes the build.
|
|
47
|
+
*/
|
|
48
|
+
deployedCycles?: bigint;
|
|
49
|
+
/** With `bin`: the exit code of that run (with the deployed binary), and whether the VM stopped it. */
|
|
50
|
+
deployedResult?: number;
|
|
51
|
+
deployedError?: string;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Profiles each script group with ckb-debugger's flamegraph mode. `bins` maps a
|
|
55
|
+
* code hash to an unstripped build of that script, used instead of the
|
|
56
|
+
* deployed (stripped) binary so the frames have names; each such group is also
|
|
57
|
+
* run with the deployed binary, to check the build behaves the same.
|
|
58
|
+
* `scripts` limits the run to those selectors (`input.0.lock`, …).
|
|
59
|
+
*/
|
|
60
|
+
export declare function flameTransaction(target: string | RpcTransaction | MockTransaction, options: ProfileOptions & {
|
|
61
|
+
bins?: Record<string, string>;
|
|
62
|
+
scripts?: string[];
|
|
63
|
+
readFile: (path: string) => Promise<string>;
|
|
64
|
+
}): Promise<{
|
|
65
|
+
plan: ReplayPlan;
|
|
66
|
+
groups: FlameGroup[];
|
|
67
|
+
debugger: string;
|
|
68
|
+
}>;
|
package/dist/profile.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { checkDebuggerPath, resolveDebugger } from "./debugger.js";
|
|
7
|
+
import { parseFolded } from "./flame.js";
|
|
8
|
+
import { debuggerArgs, parseDebuggerRun, planReplay, replayGroups, selectorFor, TYPE_ID_CODE_HASH, } from "./replay.js";
|
|
9
|
+
// The pure parts live in replay.ts, shared with the browser; existing imports keep working.
|
|
10
|
+
export { checkTypeId, parseDebuggerOutput, parseDebuggerRun, parseNames, readTransactionJson, selectorFor, TYPE_ID_CODE_HASH, TYPE_ID_CYCLES, } from "./replay.js";
|
|
11
|
+
const run = promisify(execFile);
|
|
12
|
+
/** The most a run may print. More is a script flooding its logs: the run is an error, not a result. */
|
|
13
|
+
export const MAX_DEBUGGER_OUTPUT = 64 << 20;
|
|
14
|
+
/** The debugger to run, and its `--version` line ("unknown" if it cannot say). */
|
|
15
|
+
async function debuggerOf(options) {
|
|
16
|
+
let exec = options.runDebugger;
|
|
17
|
+
if (!exec) {
|
|
18
|
+
const debuggerPath = options.debuggerPath ? checkDebuggerPath(options.debuggerPath) : resolveDebugger();
|
|
19
|
+
exec = (args) => runNativeDebugger(debuggerPath, args);
|
|
20
|
+
}
|
|
21
|
+
const version = await exec(["--version"]).then((r) => (r.exitCode === 0 && r.stdout.trim()) || "unknown", () => "unknown");
|
|
22
|
+
return { exec, version };
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Runs the native ckb-debugger once and keeps what a parser needs to trust the
|
|
26
|
+
* output: the exit code, and whether the output was complete. A debugger that
|
|
27
|
+
* cannot be started at all is an error (thrown), not a script result.
|
|
28
|
+
*/
|
|
29
|
+
export async function runNativeDebugger(debuggerPath, args, maxBuffer = MAX_DEBUGGER_OUTPUT) {
|
|
30
|
+
try {
|
|
31
|
+
const r = await run(debuggerPath, args, { maxBuffer });
|
|
32
|
+
return { stdout: r.stdout, stderr: r.stderr, exitCode: 0 };
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
const e = err;
|
|
36
|
+
// Killed at the buffer limit: what is left is the beginning of the output, and
|
|
37
|
+
// the real result lines (at the end) are gone. Never parse it.
|
|
38
|
+
if (e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
|
|
39
|
+
return { stdout: "", stderr: "", exitCode: null, failure: `output exceeded ${MAX_DEBUGGER_OUTPUT >> 20} MB (script logs?): not trusted` };
|
|
40
|
+
}
|
|
41
|
+
// ENOENT, EACCES, EINVAL…: it never ran.
|
|
42
|
+
if (typeof e.code === "string")
|
|
43
|
+
throw new Error(`cannot run ckb-debugger at ${debuggerPath}: ${e.code}`);
|
|
44
|
+
if (typeof e.code === "number")
|
|
45
|
+
return { stdout: e.stdout ?? "", stderr: e.stderr ?? "", exitCode: e.code };
|
|
46
|
+
return { stdout: e.stdout ?? "", stderr: e.stderr ?? "", exitCode: null, ...(e.signal && { failure: `ckb-debugger was killed (${e.signal})` }) };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Profiles a transaction per script group: a committed one by hash (and checks
|
|
51
|
+
* the node's total), or any transaction in RPC shape — e.g. one about to be sent,
|
|
52
|
+
* or one the node rejected — to see which script refuses it, with what exit code,
|
|
53
|
+
* and what it cost to get there. A ready ckb-debugger mock transaction (every
|
|
54
|
+
* cell already in it) needs no node at all.
|
|
55
|
+
*/
|
|
56
|
+
export async function profileTransaction(target, options = {}) {
|
|
57
|
+
const { exec, version: debuggerVersion } = await debuggerOf(options);
|
|
58
|
+
const plan = await planReplay(target, options);
|
|
59
|
+
const dir = await mkdtemp(join(tmpdir(), "ckb-cycles-"));
|
|
60
|
+
try {
|
|
61
|
+
const txFile = join(dir, "tx.json");
|
|
62
|
+
await writeFile(txFile, JSON.stringify(plan.mock));
|
|
63
|
+
// ckb-debugger exits non-zero when a script rejects; its output still says why.
|
|
64
|
+
return await replayGroups(plan, exec, { txFile, debugger: debuggerVersion });
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
await rm(dir, { recursive: true, force: true });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Profiles each script group with ckb-debugger's flamegraph mode. `bins` maps a
|
|
72
|
+
* code hash to an unstripped build of that script, used instead of the
|
|
73
|
+
* deployed (stripped) binary so the frames have names; each such group is also
|
|
74
|
+
* run with the deployed binary, to check the build behaves the same.
|
|
75
|
+
* `scripts` limits the run to those selectors (`input.0.lock`, …).
|
|
76
|
+
*/
|
|
77
|
+
export async function flameTransaction(target, options) {
|
|
78
|
+
const { exec, version: debuggerVersion } = await debuggerOf(options);
|
|
79
|
+
const plan = await planReplay(target, options);
|
|
80
|
+
const bins = Object.fromEntries(Object.entries(options.bins ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
|
|
81
|
+
const dir = await mkdtemp(join(tmpdir(), "ckb-flame-"));
|
|
82
|
+
try {
|
|
83
|
+
const txFile = join(dir, "tx.json");
|
|
84
|
+
await writeFile(txFile, JSON.stringify(plan.mock));
|
|
85
|
+
const groups = [];
|
|
86
|
+
for (const g of plan.groups) {
|
|
87
|
+
const selector = selectorFor(g);
|
|
88
|
+
if (options.scripts && !options.scripts.includes(selector))
|
|
89
|
+
continue;
|
|
90
|
+
if (g.role === "type" && g.codeHash === TYPE_ID_CODE_HASH)
|
|
91
|
+
continue; // built into the node: nothing to profile
|
|
92
|
+
const base = debuggerArgs(txFile, selector, plan.scriptVersion);
|
|
93
|
+
const bin = bins[g.codeHash.toLowerCase()];
|
|
94
|
+
const out = join(dir, `${selector}.folded`);
|
|
95
|
+
const runOut = await exec([
|
|
96
|
+
...base,
|
|
97
|
+
...(bin ? ["--bin", bin] : []),
|
|
98
|
+
"--enable-flamegraph",
|
|
99
|
+
"--flamegraph-output",
|
|
100
|
+
out,
|
|
101
|
+
]);
|
|
102
|
+
const folded = parseFolded(await options.readFile(out).catch(() => ""));
|
|
103
|
+
// Flamegraph mode leaves out loading the binary, so result and cycles come
|
|
104
|
+
// from plain runs: with the build, and with the deployed binary to compare.
|
|
105
|
+
const parsed = runOut.exitCode === null ? parseDebuggerRun(runOut) : parseDebuggerRun(await exec([...base, ...(bin ? ["--bin", bin] : [])]));
|
|
106
|
+
const deployed = bin ? parseDebuggerRun(await exec(base)) : undefined;
|
|
107
|
+
groups.push({
|
|
108
|
+
selector,
|
|
109
|
+
...(g.name && { name: g.name }),
|
|
110
|
+
codeHash: g.codeHash,
|
|
111
|
+
role: g.role,
|
|
112
|
+
result: parsed.result,
|
|
113
|
+
...(parsed.error && { error: parsed.error }),
|
|
114
|
+
cycles: parsed.cycles,
|
|
115
|
+
folded,
|
|
116
|
+
...(bin &&
|
|
117
|
+
deployed && {
|
|
118
|
+
bin,
|
|
119
|
+
deployedCycles: deployed.cycles,
|
|
120
|
+
deployedResult: deployed.result,
|
|
121
|
+
...(deployed.error && { deployedError: deployed.error }),
|
|
122
|
+
}),
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return { plan, groups, debugger: debuggerVersion };
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
await rm(dir, { recursive: true, force: true });
|
|
129
|
+
}
|
|
130
|
+
}
|
package/dist/replay.d.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { type ScriptGroup } from "./analyze.js";
|
|
2
|
+
import { type MockTransaction, type NodeConsensus, type Rpc, type RpcTransaction } from "./mock.js";
|
|
3
|
+
export interface GroupRun {
|
|
4
|
+
/** The `--script` selector passed to ckb-debugger, e.g. `input.0.lock`. */
|
|
5
|
+
selector: string;
|
|
6
|
+
/** Exit code of the script: 0 means it accepted the transaction. */
|
|
7
|
+
result: number;
|
|
8
|
+
/** Set when the VM itself stopped the script (a fault, the cycle limit), or Type ID refused. */
|
|
9
|
+
error?: string;
|
|
10
|
+
cycles: bigint;
|
|
11
|
+
/** Lines the script printed through ckb_debug. */
|
|
12
|
+
logs: string[];
|
|
13
|
+
}
|
|
14
|
+
export type ProfiledGroup = ScriptGroup & GroupRun;
|
|
15
|
+
export interface Profile {
|
|
16
|
+
/** The transaction hash, or "(not on chain)" for a transaction passed in directly. */
|
|
17
|
+
hash: string;
|
|
18
|
+
status: string;
|
|
19
|
+
/** Total cycles as reported by the node. */
|
|
20
|
+
nodeCycles?: bigint;
|
|
21
|
+
/** Sum of the per-group cycles measured by ckb-debugger. */
|
|
22
|
+
measuredCycles: bigint;
|
|
23
|
+
groups: ProfiledGroup[];
|
|
24
|
+
/** Where the numbers came from, so a result can be reproduced. */
|
|
25
|
+
env: {
|
|
26
|
+
debugger: string;
|
|
27
|
+
network: string;
|
|
28
|
+
rpcUrl: string;
|
|
29
|
+
scriptVersion: number;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
export interface ReplayOptions {
|
|
33
|
+
/**
|
|
34
|
+
* The public node to use when there is no `rpcUrl`. When set, the node's own
|
|
35
|
+
* chain (from `get_consensus`) must agree with it, or the replay stops.
|
|
36
|
+
*/
|
|
37
|
+
network?: "testnet" | "mainnet";
|
|
38
|
+
/** A node to fetch from instead of the public one for `network`. */
|
|
39
|
+
rpcUrl?: string;
|
|
40
|
+
/** Per RPC request, in milliseconds. Default 30 s. */
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
/**
|
|
43
|
+
* Names for scripts this tool cannot know, e.g. on a devnet: `codeHash:hashType`
|
|
44
|
+
* (lowercase hex) → name. They take precedence over the known scripts.
|
|
45
|
+
*/
|
|
46
|
+
scriptNames?: Record<string, string>;
|
|
47
|
+
/**
|
|
48
|
+
* The CKB-VM version for `hash_type: "type"` scripts. By default, that of the
|
|
49
|
+
* transaction's block, or the current one (2) for a transaction not on chain.
|
|
50
|
+
*/
|
|
51
|
+
scriptVersion?: 0 | 1 | 2;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Type ID is verified natively by the node rather than by a script binary, so
|
|
55
|
+
* ckb-debugger cannot run it. The node charges it a fixed cost (TYPE_ID_CYCLES
|
|
56
|
+
* in ckb-script).
|
|
57
|
+
*/
|
|
58
|
+
export declare const TYPE_ID_CODE_HASH = "0x00000000000000000000000000000000000000000000000000545950455f4944";
|
|
59
|
+
export declare const TYPE_ID_CYCLES = 1000000n;
|
|
60
|
+
export declare const PUBLIC_RPC: {
|
|
61
|
+
testnet: string;
|
|
62
|
+
mainnet: string;
|
|
63
|
+
};
|
|
64
|
+
/** The first cell in a group is enough: ckb-debugger runs the whole group from it. */
|
|
65
|
+
export declare function selectorFor(g: ScriptGroup): string;
|
|
66
|
+
/** The ckb-debugger arguments for one group, the same for the native and the WebAssembly build. */
|
|
67
|
+
export declare function debuggerArgs(txFile: string, selector: string, scriptVersion: number): string[];
|
|
68
|
+
/** The tail of some output, cleaned for a terminal: enough to see what went wrong, never megabytes. */
|
|
69
|
+
export declare function outputTail(out: string, max?: number): string;
|
|
70
|
+
/**
|
|
71
|
+
* ckb-debugger's own result lines are the last lines it prints: `Run result:`
|
|
72
|
+
* then `All cycles:` (or `Run result:` alone when the VM stopped the script).
|
|
73
|
+
* A script's logs come before them. Only those final lines are read, so a
|
|
74
|
+
* script that logs "Run result: 0" (even after a newline of its own) cannot
|
|
75
|
+
* fake its result, as long as the output is complete: a run whose output was
|
|
76
|
+
* cut off must never get here (see parseDebuggerRun).
|
|
77
|
+
*/
|
|
78
|
+
export declare function parseDebuggerOutput(out: string): Omit<GroupRun, "selector">;
|
|
79
|
+
/** One ckb-debugger run, as a RunDebugger returns it. */
|
|
80
|
+
export interface DebuggerOutput {
|
|
81
|
+
stdout: string;
|
|
82
|
+
stderr: string;
|
|
83
|
+
/** The exit code; null when the process was killed, -1 when the WebAssembly build trapped. */
|
|
84
|
+
exitCode: number | null;
|
|
85
|
+
/** Set when the output cannot be trusted, e.g. it was cut off at the buffer limit. */
|
|
86
|
+
failure?: string;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Reads one run: its final result lines (parseDebuggerOutput), checked against
|
|
90
|
+
* its exit code. ckb-debugger exits 0 only when the script returned 0, so lines
|
|
91
|
+
* that say 0 with a non-zero exit code (or the reverse) were faked or cut
|
|
92
|
+
* short, and make an error rather than a result. Output that was cut off is
|
|
93
|
+
* never parsed at all.
|
|
94
|
+
*/
|
|
95
|
+
export declare function parseDebuggerRun(run: DebuggerOutput): Omit<GroupRun, "selector">;
|
|
96
|
+
/**
|
|
97
|
+
* Type ID, checked as the node does (ckb-script's type_id): at most one cell on
|
|
98
|
+
* each side, 32-byte args, and a new Type ID's args are the hash of the first
|
|
99
|
+
* input and the new cell's output index.
|
|
100
|
+
*/
|
|
101
|
+
export declare function checkTypeId(g: ScriptGroup, tx: RpcTransaction): string | undefined;
|
|
102
|
+
/** Everything a replay needs, fetched from the node: the mock transaction, its groups, and how to run them. */
|
|
103
|
+
export interface ReplayPlan {
|
|
104
|
+
hash: string;
|
|
105
|
+
status: string;
|
|
106
|
+
nodeCycles?: bigint;
|
|
107
|
+
mock: MockTransaction;
|
|
108
|
+
groups: ScriptGroup[];
|
|
109
|
+
/** CKB-VM version for `hash_type: "type"` scripts: the one of the block's epoch. */
|
|
110
|
+
scriptVersion: 0 | 1 | 2;
|
|
111
|
+
/** "testnet", "mainnet", or a devnet's chain id: what the node says it serves, when it was asked. */
|
|
112
|
+
network: string;
|
|
113
|
+
rpcUrl: string;
|
|
114
|
+
}
|
|
115
|
+
/** The script groups that run for a mock transaction, in first-appearance order. A cellbase runs none. */
|
|
116
|
+
export declare function groupsOf(mock: MockTransaction): ScriptGroup[];
|
|
117
|
+
/**
|
|
118
|
+
* Fetches what a replay needs: a committed transaction by hash (with the node's
|
|
119
|
+
* total), or any transaction in RPC shape, e.g. one about to be sent.
|
|
120
|
+
*/
|
|
121
|
+
export declare function planReplay(target: string | RpcTransaction | MockTransaction, options?: ReplayOptions): Promise<ReplayPlan>;
|
|
122
|
+
/**
|
|
123
|
+
* The node's chain and CKB-VM epochs, from `get_consensus`. Stops when the node
|
|
124
|
+
* serves another chain than `options.network` names. If the node cannot say,
|
|
125
|
+
* the built-in table stands in only for the public node of `network`; for a
|
|
126
|
+
* node given by URL the chain is unknown, so the replay stops.
|
|
127
|
+
*/
|
|
128
|
+
export declare function consensusOf(rpc: Rpc, rpcUrl: string, options?: ReplayOptions): Promise<NodeConsensus | undefined>;
|
|
129
|
+
/**
|
|
130
|
+
* Runs one group in a ckb-debugger with `args` (from `debuggerArgs`) and
|
|
131
|
+
* returns the run: its output and exit code, read with parseDebuggerRun. A
|
|
132
|
+
* plain string (stdout and stderr together) is read without the exit-code check.
|
|
133
|
+
*/
|
|
134
|
+
export type RunDebugger = (args: string[]) => Promise<DebuggerOutput | string>;
|
|
135
|
+
/**
|
|
136
|
+
* Replays every group of a plan, one after another, through `run`. The mock
|
|
137
|
+
* transaction must already be readable by that debugger at `txFile`.
|
|
138
|
+
* `onGroup` hears about each group before it runs, for progress.
|
|
139
|
+
*/
|
|
140
|
+
export declare function replayGroups(plan: ReplayPlan, run: RunDebugger, options: {
|
|
141
|
+
txFile: string;
|
|
142
|
+
debugger: string;
|
|
143
|
+
onGroup?: (index: number, selector: string) => void;
|
|
144
|
+
}): Promise<Profile>;
|
|
145
|
+
/** How a profile's total compares with the node's: what the CLI and the web page both print. */
|
|
146
|
+
export declare function nodeVerdict(p: Profile): "match" | "mismatch" | "not recorded" | undefined;
|
|
147
|
+
/**
|
|
148
|
+
* Reads a transaction from JSON in any of the shapes people have at hand: the
|
|
149
|
+
* node's RPC shape, a `get_transaction` result (`{ transaction }`), or a CCC
|
|
150
|
+
* transaction saved with `ccc.stringify`.
|
|
151
|
+
*/
|
|
152
|
+
export declare function readTransactionJson(json: string): RpcTransaction;
|
|
153
|
+
/** `--name 0xabc…=campaign-lock` (or `0xabc…:type=…`) → profileTransaction's scriptNames. */
|
|
154
|
+
export declare function parseNames(flags: string[]): Record<string, string>;
|