crypto_bigint/uint/
add_mod.rs

1//! [`Uint`] modular addition operations.
2
3use crate::{AddMod, Limb, Uint};
4
5impl<const LIMBS: usize> Uint<LIMBS> {
6    /// Computes `self + rhs mod p`.
7    ///
8    /// Assumes `self + rhs` as unbounded integer is `< 2p`.
9    pub const fn add_mod(&self, rhs: &Self, p: &Self) -> Self {
10        let (w, carry) = self.adc(rhs, Limb::ZERO);
11
12        // Attempt to subtract the modulus, to ensure the result is in the field.
13        let (w, borrow) = w.sbb(p, Limb::ZERO);
14        let (_, mask) = carry.sbb(Limb::ZERO, borrow);
15
16        // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
17        // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the
18        // modulus.
19        w.wrapping_add(&p.bitand_limb(mask))
20    }
21
22    /// Computes `self + rhs mod p` for the special modulus
23    /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`].
24    ///
25    /// Assumes `self + rhs` as unbounded integer is `< 2p`.
26    pub const fn add_mod_special(&self, rhs: &Self, c: Limb) -> Self {
27        // `Uint::adc` also works with a carry greater than 1.
28        let (out, carry) = self.adc(rhs, c);
29
30        // If overflow occurred, then above addition of `c` already accounts
31        // for the overflow. Otherwise, we need to subtract `c` again, which
32        // in that case cannot underflow.
33        let l = carry.0.wrapping_sub(1) & c.0;
34        out.wrapping_sub(&Self::from_word(l))
35    }
36
37    /// Computes `self + self mod p`.
38    ///
39    /// Assumes `self` as unbounded integer is `< p`.
40    pub const fn double_mod(&self, p: &Self) -> Self {
41        let (w, carry) = self.overflowing_shl1();
42
43        // Attempt to subtract the modulus, to ensure the result is in the field.
44        let (w, borrow) = w.sbb(p, Limb::ZERO);
45        let (_, mask) = carry.sbb(Limb::ZERO, borrow);
46
47        // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
48        // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the
49        // modulus.
50        w.wrapping_add(&p.bitand_limb(mask))
51    }
52}
53
54impl<const LIMBS: usize> AddMod for Uint<LIMBS> {
55    type Output = Self;
56
57    fn add_mod(&self, rhs: &Self, p: &Self) -> Self {
58        debug_assert!(self < p);
59        debug_assert!(rhs < p);
60        self.add_mod(rhs, p)
61    }
62}
63
64#[cfg(all(test, feature = "rand"))]
65mod tests {
66    use crate::{Limb, NonZero, Random, RandomMod, Uint, U256};
67    use rand_core::SeedableRng;
68
69    #[test]
70    fn add_mod_nist_p256() {
71        let a =
72            U256::from_be_hex("44acf6b7e36c1342c2c5897204fe09504e1e2efb1a900377dbc4e7a6a133ec56");
73        let b =
74            U256::from_be_hex("d5777c45019673125ad240f83094d4252d829516fac8601ed01979ec1ec1a251");
75        let n =
76            U256::from_be_hex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551");
77
78        let actual = a.add_mod(&b, &n);
79        let expected =
80            U256::from_be_hex("1a2472fde50286541d97ca6a3592dd75beb9c9646e40c511b82496cfc3926956");
81
82        assert_eq!(expected, actual);
83    }
84
85    #[test]
86    fn double_mod_expected() {
87        let a =
88            U256::from_be_hex("44acf6b7e36c1342c2c5897204fe09504e1e2efb1a900377dbc4e7a6a133ec56");
89        let n =
90            U256::from_be_hex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551");
91
92        assert_eq!(a.add_mod(&a, &n), a.double_mod(&n));
93    }
94
95    macro_rules! test_add_mod_special {
96        ($size:expr, $test_name:ident) => {
97            #[test]
98            fn $test_name() {
99                let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1);
100                let moduli = [
101                    NonZero::<Limb>::random(&mut rng),
102                    NonZero::<Limb>::random(&mut rng),
103                ];
104
105                for special in &moduli {
106                    let p =
107                        &NonZero::new(Uint::ZERO.wrapping_sub(&Uint::from(special.get()))).unwrap();
108
109                    let minus_one = p.wrapping_sub(&Uint::ONE);
110
111                    let base_cases = [
112                        (Uint::ZERO, Uint::ZERO, Uint::ZERO),
113                        (Uint::ONE, Uint::ZERO, Uint::ONE),
114                        (Uint::ZERO, Uint::ONE, Uint::ONE),
115                        (minus_one, Uint::ONE, Uint::ZERO),
116                        (Uint::ONE, minus_one, Uint::ZERO),
117                    ];
118                    for (a, b, c) in &base_cases {
119                        let x = a.add_mod_special(b, *special.as_ref());
120                        assert_eq!(*c, x, "{} + {} mod {} = {} != {}", a, b, p, x, c);
121                    }
122
123                    for _i in 0..100 {
124                        let a = Uint::<$size>::random_mod(&mut rng, p);
125                        let b = Uint::<$size>::random_mod(&mut rng, p);
126
127                        let c = a.add_mod_special(&b, *special.as_ref());
128                        assert!(c < **p, "not reduced: {} >= {} ", c, p);
129
130                        let expected = a.add_mod(&b, p);
131                        assert_eq!(c, expected, "incorrect result");
132                    }
133                }
134            }
135        };
136    }
137
138    test_add_mod_special!(1, add_mod_special_1);
139    test_add_mod_special!(2, add_mod_special_2);
140    test_add_mod_special!(3, add_mod_special_3);
141    test_add_mod_special!(4, add_mod_special_4);
142    test_add_mod_special!(5, add_mod_special_5);
143    test_add_mod_special!(6, add_mod_special_6);
144    test_add_mod_special!(7, add_mod_special_7);
145    test_add_mod_special!(8, add_mod_special_8);
146    test_add_mod_special!(9, add_mod_special_9);
147    test_add_mod_special!(10, add_mod_special_10);
148    test_add_mod_special!(11, add_mod_special_11);
149    test_add_mod_special!(12, add_mod_special_12);
150}