Skip to main content

p256/arithmetic/
scalar.rs

1//! Scalar field arithmetic modulo n = 115792089210356248762697446949407573529996955224135760342422259061068512044369
2
3pub mod blinding;
4
5use crate::{
6    arithmetic::util::{adc, mac, sbb},
7    FieldBytes, NistP256,
8};
9use core::{
10    convert::TryInto,
11    ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign},
12};
13use elliptic_curve::{
14    generic_array::arr,
15    group::ff::{Field, PrimeField},
16    rand_core::RngCore,
17    subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption},
18    ScalarArithmetic,
19};
20
21#[cfg(feature = "bits")]
22use {crate::ScalarBits, elliptic_curve::group::ff::PrimeFieldBits};
23
24#[cfg(feature = "digest")]
25use ecdsa_core::{elliptic_curve::consts::U32, hazmat::FromDigest, signature::digest::Digest};
26
27#[cfg(feature = "zeroize")]
28use crate::SecretKey;
29#[cfg(feature = "zeroize")]
30use elliptic_curve::zeroize::Zeroize;
31
32/// The number of 64-bit limbs used to represent a [`Scalar`].
33const LIMBS: usize = 4;
34
35type U256 = [u64; LIMBS];
36
37/// Constant representing the modulus
38/// n = FFFFFFFF 00000000 FFFFFFFF FFFFFFFF BCE6FAAD A7179E84 F3B9CAC2 FC632551
39///
40/// # Calculating the modulus
41/// One way to calculate the modulus is with `GP/PARI`:
42///
43/// ```text
44/// p = (2^224) * (2^32 - 1) + 2^192 + 2^96 - 1
45/// b = 41058363725152142129326129780047268409114441015993725554835256314039467401291
46/// E = ellinit([Mod(-3, p), Mod(b, p)])
47/// default(parisize, 120000000)
48/// n = ellsea(E)
49/// isprime(n)
50/// ```
51pub const MODULUS: U256 = [
52    0xf3b9_cac2_fc63_2551,
53    0xbce6_faad_a717_9e84,
54    0xffff_ffff_ffff_ffff,
55    0xffff_ffff_0000_0000,
56];
57
58const MODULUS_SHR1: U256 = [
59    0x79dc_e561_7e31_92a8,
60    0xde73_7d56_d38b_cf42,
61    0x7fff_ffff_ffff_ffff,
62    0x7fff_ffff_8000_0000,
63];
64
65/// MU = floor(2^512 / n)
66///    = 115792089264276142090721624801893421302707618245269942344307673200490803338238
67///    = 0x100000000fffffffffffffffeffffffff43190552df1a6c21012ffd85eedf9bfe
68pub const MU: [u64; 5] = [
69    0x012f_fd85_eedf_9bfe,
70    0x4319_0552_df1a_6c21,
71    0xffff_fffe_ffff_ffff,
72    0x0000_0000_ffff_ffff,
73    0x0000_0000_0000_0001,
74];
75
76impl ScalarArithmetic for NistP256 {
77    type Scalar = Scalar;
78}
79
80/// Scalars are elements in the finite field modulo n.
81///
82/// # Trait impls
83///
84/// Much of the important functionality of scalars is provided by traits from
85/// the [`ff`](https://docs.rs/ff/) crate, which is re-exported as
86/// `p256::elliptic_curve::ff`:
87///
88/// - [`Field`](https://docs.rs/ff/latest/ff/trait.Field.html) -
89///   represents elements of finite fields and provides:
90///   - [`Field::random`](https://docs.rs/ff/latest/ff/trait.Field.html#tymethod.random) -
91///     generate a random scalar
92///   - `double`, `square`, and `invert` operations
93///   - Bounds for [`Add`], [`Sub`], [`Mul`], and [`Neg`] (as well as `*Assign` equivalents)
94///   - Bounds for [`ConditionallySelectable`] from the `subtle` crate
95/// - [`PrimeField`](https://docs.rs/ff/0.9.0/ff/trait.PrimeField.html) -
96///   represents elements of prime fields and provides:
97///   - `from_repr`/`to_repr` for converting field elements from/to big integers.
98///   - `char_le_bits`, `multiplicative_generator`, `root_of_unity` constants.
99/// - [`PrimeFieldBits`](https://docs.rs/ff/latest/ff/trait.PrimeFieldBits.html) -
100///   operations over field elements represented as bits (requires `bits` feature)
101///
102/// Please see the documentation for the relevant traits for more information.
103#[derive(Clone, Copy, Debug, Default)]
104#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
105pub struct Scalar(pub(crate) U256);
106
107impl Field for Scalar {
108    fn random(mut rng: impl RngCore) -> Self {
109        let mut bytes = FieldBytes::default();
110
111        // Generate a uniformly random scalar using rejection sampling,
112        // which produces a uniformly random distribution of scalars.
113        //
114        // This method is not constant time, but should be secure so long as
115        // rejected RNG outputs are unrelated to future ones (which is a
116        // necessary property of a `CryptoRng`).
117        //
118        // With an unbiased RNG, the probability of failing to complete after 4
119        // iterations is vanishingly small.
120        loop {
121            rng.fill_bytes(&mut bytes);
122            if let Some(scalar) = Scalar::from_repr(bytes) {
123                return scalar;
124            }
125        }
126    }
127
128    fn zero() -> Self {
129        Scalar::zero()
130    }
131
132    fn one() -> Self {
133        Scalar::one()
134    }
135
136    fn is_zero(&self) -> bool {
137        self.is_zero().into()
138    }
139
140    #[must_use]
141    fn square(&self) -> Self {
142        Scalar::square(self)
143    }
144
145    #[must_use]
146    fn double(&self) -> Self {
147        self.add(self)
148    }
149
150    fn invert(&self) -> CtOption<Self> {
151        Scalar::invert(self)
152    }
153
154    // TODO(tarcieri); stub! See: https://github.com/RustCrypto/elliptic-curves/issues/170
155    fn sqrt(&self) -> CtOption<Self> {
156        todo!("see RustCrypto/elliptic-curves#170");
157    }
158}
159
160impl PrimeField for Scalar {
161    type Repr = FieldBytes;
162
163    const NUM_BITS: u32 = 256;
164    const CAPACITY: u32 = 255;
165    const S: u32 = 4;
166
167    /// Attempts to parse the given byte array as an SEC1-encoded scalar.
168    ///
169    /// Returns None if the byte array does not contain a big-endian integer in the range
170    /// [0, p).
171    fn from_repr(bytes: FieldBytes) -> Option<Self> {
172        let mut w = [0u64; LIMBS];
173
174        // Interpret the bytes as a big-endian integer w.
175        w[3] = u64::from_be_bytes(bytes[0..8].try_into().unwrap());
176        w[2] = u64::from_be_bytes(bytes[8..16].try_into().unwrap());
177        w[1] = u64::from_be_bytes(bytes[16..24].try_into().unwrap());
178        w[0] = u64::from_be_bytes(bytes[24..32].try_into().unwrap());
179
180        // If w is in the range [0, n) then w - n will overflow, resulting in a borrow
181        // value of 2^64 - 1.
182        let (_, borrow) = sbb(w[0], MODULUS[0], 0);
183        let (_, borrow) = sbb(w[1], MODULUS[1], borrow);
184        let (_, borrow) = sbb(w[2], MODULUS[2], borrow);
185        let (_, borrow) = sbb(w[3], MODULUS[3], borrow);
186        let is_some = (borrow as u8) & 1;
187
188        CtOption::new(Scalar(w), Choice::from(is_some)).into()
189    }
190
191    fn to_repr(&self) -> FieldBytes {
192        self.to_bytes()
193    }
194
195    fn is_odd(&self) -> bool {
196        self.0[0] as u8 == 1
197    }
198
199    fn multiplicative_generator() -> Self {
200        7u64.into()
201    }
202
203    fn root_of_unity() -> Self {
204        Scalar::from_repr(arr![u8;
205            0xff, 0xc9, 0x7f, 0x06, 0x2a, 0x77, 0x09, 0x92, 0xba, 0x80, 0x7a, 0xce, 0x84, 0x2a,
206            0x3d, 0xfc, 0x15, 0x46, 0xca, 0xd0, 0x04, 0x37, 0x8d, 0xaf, 0x05, 0x92, 0xd7, 0xfb,
207            0xb4, 0x1e, 0x66, 0x00,
208        ])
209        .unwrap()
210    }
211}
212
213#[cfg(feature = "bits")]
214#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
215impl PrimeFieldBits for Scalar {
216    #[cfg(target_pointer_width = "32")]
217    type ReprBits = [u32; 8];
218
219    #[cfg(target_pointer_width = "64")]
220    type ReprBits = [u64; 4];
221
222    fn to_le_bits(&self) -> ScalarBits {
223        self.into()
224    }
225
226    #[cfg(target_pointer_width = "32")]
227    fn char_le_bits() -> ScalarBits {
228        [
229            0xfc63_2551,
230            0xf3b9_cac2,
231            0xa717_9e84,
232            0xbce6_faad,
233            0xffff_ffff,
234            0xffff_ffff,
235            0x0000_0000,
236            0xffff_ffff,
237        ]
238        .into()
239    }
240
241    #[cfg(target_pointer_width = "64")]
242    fn char_le_bits() -> ScalarBits {
243        MODULUS.into()
244    }
245}
246
247impl From<u64> for Scalar {
248    fn from(k: u64) -> Self {
249        Scalar([k, 0, 0, 0])
250    }
251}
252
253impl PartialEq for Scalar {
254    fn eq(&self, other: &Self) -> bool {
255        self.ct_eq(other).into()
256    }
257}
258
259impl Eq for Scalar {}
260
261impl PartialOrd for Scalar {
262    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
263        Some(self.cmp(other))
264    }
265}
266
267/// Returns sign of left - right
268fn cmp_vartime(left: &U256, right: &U256) -> i32 {
269    use core::cmp::Ordering::*;
270
271    // since we're little-endian, need to reverse iterate
272    for (l, r) in left.iter().rev().zip(right.iter().rev()) {
273        match l.cmp(r) {
274            Less => return -1,
275            Greater => return 1,
276            Equal => continue,
277        }
278    }
279    0
280}
281
282fn shr1(u256: &mut U256) {
283    let mut bit: u64 = 0;
284    for digit in u256.iter_mut().rev() {
285        let new_digit = (bit << 63) | (*digit >> 1);
286        bit = *digit & 1;
287        *digit = new_digit;
288    }
289}
290
291impl Ord for Scalar {
292    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
293        use core::cmp::Ordering::*;
294        match cmp_vartime(&self.0, &other.0) {
295            -1 => Less,
296            0 => Equal,
297            1 => Greater,
298            _ => unreachable!(),
299        }
300    }
301}
302
303#[cfg(feature = "digest")]
304#[cfg_attr(docsrs, doc(cfg(feature = "digest")))]
305impl FromDigest<NistP256> for Scalar {
306    /// Convert the output of a digest algorithm into a [`Scalar`] reduced
307    /// modulo n.
308    fn from_digest<D>(digest: D) -> Self
309    where
310        D: Digest<OutputSize = U32>,
311    {
312        Self::from_bytes_reduced(&digest.finalize())
313    }
314}
315
316impl Scalar {
317    /// Returns the zero scalar.
318    pub const fn zero() -> Scalar {
319        Scalar([0, 0, 0, 0])
320    }
321
322    /// Returns the multiplicative identity.
323    pub const fn one() -> Scalar {
324        Scalar([1, 0, 0, 0])
325    }
326
327    /// Parses the given byte array as a scalar.
328    ///
329    /// Subtracts the modulus when the byte array is larger than the modulus.
330    pub fn from_bytes_reduced(bytes: &FieldBytes) -> Self {
331        Self::sub_inner(
332            u64::from_be_bytes(bytes[24..32].try_into().unwrap()),
333            u64::from_be_bytes(bytes[16..24].try_into().unwrap()),
334            u64::from_be_bytes(bytes[8..16].try_into().unwrap()),
335            u64::from_be_bytes(bytes[0..8].try_into().unwrap()),
336            0,
337            MODULUS[0],
338            MODULUS[1],
339            MODULUS[2],
340            MODULUS[3],
341            0,
342        )
343    }
344
345    /// Returns the SEC1 encoding of this scalar.
346    pub fn to_bytes(&self) -> FieldBytes {
347        let mut ret = FieldBytes::default();
348        ret[0..8].copy_from_slice(&self.0[3].to_be_bytes());
349        ret[8..16].copy_from_slice(&self.0[2].to_be_bytes());
350        ret[16..24].copy_from_slice(&self.0[1].to_be_bytes());
351        ret[24..32].copy_from_slice(&self.0[0].to_be_bytes());
352        ret
353    }
354
355    /// Determine if this `Scalar` is zero.
356    ///
357    /// # Returns
358    ///
359    /// If zero, return `Choice(1)`.  Otherwise, return `Choice(0)`.
360    pub fn is_zero(&self) -> Choice {
361        self.ct_eq(&Scalar::zero())
362    }
363
364    /// Returns self + rhs mod n
365    pub const fn add(&self, rhs: &Self) -> Self {
366        // Bit 256 of n is set, so addition can result in five words.
367        let (w0, carry) = adc(self.0[0], rhs.0[0], 0);
368        let (w1, carry) = adc(self.0[1], rhs.0[1], carry);
369        let (w2, carry) = adc(self.0[2], rhs.0[2], carry);
370        let (w3, w4) = adc(self.0[3], rhs.0[3], carry);
371
372        // Attempt to subtract the modulus, to ensure the result is in the field.
373        Self::sub_inner(
374            w0, w1, w2, w3, w4, MODULUS[0], MODULUS[1], MODULUS[2], MODULUS[3], 0,
375        )
376    }
377
378    /// Returns 2*self.
379    pub const fn double(&self) -> Self {
380        self.add(self)
381    }
382
383    /// Returns self - rhs mod n
384    pub const fn subtract(&self, rhs: &Self) -> Self {
385        Self::sub_inner(
386            self.0[0], self.0[1], self.0[2], self.0[3], 0, rhs.0[0], rhs.0[1], rhs.0[2], rhs.0[3],
387            0,
388        )
389    }
390
391    #[inline]
392    #[allow(clippy::too_many_arguments)]
393    const fn sub_inner(
394        l0: u64,
395        l1: u64,
396        l2: u64,
397        l3: u64,
398        l4: u64,
399        r0: u64,
400        r1: u64,
401        r2: u64,
402        r3: u64,
403        r4: u64,
404    ) -> Self {
405        let (w0, borrow) = sbb(l0, r0, 0);
406        let (w1, borrow) = sbb(l1, r1, borrow);
407        let (w2, borrow) = sbb(l2, r2, borrow);
408        let (w3, borrow) = sbb(l3, r3, borrow);
409        let (_, borrow) = sbb(l4, r4, borrow);
410
411        // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
412        // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the
413        // modulus.
414        let (w0, carry) = adc(w0, MODULUS[0] & borrow, 0);
415        let (w1, carry) = adc(w1, MODULUS[1] & borrow, carry);
416        let (w2, carry) = adc(w2, MODULUS[2] & borrow, carry);
417        let (w3, _) = adc(w3, MODULUS[3] & borrow, carry);
418
419        Scalar([w0, w1, w2, w3])
420    }
421
422    /// Barrett Reduction
423    ///
424    /// The general algorithm is:
425    /// ```text
426    /// p = n = order of group
427    /// b = 2^64 = 64bit machine word
428    /// k = 4
429    /// a \in [0, 2^512]
430    /// mu := floor(b^{2k} / p)
431    /// q1 := floor(a / b^{k - 1})
432    /// q2 := q1 * mu
433    /// q3 := <- floor(a / b^{k - 1})
434    /// r1 := a mod b^{k + 1}
435    /// r2 := q3 * m mod b^{k + 1}
436    /// r := r1 - r2
437    ///
438    /// if r < 0: r := r + b^{k + 1}
439    /// while r >= p: do r := r - p (at most twice)
440    /// ```
441    ///
442    /// References:
443    /// - Handbook of Applied Cryptography, Chapter 14
444    ///   Algorithm 14.42
445    ///   http://cacr.uwaterloo.ca/hac/about/chap14.pdf
446    ///
447    /// - Efficient and Secure Elliptic Curve Cryptography Implementation of Curve P-256
448    ///   Algorithm 6) Barrett Reduction modulo p
449    ///   https://csrc.nist.gov/csrc/media/events/workshop-on-elliptic-curve-cryptography-standards/documents/papers/session6-adalier-mehmet.pdf
450    #[inline]
451    #[allow(clippy::too_many_arguments)]
452    const fn barrett_reduce(
453        a0: u64,
454        a1: u64,
455        a2: u64,
456        a3: u64,
457        a4: u64,
458        a5: u64,
459        a6: u64,
460        a7: u64,
461    ) -> Self {
462        let q1: [u64; 5] = [a3, a4, a5, a6, a7];
463
464        const fn q1_times_mu_shift_five(q1: &[u64; 5]) -> [u64; 5] {
465            // Schoolbook multiplication.
466
467            let (_w0, carry) = mac(0, q1[0], MU[0], 0);
468            let (w1, carry) = mac(0, q1[0], MU[1], carry);
469            let (w2, carry) = mac(0, q1[0], MU[2], carry);
470            let (w3, carry) = mac(0, q1[0], MU[3], carry);
471            let (w4, w5) = mac(0, q1[0], MU[4], carry);
472
473            let (_w1, carry) = mac(w1, q1[1], MU[0], 0);
474            let (w2, carry) = mac(w2, q1[1], MU[1], carry);
475            let (w3, carry) = mac(w3, q1[1], MU[2], carry);
476            let (w4, carry) = mac(w4, q1[1], MU[3], carry);
477            let (w5, w6) = mac(w5, q1[1], MU[4], carry);
478
479            let (_w2, carry) = mac(w2, q1[2], MU[0], 0);
480            let (w3, carry) = mac(w3, q1[2], MU[1], carry);
481            let (w4, carry) = mac(w4, q1[2], MU[2], carry);
482            let (w5, carry) = mac(w5, q1[2], MU[3], carry);
483            let (w6, w7) = mac(w6, q1[2], MU[4], carry);
484
485            let (_w3, carry) = mac(w3, q1[3], MU[0], 0);
486            let (w4, carry) = mac(w4, q1[3], MU[1], carry);
487            let (w5, carry) = mac(w5, q1[3], MU[2], carry);
488            let (w6, carry) = mac(w6, q1[3], MU[3], carry);
489            let (w7, w8) = mac(w7, q1[3], MU[4], carry);
490
491            let (_w4, carry) = mac(w4, q1[4], MU[0], 0);
492            let (w5, carry) = mac(w5, q1[4], MU[1], carry);
493            let (w6, carry) = mac(w6, q1[4], MU[2], carry);
494            let (w7, carry) = mac(w7, q1[4], MU[3], carry);
495            let (w8, w9) = mac(w8, q1[4], MU[4], carry);
496
497            // let q2 = [_w0, _w1, _w2, _w3, _w4, w5, w6, w7, w8, w9];
498            [w5, w6, w7, w8, w9]
499        }
500
501        let q3 = q1_times_mu_shift_five(&q1);
502
503        let r1: [u64; 5] = [a0, a1, a2, a3, a4];
504
505        const fn q3_times_n_keep_five(q3: &[u64; 5]) -> [u64; 5] {
506            // Schoolbook multiplication.
507
508            let (w0, carry) = mac(0, q3[0], MODULUS[0], 0);
509            let (w1, carry) = mac(0, q3[0], MODULUS[1], carry);
510            let (w2, carry) = mac(0, q3[0], MODULUS[2], carry);
511            let (w3, carry) = mac(0, q3[0], MODULUS[3], carry);
512            let (w4, _) = mac(0, q3[0], 0, carry);
513
514            let (w1, carry) = mac(w1, q3[1], MODULUS[0], 0);
515            let (w2, carry) = mac(w2, q3[1], MODULUS[1], carry);
516            let (w3, carry) = mac(w3, q3[1], MODULUS[2], carry);
517            let (w4, _) = mac(w4, q3[1], MODULUS[3], carry);
518
519            let (w2, carry) = mac(w2, q3[2], MODULUS[0], 0);
520            let (w3, carry) = mac(w3, q3[2], MODULUS[1], carry);
521            let (w4, _) = mac(w4, q3[2], MODULUS[2], carry);
522
523            let (w3, carry) = mac(w3, q3[3], MODULUS[0], 0);
524            let (w4, _) = mac(w4, q3[3], MODULUS[1], carry);
525
526            let (w4, _) = mac(w4, q3[4], MODULUS[0], 0);
527
528            [w0, w1, w2, w3, w4]
529        }
530
531        let r2: [u64; 5] = q3_times_n_keep_five(&q3);
532
533        #[inline]
534        #[allow(clippy::too_many_arguments)]
535        const fn sub_inner_five(l: [u64; 5], r: [u64; 5]) -> [u64; 5] {
536            let (w0, borrow) = sbb(l[0], r[0], 0);
537            let (w1, borrow) = sbb(l[1], r[1], borrow);
538            let (w2, borrow) = sbb(l[2], r[2], borrow);
539            let (w3, borrow) = sbb(l[3], r[3], borrow);
540            let (w4, _borrow) = sbb(l[4], r[4], borrow);
541
542            // If underflow occurred on the final limb - don't care (= add b^{k+1}).
543            [w0, w1, w2, w3, w4]
544        }
545
546        let r: [u64; 5] = sub_inner_five(r1, r2);
547
548        #[inline]
549        #[allow(clippy::too_many_arguments)]
550        const fn subtract_n_if_necessary(r0: u64, r1: u64, r2: u64, r3: u64, r4: u64) -> [u64; 5] {
551            let (w0, borrow) = sbb(r0, MODULUS[0], 0);
552            let (w1, borrow) = sbb(r1, MODULUS[1], borrow);
553            let (w2, borrow) = sbb(r2, MODULUS[2], borrow);
554            let (w3, borrow) = sbb(r3, MODULUS[3], borrow);
555            let (w4, borrow) = sbb(r4, 0, borrow);
556
557            // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
558            // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the
559            // modulus.
560            let (w0, carry) = adc(w0, MODULUS[0] & borrow, 0);
561            let (w1, carry) = adc(w1, MODULUS[1] & borrow, carry);
562            let (w2, carry) = adc(w2, MODULUS[2] & borrow, carry);
563            let (w3, carry) = adc(w3, MODULUS[3] & borrow, carry);
564            let (w4, _carry) = adc(w4, 0, carry);
565
566            [w0, w1, w2, w3, w4]
567        }
568
569        // Result is in range (0, 3*n - 1),
570        // and 90% of the time, no subtraction will be needed.
571        let r = subtract_n_if_necessary(r[0], r[1], r[2], r[3], r[4]);
572        let r = subtract_n_if_necessary(r[0], r[1], r[2], r[3], r[4]);
573        Scalar([r[0], r[1], r[2], r[3]])
574    }
575
576    /// Returns self * rhs mod n
577    pub const fn mul(&self, rhs: &Self) -> Self {
578        // Schoolbook multiplication.
579
580        let (w0, carry) = mac(0, self.0[0], rhs.0[0], 0);
581        let (w1, carry) = mac(0, self.0[0], rhs.0[1], carry);
582        let (w2, carry) = mac(0, self.0[0], rhs.0[2], carry);
583        let (w3, w4) = mac(0, self.0[0], rhs.0[3], carry);
584
585        let (w1, carry) = mac(w1, self.0[1], rhs.0[0], 0);
586        let (w2, carry) = mac(w2, self.0[1], rhs.0[1], carry);
587        let (w3, carry) = mac(w3, self.0[1], rhs.0[2], carry);
588        let (w4, w5) = mac(w4, self.0[1], rhs.0[3], carry);
589
590        let (w2, carry) = mac(w2, self.0[2], rhs.0[0], 0);
591        let (w3, carry) = mac(w3, self.0[2], rhs.0[1], carry);
592        let (w4, carry) = mac(w4, self.0[2], rhs.0[2], carry);
593        let (w5, w6) = mac(w5, self.0[2], rhs.0[3], carry);
594
595        let (w3, carry) = mac(w3, self.0[3], rhs.0[0], 0);
596        let (w4, carry) = mac(w4, self.0[3], rhs.0[1], carry);
597        let (w5, carry) = mac(w5, self.0[3], rhs.0[2], carry);
598        let (w6, w7) = mac(w6, self.0[3], rhs.0[3], carry);
599
600        Scalar::barrett_reduce(w0, w1, w2, w3, w4, w5, w6, w7)
601    }
602
603    /// Returns self * self mod p
604    pub const fn square(&self) -> Self {
605        // Schoolbook multiplication.
606        self.mul(self)
607    }
608
609    /// Returns `self^by`, where `by` is a little-endian integer exponent.
610    ///
611    /// **This operation is variable time with respect to the exponent.** If the exponent
612    /// is fixed, this operation is effectively constant time.
613    pub fn pow_vartime(&self, by: &[u64; 4]) -> Self {
614        let mut res = Self::one();
615        for e in by.iter().rev() {
616            for i in (0..64).rev() {
617                res = res.square();
618
619                if ((*e >> i) & 1) == 1 {
620                    res *= self;
621                }
622            }
623        }
624        res
625    }
626
627    /// Returns the multiplicative inverse of self, if self is non-zero
628    pub fn invert(&self) -> CtOption<Self> {
629        // We need to find b such that b * a ≡ 1 mod p. As we are in a prime
630        // field, we can apply Fermat's Little Theorem:
631        //
632        //    a^p         ≡ a mod p
633        //    a^(p-1)     ≡ 1 mod p
634        //    a^(p-2) * a ≡ 1 mod p
635        //
636        // Thus inversion can be implemented with a single exponentiation.
637        //
638        // This is `n - 2`, so the top right two digits are `4f` instead of `51`.
639        let inverse = self.pow_vartime(&[
640            0xf3b9_cac2_fc63_254f,
641            0xbce6_faad_a717_9e84,
642            0xffff_ffff_ffff_ffff,
643            0xffff_ffff_0000_0000,
644        ]);
645
646        CtOption::new(inverse, !self.is_zero())
647    }
648
649    /// Is integer representing equivalence class odd
650    pub fn is_odd(&self) -> Choice {
651        ((self.0[0] & 1) as u8).into()
652    }
653
654    /// Is integer representing equivalence class even
655    pub fn is_even(&self) -> Choice {
656        !self.is_odd()
657    }
658
659    fn shr1(&mut self) {
660        shr1(&mut self.0);
661    }
662
663    /// Faster inversion using Stein's algorithm
664    pub fn invert_vartime(&self) -> CtOption<Self> {
665        // https://link.springer.com/article/10.1007/s13389-016-0135-4
666
667        let mut u = *self;
668        // currently an invalid scalar
669        let mut v = Scalar(MODULUS);
670
671        #[allow(non_snake_case)]
672        let mut A = Self::one();
673        #[allow(non_snake_case)]
674        let mut C = Self::zero();
675
676        while !bool::from(u.is_zero()) {
677            // u-loop
678            while bool::from(u.is_even()) {
679                u.shr1();
680                if bool::from(A.is_even()) {
681                    A.shr1();
682                } else {
683                    A.shr1();
684                    A += Scalar(MODULUS_SHR1);
685                    A += Self::one();
686                }
687            }
688
689            // v-loop
690            while bool::from(v.is_even()) {
691                v.shr1();
692                if bool::from(C.is_even()) {
693                    C.shr1();
694                } else {
695                    C.shr1();
696                    C += Scalar(MODULUS_SHR1);
697                    C += Self::one();
698                }
699            }
700
701            // sub-step
702            if u >= v {
703                u -= &v;
704                A -= &C;
705            } else {
706                v -= &u;
707                C -= &A;
708            }
709        }
710
711        CtOption::new(C, !self.is_zero())
712    }
713}
714
715impl Add<Scalar> for Scalar {
716    type Output = Scalar;
717
718    fn add(self, other: Scalar) -> Scalar {
719        Scalar::add(&self, &other)
720    }
721}
722
723impl Add<&Scalar> for &Scalar {
724    type Output = Scalar;
725
726    fn add(self, other: &Scalar) -> Scalar {
727        Scalar::add(self, other)
728    }
729}
730
731impl Add<&Scalar> for Scalar {
732    type Output = Scalar;
733
734    fn add(self, other: &Scalar) -> Scalar {
735        Scalar::add(&self, other)
736    }
737}
738
739impl AddAssign<Scalar> for Scalar {
740    fn add_assign(&mut self, rhs: Scalar) {
741        *self = Scalar::add(self, &rhs);
742    }
743}
744
745impl AddAssign<&Scalar> for Scalar {
746    fn add_assign(&mut self, rhs: &Scalar) {
747        *self = Scalar::add(self, rhs);
748    }
749}
750
751impl Sub<Scalar> for Scalar {
752    type Output = Scalar;
753
754    fn sub(self, other: Scalar) -> Scalar {
755        Scalar::subtract(&self, &other)
756    }
757}
758
759impl Sub<&Scalar> for &Scalar {
760    type Output = Scalar;
761
762    fn sub(self, other: &Scalar) -> Scalar {
763        Scalar::subtract(self, other)
764    }
765}
766
767impl Sub<&Scalar> for Scalar {
768    type Output = Scalar;
769
770    fn sub(self, other: &Scalar) -> Scalar {
771        Scalar::subtract(&self, other)
772    }
773}
774
775impl SubAssign<Scalar> for Scalar {
776    fn sub_assign(&mut self, rhs: Scalar) {
777        *self = Scalar::subtract(self, &rhs);
778    }
779}
780
781impl SubAssign<&Scalar> for Scalar {
782    fn sub_assign(&mut self, rhs: &Scalar) {
783        *self = Scalar::subtract(self, rhs);
784    }
785}
786
787impl Mul<Scalar> for Scalar {
788    type Output = Scalar;
789
790    fn mul(self, other: Scalar) -> Scalar {
791        Scalar::mul(&self, &other)
792    }
793}
794
795impl Mul<&Scalar> for &Scalar {
796    type Output = Scalar;
797
798    fn mul(self, other: &Scalar) -> Scalar {
799        Scalar::mul(self, other)
800    }
801}
802
803impl Mul<&Scalar> for Scalar {
804    type Output = Scalar;
805
806    fn mul(self, other: &Scalar) -> Scalar {
807        Scalar::mul(&self, other)
808    }
809}
810
811impl MulAssign<Scalar> for Scalar {
812    fn mul_assign(&mut self, rhs: Scalar) {
813        *self = Scalar::mul(self, &rhs);
814    }
815}
816
817impl MulAssign<&Scalar> for Scalar {
818    fn mul_assign(&mut self, rhs: &Scalar) {
819        *self = Scalar::mul(self, rhs);
820    }
821}
822
823impl Neg for Scalar {
824    type Output = Scalar;
825
826    fn neg(self) -> Scalar {
827        Scalar::zero() - self
828    }
829}
830
831impl<'a> Neg for &'a Scalar {
832    type Output = Scalar;
833
834    fn neg(self) -> Scalar {
835        Scalar::zero() - self
836    }
837}
838
839impl ConditionallySelectable for Scalar {
840    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
841        Scalar([
842            u64::conditional_select(&a.0[0], &b.0[0], choice),
843            u64::conditional_select(&a.0[1], &b.0[1], choice),
844            u64::conditional_select(&a.0[2], &b.0[2], choice),
845            u64::conditional_select(&a.0[3], &b.0[3], choice),
846        ])
847    }
848}
849
850impl ConstantTimeEq for Scalar {
851    fn ct_eq(&self, other: &Self) -> Choice {
852        self.0[0].ct_eq(&other.0[0])
853            & self.0[1].ct_eq(&other.0[1])
854            & self.0[2].ct_eq(&other.0[2])
855            & self.0[3].ct_eq(&other.0[3])
856    }
857}
858
859#[cfg(all(feature = "bits", target_pointer_width = "32"))]
860#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
861impl From<&Scalar> for ScalarBits {
862    fn from(scalar: &Scalar) -> ScalarBits {
863        let mut output = [0u32; 8];
864
865        for (input, output) in scalar.0.iter().zip(output.chunks_mut(2)) {
866            output[0] = (input & 0xFFFFFFFF) as u32;
867            output[1] = (input >> 32) as u32;
868        }
869
870        output.into()
871    }
872}
873
874#[cfg(all(feature = "bits", target_pointer_width = "64"))]
875#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
876impl From<&Scalar> for ScalarBits {
877    fn from(scalar: &Scalar) -> ScalarBits {
878        scalar.0.into()
879    }
880}
881
882impl From<Scalar> for FieldBytes {
883    fn from(scalar: Scalar) -> Self {
884        scalar.to_bytes()
885    }
886}
887
888impl From<&Scalar> for FieldBytes {
889    fn from(scalar: &Scalar) -> Self {
890        scalar.to_bytes()
891    }
892}
893
894#[cfg(feature = "zeroize")]
895impl From<&SecretKey> for Scalar {
896    fn from(secret_key: &SecretKey) -> Scalar {
897        *secret_key.to_secret_scalar()
898    }
899}
900
901#[cfg(feature = "zeroize")]
902impl Zeroize for Scalar {
903    fn zeroize(&mut self) {
904        self.0.as_mut().zeroize()
905    }
906}
907
908#[cfg(test)]
909mod tests {
910    use super::Scalar;
911    use crate::FieldBytes;
912    use elliptic_curve::group::ff::PrimeField;
913
914    #[cfg(feature = "zeroize")]
915    use crate::SecretKey;
916
917    #[test]
918    fn from_to_bytes_roundtrip() {
919        let k: u64 = 42;
920        let mut bytes = FieldBytes::default();
921        bytes[24..].copy_from_slice(k.to_be_bytes().as_ref());
922
923        let scalar = Scalar::from_repr(bytes).unwrap();
924        assert_eq!(bytes, scalar.to_bytes());
925    }
926
927    #[test]
928    // Basic tests that multiplication works.
929    fn multiply() {
930        let one = Scalar::one();
931        let two = one + &one;
932        let three = two + &one;
933        let six = three + &three;
934        assert_eq!(six, two * &three);
935
936        let minus_two = -two;
937        let minus_three = -three;
938        assert_eq!(two, -minus_two);
939
940        assert_eq!(minus_three * &minus_two, minus_two * &minus_three);
941        assert_eq!(six, minus_two * &minus_three);
942    }
943
944    #[test]
945    // Basic tests that scalar inversion works.
946    fn invert() {
947        let one = Scalar::one();
948        let three = one + &one + &one;
949        let inv_three = three.invert().unwrap();
950        // println!("1/3 = {:x?}", &inv_three);
951        assert_eq!(three * &inv_three, one);
952
953        let minus_three = -three;
954        // println!("-3 = {:x?}", &minus_three);
955        let inv_minus_three = minus_three.invert().unwrap();
956        assert_eq!(inv_minus_three, -inv_three);
957        // println!("-1/3 = {:x?}", &inv_minus_three);
958        assert_eq!(three * &inv_minus_three, -one);
959    }
960
961    // Tests that a Scalar can be safely converted to a SecretKey and back
962    #[test]
963    #[cfg(feature = "zeroize")]
964    fn from_ec_secret() {
965        let scalar = Scalar::one();
966        let secret = SecretKey::from_bytes(scalar.to_bytes()).unwrap();
967        let rederived_scalar = Scalar::from(&secret);
968        assert_eq!(scalar.0, rederived_scalar.0);
969    }
970
971    #[test]
972    #[cfg(all(feature = "bits", target_pointer_width = "32"))]
973    fn scalar_into_scalarbits() {
974        use crate::ScalarBits;
975
976        let minus_one = ScalarBits::from([
977            0xfc63_2550,
978            0xf3b9_cac2,
979            0xa717_9e84,
980            0xbce6_faad,
981            0xffff_ffff,
982            0xffff_ffff,
983            0x0000_0000,
984            0xffff_ffff,
985        ]);
986
987        let scalar_bits = ScalarBits::from(&-Scalar::from(1));
988        assert_eq!(minus_one, scalar_bits);
989    }
990}