Skip to main content

miden_processor/
execution_options.rs

1use miden_air_definitions::vm::trace::MIN_TRACE_LEN;
2use miden_core::{
3    deferred::PrecompileLimits,
4    program::MIN_STACK_DEPTH,
5    serde::{
6        BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
7        SliceReader,
8    },
9};
10
11// EXECUTION OPTIONS
12// ================================================================================================
13
14/// A set of parameters specifying execution parameters of the VM.
15///
16/// - `max_cycles` specifies the maximum number of cycles a program is allowed to execute.
17/// - `expected_cycles` specifies the number of cycles a program is expected to execute.
18///
19/// # Binary encoding
20///
21/// The encoding writes fields in declaration order and has no version byte. Variable-length
22/// integers must use the shortest vint64 encoding. Decoding rejects invalid booleans, invalid
23/// UTF-8 class names, duplicate policy classes, truncated input, trailing input, and options that
24/// violate the invariants enforced by [`Self::new`] and [`Self::with_max_stack_depth`]. Both byte
25/// entrypoints require the decoded snapshot to consume the entire input.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct ExecutionOptions {
28    max_cycles: u32,
29    expected_cycles: u32,
30    core_trace_fragment_size: usize,
31    /// Maximum combined logical size, in bytes, of the advice stack, map, and Merkle store.
32    max_advice_size_bytes: usize,
33    /// Whether the synchronous prover may overlap hasher-chiplet trace building with program
34    /// execution (std-only; the sequential path is used on no_std regardless).
35    overlapped_trace_build: bool,
36    /// Maximum number of input bytes allowed for a single hash precompile invocation.
37    max_hash_len_bytes: usize,
38    /// Maximum number of continuations allowed on the continuation stack at any point during
39    /// execution.
40    max_num_continuations: usize,
41    /// Maximum number of field elements allowed on the operand stack across the active execution
42    /// context and all suspended contexts.
43    ///
44    /// A `call`, `dyncall`, or `syscall` context switch hides the caller's operand-stack overflow
45    /// (everything below the top 16 elements) until the callee returns. This limit bounds the
46    /// aggregate of the active context's depth plus all such suspended overflow, so nesting
47    /// context switches cannot accumulate hidden operand-stack memory beyond the configured
48    /// budget.
49    max_stack_depth: usize,
50    /// Maximum number of field elements allowed in the processor's memory at any point during
51    /// execution, rounded up to the nearest multiple of 4.
52    max_memory_elements: usize,
53    /// Policy limiting guest-induced deferred precompile work.
54    execution_precompile_limits: PrecompileLimits,
55    /// Policy limiting the final root-reachable deferred witness exported after execution.
56    verification_precompile_limits: PrecompileLimits,
57}
58
59impl Default for ExecutionOptions {
60    fn default() -> Self {
61        ExecutionOptions {
62            max_cycles: Self::MAX_CYCLES,
63            expected_cycles: MIN_TRACE_LEN as u32,
64            core_trace_fragment_size: Self::DEFAULT_CORE_TRACE_FRAGMENT_SIZE,
65            max_advice_size_bytes: Self::DEFAULT_MAX_ADVICE_SIZE_BYTES,
66            max_hash_len_bytes: Self::DEFAULT_MAX_HASH_LEN_BYTES,
67            max_num_continuations: Self::DEFAULT_MAX_NUM_CONTINUATIONS,
68            max_stack_depth: Self::DEFAULT_MAX_STACK_DEPTH,
69            max_memory_elements: Self::DEFAULT_MAX_MEMORY_ELEMENTS,
70            overlapped_trace_build: true,
71            execution_precompile_limits: miden_precompiles::default_execution_precompile_limits(),
72            verification_precompile_limits:
73                miden_precompiles::default_verification_precompile_limits(),
74        }
75    }
76}
77
78impl ExecutionOptions {
79    // CONSTANTS
80    // --------------------------------------------------------------------------------------------
81
82    /// The maximum number of VM cycles a program is allowed to take.
83    pub const MAX_CYCLES: u32 = 1 << 29;
84
85    /// Default fragment size for core trace generation.
86    pub const DEFAULT_CORE_TRACE_FRAGMENT_SIZE: usize = 4096; // 2^12
87
88    /// Default maximum combined logical size of the advice provider. Set to 16 MiB.
89    pub const DEFAULT_MAX_ADVICE_SIZE_BYTES: usize = 16 * 1024 * 1024;
90
91    /// Default maximum number of input bytes for a single hash precompile invocation.
92    /// Set to 2^20 (1 MB).
93    pub const DEFAULT_MAX_HASH_LEN_BYTES: usize = 1 << 20;
94
95    /// Default maximum number of continuations allowed on the continuation stack.
96    /// Set to 2^16 (65536).
97    pub const DEFAULT_MAX_NUM_CONTINUATIONS: usize = 1 << 16;
98
99    /// Default maximum number of field elements allowed on the operand stack.
100    ///
101    /// This preserves the effective stack depth ceiling imposed by the previous fixed
102    /// `FastProcessor` stack buffer.
103    pub const DEFAULT_MAX_STACK_DEPTH: usize = 6615;
104
105    /// Default maximum number of field elements allowed in the processor's memory.
106    ///
107    /// Memory is element-addressable, so this bounds the total number of elements live across all
108    /// contexts. Internally memory is stored at word granularity (4 elements per word), so the
109    /// effective limit is rounded up to a whole number of words. Set to 2^28, which lets programs
110    /// use a large amount of memory while still providing a finite host-memory backstop against
111    /// unbounded growth from writes to arbitrarily many unique addresses.
112    pub const DEFAULT_MAX_MEMORY_ELEMENTS: usize = 1 << 28;
113
114    // CONSTRUCTOR
115    // --------------------------------------------------------------------------------------------
116
117    /// Creates a new instance of [ExecutionOptions] from the specified parameters.
118    ///
119    /// If the `max_cycles` is `None` the maximum number of cycles will be set to 2^29.
120    ///
121    /// # Errors
122    /// Returns an error if:
123    /// - `max_cycles` is outside the valid range
124    /// - after rounding up to the next power of two, `expected_cycles` exceeds `max_cycles`
125    /// - `core_trace_fragment_size` is zero
126    pub fn new(
127        max_cycles: Option<u32>,
128        expected_cycles: u32,
129        core_trace_fragment_size: usize,
130    ) -> Result<Self, ExecutionOptionsError> {
131        // Validate max cycles.
132        let max_cycles = if let Some(max_cycles) = max_cycles {
133            if max_cycles > Self::MAX_CYCLES {
134                return Err(ExecutionOptionsError::MaxCycleNumTooBig {
135                    max_cycles,
136                    max_cycles_limit: Self::MAX_CYCLES,
137                });
138            }
139            if max_cycles < MIN_TRACE_LEN as u32 {
140                return Err(ExecutionOptionsError::MaxCycleNumTooSmall {
141                    max_cycles,
142                    min_cycles_limit: MIN_TRACE_LEN,
143                });
144            }
145            max_cycles
146        } else {
147            Self::MAX_CYCLES
148        };
149        // Round up the expected number of cycles to the next power of two. If it is smaller than
150        // MIN_TRACE_LEN -- pad expected number to it.
151        let expected_cycles = expected_cycles.next_power_of_two().max(MIN_TRACE_LEN as u32);
152        // Validate expected cycles (after rounding) against max_cycles.
153        if max_cycles < expected_cycles {
154            return Err(ExecutionOptionsError::ExpectedCyclesTooBig {
155                max_cycles,
156                expected_cycles,
157            });
158        }
159
160        // Validate core trace fragment size.
161        if core_trace_fragment_size == 0 {
162            return Err(ExecutionOptionsError::CoreTraceFragmentSizeTooSmall);
163        }
164
165        Ok(ExecutionOptions {
166            max_cycles,
167            expected_cycles,
168            core_trace_fragment_size,
169            max_advice_size_bytes: Self::DEFAULT_MAX_ADVICE_SIZE_BYTES,
170            max_hash_len_bytes: Self::DEFAULT_MAX_HASH_LEN_BYTES,
171            max_num_continuations: Self::DEFAULT_MAX_NUM_CONTINUATIONS,
172            max_stack_depth: Self::DEFAULT_MAX_STACK_DEPTH,
173            max_memory_elements: Self::DEFAULT_MAX_MEMORY_ELEMENTS,
174            overlapped_trace_build: true,
175            execution_precompile_limits: miden_precompiles::default_execution_precompile_limits(),
176            verification_precompile_limits:
177                miden_precompiles::default_verification_precompile_limits(),
178        })
179    }
180
181    /// Sets the fragment size for core trace generation.
182    ///
183    /// Returns an error if the size is zero.
184    pub fn with_core_trace_fragment_size(
185        mut self,
186        size: usize,
187    ) -> Result<Self, ExecutionOptionsError> {
188        if size == 0 {
189            return Err(ExecutionOptionsError::CoreTraceFragmentSizeTooSmall);
190        }
191        self.core_trace_fragment_size = size;
192        Ok(self)
193    }
194
195    // PUBLIC ACCESSORS
196    // --------------------------------------------------------------------------------------------
197
198    /// Returns maximum number of cycles a program is allowed to execute for.
199    #[inline(always)]
200    pub fn max_cycles(&self) -> u32 {
201        self.max_cycles
202    }
203
204    /// Returns the number of cycles a program is expected to take.
205    ///
206    /// This will serve as a hint to the VM for how much memory to allocate for a program's
207    /// execution trace and may result in performance improvements when the number of expected
208    /// cycles is equal to the number of actual cycles.
209    pub fn expected_cycles(&self) -> u32 {
210        self.expected_cycles
211    }
212
213    /// Returns the fragment size for core trace generation.
214    pub fn core_trace_fragment_size(&self) -> usize {
215        self.core_trace_fragment_size
216    }
217
218    /// Returns the maximum combined logical size, in bytes, of the advice provider.
219    #[inline]
220    pub fn max_advice_size_bytes(&self) -> usize {
221        self.max_advice_size_bytes
222    }
223
224    /// Returns the maximum number of input bytes allowed for a single hash precompile invocation.
225    #[inline]
226    pub fn max_hash_len_bytes(&self) -> usize {
227        self.max_hash_len_bytes
228    }
229
230    /// Sets whether the synchronous prover may overlap hasher-chiplet trace building with program
231    /// execution (defaults to `true`; ignored on no_std, which always uses the sequential path).
232    /// When enabled, overlap is opportunistic. A caller with no separate Rayon worker uses compact
233    /// buffered replay.
234    pub fn with_overlapped_trace_build(mut self, overlapped: bool) -> Self {
235        self.overlapped_trace_build = overlapped;
236        self
237    }
238
239    /// Returns whether the synchronous prover may overlap trace building with execution.
240    pub fn overlapped_trace_build(&self) -> bool {
241        self.overlapped_trace_build
242    }
243
244    /// Sets the maximum combined logical size, in bytes, of the advice provider.
245    pub fn with_max_advice_size_bytes(mut self, size: usize) -> Self {
246        self.max_advice_size_bytes = size;
247        self
248    }
249
250    /// Sets the maximum number of input bytes allowed for a single hash precompile invocation.
251    pub fn with_max_hash_len_bytes(mut self, size: usize) -> Self {
252        self.max_hash_len_bytes = size;
253        self
254    }
255
256    /// Returns the maximum number of continuations allowed on the continuation stack.
257    #[inline]
258    pub fn max_num_continuations(&self) -> usize {
259        self.max_num_continuations
260    }
261
262    /// Returns the maximum number of field elements allowed on the operand stack across the active
263    /// execution context and all suspended contexts.
264    #[inline]
265    pub fn max_stack_depth(&self) -> usize {
266        self.max_stack_depth
267    }
268
269    /// Returns the configured maximum number of field elements allowed in the processor's memory.
270    ///
271    /// This is the raw value as set via [`Self::with_max_memory_elements`]; the effective cap is
272    /// rounded up to a whole number of words (a multiple of 4) when memory is initialized.
273    #[inline]
274    pub fn max_memory_elements(&self) -> usize {
275        self.max_memory_elements
276    }
277
278    /// Sets the maximum number of continuations allowed on the continuation stack.
279    pub fn with_max_num_continuations(mut self, max_num_continuations: usize) -> Self {
280        self.max_num_continuations = max_num_continuations;
281        self
282    }
283
284    /// Sets the maximum number of field elements allowed on the operand stack across the active
285    /// execution context and all suspended contexts.
286    pub fn with_max_stack_depth(
287        mut self,
288        max_stack_depth: usize,
289    ) -> Result<Self, ExecutionOptionsError> {
290        if max_stack_depth < MIN_STACK_DEPTH {
291            return Err(ExecutionOptionsError::MaxStackDepthTooSmall {
292                max_stack_depth,
293                min_stack_depth: MIN_STACK_DEPTH,
294            });
295        }
296        self.max_stack_depth = max_stack_depth;
297        Ok(self)
298    }
299
300    /// Sets the maximum number of field elements allowed in the processor's memory.
301    pub fn with_max_memory_elements(mut self, max_memory_elements: usize) -> Self {
302        self.max_memory_elements = max_memory_elements;
303        self
304    }
305
306    /// Returns the policy limiting guest-induced deferred precompile work.
307    pub const fn execution_precompile_limits(&self) -> &PrecompileLimits {
308        &self.execution_precompile_limits
309    }
310
311    /// Sets the policy limiting guest-induced deferred precompile work.
312    pub fn with_execution_precompile_limits(mut self, limits: PrecompileLimits) -> Self {
313        self.execution_precompile_limits = limits;
314        self
315    }
316
317    /// Returns the policy limiting the final root-reachable deferred witness.
318    pub const fn verification_precompile_limits(&self) -> &PrecompileLimits {
319        &self.verification_precompile_limits
320    }
321
322    /// Sets the policy limiting the final root-reachable deferred witness.
323    pub fn with_verification_precompile_limits(mut self, limits: PrecompileLimits) -> Self {
324        self.verification_precompile_limits = limits;
325        self
326    }
327}
328
329// SERIALIZATION
330// ================================================================================================
331
332fn read_shortest_usize<R: ByteReader>(
333    source: &mut R,
334    label: &str,
335) -> Result<usize, DeserializationError> {
336    let encoded_len = source.peek_u8()?.trailing_zeros() as usize + 1;
337    let value = source.read_usize()?;
338    if encoded_len != value.get_size_hint() {
339        return Err(DeserializationError::InvalidValue(format!("noncanonical {label} length")));
340    }
341    Ok(value)
342}
343
344fn validate_decoded_options(
345    max_cycles: u32,
346    expected_cycles: u32,
347    core_trace_fragment_size: usize,
348    max_stack_depth: usize,
349) -> Result<(), DeserializationError> {
350    let min_cycles = MIN_TRACE_LEN as u32;
351    if max_cycles < min_cycles || max_cycles > ExecutionOptions::MAX_CYCLES {
352        return Err(DeserializationError::InvalidValue(format!(
353            "max_cycles {max_cycles} is outside [{min_cycles}, {}]",
354            ExecutionOptions::MAX_CYCLES
355        )));
356    }
357    if !expected_cycles.is_power_of_two() || expected_cycles < min_cycles {
358        return Err(DeserializationError::InvalidValue(format!(
359            "expected_cycles {expected_cycles} must be a power of two at least {min_cycles}"
360        )));
361    }
362    if expected_cycles > max_cycles {
363        return Err(DeserializationError::InvalidValue(format!(
364            "expected_cycles {expected_cycles} exceeds max_cycles {max_cycles}"
365        )));
366    }
367    if core_trace_fragment_size == 0 {
368        return Err(DeserializationError::InvalidValue(
369            "core_trace_fragment_size must be greater than 0".into(),
370        ));
371    }
372    if max_stack_depth < MIN_STACK_DEPTH {
373        return Err(DeserializationError::InvalidValue(format!(
374            "max_stack_depth {max_stack_depth} must be at least {MIN_STACK_DEPTH}"
375        )));
376    }
377    Ok(())
378}
379
380impl Serializable for ExecutionOptions {
381    fn write_into<W: ByteWriter>(&self, target: &mut W) {
382        self.max_cycles.write_into(target);
383        self.expected_cycles.write_into(target);
384        self.core_trace_fragment_size.write_into(target);
385        self.max_advice_size_bytes.write_into(target);
386        target.write_bool(self.overlapped_trace_build);
387        self.max_hash_len_bytes.write_into(target);
388        self.max_num_continuations.write_into(target);
389        self.max_stack_depth.write_into(target);
390        self.max_memory_elements.write_into(target);
391        self.execution_precompile_limits.write_into(target);
392        self.verification_precompile_limits.write_into(target);
393    }
394
395    fn get_size_hint(&self) -> usize {
396        self.max_cycles.get_size_hint()
397            + self.expected_cycles.get_size_hint()
398            + self.core_trace_fragment_size.get_size_hint()
399            + self.max_advice_size_bytes.get_size_hint()
400            + 1
401            + self.max_hash_len_bytes.get_size_hint()
402            + self.max_num_continuations.get_size_hint()
403            + self.max_stack_depth.get_size_hint()
404            + self.max_memory_elements.get_size_hint()
405            + self.execution_precompile_limits.get_size_hint()
406            + self.verification_precompile_limits.get_size_hint()
407    }
408}
409
410impl Deserializable for ExecutionOptions {
411    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
412        let max_cycles = source.read_u32()?;
413        let expected_cycles = source.read_u32()?;
414        let core_trace_fragment_size = read_shortest_usize(source, "core_trace_fragment_size")?;
415        let max_advice_size_bytes = read_shortest_usize(source, "max_advice_size_bytes")?;
416        let overlapped_trace_build = source.read_bool()?;
417        let max_hash_len_bytes = read_shortest_usize(source, "max_hash_len_bytes")?;
418        let max_num_continuations = read_shortest_usize(source, "max_num_continuations")?;
419        let max_stack_depth = read_shortest_usize(source, "max_stack_depth")?;
420        let max_memory_elements = read_shortest_usize(source, "max_memory_elements")?;
421        let execution_precompile_limits = PrecompileLimits::read_from(source)?;
422        let verification_precompile_limits = PrecompileLimits::read_from(source)?;
423
424        validate_decoded_options(
425            max_cycles,
426            expected_cycles,
427            core_trace_fragment_size,
428            max_stack_depth,
429        )?;
430
431        Ok(Self {
432            max_cycles,
433            expected_cycles,
434            core_trace_fragment_size,
435            max_advice_size_bytes,
436            overlapped_trace_build,
437            max_hash_len_bytes,
438            max_num_continuations,
439            max_stack_depth,
440            max_memory_elements,
441            execution_precompile_limits,
442            verification_precompile_limits,
443        })
444    }
445
446    fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
447        Self::read_from_bytes_with_budget(bytes, bytes.len())
448    }
449
450    fn read_from_bytes_with_budget(
451        bytes: &[u8],
452        budget: usize,
453    ) -> Result<Self, DeserializationError> {
454        let budget = budget.min(bytes.len());
455        let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
456        let options = Self::read_from(&mut reader)?;
457        let consumed = budget.saturating_sub(reader.remaining());
458        if consumed != bytes.len() {
459            return Err(DeserializationError::InvalidValue(
460                "trailing bytes after execution options".into(),
461            ));
462        }
463        Ok(options)
464    }
465
466    fn min_serialized_size() -> usize {
467        2 * u32::min_serialized_size()
468            + 6 * usize::min_serialized_size()
469            + 1
470            + 2 * PrecompileLimits::min_serialized_size()
471    }
472}
473
474// EXECUTION OPTIONS ERROR
475// ================================================================================================
476
477#[derive(Debug, thiserror::Error)]
478pub enum ExecutionOptionsError {
479    #[error(
480        "expected number of cycles {expected_cycles} must be smaller than the maximum number of cycles {max_cycles}"
481    )]
482    ExpectedCyclesTooBig { max_cycles: u32, expected_cycles: u32 },
483    #[error("maximum number of cycles {max_cycles} must be greater than {min_cycles_limit}")]
484    MaxCycleNumTooSmall { max_cycles: u32, min_cycles_limit: usize },
485    #[error("maximum number of cycles {max_cycles} must be less than {max_cycles_limit}")]
486    MaxCycleNumTooBig { max_cycles: u32, max_cycles_limit: u32 },
487    #[error("core trace fragment size must be greater than 0")]
488    CoreTraceFragmentSizeTooSmall,
489    #[error("maximum stack depth {max_stack_depth} must be at least {min_stack_depth}")]
490    MaxStackDepthTooSmall {
491        max_stack_depth: usize,
492        min_stack_depth: usize,
493    },
494}
495
496// TESTS
497// ================================================================================================
498
499#[cfg(test)]
500mod tests {
501    use alloc::{string::String, vec::Vec};
502
503    use miden_core::{
504        deferred::{WorkClass, WorkLimit},
505        serde::{ByteWriter, Deserializable, Serializable},
506    };
507
508    use super::*;
509
510    fn write_option_header(bytes: &mut Vec<u8>) {
511        (MIN_TRACE_LEN as u32).write_into(bytes);
512        (MIN_TRACE_LEN as u32).write_into(bytes);
513        1usize.write_into(bytes);
514        0usize.write_into(bytes);
515        bytes.write_bool(true);
516        0usize.write_into(bytes);
517        0usize.write_into(bytes);
518        MIN_STACK_DEPTH.write_into(bytes);
519        0usize.write_into(bytes);
520    }
521
522    fn encode_options(
523        max_cycles: u32,
524        expected_cycles: u32,
525        core_trace_fragment_size: usize,
526        max_advice_size_bytes: usize,
527        overlapped_trace_build: bool,
528        max_hash_len_bytes: usize,
529        max_num_continuations: usize,
530        max_stack_depth: usize,
531        max_memory_elements: usize,
532        execution: &PrecompileLimits,
533        verification: &PrecompileLimits,
534    ) -> Vec<u8> {
535        let mut bytes = Vec::new();
536        max_cycles.write_into(&mut bytes);
537        expected_cycles.write_into(&mut bytes);
538        core_trace_fragment_size.write_into(&mut bytes);
539        max_advice_size_bytes.write_into(&mut bytes);
540        bytes.write_bool(overlapped_trace_build);
541        max_hash_len_bytes.write_into(&mut bytes);
542        max_num_continuations.write_into(&mut bytes);
543        max_stack_depth.write_into(&mut bytes);
544        max_memory_elements.write_into(&mut bytes);
545        execution.write_into(&mut bytes);
546        verification.write_into(&mut bytes);
547        bytes
548    }
549
550    #[test]
551    fn valid_fragment_size() {
552        // Valid power of two values should succeed
553        let opts = ExecutionOptions::new(None, 64, 1024);
554        assert!(opts.is_ok());
555        assert_eq!(opts.unwrap().core_trace_fragment_size(), 1024);
556
557        let opts = ExecutionOptions::new(None, 64, 4096);
558        assert!(opts.is_ok());
559
560        let opts = ExecutionOptions::new(None, 64, 1);
561        assert!(opts.is_ok());
562    }
563
564    #[test]
565    fn zero_fragment_size_fails() {
566        let opts = ExecutionOptions::new(None, 64, 0);
567        assert!(matches!(opts, Err(ExecutionOptionsError::CoreTraceFragmentSizeTooSmall)));
568    }
569
570    #[test]
571    fn with_core_trace_fragment_size_validates() {
572        // Valid size should succeed
573        let result = ExecutionOptions::default().with_core_trace_fragment_size(2048);
574        assert!(result.is_ok());
575        assert_eq!(result.unwrap().core_trace_fragment_size(), 2048);
576
577        // Zero should fail
578        let result = ExecutionOptions::default().with_core_trace_fragment_size(0);
579        assert!(matches!(result, Err(ExecutionOptionsError::CoreTraceFragmentSizeTooSmall)));
580    }
581
582    #[test]
583    fn expected_cycles_validated_after_rounding() {
584        // expected_cycles=65 rounds to 128; max_cycles=100 -> must fail (128 > 100).
585        let opts = ExecutionOptions::new(Some(100), 65, 1024);
586        assert!(matches!(
587            opts,
588            Err(ExecutionOptionsError::ExpectedCyclesTooBig {
589                max_cycles: 100,
590                expected_cycles: 128
591            })
592        ));
593
594        // expected_cycles=64 rounds to 64; max_cycles=100 -> ok.
595        let opts = ExecutionOptions::new(Some(100), 64, 1024);
596        assert!(opts.is_ok());
597        assert_eq!(opts.unwrap().expected_cycles(), 64);
598    }
599
600    #[test]
601    fn max_stack_depth_validates_minimum_depth() {
602        let result = ExecutionOptions::default().with_max_stack_depth(MIN_STACK_DEPTH - 1);
603        assert!(matches!(
604            result,
605            Err(ExecutionOptionsError::MaxStackDepthTooSmall {
606                max_stack_depth,
607                min_stack_depth: MIN_STACK_DEPTH,
608            }) if max_stack_depth == MIN_STACK_DEPTH - 1
609        ));
610
611        let result = ExecutionOptions::default().with_max_stack_depth(MIN_STACK_DEPTH);
612        assert!(result.is_ok());
613        assert_eq!(result.unwrap().max_stack_depth(), MIN_STACK_DEPTH);
614    }
615
616    #[test]
617    fn default_execution_options_roundtrip() {
618        let options = ExecutionOptions::default();
619        let bytes = options.to_bytes();
620        let decoded = ExecutionOptions::read_from_bytes(&bytes).unwrap();
621        assert_eq!(decoded, options);
622        assert_eq!(decoded.to_bytes(), bytes);
623        assert_eq!(decoded.execution_precompile_limits(), options.execution_precompile_limits());
624        assert_eq!(
625            decoded.verification_precompile_limits(),
626            options.verification_precompile_limits()
627        );
628    }
629
630    #[test]
631    fn non_default_execution_options_roundtrip() {
632        let execution_class = WorkClass::from_string(String::from("execution-custom"));
633        let verification_class = WorkClass::from_string(String::from("verification-custom"));
634        let execution_limit = WorkLimit {
635            max_count: 3,
636            max_total_size: 5,
637            max_size: 2,
638        };
639        let verification_limit = WorkLimit {
640            max_count: 7,
641            max_total_size: 11,
642            max_size: 4,
643        };
644        let options = ExecutionOptions::default()
645            .with_core_trace_fragment_size(1)
646            .unwrap()
647            .with_max_advice_size_bytes(17)
648            .with_overlapped_trace_build(false)
649            .with_max_hash_len_bytes(19)
650            .with_max_num_continuations(23)
651            .with_max_stack_depth(MIN_STACK_DEPTH)
652            .unwrap()
653            .with_max_memory_elements(29)
654            .with_execution_precompile_limits(
655                PrecompileLimits::new(31).with_class(execution_class.clone(), execution_limit),
656            )
657            .with_verification_precompile_limits(
658                PrecompileLimits::new(37)
659                    .with_class(verification_class.clone(), verification_limit),
660            );
661
662        let bytes = options.to_bytes();
663        let decoded = ExecutionOptions::read_from_bytes(&bytes).unwrap();
664        assert_eq!(decoded, options);
665        assert_eq!(decoded.to_bytes(), bytes);
666        assert_eq!(decoded.execution_precompile_limits().max_elements(), 31);
667        assert_eq!(decoded.verification_precompile_limits().max_elements(), 37);
668        assert_eq!(
669            decoded.execution_precompile_limits().class(&execution_class),
670            Some(execution_limit)
671        );
672        assert_eq!(
673            decoded.verification_precompile_limits().class(&verification_class),
674            Some(verification_limit)
675        );
676        assert_ne!(decoded.execution_precompile_limits(), decoded.verification_precompile_limits());
677    }
678
679    #[test]
680    fn execution_options_fixed_vector_roundtrip() {
681        let expected = vec![
682            128, 0, 0, 0, // max_cycles
683            64, 0, 0, 0, // expected_cycles
684            5, // core_trace_fragment_size = 2
685            7, // max_advice_size_bytes = 3
686            0, // overlapped_trace_build = false
687            2, 2,  // max_hash_len_bytes = 128
688            11, // max_num_continuations = 5
689            35, // max_stack_depth = 17
690            13, // max_memory_elements = 6
691            7, 0, 0, 0, 0, 0, 0, 0, 1, // execution policy ceiling 7
692            8, 0, 0, 0, 0, 0, 0, 0, 1, // verification policy ceiling 8
693        ];
694        let options = ExecutionOptions::new(Some(128), 64, 2)
695            .unwrap()
696            .with_max_advice_size_bytes(3)
697            .with_overlapped_trace_build(false)
698            .with_max_hash_len_bytes(128)
699            .with_max_num_continuations(5)
700            .with_max_stack_depth(17)
701            .unwrap()
702            .with_max_memory_elements(6)
703            .with_execution_precompile_limits(PrecompileLimits::new(7))
704            .with_verification_precompile_limits(PrecompileLimits::new(8));
705
706        assert_eq!(options.to_bytes(), expected);
707        let decoded = ExecutionOptions::read_from_bytes(&expected).unwrap();
708        assert_eq!(decoded, options);
709    }
710
711    #[test]
712    fn execution_and_verification_zero_policies_stay_distinct() {
713        for execution_zero in [true, false] {
714            let options = if execution_zero {
715                ExecutionOptions::default()
716                    .with_execution_precompile_limits(PrecompileLimits::new(0))
717            } else {
718                ExecutionOptions::default()
719                    .with_verification_precompile_limits(PrecompileLimits::new(0))
720            };
721            let decoded = ExecutionOptions::read_from_bytes(&options.to_bytes()).unwrap();
722            assert_eq!(decoded, options);
723            if execution_zero {
724                assert_eq!(decoded.execution_precompile_limits(), &PrecompileLimits::new(0));
725                assert_eq!(
726                    decoded.verification_precompile_limits(),
727                    options.verification_precompile_limits()
728                );
729            } else {
730                assert_eq!(decoded.verification_precompile_limits(), &PrecompileLimits::new(0));
731                assert_eq!(
732                    decoded.execution_precompile_limits(),
733                    options.execution_precompile_limits()
734                );
735            }
736        }
737    }
738
739    #[test]
740    fn execution_options_reject_invalid_invariants() {
741        let valid = encode_options(
742            MIN_TRACE_LEN as u32,
743            MIN_TRACE_LEN as u32,
744            1,
745            0,
746            true,
747            0,
748            0,
749            MIN_STACK_DEPTH,
750            0,
751            &PrecompileLimits::new(0),
752            &PrecompileLimits::new(0),
753        );
754        assert!(ExecutionOptions::read_from_bytes(&valid).is_ok());
755
756        let mut bytes = valid.clone();
757        bytes[0..4].copy_from_slice(&((MIN_TRACE_LEN as u32) - 1).to_le_bytes());
758        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
759
760        let mut bytes = valid.clone();
761        bytes[0..4].copy_from_slice(&(ExecutionOptions::MAX_CYCLES + 1).to_le_bytes());
762        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
763
764        let mut bytes = valid.clone();
765        bytes[4..8].copy_from_slice(&((MIN_TRACE_LEN as u32) + 1).to_le_bytes());
766        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
767
768        let mut bytes = valid.clone();
769        bytes[4..8].copy_from_slice(&((MIN_TRACE_LEN as u32) - 1).to_le_bytes());
770        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
771
772        let mut bytes = valid;
773        bytes[4..8].copy_from_slice(&((MIN_TRACE_LEN as u32) * 2).to_le_bytes());
774        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
775
776        let zero_fragment = encode_options(
777            MIN_TRACE_LEN as u32,
778            MIN_TRACE_LEN as u32,
779            0,
780            0,
781            true,
782            0,
783            0,
784            MIN_STACK_DEPTH,
785            0,
786            &PrecompileLimits::new(0),
787            &PrecompileLimits::new(0),
788        );
789        assert!(ExecutionOptions::read_from_bytes(&zero_fragment).is_err());
790
791        let shallow_stack = encode_options(
792            MIN_TRACE_LEN as u32,
793            MIN_TRACE_LEN as u32,
794            1,
795            0,
796            true,
797            0,
798            0,
799            MIN_STACK_DEPTH - 1,
800            0,
801            &PrecompileLimits::new(0),
802            &PrecompileLimits::new(0),
803        );
804        assert!(ExecutionOptions::read_from_bytes(&shallow_stack).is_err());
805    }
806
807    #[test]
808    fn execution_options_reject_invalid_bool_and_bad_bytes() {
809        let valid = encode_options(
810            MIN_TRACE_LEN as u32,
811            MIN_TRACE_LEN as u32,
812            1,
813            0,
814            true,
815            0,
816            0,
817            MIN_STACK_DEPTH,
818            0,
819            &PrecompileLimits::new(0),
820            &PrecompileLimits::new(0),
821        );
822
823        let mut invalid_bool = valid.clone();
824        invalid_bool[10] = 2;
825        assert!(ExecutionOptions::read_from_bytes(&invalid_bool).is_err());
826
827        for len in 0..valid.len() {
828            assert!(ExecutionOptions::read_from_bytes(&valid[..len]).is_err());
829        }
830
831        let mut trailing = valid.clone();
832        trailing.push(0);
833        assert!(ExecutionOptions::read_from_bytes(&trailing).is_err());
834        assert!(ExecutionOptions::read_from_bytes_with_budget(&trailing, trailing.len()).is_err());
835        assert!(ExecutionOptions::read_from_bytes_with_budget(&trailing, valid.len()).is_err());
836        assert!(ExecutionOptions::read_from_bytes_with_budget(&valid, valid.len()).is_ok());
837        assert!(ExecutionOptions::read_from_bytes_with_budget(&valid, valid.len() + 1).is_ok());
838        assert!(ExecutionOptions::read_from_bytes_with_budget(&valid, valid.len() - 1).is_err());
839    }
840
841    #[test]
842    fn execution_options_reject_overlong_scalar_usize() {
843        let mut bytes = Vec::new();
844        (MIN_TRACE_LEN as u32).write_into(&mut bytes);
845        (MIN_TRACE_LEN as u32).write_into(&mut bytes);
846        bytes.extend_from_slice(&[0x06, 0x00]);
847        0usize.write_into(&mut bytes);
848        bytes.write_bool(true);
849        0usize.write_into(&mut bytes);
850        0usize.write_into(&mut bytes);
851        MIN_STACK_DEPTH.write_into(&mut bytes);
852        0usize.write_into(&mut bytes);
853        PrecompileLimits::new(0).write_into(&mut bytes);
854        PrecompileLimits::new(0).write_into(&mut bytes);
855        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
856    }
857
858    #[test]
859    fn execution_options_reject_overlong_nested_policy_count() {
860        let mut valid = Vec::new();
861        write_option_header(&mut valid);
862        PrecompileLimits::new(0).write_into(&mut valid);
863        PrecompileLimits::new(0).write_into(&mut valid);
864        assert!(ExecutionOptions::read_from_bytes(&valid).is_ok());
865
866        let mut bytes = Vec::new();
867        write_option_header(&mut bytes);
868        0u64.write_into(&mut bytes);
869        bytes.extend_from_slice(&[0x02, 0x00]);
870        PrecompileLimits::new(0).write_into(&mut bytes);
871        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
872    }
873
874    #[test]
875    fn execution_options_reject_duplicate_policy_keys() {
876        let custom = WorkClass::from_string(String::from("custom"));
877        let limit = WorkLimit {
878            max_count: 1,
879            max_total_size: 2,
880            max_size: 1,
881        };
882        let mut bytes = Vec::new();
883        write_option_header(&mut bytes);
884        42u64.write_into(&mut bytes);
885        2usize.write_into(&mut bytes);
886        custom.write_into(&mut bytes);
887        limit.write_into(&mut bytes);
888        custom.write_into(&mut bytes);
889        limit.write_into(&mut bytes);
890        0u64.write_into(&mut bytes);
891        0usize.write_into(&mut bytes);
892        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
893    }
894
895    #[test]
896    fn execution_options_reject_oversized_policy_count() {
897        let mut bytes = Vec::new();
898        write_option_header(&mut bytes);
899        0u64.write_into(&mut bytes);
900        usize::MAX.write_into(&mut bytes);
901        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
902    }
903
904    #[test]
905    fn execution_options_reject_invalid_utf8_class_name() {
906        let limit = WorkLimit {
907            max_count: 1,
908            max_total_size: 2,
909            max_size: 1,
910        };
911
912        let mut valid = Vec::new();
913        write_option_header(&mut valid);
914        0u64.write_into(&mut valid);
915        1usize.write_into(&mut valid);
916        2usize.write_into(&mut valid);
917        valid.extend_from_slice(b"ab");
918        limit.write_into(&mut valid);
919        PrecompileLimits::new(0).write_into(&mut valid);
920        assert!(ExecutionOptions::read_from_bytes(&valid).is_ok());
921
922        let mut bytes = Vec::new();
923        write_option_header(&mut bytes);
924        0u64.write_into(&mut bytes);
925        1usize.write_into(&mut bytes);
926        2usize.write_into(&mut bytes);
927        bytes.extend_from_slice(&[0xff, 0xfe]);
928        limit.write_into(&mut bytes);
929        PrecompileLimits::new(0).write_into(&mut bytes);
930        assert!(ExecutionOptions::read_from_bytes(&bytes).is_err());
931    }
932}