tasm_lib/arithmetic/u32/
safe_mul.rs

1use std::collections::HashMap;
2
3use triton_vm::prelude::*;
4
5use crate::prelude::*;
6use crate::traits::basic_snippet::Reviewer;
7use crate::traits::basic_snippet::SignOffFingerprint;
8
9/// Multiply two `u32`s and crash on overflow.
10///
11/// ### Behavior
12///
13/// ```text
14/// BEFORE: _ [right: 32] [left: u32]
15/// AFTER:  _ [left · right: u32]
16/// ```
17///
18/// ### Preconditions
19///
20/// - all input arguments are properly [`BFieldCodec`] encoded
21/// - the product of `left` and `right` is less than or equal to [`u32::MAX`]
22///
23/// ### Postconditions
24///
25/// - the output is the product of the input
26/// - the output is properly [`BFieldCodec`] encoded
27#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
28pub struct SafeMul;
29
30impl SafeMul {
31    pub const OVERFLOW_ERROR_ID: i128 = 460;
32}
33
34impl BasicSnippet for SafeMul {
35    fn inputs(&self) -> Vec<(DataType, String)> {
36        ["right", "left"]
37            .map(|s| (DataType::U32, s.to_string()))
38            .to_vec()
39    }
40
41    fn outputs(&self) -> Vec<(DataType, String)> {
42        vec![(DataType::U32, "left · right".to_string())]
43    }
44
45    fn entrypoint(&self) -> String {
46        "tasmlib_arithmetic_u32_safe_mul".to_string()
47    }
48
49    fn code(&self, _: &mut Library) -> Vec<LabelledInstruction> {
50        triton_asm!(
51            // BEFORE: _ right left
52            // AFTER:  _ product
53            {self.entrypoint()}:
54                mul
55                dup 0  // _ product product
56                split  // _ product hi lo
57                pop 1  // _ product hi
58                push 0 // _ product hi 0
59                eq     // _ product (hi == 0)
60                assert error_id {Self::OVERFLOW_ERROR_ID}
61                return
62        )
63    }
64
65    fn sign_offs(&self) -> HashMap<Reviewer, SignOffFingerprint> {
66        let mut sign_offs = HashMap::new();
67        sign_offs.insert(Reviewer("ferdinand"), 0x3836d772ff7b6165.into());
68        sign_offs
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use crate::test_prelude::*;
76
77    impl Closure for SafeMul {
78        type Args = (u32, u32);
79
80        fn rust_shadow(&self, stack: &mut Vec<BFieldElement>) {
81            let (right, left) = pop_encodable::<Self::Args>(stack);
82            let product = left.checked_mul(right).unwrap();
83            push_encodable(stack, &product);
84        }
85
86        fn pseudorandom_args(
87            &self,
88            seed: [u8; 32],
89            bench_case: Option<BenchmarkCase>,
90        ) -> Self::Args {
91            let Some(bench_case) = bench_case else {
92                let mut rng = StdRng::from_seed(seed);
93                let left = rng.random_range(1..=u32::MAX);
94                let right = rng.random_range(0..=u32::MAX / left);
95
96                return (right, left);
97            };
98
99            match bench_case {
100                BenchmarkCase::CommonCase => (1 << 8, 1 << 9),
101                BenchmarkCase::WorstCase => (1 << 15, 1 << 16),
102            }
103        }
104
105        fn corner_case_args(&self) -> Vec<Self::Args> {
106            [0, 1]
107                .into_iter()
108                .cartesian_product([0, 1, u32::MAX])
109                .collect()
110        }
111    }
112
113    #[test]
114    fn rust_shadow() {
115        ShadowedClosure::new(SafeMul).test();
116    }
117
118    #[proptest]
119    fn overflow_crashes_vm(
120        #[strategy(1_u32..)] left: u32,
121        #[strategy(u32::MAX / #left..)]
122        #[filter(#left.checked_mul(#right).is_none())]
123        right: u32,
124    ) {
125        test_assertion_failure(
126            &ShadowedClosure::new(SafeMul),
127            InitVmState::with_stack(SafeMul.set_up_test_stack((left, right))),
128            &[SafeMul::OVERFLOW_ERROR_ID],
129        )
130    }
131}
132
133#[cfg(test)]
134mod benches {
135    use super::*;
136    use crate::test_prelude::*;
137
138    #[test]
139    fn safe_mul_benchmark() {
140        ShadowedClosure::new(SafeMul).bench();
141    }
142}