miden_core/operations/mod.rs
1use core::fmt;
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6mod decorators;
7pub use decorators::{AssemblyOp, DebugOptions, Decorator, DecoratorList};
8use opcode_constants::*;
9
10use crate::{
11 Felt,
12 utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
13};
14
15// OPERATIONS OP CODES
16// ================================================================================================
17
18/// Opcode patterns have the following meanings:
19/// - 00xxxxx operations do not shift the stack; constraint degree can be up to 2.
20/// - 010xxxx operations shift the stack the left; constraint degree can be up to 2.
21/// - 011xxxx operations shift the stack to the right; constraint degree can be up to 2.
22/// - 100xxx-: operations consume 4 range checks; constraint degree can be up to 3. These are used
23/// to encode most u32 operations.
24/// - 101xxx-: operations where constraint degree can be up to 3. These include control flow
25/// operations and some other operations requiring high degree constraints.
26/// - 11xxx--: operations where constraint degree can be up to 5. These include control flow
27/// operations and some other operations requiring very high degree constraints.
28#[rustfmt::skip]
29pub(super) mod opcode_constants {
30 pub const OPCODE_NOOP: u8 = 0b0000_0000;
31 pub const OPCODE_EQZ: u8 = 0b0000_0001;
32 pub const OPCODE_NEG: u8 = 0b0000_0010;
33 pub const OPCODE_INV: u8 = 0b0000_0011;
34 pub const OPCODE_INCR: u8 = 0b0000_0100;
35 pub const OPCODE_NOT: u8 = 0b0000_0101;
36 /* unused 0b0000_0110 */
37 pub const OPCODE_MLOAD: u8 = 0b0000_0111;
38 pub const OPCODE_SWAP: u8 = 0b0000_1000;
39 pub const OPCODE_CALLER: u8 = 0b0000_1001;
40 pub const OPCODE_MOVUP2: u8 = 0b0000_1010;
41 pub const OPCODE_MOVDN2: u8 = 0b0000_1011;
42 pub const OPCODE_MOVUP3: u8 = 0b0000_1100;
43 pub const OPCODE_MOVDN3: u8 = 0b0000_1101;
44 pub const OPCODE_ADVPOPW: u8 = 0b0000_1110;
45 pub const OPCODE_EXPACC: u8 = 0b0000_1111;
46
47 pub const OPCODE_MOVUP4: u8 = 0b0001_0000;
48 pub const OPCODE_MOVDN4: u8 = 0b0001_0001;
49 pub const OPCODE_MOVUP5: u8 = 0b0001_0010;
50 pub const OPCODE_MOVDN5: u8 = 0b0001_0011;
51 pub const OPCODE_MOVUP6: u8 = 0b0001_0100;
52 pub const OPCODE_MOVDN6: u8 = 0b0001_0101;
53 pub const OPCODE_MOVUP7: u8 = 0b0001_0110;
54 pub const OPCODE_MOVDN7: u8 = 0b0001_0111;
55 pub const OPCODE_SWAPW: u8 = 0b0001_1000;
56 pub const OPCODE_EXT2MUL: u8 = 0b0001_1001;
57 pub const OPCODE_MOVUP8: u8 = 0b0001_1010;
58 pub const OPCODE_MOVDN8: u8 = 0b0001_1011;
59 pub const OPCODE_SWAPW2: u8 = 0b0001_1100;
60 pub const OPCODE_SWAPW3: u8 = 0b0001_1101;
61 pub const OPCODE_SWAPDW: u8 = 0b0001_1110;
62 pub const OPCODE_EMIT: u8 = 0b0001_1111;
63
64 pub const OPCODE_ASSERT: u8 = 0b0010_0000;
65 pub const OPCODE_EQ: u8 = 0b0010_0001;
66 pub const OPCODE_ADD: u8 = 0b0010_0010;
67 pub const OPCODE_MUL: u8 = 0b0010_0011;
68 pub const OPCODE_AND: u8 = 0b0010_0100;
69 pub const OPCODE_OR: u8 = 0b0010_0101;
70 pub const OPCODE_U32AND: u8 = 0b0010_0110;
71 pub const OPCODE_U32XOR: u8 = 0b0010_0111;
72 pub const OPCODE_FRIE2F4: u8 = 0b0010_1000;
73 pub const OPCODE_DROP: u8 = 0b0010_1001;
74 pub const OPCODE_CSWAP: u8 = 0b0010_1010;
75 pub const OPCODE_CSWAPW: u8 = 0b0010_1011;
76 pub const OPCODE_MLOADW: u8 = 0b0010_1100;
77 pub const OPCODE_MSTORE: u8 = 0b0010_1101;
78 pub const OPCODE_MSTOREW: u8 = 0b0010_1110;
79 /* unused 0b0010_1111 */
80
81 pub const OPCODE_PAD: u8 = 0b0011_0000;
82 pub const OPCODE_DUP0: u8 = 0b0011_0001;
83 pub const OPCODE_DUP1: u8 = 0b0011_0010;
84 pub const OPCODE_DUP2: u8 = 0b0011_0011;
85 pub const OPCODE_DUP3: u8 = 0b0011_0100;
86 pub const OPCODE_DUP4: u8 = 0b0011_0101;
87 pub const OPCODE_DUP5: u8 = 0b0011_0110;
88 pub const OPCODE_DUP6: u8 = 0b0011_0111;
89 pub const OPCODE_DUP7: u8 = 0b0011_1000;
90 pub const OPCODE_DUP9: u8 = 0b0011_1001;
91 pub const OPCODE_DUP11: u8 = 0b0011_1010;
92 pub const OPCODE_DUP13: u8 = 0b0011_1011;
93 pub const OPCODE_DUP15: u8 = 0b0011_1100;
94 pub const OPCODE_ADVPOP: u8 = 0b0011_1101;
95 pub const OPCODE_SDEPTH: u8 = 0b0011_1110;
96 pub const OPCODE_CLK: u8 = 0b0011_1111;
97
98 pub const OPCODE_U32ADD: u8 = 0b0100_0000;
99 pub const OPCODE_U32SUB: u8 = 0b0100_0010;
100 pub const OPCODE_U32MUL: u8 = 0b0100_0100;
101 pub const OPCODE_U32DIV: u8 = 0b0100_0110;
102 pub const OPCODE_U32SPLIT: u8 = 0b0100_1000;
103 pub const OPCODE_U32ASSERT2: u8 = 0b0100_1010;
104 pub const OPCODE_U32ADD3: u8 = 0b0100_1100;
105 pub const OPCODE_U32MADD: u8 = 0b0100_1110;
106
107 pub const OPCODE_HPERM: u8 = 0b0101_0000;
108 pub const OPCODE_MPVERIFY: u8 = 0b0101_0001;
109 pub const OPCODE_PIPE: u8 = 0b0101_0010;
110 pub const OPCODE_MSTREAM: u8 = 0b0101_0011;
111 pub const OPCODE_SPLIT: u8 = 0b0101_0100;
112 pub const OPCODE_LOOP: u8 = 0b0101_0101;
113 pub const OPCODE_SPAN: u8 = 0b0101_0110;
114 pub const OPCODE_JOIN: u8 = 0b0101_0111;
115 pub const OPCODE_DYN: u8 = 0b0101_1000;
116 pub const OPCODE_HORNEREXT: u8 = 0b0101_1001;
117 pub const OPCODE_LOGPRECOMPILE: u8 = 0b0101_1010;
118 pub const OPCODE_PUSH: u8 = 0b0101_1011;
119 pub const OPCODE_DYNCALL: u8 = 0b0101_1100;
120 pub const OPCODE_EVALCIRCUIT: u8 = 0b0101_1101;
121
122 pub const OPCODE_MRUPDATE: u8 = 0b0110_0000;
123 pub const OPCODE_HORNERBASE: u8 = 0b0110_0100;
124 pub const OPCODE_SYSCALL: u8 = 0b0110_1000;
125 pub const OPCODE_CALL: u8 = 0b0110_1100;
126 pub const OPCODE_END: u8 = 0b0111_0000;
127 pub const OPCODE_REPEAT: u8 = 0b0111_0100;
128 pub const OPCODE_RESPAN: u8 = 0b0111_1000;
129 pub const OPCODE_HALT: u8 = 0b0111_1100;
130}
131
132// OPERATIONS
133// ================================================================================================
134
135/// A set of native VM operations which take exactly one cycle to execute.
136#[derive(Copy, Clone, Debug, Eq, PartialEq)]
137#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
138#[repr(u8)]
139pub enum Operation {
140 // ----- system operations -------------------------------------------------------------------
141 /// Advances cycle counter, but does not change the state of user stack.
142 Noop = OPCODE_NOOP,
143
144 /// Pops the stack; if the popped value is not 1, execution fails.
145 ///
146 /// The internal value specifies an error code associated with the error in case when the
147 /// execution fails.
148 Assert(Felt) = OPCODE_ASSERT,
149
150 /// Pushes the current depth of the stack onto the stack.
151 SDepth = OPCODE_SDEPTH,
152
153 /// Overwrites the top four stack items with the hash of a function which initiated the current
154 /// SYSCALL. Thus, this operation can be executed only inside a SYSCALL code block.
155 Caller = OPCODE_CALLER,
156
157 /// Pushes the current value of the clock cycle onto the stack. This operation can be used to
158 /// measure the number of cycles it has taken to execute the program up to the current
159 /// instruction.
160 Clk = OPCODE_CLK,
161
162 /// Emits an event to the host.
163 ///
164 /// Semantics:
165 /// - Reads the event id from the top of the stack (as a `Felt`) without consuming it; the
166 /// caller is responsible for pushing and later dropping the id.
167 /// - User-defined events are conventionally derived from strings via
168 /// `hash_string_to_word(name)[0]` (Blake3-based) and may be emitted via immediate forms in
169 /// assembly (`emit.event("...")` or `emit.CONST` where `CONST=event("...")`).
170 /// - System events are still identified by specific 32-bit codes; the VM attempts to interpret
171 /// the stack `Felt` as `u32` to dispatch known system events, and otherwise forwards the
172 /// event to the host.
173 ///
174 /// This operation does not change the state of the user stack aside from reading the value.
175 Emit = OPCODE_EMIT,
176
177 // ----- flow control operations -------------------------------------------------------------
178 /// Marks the beginning of a join block.
179 Join = OPCODE_JOIN,
180
181 /// Marks the beginning of a split block.
182 Split = OPCODE_SPLIT,
183
184 /// Marks the beginning of a loop block.
185 Loop = OPCODE_LOOP,
186
187 /// Marks the beginning of a function call.
188 Call = OPCODE_CALL,
189
190 /// Marks the beginning of a dynamic code block, where the target is specified by the stack.
191 Dyn = OPCODE_DYN,
192
193 /// Marks the beginning of a dynamic function call, where the target is specified by the stack.
194 Dyncall = OPCODE_DYNCALL,
195
196 /// Marks the beginning of a kernel call.
197 SysCall = OPCODE_SYSCALL,
198
199 /// Marks the beginning of a span code block.
200 Span = OPCODE_SPAN,
201
202 /// Marks the end of a program block.
203 End = OPCODE_END,
204
205 /// Indicates that body of an executing loop should be executed again.
206 Repeat = OPCODE_REPEAT,
207
208 /// Starts processing a new operation batch.
209 Respan = OPCODE_RESPAN,
210
211 /// Indicates the end of the program. This is used primarily to pad the execution trace to
212 /// the required length. Once HALT operation is executed, no other operations can be executed
213 /// by the VM (HALT operation itself excepted).
214 Halt = OPCODE_HALT,
215
216 // ----- field operations --------------------------------------------------------------------
217 /// Pops two elements off the stack, adds them, and pushes the result back onto the stack.
218 Add = OPCODE_ADD,
219
220 /// Pops an element off the stack, negates it, and pushes the result back onto the stack.
221 Neg = OPCODE_NEG,
222
223 /// Pops two elements off the stack, multiplies them, and pushes the result back onto the
224 /// stack.
225 Mul = OPCODE_MUL,
226
227 /// Pops an element off the stack, computes its multiplicative inverse, and pushes the result
228 /// back onto the stack.
229 Inv = OPCODE_INV,
230
231 /// Pops an element off the stack, adds 1 to it, and pushes the result back onto the stack.
232 Incr = OPCODE_INCR,
233
234 /// Pops two elements off the stack, multiplies them, and pushes the result back onto the
235 /// stack.
236 ///
237 /// If either of the elements is greater than 1, execution fails. This operation is equivalent
238 /// to boolean AND.
239 And = OPCODE_AND,
240
241 /// Pops two elements off the stack and subtracts their product from their sum.
242 ///
243 /// If either of the elements is greater than 1, execution fails. This operation is equivalent
244 /// to boolean OR.
245 Or = OPCODE_OR,
246
247 /// Pops an element off the stack and subtracts it from 1.
248 ///
249 /// If the element is greater than one, the execution fails. This operation is equivalent to
250 /// boolean NOT.
251 Not = OPCODE_NOT,
252
253 /// Pops two elements off the stack and compares them. If the elements are equal, pushes 1
254 /// onto the stack, otherwise pushes 0 onto the stack.
255 Eq = OPCODE_EQ,
256
257 /// Pops an element off the stack and compares it to 0. If the element is 0, pushes 1 onto
258 /// the stack, otherwise pushes 0 onto the stack.
259 Eqz = OPCODE_EQZ,
260
261 /// Computes a single turn of exponent accumulation for the given inputs. This operation can be
262 /// be used to compute a single turn of power of a field element.
263 ///
264 /// The top 4 elements of the stack are expected to be arranged as follows (form the top):
265 /// - least significant bit of the exponent in the previous trace if there's an expacc call,
266 /// otherwise ZERO
267 /// - exponent of base number `a` for this turn
268 /// - accumulated power of base number `a` so far
269 /// - number which needs to be shifted to the right
270 ///
271 /// At the end of the operation, exponent is replaced with its square, current value of power
272 /// of base number `a` on exponent is incorporated into the accumulator and the number is
273 /// shifted to the right by one bit.
274 Expacc = OPCODE_EXPACC,
275
276 // ----- ext2 operations ---------------------------------------------------------------------
277 /// Computes the product of two elements in the extension field of degree 2 and pushes the
278 /// result back onto the stack as the third and fourth elements. Pushes 0 onto the stack as
279 /// the first and second elements.
280 ///
281 /// The extension field is defined as 𝔽ₚ\[x\]/(x² - x + 2), i.e. using the
282 /// irreducible quadratic polynomial x² - x + 2 over the base field.
283 Ext2Mul = OPCODE_EXT2MUL,
284
285 // ----- u32 operations ----------------------------------------------------------------------
286 /// Pops an element off the stack, splits it into upper and lower 32-bit values, and pushes
287 /// these values back onto the stack.
288 U32split = OPCODE_U32SPLIT,
289
290 /// Pops two elements off the stack, adds them, and splits the result into upper and lower
291 /// 32-bit values. Then pushes these values back onto the stack.
292 ///
293 /// If either of these elements is greater than or equal to 2^32, the result of this
294 /// operation is undefined.
295 U32add = OPCODE_U32ADD,
296
297 /// Pops two elements off the stack and checks if each of them represents a 32-bit value.
298 /// If both of them are, they are pushed back onto the stack, otherwise an error is returned.
299 ///
300 /// The internal value specifies an error code associated with the error in case when the
301 /// assertion fails.
302 U32assert2(Felt) = OPCODE_U32ASSERT2,
303
304 /// Pops three elements off the stack, adds them together, and splits the result into upper
305 /// and lower 32-bit values. Then pushes the result back onto the stack.
306 U32add3 = OPCODE_U32ADD3,
307
308 /// Pops two elements off the stack and subtracts the first element from the second. Then,
309 /// the result, together with a flag indicating whether subtraction underflowed is pushed
310 /// onto the stack.
311 ///
312 /// If their of the values is greater than or equal to 2^32, the result of this operation is
313 /// undefined.
314 U32sub = OPCODE_U32SUB,
315
316 /// Pops two elements off the stack, multiplies them, and splits the result into upper and
317 /// lower 32-bit values. Then pushes these values back onto the stack.
318 ///
319 /// If their of the values is greater than or equal to 2^32, the result of this operation is
320 /// undefined.
321 U32mul = OPCODE_U32MUL,
322
323 /// Pops two elements off the stack and multiplies them. Then pops the third element off the
324 /// stack, and adds it to the result. Finally, splits the result into upper and lower 32-bit
325 /// values, and pushes them onto the stack.
326 ///
327 /// If any of the three values is greater than or equal to 2^32, the result of this operation
328 /// is undefined.
329 U32madd = OPCODE_U32MADD,
330
331 /// Pops two elements off the stack and divides the second element by the first. Then pushes
332 /// the integer result of the division, together with the remainder, onto the stack.
333 ///
334 /// If their of the values is greater than or equal to 2^32, the result of this operation is
335 /// undefined.
336 U32div = OPCODE_U32DIV,
337
338 /// Pops two elements off the stack, computes their binary AND, and pushes the result back
339 /// onto the stack.
340 ///
341 /// If either of the elements is greater than or equal to 2^32, execution fails.
342 U32and = OPCODE_U32AND,
343
344 /// Pops two elements off the stack, computes their binary XOR, and pushes the result back
345 /// onto the stack.
346 ///
347 /// If either of the elements is greater than or equal to 2^32, execution fails.
348 U32xor = OPCODE_U32XOR,
349
350 // ----- stack manipulation ------------------------------------------------------------------
351 /// Pushes 0 onto the stack.
352 Pad = OPCODE_PAD,
353
354 /// Removes to element from the stack.
355 Drop = OPCODE_DROP,
356
357 /// Pushes a copy of stack element 0 onto the stack.
358 Dup0 = OPCODE_DUP0,
359
360 /// Pushes a copy of stack element 1 onto the stack.
361 Dup1 = OPCODE_DUP1,
362
363 /// Pushes a copy of stack element 2 onto the stack.
364 Dup2 = OPCODE_DUP2,
365
366 /// Pushes a copy of stack element 3 onto the stack.
367 Dup3 = OPCODE_DUP3,
368
369 /// Pushes a copy of stack element 4 onto the stack.
370 Dup4 = OPCODE_DUP4,
371
372 /// Pushes a copy of stack element 5 onto the stack.
373 Dup5 = OPCODE_DUP5,
374
375 /// Pushes a copy of stack element 6 onto the stack.
376 Dup6 = OPCODE_DUP6,
377
378 /// Pushes a copy of stack element 7 onto the stack.
379 Dup7 = OPCODE_DUP7,
380
381 /// Pushes a copy of stack element 9 onto the stack.
382 Dup9 = OPCODE_DUP9,
383
384 /// Pushes a copy of stack element 11 onto the stack.
385 Dup11 = OPCODE_DUP11,
386
387 /// Pushes a copy of stack element 13 onto the stack.
388 Dup13 = OPCODE_DUP13,
389
390 /// Pushes a copy of stack element 15 onto the stack.
391 Dup15 = OPCODE_DUP15,
392
393 /// Swaps stack elements 0 and 1.
394 Swap = OPCODE_SWAP,
395
396 /// Swaps stack elements 0, 1, 2, and 3 with elements 4, 5, 6, and 7.
397 SwapW = OPCODE_SWAPW,
398
399 /// Swaps stack elements 0, 1, 2, and 3 with elements 8, 9, 10, and 11.
400 SwapW2 = OPCODE_SWAPW2,
401
402 /// Swaps stack elements 0, 1, 2, and 3, with elements 12, 13, 14, and 15.
403 SwapW3 = OPCODE_SWAPW3,
404
405 /// Swaps the top two words pair wise.
406 ///
407 /// Input: [D, C, B, A, ...]
408 /// Output: [B, A, D, C, ...]
409 SwapDW = OPCODE_SWAPDW,
410
411 /// Moves stack element 2 to the top of the stack.
412 MovUp2 = OPCODE_MOVUP2,
413
414 /// Moves stack element 3 to the top of the stack.
415 MovUp3 = OPCODE_MOVUP3,
416
417 /// Moves stack element 4 to the top of the stack.
418 MovUp4 = OPCODE_MOVUP4,
419
420 /// Moves stack element 5 to the top of the stack.
421 MovUp5 = OPCODE_MOVUP5,
422
423 /// Moves stack element 6 to the top of the stack.
424 MovUp6 = OPCODE_MOVUP6,
425
426 /// Moves stack element 7 to the top of the stack.
427 MovUp7 = OPCODE_MOVUP7,
428
429 /// Moves stack element 8 to the top of the stack.
430 MovUp8 = OPCODE_MOVUP8,
431
432 /// Moves the top stack element to position 2 on the stack.
433 MovDn2 = OPCODE_MOVDN2,
434
435 /// Moves the top stack element to position 3 on the stack.
436 MovDn3 = OPCODE_MOVDN3,
437
438 /// Moves the top stack element to position 4 on the stack.
439 MovDn4 = OPCODE_MOVDN4,
440
441 /// Moves the top stack element to position 5 on the stack.
442 MovDn5 = OPCODE_MOVDN5,
443
444 /// Moves the top stack element to position 6 on the stack.
445 MovDn6 = OPCODE_MOVDN6,
446
447 /// Moves the top stack element to position 7 on the stack.
448 MovDn7 = OPCODE_MOVDN7,
449
450 /// Moves the top stack element to position 8 on the stack.
451 MovDn8 = OPCODE_MOVDN8,
452
453 /// Pops an element off the stack, and if the element is 1, swaps the top two remaining
454 /// elements on the stack. If the popped element is 0, the stack remains unchanged.
455 ///
456 /// If the popped element is neither 0 nor 1, execution fails.
457 CSwap = OPCODE_CSWAP,
458
459 /// Pops an element off the stack, and if the element is 1, swaps the remaining elements
460 /// 0, 1, 2, and 3 with elements 4, 5, 6, and 7. If the popped element is 0, the stack
461 /// remains unchanged.
462 ///
463 /// If the popped element is neither 0 nor 1, execution fails.
464 CSwapW = OPCODE_CSWAPW,
465
466 // ----- input / output ----------------------------------------------------------------------
467 /// Pushes the immediate value onto the stack.
468 Push(Felt) = OPCODE_PUSH,
469
470 /// Removes the next element from the advice stack and pushes it onto the operand stack.
471 AdvPop = OPCODE_ADVPOP,
472
473 /// Removes a word (4 elements) from the advice stack and overwrites the top four operand
474 /// stack elements with it.
475 AdvPopW = OPCODE_ADVPOPW,
476
477 /// Pops an element off the stack, interprets it as a memory address, and replaces the
478 /// remaining 4 elements at the top of the stack with values located at the specified address.
479 MLoadW = OPCODE_MLOADW,
480
481 /// Pops an element off the stack, interprets it as a memory address, and writes the remaining
482 /// 4 elements at the top of the stack into memory at the specified address.
483 MStoreW = OPCODE_MSTOREW,
484
485 /// Pops an element off the stack, interprets it as a memory address, and pushes the first
486 /// element of the word located at the specified address to the stack.
487 MLoad = OPCODE_MLOAD,
488
489 /// Pops an element off the stack, interprets it as a memory address, and writes the remaining
490 /// element at the top of the stack into the first element of the word located at the specified
491 /// memory address. The remaining 3 elements of the word are not affected.
492 MStore = OPCODE_MSTORE,
493
494 /// Loads two words from memory, and replaces the top 8 elements of the stack with them,
495 /// element-wise, in stack order.
496 ///
497 /// The operation works as follows:
498 /// - The memory address of the first word is retrieved from 13th stack element (position 12).
499 /// - Two consecutive words, starting at this address, are loaded from memory.
500 /// - The top 8 elements of the stack are overwritten with these words (element-wise, in stack
501 /// order).
502 /// - Memory address (in position 12) is incremented by 2.
503 /// - All other stack elements remain the same.
504 MStream = OPCODE_MSTREAM,
505
506 /// Pops two words from the advice stack, writes them to memory, and replaces the top 8
507 /// elements of the stack with them, element-wise, in stack order.
508 ///
509 /// The operation works as follows:
510 /// - Two words are popped from the advice stack.
511 /// - The destination memory address for the first word is retrieved from the 13th stack element
512 /// (position 12).
513 /// - The two words are written to memory consecutively, starting at this address.
514 /// - The top 8 elements of the stack are overwritten with these words (element-wise, in stack
515 /// order).
516 /// - Memory address (in position 12) is incremented by 2.
517 /// - All other stack elements remain the same.
518 Pipe = OPCODE_PIPE,
519
520 // ----- cryptographic operations ------------------------------------------------------------
521 /// Performs a Rescue Prime Optimized permutation on the top 3 words of the operand stack,
522 /// where the top 2 words are the rate (words C and B), the deepest word is the capacity (word
523 /// A), and the digest output is the middle word E.
524 ///
525 /// Stack transition:
526 /// [C, B, A, ...] -> [F, E, D, ...]
527 HPerm = OPCODE_HPERM,
528
529 /// Verifies that a Merkle path from the specified node resolves to the specified root. This
530 /// operation can be used to prove that the prover knows a path in the specified Merkle tree
531 /// which starts with the specified node.
532 ///
533 /// The stack is expected to be arranged as follows (from the top):
534 /// - value of the node, 4 elements.
535 /// - depth of the path, 1 element.
536 /// - index of the node, 1 element.
537 /// - root of the tree, 4 elements.
538 ///
539 /// The Merkle path itself is expected to be provided by the prover non-deterministically (via
540 /// merkle sets). If the prover is not able to provide the required path, the operation fails.
541 /// The state of the stack does not change.
542 ///
543 /// The internal value specifies an error code associated with the error in case when the
544 /// assertion fails.
545 MpVerify(Felt) = OPCODE_MPVERIFY,
546
547 /// Computes a new root of a Merkle tree where a node at the specified position is updated to
548 /// the specified value.
549 ///
550 /// The stack is expected to be arranged as follows (from the top):
551 /// - old value of the node, 4 element
552 /// - depth of the node, 1 element
553 /// - index of the node, 1 element
554 /// - current root of the tree, 4 elements
555 /// - new value of the node, 4 element
556 ///
557 /// The Merkle path for the node is expected to be provided by the prover non-deterministically
558 /// via the advice provider. At the end of the operation, the old node value is replaced with
559 /// the new root value, that is computed based on the provided path. Everything else on the
560 /// stack remains the same.
561 ///
562 /// The tree will always be copied into a new instance, meaning the advice provider will keep
563 /// track of both the old and new Merkle trees.
564 MrUpdate = OPCODE_MRUPDATE,
565
566 /// Performs FRI (Fast Reed-Solomon Interactive Oracle Proofs) layer folding by a factor of 4
567 /// for FRI protocol executed in a degree 2 extension of the base field.
568 ///
569 /// This operation:
570 /// - Folds 4 query values (v0, v1), (v2, v3), (v4, v5), (v6, v7) into a single value (ne0, ne1)
571 /// - Computes new value of the domain generator power: poe' = poe^4
572 /// - Increments layer pointer (cptr) by 2
573 /// - Checks that the previous folding was done correctly
574 /// - Shifts the stack to move an item from the overflow table to stack position 15
575 ///
576 /// Stack transition:
577 /// Input: [v7, v6, v5, v4, v3, v2, v1, v0, f_pos, d_seg, poe, pe1, pe0, a1, a0, cptr, ...]
578 /// Output: [t1, t0, s1, s0, df3, df2, df1, df0, poe^2, f_tau, cptr+2, poe^4, f_pos, ne1, ne0,
579 /// eptr, ...] where eptr is moved from the stack overflow table and is the address of the
580 /// final FRI layer.
581 FriE2F4 = OPCODE_FRIE2F4,
582
583 /// Performs 8 steps of the Horner evaluation method on a polynomial with coefficients over
584 /// the base field, i.e., it computes
585 ///
586 /// acc' = (((acc_tmp * alpha + c3) * alpha + c2) * alpha + c1) * alpha + c0
587 ///
588 /// where
589 ///
590 /// acc_tmp := (((acc * alpha + c7) * alpha + c6) * alpha + c5) * alpha + c4
591 ///
592 ///
593 /// In other words, the intsruction computes the evaluation at alpha of the polynomial
594 ///
595 /// P(X) := c7 * X^7 + c6 * X^6 + ... + c1 * X + c0
596 HornerBase = OPCODE_HORNERBASE,
597
598 /// Performs 4 steps of the Horner evaluation method on a polynomial with coefficients over
599 /// the extension field, i.e., it computes
600 ///
601 /// acc' = (((acc * alpha + c3) * alpha + c2) * alpha + c1) * alpha + c0
602 ///
603 /// In other words, the intsruction computes the evaluation at alpha of the polynomial
604 ///
605 /// P(X) := c3 * X^3 + c2 * X^2 + c1 * X + c0
606 HornerExt = OPCODE_HORNEREXT,
607
608 /// Evaluates an arithmetic circuit given a pointer to its description in memory, the number
609 /// of arithmetic gates, and the sum of the input and constant gates.
610 EvalCircuit = OPCODE_EVALCIRCUIT,
611
612 /// Logs a precompile event. This instruction is used to signal that a precompile computation
613 /// was requested.
614 LogPrecompile = OPCODE_LOGPRECOMPILE,
615}
616
617impl Operation {
618 pub const OP_BITS: usize = 7;
619
620 /// Returns the opcode of this operation.
621 #[rustfmt::skip]
622 pub fn op_code(&self) -> u8 {
623 // SAFETY: This is safe because we have given this enum a primitive representation with
624 // #[repr(u8)], with the first field of the underlying union-of-structs the discriminant.
625 //
626 // See the section on "accessing the numeric value of the discriminant"
627 // here: https://doc.rust-lang.org/std/mem/fn.discriminant.html
628 unsafe { *<*const _>::from(self).cast::<u8>() }
629 }
630
631 /// Returns an immediate value carried by this operation.
632 // Proptest generators for operations in crate::mast::node::basic_block_node::tests discriminate
633 // on this flag, please update them when you modify the semantics of this method.
634 pub fn imm_value(&self) -> Option<Felt> {
635 match *self {
636 Self::Push(imm) => Some(imm),
637 _ => None,
638 }
639 }
640
641 /// Returns true if this operation writes any data to the decoder hasher registers.
642 ///
643 /// In other words, if so, then the user op helper registers are not available.
644 pub fn populates_decoder_hasher_registers(&self) -> bool {
645 matches!(
646 self,
647 Self::End
648 | Self::Join
649 | Self::Split
650 | Self::Loop
651 | Self::Repeat
652 | Self::Respan
653 | Self::Span
654 | Self::Halt
655 | Self::Call
656 | Self::SysCall
657 )
658 }
659}
660
661impl crate::prettier::PrettyPrint for Operation {
662 fn render(&self) -> crate::prettier::Document {
663 crate::prettier::display(self)
664 }
665}
666
667impl fmt::Display for Operation {
668 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
669 match self {
670 // ----- system operations ------------------------------------------------------------
671 Self::Noop => write!(f, "noop"),
672 Self::Assert(err_code) => write!(f, "assert({err_code})"),
673
674 Self::SDepth => write!(f, "sdepth"),
675 Self::Caller => write!(f, "caller"),
676
677 Self::Clk => write!(f, "clk"),
678
679 // ----- flow control operations ------------------------------------------------------
680 Self::Join => write!(f, "join"),
681 Self::Split => write!(f, "split"),
682 Self::Loop => write!(f, "loop"),
683 Self::Call => writeln!(f, "call"),
684 Self::Dyncall => writeln!(f, "dyncall"),
685 Self::SysCall => writeln!(f, "syscall"),
686 Self::Dyn => writeln!(f, "dyn"),
687 Self::Span => write!(f, "span"),
688 Self::End => write!(f, "end"),
689 Self::Repeat => write!(f, "repeat"),
690 Self::Respan => write!(f, "respan"),
691 Self::Halt => write!(f, "halt"),
692
693 // ----- field operations -------------------------------------------------------------
694 Self::Add => write!(f, "add"),
695 Self::Neg => write!(f, "neg"),
696 Self::Mul => write!(f, "mul"),
697 Self::Inv => write!(f, "inv"),
698 Self::Incr => write!(f, "incr"),
699
700 Self::And => write!(f, "and"),
701 Self::Or => write!(f, "or"),
702 Self::Not => write!(f, "not"),
703
704 Self::Eq => write!(f, "eq"),
705 Self::Eqz => write!(f, "eqz"),
706
707 Self::Expacc => write!(f, "expacc"),
708
709 // ----- ext2 operations --------------------------------------------------------------
710 Self::Ext2Mul => write!(f, "ext2mul"),
711
712 // ----- u32 operations ---------------------------------------------------------------
713 Self::U32assert2(err_code) => write!(f, "u32assert2({err_code})"),
714 Self::U32split => write!(f, "u32split"),
715 Self::U32add => write!(f, "u32add"),
716 Self::U32add3 => write!(f, "u32add3"),
717 Self::U32sub => write!(f, "u32sub"),
718 Self::U32mul => write!(f, "u32mul"),
719 Self::U32madd => write!(f, "u32madd"),
720 Self::U32div => write!(f, "u32div"),
721
722 Self::U32and => write!(f, "u32and"),
723 Self::U32xor => write!(f, "u32xor"),
724
725 // ----- stack manipulation -----------------------------------------------------------
726 Self::Drop => write!(f, "drop"),
727 Self::Pad => write!(f, "pad"),
728
729 Self::Dup0 => write!(f, "dup0"),
730 Self::Dup1 => write!(f, "dup1"),
731 Self::Dup2 => write!(f, "dup2"),
732 Self::Dup3 => write!(f, "dup3"),
733 Self::Dup4 => write!(f, "dup4"),
734 Self::Dup5 => write!(f, "dup5"),
735 Self::Dup6 => write!(f, "dup6"),
736 Self::Dup7 => write!(f, "dup7"),
737 Self::Dup9 => write!(f, "dup9"),
738 Self::Dup11 => write!(f, "dup11"),
739 Self::Dup13 => write!(f, "dup13"),
740 Self::Dup15 => write!(f, "dup15"),
741
742 Self::Swap => write!(f, "swap"),
743 Self::SwapW => write!(f, "swapw"),
744 Self::SwapW2 => write!(f, "swapw2"),
745 Self::SwapW3 => write!(f, "swapw3"),
746 Self::SwapDW => write!(f, "swapdw"),
747
748 Self::MovUp2 => write!(f, "movup2"),
749 Self::MovUp3 => write!(f, "movup3"),
750 Self::MovUp4 => write!(f, "movup4"),
751 Self::MovUp5 => write!(f, "movup5"),
752 Self::MovUp6 => write!(f, "movup6"),
753 Self::MovUp7 => write!(f, "movup7"),
754 Self::MovUp8 => write!(f, "movup8"),
755
756 Self::MovDn2 => write!(f, "movdn2"),
757 Self::MovDn3 => write!(f, "movdn3"),
758 Self::MovDn4 => write!(f, "movdn4"),
759 Self::MovDn5 => write!(f, "movdn5"),
760 Self::MovDn6 => write!(f, "movdn6"),
761 Self::MovDn7 => write!(f, "movdn7"),
762 Self::MovDn8 => write!(f, "movdn8"),
763
764 Self::CSwap => write!(f, "cswap"),
765 Self::CSwapW => write!(f, "cswapw"),
766
767 // ----- input / output ---------------------------------------------------------------
768 Self::Push(value) => write!(f, "push({value})"),
769
770 Self::AdvPop => write!(f, "advpop"),
771 Self::AdvPopW => write!(f, "advpopw"),
772
773 Self::MLoadW => write!(f, "mloadw"),
774 Self::MStoreW => write!(f, "mstorew"),
775
776 Self::MLoad => write!(f, "mload"),
777 Self::MStore => write!(f, "mstore"),
778
779 Self::MStream => write!(f, "mstream"),
780 Self::Pipe => write!(f, "pipe"),
781
782 Self::Emit => write!(f, "emit"),
783
784 // ----- cryptographic operations -----------------------------------------------------
785 Self::HPerm => write!(f, "hperm"),
786 Self::MpVerify(err_code) => write!(f, "mpverify({err_code})"),
787 Self::MrUpdate => write!(f, "mrupdate"),
788
789 // ----- STARK proof verification -----------------------------------------------------
790 Self::FriE2F4 => write!(f, "frie2f4"),
791 Self::HornerBase => write!(f, "horner_eval_base"),
792 Self::HornerExt => write!(f, "horner_eval_ext"),
793 Self::EvalCircuit => write!(f, "eval_circuit"),
794 Self::LogPrecompile => write!(f, "log_precompile"),
795 }
796 }
797}
798
799impl Serializable for Operation {
800 fn write_into<W: ByteWriter>(&self, target: &mut W) {
801 target.write_u8(self.op_code());
802
803 // For operations that have extra data, encode it in `data`.
804 match self {
805 Operation::Assert(err_code)
806 | Operation::MpVerify(err_code)
807 | Operation::U32assert2(err_code) => {
808 err_code.write_into(target);
809 },
810 Operation::Push(value) => value.as_int().write_into(target),
811
812 // Note: we explicitly write out all the operations so that whenever we make a
813 // modification to the `Operation` enum, we get a compile error here. This
814 // should help us remember to properly encode/decode each operation variant.
815 Operation::Noop
816 | Operation::SDepth
817 | Operation::Caller
818 | Operation::Clk
819 | Operation::Join
820 | Operation::Split
821 | Operation::Loop
822 | Operation::Call
823 | Operation::Dyn
824 | Operation::Dyncall
825 | Operation::SysCall
826 | Operation::Span
827 | Operation::End
828 | Operation::Repeat
829 | Operation::Respan
830 | Operation::Halt
831 | Operation::Add
832 | Operation::Neg
833 | Operation::Mul
834 | Operation::Inv
835 | Operation::Incr
836 | Operation::And
837 | Operation::Or
838 | Operation::Not
839 | Operation::Eq
840 | Operation::Eqz
841 | Operation::Expacc
842 | Operation::Ext2Mul
843 | Operation::U32split
844 | Operation::U32add
845 | Operation::U32add3
846 | Operation::U32sub
847 | Operation::U32mul
848 | Operation::U32madd
849 | Operation::U32div
850 | Operation::U32and
851 | Operation::U32xor
852 | Operation::Pad
853 | Operation::Drop
854 | Operation::Dup0
855 | Operation::Dup1
856 | Operation::Dup2
857 | Operation::Dup3
858 | Operation::Dup4
859 | Operation::Dup5
860 | Operation::Dup6
861 | Operation::Dup7
862 | Operation::Dup9
863 | Operation::Dup11
864 | Operation::Dup13
865 | Operation::Dup15
866 | Operation::Swap
867 | Operation::SwapW
868 | Operation::SwapW2
869 | Operation::SwapW3
870 | Operation::SwapDW
871 | Operation::Emit
872 | Operation::MovUp2
873 | Operation::MovUp3
874 | Operation::MovUp4
875 | Operation::MovUp5
876 | Operation::MovUp6
877 | Operation::MovUp7
878 | Operation::MovUp8
879 | Operation::MovDn2
880 | Operation::MovDn3
881 | Operation::MovDn4
882 | Operation::MovDn5
883 | Operation::MovDn6
884 | Operation::MovDn7
885 | Operation::MovDn8
886 | Operation::CSwap
887 | Operation::CSwapW
888 | Operation::AdvPop
889 | Operation::AdvPopW
890 | Operation::MLoadW
891 | Operation::MStoreW
892 | Operation::MLoad
893 | Operation::MStore
894 | Operation::MStream
895 | Operation::Pipe
896 | Operation::HPerm
897 | Operation::MrUpdate
898 | Operation::FriE2F4
899 | Operation::HornerBase
900 | Operation::HornerExt
901 | Operation::EvalCircuit
902 | Operation::LogPrecompile => (),
903 }
904 }
905}
906
907impl Deserializable for Operation {
908 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
909 let op_code = source.read_u8()?;
910
911 let operation = match op_code {
912 OPCODE_NOOP => Self::Noop,
913 OPCODE_EQZ => Self::Eqz,
914 OPCODE_NEG => Self::Neg,
915 OPCODE_INV => Self::Inv,
916 OPCODE_INCR => Self::Incr,
917 OPCODE_NOT => Self::Not,
918 OPCODE_MLOAD => Self::MLoad,
919 OPCODE_SWAP => Self::Swap,
920 OPCODE_CALLER => Self::Caller,
921 OPCODE_MOVUP2 => Self::MovUp2,
922 OPCODE_MOVDN2 => Self::MovDn2,
923 OPCODE_MOVUP3 => Self::MovUp3,
924 OPCODE_MOVDN3 => Self::MovDn3,
925 OPCODE_ADVPOPW => Self::AdvPopW,
926 OPCODE_EXPACC => Self::Expacc,
927
928 OPCODE_MOVUP4 => Self::MovUp4,
929 OPCODE_MOVDN4 => Self::MovDn4,
930 OPCODE_MOVUP5 => Self::MovUp5,
931 OPCODE_MOVDN5 => Self::MovDn5,
932 OPCODE_MOVUP6 => Self::MovUp6,
933 OPCODE_MOVDN6 => Self::MovDn6,
934 OPCODE_MOVUP7 => Self::MovUp7,
935 OPCODE_MOVDN7 => Self::MovDn7,
936 OPCODE_SWAPW => Self::SwapW,
937 OPCODE_EXT2MUL => Self::Ext2Mul,
938 OPCODE_MOVUP8 => Self::MovUp8,
939 OPCODE_MOVDN8 => Self::MovDn8,
940 OPCODE_SWAPW2 => Self::SwapW2,
941 OPCODE_SWAPW3 => Self::SwapW3,
942 OPCODE_SWAPDW => Self::SwapDW,
943 OPCODE_EMIT => Self::Emit,
944
945 OPCODE_ASSERT => Self::Assert(Felt::read_from(source)?),
946 OPCODE_EQ => Self::Eq,
947 OPCODE_ADD => Self::Add,
948 OPCODE_MUL => Self::Mul,
949 OPCODE_AND => Self::And,
950 OPCODE_OR => Self::Or,
951 OPCODE_U32AND => Self::U32and,
952 OPCODE_U32XOR => Self::U32xor,
953 OPCODE_FRIE2F4 => Self::FriE2F4,
954 OPCODE_DROP => Self::Drop,
955 OPCODE_CSWAP => Self::CSwap,
956 OPCODE_CSWAPW => Self::CSwapW,
957 OPCODE_MLOADW => Self::MLoadW,
958 OPCODE_MSTORE => Self::MStore,
959 OPCODE_MSTOREW => Self::MStoreW,
960
961 OPCODE_PAD => Self::Pad,
962 OPCODE_DUP0 => Self::Dup0,
963 OPCODE_DUP1 => Self::Dup1,
964 OPCODE_DUP2 => Self::Dup2,
965 OPCODE_DUP3 => Self::Dup3,
966 OPCODE_DUP4 => Self::Dup4,
967 OPCODE_DUP5 => Self::Dup5,
968 OPCODE_DUP6 => Self::Dup6,
969 OPCODE_DUP7 => Self::Dup7,
970 OPCODE_DUP9 => Self::Dup9,
971 OPCODE_DUP11 => Self::Dup11,
972 OPCODE_DUP13 => Self::Dup13,
973 OPCODE_DUP15 => Self::Dup15,
974 OPCODE_ADVPOP => Self::AdvPop,
975 OPCODE_SDEPTH => Self::SDepth,
976 OPCODE_CLK => Self::Clk,
977
978 OPCODE_U32ADD => Self::U32add,
979 OPCODE_U32SUB => Self::U32sub,
980 OPCODE_U32MUL => Self::U32mul,
981 OPCODE_U32DIV => Self::U32div,
982 OPCODE_U32SPLIT => Self::U32split,
983 OPCODE_U32ASSERT2 => Self::U32assert2(Felt::read_from(source)?),
984 OPCODE_U32ADD3 => Self::U32add3,
985 OPCODE_U32MADD => Self::U32madd,
986
987 OPCODE_HPERM => Self::HPerm,
988 OPCODE_MPVERIFY => Self::MpVerify(Felt::read_from(source)?),
989 OPCODE_PIPE => Self::Pipe,
990 OPCODE_MSTREAM => Self::MStream,
991 OPCODE_SPLIT => Self::Split,
992 OPCODE_LOOP => Self::Loop,
993 OPCODE_SPAN => Self::Span,
994 OPCODE_JOIN => Self::Join,
995 OPCODE_DYN => Self::Dyn,
996 OPCODE_DYNCALL => Self::Dyncall,
997 OPCODE_HORNERBASE => Self::HornerBase,
998 OPCODE_HORNEREXT => Self::HornerExt,
999 OPCODE_LOGPRECOMPILE => Self::LogPrecompile,
1000 OPCODE_EVALCIRCUIT => Self::EvalCircuit,
1001
1002 OPCODE_MRUPDATE => Self::MrUpdate,
1003 OPCODE_PUSH => Self::Push(Felt::read_from(source)?),
1004 OPCODE_SYSCALL => Self::SysCall,
1005 OPCODE_CALL => Self::Call,
1006 OPCODE_END => Self::End,
1007 OPCODE_REPEAT => Self::Repeat,
1008 OPCODE_RESPAN => Self::Respan,
1009 OPCODE_HALT => Self::Halt,
1010 _ => {
1011 return Err(DeserializationError::InvalidValue(format!(
1012 "Invalid opcode '{op_code}'"
1013 )));
1014 },
1015 };
1016
1017 Ok(operation)
1018 }
1019}