miden_core/operations/mod.rs
1use core::fmt;
2
3mod debug_metadata;
4pub use debug_metadata::AssemblyOp;
5
6use crate::{
7 Felt,
8 serde::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
9};
10
11// OPERATIONS AND CONTROL FLOW OPCODES
12// ================================================================================================
13
14/// Opcode patterns have the following meanings:
15/// - 00xxxxx operations do not shift the stack; constraint degree can be up to 2.
16/// - 010xxxx operations shift the stack the left; constraint degree can be up to 2.
17/// - 011xxxx operations shift the stack to the right; constraint degree can be up to 2.
18/// - 100xxx-: operations consume 4 range checks; constraint degree can be up to 3. These are used
19/// to encode most u32 operations.
20/// - 101xxx-: operations where constraint degree can be up to 3. These include control flow
21/// operations and some other operations requiring high degree constraints.
22/// - 11xxx--: operations where constraint degree can be up to 5. These include control flow
23/// operations and some other operations requiring very high degree constraints.
24#[rustfmt::skip]
25pub mod opcodes {
26 pub const NOOP: u8 = 0b0000_0000;
27 pub const EQZ: u8 = 0b0000_0001;
28 pub const NEG: u8 = 0b0000_0010;
29 pub const INV: u8 = 0b0000_0011;
30 pub const INCR: u8 = 0b0000_0100;
31 pub const NOT: u8 = 0b0000_0101;
32 /* unused 0b0000_0110 */
33 pub const MLOAD: u8 = 0b0000_0111;
34 pub const SWAP: u8 = 0b0000_1000;
35 pub const CALLER: u8 = 0b0000_1001;
36 pub const MOVUP2: u8 = 0b0000_1010;
37 pub const MOVDN2: u8 = 0b0000_1011;
38 pub const MOVUP3: u8 = 0b0000_1100;
39 pub const MOVDN3: u8 = 0b0000_1101;
40 pub const ADVPOPW: u8 = 0b0000_1110;
41 pub const EXPACC: u8 = 0b0000_1111;
42
43 pub const MOVUP4: u8 = 0b0001_0000;
44 pub const MOVDN4: u8 = 0b0001_0001;
45 pub const MOVUP5: u8 = 0b0001_0010;
46 pub const MOVDN5: u8 = 0b0001_0011;
47 pub const MOVUP6: u8 = 0b0001_0100;
48 pub const MOVDN6: u8 = 0b0001_0101;
49 pub const MOVUP7: u8 = 0b0001_0110;
50 pub const MOVDN7: u8 = 0b0001_0111;
51 pub const SWAPW: u8 = 0b0001_1000;
52 pub const EXT2MUL: u8 = 0b0001_1001;
53 pub const MOVUP8: u8 = 0b0001_1010;
54 pub const MOVDN8: u8 = 0b0001_1011;
55 pub const SWAPW2: u8 = 0b0001_1100;
56 pub const SWAPW3: u8 = 0b0001_1101;
57 pub const SWAPDW: u8 = 0b0001_1110;
58 pub const EMIT: u8 = 0b0001_1111;
59
60 pub const ASSERT: u8 = 0b0010_0000;
61 pub const EQ: u8 = 0b0010_0001;
62 pub const ADD: u8 = 0b0010_0010;
63 pub const MUL: u8 = 0b0010_0011;
64 pub const AND: u8 = 0b0010_0100;
65 pub const OR: u8 = 0b0010_0101;
66 pub const U32AND: u8 = 0b0010_0110;
67 pub const U32XOR: u8 = 0b0010_0111;
68 pub const FRIE2F4: u8 = 0b0010_1000;
69 pub const DROP: u8 = 0b0010_1001;
70 pub const CSWAP: u8 = 0b0010_1010;
71 pub const CSWAPW: u8 = 0b0010_1011;
72 pub const MLOADW: u8 = 0b0010_1100;
73 pub const MSTORE: u8 = 0b0010_1101;
74 pub const MSTOREW: u8 = 0b0010_1110;
75 /* unused 0b0010_1111 */
76
77 pub const PAD: u8 = 0b0011_0000;
78 pub const DUP0: u8 = 0b0011_0001;
79 pub const DUP1: u8 = 0b0011_0010;
80 pub const DUP2: u8 = 0b0011_0011;
81 pub const DUP3: u8 = 0b0011_0100;
82 pub const DUP4: u8 = 0b0011_0101;
83 pub const DUP5: u8 = 0b0011_0110;
84 pub const DUP6: u8 = 0b0011_0111;
85 pub const DUP7: u8 = 0b0011_1000;
86 pub const DUP9: u8 = 0b0011_1001;
87 pub const DUP11: u8 = 0b0011_1010;
88 pub const DUP13: u8 = 0b0011_1011;
89 pub const DUP15: u8 = 0b0011_1100;
90 pub const ADVPOP: u8 = 0b0011_1101;
91 pub const SDEPTH: u8 = 0b0011_1110;
92 pub const CLK: u8 = 0b0011_1111;
93
94 pub const U32ADD: u8 = 0b0100_0000;
95 pub const U32SUB: u8 = 0b0100_0010;
96 pub const U32MUL: u8 = 0b0100_0100;
97 pub const U32DIV: u8 = 0b0100_0110;
98 pub const U32SPLIT: u8 = 0b0100_1000;
99 pub const U32ASSERT2: u8 = 0b0100_1010;
100 pub const U32ADD3: u8 = 0b0100_1100;
101 pub const U32MADD: u8 = 0b0100_1110;
102
103 pub const HPERM: u8 = 0b0101_0000;
104 pub const MPVERIFY: u8 = 0b0101_0001;
105 pub const PIPE: u8 = 0b0101_0010;
106 pub const MSTREAM: u8 = 0b0101_0011;
107 pub const SPLIT: u8 = 0b0101_0100;
108 pub const LOOP: u8 = 0b0101_0101;
109 pub const SPAN: u8 = 0b0101_0110;
110 pub const JOIN: u8 = 0b0101_0111;
111 pub const DYN: u8 = 0b0101_1000;
112 pub const HORNERBASE: u8 = 0b0101_1001;
113 pub const HORNEREXT: u8 = 0b0101_1010;
114 pub const PUSH: u8 = 0b0101_1011;
115 pub const DYNCALL: u8 = 0b0101_1100;
116 pub const EVALCIRCUIT: u8 = 0b0101_1101;
117 pub const LOGDEFERRED: u8 = 0b0101_1110;
118
119 pub const MRUPDATE: u8 = 0b0110_0000;
120 pub const CRYPTOSTREAM: u8 = 0b0110_0100;
121 pub const SYSCALL: u8 = 0b0110_1000;
122 pub const CALL: u8 = 0b0110_1100;
123 pub const END: u8 = 0b0111_0000;
124 pub const REPEAT: u8 = 0b0111_0100;
125 pub const RESPAN: u8 = 0b0111_1000;
126 pub const HALT: u8 = 0b0111_1100;
127}
128
129// OPERATIONS
130// ================================================================================================
131
132/// The set of native VM basic block operations executable which take exactly one cycle to execute.
133///
134/// Specifically, the operations encoded here are only those which can be executed within basic
135/// blocks, i.e., they exclude all control flow operations (e.g., `Loop`, `Span`, `Join`, etc.).
136/// Note though that those operations have their own unique opcode which lives in the same 7-bit
137/// opcode space as the basic block operations.
138#[derive(Copy, Clone, Debug, Eq, PartialEq)]
139#[repr(u8)]
140pub enum Operation {
141 // ----- system operations -------------------------------------------------------------------
142 /// Advances cycle counter, but does not change the state of user stack.
143 Noop = opcodes::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) = opcodes::ASSERT,
150
151 /// Pushes the current depth of the stack onto the stack.
152 SDepth = opcodes::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 = opcodes::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 = opcodes::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 identified by reserved [`SystemEvent`](crate::events::SystemEvent) IDs.
172 /// Most are handled by the VM; `SystemEvent::TraceEvent` triggers the host's optional
173 /// read-only trace handler for the trace event id at stack position 1. Assembly exposes this
174 /// through `trace`, `trace.CONST`, and `trace.event("...")`.
175 /// - Any non system event ID is forwarded to the host's regular event handler.
176 ///
177 /// This operation does not change the state of the user stack aside from reading the value.
178 Emit = opcodes::EMIT,
179
180 // ----- field operations --------------------------------------------------------------------
181 /// Pops two elements off the stack, adds them, and pushes the result back onto the stack.
182 Add = opcodes::ADD,
183
184 /// Pops an element off the stack, negates it, and pushes the result back onto the stack.
185 Neg = opcodes::NEG,
186
187 /// Pops two elements off the stack, multiplies them, and pushes the result back onto the
188 /// stack.
189 Mul = opcodes::MUL,
190
191 /// Pops an element off the stack, computes its multiplicative inverse, and pushes the result
192 /// back onto the stack.
193 Inv = opcodes::INV,
194
195 /// Pops an element off the stack, adds 1 to it, and pushes the result back onto the stack.
196 Incr = opcodes::INCR,
197
198 /// Pops two elements off the stack, multiplies them, and pushes the result back onto the
199 /// stack.
200 ///
201 /// If either of the elements is greater than 1, execution fails. This operation is equivalent
202 /// to boolean AND.
203 And = opcodes::AND,
204
205 /// Pops two elements off the stack and subtracts their product from their sum.
206 ///
207 /// If either of the elements is greater than 1, execution fails. This operation is equivalent
208 /// to boolean OR.
209 Or = opcodes::OR,
210
211 /// Pops an element off the stack and subtracts it from 1.
212 ///
213 /// If the element is greater than one, the execution fails. This operation is equivalent to
214 /// boolean NOT.
215 Not = opcodes::NOT,
216
217 /// Pops two elements off the stack and compares them. If the elements are equal, pushes 1
218 /// onto the stack, otherwise pushes 0 onto the stack.
219 Eq = opcodes::EQ,
220
221 /// Pops an element off the stack and compares it to 0. If the element is 0, pushes 1 onto
222 /// the stack, otherwise pushes 0 onto the stack.
223 Eqz = opcodes::EQZ,
224
225 /// Computes a single turn of exponent accumulation for the given inputs. This operation can be
226 /// be used to compute a single turn of power of a field element.
227 ///
228 /// The top 4 elements of the stack are expected to be arranged as follows (form the top):
229 /// - least significant bit of the exponent in the previous trace if there's an expacc call,
230 /// otherwise ZERO
231 /// - exponent of base number `a` for this turn
232 /// - accumulated power of base number `a` so far
233 /// - number which needs to be shifted to the right
234 ///
235 /// At the end of the operation, exponent is replaced with its square, current value of power
236 /// of base number `a` on exponent is incorporated into the accumulator and the number is
237 /// shifted to the right by one bit.
238 Expacc = opcodes::EXPACC,
239
240 // ----- ext2 operations ---------------------------------------------------------------------
241 /// Computes the product of two elements in the extension field of degree 2 and pushes the
242 /// result back onto the stack as the third and fourth elements. Pushes 0 onto the stack as
243 /// the first and second elements.
244 ///
245 /// The extension field is defined as 𝔽ₚ\[x\]/(x² - 7), i.e. using the
246 /// irreducible quadratic polynomial x² - 7 over the base field.
247 Ext2Mul = opcodes::EXT2MUL,
248
249 // ----- u32 operations ----------------------------------------------------------------------
250 /// Pops an element off the stack, splits it into upper and lower 32-bit values, and pushes
251 /// these values back onto the stack.
252 U32split = opcodes::U32SPLIT,
253
254 /// Pops two elements off the stack, adds them, and splits the result into upper and lower
255 /// 32-bit values. Then pushes these values back onto the stack.
256 ///
257 /// If either of these elements is greater than or equal to 2^32, the result of this
258 /// operation is undefined.
259 U32add = opcodes::U32ADD,
260
261 /// Pops two elements off the stack and checks if each of them represents a 32-bit value.
262 /// If both of them are, they are pushed back onto the stack, otherwise an error is returned.
263 ///
264 /// The internal value specifies an error code associated with the error in case when the
265 /// assertion fails.
266 U32assert2(Felt) = opcodes::U32ASSERT2,
267
268 /// Pops three elements off the stack, adds them together, and splits the result into upper
269 /// and lower 32-bit values. Then pushes the result back onto the stack.
270 U32add3 = opcodes::U32ADD3,
271
272 /// Pops two elements off the stack and subtracts the first element from the second. Then,
273 /// the result, together with a flag indicating whether subtraction underflowed is pushed
274 /// onto the stack.
275 ///
276 /// If their of the values is greater than or equal to 2^32, the result of this operation is
277 /// undefined.
278 U32sub = opcodes::U32SUB,
279
280 /// Pops two elements off the stack, multiplies them, and splits the result into upper and
281 /// lower 32-bit values. Then pushes these values back onto the stack.
282 ///
283 /// If their of the values is greater than or equal to 2^32, the result of this operation is
284 /// undefined.
285 U32mul = opcodes::U32MUL,
286
287 /// Pops two elements off the stack and multiplies them. Then pops the third element off the
288 /// stack, and adds it to the result. Finally, splits the result into upper and lower 32-bit
289 /// values, and pushes them onto the stack.
290 ///
291 /// If any of the three values is greater than or equal to 2^32, the result of this operation
292 /// is undefined.
293 U32madd = opcodes::U32MADD,
294
295 /// Pops two elements off the stack and divides the second element by the first. Then pushes
296 /// the integer result of the division, together with the remainder, onto the stack.
297 ///
298 /// If their of the values is greater than or equal to 2^32, the result of this operation is
299 /// undefined.
300 U32div = opcodes::U32DIV,
301
302 /// Pops two elements off the stack, computes their binary AND, and pushes the result back
303 /// onto the stack.
304 ///
305 /// If either of the elements is greater than or equal to 2^32, execution fails.
306 U32and = opcodes::U32AND,
307
308 /// Pops two elements off the stack, computes their binary XOR, and pushes the result back
309 /// onto the stack.
310 ///
311 /// If either of the elements is greater than or equal to 2^32, execution fails.
312 U32xor = opcodes::U32XOR,
313
314 // ----- stack manipulation ------------------------------------------------------------------
315 /// Pushes 0 onto the stack.
316 Pad = opcodes::PAD,
317
318 /// Removes to element from the stack.
319 Drop = opcodes::DROP,
320
321 /// Pushes a copy of stack element 0 onto the stack.
322 Dup0 = opcodes::DUP0,
323
324 /// Pushes a copy of stack element 1 onto the stack.
325 Dup1 = opcodes::DUP1,
326
327 /// Pushes a copy of stack element 2 onto the stack.
328 Dup2 = opcodes::DUP2,
329
330 /// Pushes a copy of stack element 3 onto the stack.
331 Dup3 = opcodes::DUP3,
332
333 /// Pushes a copy of stack element 4 onto the stack.
334 Dup4 = opcodes::DUP4,
335
336 /// Pushes a copy of stack element 5 onto the stack.
337 Dup5 = opcodes::DUP5,
338
339 /// Pushes a copy of stack element 6 onto the stack.
340 Dup6 = opcodes::DUP6,
341
342 /// Pushes a copy of stack element 7 onto the stack.
343 Dup7 = opcodes::DUP7,
344
345 /// Pushes a copy of stack element 9 onto the stack.
346 Dup9 = opcodes::DUP9,
347
348 /// Pushes a copy of stack element 11 onto the stack.
349 Dup11 = opcodes::DUP11,
350
351 /// Pushes a copy of stack element 13 onto the stack.
352 Dup13 = opcodes::DUP13,
353
354 /// Pushes a copy of stack element 15 onto the stack.
355 Dup15 = opcodes::DUP15,
356
357 /// Swaps stack elements 0 and 1.
358 Swap = opcodes::SWAP,
359
360 /// Swaps stack elements 0, 1, 2, and 3 with elements 4, 5, 6, and 7.
361 SwapW = opcodes::SWAPW,
362
363 /// Swaps stack elements 0, 1, 2, and 3 with elements 8, 9, 10, and 11.
364 SwapW2 = opcodes::SWAPW2,
365
366 /// Swaps stack elements 0, 1, 2, and 3, with elements 12, 13, 14, and 15.
367 SwapW3 = opcodes::SWAPW3,
368
369 /// Swaps the top two words pair wise.
370 ///
371 /// Input: [D, C, B, A, ...]
372 /// Output: [B, A, D, C, ...]
373 SwapDW = opcodes::SWAPDW,
374
375 /// Moves stack element 2 to the top of the stack.
376 MovUp2 = opcodes::MOVUP2,
377
378 /// Moves stack element 3 to the top of the stack.
379 MovUp3 = opcodes::MOVUP3,
380
381 /// Moves stack element 4 to the top of the stack.
382 MovUp4 = opcodes::MOVUP4,
383
384 /// Moves stack element 5 to the top of the stack.
385 MovUp5 = opcodes::MOVUP5,
386
387 /// Moves stack element 6 to the top of the stack.
388 MovUp6 = opcodes::MOVUP6,
389
390 /// Moves stack element 7 to the top of the stack.
391 MovUp7 = opcodes::MOVUP7,
392
393 /// Moves stack element 8 to the top of the stack.
394 MovUp8 = opcodes::MOVUP8,
395
396 /// Moves the top stack element to position 2 on the stack.
397 MovDn2 = opcodes::MOVDN2,
398
399 /// Moves the top stack element to position 3 on the stack.
400 MovDn3 = opcodes::MOVDN3,
401
402 /// Moves the top stack element to position 4 on the stack.
403 MovDn4 = opcodes::MOVDN4,
404
405 /// Moves the top stack element to position 5 on the stack.
406 MovDn5 = opcodes::MOVDN5,
407
408 /// Moves the top stack element to position 6 on the stack.
409 MovDn6 = opcodes::MOVDN6,
410
411 /// Moves the top stack element to position 7 on the stack.
412 MovDn7 = opcodes::MOVDN7,
413
414 /// Moves the top stack element to position 8 on the stack.
415 MovDn8 = opcodes::MOVDN8,
416
417 /// Pops an element off the stack, and if the element is 1, swaps the top two remaining
418 /// elements on the stack. If the popped element is 0, the stack remains unchanged.
419 ///
420 /// If the popped element is neither 0 nor 1, execution fails.
421 CSwap = opcodes::CSWAP,
422
423 /// Pops an element off the stack, and if the element is 1, swaps the remaining elements
424 /// 0, 1, 2, and 3 with elements 4, 5, 6, and 7. If the popped element is 0, the stack
425 /// remains unchanged.
426 ///
427 /// If the popped element is neither 0 nor 1, execution fails.
428 CSwapW = opcodes::CSWAPW,
429
430 // ----- input / output ----------------------------------------------------------------------
431 /// Pushes the immediate value onto the stack.
432 Push(Felt) = opcodes::PUSH,
433
434 /// Removes the next element from the advice stack and pushes it onto the operand stack.
435 AdvPop = opcodes::ADVPOP,
436
437 /// Removes a word (4 elements) from the advice stack and overwrites the top four operand
438 /// stack elements with it.
439 AdvPopW = opcodes::ADVPOPW,
440
441 /// Pops an element off the stack, interprets it as a memory address, and replaces the
442 /// remaining 4 elements at the top of the stack with values located at the specified address.
443 MLoadW = opcodes::MLOADW,
444
445 /// Pops an element off the stack, interprets it as a memory address, and writes the remaining
446 /// 4 elements at the top of the stack into memory at the specified address.
447 MStoreW = opcodes::MSTOREW,
448
449 /// Pops an element off the stack, interprets it as a memory address, and pushes the first
450 /// element of the word located at the specified address to the stack.
451 MLoad = opcodes::MLOAD,
452
453 /// Pops an element off the stack, interprets it as a memory address, and writes the remaining
454 /// element at the top of the stack into the first element of the word located at the specified
455 /// memory address. The remaining 3 elements of the word are not affected.
456 MStore = opcodes::MSTORE,
457
458 /// Loads two words from memory, and replaces the top 8 elements of the stack with them,
459 /// element-wise, in stack order.
460 ///
461 /// The operation works as follows:
462 /// - The memory address of the first word is retrieved from 13th stack element (position 12).
463 /// - Two consecutive words, starting at this address, are loaded from memory.
464 /// - The top 8 elements of the stack are overwritten with these words (element-wise, in stack
465 /// order).
466 /// - Memory address (in position 12) is incremented by 2.
467 /// - All other stack elements remain the same.
468 MStream = opcodes::MSTREAM,
469
470 /// Pops two words from the advice stack, writes them to memory, and replaces the top 8
471 /// elements of the stack with them, element-wise, in stack order.
472 ///
473 /// The operation works as follows:
474 /// - Two words are popped from the advice stack.
475 /// - The destination memory address for the first word is retrieved from the 13th stack element
476 /// (position 12).
477 /// - The two words are written to memory consecutively, starting at this address.
478 /// - The top 8 elements of the stack are overwritten with these words (element-wise, in stack
479 /// order).
480 /// - Memory address (in position 12) is incremented by 2.
481 /// - All other stack elements remain the same.
482 Pipe = opcodes::PIPE,
483
484 /// Encrypts data from source memory to destination memory using the Poseidon2 sponge keystream.
485 ///
486 /// Two consecutive words (8 elements) are loaded from source memory, each element is added
487 /// to the corresponding element in the rate (top 8 stack elements), and the resulting
488 /// ciphertext is written to destination memory and replaces the rate. Source and destination
489 /// addresses are incremented by 8.
490 ///
491 /// Stack transition:
492 /// ```text
493 /// [rate(8), cap(4), src, dst, ...]
494 /// ↓
495 /// [ct(8), cap(4), src+8, dst+8, ...]
496 /// ```
497 /// where `ct = mem[src..src+8] + rate`, where addition is element-wise.
498 ///
499 /// After this operation, `hperm` should be applied to refresh the keystream for the next block.
500 CryptoStream = opcodes::CRYPTOSTREAM,
501
502 // ----- cryptographic operations ------------------------------------------------------------
503 /// Performs a Poseidon2 permutation on the top 3 words of the operand stack,
504 /// where the top 2 words are the rate (words C and B), the deepest word is the capacity (word
505 /// A), and the digest output is the middle word E.
506 ///
507 /// Stack transition:
508 /// [C, B, A, ...] -> [F, E, D, ...]
509 HPerm = opcodes::HPERM,
510
511 /// Verifies that a Merkle path from the specified node resolves to the specified root. This
512 /// operation can be used to prove that the prover knows a path in the specified Merkle tree
513 /// which starts with the specified node.
514 ///
515 /// The stack is expected to be arranged as follows (from the top):
516 /// - value of the node, 4 elements.
517 /// - depth of the path, 1 element.
518 /// - index of the node, 1 element.
519 /// - root of the tree, 4 elements.
520 ///
521 /// The Merkle path itself is expected to be provided by the prover non-deterministically (via
522 /// merkle sets). If the prover is not able to provide the required path, the operation fails.
523 /// The state of the stack does not change.
524 ///
525 /// The internal value specifies an error code associated with the error in case when the
526 /// assertion fails.
527 MpVerify(Felt) = opcodes::MPVERIFY,
528
529 /// Computes a new root of a Merkle tree where a node at the specified position is updated to
530 /// the specified value.
531 ///
532 /// The stack is expected to be arranged as follows (from the top):
533 /// - old value of the node, 4 element
534 /// - depth of the node, 1 element
535 /// - index of the node, 1 element
536 /// - current root of the tree, 4 elements
537 /// - new value of the node, 4 element
538 ///
539 /// The Merkle path for the node is expected to be provided by the prover non-deterministically
540 /// via the advice provider. At the end of the operation, the old node value is replaced with
541 /// the new root value, that is computed based on the provided path. Everything else on the
542 /// stack remains the same.
543 ///
544 /// The tree will always be copied into a new instance, meaning the advice provider will keep
545 /// track of both the old and new Merkle trees.
546 MrUpdate = opcodes::MRUPDATE,
547
548 /// Performs FRI (Fast Reed-Solomon Interactive Oracle Proofs) layer folding by a factor of 4
549 /// for FRI protocol executed in a degree 2 extension of the base field.
550 ///
551 /// This operation:
552 /// - Folds 4 query values (v0, v1), (v2, v3), (v4, v5), (v6, v7) into a single value (ne0, ne1)
553 /// - Computes new value of the domain generator power: poe' = poe^4
554 /// - Increments layer pointer (cptr) by 2
555 /// - Checks that the previous folding was done correctly
556 /// - Shifts the stack to move an item from the overflow table to stack position 15
557 ///
558 /// Stack transition:
559 /// Input: [v7, v6, v5, v4, v3, v2, v1, v0, f_pos, d_seg, poe, pe1, pe0, a1, a0, cptr, ...]
560 /// Output: [t1, t0, s1, s0, df3, df2, df1, df0, poe^2, f_tau, cptr+2, poe^4, f_pos, ne1, ne0,
561 /// eptr, ...] where eptr is moved from the stack overflow table and is the address of the
562 /// final FRI layer.
563 FriE2F4 = opcodes::FRIE2F4,
564
565 /// Performs 8 steps of the Horner evaluation method on a polynomial with coefficients over
566 /// the base field, i.e., it computes
567 ///
568 /// acc' = (((acc_tmp * alpha + c3) * alpha + c2) * alpha + c1) * alpha + c0
569 ///
570 /// where
571 ///
572 /// acc_tmp := (((acc * alpha + c7) * alpha + c6) * alpha + c5) * alpha + c4
573 ///
574 ///
575 /// In other words, the intsruction computes the evaluation at alpha of the polynomial
576 ///
577 /// P(X) := c7 * X^7 + c6 * X^6 + ... + c1 * X + c0
578 HornerBase = opcodes::HORNERBASE,
579
580 /// Performs 4 steps of the Horner evaluation method on a polynomial with coefficients over
581 /// the extension field, i.e., it computes
582 ///
583 /// acc' = (((acc * alpha + c3) * alpha + c2) * alpha + c1) * alpha + c0
584 ///
585 /// In other words, the intsruction computes the evaluation at alpha of the polynomial
586 ///
587 /// P(X) := c3 * X^3 + c2 * X^2 + c1 * X + c0
588 HornerExt = opcodes::HORNEREXT,
589
590 /// Evaluates an arithmetic circuit given a pointer to its description in memory, the number
591 /// of arithmetic gates, and the sum of the input and constant gates.
592 EvalCircuit = opcodes::EVALCIRCUIT,
593
594 /// Logs a precompile event. This instruction is used to signal that a precompile computation
595 /// was requested.
596 LogDeferred = opcodes::LOGDEFERRED,
597}
598
599impl Operation {
600 pub const OP_BITS: usize = 7;
601
602 /// Returns the opcode of this operation.
603 #[rustfmt::skip]
604 pub fn op_code(&self) -> u8 {
605 // SAFETY: This is safe because we have given this enum a primitive representation with
606 // #[repr(u8)], with the first field of the underlying union-of-structs the discriminant.
607 //
608 // See the section on "accessing the numeric value of the discriminant"
609 // here: https://doc.rust-lang.org/std/mem/fn.discriminant.html
610 unsafe { *<*const _>::from(self).cast::<u8>() }
611 }
612
613 /// Returns an immediate value carried by this operation.
614 // Proptest generators for operations in crate::mast::node::basic_block_node::tests discriminate
615 // on this flag, please update them when you modify the semantics of this method.
616 pub fn imm_value(&self) -> Option<Felt> {
617 match *self {
618 Self::Push(imm) => Some(imm),
619 _ => None,
620 }
621 }
622
623 /// Returns true if this basic block operation increases the stack depth by one.
624 ///
625 /// Note: this only applies to operations within basic blocks (i.e. those executed via
626 /// `ResumeBasicBlock` continuations). Control flow operations that affect stack size
627 /// (e.g. Split, Loop, Dyn) are handled separately.
628 pub fn increments_stack_size(&self) -> bool {
629 matches!(
630 self,
631 Self::Push(_)
632 | Self::Pad
633 | Self::Dup0
634 | Self::Dup1
635 | Self::Dup2
636 | Self::Dup3
637 | Self::Dup4
638 | Self::Dup5
639 | Self::Dup6
640 | Self::Dup7
641 | Self::Dup9
642 | Self::Dup11
643 | Self::Dup13
644 | Self::Dup15
645 | Self::U32split
646 | Self::SDepth
647 | Self::Clk
648 | Self::AdvPop
649 )
650 }
651
652 /// Returns true if this basic block operation decreases the stack depth by one.
653 ///
654 /// Note: this only applies to operations within basic blocks (i.e. those executed via
655 /// `ResumeBasicBlock` continuations). Control flow operations that affect stack size
656 /// (e.g. Split, Loop, Dyn) are handled separately.
657 pub fn decrements_stack_size(&self) -> bool {
658 matches!(
659 self,
660 Self::Drop
661 | Self::Assert(_)
662 | Self::Add
663 | Self::Mul
664 | Self::And
665 | Self::Or
666 | Self::Eq
667 | Self::U32add3
668 | Self::U32madd
669 | Self::U32and
670 | Self::U32xor
671 | Self::CSwap
672 | Self::CSwapW
673 | Self::MLoadW
674 | Self::MStoreW
675 | Self::MStore
676 | Self::FriE2F4
677 )
678 }
679}
680
681impl crate::prettier::PrettyPrint for Operation {
682 fn render(&self) -> crate::prettier::Document {
683 crate::prettier::display(self)
684 }
685}
686
687impl fmt::Display for Operation {
688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689 match self {
690 // ----- system operations ------------------------------------------------------------
691 Self::Noop => write!(f, "noop"),
692 Self::Assert(err_code) => write!(f, "assert({err_code})"),
693
694 Self::SDepth => write!(f, "sdepth"),
695 Self::Caller => write!(f, "caller"),
696
697 Self::Clk => write!(f, "clk"),
698
699 // ----- field operations -------------------------------------------------------------
700 Self::Add => write!(f, "add"),
701 Self::Neg => write!(f, "neg"),
702 Self::Mul => write!(f, "mul"),
703 Self::Inv => write!(f, "inv"),
704 Self::Incr => write!(f, "incr"),
705
706 Self::And => write!(f, "and"),
707 Self::Or => write!(f, "or"),
708 Self::Not => write!(f, "not"),
709
710 Self::Eq => write!(f, "eq"),
711 Self::Eqz => write!(f, "eqz"),
712
713 Self::Expacc => write!(f, "expacc"),
714
715 // ----- ext2 operations --------------------------------------------------------------
716 Self::Ext2Mul => write!(f, "ext2mul"),
717
718 // ----- u32 operations ---------------------------------------------------------------
719 Self::U32assert2(err_code) => write!(f, "u32assert2({err_code})"),
720 Self::U32split => write!(f, "u32split"),
721 Self::U32add => write!(f, "u32add"),
722 Self::U32add3 => write!(f, "u32add3"),
723 Self::U32sub => write!(f, "u32sub"),
724 Self::U32mul => write!(f, "u32mul"),
725 Self::U32madd => write!(f, "u32madd"),
726 Self::U32div => write!(f, "u32div"),
727
728 Self::U32and => write!(f, "u32and"),
729 Self::U32xor => write!(f, "u32xor"),
730
731 // ----- stack manipulation -----------------------------------------------------------
732 Self::Drop => write!(f, "drop"),
733 Self::Pad => write!(f, "pad"),
734
735 Self::Dup0 => write!(f, "dup0"),
736 Self::Dup1 => write!(f, "dup1"),
737 Self::Dup2 => write!(f, "dup2"),
738 Self::Dup3 => write!(f, "dup3"),
739 Self::Dup4 => write!(f, "dup4"),
740 Self::Dup5 => write!(f, "dup5"),
741 Self::Dup6 => write!(f, "dup6"),
742 Self::Dup7 => write!(f, "dup7"),
743 Self::Dup9 => write!(f, "dup9"),
744 Self::Dup11 => write!(f, "dup11"),
745 Self::Dup13 => write!(f, "dup13"),
746 Self::Dup15 => write!(f, "dup15"),
747
748 Self::Swap => write!(f, "swap"),
749 Self::SwapW => write!(f, "swapw"),
750 Self::SwapW2 => write!(f, "swapw2"),
751 Self::SwapW3 => write!(f, "swapw3"),
752 Self::SwapDW => write!(f, "swapdw"),
753
754 Self::MovUp2 => write!(f, "movup2"),
755 Self::MovUp3 => write!(f, "movup3"),
756 Self::MovUp4 => write!(f, "movup4"),
757 Self::MovUp5 => write!(f, "movup5"),
758 Self::MovUp6 => write!(f, "movup6"),
759 Self::MovUp7 => write!(f, "movup7"),
760 Self::MovUp8 => write!(f, "movup8"),
761
762 Self::MovDn2 => write!(f, "movdn2"),
763 Self::MovDn3 => write!(f, "movdn3"),
764 Self::MovDn4 => write!(f, "movdn4"),
765 Self::MovDn5 => write!(f, "movdn5"),
766 Self::MovDn6 => write!(f, "movdn6"),
767 Self::MovDn7 => write!(f, "movdn7"),
768 Self::MovDn8 => write!(f, "movdn8"),
769
770 Self::CSwap => write!(f, "cswap"),
771 Self::CSwapW => write!(f, "cswapw"),
772
773 // ----- input / output ---------------------------------------------------------------
774 Self::Push(value) => write!(f, "push({value})"),
775
776 Self::AdvPop => write!(f, "advpop"),
777 Self::AdvPopW => write!(f, "advpopw"),
778
779 Self::MLoadW => write!(f, "mloadw"),
780 Self::MStoreW => write!(f, "mstorew"),
781
782 Self::MLoad => write!(f, "mload"),
783 Self::MStore => write!(f, "mstore"),
784
785 Self::MStream => write!(f, "mstream"),
786 Self::Pipe => write!(f, "pipe"),
787 Self::CryptoStream => write!(f, "crypto_stream"),
788
789 Self::Emit => write!(f, "emit"),
790
791 // ----- cryptographic operations -----------------------------------------------------
792 Self::HPerm => write!(f, "hperm"),
793 Self::MpVerify(err_code) => write!(f, "mpverify({err_code})"),
794 Self::MrUpdate => write!(f, "mrupdate"),
795
796 // ----- STARK proof verification -----------------------------------------------------
797 Self::FriE2F4 => write!(f, "frie2f4"),
798 Self::HornerBase => write!(f, "horner_eval_base"),
799 Self::HornerExt => write!(f, "horner_eval_ext"),
800 Self::EvalCircuit => write!(f, "eval_circuit"),
801 Self::LogDeferred => write!(f, "log_deferred"),
802 }
803 }
804}
805
806impl Serializable for Operation {
807 fn write_into<W: ByteWriter>(&self, target: &mut W) {
808 target.write_u8(self.op_code());
809
810 // For operations that have extra data, encode it in `data`.
811 match self {
812 Operation::Assert(err_code)
813 | Operation::MpVerify(err_code)
814 | Operation::U32assert2(err_code) => {
815 err_code.write_into(target);
816 },
817 Operation::Push(value) => value.as_canonical_u64().write_into(target),
818
819 // Note: we explicitly write out all the operations so that whenever we make a
820 // modification to the `Operation` enum, we get a compile error here. This
821 // should help us remember to properly encode/decode each operation variant.
822 Operation::Noop
823 | Operation::SDepth
824 | Operation::Caller
825 | Operation::Clk
826 | Operation::Add
827 | Operation::Neg
828 | Operation::Mul
829 | Operation::Inv
830 | Operation::Incr
831 | Operation::And
832 | Operation::Or
833 | Operation::Not
834 | Operation::Eq
835 | Operation::Eqz
836 | Operation::Expacc
837 | Operation::Ext2Mul
838 | Operation::U32split
839 | Operation::U32add
840 | Operation::U32add3
841 | Operation::U32sub
842 | Operation::U32mul
843 | Operation::U32madd
844 | Operation::U32div
845 | Operation::U32and
846 | Operation::U32xor
847 | Operation::Pad
848 | Operation::Drop
849 | Operation::Dup0
850 | Operation::Dup1
851 | Operation::Dup2
852 | Operation::Dup3
853 | Operation::Dup4
854 | Operation::Dup5
855 | Operation::Dup6
856 | Operation::Dup7
857 | Operation::Dup9
858 | Operation::Dup11
859 | Operation::Dup13
860 | Operation::Dup15
861 | Operation::Swap
862 | Operation::SwapW
863 | Operation::SwapW2
864 | Operation::SwapW3
865 | Operation::SwapDW
866 | Operation::Emit
867 | Operation::MovUp2
868 | Operation::MovUp3
869 | Operation::MovUp4
870 | Operation::MovUp5
871 | Operation::MovUp6
872 | Operation::MovUp7
873 | Operation::MovUp8
874 | Operation::MovDn2
875 | Operation::MovDn3
876 | Operation::MovDn4
877 | Operation::MovDn5
878 | Operation::MovDn6
879 | Operation::MovDn7
880 | Operation::MovDn8
881 | Operation::CSwap
882 | Operation::CSwapW
883 | Operation::AdvPop
884 | Operation::AdvPopW
885 | Operation::MLoadW
886 | Operation::MStoreW
887 | Operation::MLoad
888 | Operation::MStore
889 | Operation::MStream
890 | Operation::Pipe
891 | Operation::CryptoStream
892 | Operation::HPerm
893 | Operation::MrUpdate
894 | Operation::FriE2F4
895 | Operation::HornerBase
896 | Operation::HornerExt
897 | Operation::EvalCircuit
898 | Operation::LogDeferred => (),
899 }
900 }
901}
902
903impl Operation {
904 /// Returns the serialized size of this operation in bytes.
905 pub(crate) fn encoded_size(&self) -> usize {
906 let mut size = size_of::<u8>();
907 match self {
908 Operation::Assert(err_code)
909 | Operation::MpVerify(err_code)
910 | Operation::U32assert2(err_code) => {
911 size += err_code.get_size_hint();
912 },
913 Operation::Push(value) => {
914 size += value.as_canonical_u64().get_size_hint();
915 },
916 Operation::Noop
917 | Operation::SDepth
918 | Operation::Caller
919 | Operation::Clk
920 | Operation::Add
921 | Operation::Neg
922 | Operation::Mul
923 | Operation::Inv
924 | Operation::Incr
925 | Operation::And
926 | Operation::Or
927 | Operation::Not
928 | Operation::Eq
929 | Operation::Eqz
930 | Operation::Expacc
931 | Operation::Ext2Mul
932 | Operation::U32split
933 | Operation::U32add
934 | Operation::U32add3
935 | Operation::U32sub
936 | Operation::U32mul
937 | Operation::U32madd
938 | Operation::U32div
939 | Operation::U32and
940 | Operation::U32xor
941 | Operation::Pad
942 | Operation::Drop
943 | Operation::Dup0
944 | Operation::Dup1
945 | Operation::Dup2
946 | Operation::Dup3
947 | Operation::Dup4
948 | Operation::Dup5
949 | Operation::Dup6
950 | Operation::Dup7
951 | Operation::Dup9
952 | Operation::Dup11
953 | Operation::Dup13
954 | Operation::Dup15
955 | Operation::Swap
956 | Operation::SwapW
957 | Operation::SwapW2
958 | Operation::SwapW3
959 | Operation::SwapDW
960 | Operation::Emit
961 | Operation::MovUp2
962 | Operation::MovUp3
963 | Operation::MovUp4
964 | Operation::MovUp5
965 | Operation::MovUp6
966 | Operation::MovUp7
967 | Operation::MovUp8
968 | Operation::MovDn2
969 | Operation::MovDn3
970 | Operation::MovDn4
971 | Operation::MovDn5
972 | Operation::MovDn6
973 | Operation::MovDn7
974 | Operation::MovDn8
975 | Operation::CSwap
976 | Operation::CSwapW
977 | Operation::AdvPop
978 | Operation::AdvPopW
979 | Operation::MLoadW
980 | Operation::MStoreW
981 | Operation::MLoad
982 | Operation::MStore
983 | Operation::MStream
984 | Operation::Pipe
985 | Operation::CryptoStream
986 | Operation::HPerm
987 | Operation::MrUpdate
988 | Operation::FriE2F4
989 | Operation::HornerBase
990 | Operation::HornerExt
991 | Operation::EvalCircuit
992 | Operation::LogDeferred => (),
993 }
994 size
995 }
996}
997
998impl Deserializable for Operation {
999 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
1000 let op_code = source.read_u8()?;
1001
1002 let operation = match op_code {
1003 opcodes::NOOP => Self::Noop,
1004 opcodes::EQZ => Self::Eqz,
1005 opcodes::NEG => Self::Neg,
1006 opcodes::INV => Self::Inv,
1007 opcodes::INCR => Self::Incr,
1008 opcodes::NOT => Self::Not,
1009 opcodes::MLOAD => Self::MLoad,
1010 opcodes::SWAP => Self::Swap,
1011 opcodes::CALLER => Self::Caller,
1012 opcodes::MOVUP2 => Self::MovUp2,
1013 opcodes::MOVDN2 => Self::MovDn2,
1014 opcodes::MOVUP3 => Self::MovUp3,
1015 opcodes::MOVDN3 => Self::MovDn3,
1016 opcodes::ADVPOPW => Self::AdvPopW,
1017 opcodes::EXPACC => Self::Expacc,
1018
1019 opcodes::MOVUP4 => Self::MovUp4,
1020 opcodes::MOVDN4 => Self::MovDn4,
1021 opcodes::MOVUP5 => Self::MovUp5,
1022 opcodes::MOVDN5 => Self::MovDn5,
1023 opcodes::MOVUP6 => Self::MovUp6,
1024 opcodes::MOVDN6 => Self::MovDn6,
1025 opcodes::MOVUP7 => Self::MovUp7,
1026 opcodes::MOVDN7 => Self::MovDn7,
1027 opcodes::SWAPW => Self::SwapW,
1028 opcodes::EXT2MUL => Self::Ext2Mul,
1029 opcodes::MOVUP8 => Self::MovUp8,
1030 opcodes::MOVDN8 => Self::MovDn8,
1031 opcodes::SWAPW2 => Self::SwapW2,
1032 opcodes::SWAPW3 => Self::SwapW3,
1033 opcodes::SWAPDW => Self::SwapDW,
1034 opcodes::EMIT => Self::Emit,
1035
1036 opcodes::ASSERT => Self::Assert(Felt::read_from(source)?),
1037 opcodes::EQ => Self::Eq,
1038 opcodes::ADD => Self::Add,
1039 opcodes::MUL => Self::Mul,
1040 opcodes::AND => Self::And,
1041 opcodes::OR => Self::Or,
1042 opcodes::U32AND => Self::U32and,
1043 opcodes::U32XOR => Self::U32xor,
1044 opcodes::FRIE2F4 => Self::FriE2F4,
1045 opcodes::DROP => Self::Drop,
1046 opcodes::CSWAP => Self::CSwap,
1047 opcodes::CSWAPW => Self::CSwapW,
1048 opcodes::MLOADW => Self::MLoadW,
1049 opcodes::MSTORE => Self::MStore,
1050 opcodes::MSTOREW => Self::MStoreW,
1051
1052 opcodes::PAD => Self::Pad,
1053 opcodes::DUP0 => Self::Dup0,
1054 opcodes::DUP1 => Self::Dup1,
1055 opcodes::DUP2 => Self::Dup2,
1056 opcodes::DUP3 => Self::Dup3,
1057 opcodes::DUP4 => Self::Dup4,
1058 opcodes::DUP5 => Self::Dup5,
1059 opcodes::DUP6 => Self::Dup6,
1060 opcodes::DUP7 => Self::Dup7,
1061 opcodes::DUP9 => Self::Dup9,
1062 opcodes::DUP11 => Self::Dup11,
1063 opcodes::DUP13 => Self::Dup13,
1064 opcodes::DUP15 => Self::Dup15,
1065 opcodes::ADVPOP => Self::AdvPop,
1066 opcodes::SDEPTH => Self::SDepth,
1067 opcodes::CLK => Self::Clk,
1068
1069 opcodes::U32ADD => Self::U32add,
1070 opcodes::U32SUB => Self::U32sub,
1071 opcodes::U32MUL => Self::U32mul,
1072 opcodes::U32DIV => Self::U32div,
1073 opcodes::U32SPLIT => Self::U32split,
1074 opcodes::U32ASSERT2 => Self::U32assert2(Felt::read_from(source)?),
1075 opcodes::U32ADD3 => Self::U32add3,
1076 opcodes::U32MADD => Self::U32madd,
1077
1078 opcodes::HPERM => Self::HPerm,
1079 opcodes::MPVERIFY => Self::MpVerify(Felt::read_from(source)?),
1080 opcodes::PIPE => Self::Pipe,
1081 opcodes::MSTREAM => Self::MStream,
1082 opcodes::CRYPTOSTREAM => Self::CryptoStream,
1083 opcodes::HORNERBASE => Self::HornerBase,
1084 opcodes::HORNEREXT => Self::HornerExt,
1085 opcodes::LOGDEFERRED => Self::LogDeferred,
1086 opcodes::EVALCIRCUIT => Self::EvalCircuit,
1087
1088 opcodes::MRUPDATE => Self::MrUpdate,
1089 opcodes::PUSH => Self::Push(Felt::read_from(source)?),
1090 _ => {
1091 return Err(DeserializationError::InvalidValue(format!(
1092 "Invalid opcode '{op_code}'"
1093 )));
1094 },
1095 };
1096
1097 Ok(operation)
1098 }
1099
1100 /// Returns the minimum serialized size: 1 byte opcode.
1101 ///
1102 /// Some operations have additional payload (e.g., Push has 8 bytes for Felt),
1103 /// but the minimum is just the opcode byte.
1104 fn min_serialized_size() -> usize {
1105 1
1106 }
1107}
1108
1109#[cfg(test)]
1110mod tests;