Skip to main content

miden_core/deferred/
work.rs

1//! Declared deferred-precompile workload accounting.
2
3use alloc::{borrow::Cow, collections::BTreeMap, string::String, vec::Vec};
4
5use super::{Node, PrecompileError, PrecompileRegistry, precompile_registry::is_framework_domain};
6use crate::serde::{
7    BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
8    SliceReader, validate_bounded_len,
9};
10
11/// Stable identifier for one class of precompile work.
12///
13/// Returning the same class from multiple frames intentionally combines their accounting. The
14/// name is serialized in precompile policies but does not affect deferred commitments. Names are
15/// arbitrary UTF-8 and are compared byte for byte.
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct WorkClass(Cow<'static, str>);
18
19impl WorkClass {
20    /// Creates a work class from a static name. The name is borrowed and not copied.
21    pub const fn new(name: &'static str) -> Self {
22        Self(Cow::Borrowed(name))
23    }
24
25    /// Creates a work class from an owned name.
26    ///
27    /// Use this for names that are not available as a `&'static str`, such as names decoded from a
28    /// serialized policy. Names have no restrictions beyond valid UTF-8.
29    pub fn from_string(name: String) -> Self {
30        Self(Cow::Owned(name))
31    }
32
33    /// Returns the class name.
34    pub fn as_str(&self) -> &str {
35        self.0.as_ref()
36    }
37}
38
39impl core::fmt::Display for WorkClass {
40    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41        f.write_str(self.as_str())
42    }
43}
44
45/// Work declared by one precompile-owned node.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct WorkItem {
48    class: WorkClass,
49    size: u32,
50}
51
52impl WorkItem {
53    /// Creates a work item. `size` is the class-specific variable dimension, such as hash input
54    /// bytes or MSM terms. Fixed-size operations use one.
55    pub const fn new(class: WorkClass, size: u32) -> Self {
56        Self { class, size }
57    }
58}
59
60/// Aggregate work for one class within an accounting scope.
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
62pub struct WorkSummary {
63    count: u64,
64    total_size: u64,
65    max_size: u32,
66}
67
68impl WorkSummary {
69    /// Returns the number of charged items in this class.
70    pub const fn count(self) -> u64 {
71        self.count
72    }
73
74    /// Returns the checked sum of item sizes in this class.
75    pub const fn total_size(self) -> u64 {
76        self.total_size
77    }
78
79    /// Returns the largest individual item size in this class.
80    pub const fn max_size(self) -> u32 {
81        self.max_size
82    }
83
84    fn checked_with(self, size: u32) -> Result<Self, PrecompileLimitError> {
85        Ok(Self {
86            count: self.count.checked_add(1).ok_or(PrecompileLimitError::Overflow)?,
87            total_size: self
88                .total_size
89                .checked_add(u64::from(size))
90                .ok_or(PrecompileLimitError::Overflow)?,
91            max_size: self.max_size.max(size),
92        })
93    }
94}
95
96/// Work accumulated within one execution or verification accounting scope.
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct PrecompileWork {
99    nodes: u64,
100    elements: u64,
101    classes: BTreeMap<WorkClass, WorkSummary>,
102}
103
104impl PrecompileWork {
105    /// Returns the number of charged nodes in this accounting scope.
106    pub const fn nodes(&self) -> u64 {
107        self.nodes
108    }
109
110    /// Returns the canonical field-element footprint charged in this accounting scope.
111    pub const fn elements(&self) -> u64 {
112        self.elements
113    }
114
115    /// Returns the summary for `class`, if this scope contains that class.
116    pub fn class(&self, class: &WorkClass) -> Option<WorkSummary> {
117        self.classes.get(class).copied()
118    }
119
120    /// Validates already-accumulated work against `limits` without changing it.
121    pub(crate) fn validate(&self, limits: &PrecompileLimits) -> Result<(), PrecompileLimitError> {
122        limits.check_elements(self.elements)?;
123        for (class, &summary) in &self.classes {
124            limits.check_class(class, summary)?;
125        }
126        Ok(())
127    }
128
129    /// Charges one node under `limits`.
130    ///
131    /// Framework nodes contribute structural elements but no precompile work class. Every other
132    /// node uses the owning precompile's declared work item.
133    pub(crate) fn charge_node(
134        &mut self,
135        node: &Node,
136        registry: &PrecompileRegistry,
137        limits: &PrecompileLimits,
138    ) -> Result<(), PrecompileError> {
139        let item = match node.frame() {
140            None => None,
141            Some(frame) if is_framework_domain(frame.domain()) => None,
142            Some(_) => Some(registry.work(node)?),
143        };
144        self.charge(node.felt_len(), item, limits)?;
145        Ok(())
146    }
147
148    fn charge(
149        &mut self,
150        elements: usize,
151        item: Option<WorkItem>,
152        limits: &PrecompileLimits,
153    ) -> Result<(), PrecompileLimitError> {
154        let nodes = self.nodes.checked_add(1).ok_or(PrecompileLimitError::Overflow)?;
155        let elements = self
156            .elements
157            .checked_add(u64::try_from(elements).map_err(|_| PrecompileLimitError::Overflow)?)
158            .ok_or(PrecompileLimitError::Overflow)?;
159        limits.check_elements(elements)?;
160
161        let next = item
162            .map(|item| {
163                let WorkItem { class, size } = item;
164                let summary =
165                    self.classes.get(&class).copied().unwrap_or_default().checked_with(size)?;
166                limits.check_class(&class, summary)?;
167                Ok((class, summary))
168            })
169            .transpose()?;
170
171        self.nodes = nodes;
172        self.elements = elements;
173        if let Some((class, summary)) = next {
174            self.classes.insert(class, summary);
175        }
176        Ok(())
177    }
178}
179
180/// Bounds for one work class within a single accounting scope.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub struct WorkLimit {
183    /// Maximum number of items in this class.
184    pub max_count: u64,
185    /// Maximum sum of item sizes in this class.
186    pub max_total_size: u64,
187    /// Maximum size of one item in this class.
188    pub max_size: u32,
189}
190
191impl WorkLimit {
192    fn check(self, class: &WorkClass, summary: WorkSummary) -> Result<(), PrecompileLimitError> {
193        if summary.count > self.max_count {
194            return Err(PrecompileLimitError::Count {
195                class: class.clone(),
196                actual: summary.count,
197                max: self.max_count,
198            });
199        }
200        if summary.total_size > self.max_total_size {
201            return Err(PrecompileLimitError::TotalSize {
202                class: class.clone(),
203                actual: summary.total_size,
204                max: self.max_total_size,
205            });
206        }
207        if summary.max_size > self.max_size {
208            return Err(PrecompileLimitError::ItemSize {
209                class: class.clone(),
210                actual: summary.max_size,
211                max: self.max_size,
212            });
213        }
214        Ok(())
215    }
216}
217
218/// Admission policy for one execution or verification accounting scope.
219///
220/// # Binary encoding
221///
222/// The encoding starts with the structural element ceiling as a `u64`. It then writes the class
223/// map as a length-prefixed sequence in class-name order. Each entry contains a length-prefixed
224/// UTF-8 class name and three work limits. Decoding requires class names in strictly increasing
225/// order, rejects duplicates, and requires length prefixes to use the shortest vint64 encoding.
226/// The format has no version byte. Both byte entrypoints require the decoded snapshot to consume
227/// the entire input.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct PrecompileLimits {
230    max_elements: u64,
231    classes: BTreeMap<WorkClass, WorkLimit>,
232}
233
234impl PrecompileLimits {
235    /// Creates a policy with a structural element ceiling and no admitted precompile work classes.
236    pub const fn new(max_elements: u64) -> Self {
237        Self { max_elements, classes: BTreeMap::new() }
238    }
239
240    /// Replaces the structural field-element ceiling.
241    #[must_use]
242    pub const fn with_max_elements(mut self, max_elements: u64) -> Self {
243        self.max_elements = max_elements;
244        self
245    }
246
247    /// Adds or replaces the bound for `class`.
248    #[must_use]
249    pub fn with_class(mut self, class: WorkClass, limit: WorkLimit) -> Self {
250        self.classes.insert(class, limit);
251        self
252    }
253
254    /// Returns the configured bound for `class`, if the policy admits it.
255    pub fn class(&self, class: &WorkClass) -> Option<WorkLimit> {
256        self.classes.get(class).copied()
257    }
258
259    /// Returns the structural field-element ceiling.
260    pub const fn max_elements(&self) -> u64 {
261        self.max_elements
262    }
263
264    /// Returns the configured class bounds in class-name order.
265    pub fn classes(&self) -> impl Iterator<Item = (&WorkClass, &WorkLimit)> + '_ {
266        self.classes.iter()
267    }
268
269    fn check_elements(&self, actual: u64) -> Result<(), PrecompileLimitError> {
270        if actual > self.max_elements {
271            return Err(PrecompileLimitError::Elements { actual, max: self.max_elements });
272        }
273        Ok(())
274    }
275
276    fn check_class(
277        &self,
278        class: &WorkClass,
279        summary: WorkSummary,
280    ) -> Result<(), PrecompileLimitError> {
281        let limit = self
282            .classes
283            .get(class)
284            .copied()
285            .ok_or_else(|| PrecompileLimitError::MissingClass { class: class.clone() })?;
286        limit.check(class, summary)
287    }
288}
289
290// SERIALIZATION
291// ================================================================================================
292
293fn read_shortest_len<R: ByteReader>(
294    source: &mut R,
295    label: &str,
296    min_element_size: usize,
297) -> Result<usize, DeserializationError> {
298    let encoded_len = source.peek_u8()?.trailing_zeros() as usize + 1;
299    let len = source.read_usize()?;
300    if encoded_len != len.get_size_hint() {
301        return Err(DeserializationError::InvalidValue(format!("noncanonical {label} length")));
302    }
303    validate_bounded_len(source, label, len, min_element_size)?;
304    Ok(len)
305}
306
307impl Serializable for WorkClass {
308    fn write_into<W: ByteWriter>(&self, target: &mut W) {
309        self.as_str().write_into(target);
310    }
311
312    fn get_size_hint(&self) -> usize {
313        self.as_str().get_size_hint()
314    }
315}
316
317impl Deserializable for WorkClass {
318    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
319        let len = read_shortest_len(source, "work class name", 1)?;
320        let bytes = source.read_many_iter::<u8>(len)?.collect::<Result<Vec<_>, _>>()?;
321        let name = String::from_utf8(bytes)
322            .map_err(|err| DeserializationError::InvalidValue(format!("{err}")))?;
323        Ok(Self::from_string(name))
324    }
325
326    fn min_serialized_size() -> usize {
327        1
328    }
329}
330
331impl Serializable for WorkLimit {
332    fn write_into<W: ByteWriter>(&self, target: &mut W) {
333        self.max_count.write_into(target);
334        self.max_total_size.write_into(target);
335        self.max_size.write_into(target);
336    }
337
338    fn get_size_hint(&self) -> usize {
339        self.max_count.get_size_hint()
340            + self.max_total_size.get_size_hint()
341            + self.max_size.get_size_hint()
342    }
343}
344
345impl Deserializable for WorkLimit {
346    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
347        let max_count = source.read_u64()?;
348        let max_total_size = source.read_u64()?;
349        let max_size = source.read_u32()?;
350        Ok(Self { max_count, max_total_size, max_size })
351    }
352
353    fn min_serialized_size() -> usize {
354        u64::min_serialized_size() + u64::min_serialized_size() + u32::min_serialized_size()
355    }
356}
357
358impl Serializable for PrecompileLimits {
359    fn write_into<W: ByteWriter>(&self, target: &mut W) {
360        self.max_elements.write_into(target);
361        self.classes.write_into(target);
362    }
363
364    fn get_size_hint(&self) -> usize {
365        self.max_elements.get_size_hint() + self.classes.get_size_hint()
366    }
367}
368
369impl Deserializable for PrecompileLimits {
370    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
371        let max_elements = source.read_u64()?;
372        let min_entry_size = WorkClass::min_serialized_size() + WorkLimit::min_serialized_size();
373        let class_count = read_shortest_len(source, "precompile limits class", min_entry_size)?;
374        let mut classes = BTreeMap::new();
375        for entry in source.read_many_iter::<(WorkClass, WorkLimit)>(class_count)? {
376            let (class, limit) = entry?;
377            if let Some((previous, _)) = classes.last_key_value()
378                && class <= *previous
379            {
380                return Err(DeserializationError::InvalidValue(format!(
381                    "precompile limits class names must be strictly increasing: previous `{previous}`, current `{class}`"
382                )));
383            }
384            classes.insert(class, limit);
385        }
386        Ok(Self { max_elements, classes })
387    }
388
389    fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
390        Self::read_from_bytes_with_budget(bytes, bytes.len())
391    }
392
393    fn read_from_bytes_with_budget(
394        bytes: &[u8],
395        budget: usize,
396    ) -> Result<Self, DeserializationError> {
397        let budget = budget.min(bytes.len());
398        let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
399        let limits = Self::read_from(&mut reader)?;
400        let consumed = budget.saturating_sub(reader.remaining());
401        if consumed != bytes.len() {
402            return Err(DeserializationError::InvalidValue(
403                "trailing bytes after precompile limits".into(),
404            ));
405        }
406        Ok(limits)
407    }
408
409    fn min_serialized_size() -> usize {
410        u64::min_serialized_size() + BTreeMap::<WorkClass, WorkLimit>::min_serialized_size()
411    }
412}
413
414/// Work exceeded its configured precompile admission policy.
415#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
416pub enum PrecompileLimitError {
417    #[error("precompile work accounting overflowed")]
418    Overflow,
419    #[error("precompile work uses {actual} structural elements, maximum is {max}")]
420    Elements { actual: u64, max: u64 },
421    #[error("precompile work class `{class}` has no configured limit")]
422    MissingClass { class: WorkClass },
423    #[error("precompile work class `{class}` occurs {actual} times, maximum is {max}")]
424    Count { class: WorkClass, actual: u64, max: u64 },
425    #[error("precompile work class `{class}` has total size {actual}, maximum is {max}")]
426    TotalSize { class: WorkClass, actual: u64, max: u64 },
427    #[error("precompile work class `{class}` has item size {actual}, maximum is {max}")]
428    ItemSize { class: WorkClass, actual: u32, max: u32 },
429}
430
431#[cfg(test)]
432mod tests {
433    use alloc::{string::String, vec::Vec};
434
435    use super::*;
436
437    const TEST: WorkClass = WorkClass::new("test");
438
439    #[test]
440    fn charging_is_checked_before_mutating_the_summary() {
441        let limits = PrecompileLimits::new(24).with_class(
442            TEST,
443            WorkLimit {
444                max_count: 2,
445                max_total_size: 7,
446                max_size: 4,
447            },
448        );
449        let mut work = PrecompileWork::default();
450
451        work.charge(12, Some(WorkItem::new(TEST, 3)), &limits).unwrap();
452        work.charge(12, Some(WorkItem::new(TEST, 4)), &limits).unwrap();
453        assert_eq!(work.nodes(), 2);
454        assert_eq!(work.elements(), 24);
455        assert_eq!(work.class(&TEST), Some(WorkSummary { count: 2, total_size: 7, max_size: 4 }));
456
457        assert!(matches!(
458            work.charge(1, None, &limits),
459            Err(PrecompileLimitError::Elements { actual: 25, max: 24 })
460        ));
461        assert_eq!(work.nodes(), 2);
462        assert_eq!(work.elements(), 24);
463    }
464
465    #[test]
466    fn unconfigured_and_overflowing_work_is_rejected() {
467        let mut work = PrecompileWork::default();
468        assert!(matches!(
469            work.charge(1, Some(WorkItem::new(TEST, 1)), &PrecompileLimits::new(u64::MAX),),
470            Err(PrecompileLimitError::MissingClass { class }) if class == TEST
471        ));
472        assert_eq!(work, PrecompileWork::default());
473
474        work.nodes = u64::MAX;
475        assert!(matches!(
476            work.charge(0, None, &PrecompileLimits::new(u64::MAX)),
477            Err(PrecompileLimitError::Overflow)
478        ));
479    }
480
481    #[test]
482    fn work_class_roundtrip_preserves_arbitrary_names() {
483        let static_class = WorkClass::new("hash");
484        let decoded_static = WorkClass::read_from_bytes(&static_class.to_bytes()).unwrap();
485        assert_eq!(decoded_static, static_class);
486        assert_eq!(decoded_static.as_str(), "hash");
487        assert_eq!(format!("{decoded_static}"), "hash");
488
489        for name in ["", "custom class", "custom/λ", "custom\nname"] {
490            let class = WorkClass::from_string(String::from(name));
491            let bytes = class.to_bytes();
492            let decoded = WorkClass::read_from_bytes(&bytes).unwrap();
493            assert_eq!(decoded, class);
494            assert_eq!(decoded.to_bytes(), bytes);
495            assert_eq!(decoded.as_str(), name);
496            assert_eq!(format!("{decoded}"), name);
497        }
498    }
499
500    #[test]
501    fn work_class_rejects_invalid_utf8_and_truncated_length() {
502        let mut invalid = Vec::new();
503        2usize.write_into(&mut invalid);
504        invalid.extend_from_slice(&[0xff, 0xfe]);
505        assert!(WorkClass::read_from_bytes(&invalid).is_err());
506
507        let mut truncated = Vec::new();
508        3usize.write_into(&mut truncated);
509        truncated.extend_from_slice(b"ab");
510        assert!(WorkClass::read_from_bytes(&truncated).is_err());
511    }
512
513    #[test]
514    fn precompile_limits_roundtrip_preserves_ceiling_and_multiple_custom_classes() {
515        let custom_a = WorkClass::from_string(String::from("custom-a"));
516        let custom_b = WorkClass::from_string(String::from("custom class"));
517        let hash_limit = WorkLimit {
518            max_count: 9,
519            max_total_size: 13,
520            max_size: 5,
521        };
522        let limits = PrecompileLimits::new(123)
523            .with_class(
524                custom_a.clone(),
525                WorkLimit {
526                    max_count: 7,
527                    max_total_size: 11,
528                    max_size: 3,
529                },
530            )
531            .with_class(
532                custom_b.clone(),
533                WorkLimit {
534                    max_count: 0,
535                    max_total_size: 0,
536                    max_size: 0,
537                },
538            )
539            .with_class(WorkClass::new("hash"), hash_limit);
540
541        let bytes = limits.to_bytes();
542        let decoded = PrecompileLimits::read_from_bytes(&bytes).unwrap();
543        assert_eq!(decoded, limits);
544        assert_eq!(decoded.to_bytes(), bytes);
545        assert_eq!(decoded.max_elements(), 123);
546        assert_eq!(
547            decoded.class(&custom_a),
548            Some(WorkLimit {
549                max_count: 7,
550                max_total_size: 11,
551                max_size: 3
552            })
553        );
554        assert_eq!(
555            decoded.class(&custom_b),
556            Some(WorkLimit {
557                max_count: 0,
558                max_total_size: 0,
559                max_size: 0
560            })
561        );
562        assert_eq!(decoded.class(&WorkClass::new("hash")), Some(hash_limit));
563        assert_eq!(decoded.classes().count(), 3);
564        assert!(decoded.classes().any(|(class, _)| class == &custom_a));
565        assert!(decoded.classes().any(|(class, _)| class == &custom_b));
566    }
567
568    #[test]
569    fn empty_precompile_limits_roundtrip() {
570        let limits = PrecompileLimits::new(0);
571        let bytes = limits.to_bytes();
572        let decoded = PrecompileLimits::read_from_bytes(&bytes).unwrap();
573        assert_eq!(decoded, limits);
574        assert_eq!(decoded.to_bytes(), bytes);
575        assert_eq!(decoded.max_elements(), 0);
576        assert_eq!(decoded.classes().count(), 0);
577    }
578
579    #[test]
580    fn precompile_limits_roundtrip_admission_matches_original() {
581        fn assert_same_admission(
582            original: &PrecompileLimits,
583            decoded: &PrecompileLimits,
584            elements: usize,
585            item: Option<WorkItem>,
586        ) {
587            let mut original_work = PrecompileWork::default();
588            let original_result = original_work.charge(elements, item.clone(), original);
589            let mut decoded_work = PrecompileWork::default();
590            let decoded_result = decoded_work.charge(elements, item, decoded);
591            assert_eq!(original_result, decoded_result);
592            assert_eq!(original_work, decoded_work);
593        }
594
595        let custom = WorkClass::from_string(String::from("custom"));
596        let allowed = PrecompileLimits::new(4).with_class(
597            custom.clone(),
598            WorkLimit {
599                max_count: 2,
600                max_total_size: 5,
601                max_size: 3,
602            },
603        );
604        let decoded_allowed = PrecompileLimits::read_from_bytes(&allowed.to_bytes()).unwrap();
605        assert_same_admission(
606            &allowed,
607            &decoded_allowed,
608            1,
609            Some(WorkItem::new(custom.clone(), 1)),
610        );
611        assert_same_admission(&allowed, &decoded_allowed, 5, None);
612
613        let missing = PrecompileLimits::new(4);
614        let decoded_missing = PrecompileLimits::read_from_bytes(&missing.to_bytes()).unwrap();
615        assert_same_admission(
616            &missing,
617            &decoded_missing,
618            1,
619            Some(WorkItem::new(custom.clone(), 1)),
620        );
621
622        let count = PrecompileLimits::new(4).with_class(
623            custom.clone(),
624            WorkLimit {
625                max_count: 0,
626                max_total_size: 5,
627                max_size: 3,
628            },
629        );
630        let decoded_count = PrecompileLimits::read_from_bytes(&count.to_bytes()).unwrap();
631        assert_same_admission(&count, &decoded_count, 1, Some(WorkItem::new(custom.clone(), 1)));
632
633        let total = PrecompileLimits::new(4).with_class(
634            custom.clone(),
635            WorkLimit {
636                max_count: 2,
637                max_total_size: 0,
638                max_size: 3,
639            },
640        );
641        let decoded_total = PrecompileLimits::read_from_bytes(&total.to_bytes()).unwrap();
642        assert_same_admission(&total, &decoded_total, 1, Some(WorkItem::new(custom.clone(), 1)));
643
644        let item_size = PrecompileLimits::new(4).with_class(
645            custom.clone(),
646            WorkLimit {
647                max_count: 2,
648                max_total_size: 5,
649                max_size: 0,
650            },
651        );
652        let decoded_item_size = PrecompileLimits::read_from_bytes(&item_size.to_bytes()).unwrap();
653        assert_same_admission(&item_size, &decoded_item_size, 1, Some(WorkItem::new(custom, 1)));
654    }
655
656    #[test]
657    fn owned_custom_name_matches_static_live_class() {
658        let live = WorkClass::new("hash");
659        let decoded_name = WorkClass::from_string(String::from("hash"));
660        assert_eq!(live, decoded_name);
661        let limit = WorkLimit {
662            max_count: 3,
663            max_total_size: 4,
664            max_size: 2,
665        };
666        let limits = PrecompileLimits::new(1).with_class(live, limit);
667        let decoded = PrecompileLimits::read_from_bytes(&limits.to_bytes()).unwrap();
668        assert_eq!(decoded.class(&decoded_name), Some(limit));
669        // The same owned key can be reused for a lookup against an unrelated policy.
670        assert_eq!(PrecompileLimits::new(0).class(&decoded_name), None);
671    }
672
673    #[test]
674    fn precompile_limits_rejects_duplicate_class_keys() {
675        let custom = WorkClass::from_string(String::from("custom"));
676        let limit = WorkLimit {
677            max_count: 1,
678            max_total_size: 2,
679            max_size: 1,
680        };
681        let mut bytes = Vec::new();
682        42u64.write_into(&mut bytes);
683        2usize.write_into(&mut bytes);
684        custom.write_into(&mut bytes);
685        limit.write_into(&mut bytes);
686        custom.write_into(&mut bytes);
687        limit.write_into(&mut bytes);
688        assert!(PrecompileLimits::read_from_bytes(&bytes).is_err());
689    }
690
691    #[test]
692    fn precompile_limits_rejects_out_of_order_class_keys() {
693        let limit = WorkLimit {
694            max_count: 1,
695            max_total_size: 2,
696            max_size: 1,
697        };
698        let mut bytes = Vec::new();
699        0u64.write_into(&mut bytes);
700        2usize.write_into(&mut bytes);
701        WorkClass::new("b").write_into(&mut bytes);
702        limit.write_into(&mut bytes);
703        WorkClass::new("a").write_into(&mut bytes);
704        limit.write_into(&mut bytes);
705        let error = PrecompileLimits::read_from_bytes(&bytes).unwrap_err();
706        assert!(matches!(
707            error,
708            DeserializationError::InvalidValue(ref message)
709                if message.contains("`b`") && message.contains("`a`")
710        ));
711    }
712
713    #[test]
714    fn precompile_limits_fixed_vector_roundtrip() {
715        let expected = vec![
716            5, 0, 0, 0, 0, 0, 0, 0, // max_elements
717            3, // one class
718            9, // four-byte name
719            b'h', b'a', b's', b'h', 7, 0, 0, 0, 0, 0, 0, 0, // max_count
720            9, 0, 0, 0, 0, 0, 0, 0, // max_total_size
721            2, 0, 0, 0, // max_size
722        ];
723        let limits = PrecompileLimits::new(5).with_class(
724            WorkClass::new("hash"),
725            WorkLimit {
726                max_count: 7,
727                max_total_size: 9,
728                max_size: 2,
729            },
730        );
731        assert_eq!(limits.to_bytes(), expected);
732        let decoded = PrecompileLimits::read_from_bytes(&expected).unwrap();
733        assert_eq!(decoded, limits);
734    }
735
736    #[test]
737    fn precompile_limits_rejects_overlong_class_count() {
738        let mut bytes = Vec::new();
739        0u64.write_into(&mut bytes);
740        bytes.extend_from_slice(&[0x02, 0x00]);
741        assert!(PrecompileLimits::read_from_bytes(&bytes).is_err());
742    }
743
744    #[test]
745    fn precompile_limits_rejects_overlong_class_name_length() {
746        let mut bytes = Vec::new();
747        0u64.write_into(&mut bytes);
748        1usize.write_into(&mut bytes);
749        bytes.extend_from_slice(&[0x02, 0x00]);
750        WorkLimit {
751            max_count: 1,
752            max_total_size: 2,
753            max_size: 1,
754        }
755        .write_into(&mut bytes);
756        assert!(PrecompileLimits::read_from_bytes(&bytes).is_err());
757    }
758
759    #[test]
760    fn precompile_limits_rejects_oversized_lengths() {
761        let mut huge_count = Vec::new();
762        0u64.write_into(&mut huge_count);
763        usize::MAX.write_into(&mut huge_count);
764        assert!(PrecompileLimits::read_from_bytes(&huge_count).is_err());
765
766        let mut huge_name = Vec::new();
767        0u64.write_into(&mut huge_name);
768        1usize.write_into(&mut huge_name);
769        usize::MAX.write_into(&mut huge_name);
770        WorkLimit {
771            max_count: 1,
772            max_total_size: 2,
773            max_size: 1,
774        }
775        .write_into(&mut huge_name);
776        assert!(PrecompileLimits::read_from_bytes(&huge_name).is_err());
777
778        let mut valid_name = Vec::new();
779        0u64.write_into(&mut valid_name);
780        1usize.write_into(&mut valid_name);
781        1usize.write_into(&mut valid_name);
782        valid_name.push(b'x');
783        WorkLimit {
784            max_count: 1,
785            max_total_size: 2,
786            max_size: 1,
787        }
788        .write_into(&mut valid_name);
789        assert!(PrecompileLimits::read_from_bytes(&valid_name).is_ok());
790    }
791
792    #[test]
793    fn precompile_limits_rejects_truncated_and_trailing_bytes() {
794        let limits = PrecompileLimits::new(7).with_class(
795            WorkClass::new("hash"),
796            WorkLimit {
797                max_count: 1,
798                max_total_size: 1,
799                max_size: 1,
800            },
801        );
802        let bytes = limits.to_bytes();
803        for len in 0..bytes.len() {
804            assert!(PrecompileLimits::read_from_bytes(&bytes[..len]).is_err());
805        }
806        assert!(PrecompileLimits::read_from_bytes_with_budget(&bytes, bytes.len()).is_ok());
807        assert!(PrecompileLimits::read_from_bytes_with_budget(&bytes, bytes.len() + 1).is_ok());
808
809        let mut trailing = bytes.clone();
810        trailing.push(0);
811        assert!(PrecompileLimits::read_from_bytes(&trailing).is_err());
812        assert!(PrecompileLimits::read_from_bytes_with_budget(&trailing, trailing.len()).is_err());
813        assert!(PrecompileLimits::read_from_bytes_with_budget(&trailing, bytes.len()).is_err());
814        assert!(PrecompileLimits::read_from_bytes_with_budget(&bytes, bytes.len() - 1).is_err());
815    }
816}