@fluffylabs/anan-as 1.1.3-dde58f0 → 1.1.3-dffbae7

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.
Files changed (39) hide show
  1. package/README.md +47 -10
  2. package/dist/bin/index.js +97 -42
  3. package/dist/bin/{fuzz.js → src/fuzz.js} +4 -21
  4. package/dist/bin/src/log-host-call.js +41 -0
  5. package/dist/bin/src/trace-parse.js +315 -0
  6. package/dist/bin/src/trace-replay.js +130 -0
  7. package/dist/bin/src/tracer.js +64 -0
  8. package/dist/bin/src/utils.js +25 -0
  9. package/dist/bin/test.js +1 -3
  10. package/dist/build/compiler-inline.js +1 -1
  11. package/dist/build/compiler.wasm +0 -0
  12. package/dist/build/debug-inline.js +1 -1
  13. package/dist/build/debug-raw-inline.js +1 -1
  14. package/dist/build/debug-raw.d.ts +121 -42
  15. package/dist/build/debug-raw.js +109 -48
  16. package/dist/build/debug-raw.wasm +0 -0
  17. package/dist/build/debug.d.ts +121 -42
  18. package/dist/build/debug.js +119 -50
  19. package/dist/build/debug.wasm +0 -0
  20. package/dist/build/release-inline.js +1 -1
  21. package/dist/build/release-mini-inline.js +1 -1
  22. package/dist/build/release-mini.d.ts +121 -42
  23. package/dist/build/release-mini.js +119 -50
  24. package/dist/build/release-mini.wasm +0 -0
  25. package/dist/build/release-stub-inline.js +1 -1
  26. package/dist/build/release-stub.d.ts +121 -42
  27. package/dist/build/release-stub.js +119 -50
  28. package/dist/build/release-stub.wasm +0 -0
  29. package/dist/build/release.d.ts +121 -42
  30. package/dist/build/release.js +119 -50
  31. package/dist/build/release.wasm +0 -0
  32. package/dist/build/test-inline.js +1 -1
  33. package/dist/build/test.wasm +0 -0
  34. package/dist/test/test-as.js +3 -0
  35. package/dist/{bin → test}/test-gas-cost.js +1 -1
  36. package/dist/test/test-trace-replay.js +19 -0
  37. package/dist/{bin → test}/test-w3f.js +2 -2
  38. package/package.json +5 -5
  39. /package/dist/bin/{test-json.js → src/test-json.js} +0 -0
package/README.md CHANGED
@@ -48,9 +48,26 @@ import ananAs from '@fluffylabs/anan-as/release-mini';
48
48
  // make sure to call GC after multiple independent runs
49
49
  ananAs.__collect();
50
50
 
51
+ // Release build with stub host functions (for standalone testing)
52
+ import ananAs from '@fluffylabs/anan-as/release-stub';
53
+
54
+ // Compiler module (for PVM bytecode compilation)
55
+ import ananAs from '@fluffylabs/anan-as/compiler';
56
+ ```
57
+
58
+ ### Inline Builds
59
+
60
+ Inline builds bundle the WASM binary directly into the JavaScript module (base64 encoded),
61
+ eliminating the need to fetch a separate `.wasm` file:
62
+
63
+ ```javascript
64
+ import ananAs from '@fluffylabs/anan-as/debug-inline';
65
+ import ananAs from '@fluffylabs/anan-as/release-inline';
66
+ import ananAs from '@fluffylabs/anan-as/release-mini-inline';
67
+ import ananAs from '@fluffylabs/anan-as/release-stub-inline';
51
68
  ```
52
69
 
53
- ## Raw Bindings
70
+ ### Raw Bindings
54
71
 
55
72
  Raw bindings give you direct access to WebAssembly exports
56
73
  without the JavaScript wrapper layer.
@@ -69,7 +86,6 @@ const module = await WebAssembly.instantiateStreaming(
69
86
  imports
70
87
  );
71
88
  const ananAs = await instantiate(module);
72
-
73
89
  ```
