miden_core/operations/
mod.rs

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