@aztec/simulator 0.0.1-commit.d3ec352c → 0.0.1-commit.f295ac2

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 (273) hide show
  1. package/README.md +2 -0
  2. package/dest/common/errors.d.ts +8 -2
  3. package/dest/common/errors.d.ts.map +1 -1
  4. package/dest/private/acvm/deserialize.d.ts +2 -2
  5. package/dest/private/acvm/deserialize.d.ts.map +1 -1
  6. package/dest/private/acvm/deserialize.js +1 -1
  7. package/dest/private/acvm/serialize.d.ts +2 -2
  8. package/dest/private/acvm/serialize.d.ts.map +1 -1
  9. package/dest/private/acvm/serialize.js +1 -1
  10. package/dest/private/circuit_recording/circuit_recorder.d.ts +1 -1
  11. package/dest/private/circuit_recording/circuit_recorder.d.ts.map +1 -1
  12. package/dest/private/circuit_recording/circuit_recorder.js +16 -15
  13. package/dest/public/avm/avm_context.d.ts +2 -2
  14. package/dest/public/avm/avm_context.d.ts.map +1 -1
  15. package/dest/public/avm/avm_contract_call_result.d.ts +2 -2
  16. package/dest/public/avm/avm_contract_call_result.d.ts.map +1 -1
  17. package/dest/public/avm/avm_execution_environment.d.ts +2 -2
  18. package/dest/public/avm/avm_execution_environment.d.ts.map +1 -1
  19. package/dest/public/avm/avm_execution_environment.js +1 -1
  20. package/dest/public/avm/avm_gas.d.ts +1 -1
  21. package/dest/public/avm/avm_gas.d.ts.map +1 -1
  22. package/dest/public/avm/avm_machine_state.d.ts +2 -2
  23. package/dest/public/avm/avm_machine_state.d.ts.map +1 -1
  24. package/dest/public/avm/avm_memory_types.d.ts +2 -2
  25. package/dest/public/avm/avm_memory_types.d.ts.map +1 -1
  26. package/dest/public/avm/avm_memory_types.js +1 -1
  27. package/dest/public/avm/avm_simulator.d.ts +2 -2
  28. package/dest/public/avm/avm_simulator.d.ts.map +1 -1
  29. package/dest/public/avm/avm_simulator.js +1 -1
  30. package/dest/public/avm/errors.d.ts +2 -2
  31. package/dest/public/avm/errors.d.ts.map +1 -1
  32. package/dest/public/avm/fixtures/avm_simulation_tester.js +1 -1
  33. package/dest/public/avm/fixtures/base_avm_simulation_tester.d.ts +2 -2
  34. package/dest/public/avm/fixtures/base_avm_simulation_tester.d.ts.map +1 -1
  35. package/dest/public/avm/fixtures/base_avm_simulation_tester.js +1 -1
  36. package/dest/public/avm/fixtures/initializers.d.ts +2 -2
  37. package/dest/public/avm/fixtures/initializers.d.ts.map +1 -1
  38. package/dest/public/avm/fixtures/initializers.js +1 -1
  39. package/dest/public/avm/fixtures/utils.d.ts +2 -2
  40. package/dest/public/avm/fixtures/utils.d.ts.map +1 -1
  41. package/dest/public/avm/fixtures/utils.js +1 -1
  42. package/dest/public/avm/opcodes/accrued_substate.d.ts +15 -15
  43. package/dest/public/avm/opcodes/accrued_substate.d.ts.map +1 -1
  44. package/dest/public/avm/opcodes/accrued_substate.js +29 -29
  45. package/dest/public/avm/opcodes/arithmetic.d.ts +10 -8
  46. package/dest/public/avm/opcodes/arithmetic.d.ts.map +1 -1
  47. package/dest/public/avm/opcodes/arithmetic.js +12 -2
  48. package/dest/public/avm/opcodes/bitwise.d.ts +7 -7
  49. package/dest/public/avm/opcodes/bitwise.d.ts.map +1 -1
  50. package/dest/public/avm/opcodes/bitwise.js +5 -5
  51. package/dest/public/avm/opcodes/comparators.d.ts +4 -4
  52. package/dest/public/avm/opcodes/comparators.d.ts.map +1 -1
  53. package/dest/public/avm/opcodes/comparators.js +1 -1
  54. package/dest/public/avm/opcodes/contract.d.ts +3 -3
  55. package/dest/public/avm/opcodes/contract.d.ts.map +1 -1
  56. package/dest/public/avm/opcodes/contract.js +4 -4
  57. package/dest/public/avm/opcodes/control_flow.d.ts +3 -3
  58. package/dest/public/avm/opcodes/control_flow.d.ts.map +1 -1
  59. package/dest/public/avm/opcodes/control_flow.js +4 -4
  60. package/dest/public/avm/opcodes/conversion.d.ts +3 -3
  61. package/dest/public/avm/opcodes/conversion.d.ts.map +1 -1
  62. package/dest/public/avm/opcodes/conversion.js +4 -4
  63. package/dest/public/avm/opcodes/ec_add.d.ts +4 -4
  64. package/dest/public/avm/opcodes/ec_add.d.ts.map +1 -1
  65. package/dest/public/avm/opcodes/ec_add.js +17 -8
  66. package/dest/public/avm/opcodes/environment_getters.d.ts +5 -5
  67. package/dest/public/avm/opcodes/environment_getters.d.ts.map +1 -1
  68. package/dest/public/avm/opcodes/environment_getters.js +6 -6
  69. package/dest/public/avm/opcodes/external_calls.d.ts +9 -9
  70. package/dest/public/avm/opcodes/external_calls.d.ts.map +1 -1
  71. package/dest/public/avm/opcodes/external_calls.js +17 -16
  72. package/dest/public/avm/opcodes/hashing.d.ts +8 -8
  73. package/dest/public/avm/opcodes/hashing.d.ts.map +1 -1
  74. package/dest/public/avm/opcodes/hashing.js +21 -16
  75. package/dest/public/avm/opcodes/instruction_impl.d.ts +4 -4
  76. package/dest/public/avm/opcodes/instruction_impl.d.ts.map +1 -1
  77. package/dest/public/avm/opcodes/instruction_impl.js +4 -4
  78. package/dest/public/avm/opcodes/memory.d.ts +14 -14
  79. package/dest/public/avm/opcodes/memory.d.ts.map +1 -1
  80. package/dest/public/avm/opcodes/memory.js +25 -25
  81. package/dest/public/avm/opcodes/misc.d.ts +3 -3
  82. package/dest/public/avm/opcodes/misc.d.ts.map +1 -1
  83. package/dest/public/avm/opcodes/misc.js +4 -4
  84. package/dest/public/avm/opcodes/storage.d.ts +7 -7
  85. package/dest/public/avm/opcodes/storage.d.ts.map +1 -1
  86. package/dest/public/avm/opcodes/storage.js +9 -9
  87. package/dest/public/avm/revert_reason.d.ts +2 -2
  88. package/dest/public/avm/revert_reason.d.ts.map +1 -1
  89. package/dest/public/avm/serialization/instruction_serialization.js +1 -1
  90. package/dest/public/avm/test_utils.d.ts +2 -2
  91. package/dest/public/avm/test_utils.d.ts.map +1 -1
  92. package/dest/public/avm/test_utils.js +1 -1
  93. package/dest/public/contracts_db_checkpoint.d.ts +2 -2
  94. package/dest/public/contracts_db_checkpoint.d.ts.map +1 -1
  95. package/dest/public/db_interfaces.d.ts +2 -2
  96. package/dest/public/db_interfaces.d.ts.map +1 -1
  97. package/dest/public/debug_fn_name.d.ts +2 -2
  98. package/dest/public/debug_fn_name.d.ts.map +1 -1
  99. package/dest/public/debug_fn_name.js +10 -3
  100. package/dest/public/executor_metrics.d.ts +1 -1
  101. package/dest/public/executor_metrics.d.ts.map +1 -1
  102. package/dest/public/executor_metrics.js +8 -34
  103. package/dest/public/fixtures/amm_test.js +2 -2
  104. package/dest/public/fixtures/bulk_test.d.ts +3 -3
  105. package/dest/public/fixtures/bulk_test.d.ts.map +1 -1
  106. package/dest/public/fixtures/bulk_test.js +5 -69
  107. package/dest/public/fixtures/custom_bytecode_tester.d.ts +28 -6
  108. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -1
  109. package/dest/public/fixtures/custom_bytecode_tester.js +36 -12
  110. package/dest/public/fixtures/custom_bytecode_tests.d.ts +11 -8
  111. package/dest/public/fixtures/custom_bytecode_tests.d.ts.map +1 -1
  112. package/dest/public/fixtures/custom_bytecode_tests.js +83 -18
  113. package/dest/public/fixtures/index.d.ts +4 -2
  114. package/dest/public/fixtures/index.d.ts.map +1 -1
  115. package/dest/public/fixtures/index.js +3 -1
  116. package/dest/public/fixtures/minimal_public_tx.d.ts +2 -7
  117. package/dest/public/fixtures/minimal_public_tx.d.ts.map +1 -1
  118. package/dest/public/fixtures/minimal_public_tx.js +4 -14
  119. package/dest/public/fixtures/opcode_spammer.d.ts +123 -0
  120. package/dest/public/fixtures/opcode_spammer.d.ts.map +1 -0
  121. package/dest/public/fixtures/opcode_spammer.js +1681 -0
  122. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +15 -2
  123. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -1
  124. package/dest/public/fixtures/public_tx_simulation_tester.js +36 -8
  125. package/dest/public/fixtures/simple_contract_data_source.d.ts +2 -2
  126. package/dest/public/fixtures/simple_contract_data_source.d.ts.map +1 -1
  127. package/dest/public/fixtures/token_test.js +1 -1
  128. package/dest/public/fixtures/utils.d.ts +2 -2
  129. package/dest/public/fixtures/utils.d.ts.map +1 -1
  130. package/dest/public/fixtures/utils.js +4 -3
  131. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts +60 -0
  132. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts.map +1 -0
  133. package/dest/public/fuzzing/avm_fuzzer_simulator.js +171 -0
  134. package/dest/public/fuzzing/avm_simulator_bin.d.ts +2 -0
  135. package/dest/public/fuzzing/avm_simulator_bin.d.ts.map +1 -0
  136. package/dest/public/fuzzing/avm_simulator_bin.js +115 -0
  137. package/dest/public/hinting_db_sources.d.ts +3 -2
  138. package/dest/public/hinting_db_sources.d.ts.map +1 -1
  139. package/dest/public/hinting_db_sources.js +7 -2
  140. package/dest/public/index.d.ts +2 -2
  141. package/dest/public/index.d.ts.map +1 -1
  142. package/dest/public/index.js +1 -1
  143. package/dest/public/public_db_sources.d.ts +2 -2
  144. package/dest/public/public_db_sources.d.ts.map +1 -1
  145. package/dest/public/public_db_sources.js +1 -1
  146. package/dest/public/public_processor/guarded_merkle_tree.d.ts +2 -1
  147. package/dest/public/public_processor/guarded_merkle_tree.d.ts.map +1 -1
  148. package/dest/public/public_processor/guarded_merkle_tree.js +5 -0
  149. package/dest/public/public_processor/public_processor.d.ts +3 -3
  150. package/dest/public/public_processor/public_processor.d.ts.map +1 -1
  151. package/dest/public/public_processor/public_processor.js +425 -32
  152. package/dest/public/public_processor/public_processor_metrics.d.ts +1 -1
  153. package/dest/public/public_processor/public_processor_metrics.d.ts.map +1 -1
  154. package/dest/public/public_processor/public_processor_metrics.js +12 -45
  155. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts +1 -13
  156. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts.map +1 -1
  157. package/dest/public/public_tx_simulator/contract_provider_for_cpp.js +18 -53
  158. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts +16 -1
  159. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts.map +1 -1
  160. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.js +42 -3
  161. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts +1 -1
  162. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts.map +1 -1
  163. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.js +7 -6
  164. package/dest/public/public_tx_simulator/dumping_cpp_public_tx_simulator.d.ts +22 -0
  165. package/dest/public/public_tx_simulator/dumping_cpp_public_tx_simulator.d.ts.map +1 -0
  166. package/dest/public/public_tx_simulator/dumping_cpp_public_tx_simulator.js +52 -0
  167. package/dest/public/public_tx_simulator/factories.d.ts +13 -0
  168. package/dest/public/public_tx_simulator/factories.d.ts.map +1 -0
  169. package/dest/public/public_tx_simulator/factories.js +28 -0
  170. package/dest/public/public_tx_simulator/index.d.ts +3 -1
  171. package/dest/public/public_tx_simulator/index.d.ts.map +1 -1
  172. package/dest/public/public_tx_simulator/index.js +2 -0
  173. package/dest/public/public_tx_simulator/measured_public_tx_simulator.d.ts +3 -3
  174. package/dest/public/public_tx_simulator/measured_public_tx_simulator.d.ts.map +1 -1
  175. package/dest/public/public_tx_simulator/public_tx_context.d.ts +2 -2
  176. package/dest/public/public_tx_simulator/public_tx_context.d.ts.map +1 -1
  177. package/dest/public/public_tx_simulator/public_tx_context.js +1 -1
  178. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts +5 -4
  179. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts.map +1 -1
  180. package/dest/public/public_tx_simulator/public_tx_simulator.js +10 -6
  181. package/dest/public/public_tx_simulator/public_tx_simulator_interface.d.ts +24 -1
  182. package/dest/public/public_tx_simulator/public_tx_simulator_interface.d.ts.map +1 -1
  183. package/dest/public/public_tx_simulator/telemetry_public_tx_simulator.d.ts +2 -2
  184. package/dest/public/public_tx_simulator/telemetry_public_tx_simulator.d.ts.map +1 -1
  185. package/dest/public/public_tx_simulator/telemetry_public_tx_simulator.js +395 -19
  186. package/dest/public/side_effect_trace.d.ts +3 -2
  187. package/dest/public/side_effect_trace.d.ts.map +1 -1
  188. package/dest/public/side_effect_trace.js +1 -1
  189. package/dest/public/side_effect_trace_interface.d.ts +2 -2
  190. package/dest/public/side_effect_trace_interface.d.ts.map +1 -1
  191. package/dest/public/state_manager/nullifiers.d.ts +2 -2
  192. package/dest/public/state_manager/nullifiers.d.ts.map +1 -1
  193. package/dest/public/state_manager/public_storage.d.ts +2 -2
  194. package/dest/public/state_manager/public_storage.d.ts.map +1 -1
  195. package/dest/public/state_manager/public_storage.js +1 -1
  196. package/dest/public/state_manager/state_manager.d.ts +2 -2
  197. package/dest/public/state_manager/state_manager.d.ts.map +1 -1
  198. package/dest/public/state_manager/state_manager.js +3 -3
  199. package/package.json +18 -18
  200. package/src/common/errors.ts +1 -1
  201. package/src/private/acvm/deserialize.ts +1 -1
  202. package/src/private/acvm/serialize.ts +1 -1
  203. package/src/private/circuit_recording/circuit_recorder.ts +17 -16
  204. package/src/public/avm/avm_context.ts +1 -1
  205. package/src/public/avm/avm_contract_call_result.ts +1 -1
  206. package/src/public/avm/avm_execution_environment.ts +1 -1
  207. package/src/public/avm/avm_gas.ts +3 -3
  208. package/src/public/avm/avm_machine_state.ts +1 -1
  209. package/src/public/avm/avm_memory_types.ts +1 -1
  210. package/src/public/avm/avm_simulator.ts +1 -1
  211. package/src/public/avm/errors.ts +1 -1
  212. package/src/public/avm/fixtures/avm_simulation_tester.ts +1 -1
  213. package/src/public/avm/fixtures/base_avm_simulation_tester.ts +1 -1
  214. package/src/public/avm/fixtures/initializers.ts +1 -1
  215. package/src/public/avm/fixtures/utils.ts +1 -1
  216. package/src/public/avm/opcodes/accrued_substate.ts +15 -15
  217. package/src/public/avm/opcodes/arithmetic.ts +14 -2
  218. package/src/public/avm/opcodes/bitwise.ts +3 -3
  219. package/src/public/avm/opcodes/comparators.ts +1 -1
  220. package/src/public/avm/opcodes/contract.ts +3 -3
  221. package/src/public/avm/opcodes/control_flow.ts +2 -2
  222. package/src/public/avm/opcodes/conversion.ts +3 -3
  223. package/src/public/avm/opcodes/ec_add.ts +15 -6
  224. package/src/public/avm/opcodes/environment_getters.ts +7 -7
  225. package/src/public/avm/opcodes/external_calls.ts +10 -9
  226. package/src/public/avm/opcodes/hashing.ts +16 -10
  227. package/src/public/avm/opcodes/instruction_impl.ts +2 -2
  228. package/src/public/avm/opcodes/memory.ts +19 -19
  229. package/src/public/avm/opcodes/misc.ts +2 -2
  230. package/src/public/avm/opcodes/storage.ts +7 -7
  231. package/src/public/avm/revert_reason.ts +1 -1
  232. package/src/public/avm/serialization/instruction_serialization.ts +1 -1
  233. package/src/public/avm/test_utils.ts +1 -1
  234. package/src/public/contracts_db_checkpoint.ts +1 -1
  235. package/src/public/db_interfaces.ts +1 -1
  236. package/src/public/debug_fn_name.ts +11 -4
  237. package/src/public/executor_metrics.ts +7 -34
  238. package/src/public/fixtures/amm_test.ts +2 -2
  239. package/src/public/fixtures/bulk_test.ts +9 -9
  240. package/src/public/fixtures/custom_bytecode_tester.ts +53 -19
  241. package/src/public/fixtures/custom_bytecode_tests.ts +111 -18
  242. package/src/public/fixtures/index.ts +7 -1
  243. package/src/public/fixtures/minimal_public_tx.ts +6 -15
  244. package/src/public/fixtures/opcode_spammer.ts +1725 -0
  245. package/src/public/fixtures/public_tx_simulation_tester.ts +40 -6
  246. package/src/public/fixtures/simple_contract_data_source.ts +1 -1
  247. package/src/public/fixtures/token_test.ts +1 -1
  248. package/src/public/fixtures/utils.ts +2 -3
  249. package/src/public/fuzzing/avm_fuzzer_simulator.ts +288 -0
  250. package/src/public/fuzzing/avm_simulator_bin.ts +165 -0
  251. package/src/public/hinting_db_sources.ts +6 -2
  252. package/src/public/index.ts +2 -0
  253. package/src/public/public_db_sources.ts +1 -1
  254. package/src/public/public_processor/guarded_merkle_tree.ts +4 -0
  255. package/src/public/public_processor/public_processor.ts +31 -14
  256. package/src/public/public_processor/public_processor_metrics.ts +11 -45
  257. package/src/public/public_tx_simulator/contract_provider_for_cpp.ts +19 -60
  258. package/src/public/public_tx_simulator/cpp_public_tx_simulator.ts +56 -3
  259. package/src/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.ts +1 -1
  260. package/src/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.ts +7 -10
  261. package/src/public/public_tx_simulator/dumping_cpp_public_tx_simulator.ts +81 -0
  262. package/src/public/public_tx_simulator/factories.ts +41 -0
  263. package/src/public/public_tx_simulator/index.ts +2 -0
  264. package/src/public/public_tx_simulator/measured_public_tx_simulator.ts +1 -1
  265. package/src/public/public_tx_simulator/public_tx_context.ts +1 -1
  266. package/src/public/public_tx_simulator/public_tx_simulator.ts +18 -5
  267. package/src/public/public_tx_simulator/public_tx_simulator_interface.ts +23 -0
  268. package/src/public/public_tx_simulator/telemetry_public_tx_simulator.ts +1 -1
  269. package/src/public/side_effect_trace.ts +1 -1
  270. package/src/public/side_effect_trace_interface.ts +1 -1
  271. package/src/public/state_manager/nullifiers.ts +1 -1
  272. package/src/public/state_manager/public_storage.ts +1 -1
  273. package/src/public/state_manager/state_manager.ts +4 -18