74
90
 
75
91
  ## Version Tags
@@ -105,24 +121,33 @@ To run the example in the browser at [http://localhost:3000](http://localhost:30
105
121
  npm run web
106
122
  ```
107
123
 
108
- To run JSON test vectors.
124
+ To run tests:
109
125
 
110
126
  ```cmd
111
- npm start ./path/to/tests/*.json
127
+ # Run AssemblyScript unit tests and trace replay tests
128
+ npm test
129
+
130
+ # Run W3F test vectors
131
+ npm run test:w3f
132
+
133
+ # Run gas cost tests
134
+ npm run test:gas-cost
112
135
  ```
113
136
 
114
137
  ## CLI Usage
115
138
 
116
- The package includes a CLI tool for disassembling and running PVM bytecode:
139
+ The package includes a CLI tool for disassembling, running, and replaying PVM bytecode:
117
140
 
118
141
  ```bash
119
142
  # Disassemble bytecode to assembly
120
143
  npx @fluffylabs/anan-as disassemble [--spi] [--no-metadata] <file.(jam|pvm|spi|bin)>
121
144
 
122
145
  # Run JAM programs
123
- npx @fluffylabs/anan-as run [--spi] [--no-logs] [--no-metadata] [--pc <number>] [--gas <number>] <file.jam> [spi-args.bin]
146
+ npx @fluffylabs/anan-as run [--spi] [--no-logs] [--no-metadata] [--pc <number>] [--gas <number>] <file.jam> [spi-args.bin or hex]
124
147
 
125
- The `run` command executes PVM bytecode until it encounters a `halt` instruction or the first host call. For full execution including host call handling, use the disassemble command or other tooling.
148
+ # Replay an ecalli trace
149
+ # Learn more: https://github.com/tomusdrw/JIPs/blob/td-jip6-ecalliloggin/JIP-6.md
150
+ npx @fluffylabs/anan-as replay-trace [--no-metadata] [--no-verify] [--no-logs] <trace.log>
126
151
 
127
152
  # Show help
128
153
  npx @fluffylabs/anan-as --help
@@ -130,18 +155,23 @@ npx @fluffylabs/anan-as disassemble --help
130
155
  npx @fluffylabs/anan-as run --help
131
156
  ```
132
157
 
158
+ The `run` command executes PVM bytecode until it encounters a `halt` instruction or a host call.
159
+ The `replay-trace` command re-executes an ecalli trace, replaying recorded host call responses.
160
+
133
161
  ### Commands
134
162
 
135
163
  - `disassemble`: Convert PVM bytecode to human-readable assembly
136
164
  - `run`: Execute PVM bytecode and show results
165
+ - `replay-trace`: Re-execute an ecalli trace with recorded host call responses
137
166
 
138
167
  ### Flags
139
168
 
140
169
  - `--spi`: Treat input as JAM SPI format instead of generic PVM
141
170
  - `--no-metadata`: Input does not start with metadata
142
- - `--no-logs`: Disable execution logs (run command only)
171
+ - `--no-logs`: Disable execution logs (run and replay-trace commands)
172
+ - `--no-verify`: Skip verification against trace data (replay-trace only)
143
173
  - `--pc <number>`: Set initial program counter (default: 0)
144
- - `--gas <number>`: Set initial gas amount (default: 0)
174
+ - `--gas <number>`: Set initial gas amount (default: 10,000)
145
175
  - `--help`, `-h`: Show help information
146
176
 
147
177
  ### Examples
@@ -168,6 +198,13 @@ npx @fluffylabs/anan-as run --no-logs program.jam
168
198
  # Run a JAM program with custom initial PC and gas
169
199
  npx @fluffylabs/anan-as run --pc 100 --gas 10000 program.jam
170
200
 
171
- # Run SPI program with arguments
201
+ # Run SPI program with arguments (file or hex)
172
202
  npx @fluffylabs/anan-as run --spi program.spi args.bin
203
+ npx @fluffylabs/anan-as run --spi program.spi 0xdeadbeef
204
+
205
+ # Replay an ecalli trace
206
+ npx @fluffylabs/anan-as replay-trace trace.log
207
+
208
+ # Replay without verification
209
+ npx @fluffylabs/anan-as replay-trace --no-verify trace.log
173
210
  ```
package/dist/bin/index.js CHANGED
@@ -1,22 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs";
3
3
  import minimist from "minimist";
4
- import { disassemble, HasMetadata, InputKind, prepareProgram, runProgram } from "../build/release.js";
4
+ import { disassemble, HasMetadata, InputKind, prepareProgram, pvmDestroy, pvmResume, pvmSetRegisters, pvmStart, } from "../build/release.js";
5
+ import { LOG_GAS_COST, LOG_HOST_CALL_INDEX, printLogHostCall, WHAT } from "./src/log-host-call.js";
6
+ import { STATUS } from "./src/trace-parse.js";
7
+ import { replayTraceFile } from "./src/trace-replay.js";
8
+ import { hexDecode, hexEncode } from "./src/utils.js";
5
9
  const HELP_TEXT = `Usage:
6
10
  anan-as disassemble [--spi] [--no-metadata] <file.(jam|pvm|spi|bin)>
7
- anan-as run [--spi] [--no-logs] [--no-metadata] [--pc <number>] [--gas <number>] <file.jam> [spi-args.bin or hex]
11
+ anan-as run [--spi] [--no-logs] [--no-metadata] [--no-log-host-call] [--pc <number>] [--gas <number>] <file.jam> [spi-args.bin or hex]
12
+ anan-as replay-trace [--no-metadata] [--no-verify] [--no-logs] [--no-log-host-call] <trace.log>
8
13
 
9
14
  Commands:
10
15
  disassemble Disassemble PVM bytecode to assembly
11
16
  run Execute PVM bytecode
17
+ replay-trace Re-execute a ecalli IO trace
12
18
 
13
19
  Flags:
14
- --spi Treat input as JAM SPI format
15
- --no-metadata Input does not contain metadata
16
- --no-logs Disable execution logs (run command only)
17
- --pc <number> Set initial program counter (default: 0)
18
- --gas <number> Set initial gas amount (default: 10_000)
19
- --help, -h Show this help message`;
20
+ --spi Treat input as JAM SPI format
21
+ --no-metadata Input does not contain metadata
22
+ --no-logs Disable execution logs
23
+ --no-log-host-call Disable built-in handling of JIP-1 log host call (ecalli 100)
24
+ --no-verify Skip verification against trace data (replay-trace only)
25
+ --pc <number> Set initial program counter (default: 0)
26
+ --gas <number> Set initial gas amount (default: 10_000)
27
+ --help, -h Show this help message`;
20
28
  main();
21
29
  function main() {
22
30
  const args = process.argv.slice(2);
@@ -33,6 +41,9 @@ function main() {
33
41
  case "run":
34
42
  handleRun(args.slice(1));
35
43
  break;
44
+ case "replay-trace":
45
+ handleReplayTrace(args.slice(1));
46
+ break;
36
47
  default:
37
48
  console.error(`Error: Unknown sub-command '${subCommand}'`);
38
49
  console.error("");
@@ -85,11 +96,11 @@ function handleDisassemble(args) {
85
96
  }
86
97
  function handleRun(args) {
87
98
  const parsed = minimist(args, {
88
- boolean: ["spi", "logs", "metadata", "help"],
99
+ boolean: ["spi", "logs", "metadata", "help", "log-host-call"],
89
100
  /** Prevents parsing hex values as numbers. */
90
101
  string: ["pc", "gas", "_"],
91
102
  alias: { h: "help" },
92
- default: { metadata: true, logs: true },
103
+ default: { metadata: true, logs: true, "log-host-call": true },
93
104
  });
