Skip to main content

ethrex_levm/opcode_handlers/
arithmetic.rs

1//! # Arithmetic operations
2//!
3//! Includes the following opcodes:
4//!   - `ADD`
5//!   - `SUB`
6//!   - `MUL`
7//!   - `DIV`
8//!   - `SDIV`
9//!   - `MOD`
10//!   - `SMOD`
11//!   - `ADDMOD`
12//!   - `MULMOD`
13//!   - `EXP`
14//!   - `SIGNEXTEND`
15//!   - `CLZ`
16
17use crate::{
18    errors::{OpcodeResult, VMError},
19    gas_cost,
20    opcode_handlers::OpcodeHandler,
21    vm::VM,
22};
23use ethrex_common::U256;
24use ethrex_crypto::u256_div;
25
26/// Implementation for the `ADD` opcode.
27pub struct OpAddHandler;
28impl OpcodeHandler for OpAddHandler {
29    #[inline(always)]
30    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
31        vm.current_call_frame.increase_consumed_gas(gas_cost::ADD)?;
32
33        let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
34        *rhs = lhs.overflowing_add(*rhs).0;
35
36        Ok(OpcodeResult::Continue)
37    }
38}
39
40/// Implementation for the `SUB` opcode.
41pub struct OpSubHandler;
42impl OpcodeHandler for OpSubHandler {
43    #[inline(always)]
44    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
45        vm.current_call_frame.increase_consumed_gas(gas_cost::SUB)?;
46
47        let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
48        *rhs = lhs.overflowing_sub(*rhs).0;
49
50        Ok(OpcodeResult::Continue)
51    }
52}
53
54/// Implementation for the `MUL` opcode.
55pub struct OpMulHandler;
56impl OpcodeHandler for OpMulHandler {
57    #[inline(always)]
58    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
59        vm.current_call_frame.increase_consumed_gas(gas_cost::MUL)?;
60
61        let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
62        *rhs = wrapping_mul(&lhs, rhs);
63
64        Ok(OpcodeResult::Continue)
65    }
66}
67
68/// Implementation for the `DIV` opcode.
69pub struct OpDivHandler;
70impl OpcodeHandler for OpDivHandler {
71    #[inline(always)]
72    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
73        vm.current_call_frame.increase_consumed_gas(gas_cost::DIV)?;
74
75        let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
76        *rhs = u256_div::div(lhs, *rhs);
77
78        Ok(OpcodeResult::Continue)
79    }
80}
81
82/// Implementation for the `SDIV` opcode.
83pub struct OpSDivHandler;
84impl OpcodeHandler for OpSDivHandler {
85    #[inline(always)]
86    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
87        vm.current_call_frame
88            .increase_consumed_gas(gas_cost::SDIV)?;
89
90        let (&top, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
91        let mut lhs = top;
92        let mut rhs = *slot;
93
94        let mut sign = false;
95        if lhs.bit(255) {
96            lhs = U256::zero().overflowing_sub(lhs).0;
97            sign = !sign;
98        }
99        if rhs.bit(255) {
100            rhs = U256::zero().overflowing_sub(rhs).0;
101            sign = !sign;
102        }
103
104        let mut res = u256_div::div(lhs, rhs);
105        if sign {
106            res = U256::zero().overflowing_sub(res).0;
107        }
108        *slot = res;
109
110        Ok(OpcodeResult::Continue)
111    }
112}
113
114/// Implementation for the `MOD` opcode.
115pub struct OpModHandler;
116impl OpcodeHandler for OpModHandler {
117    #[inline(always)]
118    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
119        vm.current_call_frame.increase_consumed_gas(gas_cost::MOD)?;
120
121        let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
122        *rhs = u256_div::rem(lhs, *rhs);
123
124        Ok(OpcodeResult::Continue)
125    }
126}
127
128/// Implementation for the `SMOD` opcode.
129pub struct OpSModHandler;
130impl OpcodeHandler for OpSModHandler {
131    #[inline(always)]
132    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
133        vm.current_call_frame
134            .increase_consumed_gas(gas_cost::SMOD)?;
135
136        let (&top, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
137        let mut lhs = top;
138        let mut rhs = *slot;
139
140        let sign = lhs.bit(255);
141        if sign {
142            (lhs, _) = (!lhs).overflowing_add(U256::one());
143        }
144        if rhs.bit(255) {
145            (rhs, _) = (!rhs).overflowing_add(U256::one());
146        }
147
148        let mut res = u256_div::rem(lhs, rhs);
149        if sign {
150            (res, _) = (!res).overflowing_add(U256::one());
151        }
152        *slot = res;
153
154        Ok(OpcodeResult::Continue)
155    }
156}
157
158/// Implementation for the `ADDMOD` opcode.
159pub struct OpAddModHandler;
160impl OpcodeHandler for OpAddModHandler {
161    #[inline(always)]
162    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
163        vm.current_call_frame
164            .increase_consumed_gas(gas_cost::ADDMOD)?;
165
166        let [lhs, rhs, r#mod] = *vm.current_call_frame.stack.pop()?;
167        vm.current_call_frame
168            .stack
169            .push(u256_div::add_mod(lhs, rhs, r#mod))?;
170
171        Ok(OpcodeResult::Continue)
172    }
173}
174
175/// Implementation for the `MULMOD` opcode.
176pub struct OpMulModHandler;
177impl OpcodeHandler for OpMulModHandler {
178    #[inline(always)]
179    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
180        vm.current_call_frame
181            .increase_consumed_gas(gas_cost::MULMOD)?;
182
183        let [multiplicand, multiplier, modulus] = *vm.current_call_frame.stack.pop()?;
184        if modulus.is_zero() || multiplicand.is_zero() || multiplier.is_zero() {
185            vm.current_call_frame.stack.push_zero()?;
186        } else {
187            let a_bytes = multiplicand.to_big_endian();
188            let b_bytes = multiplier.to_big_endian();
189            let m_bytes = modulus.to_big_endian();
190            let result_bytes = vm.crypto.mulmod256(&a_bytes, &b_bytes, &m_bytes);
191            let product_mod = U256::from_big_endian(&result_bytes);
192            vm.current_call_frame.stack.push(product_mod)?;
193        }
194
195        Ok(OpcodeResult::Continue)
196    }
197}
198
199/// Implementation for the `EXP` opcode.
200pub struct OpExpHandler;
201impl OpcodeHandler for OpExpHandler {
202    #[inline(always)]
203    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
204        let [base, exp] = *vm.current_call_frame.stack.pop()?;
205        vm.current_call_frame
206            .increase_consumed_gas(gas_cost::exp(exp)?)?;
207
208        vm.current_call_frame.stack.push(wrapping_pow(base, exp))?;
209
210        Ok(OpcodeResult::Continue)
211    }
212}
213
214/// Implementation for the `SIGNEXTEND` opcode.
215pub struct OpSignExtendHandler;
216impl OpcodeHandler for OpSignExtendHandler {
217    #[inline(always)]
218    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
219        vm.current_call_frame
220            .increase_consumed_gas(gas_cost::SIGNEXTEND)?;
221
222        let (&index, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
223        *slot = sign_extend(index, *slot);
224
225        Ok(OpcodeResult::Continue)
226    }
227}
228
229/// Implementation for the `CLZ` opcode.
230pub struct OpClzHandler;
231impl OpcodeHandler for OpClzHandler {
232    #[inline(always)]
233    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
234        vm.current_call_frame.increase_consumed_gas(gas_cost::CLZ)?;
235
236        let slot = vm.current_call_frame.stack.top_mut()?;
237        let lz = slot.leading_zeros();
238        *slot = lz.into();
239
240        Ok(OpcodeResult::Continue)
241    }
242}
243
244/// Low 256 bits of `a * b`. Only the ten partial products below 2^256 are computed; the
245/// full 512-bit product needs sixteen.
246#[inline(always)]
247#[expect(
248    clippy::arithmetic_side_effects,
249    clippy::as_conversions,
250    clippy::indexing_slicing,
251    reason = "i + j < 4, and a 64x64-bit product plus two words fits in 128 bits"
252)]
253fn wrapping_mul(a: &U256, b: &U256) -> U256 {
254    let mut product = [0u64; 4];
255    for i in 0..4 {
256        let mut carry = 0u64;
257        for j in 0..4 - i {
258            let t = u128::from(a.0[i]) * u128::from(b.0[j])
259                + u128::from(product[i + j])
260                + u128::from(carry);
261            product[i + j] = t as u64;
262            carry = (t >> 64) as u64;
263        }
264    }
265    U256(product)
266}
267
268/// `base^exponent mod 2^256`.
269///
270/// Powers with a closed form skip square-and-multiply, which otherwise costs up to 255
271/// squarings for a full-width exponent: bases 0, 1 and 2^256 - 1, powers of two, and even
272/// bases raised far enough to wrap to zero.
273#[expect(
274    clippy::arithmetic_side_effects,
275    reason = "shift amounts and the exponent bit index stay below 256"
276)]
277fn wrapping_pow(base: U256, exponent: U256) -> U256 {
278    if exponent.is_zero() {
279        return U256::one();
280    }
281    if base <= U256::one() || exponent == U256::one() {
282        return base;
283    }
284    // (2^256 - 1)^e is (-1)^e.
285    if base == U256::MAX {
286        return if exponent.bit(0) {
287            U256::MAX
288        } else {
289            U256::one()
290        };
291    }
292    let trailing_zeros = base.trailing_zeros();
293    if trailing_zeros > 0 {
294        // base = 2^tz * odd, so base^e is a multiple of 2^(tz * e): zero once that
295        // reaches 2^256.
296        let shift = match u32::try_from(exponent) {
297            Ok(e) if e < 256 => trailing_zeros * e,
298            _ => return U256::zero(),
299        };
300        if shift >= 256 {
301            return U256::zero();
302        }
303        if base == U256::one() << trailing_zeros {
304            return U256::one() << shift;
305        }
306    }
307
308    // Left-to-right square-and-multiply over the exponent bits below the top one.
309    let mut result = base;
310    for i in (0..exponent.bits() - 1).rev() {
311        result = wrapping_mul(&result, &result);
312        if exponent.bit(i) {
313            result = wrapping_mul(&result, &base);
314        }
315    }
316    result
317}
318
319/// Extends the sign bit of byte `byte_index` (counted from the least significant byte)
320/// through the upper bytes of `value`. Indexes past 30 leave `value` unchanged.
321///
322/// Each limb is selected with constant indexes, so the result stays in registers instead
323/// of being patched in memory and read back.
324#[inline(always)]
325#[expect(
326    clippy::arithmetic_side_effects,
327    clippy::indexing_slicing,
328    reason = "byte_index < 31, so the sign bit is below 255 and its word below 4"
329)]
330fn sign_extend(byte_index: U256, value: U256) -> U256 {
331    let byte_index = match usize::try_from(byte_index) {
332        Ok(i) if i < 31 => i,
333        _ => return value,
334    };
335    let sign_bit = byte_index * 8 + 7;
336    let word = sign_bit / 64;
337    let bit = sign_bit % 64;
338    // All ones when the sign bit is set.
339    let fill = 0u64.wrapping_sub((value.0[word] >> bit) & 1);
340    // Bits up to and including the sign bit within its word.
341    let kept = u64::MAX >> (63 - bit);
342    let limb = |i: usize| match i.cmp(&word) {
343        core::cmp::Ordering::Less => value.0[i],
344        core::cmp::Ordering::Equal => (value.0[i] & kept) | (fill & !kept),
345        core::cmp::Ordering::Greater => fill,
346    };
347    U256([limb(0), limb(1), limb(2), limb(3)])
348}
349
350#[cfg(test)]
351#[expect(
352    clippy::arithmetic_side_effects,
353    clippy::as_conversions,
354    reason = "test operand generation"
355)]
356mod tests {
357    use super::*;
358
359    /// SplitMix64: deterministic operands without a dev-dependency.
360    struct Rng(u64);
361
362    impl Rng {
363        fn next(&mut self) -> u64 {
364            self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
365            let mut z = self.0;
366            z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
367            z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
368            z ^ (z >> 31)
369        }
370
371        fn word(&mut self) -> U256 {
372            let bits = (self.next() % 257) as usize;
373            let x = U256([self.next(), self.next(), self.next(), self.next()]);
374            if bits < 256 {
375                x & ((U256::one() << bits) - 1)
376            } else {
377                x
378            }
379        }
380    }
381
382    #[test]
383    fn wrapping_mul_matches_full_product() {
384        let mut rng = Rng(1);
385        for _ in 0..10_000 {
386            let (a, b) = (rng.word(), rng.word());
387            assert_eq!(
388                wrapping_mul(&a, &b),
389                a.overflowing_mul(b).0,
390                "{a:#x} * {b:#x}"
391            );
392        }
393        assert_eq!(wrapping_mul(&U256::MAX, &U256::MAX), U256::one());
394    }
395
396    #[test]
397    fn wrapping_pow_matches_square_and_multiply() {
398        let max = U256::MAX;
399        let bases = [
400            U256::zero(),
401            U256::one(),
402            U256::from(2),
403            U256::from(3),
404            U256::from(6),
405            U256::one() << 255,
406            U256::from(3) << 254,
407            max,
408            max - 1,
409            max - 2,
410        ];
411        let exponents = [
412            U256::zero(),
413            U256::one(),
414            U256::from(2),
415            U256::from(3),
416            U256::from(127),
417            U256::from(128),
418            U256::from(255),
419            U256::from(256),
420            U256::from(u32::MAX),
421            U256::one() << 32,
422            max - 1,
423            max,
424        ];
425        for base in bases {
426            for exponent in exponents {
427                assert_eq!(
428                    wrapping_pow(base, exponent),
429                    base.overflowing_pow(exponent).0,
430                    "{base:#x} ^ {exponent:#x}"
431                );
432            }
433        }
434        let mut rng = Rng(2);
435        for _ in 0..500 {
436            let (mut base, exponent) = (rng.word(), rng.word());
437            match rng.next() % 3 {
438                0 => base = U256::one() << (rng.next() % 256),
439                1 => base <<= rng.next() % 8,
440                _ => {}
441            }
442            assert_eq!(
443                wrapping_pow(base, exponent),
444                base.overflowing_pow(exponent).0,
445                "{base:#x} ^ {exponent:#x}"
446            );
447        }
448    }
449
450    #[test]
451    fn sign_extend_matches_definition() {
452        let mut rng = Rng(3);
453        for _ in 0..2_000 {
454            let value = rng.word();
455            for index in (0..34).chain([u64::MAX]) {
456                // Reference: keep the low (index + 1) bytes, fill the rest with the sign bit.
457                let expected = if index < 31 {
458                    let bits = 8 * (index as usize + 1);
459                    let low = value & ((U256::one() << bits) - 1);
460                    if value.bit(bits - 1) {
461                        low | (U256::MAX << bits)
462                    } else {
463                        low
464                    }
465                } else {
466                    value
467                };
468                assert_eq!(
469                    sign_extend(U256::from(index), value),
470                    expected,
471                    "signextend({index}, {value:#x})"
472                );
473            }
474        }
475        assert_eq!(
476            sign_extend(U256::one() << 64, U256::from(0x80)),
477            U256::from(0x80)
478        );
479        assert_eq!(
480            sign_extend(U256::from(3), U256::from(0xffda_dadau64)),
481            U256::MAX - 0x25_2525
482        );
483    }
484}