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/dist/elf.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Function names from an ELF symbol table, for the frames ckb-debugger's
3
+ * profiler cannot name. The profiler names a frame from the DWARF line table;
4
+ * code without line info (the `_start` that ckb-std writes in assembly, the
5
+ * allocator shims rustc generates) comes out as `func_0x<address>`. The symbol
6
+ * table of the same unstripped build still has those names. Without them, a
7
+ * function that moved between two builds shows in a diff as one address gone
8
+ * and another new. Plain TypeScript with no Node built-ins, like flame.ts.
9
+ */
10
+ /** Start address → name (demangled when it can be), of every function symbol in `.symtab`. */
11
+ export declare function elfFunctionNames(elf: Uint8Array): Map<bigint, string>;
12
+ /**
13
+ * A Rust symbol name as `crate::module::function`, for the plain paths a
14
+ * symbol table mostly holds: legacy (`_ZN…E`, hash dropped) and v0 (`_R…`).
15
+ * Anything it does not follow (generics, trait impls) comes back unchanged:
16
+ * still a stable name, only a less readable one.
17
+ */
18
+ export declare function demangle(name: string): string;
package/dist/elf.js ADDED
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Function names from an ELF symbol table, for the frames ckb-debugger's
3
+ * profiler cannot name. The profiler names a frame from the DWARF line table;
4
+ * code without line info (the `_start` that ckb-std writes in assembly, the
5
+ * allocator shims rustc generates) comes out as `func_0x<address>`. The symbol
6
+ * table of the same unstripped build still has those names. Without them, a
7
+ * function that moved between two builds shows in a diff as one address gone
8
+ * and another new. Plain TypeScript with no Node built-ins, like flame.ts.
9
+ */
10
+ /** `__text_start`, `__init_array_end`, `_etext`, `_stext`, `end` and the like: labels, not functions. */
11
+ const LINKER_MARKER = /^(__\w*_(start|end)|_?_?(etext|edata|end|stext|ftext)|__executable_start|__ehdr_start|__global_pointer\$)$/;
12
+ /** Start address → name (demangled when it can be), of every function symbol in `.symtab`. */
13
+ export function elfFunctionNames(elf) {
14
+ const names = new Map();
15
+ // ELF64 little-endian only: what a CKB script is (RISC-V 64).
16
+ if (elf.length < 64 || elf[0] !== 0x7f || elf[1] !== 0x45 || elf[2] !== 0x4c || elf[3] !== 0x46)
17
+ return names;
18
+ if (elf[4] !== 2 || elf[5] !== 1)
19
+ return names;
20
+ const view = new DataView(elf.buffer, elf.byteOffset, elf.byteLength);
21
+ const u16 = (o) => view.getUint16(o, true);
22
+ const u32 = (o) => view.getUint32(o, true);
23
+ const u64 = (o) => view.getBigUint64(o, true);
24
+ const inside = (o, n) => o >= 0 && n >= 0 && o + n <= elf.length;
25
+ const shoff = Number(u64(0x28));
26
+ const shentsize = u16(0x3a);
27
+ const shnum = u16(0x3c);
28
+ if (shentsize < 64 || !inside(shoff, shentsize * shnum))
29
+ return names;
30
+ const section = (i) => {
31
+ const o = shoff + i * shentsize;
32
+ return { type: u32(o + 4), flags: u64(o + 8), offset: Number(u64(o + 0x18)), size: Number(u64(o + 0x20)), link: u32(o + 0x28), entsize: Number(u64(o + 0x38)) };
33
+ };
34
+ const SHT_SYMTAB = 2;
35
+ const SHF_EXECINSTR = 0x4n;
36
+ // SHN_LORESERVE and up: SHN_ABS, SHN_COMMON, SHN_XINDEX. Not an address in code.
37
+ const SHN_LORESERVE = 0xff00;
38
+ const inCode = (shndx) => shndx < shnum && (section(shndx).flags & SHF_EXECINSTR) !== 0n;
39
+ for (let i = 0; i < shnum; i++) {
40
+ const symtab = section(i);
41
+ if (symtab.type !== SHT_SYMTAB || symtab.entsize < 24 || !inside(symtab.offset, symtab.size))
42
+ continue;
43
+ if (symtab.link >= shnum)
44
+ continue;
45
+ const strtab = section(symtab.link);
46
+ if (!inside(strtab.offset, strtab.size))
47
+ continue;
48
+ const decoder = new TextDecoder();
49
+ for (let o = symtab.offset; o + symtab.entsize <= symtab.offset + symtab.size; o += symtab.entsize) {
50
+ const nameOff = u32(o);
51
+ const info = elf[o + 4];
52
+ const shndx = u16(o + 6);
53
+ const value = u64(o + 8);
54
+ const type = info & 0xf;
55
+ // STT_FUNC, or STT_NOTYPE for a global label in assembly (`_start`) in an
56
+ // executable section, defined in a real section (not SHN_UNDEF or SHN_ABS).
57
+ if (!(type === 2 || (type === 0 && info >> 4 !== 0)) || shndx === 0 || shndx >= SHN_LORESERVE || nameOff === 0 || nameOff >= strtab.size)
58
+ continue;
59
+ if (type === 0 && !inCode(shndx))
60
+ continue;
61
+ let end = strtab.offset + nameOff;
62
+ while (end < strtab.offset + strtab.size && elf[end] !== 0)
63
+ end++;
64
+ const raw = decoder.decode(elf.subarray(strtab.offset + nameOff, end));
65
+ if (!raw || raw.startsWith("$") || raw.startsWith(".L"))
66
+ continue;
67
+ // Section bounds the linker or a linker script defines; one can sit at `_start`'s address.
68
+ if (type === 0 && LINKER_MARKER.test(raw))
69
+ continue;
70
+ // A function and a label at the same address: the function's name wins.
71
+ if (type === 2 || !names.has(value))
72
+ names.set(value, demangle(raw));
73
+ }
74
+ }
75
+ return names;
76
+ }
77
+ /**
78
+ * A Rust symbol name as `crate::module::function`, for the plain paths a
79
+ * symbol table mostly holds: legacy (`_ZN…E`, hash dropped) and v0 (`_R…`).
80
+ * Anything it does not follow (generics, trait impls) comes back unchanged:
81
+ * still a stable name, only a less readable one.
82
+ */
83
+ export function demangle(name) {
84
+ if (name.startsWith("_ZN"))
85
+ return demangleLegacy(name) ?? name;
86
+ if (name.startsWith("_R"))
87
+ return demangleV0(name) ?? name;
88
+ return name;
89
+ }
90
+ function demangleLegacy(name) {
91
+ const parts = [];
92
+ let i = 3;
93
+ while (i < name.length && name[i] !== "E") {
94
+ const m = /^\d+/.exec(name.slice(i));
95
+ if (!m)
96
+ return undefined;
97
+ const len = Number(m[0]);
98
+ i += m[0].length;
99
+ if (i + len > name.length)
100
+ return undefined;
101
+ parts.push(name.slice(i, i + len));
102
+ i += len;
103
+ }
104
+ if (name[i] !== "E" || !parts.length)
105
+ return undefined;
106
+ if (parts.length > 1 && /^h[0-9a-f]{16}$/.test(parts[parts.length - 1]))
107
+ parts.pop();
108
+ const out = [];
109
+ for (const p of parts) {
110
+ const s = unescapeLegacy(p);
111
+ if (s === undefined)
112
+ return undefined;
113
+ out.push(s);
114
+ }
115
+ return out.join("::");
116
+ }
117
+ const LEGACY_ESCAPES = { SP: "@", BP: "*", RF: "&", LT: "<", GT: ">", LP: "(", RP: ")", C: "," };
118
+ /** One legacy path element: `$RF$`, `$u7b$` and the rest decoded, `..` as `::`. Undefined on an escape it does not know. */
119
+ function unescapeLegacy(part) {
120
+ // An element that would start with `$` is written `_$`.
121
+ let s = part.startsWith("_$") ? part.slice(1) : part;
122
+ let out = "";
123
+ while (s) {
124
+ if (s.startsWith("..")) {
125
+ out += "::";
126
+ s = s.slice(2);
127
+ }
128
+ else if (s[0] === "$") {
129
+ const end = s.indexOf("$", 1);
130
+ if (end < 0)
131
+ return undefined;
132
+ const esc = s.slice(1, end);
133
+ const code = /^u[0-9a-f]{1,6}$/.test(esc) ? parseInt(esc.slice(1), 16) : -1;
134
+ const ch = LEGACY_ESCAPES[esc] ?? (code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : undefined);
135
+ if (ch === undefined)
136
+ return undefined;
137
+ out += ch;
138
+ s = s.slice(end + 1);
139
+ }
140
+ else {
141
+ const m = /^[^$.]+|^\./.exec(s);
142
+ out += m[0];
143
+ s = s.slice(m[0].length);
144
+ }
145
+ }
146
+ return out;
147
+ }
148
+ function demangleV0(name) {
149
+ let i = 2;
150
+ const peek = () => name[i];
151
+ // `s<base62>_`: a disambiguator, not part of the name.
152
+ const skipDisambiguator = () => {
153
+ if (peek() !== "s")
154
+ return true;
155
+ const end = name.indexOf("_", i);
156
+ if (end < 0)
157
+ return false;
158
+ i = end + 1;
159
+ return true;
160
+ };
161
+ const ident = () => {
162
+ if (!skipDisambiguator())
163
+ return undefined;
164
+ if (peek() === "u")
165
+ return undefined; // punycode: leave it to a real demangler
166
+ const m = /^\d+/.exec(name.slice(i));
167
+ if (!m)
168
+ return undefined;
169
+ const len = Number(m[0]);
170
+ i += m[0].length;
171
+ if (peek() === "_")
172
+ i++;
173
+ if (i + len > name.length)
174
+ return undefined;
175
+ const s = name.slice(i, i + len);
176
+ i += len;
177
+ return s;
178
+ };
179
+ const path = (depth) => {
180
+ if (depth > 64)
181
+ return undefined;
182
+ const tag = name[i++];
183
+ if (tag === "C")
184
+ return ident();
185
+ if (tag === "N") {
186
+ const ns = name[i++];
187
+ const parent = path(depth + 1);
188
+ if (parent === undefined)
189
+ return undefined;
190
+ const id = ident();
191
+ if (id === undefined)
192
+ return undefined;
193
+ if (ns === "C")
194
+ return `${parent}::{closure}`;
195
+ if (ns >= "A" && ns <= "Z")
196
+ return `${parent}::{${id || "shim"}}`;
197
+ return `${parent}::${id}`;
198
+ }
199
+ return undefined;
200
+ };
201
+ if (/^\d/.test(name.slice(i)))
202
+ return undefined; // an encoding version this does not know
203
+ const p = path(0);
204
+ if (p === undefined)
205
+ return undefined;
206
+ // What may follow the path: an instantiating crate, or a suffix LLVM added.
207
+ const rest = name.slice(i);
208
+ return rest === "" || rest.startsWith("C") || rest.startsWith(".") ? p : undefined;
209
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Flamegraphs of where a script's cycles go, from ckb-debugger's own profiler
3
+ * (`--enable-flamegraph --flamegraph-output`). ckb-debugger writes folded
4
+ * stacks, one `frame;frame;… cycles` line per sample, with the same stack on
5
+ * many lines and every frame as `<source path>:<function>`. Here they are
6
+ * merged, the paths dropped, and drawn as an SVG. Plain TypeScript with no Node
7
+ * built-ins, like replay.ts, so the browser can draw the same thing.
8
+ *
9
+ * A deployed binary is usually stripped: its whole run is one frame. Pass an
10
+ * unstripped build of the same code (`ckb-debugger --bin`) to see functions.
11
+ */
12
+ /** Stack (frames joined by `;`, outermost first) → cycles. */
13
+ export type Folded = Map<string, bigint>;
14
+ /**
15
+ * `E:\…\src\main.rs:session_lock::lock_hash` → `session_lock::lock_hash`. The
16
+ * path ends at the first `.<ext>:`; `??:func_0x114e4` (no symbols) keeps its address.
17
+ */
18
+ export declare function frameName(frame: string): string;
19
+ /**
20
+ * Splits a folded stack into frames. `;` separates frames, but Rust names hold
21
+ * it too (`[u8; 32]`), so a `;` inside brackets belongs to the name.
22
+ */
23
+ export declare function splitStack(stack: string): string[];
24
+ /** The deepest stack kept; deeper frames are folded into one. */
25
+ export declare const MAX_DEPTH = 256;
26
+ /** Parses ckb-debugger's folded output: identical stacks merged, frames named by function only. */
27
+ export declare function parseFolded(text: string): Folded;
28
+ /**
29
+ * Renames each `func_0x<address>` frame (code the profiler found no line info
30
+ * for) to the function starting at that address in `names` (elf.ts), merging
31
+ * stacks that become the same. Frames it has no name for keep their address.
32
+ */
33
+ export declare function nameAddresses(f: Folded, names: Map<bigint, string>): Folded;
34
+ export declare const foldedTotal: (f: Folded) => bigint;
35
+ /** Back to text, one merged stack per line, heaviest first: the format speedscope and inferno read. */
36
+ export declare function formatFolded(f: Folded): string;
37
+ export interface FunctionCost {
38
+ name: string;
39
+ /** Cycles spent in the function itself. */
40
+ self: bigint;
41
+ /** Cycles spent in it and everything it called (counted once per stack, so recursion is not doubled). */
42
+ total: bigint;
43
+ }
44
+ /** Every function with its self and total cycles, heaviest self first. */
45
+ export declare function functionCosts(f: Folded): FunctionCost[];
46
+ export interface FlameNode {
47
+ name: string;
48
+ value: bigint;
49
+ children: FlameNode[];
50
+ }
51
+ /** The call tree: each node's value is the cycles of every stack through it. Children heaviest first. */
52
+ export declare function flameTree(f: Folded, rootName?: string): FlameNode;
53
+ /**
54
+ * A self-contained SVG flamegraph: root at the bottom, width proportional to
55
+ * cycles, a tooltip (`<title>`) with the cycles and share on every frame.
56
+ * Frames narrower than `minWidth` pixels are left out. Colours are fixed per
57
+ * function name, so the same function looks the same in two graphs.
58
+ */
59
+ export declare function renderFlameSvg(tree: FlameNode, opts?: {
60
+ title?: string;
61
+ width?: number;
62
+ minWidth?: number;
63
+ }): string;
64
+ /** The `All cycles: N` line ckb-debugger prints in flamegraph mode: what the profile covers. */
65
+ export declare function profiledCycles(output: string): bigint | undefined;
package/dist/flame.js ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Flamegraphs of where a script's cycles go, from ckb-debugger's own profiler
3
+ * (`--enable-flamegraph --flamegraph-output`). ckb-debugger writes folded
4
+ * stacks, one `frame;frame;… cycles` line per sample, with the same stack on
5
+ * many lines and every frame as `<source path>:<function>`. Here they are
6
+ * merged, the paths dropped, and drawn as an SVG. Plain TypeScript with no Node
7
+ * built-ins, like replay.ts, so the browser can draw the same thing.
8
+ *
9
+ * A deployed binary is usually stripped: its whole run is one frame. Pass an
10
+ * unstripped build of the same code (`ckb-debugger --bin`) to see functions.
11
+ */
12
+ /**
13
+ * `E:\…\src\main.rs:session_lock::lock_hash` → `session_lock::lock_hash`. The
14
+ * path ends at the first `.<ext>:`; `??:func_0x114e4` (no symbols) keeps its address.
15
+ */
16
+ export function frameName(frame) {
17
+ const f = frame.trim();
18
+ if (f.startsWith("??:"))
19
+ return f.slice(3);
20
+ const m = /^.*?\.[A-Za-z0-9]+:(.+)$/.exec(f);
21
+ return m ? m[1] : f;
22
+ }
23
+ /**
24
+ * Splits a folded stack into frames. `;` separates frames, but Rust names hold
25
+ * it too (`[u8; 32]`), so a `;` inside brackets belongs to the name.
26
+ */
27
+ export function splitStack(stack) {
28
+ const frames = [];
29
+ let depth = 0;
30
+ let start = 0;
31
+ for (let i = 0; i < stack.length; i++) {
32
+ const c = stack[i];
33
+ if (c === "<" || c === "[" || c === "(" || c === "{")
34
+ depth++;
35
+ else if ((c === ">" || c === "]" || c === ")" || c === "}") && depth > 0)
36
+ depth--;
37
+ else if (c === ";" && depth === 0) {
38
+ frames.push(stack.slice(start, i));
39
+ start = i + 1;
40
+ }
41
+ }
42
+ frames.push(stack.slice(start));
43
+ return frames;
44
+ }
45
+ /** The deepest stack kept; deeper frames are folded into one. */
46
+ export const MAX_DEPTH = 256;
47
+ /** Parses ckb-debugger's folded output: identical stacks merged, frames named by function only. */
48
+ export function parseFolded(text) {
49
+ const folded = new Map();
50
+ for (const line of text.split(/\r?\n/)) {
51
+ const m = /^(.*\S)\s+(\d+)$/.exec(line);
52
+ if (!m)
53
+ continue;
54
+ // A real CKB script nests nowhere near this deep; a hostile file could, and
55
+ // the tree is walked recursively (review, 27 Oct). Deeper frames fold into the last.
56
+ const frames = splitStack(m[1]).map(frameName);
57
+ if (frames.length > MAX_DEPTH)
58
+ frames.splice(MAX_DEPTH - 1, frames.length, "…");
59
+ // Rejoined with ";" as the frame separator: a name's own "; " (with a space) stays inside it.
60
+ const stack = frames.join(";");
61
+ folded.set(stack, (folded.get(stack) ?? 0n) + BigInt(m[2]));
62
+ }
63
+ return folded;
64
+ }
65
+ /**
66
+ * Renames each `func_0x<address>` frame (code the profiler found no line info
67
+ * for) to the function starting at that address in `names` (elf.ts), merging
68
+ * stacks that become the same. Frames it has no name for keep their address.
69
+ */
70
+ export function nameAddresses(f, names) {
71
+ if (!names.size)
72
+ return f;
73
+ const out = new Map();
74
+ for (const [stack, v] of f) {
75
+ const renamed = splitStack(stack)
76
+ .map((frame) => {
77
+ const m = /^func_0x([0-9a-fA-F]+)$/.exec(frame);
78
+ return (m && names.get(BigInt(`0x${m[1]}`))) || frame;
79
+ })
80
+ .join(";");
81
+ out.set(renamed, (out.get(renamed) ?? 0n) + v);
82
+ }
83
+ return out;
84
+ }
85
+ export const foldedTotal = (f) => [...f.values()].reduce((s, v) => s + v, 0n);
86
+ /** Back to text, one merged stack per line, heaviest first: the format speedscope and inferno read. */
87
+ export function formatFolded(f) {
88
+ return [...f.entries()]
89
+ .sort((a, b) => (a[1] === b[1] ? (a[0] < b[0] ? -1 : 1) : a[1] > b[1] ? -1 : 1))
90
+ .map(([s, v]) => `${s} ${v}`)
91
+ .join("\n");
92
+ }
93
+ /** Every function with its self and total cycles, heaviest self first. */
94
+ export function functionCosts(f) {
95
+ const costs = new Map();
96
+ const at = (name) => costs.get(name) ?? costs.set(name, { name, self: 0n, total: 0n }).get(name);
97
+ for (const [stack, v] of f) {
98
+ const frames = splitStack(stack);
99
+ at(frames[frames.length - 1]).self += v;
100
+ for (const name of new Set(frames))
101
+ at(name).total += v;
102
+ }
103
+ return [...costs.values()].sort((a, b) => (a.self === b.self ? (a.name < b.name ? -1 : 1) : a.self > b.self ? -1 : 1));
104
+ }
105
+ /** The call tree: each node's value is the cycles of every stack through it. Children heaviest first. */
106
+ export function flameTree(f, rootName = "all") {
107
+ const root = { name: rootName, value: 0n, children: [] };
108
+ // Children by name, so a wide profile is not quadratic (review, 27 Oct).
109
+ const index = new Map();
110
+ for (const [stack, v] of f) {
111
+ root.value += v;
112
+ let node = root;
113
+ for (const name of splitStack(stack)) {
114
+ const byName = index.get(node) ?? index.set(node, new Map()).get(node);
115
+ let child = byName.get(name);
116
+ if (!child) {
117
+ child = { name, value: 0n, children: [] };
118
+ node.children.push(child);
119
+ byName.set(name, child);
120
+ }
121
+ child.value += v;
122
+ node = child;
123
+ }
124
+ }
125
+ const sort = (n) => {
126
+ n.children.sort((a, b) => (a.value === b.value ? 0 : a.value > b.value ? -1 : 1));
127
+ n.children.forEach(sort);
128
+ };
129
+ sort(root);
130
+ return root;
131
+ }
132
+ const escape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
133
+ const fmt = (n) => n.toLocaleString("en-US");
134
+ /**
135
+ * A self-contained SVG flamegraph: root at the bottom, width proportional to
136
+ * cycles, a tooltip (`<title>`) with the cycles and share on every frame.
137
+ * Frames narrower than `minWidth` pixels are left out. Colours are fixed per
138
+ * function name, so the same function looks the same in two graphs.
139
+ */
140
+ export function renderFlameSvg(tree, opts = {}) {
141
+ const width = opts.width ?? 1200;
142
+ const minWidth = opts.minWidth ?? 0.5;
143
+ const row = 18;
144
+ const top = 34;
145
+ const total = tree.value || 1n;
146
+ let depth = 0;
147
+ const rects = [];
148
+ const draw = (n, x, level) => {
149
+ const w = (Number(n.value) / Number(total)) * width;
150
+ if (w < minWidth)
151
+ return;
152
+ depth = Math.max(depth, level);
153
+ rects.push(`<g data-level="${level}" data-x="${x.toFixed(2)}"><title>${escape(n.name)} — ${fmt(n.value)} cycles (${((Number(n.value) / Number(total)) * 100).toFixed(1)}%)</title>` +
154
+ `<rect x="${x.toFixed(2)}" y="LEVEL${level}" width="${Math.max(w - 0.5, 0.5).toFixed(2)}" height="${row - 1}" rx="2" fill="${colour(n.name)}"/>` +
155
+ (w > 40 ? `<text x="${(x + 4).toFixed(2)}" y="TEXT${level}">${escape(clip(n.name, Math.floor((w - 8) / 7)))}</text>` : "") +
156
+ `</g>`);
157
+ let cx = x;
158
+ for (const c of n.children) {
159
+ draw(c, cx, level + 1);
160
+ cx += (Number(c.value) / Number(total)) * width;
161
+ }
162
+ };
163
+ draw(tree, 0, 0);
164
+ const height = top + (depth + 1) * row + 8;
165
+ // Root at the bottom: level 0 is the last row.
166
+ const body = rects
167
+ .join("\n")
168
+ .replace(/y="LEVEL(\d+)"/g, (_, l) => `y="${height - 8 - (Number(l) + 1) * row}"`)
169
+ .replace(/y="TEXT(\d+)"/g, (_, l) => `y="${height - 8 - (Number(l) + 1) * row + 12.5}"`);
170
+ const title = escape(opts.title ?? "cycles");
171
+ return [
172
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="JetBrains Mono, ui-monospace, monospace" font-size="11">`,
173
+ `<rect width="100%" height="100%" fill="#0d1117"/>`,
174
+ `<text x="4" y="20" fill="#c9d1d9" font-size="13">${title} · ${fmt(tree.value)} cycles</text>`,
175
+ `<g fill="#0d1117">`,
176
+ body,
177
+ `</g>`,
178
+ `</svg>`,
179
+ ].join("\n");
180
+ }
181
+ function clip(s, chars) {
182
+ if (chars <= 1)
183
+ return "";
184
+ return s.length <= chars ? s : s.slice(0, Math.max(chars - 1, 1)) + "…";
185
+ }
186
+ /** A warm colour from the name, stable across graphs. */
187
+ function colour(name) {
188
+ let h = 0;
189
+ for (let i = 0; i < name.length; i++)
190
+ h = (h * 31 + name.charCodeAt(i)) >>> 0;
191
+ const hue = 10 + (h % 45); // red to amber
192
+ const light = 45 + ((h >>> 8) % 15);
193
+ return `hsl(${hue} 75% ${light}%)`;
194
+ }
195
+ /** The `All cycles: N` line ckb-debugger prints in flamegraph mode: what the profile covers. */
196
+ export function profiledCycles(output) {
197
+ const m = /^All cycles:\s*(\d+)/m.exec(output);
198
+ return m ? BigInt(m[1]) : undefined;
199
+ }
@@ -0,0 +1,22 @@
1
+ export { checkDebuggerPath, DebuggerNotFoundError, resolveDebugger } from "./debugger.js";
2
+ export type { ResolveOptions } from "./debugger.js";
3
+ export { analyzeTransaction, groupScripts, knownScriptNames, TransactionNotFoundError } from "./analyze.js";
4
+ export type { ScriptGroup, TxAnalysis } from "./analyze.js";
5
+ export { buildMockTransaction, httpRpc, isCellbase, mockFromTransaction, nodeConsensus, parseOutPointVec, scriptVersionAt, } from "./mock.js";
6
+ export type { HttpRpcOptions, MockTransaction, NodeConsensus, Rpc, RpcOutPoint, RpcTransaction, VmEpochs } from "./mock.js";
7
+ export { checkMockTransaction, checkTypeId, debuggerArgs, groupsOf, nodeVerdict, parseDebuggerOutput, parseDebuggerRun, planReplay, readTransactionJson, replayGroups, selectorFor, } from "./replay.js";
8
+ export type { DebuggerOutput, GroupRun, Profile, ProfiledGroup, ReplayOptions, ReplayPlan, RunDebugger } from "./replay.js";
9
+ export { flameTransaction, profileTransaction, runNativeDebugger } from "./profile.js";
10
+ export type { FlameGroup, ProfileOptions } from "./profile.js";
11
+ export { flameTree, foldedTotal, formatFolded, frameName, functionCosts, parseFolded, profiledCycles, renderFlameSvg, splitStack, } from "./flame.js";
12
+ export type { FlameNode, Folded, FunctionCost } from "./flame.js";
13
+ export { runWasmDebugger, wasmDebuggerVersion, wasmOutput, wasmRunner, WASM_TX_FILE } from "./wasm.js";
14
+ export type { WasmRun } from "./wasm.js";
15
+ export { substituteBinaries } from "./substitute.js";
16
+ export type { AppliedSubstitution, BinarySubstitution } from "./substitute.js";
17
+ export { COMMENT_MARKER, diffFailed, diffReports, formatMarkdown, formatText, FUNCTION_LIMIT, functionDeltas, FUNCTIONS_SHOWN, resultLabel, summarize, } from "./diff.js";
18
+ export type { CycleDiff, CycleReport, DiffOptions, DiffRow, FunctionDelta, FunctionResult, GroupResult, MarkdownOptions, ScenarioResult } from "./diff.js";
19
+ export { formatReport, groupResults, parseCyclesConfig, runReport } from "./report.js";
20
+ export type { BinaryConfig, CyclesConfig, ReportOptions, ScenarioConfig } from "./report.js";
21
+ export { configFromMocks, formatScan, scanTestMocks } from "./scan.js";
22
+ export type { ScanOptions, ScanResult, ScannedBinary, ScannedMock } from "./scan.js";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export { checkDebuggerPath, DebuggerNotFoundError, resolveDebugger } from "./debugger.js";
2
+ export { analyzeTransaction, groupScripts, knownScriptNames, TransactionNotFoundError } from "./analyze.js";
3
+ export { buildMockTransaction, httpRpc, isCellbase, mockFromTransaction, nodeConsensus, parseOutPointVec, scriptVersionAt, } from "./mock.js";
4
+ export { checkMockTransaction, checkTypeId, debuggerArgs, groupsOf, nodeVerdict, parseDebuggerOutput, parseDebuggerRun, planReplay, readTransactionJson, replayGroups, selectorFor, } from "./replay.js";
5
+ export { flameTransaction, profileTransaction, runNativeDebugger } from "./profile.js";
6
+ export { flameTree, foldedTotal, formatFolded, frameName, functionCosts, parseFolded, profiledCycles, renderFlameSvg, splitStack, } from "./flame.js";
7
+ export { runWasmDebugger, wasmDebuggerVersion, wasmOutput, wasmRunner, WASM_TX_FILE } from "./wasm.js";
8
+ export { substituteBinaries } from "./substitute.js";
9
+ export { COMMENT_MARKER, diffFailed, diffReports, formatMarkdown, formatText, FUNCTION_LIMIT, functionDeltas, FUNCTIONS_SHOWN, resultLabel, summarize, } from "./diff.js";
10
+ export { formatReport, groupResults, parseCyclesConfig, runReport } from "./report.js";
11
+ export { configFromMocks, formatScan, scanTestMocks } from "./scan.js";
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 {};