94
105
  if (parsed.help) {
95
106
  console.log(HELP_TEXT);
@@ -126,6 +137,7 @@ function handleRun(args) {
126
137
  // Validate SPI args file if provided
127
138
  const spiArgs = parseSpiArgs(spiArgsStr);
128
139
  const logs = parsed.logs;
140
+ const logHostCall = parsed["log-host-call"];
129
141
  const hasMetadata = parsed.metadata ? HasMetadata.Yes : HasMetadata.No;
130
142
  // Parse and validate PC and gas options
131
143
  const initialPc = parsePc(parsed);
@@ -134,20 +146,87 @@ function handleRun(args) {
134
146
  const name = kind === InputKind.Generic ? "generic PVM" : "JAM SPI";
135
147
  console.log(`🚀 Running ${programFile} (as ${name})`);
136
148
  try {
137
- const program = prepareProgram(kind, hasMetadata, programCode, [], [], [], spiArgs);
138
- const result = runProgram(program, initialGas, initialPc, logs, false);
139
- console.log(`Status: ${result.status}`);
140
- console.log(`Exit code: ${result.exitCode}`);
141
- console.log(`Program counter: ${result.pc}`);
142
- console.log(`Gas remaining: ${result.gas}`);
143
- console.log(`Registers: [${result.registers.join(", ")}]`);
144
- console.log(`Result: [${hexEncode(result.result)}]`);
149
+ const preallocateMemoryPages = 128;
150
+ const program = prepareProgram(kind, hasMetadata, programCode, [], [], [], spiArgs, preallocateMemoryPages);
151
+ const id = pvmStart(program, false);
152
+ let gas = initialGas;
153
+ let pc = initialPc;
154
+ for (;;) {
155
+ const pause = pvmResume(id, gas, pc, logs);
156
+ if (!pause) {
157
+ throw new Error("pvmResume returned null");
158
+ }
159
+ if (pause.status === STATUS.HOST && pause.exitCode === LOG_HOST_CALL_INDEX && logHostCall) {
160
+ printLogHostCall(id, pause.registers);
161
+ // Set r7 = WHAT
162
+ const regs = pause.registers;
163
+ regs[7] = WHAT;
164
+ pvmSetRegisters(id, regs);
165
+ // Deduct gas and advance PC
166
+ gas = pause.gas >= LOG_GAS_COST ? pause.gas - LOG_GAS_COST : 0n;
167
+ pc = pause.nextPc;
168
+ }
169
+ else {
170
+ console.warn(`Unhandled host call: ecalli ${pause.exitCode}. Finishing.`);
171
+ break;
172
+ }
173
+ }
174
+ const result = pvmDestroy(id);
175
+ console.log(`Status: ${result?.status}`);
176
+ console.log(`Exit code: ${result?.exitCode}`);
177
+ console.log(`Program counter: ${result?.pc}`);
178
+ console.log(`Gas remaining: ${result?.gas}`);
179
+ console.log(`Registers: [${result?.registers.join(", ")}]`);
180
+ console.log(`Result: [${hexEncode(result?.result ?? [])}]`);
145
181
  }
146
182
  catch (error) {
147
183
  console.error(`Error running ${programFile}:`, error);
148
184
  process.exit(1);
149
185
  }
150
186
  }
187
+ function handleReplayTrace(args) {
188
+ const parsed = minimist(args, {
189
+ boolean: ["metadata", "verify", "logs", "help", "log-host-call"],
190
+ alias: { h: "help" },
191
+ default: { metadata: true, logs: true, verify: true, "log-host-call": true },
192
+ });
193
+ if (parsed.help) {
194
+ console.log(HELP_TEXT);
195
+ return;
196
+ }
197
+ const files = parsed._;
198
+ if (files.length === 0) {
199
+ console.error("Error: No trace file provided for replay-trace command.");
200
+ console.error("Usage: anan-as replay-trace [--no-metadata] [--no-verify] [--no-logs] <trace.log>");
201
+ process.exit(1);
202
+ }
203
+ if (files.length > 1) {
204
+ console.error("Error: Only one trace file can be replayed at a time.");
205
+ console.error("Usage: anan-as replay-trace [--no-metadata] [--no-verify] [--no-logs] <trace.log>");
206
+ process.exit(1);
207
+ }
208
+ const file = files[0];
209
+ const hasMetadata = parsed.metadata ? HasMetadata.Yes : HasMetadata.No;
210
+ const verify = parsed.verify;
211
+ const logs = parsed.logs;
212
+ const logHostCall = parsed["log-host-call"];
213
+ try {
214
+ const summary = replayTraceFile(file, {
215
+ logs,
216
+ hasMetadata,
217
+ verify,
218
+ logHostCall,
219
+ });
220
+ console.log(`✅ Replay complete: ${summary.ecalliCount} ecalli entries`);
221
+ console.log(`Status: ${summary.termination.type}`);
222
+ console.log(`Program counter: ${summary.termination.pc}`);
223
+ console.log(`Gas remaining: ${summary.termination.gas}`);
224
+ }
225
+ catch (error) {
226
+ console.error(`Error replaying trace ${file}:`, error);
227
+ process.exit(1);
228
+ }
229
+ }
151
230
  function parseGas(parsed) {
152
231
  if (parsed.gas === undefined) {
153
232
  return BigInt(10_000);
@@ -212,27 +291,3 @@ function parsePc(parsed) {
212
291
  }
213
292
  return pcValue;
214
293
  }
215
- function hexEncode(result) {
216
- return `0x${result.map((x) => x.toString(16).padStart(2, "0")).join("")}`;
217
- }
218
- function hexDecode(data) {
219
- if (!data.startsWith("0x")) {
220
- throw new Error("hex input must start with 0x");
221
- }
222
- const hex = data.substring(2);
223
- const len = hex.length;
224
- if (len % 2 === 1) {
225
- throw new Error("Odd number of nibbles");
226
- }
227
- const bytes = new Uint8Array(len / 2);
228
- for (let i = 0; i < len; i += 2) {
229
- const c = hex.substring(i, i + 2);
230
- const byteIndex = i / 2;
231
- const value = parseInt(c, 16);
232
- if (Number.isNaN(value)) {
233
- throw new Error(`hexDecode: invalid hex pair "${c}" in data "${data}" for bytes[${byteIndex}]`);
234
- }
235
- bytes[byteIndex] = value;
236
- }
237
- return bytes;
238
- }
@@ -3,7 +3,7 @@ import "json-bigint-patch";
3
3
  import fs from "node:fs";
4
4
  import { tryAsGas } from "@typeberry/lib/pvm-interface";
5
5
  import { Interpreter } from "@typeberry/lib/pvm-interpreter";
6
- import { disassemble, HasMetadata, InputKind, prepareProgram, runProgram, wrapAsProgram } from "../build/release.js";
6
+ import { disassemble, HasMetadata, InputKind, prepareProgram, runProgram, wrapAsProgram } from "../../build/release.js";
7
7
  const runNumber = 0;
8
8
  export function fuzz(data) {
9
9
  const gas = 200n;
@@ -21,7 +21,7 @@ export function fuzz(data) {
21
21
  .join(",")
22
22
  .split(",")
23
23
  .map(() => BigInt(0));
24
- const exe = prepareProgram(InputKind.Generic, HasMetadata.No, Array.from(program), registers, [], [], []);
24
+ const exe = prepareProgram(InputKind.Generic, HasMetadata.No, Array.from(program), registers, [], [], [], 0);
25
25
  const output = runProgram(exe, gas, pc, printDebugInfo);
26
26
  const vmRegisters = decodeRegistersFromTypeberry(vm);
27
27
  collectErrors((assertFn) => {
@@ -56,30 +56,13 @@ export function fuzz(data) {
56
56
  throw e;
57
57
  }
58
58
  }
59
+ import { hexEncode } from "./utils.js";
59
60
  function programHex(program) {
60
- return Array.from(program)
61
- .map((x) => x.toString(16).padStart(2, "0"))
62
- .join("");
61
+ return hexEncode(program, false);
63
62
  }
64
63
  function linkTo(programHex) {
65
64
  return `https://pvm.fluffylabs.dev/?program=0x${programHex}#/`;
66
65
  }
67
- const REGISTER_BYTE_WIDTH = 8;
68
- function _decodeRegisters(value) {
69
- if (value.length === 0) {
70
- return [];
71
- }
72
- if (value.length % REGISTER_BYTE_WIDTH !== 0) {
73
- throw new Error(`Invalid register buffer size: ${value.length}`);
74
- }
75
- const view = new DataView(value.buffer, value.byteOffset, value.byteLength);
76
- const registerCount = value.length / REGISTER_BYTE_WIDTH;
77
- const registers = new Array(registerCount);
78
- for (let i = 0; i < registerCount; i++) {
79
- registers[i] = view.getBigUint64(i * REGISTER_BYTE_WIDTH, true);
80
- }
81
- return registers;
82
- }
83
66
  function decodeRegistersFromTypeberry(vm) {
84
67
  const registers = [];
85
68
  // Try to get up to 13 registers (common register count)
@@ -0,0 +1,41 @@
1
+ import { pvmReadMemory } from "../../build/release.js";
2
+ export const LOG_HOST_CALL_INDEX = 100;
3
+ export const LOG_GAS_COST = 10n;
4
+ /** The WHAT return value - indicates the host call is not implemented / acknowledged. */
5
+ export const WHAT = 0xfffffffffffffffen;
6
+ const LOG_LEVELS = ["FATAL", "ERROR", "WARN", "INFO", "DEBUG"];
7
+ const MAX_LOG_LEN = 8192;
8
+ /**
9
+ * Print the log message from a JIP-1 log host call (ecalli 100).
10
+ *
11
+ * Reads the level, target, and message from the PVM registers and memory,
12
+ * then prints via console.info.
13
+ */
14
+ export function printLogHostCall(pvmId, registers) {
15
+ const level = Number(registers[7]);
16
+ const targetPtr = Number(registers[8] & 0xffffffffn);
17
+ const targetLen = Math.min(Math.max(0, Number(registers[9] & 0xffffffffn)), MAX_LOG_LEN);
18
+ const messagePtr = Number(registers[10] & 0xffffffffn);
19
+ const messageLen = Math.min(Math.max(0, Number(registers[11] & 0xffffffffn)), MAX_LOG_LEN);
20
+ const levelStr = LOG_LEVELS[level] ?? `LEVEL(${level})`;
21
+ let target = "";
22
+ if (targetPtr !== 0 && targetLen > 0) {
23
+ const targetBytes = pvmReadMemory(pvmId, targetPtr, targetLen);
24
+ if (targetBytes) {
25
+ target = new TextDecoder().decode(targetBytes);
26
+ }
27
+ }
28
+ let message = "";
29
+ if (messagePtr !== 0 && messageLen > 0) {
30
+ const messageBytes = pvmReadMemory(pvmId, messagePtr, messageLen);
31
+ if (messageBytes) {
32
+ message = new TextDecoder().decode(messageBytes);
33
+ }
34
+ }
35
+ if (target) {
36
+ console.info(`[${levelStr}] ${target}: ${message}`);
37
+ }
38
+ else {
39
+ console.info(`[${levelStr}] ${message}`);
40
+ }
41
+ }