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