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/CHANGELOG.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
This project follows [semantic versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## 1.0.0 (2026-10-27)
|
|
6
|
+
|
|
7
|
+
First stable release.
|
|
8
|
+
|
|
9
|
+
### CLI: `ckb-cycles`
|
|
10
|
+
- Replays a transaction per script group in ckb-debugger; the sum matches the node's
|
|
11
|
+
total. Resolves the real ckb-debugger past the Windows `.cmd` shim.
|
|
12
|
+
- Failure-path profiling: `--file` profiles a transaction that is not on chain.
|
|
13
|
+
- Right VM version per script, from the node's hardfork epochs; input headers are
|
|
14
|
+
replayed, so header-reading scripts (Nervos DAO) match.
|
|
15
|
+
- Only complete ckb-debugger result lines are trusted, cross-checked with its exit code.
|
|
16
|
+
- `report`, `diff` and `mock` subcommands; swap a cell dep's binary for a fresh build
|
|
17
|
+
before replaying; name your own scripts with `--name`.
|
|
18
|
+
- `flame`: per-group flamegraphs from ckb-debugger's profiler (SVG + folded
|
|
19
|
+
stacks, costliest functions printed); `--bin` swaps in an unstripped build and
|
|
20
|
+
checks its cycles against the deployed binary's.
|
|
21
|
+
- Exit codes: 0 every script accepts and the sum matches the node; 1 a script
|
|
22
|
+
rejects or the sum differs; 2 a usage or environment error.
|
|
23
|
+
|
|
24
|
+
### Library
|
|
25
|
+
- `.` (analysis), `./analyze`, `./replay` and `./flame` (pure, work in the browser), `./wasm`
|
|
26
|
+
(ckb-debugger's WebAssembly build, in memory, same numbers as native).
|
|
27
|
+
|
|
28
|
+
### GitHub Action
|
|
29
|
+
- `action/`: posts one sticky cycle report on a pull request, group by group against
|
|
30
|
+
the base branch; checksums the ckb-debugger it installs; fails on a broken base.
|
|
31
|
+
- Function-level costs in the report: a binary's `symbols` build and `"functions": true`
|
|
32
|
+
in cycles.json record each group's costliest functions (checked against the binary's
|
|
33
|
+
cycles), and the comment folds in which functions changed.
|
|
34
|
+
- Hardened for untrusted pull requests: `report --root` keeps the files a PR's
|
|
35
|
+
cycles.json names inside the checkout; names in the comment cannot mention,
|
|
36
|
+
link or break the table; the comment always fits GitHub's size limit.
|
|
37
|
+
|
|
38
|
+
### Web inspector
|
|
39
|
+
- ckb-cycle-tools.vercel.app: paste a transaction hash, see its scripts and the
|
|
40
|
+
per-group cycles computed in the page.
|
|
41
|
+
|
|
42
|
+
### Benchmark
|
|
43
|
+
- The session lock in Rust vs ckb-js-vm, rebuilt and rerun in CI: the current lock
|
|
44
|
+
(ckb-session-kit 49227cd, plain CKB and token sessions, codes 10-20), 58 scenarios.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Luong Thanh Tung
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,394 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# ckb-cycle-tools
|
|
2
|
+
|
|
3
|
+
Cycle measurement for CKB on-chain scripts.
|
|
4
|
+
|
|
5
|
+
**Live demo:** [ckb-cycle-tools.vercel.app](https://ckb-cycle-tools.vercel.app/) — paste a testnet tx hash, see cycles and script groups (CKB testnet).
|
|
6
|
+
|
|
7
|
+
**Status: v1.0.** Built in the open during my CKBuilder programme.
|
|
8
|
+
|
|
9
|
+
| When | Milestone |
|
|
10
|
+
|---|---|
|
|
11
|
+
| w/c 5 Oct 2026 | ✅ Scaffold, CI, the Windows `ckb-debugger` shim fix |
|
|
12
|
+
| w/c 12 Oct | ✅ CLI: per-script cycle table for a transaction |
|
|
13
|
+
| w/c 19 Oct | ✅ Failure-path profiling; ✅ CI on Linux and Windows |
|
|
14
|
+
| w/c 26 Oct | ✅ ckb-js-vm vs Rust comparison harness |
|
|
15
|
+
| w/c 2 Nov | v1.0 on npm |
|
|
16
|
+
|
|
17
|
+
## The problem
|
|
18
|
+
|
|
19
|
+
Every CKB script consumes cycles, and cycles are a hard limit rather than a
|
|
20
|
+
suggestion. But finding out how many a script uses — and *which part* of it is
|
|
21
|
+
expensive — currently means driving `ckb-debugger` by hand and reading raw output.
|
|
22
|
+
|
|
23
|
+
There is no convenient way to answer the two questions people actually have:
|
|
24
|
+
|
|
25
|
+
1. How many cycles does this script use, on the transactions it will really see?
|
|
26
|
+
2. Which implementation is cheaper, and by how much?
|
|
27
|
+
|
|
28
|
+
## What this is meant to be
|
|
29
|
+
|
|
30
|
+
- A **cycle profiler** that reports usage per script for a given transaction,
|
|
31
|
+
including the failure paths rather than only the happy one.
|
|
32
|
+
- A **comparison harness** that runs the *same* assertion set against two
|
|
33
|
+
implementations — ckb-js-vm and native Rust — and reports both, so the comparison
|
|
34
|
+
is like-for-like instead of anecdotal.
|
|
35
|
+
- The **Windows toolchain fixes** from my Week 1 findings: `ckb-testtool` cannot find
|
|
36
|
+
the `ckb-debugger` that offckb installs, because a `.cmd` shim is invisible to a
|
|
37
|
+
bare-name `child_process` spawn. That blocks every contract test on Windows, and
|
|
38
|
+
the workaround should not have to be rediscovered by everyone who hits it.
|
|
39
|
+
|
|
40
|
+
## Try it
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm install
|
|
44
|
+
npm test # unit tests, no network needed
|
|
45
|
+
npm run demo # the Next.js web demo at http://localhost:3000
|
|
46
|
+
npm run analyze:testnet -- <tx hash> [<tx hash> …]
|
|
47
|
+
npm run cycles -- <tx hash> # per-group cycles via ckb-debugger
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The demo takes a CKB testnet transaction hash and shows the total cycles the node
|
|
51
|
+
spent verifying it, and every **script group** that ran. CKB runs each script once
|
|
52
|
+
per group: input locks grouped by lock script, type scripts grouped across inputs and
|
|
53
|
+
outputs. Output locks never run. Links are shareable: `?tx=<hash>`.
|
|
54
|
+
|
|
55
|
+
### What it already shows
|
|
56
|
+
|
|
57
|
+
Real testnet transactions from my CKBuilder work:
|
|
58
|
+
|
|
59
|
+
| Transaction | Cycles | Script groups |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| [Plain CKB transfer](https://testnet.explorer.nervos.org/transaction/0x52a1b3ba45a28614c30ddc52f0795c164141abbebd1558e6c69fb0ac45fada50) | 1,657,727 | 1 lock |
|
|
62
|
+
| [Counter Type Script update (ckb-js-vm)](https://testnet.explorer.nervos.org/transaction/0x64f695a23416d9a7b2d34bb7025140c90991b82e9f1dea98e103bc13a72b77ac) | 15,675,038 | 1 lock + 1 type |
|
|
63
|
+
| [Script deployment with Type ID](https://testnet.explorer.nervos.org/transaction/0xa21da18ff3f142127cf63d6e705d64c14577fb99a9a0cbf74f47fb70b6ad66cf) | 2,607,561 | 1 lock + Type ID |
|
|
64
|
+
|
|
65
|
+
The counter's type script, running on ckb-js-vm, costs roughly ten times a standard
|
|
66
|
+
lock. Which part of that is the JavaScript VM and which is the script itself is what
|
|
67
|
+
the per-group breakdown (the CLI, below) and the ckb-js-vm vs Rust harness are for.
|
|
68
|
+
|
|
69
|
+
## Per-script cycles: the `ckb-cycles` CLI
|
|
70
|
+
|
|
71
|
+
The web demo shows the total the node reports. The CLI goes further: it rebuilds
|
|
72
|
+
the transaction as a ckb-debugger mock transaction (every input cell, every cell
|
|
73
|
+
dep, dep groups expanded), runs `ckb-debugger` once per script group, and checks
|
|
74
|
+
that the groups add up to exactly what the node reported.
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
$ npm run cycles -- 0x64f695a23416d9a7b2d34bb7025140c90991b82e9f1dea98e103bc13a72b77ac
|
|
78
|
+
|
|
79
|
+
GROUP SCRIPT RUN AT RESULT CYCLES SHARE
|
|
80
|
+
lock Secp256k1Blake160 input.0.lock ok 1,652,198 10.5%
|
|
81
|
+
type 0x3e9b6b…18bed7 input.0.type ok 14,022,840 89.5%
|
|
82
|
+
|
|
83
|
+
measured (sum of groups) 15,675,038
|
|
84
|
+
reported by node 15,675,038 ✓ match
|
|
85
|
+
ckb-debugger 1.1.1 · testnet · https://testnet.ckb.dev/
|
|
86
|
+
|
|
87
|
+
input.0.type logged:
|
|
88
|
+
[DEBUG] counter: 1 input(s) -> 1 output(s)
|
|
89
|
+
[DEBUG] counter incremented 2 -> 3
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
So in that transaction, **89.5% of the cost is the counter Type Script running on
|
|
93
|
+
ckb-js-vm**. Type ID is verified natively by the node and cannot run in
|
|
94
|
+
ckb-debugger; the CLI charges it the node's fixed `TYPE_ID_CYCLES` (1,000,000), and
|
|
95
|
+
the totals still match exactly.
|
|
96
|
+
|
|
97
|
+
**Header-reading scripts replay too.** Each input cell carries the block it was
|
|
98
|
+
created in, so a script that reads its input's header (as a Nervos DAO withdrawal
|
|
99
|
+
does) sees what it saw on the node, as long as the transaction lists that block in
|
|
100
|
+
`header_deps`, which the node requires as well. Before this, a
|
|
101
|
+
[DAO withdrawal](https://testnet.explorer.nervos.org/transaction/0xe8776bb8eb039365be9679cd61870cdc7ea3c24e4f2164fdd5d5f103bdfa2cc5)
|
|
102
|
+
replayed with NervosDao exiting 2 (header missing) and a total 8,058 cycles short;
|
|
103
|
+
it now matches the node's 1,776,369 exactly, and CI checks it.
|
|
104
|
+
|
|
105
|
+
The replay is exact for what a script can observe through syscalls: cells, data,
|
|
106
|
+
witnesses, headers. **Older transactions replay on the VM they ran on:** a
|
|
107
|
+
`hash_type: "type"` script runs on the CKB-VM version of its block's epoch (v0
|
|
108
|
+
before Mirana, v1 before Meepo, v2 since), so a 2023 testnet transaction matches
|
|
109
|
+
the node only on v1, and the CLI picks it from the block. The hardfork epochs come
|
|
110
|
+
from the node it asks (`get_consensus`), never from a flag: `--rpc` with a mainnet
|
|
111
|
+
node gives mainnet's schedule with or without `--mainnet`, and `--mainnet` with a
|
|
112
|
+
node that serves another chain stops with an error. The output ends with the
|
|
113
|
+
ckb-debugger version, that VM version, the network and the node used, so a result
|
|
114
|
+
can be reproduced.
|
|
115
|
+
|
|
116
|
+
Some public nodes report `0x0` cycles for older blocks; the CLI then says the node
|
|
117
|
+
did not record them instead of claiming a mismatch (`--rpc` another node to
|
|
118
|
+
compare). A script that faults in the VM (invalid instruction, cycle limit) shows
|
|
119
|
+
as a rejection with the VM's message, Type ID is checked as the node checks it,
|
|
120
|
+
and a script's logs can neither fake its result nor send control characters to
|
|
121
|
+
your terminal: only ckb-debugger's final lines are read, they must agree with its
|
|
122
|
+
exit code, and a run that prints more than 64 MB is an error, never parsed.
|
|
123
|
+
|
|
124
|
+
Exit codes: **0** every script accepts (and the sum matches the node's); **1** a
|
|
125
|
+
script rejects, or the sum differs from the node's; **2** a usage or environment
|
|
126
|
+
error: bad arguments, a node that cannot be reached or does not answer within
|
|
127
|
+
`--timeout` (default 30 s), a transaction the node does not have (or rejected),
|
|
128
|
+
ckb-debugger missing or printing something it cannot read. So `test $? = 1`
|
|
129
|
+
asserts a rejection without passing when the node is down. CI runs the CLI against
|
|
130
|
+
live testnet transactions on a clean machine. `--json` for machine output,
|
|
131
|
+
`--mainnet` or `--rpc <url>` for another node (at most 16 requests in flight).
|
|
132
|
+
Your own scripts show as a short code
|
|
133
|
+
hash; name them with `--name <code-hash>=<label>` (repeatable, optionally
|
|
134
|
+
`<code-hash>:<hash-type>=…`), or `profileTransaction(tx, { scriptNames })` from code.
|
|
135
|
+
The web page does the same: click a script for its full code hash and a name box
|
|
136
|
+
(saved in that browser), and it prints the CLI command for the per-group breakdown
|
|
137
|
+
with those names filled in. ckb-debugger is found the same way
|
|
138
|
+
as everywhere else in this repo (see the Windows fix above).
|
|
139
|
+
|
|
140
|
+
### In the browser: per-group cycles on the web page
|
|
141
|
+
|
|
142
|
+
The page's **per-group cycles** button runs the same replay without installing
|
|
143
|
+
anything: ckb-debugger's WebAssembly build (0.200.1, shipped in `ckb-testtool`)
|
|
144
|
+
runs in a Web Worker through a WASI shim, with the mock transaction as an
|
|
145
|
+
in-memory file. It downloads ~4 MB (about 1.1 MB compressed) only when pressed,
|
|
146
|
+
then shows each group's result, cycles, share and logs, and whether the total
|
|
147
|
+
matches the node. It gives the same numbers as the native ckb-debugger 1.1.1:
|
|
148
|
+
15,675,038 (counter), 2,607,561 (Type ID deploy) and 1,787,335 (a 2023, VM v1
|
|
149
|
+
transaction), and `test/wasm.test.ts` checks that offline on recorded transactions.
|
|
150
|
+
From code: `wasmRunner(module, tx)` from `ckb-cycle-tools/wasm` plugs into
|
|
151
|
+
`replayGroups` from `ckb-cycle-tools/replay`, neither of which uses Node built-ins.
|
|
152
|
+
|
|
153
|
+
### Before you send: the failure path
|
|
154
|
+
|
|
155
|
+
`--file` profiles a transaction that is not on chain — one you are about to send,
|
|
156
|
+
or one the node rejected — and shows which script refuses it, with its exit code
|
|
157
|
+
and what it cost to get there. It reads the node's RPC JSON, a `get_transaction`
|
|
158
|
+
result, or a CCC transaction saved with `ccc.stringify(tx)`.
|
|
159
|
+
|
|
160
|
+
Here a real [session-lock spend](https://testnet.explorer.nervos.org/transaction/0x48b3bde2a50bb8ba3aff0800e850b2aa521793b35628d165eab7f22f984be828)
|
|
161
|
+
of exactly its 100 CKB limit, edited to pay one shannon more
|
|
162
|
+
([`test/fixtures/session-lock-overspend.json`](test/fixtures/session-lock-overspend.json)):
|
|
163
|
+
|
|
164
|
+
```
|
|
165
|
+
$ npx ckb-cycles --file session-lock-overspend.json
|
|
166
|
+
tx not on chain
|
|
167
|
+
|
|
168
|
+
GROUP SCRIPT RUN AT RESULT CYCLES SHARE
|
|
169
|
+
lock 0x1ae8b8…26bc20 input.0.lock exit 12 12,893 0.8%
|
|
170
|
+
lock Secp256k1Blake160 input.1.lock exit -31 1,642,194 99.2%
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The session lock refuses with its code 12 (outflow over `max_per_tx`) after
|
|
174
|
+
12,893 cycles; the secp256k1 lock fails too, because the edit invalidated the
|
|
175
|
+
signature. CI replays this file and requires exactly that refusal.
|
|
176
|
+
|
|
177
|
+
In code: `profileTransaction(readTransactionJson(json))`, or pass an RPC-shaped
|
|
178
|
+
transaction object directly.
|
|
179
|
+
|
|
180
|
+
### Inside a script: flamegraphs
|
|
181
|
+
|
|
182
|
+
`ckb-cycles flame` shows where inside each script the cycles go. It runs every
|
|
183
|
+
script group in ckb-debugger's flamegraph mode, merges the stacks, names the
|
|
184
|
+
frames by function, prints the costliest ones and writes an SVG flamegraph and
|
|
185
|
+
a folded-stack file per group (open the `.folded` in
|
|
186
|
+
[speedscope](https://www.speedscope.app/) for an interactive view).
|
|
187
|
+
|
|
188
|
+
Deployed scripts are stripped, so a profile of one is a single frame. Give an
|
|
189
|
+
unstripped build of the same code with `--bin <code-hash>=<elf>`; the tool runs
|
|
190
|
+
the group with both binaries and says whether the cycles agree, so you know the
|
|
191
|
+
graph describes the deployed code. Here, a real
|
|
192
|
+
[subscription charge](https://testnet.explorer.nervos.org/transaction/0x50ae6df49d411a5766da1c9717da9e6ff34670194b389779f717fcee71a03092)
|
|
193
|
+
of the ckb-session-kit lock, with that lock built with symbols
|
|
194
|
+
(`CARGO_PROFILE_RELEASE_STRIP=false cargo build --release`):
|
|
195
|
+
|
|
196
|
+
```
|
|
197
|
+
$ npx ckb-cycles flame 0x50ae6df4…a03092 --script input.0.lock \
|
|
198
|
+
--bin 0xab419466…4c08ce=target/riscv64imac-unknown-none-elf/release/session-lock
|
|
199
|
+
input.0.lock 0xab4194…4c08ce ok 20,999 cycles
|
|
200
|
+
--bin …/session-lock: same cycles as the deployed binary
|
|
201
|
+
profiled 19,187 cycles (loading the binary is not profiled)
|
|
202
|
+
SELF TOTAL FUNCTION
|
|
203
|
+
4,490 5,972 session_lock::lock_hash
|
|
204
|
+
3,145 3,145 compiler_builtins::mem::memcpy
|
|
205
|
+
2,545 18,678 __ckb_std_main
|
|
206
|
+
2,156 2,156 session_lock::has_type
|
|
207
|
+
2,076 2,076 memcmp
|
|
208
|
+
→ flame/input.0.lock.svg, flame/input.0.lock.folded
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Reading the lock hashes of the transaction's cells is the lock's largest cost.
|
|
212
|
+
The profile covers the script's run; loading the binary into the VM (1,812
|
|
213
|
+
cycles here) is counted by the node but not by the profiler.
|
|
214
|
+
|
|
215
|
+
**In the browser:** drop the `.folded` file on the
|
|
216
|
+
[web inspector](https://ckb-cycle-tools.vercel.app/) ("inside a script"), or open
|
|
217
|
+
its example, and it draws the same flamegraph and table. Nothing is uploaded.
|
|
218
|
+
(The page's WebAssembly ckb-debugger can profile but not name functions, so the
|
|
219
|
+
profile itself comes from the CLI.)
|
|
220
|
+
|
|
221
|
+
In code: `flameTransaction(target, { bins, readFile })`, then `functionCosts`,
|
|
222
|
+
`flameTree` and `renderFlameSvg` from `ckb-cycle-tools/flame` (no Node
|
|
223
|
+
built-ins, so the browser can draw the same graph).
|
|
224
|
+
|
|
225
|
+
## Cycle reports on pull requests
|
|
226
|
+
|
|
227
|
+
A change to a script should say what it did to that script's cycles, and above
|
|
228
|
+
all whether any accept turned into a reject. `ckb-cycles report` replays every
|
|
229
|
+
scenario in a [`cycles.json`](cycles.json) and records each script group's result
|
|
230
|
+
and cycles; `ckb-cycles diff` compares two such reports; the
|
|
231
|
+
[GitHub Action](action/README.md) runs both on a PR (the PR's build against its
|
|
232
|
+
base's) and keeps one comment up to date.
|
|
233
|
+
|
|
234
|
+
Scenarios are best kept as ckb-debugger mock transactions, so CI needs no node:
|
|
235
|
+
this repo's five are written by `benchmarks/session-lock/mocks.mjs`, and
|
|
236
|
+
`ckb-cycles mock <tx-hash> -o file.json` saves any transaction that way.
|
|
237
|
+
`binaries` swaps the deployed code for the one just built (the rules for
|
|
238
|
+
`type` vs `data*` hash types are in the [Action's README](action/README.md#cyclesjson)).
|
|
239
|
+
|
|
240
|
+
Here the ckb-js-vm session lock was changed to allow one shannon more than its
|
|
241
|
+
limit and to do extra work per recipient check:
|
|
242
|
+
|
|
243
|
+
```
|
|
244
|
+
$ npx ckb-cycles report cycles.json --json base.json
|
|
245
|
+
$ npx ckb-cycles report cycles.json --binaries-from ../pr --json head.json
|
|
246
|
+
$ npx ckb-cycles diff base.json head.json --fail-above 1
|
|
247
|
+
1 result change, 1 over the 1% threshold, 5 of 10 script groups changed
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
| Scenario | Group | Script | Base | Head | Δ | Δ% | |
|
|
251
|
+
|---|---|---|---:|---:|---:|---:|---|
|
|
252
|
+
| one shannon over max\_per\_tx | `input.0.lock` | session-lock (ckb-js-vm) | 14,544,014 (exit 12) | 14,557,318 | +13,304 | +0.09% | **RESULT CHANGED: exit 12 → ok** |
|
|
253
|
+
| pays the allowed recipient | `input.0.lock` | session-lock (ckb-js-vm) | 14,768,645 | 15,465,881 | +697,236 | +4.72% | **over 1%** |
|
|
254
|
+
| spend exactly max\_per\_tx | `input.0.lock` | session-lock (ckb-js-vm) | 14,544,018 | 14,557,320 | +13,302 | +0.09% | |
|
|
255
|
+
|
|
256
|
+
That table (with `--markdown`) is what the PR comment shows; unchanged groups
|
|
257
|
+
fold away below it. This repo runs the Action on its own pull requests
|
|
258
|
+
([`.github/workflows/cycle-report.yml`](.github/workflows/cycle-report.yml)).
|
|
259
|
+
|
|
260
|
+
### Which functions changed
|
|
261
|
+
|
|
262
|
+
A row says a group got 3% dearer; the flamegraph mode can say where. Give a
|
|
263
|
+
binary an unstripped build of the same code as `symbols`, and ask for
|
|
264
|
+
`functions`, for every scenario or per scenario:
|
|
265
|
+
|
|
266
|
+
```json
|
|
267
|
+
{
|
|
268
|
+
"functions": true,
|
|
269
|
+
"binaries": {
|
|
270
|
+
"my-lock": {
|
|
271
|
+
"path": "build/release/my-lock",
|
|
272
|
+
"symbols": "build/release/my-lock.debug",
|
|
273
|
+
"codeHash": "0x…"
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
"scenarios": [{ "name": "spend", "mock": "tests/mocks/spend.json" }]
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
For each group whose script is that binary, `report` runs the group again in
|
|
281
|
+
ckb-debugger's flamegraph mode with `--bin <symbols>` and records the 15
|
|
282
|
+
costliest functions (self and total cycles) in the report. It first checks that
|
|
283
|
+
the symbols build costs exactly the cycles of the binary it stands for; if not,
|
|
284
|
+
it is not the same code, and the group gets a warning instead of functions.
|
|
285
|
+
`diff --markdown` then adds a folded block under the table for each changed
|
|
286
|
+
group: the functions whose self cycles changed, base, head and Δ, the ten
|
|
287
|
+
largest changes first. A report without functions (an older base, or a
|
|
288
|
+
config without `symbols`) still diffs as before; a function shows `—` where
|
|
289
|
+
its cycles are not known on that side.
|
|
290
|
+
|
|
291
|
+
A Rust build keeps its symbols with `CARGO_PROFILE_RELEASE_STRIP=false`; build
|
|
292
|
+
it next to the stripped one, from the same commit.
|
|
293
|
+
|
|
294
|
+
## ckb-js-vm vs Rust: one lock, two implementations
|
|
295
|
+
|
|
296
|
+
`benchmarks/session-lock` holds a TypeScript port of the
|
|
297
|
+
[ckb-session-kit](https://github.com/luongthanhtung03/ckb-session-kit) session lock
|
|
298
|
+
for ckb-js-vm, plain CKB and token sessions (error codes 10-20). It runs the same
|
|
299
|
+
58 scenarios as the Rust original (ckb-session-kit 49227cd) in the real CKB-VM and
|
|
300
|
+
fails unless both implementations make every accept/reject decision correctly.
|
|
301
|
+
|
|
302
|
+
| | Rust | ckb-js-vm |
|
|
303
|
+
|---|---:|---:|
|
|
304
|
+
| Mean cycles, accepted plain CKB spends | 14,758 | 15,037,968 |
|
|
305
|
+
| Mean cycles, accepted token spends | 20,348 | 15,518,698 |
|
|
306
|
+
| Cheapest run (start-up cost) | 3,145 | 14,272,805 |
|
|
307
|
+
|
|
308
|
+
About 95% of the ckb-js-vm cost is starting the VM; the lock's own logic runs at
|
|
309
|
+
roughly 66× the Rust logic. Full table, and the 8 Oct numbers for comparison:
|
|
310
|
+
[RESULTS.md](benchmarks/session-lock/RESULTS.md).
|
|
311
|
+
|
|
312
|
+
```bash
|
|
313
|
+
npm run bench:session-lock # needs the Rust lock built in ../ckb-session-kit, or SESSION_LOCK_BIN
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
CI rebuilds both implementations from source — the Rust lock from a pinned
|
|
317
|
+
ckb-session-kit commit — reruns every scenario, and publishes the table in the
|
|
318
|
+
job summary.
|
|
319
|
+
|
|
320
|
+
## Limits
|
|
321
|
+
|
|
322
|
+
- **It needs a node, or a saved transaction.** Rebuilding a transaction means
|
|
323
|
+
fetching every input cell and cell dep; without RPC access, use a mock file
|
|
324
|
+
(`ckb-cycles mock` saves one) or `--file`.
|
|
325
|
+
- **Type ID is charged, not run.** The node verifies Type ID natively; the tools
|
|
326
|
+
charge its fixed 1,000,000 cycles and check its rules the way the node does.
|
|
327
|
+
- **Two debugger builds.** The CLI uses the native ckb-debugger you install
|
|
328
|
+
(1.1.1 here); the web page uses the WebAssembly build shipped in
|
|
329
|
+
`ckb-testtool` (0.200.1). They agree on every transaction checked, but a
|
|
330
|
+
future CKB-VM change could reach one before the other; each result names the
|
|
331
|
+
version it used.
|
|
332
|
+
- **Flamegraphs need symbols.** On-chain binaries are stripped; `flame` names
|
|
333
|
+
functions only with an unstripped build passed by `--bin` (or `symbols` in a
|
|
334
|
+
cycles.json). The CLI draws the graphs, the PR comment lists the changed
|
|
335
|
+
functions, and the web page draws a `.folded` file the CLI made.
|
|
336
|
+
- **Older blocks.** Some public nodes report `0x0` cycles for old blocks; the
|
|
337
|
+
tools then say the total is unknown instead of claiming a match.
|
|
338
|
+
- **The PR Action has not yet commented on a real pull request.** Every step is
|
|
339
|
+
covered by tests and was run locally end to end; the first public run will be
|
|
340
|
+
linked here.
|
|
341
|
+
|
|
342
|
+
## Why it is a separate repository
|
|
343
|
+
|
|
344
|
+
It started as measurement scaffolding inside a learning exercise. That is a bad place
|
|
345
|
+
for a tool to live if anyone else might want it.
|
|
346
|
+
|
|
347
|
+
## Related work
|
|
348
|
+
|
|
349
|
+
Other CKB tools touch the same ground. This is what each one does, as far as its
|
|
350
|
+
own documentation says, and where this repository sits next to it.
|
|
351
|
+
|
|
352
|
+
- **[ckb-debugger](https://github.com/nervosnetwork/ckb-standalone-debugger)**
|
|
353
|
+
(nervosnetwork) runs CKB scripts off chain from a mock transaction and reports
|
|
354
|
+
their cycles, with a flamegraph mode. It is the engine everything here drives;
|
|
355
|
+
nothing in this repository re-implements the VM. What is added on top: rebuilding
|
|
356
|
+
a mock transaction from a tx hash or a saved transaction, one run per script
|
|
357
|
+
group with totals checked against the node, picking the VM version from the
|
|
358
|
+
block, Type ID charged as the node charges it, named flamegraphs checked against
|
|
359
|
+
the deployed binary, report diffs, and the PR Action.
|
|
360
|
+
- **[ckb-devnet-explorer](https://github.com/wildanrhmn/ckb-devnet-explorer)** is a
|
|
361
|
+
lightweight explorer for OffCKB devnets that reads the node directly. It names
|
|
362
|
+
genesis and project-deployed scripts (including JS contracts on ckb-js-vm),
|
|
363
|
+
decodes cells such as DAO, xUDT, Spore and Type ID, and shows each transaction's
|
|
364
|
+
fee, size and cycles. It answers "what is in this transaction"; cycle-tools
|
|
365
|
+
answers "which script spent the cycles, and why", on testnet and mainnet as well.
|
|
366
|
+
The two fit together: a devnet transaction can be saved with `ckb-cycles mock`
|
|
367
|
+
and profiled here.
|
|
368
|
+
- **[CKB Contract Flow](https://talk.nervos.org/t/ckb-contract-flow-visual-cell-transition-explainers-on-chain-tx-decoder-for-46-ckb-contracts/11014)**
|
|
369
|
+
([repo](https://github.com/gpBlockchain/ckb-contract-flow-html)) explains the
|
|
370
|
+
cell transition rules of 46 contracts as visual pages, and its decoder splits a
|
|
371
|
+
testnet or mainnet transaction into script groups and checks each contract's
|
|
372
|
+
rules. It explains what a script requires; it does not run scripts or measure
|
|
373
|
+
cycles. Cycle-tools runs them and measures, without explaining the rules.
|
|
374
|
+
- **[CKBadger](https://talk.nervos.org/t/ckbadger-a-local-first-ckb-native-explorer-and-a-vibe-coding-experiment/10276)**
|
|
375
|
+
([repo](https://github.com/janx/ckbadger)) is a local-first explorer built around
|
|
376
|
+
the cell model, syncing from a node and showing mainnet and testnet side by side.
|
|
377
|
+
It is for browsing the chain; cycle-tools looks at one transaction at a time and
|
|
378
|
+
only at its execution cost.
|
|
379
|
+
- **[CellScript](https://github.com/CellScript-Labs/CellScript)**'s
|
|
380
|
+
[cost report](https://talk.nervos.org/t/cellscript-0-30-abstractions-bytes-and-the-cost/10732)
|
|
381
|
+
compares executable bytes and cycles of matched CellScript and hand-written Rust
|
|
382
|
+
contracts, with acceptance and rejection cases on both sides. It is a language
|
|
383
|
+
project measuring its own compiler output, and the method is close to this
|
|
384
|
+
repository's ckb-js-vm vs Rust harness. The two are complementary: a
|
|
385
|
+
`cycles.json` and the PR Action could track such pairs on every change, with
|
|
386
|
+
per-function diffs, rather than only at release time.
|
|
387
|
+
|
|
388
|
+
## Licence
|
|
389
|
+
|
|
390
|
+
MIT. See [LICENSE](LICENSE).
|
|
391
|
+
|
|
392
|
+
## Author
|
|
393
|
+
|
|
394
|
+
Luong Thanh Tung — [@luongthanhtung03](https://github.com/luongthanhtung03)
|
|
@@ -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