@aztec/simulator 3.0.0-nightly.20251216 → 3.0.0-nightly.20251218

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