Skip to main content

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 parameters(&self) -> Vec<(DataType, String)> {
36        ["right", "left"]
37            .map(|s| (DataType::U32, s.to_string()))
38            .to_vec()
39    }
40
41    fn return_values(&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"), 0x502e4ccfdbf1b531.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>) -> Result<(), RustShadowError> {
81            let (right, left) = pop_encodable::<Self::Args>(stack)?;
82            let product = left
83                .checked_mul(right)
84                .ok_or(RustShadowError::ArithmeticOverflow)?;
85            push_encodable(stack, &product);
86            Ok(())
87        }
88
89        fn pseudorandom_args(
90            &self,
91            seed: [u8; 32],
92            bench_case: Option<BenchmarkCase>,
93        ) -> Self::Args {
94            let Some(bench_case) = bench_case else {
95                let mut rng = StdRng::from_seed(seed);
96                let left = rng.random_range(1..=u32::MAX);
97                let right = rng.random_range(0..=u32::MAX / left);
98
99                return (right, left);
100            };
101
102            match bench_case {
103                BenchmarkCase::CommonCase => (1 << 8, 1 << 9),
104                BenchmarkCase::WorstCase => (1 << 15, 1 << 16),
105            }
106        }
107
108        fn corner_case_args(&self) -> Vec<Self::Args> {
109            [0, 1]
110                .into_iter()
111                .cartesian_product([0, 1, u32::MAX])
112                .collect()
113        }
114    }
115
116    #[macro_rules_attr::apply(test)]
117    fn rust_shadow() {
118        ShadowedClosure::new(SafeMul).test();
119    }
120
121    #[macro_rules_attr::apply(proptest)]
122    fn overflow_crashes_vm(
123        #[strategy(1_u32..)] left: u32,
124        #[strategy(u32::MAX / #left..)]
125        #[filter(#left.checked_mul(#right).is_none())]
126        right: u32,
127    ) {
128        test_assertion_failure(
129            &ShadowedClosure::new(SafeMul),
130            InitVmState::with_stack(SafeMul.set_up_test_stack((left, right))),
131            &[SafeMul::OVERFLOW_ERROR_ID],
132        )
133    }
134}
135
136#[cfg(test)]
137mod benches {
138    use super::*;
139    use crate::test_prelude::*;
140
141    #[macro_rules_attr::apply(test)]
142    fn safe_mul_benchmark() {
143        ShadowedClosure::new(SafeMul).bench();
144    }
145}