@@ -0,0 +1,1725 @@
1
+ /**
2
+ * Opcode Spammer - A minimal, data-driven opcode spammer for AVM gas benchmarking.
3
+ *
4
+ * Design principles:
5
+ * 1. Data over code: Opcode behavior is configuration, not control flow
6
+ * 2. Derive, don't declare: Categories and strategies follow from the data
7
+ * 3. Maximize coverage: Fill bytecode to the limit for accurate gas measurement
8
+ * 4. Smallest wire format: Use _8 variants over _16 to fit more instructions per loop
9
+ * 5. Single file: Everything in one module
10
+ *
11
+ * ## Architecture
12
+ *
13
+ * ```
14
+ * ┌─────────────────────────────────────────────────────────────────┐
15
+ * │ SPAM_CONFIGS │
16
+ * │ Record<Opcode, SpamConfig[]> │
17
+ * │ │
18
+ * │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
19
+ * │ │ ADD_8 │ │ POSEIDON2 │ │EMITNULLIFIER│ ... │
20
+ * │ │ [7 configs] │ │ [1 config] │ │ [1 config] │ │
21
+ * │ │ (per type) │ │ │ │ (limit=63) │ │
22
+ * │ └─────────────┘ └─────────────┘ └─────────────┘ │
23
+ * └─────────────────────────────────────────────────────────────────┘
24
+ * │
25
+ * ▼
26
+ * ┌─────────────────────────────────────────────────────────────────┐
27
+ * │ getSpamConfigsPerOpcode() │
28
+ * │ Returns { opcodes, config[] } for test iteration │
29
+ * └─────────────────────────────────────────────────────────────────┘
30
+ * │
31
+ * ▼
32
+ * ┌─────────────────────────────────────────────────────────────────┐
33
+ * │ testOpcodeSpamCase() │
34
+ * │ Routes to appropriate bytecode generator & executes test │
35
+ * │ │
36
+ * │ config.limit === undefined? │
37
+ * │ YES → testStandardOpcodeSpam() │
38
+ * │ NO → testSideEffectOpcodeSpam() │
39
+ * └─────────────────────────────────────────────────────────────────┘
40
+ * ```
41
+ *
42
+ * ## Two Execution Strategies
43
+ *
44
+ * ### Strategy 1: Standard Opcodes (Gas-Limited)
45
+ *
46
+ * For opcodes without per-TX limits (arithmetic, comparisons, memory ops, etc.), we create a single contract with an infinite loop:
47
+ *
48
+ * ```
49
+ * ┌────────────────────────────────────────────────────────────────┐
50
+ * │ SINGLE CONTRACT │
51
+ * │ │
52
+ * │ ┌──────────────────────────────────────────────────────────┐ │
53
+ * │ │ SETUP PHASE │ │
54
+ * │ │ SET mem[0] = initial_value │ │
55
+ * │ │ SET mem[1] = operand │ │
56
+ * │ │ ... │ │
57
+ * │ └──────────────────────────────────────────────────────────┘ │
58
+ * │ │ │
59
+ * │ ▼ │
60
+ * │ ┌──────────────────────────────────────────────────────────┐ │
61
+ * │ │ LOOP (fills remaining bytecode space) ◄─────┐ │ │
62
+ * │ │ TARGET_OPCODE ─┐ │ │ │
63
+ * │ │ TARGET_OPCODE │ unrolled N times │ │ │
64
+ * │ │ TARGET_OPCODE │ (N = available_bytes / instr_size)│ │ │
65
+ * │ │ ... ─┘ │ │ │
66
+ * │ │ JUMP back ──────────────────────────────────────────┘ │ │
67
+ * │ └──────────────────────────────────────────────────────────┘ │
68
+ * │ │
69
+ * │ Executes until: OUT OF GAS │
70
+ * └────────────────────────────────────────────────────────────────┘
71
+ * ```
72
+ *
73
+ * **Bytecode Layout:**
74
+ * ```
75
+ * ┌─────────────────────────────────────────────────────────────────┐
76
+ * │ 0x00: SET instructions (setup) │
77
+ * │ ... │
78
+ * │ 0xNN: ┌─── LOOP START ◄──────────────────────────────────────┐ │
79
+ * │ │ TARGET_OPCODE │ │
80
+ * │ │ TARGET_OPCODE (unrolled to fill max bytecode size) │ │
81
+ * │ │ TARGET_OPCODE │ │
82
+ * │ │ ... │ │
83
+ * │ └─► JUMP 0xNN ─────────────────────────────────────────┘ │
84
+ * │ MAX_BYTECODE_BYTES │
85
+ * └─────────────────────────────────────────────────────────────────┘
86
+ * ```
87
+ *
88
+ * ### Strategy 2: Side-Effect Limited Opcodes (Nested Call Pattern)
89
+ *
90
+ * For opcodes with per-TX limits (EMITNOTEHASH, EMITNULLIFIER, SENDL2TOL1MSG, etc.), we use a two-contract pattern where the inner contract executes side effects up to the limit, then REVERTs to discard them:
91
+ *
92
+ * ```
93
+ * ┌─────────────────────────────────────────────────────────────────┐
94
+ * │ OUTER CONTRACT │
95
+ * │ │
96
+ * │ ┌───────────────────────────────────────────────────────────┐ │
97
+ * │ │ SETUP │ │
98
+ * │ │ CALLDATACOPY inner_address from calldata[0] │ │
99
+ * │ │ SET l2Gas = MAX_UINT32 │ │
100
+ * │ │ SET daGas = MAX_UINT32 │ │
101
+ * │ └───────────────────────────────────────────────────────────┘ │
102
+ * │ │ │
103
+ * │ ▼ │
104
+ * │ ┌───────────────────────────────────────────────────────────┐ │
105
+ * │ │ LOOP ◄────┐ │ │
106
+ * │ │ CALL inner_contract ──────────────────────┐ │ │ │
107
+ * │ │ JUMP back ─────────────────────────────────────────────┘ │ │
108
+ * │ └───────────────────────────────────────────────────────────┘ │
109
+ * │ │ │
110
+ * │ Executes until: OUT OF GAS │ │
111
+ * └───────────────────────────────────────────────│─────────────────┘
112
+ * │
113
+ * ▼
114
+ * ┌─────────────────────────────────────────────────────────────────┐
115
+ * │ INNER CONTRACT │
116
+ * │ │
117
+ * │ ┌───────────────────────────────────────────────────────────┐ │
118
+ * │ │ SETUP │ │
119
+ * │ │ SET initial values for side-effect opcode │ │
120
+ * │ └───────────────────────────────────────────────────────────┘ │
121
+ * │ │ │
122
+ * │ ▼ │
123
+ * │ ┌───────────────────────────────────────────────────────────┐ │
124
+ * │ │ BODY (unrolled, NOT a loop) │ │
125
+ * │ │ SIDE_EFFECT_OPCODE ─┐ │ │
126
+ * │ │ SIDE_EFFECT_OPCODE │ repeated `limit` times │ │
127
+ * │ │ SIDE_EFFECT_OPCODE │ (e.g., 64 for EMITNOTEHASH) │ │
128
+ * │ │ ... ─┘ │ │
129
+ * │ └───────────────────────────────────────────────────────────┘ │
130
+ * │ │ │
131
+ * │ ▼ │
132
+ * │ ┌───────────────────────────────────────────────────────────┐ │
133
+ * │ │ CLEANUP │ │
134
+ * │ │ REVERT (discards all side effects from this call) │ │
135
+ * │ └───────────────────────────────────────────────────────────┘ │
136
+ * │ │
137
+ * └─────────────────────────────────────────────────────────────────┘
138
+ * ```
139
+ *
140
+ * **Why this pattern?**
141
+ *
142
+ * Side-effect opcodes have per-TX limits:
143
+ * - `EMITNOTEHASH`: max 64 per TX
144
+ * - `EMITNULLIFIER`: max 63 per TX (one reserved for TX nullifier)
145
+ * - `SENDL2TOL1MSG`: max 8 per TX
146
+ * - `EMITUNENCRYPTEDLOG`: limited by total log payload size
147
+ *
148
+ * By having the inner contract REVERT after emitting side effects, those effects are discarded, allowing the outer contract to call it again. This enables thousands of opcode executions per TX instead of just the limit.
149
+ *
150
+ */
151
+ import {
152
+ FLAT_PUBLIC_LOGS_PAYLOAD_LENGTH,
153
+ MAX_L2_TO_L1_MSGS_PER_TX,
154
+ MAX_NOTE_HASHES_PER_TX,
155
+ MAX_NULLIFIERS_PER_TX,
156
+ MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS,
157
+ MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
158
+ MAX_PUBLIC_LOG_SIZE_IN_FIELDS,
159
+ PUBLIC_LOG_HEADER_LENGTH,
160
+ } from '@aztec/constants';
161
+ import { Grumpkin } from '@aztec/foundation/crypto/grumpkin';
162
+ import { randomBigInt } from '@aztec/foundation/crypto/random';
163
+ import { Fr } from '@aztec/foundation/curves/bn254';
164
+ import type { Bufferable } from '@aztec/foundation/serialize';
165
+ import { type CallStackMetadata, PublicDataWrite, type PublicTxResult } from '@aztec/stdlib/avm';
166
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
167
+ import { computePublicDataTreeLeafSlot, siloNullifier } from '@aztec/stdlib/hash';
168
+ import type { MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server';
169
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
170
+
171
+ import assert from 'assert';
172
+
173
+ import { Field, type MemoryValue, TaggedMemory, TypeTag, Uint1, Uint32, Uint64 } from '../avm/avm_memory_types.js';
174
+ import {
175
+ Add,
176
+ And,
177
+ Call,
178
+ CalldataCopy,
179
+ Cast,
180
+ DebugLog,
181
+ Div,
182
+ EcAdd,
183
+ EmitNoteHash,
184
+ EmitNullifier,
185
+ EmitUnencryptedLog,
186
+ Eq,
187
+ FieldDiv,
188
+ GetContractInstance,
189
+ GetEnvVar,
190
+ InternalCall,
191
+ InternalReturn,
192
+ Jump,
193
+ JumpI,
194
+ KeccakF1600,
195
+ L1ToL2MessageExists,
196
+ Lt,
197
+ Lte,
198
+ Mov,
199
+ Mul,
200
+ Not,
201
+ NoteHashExists,
202
+ NullifierExists,
203
+ Or,
204
+ Poseidon2,
205
+ Return,
206
+ ReturndataCopy,
207
+ ReturndataSize,
208
+ Revert,
209
+ SLoad,
210
+ SStore,
211
+ SendL2ToL1Message,
212
+ Set,
213
+ Sha256Compression,
214
+ Shl,
215
+ Shr,
216
+ StaticCall,
217
+ Sub,
218
+ SuccessCopy,
219
+ ToRadixBE,
220
+ Xor,
221
+ } from '../avm/opcodes/index.js';
222
+ import { encodeToBytecode } from '../avm/serialization/bytecode_serialization.js';
223
+ import { Opcode } from '../avm/serialization/instruction_serialization.js';
224
+ import { deployCustomBytecode, executeCustomBytecode } from './custom_bytecode_tester.js';
225
+ import type { PublicTxSimulationTester } from './public_tx_simulation_tester.js';
226
+
227
+ // ============================================================================
228
+ // Types
229
+ // ============================================================================
230
+
231
+ /**
232
+ * Memory cell to initialize before spamming.
233
+ */
234
+ interface MemSetup {
235
+ offset: number;
236
+ value: MemoryValue;
237
+ }
238
+
239
+ /**
240
+ * Some setup action to take before spamming.
241
+ * Either a memory cell to initialize, or some instruction generator.
242
+ */
243
+ type SetupItem = MemSetup | (() => Bufferable[]);
244
+
245
+ /**
246
+ * Everything needed to spam an opcode.
247
+ */
248
+ export interface SpamConfig {
249
+ /** Memory cells to initialize */
250
+ setup: SetupItem[];
251
+
252
+ /** Factory to create target instruction(s) to spam */
253
+ targetInstructions: () => Bufferable[];
254
+
255
+ /** Instructions to run after target spam (e.g., REVERT) */
256
+ cleanupInstructions?: () => Bufferable[];
257
+
258
+ /**
259
+ * Per-TX limit for the target opcode (for side-effect-limited opcodes)
260
+ * If set:
261
+ * 1. makes nested CALL
262
+ * 2. executes target opcode #limit times in a nested call
263
+ * 3. REVERT
264
+ * 4. CALL again to repeat
265
+ */
266
+ limit?: number;
267
+
268
+ /** Optional label for this config variant (e.g., UINT8 or MAXSIZE) */
269
+ label?: string;
270
+
271
+ /** Whether to pass the contract address as calldata[0] */
272
+ addressAsCalldata?: boolean;
273
+ }
274
+
275
+ /**
276
+ * An object containing opcode name and its SpamConfigs
277
+ * Useful when ready to iterate over all opcodes and test them.
278
+ */
279
+ export interface SpamConfigsForOpcode {
280
+ /** Opcode name (e.g., "ADD_8") */
281
+ opcode: string;
282
+
283
+ /** All spam configs for this opcode (one or more) */
284
+ configs: SpamConfig[];
285
+ }
286
+
287
+ // ============================================================================
288
+ // Constants
289
+ // ============================================================================
290
+
291
+ /**
292
+ * Constants for "warm" tree reads - these values are inserted into the trees
293
+ * before running the spammer so that existence checks can find them.
294
+ */
295
+ export const WARM_NOTE_HASH = new Fr(0xdeadbeefn);
296
+ export const WARM_L1_TO_L2_MSG = new Fr(0xcafebabedeadbeefn);
297
+
298
+ /** Warm nullifier constants - uses a fixed address since NULLIFIEREXISTS takes address as parameter */
299
+ export const WARM_NULLIFIER = new Fr(0xdeadbeef0001n);
300
+ export const WARM_NULLIFIER_ADDRESS = AztecAddress.fromNumber(0xbeef);
301
+
302
+ /** Warm storage constants - storage is inserted for the deployed contract's address */
303
+ export const WARM_STORAGE_SLOT = new Fr(0xdeadbeef0002n);
304
+ export const WARM_STORAGE_VALUE = new Fr(0xcafebabe0003n);
305
+
306
+ /**
307
+ * Leaf indices inserted to by insertWarmTreeEntries().
308
+ * Ideally we'd getTreeInfo and set dynamically, but that doesn't
309
+ * work easily with static spam configs, so we assume intial index 0.
310
+ */
311
+ export const WARM_NOTE_HASH_LEAF_INDEX = 0n;
312
+ export const WARM_L1_TO_L2_MSG_LEAF_INDEX = 0n;
313
+
314
+ /**
315
+ * Insert entries into the trees so that "warm" configs can find them with existence checks.
316
+ * Call this before running the opcode spammer to enable warm tree reads.
317
+ *
318
+ * Inserts:
319
+ * - Note hash into NOTE_HASH_TREE
320
+ * - L1 to L2 message into L1_TO_L2_MESSAGE_TREE
321
+ * - Siloed nullifier into NULLIFIER_TREE (for NULLIFIEREXISTS warm check)
322
+ * - Storage value into PUBLIC_DATA_TREE (for SLOAD warm check)
323
+ */
324
+ export async function insertWarmTreeEntries(
325
+ merkleTrees: MerkleTreeWriteOperations,
326
+ contractAddress: AztecAddress,
327
+ ): Promise<void> {
328
+ // Insert into note hash tree
329
+ await merkleTrees.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, [WARM_NOTE_HASH]);
330
+
331
+ // Insert into L1 to L2 message tree
332
+ await merkleTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [WARM_L1_TO_L2_MSG]);
333
+
334
+ // Insert siloed nullifier into nullifier tree
335
+ const siloedNullifier = await siloNullifier(WARM_NULLIFIER_ADDRESS, WARM_NULLIFIER);
336
+ await merkleTrees.sequentialInsert(MerkleTreeId.NULLIFIER_TREE, [siloedNullifier.toBuffer()]);
337
+
338
+ // Insert storage value into public data tree
339
+ const leafSlot = await computePublicDataTreeLeafSlot(contractAddress, WARM_STORAGE_SLOT);
340
+ const publicDataWrite = new PublicDataWrite(leafSlot, WARM_STORAGE_VALUE);
341
+ await merkleTrees.sequentialInsert(MerkleTreeId.PUBLIC_DATA_TREE, [publicDataWrite.toBuffer()]);
342
+ }
343
+
344
+ /**
345
+ * Maximum bytecode size in bytes.
346
+ *
347
+ * Bytecode is encoded as fields using bufferAsFields():
348
+ * - 1 field for the byte length
349
+ * - ceil(byteLength / 31) fields for the data (31 bytes per field)
350
+ *
351
+ * So: 1 + ceil(byteLength / 31) <= MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS
352
+ * ceil(byteLength / 31) <= MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1
353
+ * byteLength <= (MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1) * 31
354
+ */
355
+ const BYTES_PER_FIELD = Fr.SIZE_IN_BYTES - 1; // 31 bytes of data per field
356
+ const MAX_BYTECODE_BYTES = (MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1) * BYTES_PER_FIELD;
357
+
358
+ const JUMP_SIZE = encodeToBytecode([new Jump(0)]).length; // JUMP_32
359
+ const INTERNALCALL_SIZE = encodeToBytecode([new InternalCall(0)]).length;
360
+
361
+ // ============================================================================
362
+ // Type Variant Helpers (for generating multiple configs per opcode)
363
+ // ============================================================================
364
+
365
+ // Not using these sets directly because we want to control order
366
+ //const ALL_TAGS = Array.from(VALID_TAGS);
367
+ //const INT_TAGS = Array.from(INTEGRAL_TAGS);
368
+ // Ordered so that limiting #configs per opcode still tests max size (Field)
369
+ const ALL_TAGS = [
370
+ TypeTag.FIELD,
371
+ TypeTag.UINT1,
372
+ TypeTag.UINT8,
373
+ TypeTag.UINT16,
374
+ TypeTag.UINT32,
375
+ TypeTag.UINT64,
376
+ TypeTag.UINT128,
377
+ ];
378
+
379
+ // ordered so that limiting #configs per opcode still tests max size
380
+ const INT_TAGS = [TypeTag.UINT128, TypeTag.UINT1, TypeTag.UINT8, TypeTag.UINT16, TypeTag.UINT32, TypeTag.UINT64];
381
+
382
+ /** Build from tag truncating - shorter name */
383
+ function withTag(v: bigint, tag: TypeTag): MemoryValue {
384
+ return TaggedMemory.buildFromTagTruncating(v, tag);
385
+ }
386
+
387
+ // ============================================================================
388
+ // Random Value Helpers (seeded via SEED env var for reproducibility)
389
+ // ============================================================================
390
+
391
+ /** Modulus (really just max+1) for each integer type tag */
392
+ const TAG_MODULI: Partial<Record<TypeTag, bigint>> = {
393
+ [TypeTag.UINT1]: 2n,
394
+ [TypeTag.UINT8]: 256n,
395
+ [TypeTag.UINT16]: 65536n,
396
+ [TypeTag.UINT32]: 0x1_0000_0000n,
397
+ [TypeTag.UINT64]: 0x1_0000_0000_0000_0000n,
398
+ [TypeTag.UINT128]: 0x1_0000_0000_0000_0000_0000_0000_0000_0000n,
399
+ [TypeTag.FIELD]: Fr.MODULUS,
400
+ };
401
+
402
+ /** Generate a random value with the given type tag. Uses SEED env var if set. */
403
+ function randomWithTag(tag: TypeTag): MemoryValue {
404
+ const modulus = TAG_MODULI[tag];
405
+ if (modulus === undefined) {
406
+ throw new Error(`Unsupported tag for random generation: ${TypeTag[tag]}`);
407
+ }
408
+ const value = randomBigInt(modulus);
409
+ return TaggedMemory.buildFromTagTruncating(value, tag);
410
+ }
411
+
412
+ /** Generate a random non-zero value with the given type tag (for division). */
413
+ function randomNonZeroWithTag(tag: TypeTag): MemoryValue {
414
+ const modulus = TAG_MODULI[tag];
415
+ if (modulus === undefined) {
416
+ throw new Error(`Unsupported tag for random generation: ${TypeTag[tag]}`);
417
+ }
418
+ // Generate random in range [1, max) by generating [0, max-1) and adding 1
419
+ const value = randomBigInt(modulus - 1n) + 1n;
420
+ return TaggedMemory.buildFromTagTruncating(value, tag);
421
+ }
422
+
423
+ /** Generate a random non-zero Field value (for field division). */
424
+ function randomNonZeroField(): Field {
425
+ return new Field(randomBigInt(Fr.MODULUS - 1n) + 1n);
426
+ }
427
+
428
+ /** Reserved memory offsets for external call loop (used by CALL spam and side-effect opcodes) */
429
+ const CONST_0_OFFSET = 0; // Uint32(0)
430
+ const CONST_1_OFFSET = 1; // Uint32(1)
431
+ const CONST_MAX_U32_OFFSET = 2; // Uint32(MAX_U32)
432
+ const CALL_ADDR_OFFSET = 3; // copy addr from calldata to here, and then use this addr for CALL
433
+ const CALL_ARGS_OFFSET = CALL_ADDR_OFFSET; // address is the arg to send to CALL
434
+ const CALL_COPY_SIZE_OFFSET = CONST_1_OFFSET; // copy size = 1 (forward calldata[0])
435
+ const CALL_CALLDATA_INDEX_OFFSET = CONST_0_OFFSET; // calldata[0]
436
+ const CALL_L2_GAS_OFFSET = CONST_MAX_U32_OFFSET; // MAX_U32 gets capped to remaining gas by AVM
437
+ const CALL_DA_GAS_OFFSET = CONST_MAX_U32_OFFSET; // MAX_U32 gets capped to remaining gas by AVM
438
+ const CALL_ARGS_SIZE_OFFSET = CONST_1_OFFSET; // argsSize = 1 (forward calldata[0] - might contain contract address)
439
+ const MAX_U32 = 0xffffffffn;
440
+
441
+ /**
442
+ * A SpamConfig for to make external CALLs to an address specified in calldata[0].
443
+ */
444
+ export const EXTERNAL_CALL_CONFIG: SpamConfig = {
445
+ setup: [
446
+ // calldata will contain 1 item: the external call address
447
+ { offset: CONST_0_OFFSET, value: new Uint32(0) }, // used for cdStartOffset
448
+ { offset: CONST_1_OFFSET, value: new Uint32(1) }, // used for copySize and argsSize
449
+ { offset: CONST_MAX_U32_OFFSET, value: new Uint32(MAX_U32) }, // l2Gas/daGas - MAX_U32 gets capped to remaining gas
450
+ () => [
451
+ new CalldataCopy(
452
+ /*addressing_mode=*/ 0,
453
+ /*copySizeOffset=*/ CALL_COPY_SIZE_OFFSET,
454
+ /*cdStartOffset=*/ CALL_CALLDATA_INDEX_OFFSET,
455
+ /*dstOffset=*/ CALL_ADDR_OFFSET,
456
+ ),
457
+ ], // address = calldata[0] of parent call
458
+ ],
459
+ targetInstructions: () => [
460
+ new Call(
461
+ /*addressing_mode=*/ 0,
462
+ /*l2GasOffset=*/ CALL_L2_GAS_OFFSET,
463
+ /*daGasOffset=*/ CALL_DA_GAS_OFFSET,
464
+ /*addrOffset=*/ CALL_ADDR_OFFSET,
465
+ /*argsSizeOffset=*/ CALL_ARGS_SIZE_OFFSET,
466
+ /*argsOffset=*/ CALL_ARGS_OFFSET,
467
+ ),
468
+ ],
469
+ addressAsCalldata: true, // indicates that the contract address should be passed as calldata[0]
470
+ };
471
+
472
+ const STATIC_CALL_CONFIG: SpamConfig = {
473
+ setup: [
474
+ // calldata will contain 1 item: the external call address
475
+ { offset: CONST_0_OFFSET, value: new Uint32(0) }, // used for cdStartOffset
476
+ { offset: CONST_1_OFFSET, value: new Uint32(1) }, // used for copySize and argsSize
477
+ { offset: CONST_MAX_U32_OFFSET, value: new Uint32(MAX_U32) }, // l2Gas/daGas - MAX_U32 gets capped to remaining gas
478
+ () => [
479
+ new CalldataCopy(
480
+ /*addressing_mode=*/ 0,
481
+ /*copySizeOffset=*/ CALL_COPY_SIZE_OFFSET,
482
+ /*cdStartOffset=*/ CALL_CALLDATA_INDEX_OFFSET,
483
+ /*dstOffset=*/ CALL_ADDR_OFFSET,
484
+ ),
485
+ ], // address = calldata[0] of parent call
486
+ ],
487
+ targetInstructions: () => [
488
+ new StaticCall(
489
+ /*addressing_mode=*/ 0,
490
+ /*l2GasOffset=*/ CALL_L2_GAS_OFFSET,
491
+ /*daGasOffset=*/ CALL_DA_GAS_OFFSET,
492
+ /*addrOffset=*/ CALL_ADDR_OFFSET,
493
+ /*argsSizeOffset=*/ CALL_ARGS_SIZE_OFFSET,
494
+ /*argsOffset=*/ CALL_ARGS_OFFSET,
495
+ ),
496
+ ],
497
+ addressAsCalldata: true, // indicates that the contract address should be passed as calldata[0]
498
+ };
499
+
500
+ // ============================================================================
501
+ // Configuration Map
502
+ // ============================================================================
503
+
504
+ /**
505
+ * Opcode spammer configs for ~all opcodes.
506
+ * Each opcode maps to an array of configs (usually one, but can be multiple for type variants, etc.)
507
+ * Uses smallest wire format (_8) for maximum instruction density.
508
+ */
509
+ export const SPAM_CONFIGS: Partial<Record<Opcode, SpamConfig[]>> = {
510
+ // ═══════════════════════════════════════════════════════════════════════════
511
+ // ARITHMETIC - Test with all type variants (random values, seeded via SEED env var)
512
+ // ═══════════════════════════════════════════════════════════════════════════
513
+ [Opcode.ADD_8]: ALL_TAGS.map(tag => ({
514
+ label: TypeTag[tag],
515
+ setup: [
516
+ { offset: 0, value: randomWithTag(tag) }, // random accumulator
517
+ { offset: 1, value: randomWithTag(tag) }, // random addend
518
+ ],
519
+ targetInstructions: () => [
520
+ new Add(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
521
+ Opcode.ADD_8,
522
+ Add.wireFormat8,
523
+ ),
524
+ ],
525
+ })),
526
+
527
+ [Opcode.SUB_8]: ALL_TAGS.map(tag => ({
528
+ label: TypeTag[tag],
529
+ setup: [
530
+ { offset: 0, value: randomWithTag(tag) }, // random minuend
531
+ { offset: 1, value: randomWithTag(tag) }, // random subtrahend
532
+ ],
533
+ targetInstructions: () => [
534
+ new Sub(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
535
+ Opcode.SUB_8,
536
+ Sub.wireFormat8,
537
+ ),
538
+ ],
539
+ })),
540
+
541
+ [Opcode.MUL_8]: ALL_TAGS.map(tag => ({
542
+ label: TypeTag[tag],
543
+ setup: [
544
+ { offset: 0, value: randomWithTag(tag) }, // random multiplicand
545
+ { offset: 1, value: randomWithTag(tag) }, // random multiplier
546
+ ],
547
+ targetInstructions: () => [
548
+ new Mul(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
549
+ Opcode.MUL_8,
550
+ Mul.wireFormat8,
551
+ ),
552
+ ],
553
+ })),
554
+
555
+ // DIV doesn't support FIELD type
556
+ [Opcode.DIV_8]: INT_TAGS.map(tag => ({
557
+ label: TypeTag[tag],
558
+ setup: [
559
+ { offset: 0, value: randomWithTag(tag) }, // random dividend
560
+ { offset: 1, value: randomNonZeroWithTag(tag) }, // random non-zero divisor
561
+ ],
562
+ targetInstructions: () => [
563
+ new Div(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
564
+ Opcode.DIV_8,
565
+ Div.wireFormat8,
566
+ ),
567
+ ],
568
+ })),
569
+
570
+ // Field-only
571
+ [Opcode.FDIV_8]: [
572
+ {
573
+ setup: [
574
+ { offset: 0, value: new Field(Fr.random()) }, // random dividend
575
+ { offset: 1, value: randomNonZeroField() }, // random non-zero divisor
576
+ ],
577
+ targetInstructions: () => [
578
+ new FieldDiv(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
579
+ Opcode.FDIV_8,
580
+ FieldDiv.wireFormat8,
581
+ ),
582
+ ],
583
+ },
584
+ ],
585
+
586
+ // ═══════════════════════════════════════════════════════════════════════════
587
+ // COMPARATORS - Test with all type variants (random values)
588
+ // ═══════════════════════════════════════════════════════════════════════════
589
+ [Opcode.EQ_8]: ALL_TAGS.map(tag => ({
590
+ label: TypeTag[tag],
591
+ setup: [
592
+ { offset: 0, value: randomWithTag(tag) }, // random value a
593
+ { offset: 1, value: randomWithTag(tag) }, // random value b
594
+ ],
595
+ targetInstructions: () => [
596
+ new Eq(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.EQ_8, Eq.wireFormat8),
597
+ ],
598
+ })),
599
+
600
+ [Opcode.LT_8]: ALL_TAGS.map(tag => ({
601
+ label: TypeTag[tag],
602
+ setup: [
603
+ { offset: 0, value: randomWithTag(tag) }, // random value a
604
+ { offset: 1, value: randomWithTag(tag) }, // random value b
605
+ ],
606
+ targetInstructions: () => [
607
+ new Lt(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.LT_8, Lt.wireFormat8),
608
+ ],
609
+ })),
610
+
611
+ [Opcode.LTE_8]: ALL_TAGS.map(tag => ({
612
+ label: TypeTag[tag],
613
+ setup: [
614
+ { offset: 0, value: randomWithTag(tag) }, // random value a
615
+ { offset: 1, value: randomWithTag(tag) }, // random value b
616
+ ],
617
+ targetInstructions: () => [
618
+ new Lte(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(
619
+ Opcode.LTE_8,
620
+ Lte.wireFormat8,
621
+ ),
622
+ ],
623
+ })),
624
+
625
+ // ═══════════════════════════════════════════════════════════════════════════
626
+ // BITWISE - Integer types only (no FIELD) (random values)
627
+ // ═══════════════════════════════════════════════════════════════════════════
628
+ [Opcode.AND_8]: INT_TAGS.map(tag => ({
629
+ label: TypeTag[tag],
630
+ setup: [
631
+ { offset: 0, value: randomWithTag(tag) }, // random value a
632
+ { offset: 1, value: randomWithTag(tag) }, // random value b
633
+ ],
634
+ targetInstructions: () => [
635
+ new And(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
636
+ Opcode.AND_8,
637
+ And.wireFormat8,
638
+ ),
639
+ ],
640
+ })),
641
+
642
+ [Opcode.OR_8]: INT_TAGS.map(tag => ({
643
+ label: TypeTag[tag],
644
+ setup: [
645
+ { offset: 0, value: randomWithTag(tag) }, // random value a
646
+ { offset: 1, value: randomWithTag(tag) }, // random value b
647
+ ],
648
+ targetInstructions: () => [
649
+ new Or(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.OR_8, Or.wireFormat8),
650
+ ],
651
+ })),
652
+
653
+ [Opcode.XOR_8]: INT_TAGS.map(tag => ({
654
+ label: TypeTag[tag],
655
+ setup: [
656
+ { offset: 0, value: randomWithTag(tag) }, // random value a
657
+ { offset: 1, value: randomWithTag(tag) }, // random value b
658
+ ],
659
+ targetInstructions: () => [
660
+ new Xor(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
661
+ Opcode.XOR_8,
662
+ Xor.wireFormat8,
663
+ ),
664
+ ],
665
+ })),
666
+
667
+ [Opcode.NOT_8]: INT_TAGS.map(tag => ({
668
+ label: TypeTag[tag],
669
+ setup: [{ offset: 0, value: randomWithTag(tag) }], // random value
670
+ targetInstructions: () => [
671
+ new Not(/*addressing_mode=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 0).as(Opcode.NOT_8, Not.wireFormat8),
672
+ ],
673
+ })),
674
+
675
+ [Opcode.SHL_8]: INT_TAGS.map(tag => ({
676
+ label: TypeTag[tag],
677
+ setup: [
678
+ { offset: 0, value: randomWithTag(tag) }, // random value to shift
679
+ { offset: 1, value: withTag(1n, tag) }, // shift by 1 (small fixed amount to avoid overflow)
680
+ ],
681
+ targetInstructions: () => [
682
+ new Shl(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
683
+ Opcode.SHL_8,
684
+ Shl.wireFormat8,
685
+ ),
686
+ ],
687
+ })),
688
+
689
+ [Opcode.SHR_8]: INT_TAGS.map(tag => ({
690
+ label: TypeTag[tag],
691
+ setup: [
692
+ { offset: 0, value: randomWithTag(tag) }, // random value to shift
693
+ { offset: 1, value: withTag(1n, tag) }, // shift by 1 (small fixed amount)
694
+ ],
695
+ targetInstructions: () => [
696
+ new Shr(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
697
+ Opcode.SHR_8,
698
+ Shr.wireFormat8,
699
+ ),
700
+ ],
701
+ })),
702
+
703
+ // ═══════════════════════════════════════════════════════════════════════════
704
+ // CAST / MOV - Test with all type variants (random values)
705
+ // ═══════════════════════════════════════════════════════════════════════════
706
+ [Opcode.CAST_8]: ALL_TAGS.map(tag => ({
707
+ label: TypeTag[tag],
708
+ setup: [{ offset: 0, value: randomWithTag(tag) }], // random value to cast
709
+ targetInstructions: () => [
710
+ new Cast(/*addressing_mode=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 1, /*dstTag=*/ TypeTag.UINT32).as(
711
+ Opcode.CAST_8,
712
+ Cast.wireFormat8,
713
+ ),
714
+ ],
715
+ })),
716
+
717
+ [Opcode.MOV_8]: ALL_TAGS.map(tag => ({
718
+ label: TypeTag[tag],
719
+ setup: [{ offset: 0, value: randomWithTag(tag) }], // random value to move
720
+ targetInstructions: () => [
721
+ new Mov(/*addressing_mode=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 1).as(Opcode.MOV_8, Mov.wireFormat8),
722
+ ],
723
+ })),
724
+
725
+ // ═══════════════════════════════════════════════════════════════════════════
726
+ // MEMORY - SET
727
+ // ═══════════════════════════════════════════════════════════════════════════
728
+ // Not testing all wire formats as they should be roughly the same in terms of simulation
729
+ // and proving time
730
+ //[Opcode.SET_8]: [
731
+ // {
732
+ // setup: [],
733
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT8, 42).as(Opcode.SET_8, Set.wireFormat8)],
734
+ // },
735
+ //],
736
+
737
+ //[Opcode.SET_16]: [
738
+ // {
739
+ // setup: [],
740
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT16, 4242).as(Opcode.SET_16, Set.wireFormat16)],
741
+ // },
742
+ //],
743
+
744
+ //[Opcode.SET_32]: [
745
+ // {
746
+ // setup: [],
747
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT32, 424242).as(Opcode.SET_32, Set.wireFormat32)],
748
+ // },
749
+ //],
750
+
751
+ //[Opcode.SET_64]: [
752
+ // {
753
+ // setup: [],
754
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT64, 42424242n).as(Opcode.SET_64, Set.wireFormat64)],
755
+ // },
756
+ //],
757
+
758
+ [Opcode.SET_128]: [
759
+ {
760
+ setup: [],
761
+ targetInstructions: () => [
762
+ new Set(/*addressing_mode=*/ 0, /*dstOffset=*/ 0, /*inTag=*/ TypeTag.UINT128, /*value=*/ 4242424242424242n).as(
763
+ Opcode.SET_128,
764
+ Set.wireFormat128,
765
+ ),
766
+ ],
767
+ },
768
+ ],
769
+
770
+ //[Opcode.SET_FF]: [
771
+ // {
772
+ // setup: [],
773
+ // targetInstructions: () => [new Set(0, 0, TypeTag.FIELD, 42n).as(Opcode.SET_FF, Set.wireFormatFF)],
774
+ // },
775
+ //],
776
+
777
+ // ═══════════════════════════════════════════════════════════════════════════
778
+ // CONTROL FLOW
779
+ // ═══════════════════════════════════════════════════════════════════════════
780
+ [Opcode.JUMP_32]: [
781
+ {
782
+ setup: [],
783
+ // Target will be overwritten by loop builder
784
+ targetInstructions: () => [new Jump(/*jumpOffset=*/ 0)],
785
+ },
786
+ ],
787
+
788
+ [Opcode.JUMPI_32]: [
789
+ {
790
+ setup: [{ offset: 0, value: new Uint1(0n) }], // Always false
791
+ targetInstructions: () => [new JumpI(/*addressing_mode=*/ 0, /*condOffset=*/ 0, /*loc=*/ 0)],
792
+ },
793
+ ],
794
+
795
+ // INTERNALCALL: calls itself infinitely by jumping to its own PC (PC 0, since no setup)
796
+ // Creates infinite recursion until OOG (internal call stack grows forever)
797
+ [Opcode.INTERNALCALL]: [
798
+ {
799
+ setup: [],
800
+ targetInstructions: () => [new InternalCall(/*loc=*/ 0)],
801
+ },
802
+ ],
803
+
804
+ // INTERNALRETURN: needs INTERNALCALL to return without error
805
+ // Layout: INTERNALCALL(10) -> JUMP(0) -> INTERNALRETURN
806
+ // INTERNALCALL jumps to INTERNALRETURN, which returns to JUMP, which loops back
807
+ [Opcode.INTERNALRETURN]: [
808
+ {
809
+ setup: [],
810
+ targetInstructions: () => [
811
+ new InternalCall(/*loc=*/ INTERNALCALL_SIZE + JUMP_SIZE), // jump to INTERNALRETURN
812
+ new Jump(/*jumpOffset=*/ 0), // loop back to start
813
+ new InternalReturn(), // return back to jump
814
+ ],
815
+ },
816
+ ],
817
+
818
+ // CALL (EXTERNALCALL): calls the current contract address (self) in a loop
819
+ // Contract address is passed via calldata[0] and propagated to nested calls
820
+ [Opcode.CALL]: [EXTERNAL_CALL_CONFIG],
821
+ [Opcode.STATICCALL]: [STATIC_CALL_CONFIG],
822
+
823
+ // RETURN: terminates execution, so we need to use the two-contract pattern
824
+ // Outer contract CALLs inner contract in a loop, inner contract does RETURN
825
+ [Opcode.RETURN]: [
826
+ {
827
+ setup: [
828
+ { offset: 0, value: new Uint32(0) }, // returnSize = 0
829
+ ],
830
+ targetInstructions: () => [
831
+ new Return(/*addressing_mode=*/ 0, /*returnSizeOffset=*/ 0, /*returnOffset=*/ 0), // return nothing (size=0)
832
+ ],
833
+ // Use the side-effect-limit pattern (even though it's not a side-effect) as it fits
834
+ // this case (we want to CALL, RETURN, then CALL again back in parent). We omit "cleanup"
835
+ // because we don't need to REVERT as we do for real side-effects.
836
+ limit: 1, // RETURN can only execute once per call
837
+ },
838
+ ],
839
+
840
+ // REVERT: terminates execution, so we need to use the two-contract pattern
841
+ // Outer contract CALLs inner contract in a loop, inner contract does REVERT
842
+ [Opcode.REVERT_8]: [
843
+ {
844
+ setup: [
845
+ { offset: 0, value: new Uint32(0) }, // retSize = 0
846
+ ],
847
+ targetInstructions: () => [
848
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 0, /*returnOffset=*/ 1).as(
849
+ Opcode.REVERT_8,
850
+ Revert.wireFormat8,
851
+ ),
852
+ ],
853
+ limit: 1, // REVERT can only execute once per call
854
+ },
855
+ ],
856
+
857
+ // ═══════════════════════════════════════════════════════════════════════════
858
+ // ENVIRONMENT
859
+ // ═══════════════════════════════════════════════════════════════════════════
860
+ [Opcode.GETENVVAR_16]: [
861
+ {
862
+ setup: [],
863
+ targetInstructions: () => [
864
+ new GetEnvVar(/*addressing_mode=*/ 0, /*dstOffset=*/ 0, /*varEnum=*/ 0).as(
865
+ Opcode.GETENVVAR_16,
866
+ GetEnvVar.wireFormat16,
867
+ ),
868
+ ],
869
+ },
870
+ ],
871
+
872
+ // CALLDATACOPY has dynamic gas scaling with copySize
873
+ [Opcode.CALLDATACOPY]: [
874
+ {
875
+ label: 'Min copy size',
876
+ // CalldataCopy with copySize=0 is a no-op but still executes the opcode
877
+ setup: [
878
+ { offset: 0, value: new Uint32(0n) }, // copySize = 0 (minimum)
879
+ { offset: 1, value: new Uint32(0n) }, // cdStart = 0
880
+ ],
881
+ targetInstructions: () => [
882
+ new CalldataCopy(/*addressing_mode=*/ 0, /*copySizeOffset=*/ 0, /*cdStartOffset=*/ 1, /*dstOffset=*/ 2),
883
+ ],
884
+ },
885
+ {
886
+ label: 'Large copy size',
887
+ // Large copySize with large dynamic gas - will OOG quickly
888
+ // NOTE: we don't want it so large that it exceeds memory bounds (MAX_MEMORY_SIZE = 2^32)
889
+ // and we really want it small enough that we run at least 1 successful target opcode.
890
+ setup: [
891
+ { offset: 0, value: new Uint32(1000n) }, // copySize = 1000 (large enough to show scaling)
892
+ { offset: 1, value: new Uint32(0n) }, // cdStart = 0
893
+ ],
894
+ targetInstructions: () => [
895
+ new CalldataCopy(/*addressing_mode=*/ 0, /*copySizeOffset=*/ 0, /*cdStartOffset=*/ 1, /*dstOffset=*/ 2),
896
+ ],
897
+ },
898
+ {
899
+ label: 'Near min copy size of 1',
900
+ // Near-min but actually copies data (more meaningful than size=0 no-op)
901
+ setup: [
902
+ { offset: 0, value: new Uint32(1n) }, // copySize = 1
903
+ { offset: 1, value: new Uint32(0n) }, // cdStart = 0
904
+ ],
905
+ targetInstructions: () => [
906
+ new CalldataCopy(/*addressing_mode=*/ 0, /*copySizeOffset=*/ 0, /*cdStartOffset=*/ 1, /*dstOffset=*/ 2),
907
+ ],
908
+ },
909
+ ],
910
+
911
+ [Opcode.SUCCESSCOPY]: [
912
+ {
913
+ setup: [],
914
+ targetInstructions: () => [new SuccessCopy(/*addressing_mode=*/ 0, /*dstOffset=*/ 0)],
915
+ },
916
+ ],
917
+
918
+ [Opcode.RETURNDATASIZE]: [
919
+ {
920
+ setup: [],
921
+ targetInstructions: () => [new ReturndataSize(/*addressing_mode=*/ 0, /*dstOffset=*/ 0)],
922
+ },
923
+ ],
924
+
925
+ // RETURNDATACOPY has dynamic gas scaling with copySize
926
+ [Opcode.RETURNDATACOPY]: [
927
+ {
928
+ label: 'Min copy size',
929
+ setup: [
930
+ { offset: 0, value: new Uint32(0n) }, // copySize = 0 (minimum)
931
+ { offset: 1, value: new Uint32(0n) }, // rdOffset
932
+ ],
933
+ targetInstructions: () => [
934
+ new ReturndataCopy(/*addressing_mode=*/ 0, /*copySizeOffset=*/ 0, /*rdStartOffset=*/ 1, /*dstOffset=*/ 2),
935
+ ],
936
+ },
937
+ {
938
+ label: 'Large copy size',
939
+ // Large copySize to maximize dynamic gas - will OOG quickly
940
+ // NOTE: we don't want it so large that it exceeds memory bounds (MAX_MEMORY_SIZE = 2^32)
941
+ // and we really want it small enough that we run at least 1 successful target opcode.
942
+ setup: [
943
+ { offset: 0, value: new Uint32(1000n) }, // copySize = 1000 (large enough to show scaling)
944
+ { offset: 1, value: new Uint32(0n) }, // rdOffset
945
+ ],
946
+ targetInstructions: () => [
947
+ new ReturndataCopy(/*addressing_mode=*/ 0, /*copySizeOffset=*/ 0, /*rdStartOffset=*/ 1, /*dstOffset=*/ 2),
948
+ ],
949
+ },
950
+ {
951
+ label: 'Near min copy size of 1',
952
+ // Near-min but actually copies data (more meaningful than size=0 no-op)
953
+ setup: [
954
+ { offset: 0, value: new Uint32(1n) }, // copySize = 1
955
+ { offset: 1, value: new Uint32(0n) }, // rdOffset
956
+ ],
957
+ targetInstructions: () => [
958
+ new ReturndataCopy(/*addressing_mode=*/ 0, /*copySizeOffset=*/ 0, /*rdStartOffset=*/ 1, /*dstOffset=*/ 2),
959
+ ],
960
+ },
961
+ ],
962
+
963
+ // ═══════════════════════════════════════════════════════════════════════════
964
+ // WORLD STATE READS
965
+ // ═══════════════════════════════════════════════════════════════════════════
966
+ [Opcode.SLOAD]: [
967
+ {
968
+ label: 'Cold read (slot not written)',
969
+ setup: [{ offset: 0, value: new Field(Fr.random()) }], // random slot
970
+ targetInstructions: () => [new SLoad(/*addressing_mode=*/ 0, /*slotOffset=*/ 0, /*dstOffset=*/ 1)],
971
+ },
972
+ {
973
+ label: 'Warm read (from tree)',
974
+ // Uses pre-inserted storage from insertWarmTreeEntries() which is called after contract deployment
975
+ setup: [{ offset: 0, value: new Field(WARM_STORAGE_SLOT) }], // pre-inserted slot
976
+ targetInstructions: () => [new SLoad(/*addressing_mode=*/ 0, /*slotOffset=*/ 0, /*dstOffset=*/ 1)],
977
+ },
978
+ {
979
+ label: 'Warm read (SSTORE first, unique slot per SLOAD)',
980
+ // Memory layout: slot (incremented), value, constant 1, revertSize, loaded value
981
+ setup: [
982
+ { offset: 0, value: new Field(Fr.random()) }, // slot (will be incremented)
983
+ { offset: 1, value: new Field(Fr.random()) }, // value to store
984
+ { offset: 2, value: new Field(1n) }, // constant 1 for ADD
985
+ { offset: 3, value: new Uint32(0n) }, // revertSize
986
+ ],
987
+ targetInstructions: () => [
988
+ new SStore(/*addressing_mode=*/ 0, /*srcOffset=*/ 1, /*slotOffset=*/ 0),
989
+ new SLoad(/*addressing_mode=*/ 0, /*slotOffset=*/ 0, /*dstOffset=*/ 4),
990
+ new Add(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 2, /*dstOffset=*/ 0).as(
991
+ Opcode.ADD_8,
992
+ Add.wireFormat8,
993
+ ), // slot++
994
+ ],
995
+ cleanupInstructions: () => [
996
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 3, /*returnOffset=*/ 0).as(
997
+ Opcode.REVERT_8,
998
+ Revert.wireFormat8,
999
+ ),
1000
+ ],
1001
+ limit: MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
1002
+ },
1003
+ ],
1004
+
1005
+ [Opcode.NOTEHASHEXISTS]: [
1006
+ {
1007
+ label: 'Cold (non-existent)',
1008
+ // Note: Can't easily do "write first" version - would need to know the leaf index
1009
+ // that EMITNOTEHASH will produce, which depends on tree state
1010
+ setup: [
1011
+ { offset: 0, value: new Field(Fr.random()) }, // random noteHash
1012
+ { offset: 1, value: randomWithTag(TypeTag.UINT64) }, // random leafIndex
1013
+ ],
1014
+ targetInstructions: () => [
1015
+ new NoteHashExists(/*addressing_mode=*/ 0, /*noteHashOffset=*/ 0, /*leafIndexOffset=*/ 1, /*existsOffset=*/ 2),
1016
+ ],
1017
+ },
1018
+ {
1019
+ label: 'Warm (exists in tree)',
1020
+ // Uses pre-inserted note hash from insertWarmTreeEntries()
1021
+ setup: [
1022
+ { offset: 0, value: new Field(WARM_NOTE_HASH) }, // pre-inserted noteHash
1023
+ { offset: 1, value: new Uint64(WARM_NOTE_HASH_LEAF_INDEX) }, // known leafIndex
1024
+ ],
1025
+ targetInstructions: () => [
1026
+ new NoteHashExists(/*addressing_mode=*/ 0, /*noteHashOffset=*/ 0, /*leafIndexOffset=*/ 1, /*existsOffset=*/ 2),
1027
+ ],
1028
+ },
1029
+ ],
1030
+
1031
+ [Opcode.NULLIFIEREXISTS]: [
1032
+ {
1033
+ label: 'Non-existent nullifier',
1034
+ setup: [
1035
+ { offset: 0, value: new Field(Fr.random()) }, // random nullifier
1036
+ { offset: 1, value: new Field(Fr.random()) }, // random address
1037
+ ],
1038
+ targetInstructions: () => [
1039
+ new NullifierExists(/*addressing_mode=*/ 0, /*nullifierOffset=*/ 0, /*addressOffset=*/ 1, /*existsOffset=*/ 2),
1040
+ ],
1041
+ },
1042
+ {
1043
+ label: 'Existing nullifier (warm - from tree)',
1044
+ // Uses pre-inserted nullifier from insertWarmTreeEntries()
1045
+ setup: [
1046
+ { offset: 0, value: new Field(WARM_NULLIFIER) }, // pre-inserted nullifier
1047
+ { offset: 1, value: new Field(WARM_NULLIFIER_ADDRESS.toField()) }, // address it was siloed with
1048
+ ],
1049
+ targetInstructions: () => [
1050
+ new NullifierExists(/*addressing_mode=*/ 0, /*nullifierOffset=*/ 0, /*addressOffset=*/ 1, /*existsOffset=*/ 2),
1051
+ ],
1052
+ },
1053
+ {
1054
+ label: 'Existing nullifier (warm - EMITNULLIFIER first)',
1055
+ // Memory layout: nullifier (incremented), constant 1, current address (from GETENVVAR), revertSize, exists result
1056
+ setup: [
1057
+ { offset: 0, value: new Field(Fr.random()) }, // nullifier (will be incremented)
1058
+ { offset: 1, value: new Field(1n) }, // constant 1 for ADD
1059
+ () => [
1060
+ // Get current contract address into offset 2
1061
+ new GetEnvVar(/*addressing_mode=*/ 0, /*dstOffset=*/ 2, /*varEnum=*/ 0).as(
1062
+ Opcode.GETENVVAR_16,
1063
+ GetEnvVar.wireFormat16,
1064
+ ),
1065
+ ],
1066
+ { offset: 3, value: new Uint32(0n) }, // revertSize
1067
+ ],
1068
+ targetInstructions: () => [
1069
+ new EmitNullifier(/*addressing_mode=*/ 0, /*nullifierOffset=*/ 0),
1070
+ new NullifierExists(/*addressing_mode=*/ 0, /*nullifierOffset=*/ 0, /*addressOffset=*/ 2, /*existsOffset=*/ 4),
1071
+ new Add(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
1072
+ Opcode.ADD_8,
1073
+ Add.wireFormat8,
1074
+ ), // nullifier++
1075
+ ],
1076
+ cleanupInstructions: () => [
1077
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 3, /*returnOffset=*/ 0).as(
1078
+ Opcode.REVERT_8,
1079
+ Revert.wireFormat8,
1080
+ ),
1081
+ ],
1082
+ limit: MAX_NULLIFIERS_PER_TX - 1,
1083
+ },
1084
+ ],
1085
+
1086
+ [Opcode.L1TOL2MSGEXISTS]: [
1087
+ {
1088
+ label: 'Cold (non-existent)',
1089
+ setup: [
1090
+ { offset: 0, value: new Field(Fr.random()) }, // random msgHash
1091
+ { offset: 1, value: randomWithTag(TypeTag.UINT64) }, // random msgLeafIndex
1092
+ ],
1093
+ targetInstructions: () => [
1094
+ new L1ToL2MessageExists(
1095
+ /*addressing_mode=*/ 0,
1096
+ /*msgHashOffset=*/ 0,
1097
+ /*msgLeafIndexOffset=*/ 1,
1098
+ /*existsOffset=*/ 2,
1099
+ ),
1100
+ ],
1101
+ },
1102
+ {
1103
+ label: 'Warm (exists in tree)',
1104
+ // Uses pre-inserted L1 to L2 message from insertWarmTreeEntries()
1105
+ setup: [
1106
+ { offset: 0, value: new Field(WARM_L1_TO_L2_MSG) }, // pre-inserted msgHash
1107
+ { offset: 1, value: new Uint64(WARM_L1_TO_L2_MSG_LEAF_INDEX) }, // known msgLeafIndex
1108
+ ],
1109
+ targetInstructions: () => [
1110
+ new L1ToL2MessageExists(
1111
+ /*addressing_mode=*/ 0,
1112
+ /*msgHashOffset=*/ 0,
1113
+ /*msgLeafIndexOffset=*/ 1,
1114
+ /*existsOffset=*/ 2,
1115
+ ),
1116
+ ],
1117
+ },
1118
+ ],
1119
+
1120
+ [Opcode.GETCONTRACTINSTANCE]: [
1121
+ {
1122
+ // Use GETENVVAR to get current contract address (varEnum 0 = ADDRESS)
1123
+ // This ensures we're querying a valid deployed contract
1124
+ setup: [
1125
+ () => [
1126
+ new GetEnvVar(/*addressing_mode=*/ 0, /*dstOffset=*/ 0, /*varEnum=*/ 0).as(
1127
+ Opcode.GETENVVAR_16,
1128
+ GetEnvVar.wireFormat16,
1129
+ ),
1130
+ ],
1131
+ ],
1132
+ // memberEnum 0 = DEPLOYER
1133
+ targetInstructions: () => [
1134
+ new GetContractInstance(/*addressing_mode=*/ 0, /*addressOffset=*/ 0, /*dstOffset=*/ 1, /*memberEnum=*/ 0),
1135
+ ],
1136
+ },
1137
+ ],
1138
+
1139
+ // ═══════════════════════════════════════════════════════════════════════════
1140
+ // SIDE-EFFECT LIMITED (have per-TX limit, use nested call pattern)
1141
+ // ═══════════════════════════════════════════════════════════════════════════
1142
+ [Opcode.EMITNOTEHASH]: [
1143
+ {
1144
+ setup: [
1145
+ { offset: 0, value: new Field(Fr.random()) }, // random noteHash
1146
+ { offset: 1, value: new Uint32(0n) }, // revertSize
1147
+ ],
1148
+ targetInstructions: () => [new EmitNoteHash(/*addressing_mode=*/ 0, /*noteHashOffset=*/ 0)],
1149
+ cleanupInstructions: () => [
1150
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(
1151
+ Opcode.REVERT_8,
1152
+ Revert.wireFormat8,
1153
+ ),
1154
+ ], // revert with empty
1155
+ limit: MAX_NOTE_HASHES_PER_TX,
1156
+ },
1157
+ ],
1158
+
1159
+ [Opcode.EMITNULLIFIER]: [
1160
+ {
1161
+ // Nullifiers must be unique - increment value after each emit
1162
+ // Memory layout: offset 0 = nullifier value, offset 1 = constant 1 for incrementing
1163
+ setup: [
1164
+ { offset: 0, value: new Field(Fr.random()) }, // random nullifier (will be incremented)
1165
+ { offset: 1, value: new Field(1n) }, // constant 1 for ADD
1166
+ { offset: 2, value: new Uint32(0n) }, // revertSize
1167
+ ],
1168
+ targetInstructions: () => [
1169
+ new EmitNullifier(/*addressing_mode=*/ 0, /*nullifierOffset=*/ 0),
1170
+ new Add(/*addressing_mode=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
1171
+ Opcode.ADD_8,
1172
+ Add.wireFormat8,
1173
+ ), // nullifier++
1174
+ ],
1175
+ cleanupInstructions: () => [
1176
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(
1177
+ Opcode.REVERT_8,
1178
+ Revert.wireFormat8,
1179
+ ),
1180
+ ], // revert with empty
1181
+ limit: MAX_NULLIFIERS_PER_TX - 1, // minus 1 because a TX will always have 1 "TX nullifier" from private
1182
+ },
1183
+ ],
1184
+
1185
+ [Opcode.SENDL2TOL1MSG]: [
1186
+ {
1187
+ setup: [
1188
+ { offset: 0, value: new Field(Fr.random()) }, // random recipient
1189
+ { offset: 1, value: new Field(Fr.random()) }, // random content
1190
+ { offset: 2, value: new Uint32(0n) }, // revertSize
1191
+ ],
1192
+ targetInstructions: () => [
1193
+ new SendL2ToL1Message(/*addressing_mode=*/ 0, /*recipientOffset=*/ 0, /*contentOffset=*/ 1),
1194
+ ],
1195
+ cleanupInstructions: () => [
1196
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(
1197
+ Opcode.REVERT_8,
1198
+ Revert.wireFormat8,
1199
+ ),
1200
+ ], // revert with empty
1201
+ limit: MAX_L2_TO_L1_MSGS_PER_TX,
1202
+ },
1203
+ ],
1204
+
1205
+ // SSTORE has two modes:
1206
+ // 1. Same slot: Writing to the same slot repeatedly has no per-TX limit - it just overwrites.
1207
+ // 2. Unique slots: Writing to unique slots is limited by MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX.
1208
+ [Opcode.SSTORE]: [
1209
+ {
1210
+ label: 'Same slot (no limit)',
1211
+ setup: [
1212
+ { offset: 0, value: new Field(Fr.random()) }, // random value
1213
+ { offset: 1, value: new Field(Fr.random()) }, // random slot (same slot each iteration)
1214
+ { offset: 2, value: new Uint32(0n) }, // revertSize
1215
+ ],
1216
+ targetInstructions: () => [new SStore(/*addressing_mode=*/ 0, /*srcOffset=*/ 0, /*slotOffset=*/ 1)],
1217
+ cleanupInstructions: () => [
1218
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(
1219
+ Opcode.REVERT_8,
1220
+ Revert.wireFormat8,
1221
+ ),
1222
+ ], // revert with empty
1223
+ },
1224
+ {
1225
+ label: 'Unique slots (side-effect limited)',
1226
+ setup: [
1227
+ { offset: 0, value: new Field(Fr.random()) }, // random value (constant)
1228
+ { offset: 1, value: new Field(Fr.random()) }, // random slot (will be incremented)
1229
+ { offset: 2, value: new Field(1n) }, // constant 1 for ADD
1230
+ { offset: 3, value: new Uint32(0n) }, // revertSize
1231
+ ],
1232
+ targetInstructions: () => [
1233
+ new SStore(/*addressing_mode=*/ 0, /*srcOffset=*/ 0, /*slotOffset=*/ 1),
1234
+ new Add(/*addressing_mode=*/ 0, /*aOffset=*/ 1, /*bOffset=*/ 2, /*dstOffset=*/ 1).as(
1235
+ Opcode.ADD_8,
1236
+ Add.wireFormat8,
1237
+ ), // slot++
1238
+ ],
1239
+ cleanupInstructions: () => [
1240
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 3, /*returnOffset=*/ 0).as(
1241
+ Opcode.REVERT_8,
1242
+ Revert.wireFormat8,
1243
+ ),
1244
+ ], // revert with empty
1245
+ limit: MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
1246
+ },
1247
+ ],
1248
+
1249
+ // EMITUNENCRYPTEDLOG - two configs: minimal (many small logs) and max-size (one large log)
1250
+ [Opcode.EMITUNENCRYPTEDLOG]: [
1251
+ {
1252
+ label: 'Many empty logs, revert, repeat',
1253
+ setup: [
1254
+ { offset: 0, value: new Uint32(0n) }, // logSize = 0 fields (minimal)
1255
+ { offset: 1, value: new Uint32(0n) }, // revertSize
1256
+ ],
1257
+ targetInstructions: () => [
1258
+ new EmitUnencryptedLog(/*addressing_mode=*/ 0, /*logSizeOffset=*/ 0, /*logOffset=*/ 1),
1259
+ ], // logOffset doesn't matter when size is 0
1260
+ cleanupInstructions: () => [
1261
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(
1262
+ Opcode.REVERT_8,
1263
+ Revert.wireFormat8,
1264
+ ),
1265
+ ], // revert with empty
1266
+ // Max logs with 0-field content: floor(4096 / 2) = 2048
1267
+ limit: Math.floor(FLAT_PUBLIC_LOGS_PAYLOAD_LENGTH / PUBLIC_LOG_HEADER_LENGTH),
1268
+ },
1269
+ {
1270
+ label: 'One max size log, revert, repeat',
1271
+ setup: [
1272
+ // logSize = MAX_PUBLIC_LOG_SIZE_IN_FIELDS
1273
+ { offset: 0, value: new Uint32(BigInt(MAX_PUBLIC_LOG_SIZE_IN_FIELDS)) },
1274
+ { offset: 1, value: new Uint32(0n) }, // revertSize
1275
+ // NOTE: We don't initialize the log contents and just let it use default values (Field(0n))
1276
+ // so that we save more gas and bytecode space for the Emit.
1277
+ //// Initialize all log content fields to zero (FIELD type)
1278
+ //...Array.from({ length: MAX_PUBLIC_LOG_SIZE_IN_FIELDS }, (_, i) => ({
1279
+ // offset: 2 + i,
1280
+ // value: new Field(0n),
1281
+ //})),
1282
+ ],
1283
+ targetInstructions: () => [
1284
+ new EmitUnencryptedLog(/*addressing_mode=*/ 0, /*logSizeOffset=*/ 0, /*logOffset=*/ 2),
1285
+ ], // uses logOffset 2 (uninitialized Field(0))
1286
+ cleanupInstructions: () => [
1287
+ new Revert(/*addressing_mode=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(
1288
+ Opcode.REVERT_8,
1289
+ Revert.wireFormat8,
1290
+ ),
1291
+ ], // revert with empty
1292
+ limit: 1, // Only 1 max-size log fits
1293
+ },
1294
+ ],
1295
+
1296
+ // ═══════════════════════════════════════════════════════════════════════════
1297
+ // GADGETS - Random inputs (seeded via SEED env var)
1298
+ // ═══════════════════════════════════════════════════════════════════════════
1299
+ [Opcode.POSEIDON2]: [
1300
+ {
1301
+ // Poseidon2 takes 4 field elements as input
1302
+ setup: Array.from({ length: 4 }, (_, i) => ({
1303
+ offset: i,
1304
+ value: new Field(Fr.random()), // random field element
1305
+ })),
1306
+ // Poseidon hash data at M[0..3], write result to M[0:3] (reuse results as next inputs)
1307
+ targetInstructions: () => [
1308
+ new Poseidon2(/*addressing_mode=*/ 0, /*inputStateOffset=*/ 0, /*outputStateOffset=*/ 0),
1309
+ ],
1310
+ },
1311
+ ],
1312
+
1313
+ [Opcode.SHA256COMPRESSION]: [
1314
+ {
1315
+ setup: [
1316
+ // State: 8 x UINT32 at offsets 0-7 (random initial state)
1317
+ ...Array.from({ length: 8 }, (_, i) => ({
1318
+ offset: i,
1319
+ value: randomWithTag(TypeTag.UINT32),
1320
+ })),
1321
+ // Inputs: 16 x UINT32 at offsets 8-23 (random message block)
1322
+ ...Array.from({ length: 16 }, (_, i) => ({
1323
+ offset: 8 + i,
1324
+ value: randomWithTag(TypeTag.UINT32),
1325
+ })),
1326
+ ],
1327
+ targetInstructions: () => [
1328
+ new Sha256Compression(/*addressing_mode=*/ 0, /*outputOffset=*/ 0, /*stateOffset=*/ 0, /*inputsOffset=*/ 8),
1329
+ ],
1330
+ },
1331
+ ],
1332
+
1333
+ [Opcode.KECCAKF1600]: [
1334
+ {
1335
+ // Keccak state: 25 x UINT64 (5x5 lane array) with random values
1336
+ setup: Array.from({ length: 25 }, (_, i) => ({
1337
+ offset: i,
1338
+ value: randomWithTag(TypeTag.UINT64),
1339
+ })),
1340
+ targetInstructions: () => [new KeccakF1600(/*addressing_mode=*/ 0, /*dstOffset=*/ 0, /*inputOffset=*/ 0)],
1341
+ },
1342
+ ],
1343
+
1344
+ [Opcode.ECADD]: [
1345
+ {
1346
+ // Use the Grumpkin generator point G for both points (valid curve point)
1347
+ setup: [
1348
+ { offset: 0, value: new Field(Grumpkin.generator.x) }, // p1X = G.x
1349
+ { offset: 1, value: new Field(Grumpkin.generator.y) }, // p1Y = G.y
1350
+ { offset: 2, value: new Uint1(0n) }, // p1IsInfinite = false
1351
+ { offset: 3, value: new Field(Grumpkin.generator.x) }, // p2X = G.x
1352
+ { offset: 4, value: new Field(Grumpkin.generator.y) }, // p2Y = G.y
1353
+ { offset: 5, value: new Uint1(0n) }, // p2IsInfinite = false
1354
+ ],
1355
+ targetInstructions: () => [
1356
+ new EcAdd(
1357
+ /*addressing_mode=*/ 0,
1358
+ /*p1XOffset=*/ 0,
1359
+ /*p1YOffset=*/ 1,
1360
+ /*p1IsInfiniteOffset=*/ 2,
1361
+ /*p2XOffset=*/ 3,
1362
+ /*p2YOffset=*/ 4,
1363
+ /*p2IsInfiniteOffset=*/ 5,
1364
+ /*dstOffset=*/ 0,
1365
+ ),
1366
+ ],
1367
+ },
1368
+ ],
1369
+
1370
+ // TORADIXBE has dynamic gas scaling with numLimbs
1371
+ [Opcode.TORADIXBE]: [
1372
+ {
1373
+ label: 'Min limbs',
1374
+ setup: [
1375
+ { offset: 0, value: new Field(1n) }, // small value that fits in 1 limb (can't randomize - would truncate)
1376
+ { offset: 1, value: new Uint32(2n) }, // radix = 2 (binary)
1377
+ { offset: 2, value: new Uint32(1n) }, // numLimbs = 1 (minimum)
1378
+ { offset: 3, value: new Uint1(0n) }, // outputBits = false
1379
+ ],
1380
+ targetInstructions: () => [
1381
+ new ToRadixBE(
1382
+ /*addressing_mode=*/ 0,
1383
+ /*srcOffset=*/ 0,
1384
+ /*radixOffset=*/ 1,
1385
+ /*numLimbsOffset=*/ 2,
1386
+ /*outputBitsOffset=*/ 3,
1387
+ /*dstOffset=*/ 4,
1388
+ ),
1389
+ ],
1390
+ },
1391
+ {
1392
+ label: 'Max limbs',
1393
+ setup: [
1394
+ { offset: 0, value: new Field(Fr.random()) }, // random field value (fits in 256 bits)
1395
+ { offset: 1, value: new Uint32(2n) }, // radix = 2 (binary)
1396
+ { offset: 2, value: new Uint32(256n) }, // numLimbs = 256 (max bits in field)
1397
+ { offset: 3, value: new Uint1(0n) }, // outputBits = false
1398
+ ],
1399
+ targetInstructions: () => [
1400
+ new ToRadixBE(
1401
+ /*addressing_mode=*/ 0,
1402
+ /*srcOffset=*/ 0,
1403
+ /*radixOffset=*/ 1,
1404
+ /*numLimbsOffset=*/ 2,
1405
+ /*outputBitsOffset=*/ 3,
1406
+ /*dstOffset=*/ 4,
1407
+ ),
1408
+ ],
1409
+ },
1410
+ {
1411
+ label: 'Radix 3 (slow divmod path)',
1412
+ // Radix 3 bypasses the fast path for power-of-2 radixes (4, 8, 16, 32, 64, 128, 256)
1413
+ // and uses the slow divmod implementation instead
1414
+ setup: [
1415
+ { offset: 0, value: new Field(Fr.random()) }, // random field value
1416
+ { offset: 1, value: new Uint32(3n) }, // radix = 3 (non-power-of-2)
1417
+ { offset: 2, value: new Uint32(161n) }, // numLimbs = 161 (ceil(256 / log2(3)) ≈ 161 limbs to represent 256 bits)
1418
+ { offset: 3, value: new Uint1(0n) }, // outputBits = false
1419
+ ],
1420
+ targetInstructions: () => [
1421
+ new ToRadixBE(
1422
+ /*addressing_mode=*/ 0,
1423
+ /*srcOffset=*/ 0,
1424
+ /*radixOffset=*/ 1,
1425
+ /*numLimbsOffset=*/ 2,
1426
+ /*outputBitsOffset=*/ 3,
1427
+ /*dstOffset=*/ 4,
1428
+ ),
1429
+ ],
1430
+ },
1431
+ ],
1432
+
1433
+ // ═══════════════════════════════════════════════════════════════════════════
1434
+ // MISC
1435
+ // ═══════════════════════════════════════════════════════════════════════════
1436
+ // DEBUGLOG only has base gas (no dynamic gas scaling) - memory reads only happen
1437
+ // when collectDebugLogs config is enabled
1438
+ [Opcode.DEBUGLOG]: [
1439
+ {
1440
+ setup: [
1441
+ { offset: 0, value: new Field(0n) }, // level (0 = trace)
1442
+ { offset: 1, value: new Field(0n) }, // message
1443
+ { offset: 2, value: new Field(0n) }, // fields
1444
+ { offset: 3, value: new Uint32(0n) }, // fieldsSize = 0
1445
+ ],
1446
+ // messageSize = 0
1447
+ targetInstructions: () => [
1448
+ new DebugLog(
1449
+ /*addressing_mode=*/ 0,
1450
+ /*levelOffset=*/ 0,
1451
+ /*messageOffset=*/ 1,
1452
+ /*fieldsOffset=*/ 2,
1453
+ /*fieldsSizeOffset=*/ 3,
1454
+ /*messageSize=*/ 0,
1455
+ ),
1456
+ ],
1457
+ },
1458
+ // No real reason to test this by default since debug logs only meaningfully do scaling work
1459
+ // when collectDebugLogs is enabled.
1460
+ // {
1461
+ // label: 'Max sizes',
1462
+ // setup: [
1463
+ // { offset: 0, value: new Field(0n) }, // level (0 = trace)
1464
+ // { offset: 1, value: new Field(0n) }, // message start
1465
+ // { offset: 2, value: new Field(0n) }, // fields start
1466
+ // { offset: 3, value: new Uint32(1000n) }, // fieldsSize = 1000 (large enough to show scaling)
1467
+ // ],
1468
+ // // messageSize = 1000 (large enough to show scaling)
1469
+ // targetInstructions: () => [
1470
+ // new DebugLog(
1471
+ // /*addressing_mode=*/ 0,
1472
+ // /*levelOffset=*/ 0,
1473
+ // /*messageOffset=*/ 1,
1474
+ // /*fieldsOffset=*/ 2,
1475
+ // /*fieldsSizeOffset=*/ 3,
1476
+ // /*messageSize=*/ 1000,
1477
+ // ),
1478
+ // ],
1479
+ // },
1480
+ ],
1481
+ };
1482
+
1483
+ /**
1484
+ * Get all spam test cases grouped by opcode.
1485
+ * This is the main entry point for tests - it handles all the complexity of
1486
+ * type variants, multiple configs, etc.
1487
+ *
1488
+ * Returns hierarchical structure for nested describe blocks in tests.
1489
+ *
1490
+ * @param maxConfigsPerOpcode - Maximum number of configs to include per opcode.
1491
+ * Defaults to Infinity (no limit). Useful for quick
1492
+ * smoke tests where testing all type variants is too slow,
1493
+ * or for proving tests that are inherently slower.
1494
+ */
1495
+ export function getSpamConfigsPerOpcode(maxConfigsPerOpcode: number = Infinity): SpamConfigsForOpcode[] {
1496
+ const groups: SpamConfigsForOpcode[] = [];
1497
+
1498
+ for (const [opcodeKey, configs] of Object.entries(SPAM_CONFIGS)) {
1499
+ const opcode = Opcode[Number(opcodeKey) as Opcode];
1500
+ if (!configs) {
1501
+ throw new Error(`Opcode ${opcode} listed in spam configs, but empty`);
1502
+ }
1503
+
1504
+ // Apply the limit to the number of configs per opcode
1505
+ const limitedConfigs = configs.slice(0, maxConfigsPerOpcode);
1506
+
1507
+ const cases: SpamConfig[] = limitedConfigs.map(config => ({
1508
+ ...config,
1509
+ // unlabeled configs just get opcode name
1510
+ label: config.label ? `${opcode}/${config.label}` : opcode,
1511
+ }));
1512
+
1513
+ groups.push({ opcode: opcode, configs: cases });
1514
+ }
1515
+
1516
+ return groups;
1517
+ }
1518
+
1519
+ // ============================================================================
1520
+ // Helper Functions
1521
+ // ============================================================================
1522
+
1523
+ /**
1524
+ * Create a SET instruction from a MemoryValue.
1525
+ * Chooses smallest SET variant based on offset and value magnitude for optimal bytecode density.
1526
+ */
1527
+ function createSetInstruction(offset: number, memValue: MemoryValue): Bufferable {
1528
+ const tag = memValue.getTag();
1529
+ const value = memValue.toBigInt();
1530
+
1531
+ // SET_8 only supports offset <= 255 and value <= 255
1532
+ if (offset <= 0xff && value <= 0xffn) {
1533
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_8, Set.wireFormat8);
1534
+ }
1535
+ // SET_16+ support offset <= 65535
1536
+ if (value <= 0xffffn) {
1537
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_16, Set.wireFormat16);
1538
+ }
1539
+ if (value <= 0xffffffffn) {
1540
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_32, Set.wireFormat32);
1541
+ }
1542
+ if (value <= 0xffffffffffffffffn) {
1543
+ return new Set(0, offset, tag, value).as(Opcode.SET_64, Set.wireFormat64);
1544
+ }
1545
+ if (value <= 0xffffffffffffffffffffffffffffffffn) {
1546
+ return new Set(0, offset, tag, value).as(Opcode.SET_128, Set.wireFormat128);
1547
+ }
1548
+ return new Set(0, offset, tag, value).as(Opcode.SET_FF, Set.wireFormatFF);
1549
+ }
1550
+
1551
+ /**
1552
+ * Append (to the instructions array) the SET instructions for the setup.
1553
+ *
1554
+ * @param instructions - the instructions array to append the setup to
1555
+ * @param setup - the setup configuration specifying what SETs to do
1556
+ */
1557
+ function appendSetupInstructions(instructions: Bufferable[], setup: SetupItem[]): void {
1558
+ for (const item of setup) {
1559
+ if (typeof item === 'function') {
1560
+ // item is a function that creates setup instructions (like)
1561
+ instructions.push(...item());
1562
+ } else {
1563
+ // MemSetup
1564
+ instructions.push(createSetInstruction(item.offset, item.value));
1565
+ }
1566
+ }
1567
+ }
1568
+
1569
+ /**
1570
+ * Append (to the instructions array) the target instructions nTimes times.
1571
+ *
1572
+ * @param instructions - the instructions array to append the loop to
1573
+ * @param config - the spam config to use
1574
+ * @param nTimes - the number of times to append the target instructions
1575
+ * @returns the number of target instructions appended
1576
+ */
1577
+ function appendTargetNTimes(instructions: Bufferable[], config: SpamConfig, nTimes: number) {
1578
+ for (let i = 0; i < nTimes; i++) {
1579
+ instructions.push(...config.targetInstructions());
1580
+ }
1581
+ }
1582
+
1583
+ /**
1584
+ * Append (to the instructions array) an infinite loop that maximizes target instruction density.
1585
+ * Fills remaining bytecode space with unrolled target instructions.
1586
+ *
1587
+ * @param instructions - the instructions array to append the loop to
1588
+ * @param config - the spam config to use
1589
+ * @returns the number of target instructions in the loop body
1590
+ */
1591
+ function appendInfiniteLoop(instructions: Bufferable[], config: SpamConfig): number {
1592
+ const setupBytecode = encodeToBytecode(instructions);
1593
+ const setupSize = setupBytecode.length;
1594
+
1595
+ // Compute the size of the target instruction(s)
1596
+ const targetSize = encodeToBytecode(config.targetInstructions()).length;
1597
+
1598
+ // Fill remaining space (loop body) with target instructions
1599
+ const availableForLoopBody = MAX_BYTECODE_BYTES - setupSize - JUMP_SIZE;
1600
+ const numTargetsInLoopBody = Math.floor(availableForLoopBody / targetSize);
1601
+
1602
+ const loopStartPc = setupSize;
1603
+ appendTargetNTimes(instructions, config, numTargetsInLoopBody);
1604
+ instructions.push(new Jump(loopStartPc)); // JUMP_SIZE (JUMP_32)
1605
+
1606
+ return numTargetsInLoopBody;
1607
+ }
1608
+
1609
+ /**
1610
+ * Generate basic opcode spam bytecode from a SpamConfig.
1611
+ * Spams the target instruction(s) in an infinite loop until out-of-gas.
1612
+ */
1613
+ export function createOpcodeSpamBytecode(config: SpamConfig): Buffer {
1614
+ assert(
1615
+ config.limit === undefined,
1616
+ 'If config has `limit`, use createSideEffectLimitedSpamInRevertingNestedCall instead',
1617
+ );
1618
+
1619
+ const instructions: Bufferable[] = [];
1620
+
1621
+ // 1. Setup memory
1622
+ appendSetupInstructions(instructions, config.setup);
1623
+
1624
+ // 2. Infinite loop - maximize calls to target until out-of-gas
1625
+ appendInfiniteLoop(instructions, config);
1626
+
1627
+ return encodeToBytecode(instructions);
1628
+ }
1629
+
1630
+ /**
1631
+ * Generate a bytecode that spams a side-effect limited opcode #limit times
1632
+ * NOT in a loop, but inline/unrolled. Then revert.
1633
+ *
1634
+ * @param config - the side-effect limited spam config to use
1635
+ * @returns the bytecode for the side-effect limited spam
1636
+ */
1637
+ export function createSideEffectSpamBytecode(config: SpamConfig): Buffer {
1638
+ assert(
1639
+ config.limit !== undefined,
1640
+ 'If config has `limit`, use createSideEffectLimitedSpamInRevertingNestedCall instead',
1641
+ );
1642
+ const instructions: Bufferable[] = [];
1643
+
1644
+ // 1. Setup
1645
+ appendSetupInstructions(instructions, config.setup);
1646
+
1647
+ // 2. Body - run target instruction(s) #limit times
1648
+ appendTargetNTimes(instructions, config, config.limit);
1649
+
1650
+ // 3. Cleanup (revert)
1651
+ if (config.cleanupInstructions) {
1652
+ instructions.push(...config.cleanupInstructions());
1653
+ }
1654
+
1655
+ return encodeToBytecode(instructions);
1656
+ }
1657
+
1658
+ async function testStandardOpcodeSpam(
1659
+ tester: PublicTxSimulationTester,
1660
+ config: SpamConfig,
1661
+ expectToBeTrue: (x: boolean) => void,
1662
+ ): Promise<PublicTxResult> {
1663
+ const bytecode = createOpcodeSpamBytecode(config);
1664
+ const contract = await deployCustomBytecode(bytecode, tester, config.label);
1665
+
1666
+ await insertWarmTreeEntries(tester.merkleTrees, contract.address);
1667
+
1668
+ // Should we pass the contract address as calldata?
1669
+ const calldata = config.addressAsCalldata ? [contract.address.toField()] : [];
1670
+ const result = await executeCustomBytecode(contract, tester, config.label, calldata);
1671
+
1672
+ // should have halted with out of gas
1673
+ expectToBeTrue(!result.revertCode.isOK());
1674
+ const revertReason = result.findRevertReason()?.message.toLowerCase();
1675
+ const allowedReasons = ['out of gas', 'not enough l2gas'];
1676
+ // expect the reason to match ONE of the allowed reasons
1677
+ expectToBeTrue(allowedReasons.some(allowedReason => revertReason?.includes(allowedReason)));
1678
+ return result;
1679
+ }
1680
+
1681
+ async function testSideEffectOpcodeSpam(
1682
+ tester: PublicTxSimulationTester,
1683
+ config: SpamConfig,
1684
+ expectToBeTrue: (x: boolean) => void,
1685
+ ): Promise<PublicTxResult> {
1686
+ // Inner contract will spam the side-effect limited opcode up to its limit, then REVERT
1687
+ const innerBytecode = createSideEffectSpamBytecode(config);
1688
+ // Outer contract will CALL to inner contract in a loop
1689
+ const outerBytecode = createOpcodeSpamBytecode(EXTERNAL_CALL_CONFIG);
1690
+ const innerContract = await deployCustomBytecode(innerBytecode, tester, `${config.label}_Inner`);
1691
+ const outerContract = await deployCustomBytecode(outerBytecode, tester, `${config.label}_Outer`);
1692
+ // Outer contract reads calldata[0] as inner contract address to CALL to
1693
+ const result = await executeCustomBytecode(outerContract, tester, config.label, [innerContract.address.toField()]);
1694
+
1695
+ // should have halted with out of gas or explicit REVERT (assertion failed)
1696
+ expectToBeTrue(!result.revertCode.isOK());
1697
+ const revertReason = result.findRevertReason()?.message.toLowerCase();
1698
+ const allowedReasons = ['assertion failed', 'out of gas', 'not enough l2gas'];
1699
+ // expect the reason to match ONE of the allowed reasons
1700
+ expectToBeTrue(allowedReasons.some(allowedReason => revertReason?.includes(allowedReason)));
1701
+
1702
+ // Top-level should _always_ run out of gas for these tests
1703
+ // Check top-level halting message
1704
+ // WARNING: only the C++ simulator (or TsVsCpp) will have haltingMessage
1705
+ const allowedOuterReasons = ['out of gas', 'not enough l2gas'];
1706
+ if (result.callStackMetadata && result.callStackMetadata.length > 0) {
1707
+ const outerCallMetadata = result.callStackMetadata[0] as CallStackMetadata;
1708
+ const outerReason = outerCallMetadata.haltingMessage?.toLowerCase();
1709
+ // expect the reason to match ONE of the allowed reasons
1710
+ expectToBeTrue(allowedOuterReasons.some(allowedReason => outerReason?.includes(allowedReason)));
1711
+ }
1712
+
1713
+ return result;
1714
+ }
1715
+
1716
+ export async function testOpcodeSpamCase(
1717
+ tester: PublicTxSimulationTester,
1718
+ config: SpamConfig,
1719
+ expectToBeTrue: (x: boolean) => void = () => {}, // default no-op
1720
+ ): Promise<PublicTxResult> {
1721
+ if (config.limit) {
1722
+ return await testSideEffectOpcodeSpam(tester, config, expectToBeTrue);
1723
+ }
1724
+ return await testStandardOpcodeSpam(tester, config, expectToBeTrue);
1725
+ }