halo2curves_axiom/bls12_381/
scalar.rs

1//! This module provides an implementation of the BLS12-381 scalar field $\mathbb{F}_q$
2//! where `q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001`
3//! Source: <https://github.com/privacy-scaling-explorations/bls12_381>
4
5#![allow(clippy::needless_borrow)]
6use core::cmp::Ordering;
7use core::fmt;
8use core::ops::{Add, Mul, MulAssign, Neg, Sub};
9use rand_core::RngCore;
10
11use ff::{Field, PrimeField, WithSmallOrderMulGroup};
12use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
13
14#[cfg(feature = "bits")]
15use ff::{FieldBits, PrimeFieldBits};
16
17use crate::arithmetic::{adc, mac, sbb};
18use crate::{
19    impl_add_binop_specify_output, impl_binops_additive, impl_binops_additive_specify_output,
20    impl_binops_multiplicative, impl_binops_multiplicative_mixed, impl_sub_binop_specify_output,
21};
22
23/// Represents an element of the scalar field $\mathbb{F}_q$ of the BLS12-381 elliptic
24/// curve construction.
25// The internal representation of this type is four 64-bit unsigned
26// integers in little-endian order. `Scalar` values are always in
27// Montgomery form; i.e., Scalar(a) = aR mod q, with R = 2^256.
28#[derive(Clone, Copy, PartialEq, Eq, Hash)]
29pub struct Scalar(pub(crate) [u64; 4]);
30
31impl fmt::Debug for Scalar {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        let tmp = self.to_bytes();
34        write!(f, "0x")?;
35        for &b in tmp.iter().rev() {
36            write!(f, "{b:02x}")?;
37        }
38        Ok(())
39    }
40}
41
42impl fmt::Display for Scalar {
43    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44        write!(f, "{self:?}")
45    }
46}
47
48impl From<u64> for Scalar {
49    fn from(val: u64) -> Scalar {
50        Scalar([val, 0, 0, 0]) * R2
51    }
52}
53
54impl ConstantTimeEq for Scalar {
55    fn ct_eq(&self, other: &Self) -> Choice {
56        self.0[0].ct_eq(&other.0[0])
57            & self.0[1].ct_eq(&other.0[1])
58            & self.0[2].ct_eq(&other.0[2])
59            & self.0[3].ct_eq(&other.0[3])
60    }
61}
62
63// impl PartialEq for Scalar {
64//     #[inline]
65//     fn eq(&self, other: &Self) -> bool {
66//         bool::from(self.ct_eq(other))
67//     }
68// }
69
70impl Ord for Scalar {
71    fn cmp(&self, other: &Self) -> Ordering {
72        let left = self.to_repr();
73        let right = other.to_repr();
74        left.iter()
75            .zip(right.iter())
76            .rev()
77            .find_map(|(left_byte, right_byte)| match left_byte.cmp(right_byte) {
78                Ordering::Equal => None,
79                res => Some(res),
80            })
81            .unwrap_or(Ordering::Equal)
82    }
83}
84
85impl PartialOrd for Scalar {
86    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
87        Some(self.cmp(other))
88    }
89}
90
91impl ConditionallySelectable for Scalar {
92    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
93        Scalar([
94            u64::conditional_select(&a.0[0], &b.0[0], choice),
95            u64::conditional_select(&a.0[1], &b.0[1], choice),
96            u64::conditional_select(&a.0[2], &b.0[2], choice),
97            u64::conditional_select(&a.0[3], &b.0[3], choice),
98        ])
99    }
100}
101
102/// Constant representing the modulus
103/// q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
104const MODULUS: Scalar = Scalar([
105    0xffff_ffff_0000_0001,
106    0x53bd_a402_fffe_5bfe,
107    0x3339_d808_09a1_d805,
108    0x73ed_a753_299d_7d48,
109]);
110
111/// The modulus as u32 limbs.
112#[cfg(all(feature = "bits", not(target_pointer_width = "64")))]
113const MODULUS_LIMBS_32: [u32; 8] = [
114    0x0000_0001,
115    0xffff_ffff,
116    0xfffe_5bfe,
117    0x53bd_a402,
118    0x09a1_d805,
119    0x3339_d808,
120    0x299d_7d48,
121    0x73ed_a753,
122];
123
124// The number of bits needed to represent the modulus.
125const MODULUS_BITS: u32 = 255;
126
127// GENERATOR = 7 (multiplicative generator of r-1 order, that is also quadratic nonresidue)
128const GENERATOR: Scalar = Scalar([
129    0x0000_000e_ffff_fff1,
130    0x17e3_63d3_0018_9c0f,
131    0xff9c_5787_6f84_57b0,
132    0x3513_3220_8fc5_a8c4,
133]);
134
135impl<'a> Neg for &'a Scalar {
136    type Output = Scalar;
137
138    #[inline]
139    fn neg(self) -> Scalar {
140        self.neg()
141    }
142}
143
144impl Neg for Scalar {
145    type Output = Scalar;
146
147    #[inline]
148    fn neg(self) -> Scalar {
149        -&self
150    }
151}
152
153impl<'a, 'b> Sub<&'b Scalar> for &'a Scalar {
154    type Output = Scalar;
155
156    #[inline]
157    fn sub(self, rhs: &'b Scalar) -> Scalar {
158        self.sub(rhs)
159    }
160}
161
162impl<'a, 'b> Add<&'b Scalar> for &'a Scalar {
163    type Output = Scalar;
164
165    #[inline]
166    fn add(self, rhs: &'b Scalar) -> Scalar {
167        self.add(rhs)
168    }
169}
170
171impl<'a, 'b> Mul<&'b Scalar> for &'a Scalar {
172    type Output = Scalar;
173
174    #[inline]
175    fn mul(self, rhs: &'b Scalar) -> Scalar {
176        self.mul(rhs)
177    }
178}
179
180impl_binops_additive!(Scalar, Scalar);
181impl_binops_multiplicative!(Scalar, Scalar);
182
183/// INV = -(q^{-1} mod 2^64) mod 2^64
184const INV: u64 = 0xffff_fffe_ffff_ffff;
185
186/// R = 2^256 mod q
187const R: Scalar = Scalar([
188    0x0000_0001_ffff_fffe,
189    0x5884_b7fa_0003_4802,
190    0x998c_4fef_ecbc_4ff5,
191    0x1824_b159_acc5_056f,
192]);
193
194/// R^2 = 2^512 mod q
195const R2: Scalar = Scalar([
196    0xc999_e990_f3f2_9c6d,
197    0x2b6c_edcb_8792_5c23,
198    0x05d3_1496_7254_398f,
199    0x0748_d9d9_9f59_ff11,
200]);
201
202/// R^3 = 2^768 mod q
203const R3: Scalar = Scalar([
204    0xc62c_1807_439b_73af,
205    0x1b3e_0d18_8cf0_6990,
206    0x73d1_3c71_c7b5_f418,
207    0x6e2a_5bb9_c8db_33e9,
208]);
209
210/// 2^-1
211const TWO_INV: Scalar = Scalar([
212    0x0000_0000_ffff_ffff,
213    0xac42_5bfd_0001_a401,
214    0xccc6_27f7_f65e_27fa,
215    0x0c12_58ac_d662_82b7,
216]);
217
218// 2^S * t = MODULUS - 1 with t odd
219const S: u32 = 32;
220
221/// GENERATOR^t where t * 2^s + 1 = q
222/// with t odd. In other words, this
223/// is a 2^s root of unity.
224///
225/// `GENERATOR = 7 mod q` is a generator
226/// of the q - 1 order multiplicative
227/// subgroup.
228const ROOT_OF_UNITY: Scalar = Scalar([
229    0xb9b5_8d8c_5f0e_466a,
230    0x5b1b_4c80_1819_d7ec,
231    0x0af5_3ae3_52a3_1e64,
232    0x5bf3_adda_19e9_b27b,
233]);
234
235/// ROOT_OF_UNITY^-1
236const ROOT_OF_UNITY_INV: Scalar = Scalar([
237    0x4256_481a_dcf3_219a,
238    0x45f3_7b7f_96b6_cad3,
239    0xf9c3_f1d7_5f7a_3b27,
240    0x2d2f_c049_658a_fd43,
241]);
242
243/// GENERATOR^{2^s} where t * 2^s + 1 = q with t odd.
244/// In other words, this is a t root of unity.
245const DELTA: Scalar = Scalar([
246    0x70e3_10d3_d146_f96a,
247    0x4b64_c089_19e2_99e6,
248    0x51e1_1418_6a8b_970d,
249    0x6185_d066_27c0_67cb,
250]);
251
252/// ZETA
253// sage: modulus = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
254//sage: GF(modulus).primitive_element() ^ ((modulus - 1) // 3)
255//228988810152649578064853576960394133503
256const ZETA: Scalar = Scalar::from_raw([0x00000000ffffffff, 0xac45a4010001a402, 0, 0]);
257
258impl Default for Scalar {
259    #[inline]
260    fn default() -> Self {
261        Self::zero()
262    }
263}
264
265#[cfg(feature = "zeroize")]
266impl zeroize::DefaultIsZeroes for Scalar {}
267
268impl Scalar {
269    /// Returns zero, the additive identity.
270    #[inline]
271    pub const fn zero() -> Scalar {
272        Scalar([0, 0, 0, 0])
273    }
274
275    /// Returns one, the multiplicative identity.
276    #[inline]
277    pub const fn one() -> Scalar {
278        R
279    }
280
281    /// Doubles this field element.
282    #[inline]
283    pub const fn double(&self) -> Scalar {
284        // TODO: This can be achieved more efficiently with a bitshift.
285        self.add(self)
286    }
287
288    /// Attempts to convert a little-endian byte representation of
289    /// a scalar into a `Scalar`, failing if the input is not canonical.
290    pub fn from_bytes(bytes: &[u8; 32]) -> CtOption<Scalar> {
291        let mut tmp = Scalar([0, 0, 0, 0]);
292
293        tmp.0[0] = u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[0..8]).unwrap());
294        tmp.0[1] = u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[8..16]).unwrap());
295        tmp.0[2] = u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[16..24]).unwrap());
296        tmp.0[3] = u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[24..32]).unwrap());
297
298        // Try to subtract the modulus
299        let (_, borrow) = sbb(tmp.0[0], MODULUS.0[0], 0);
300        let (_, borrow) = sbb(tmp.0[1], MODULUS.0[1], borrow);
301        let (_, borrow) = sbb(tmp.0[2], MODULUS.0[2], borrow);
302        let (_, borrow) = sbb(tmp.0[3], MODULUS.0[3], borrow);
303
304        // If the element is smaller than MODULUS then the
305        // subtraction will underflow, producing a borrow value
306        // of 0xffff...ffff. Otherwise, it'll be zero.
307        let is_some = (borrow as u8) & 1;
308
309        // Convert to Montgomery form by computing
310        // (a.R^0 * R^2) / R = a.R
311        tmp *= &R2;
312
313        CtOption::new(tmp, Choice::from(is_some))
314    }
315
316    /// Converts an element of `Scalar` into a byte representation in
317    /// little-endian byte order.
318    pub fn to_bytes(&self) -> [u8; 32] {
319        // Turn into canonical form by computing
320        // (a.R) / R = a
321        let tmp = Scalar::montgomery_reduce(self.0[0], self.0[1], self.0[2], self.0[3], 0, 0, 0, 0);
322
323        let mut res = [0; 32];
324        res[0..8].copy_from_slice(&tmp.0[0].to_le_bytes());
325        res[8..16].copy_from_slice(&tmp.0[1].to_le_bytes());
326        res[16..24].copy_from_slice(&tmp.0[2].to_le_bytes());
327        res[24..32].copy_from_slice(&tmp.0[3].to_le_bytes());
328
329        res
330    }
331
332    /// Converts a 512-bit little endian integer into
333    /// a `Scalar` by reducing by the modulus.
334    pub fn from_bytes_wide(bytes: &[u8; 64]) -> Scalar {
335        Scalar::from_u512([
336            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[0..8]).unwrap()),
337            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[8..16]).unwrap()),
338            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[16..24]).unwrap()),
339            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[24..32]).unwrap()),
340            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[32..40]).unwrap()),
341            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[40..48]).unwrap()),
342            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[48..56]).unwrap()),
343            u64::from_le_bytes(<[u8; 8]>::try_from(&bytes[56..64]).unwrap()),
344        ])
345    }
346
347    fn from_u512(limbs: [u64; 8]) -> Scalar {
348        // We reduce an arbitrary 512-bit number by decomposing it into two 256-bit digits
349        // with the higher bits multiplied by 2^256. Thus, we perform two reductions
350        //
351        // 1. the lower bits are multiplied by R^2, as normal
352        // 2. the upper bits are multiplied by R^2 * 2^256 = R^3
353        //
354        // and computing their sum in the field. It remains to see that arbitrary 256-bit
355        // numbers can be placed into Montgomery form safely using the reduction. The
356        // reduction works so long as the product is less than R=2^256 multiplied by
357        // the modulus. This holds because for any `c` smaller than the modulus, we have
358        // that (2^256 - 1)*c is an acceptable product for the reduction. Therefore, the
359        // reduction always works so long as `c` is in the field; in this case it is either the
360        // constant `R2` or `R3`.
361        let d0 = Scalar([limbs[0], limbs[1], limbs[2], limbs[3]]);
362        let d1 = Scalar([limbs[4], limbs[5], limbs[6], limbs[7]]);
363        // Convert to Montgomery form
364        d0 * R2 + d1 * R3
365    }
366
367    /// Converts from an integer represented in little endian
368    /// into its (congruent) `Scalar` representation.
369    pub const fn from_raw(val: [u64; 4]) -> Self {
370        (&Scalar(val)).mul(&R2)
371    }
372
373    /// Squares this element.
374    #[inline]
375    pub const fn square(&self) -> Scalar {
376        let (r1, carry) = mac(0, self.0[0], self.0[1], 0);
377        let (r2, carry) = mac(0, self.0[0], self.0[2], carry);
378        let (r3, r4) = mac(0, self.0[0], self.0[3], carry);
379
380        let (r3, carry) = mac(r3, self.0[1], self.0[2], 0);
381        let (r4, r5) = mac(r4, self.0[1], self.0[3], carry);
382
383        let (r5, r6) = mac(r5, self.0[2], self.0[3], 0);
384
385        let r7 = r6 >> 63;
386        let r6 = (r6 << 1) | (r5 >> 63);
387        let r5 = (r5 << 1) | (r4 >> 63);
388        let r4 = (r4 << 1) | (r3 >> 63);
389        let r3 = (r3 << 1) | (r2 >> 63);
390        let r2 = (r2 << 1) | (r1 >> 63);
391        let r1 = r1 << 1;
392
393        let (r0, carry) = mac(0, self.0[0], self.0[0], 0);
394        let (r1, carry) = adc(0, r1, carry);
395        let (r2, carry) = mac(r2, self.0[1], self.0[1], carry);
396        let (r3, carry) = adc(0, r3, carry);
397        let (r4, carry) = mac(r4, self.0[2], self.0[2], carry);
398        let (r5, carry) = adc(0, r5, carry);
399        let (r6, carry) = mac(r6, self.0[3], self.0[3], carry);
400        let (r7, _) = adc(0, r7, carry);
401
402        Scalar::montgomery_reduce(r0, r1, r2, r3, r4, r5, r6, r7)
403    }
404
405    /// Exponentiates `self` by `by`, where `by` is a
406    /// little-endian order integer exponent.
407    pub fn pow(&self, by: &[u64; 4]) -> Self {
408        let mut res = Self::one();
409        for e in by.iter().rev() {
410            for i in (0..64).rev() {
411                res = res.square();
412                let mut tmp = res;
413                tmp *= self;
414                res.conditional_assign(&tmp, (((*e >> i) & 0x1) as u8).into());
415            }
416        }
417        res
418    }
419
420    /// Exponentiates `self` by `by`, where `by` is a
421    /// little-endian order integer exponent.
422    ///
423    /// **This operation is variable time with respect
424    /// to the exponent.** If the exponent is fixed,
425    /// this operation is effectively constant time.
426    pub fn pow_vartime(&self, by: &[u64; 4]) -> Self {
427        let mut res = Self::one();
428        for e in by.iter().rev() {
429            for i in (0..64).rev() {
430                res = res.square();
431
432                if ((*e >> i) & 1) == 1 {
433                    res.mul_assign(self);
434                }
435            }
436        }
437        res
438    }
439
440    /// Computes the multiplicative inverse of this element,
441    /// failing if the element is zero.
442    pub fn invert(&self) -> CtOption<Self> {
443        #[inline(always)]
444        fn square_assign_multi(n: &mut Scalar, num_times: usize) {
445            for _ in 0..num_times {
446                *n = n.square();
447            }
448        }
449        // found using https://github.com/kwantam/addchain
450        let mut t0 = self.square();
451        let mut t1 = t0 * self;
452        let mut t16 = t0.square();
453        let mut t6 = t16.square();
454        let mut t5 = t6 * t0;
455        t0 = t6 * t16;
456        let mut t12 = t5 * t16;
457        let mut t2 = t6.square();
458        let mut t7 = t5 * t6;
459        let mut t15 = t0 * t5;
460        let mut t17 = t12.square();
461        t1 *= t17;
462        let mut t3 = t7 * t2;
463        let t8 = t1 * t17;
464        let t4 = t8 * t2;
465        let t9 = t8 * t7;
466        t7 = t4 * t5;
467        let t11 = t4 * t17;
468        t5 = t9 * t17;
469        let t14 = t7 * t15;
470        let t13 = t11 * t12;
471        t12 = t11 * t17;
472        t15 *= &t12;
473        t16 *= &t15;
474        t3 *= &t16;
475        t17 *= &t3;
476        t0 *= &t17;
477        t6 *= &t0;
478        t2 *= &t6;
479        square_assign_multi(&mut t0, 8);
480        t0 *= &t17;
481        square_assign_multi(&mut t0, 9);
482        t0 *= &t16;
483        square_assign_multi(&mut t0, 9);
484        t0 *= &t15;
485        square_assign_multi(&mut t0, 9);
486        t0 *= &t15;
487        square_assign_multi(&mut t0, 7);
488        t0 *= &t14;
489        square_assign_multi(&mut t0, 7);
490        t0 *= &t13;
491        square_assign_multi(&mut t0, 10);
492        t0 *= &t12;
493        square_assign_multi(&mut t0, 9);
494        t0 *= &t11;
495        square_assign_multi(&mut t0, 8);
496        t0 *= &t8;
497        square_assign_multi(&mut t0, 8);
498        t0 *= self;
499        square_assign_multi(&mut t0, 14);
500        t0 *= &t9;
501        square_assign_multi(&mut t0, 10);
502        t0 *= &t8;
503        square_assign_multi(&mut t0, 15);
504        t0 *= &t7;
505        square_assign_multi(&mut t0, 10);
506        t0 *= &t6;
507        square_assign_multi(&mut t0, 8);
508        t0 *= &t5;
509        square_assign_multi(&mut t0, 16);
510        t0 *= &t3;
511        square_assign_multi(&mut t0, 8);
512        t0 *= &t2;
513        square_assign_multi(&mut t0, 7);
514        t0 *= &t4;
515        square_assign_multi(&mut t0, 9);
516        t0 *= &t2;
517        square_assign_multi(&mut t0, 8);
518        t0 *= &t3;
519        square_assign_multi(&mut t0, 8);
520        t0 *= &t2;
521        square_assign_multi(&mut t0, 8);
522        t0 *= &t2;
523        square_assign_multi(&mut t0, 8);
524        t0 *= &t2;
525        square_assign_multi(&mut t0, 8);
526        t0 *= &t3;
527        square_assign_multi(&mut t0, 8);
528        t0 *= &t2;
529        square_assign_multi(&mut t0, 8);
530        t0 *= &t2;
531        square_assign_multi(&mut t0, 5);
532        t0 *= &t1;
533        square_assign_multi(&mut t0, 5);
534        t0 *= &t1;
535
536        CtOption::new(t0, !self.ct_eq(&Self::zero()))
537    }
538
539    #[inline(always)]
540    const fn montgomery_reduce(
541        r0: u64,
542        r1: u64,
543        r2: u64,
544        r3: u64,
545        r4: u64,
546        r5: u64,
547        r6: u64,
548        r7: u64,
549    ) -> Self {
550        // The Montgomery reduction here is based on Algorithm 14.32 in
551        // Handbook of Applied Cryptography
552        // <http://cacr.uwaterloo.ca/hac/about/chap14.pdf>.
553
554        let k = r0.wrapping_mul(INV);
555        let (_, carry) = mac(r0, k, MODULUS.0[0], 0);
556        let (r1, carry) = mac(r1, k, MODULUS.0[1], carry);
557        let (r2, carry) = mac(r2, k, MODULUS.0[2], carry);
558        let (r3, carry) = mac(r3, k, MODULUS.0[3], carry);
559        let (r4, carry2) = adc(r4, 0, carry);
560
561        let k = r1.wrapping_mul(INV);
562        let (_, carry) = mac(r1, k, MODULUS.0[0], 0);
563        let (r2, carry) = mac(r2, k, MODULUS.0[1], carry);
564        let (r3, carry) = mac(r3, k, MODULUS.0[2], carry);
565        let (r4, carry) = mac(r4, k, MODULUS.0[3], carry);
566        let (r5, carry2) = adc(r5, carry2, carry);
567
568        let k = r2.wrapping_mul(INV);
569        let (_, carry) = mac(r2, k, MODULUS.0[0], 0);
570        let (r3, carry) = mac(r3, k, MODULUS.0[1], carry);
571        let (r4, carry) = mac(r4, k, MODULUS.0[2], carry);
572        let (r5, carry) = mac(r5, k, MODULUS.0[3], carry);
573        let (r6, carry2) = adc(r6, carry2, carry);
574
575        let k = r3.wrapping_mul(INV);
576        let (_, carry) = mac(r3, k, MODULUS.0[0], 0);
577        let (r4, carry) = mac(r4, k, MODULUS.0[1], carry);
578        let (r5, carry) = mac(r5, k, MODULUS.0[2], carry);
579        let (r6, carry) = mac(r6, k, MODULUS.0[3], carry);
580        let (r7, _) = adc(r7, carry2, carry);
581
582        // Result may be within MODULUS of the correct value
583        (&Scalar([r4, r5, r6, r7])).sub(&MODULUS)
584    }
585
586    /// Multiplies `rhs` by `self`, returning the result.
587    #[inline]
588    pub const fn mul(&self, rhs: &Self) -> Self {
589        // Schoolbook multiplication
590
591        let (r0, carry) = mac(0, self.0[0], rhs.0[0], 0);
592        let (r1, carry) = mac(0, self.0[0], rhs.0[1], carry);
593        let (r2, carry) = mac(0, self.0[0], rhs.0[2], carry);
594        let (r3, r4) = mac(0, self.0[0], rhs.0[3], carry);
595
596        let (r1, carry) = mac(r1, self.0[1], rhs.0[0], 0);
597        let (r2, carry) = mac(r2, self.0[1], rhs.0[1], carry);
598        let (r3, carry) = mac(r3, self.0[1], rhs.0[2], carry);
599        let (r4, r5) = mac(r4, self.0[1], rhs.0[3], carry);
600
601        let (r2, carry) = mac(r2, self.0[2], rhs.0[0], 0);
602        let (r3, carry) = mac(r3, self.0[2], rhs.0[1], carry);
603        let (r4, carry) = mac(r4, self.0[2], rhs.0[2], carry);
604        let (r5, r6) = mac(r5, self.0[2], rhs.0[3], carry);
605
606        let (r3, carry) = mac(r3, self.0[3], rhs.0[0], 0);
607        let (r4, carry) = mac(r4, self.0[3], rhs.0[1], carry);
608        let (r5, carry) = mac(r5, self.0[3], rhs.0[2], carry);
609        let (r6, r7) = mac(r6, self.0[3], rhs.0[3], carry);
610
611        Scalar::montgomery_reduce(r0, r1, r2, r3, r4, r5, r6, r7)
612    }
613
614    /// Subtracts `rhs` from `self`, returning the result.
615    #[inline]
616    pub const fn sub(&self, rhs: &Self) -> Self {
617        let (d0, borrow) = sbb(self.0[0], rhs.0[0], 0);
618        let (d1, borrow) = sbb(self.0[1], rhs.0[1], borrow);
619        let (d2, borrow) = sbb(self.0[2], rhs.0[2], borrow);
620        let (d3, borrow) = sbb(self.0[3], rhs.0[3], borrow);
621
622        // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
623        // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the modulus.
624        let (d0, carry) = adc(d0, MODULUS.0[0] & borrow, 0);
625        let (d1, carry) = adc(d1, MODULUS.0[1] & borrow, carry);
626        let (d2, carry) = adc(d2, MODULUS.0[2] & borrow, carry);
627        let (d3, _) = adc(d3, MODULUS.0[3] & borrow, carry);
628
629        Scalar([d0, d1, d2, d3])
630    }
631
632    /// Adds `rhs` to `self`, returning the result.
633    #[inline]
634    pub const fn add(&self, rhs: &Self) -> Self {
635        let (d0, carry) = adc(self.0[0], rhs.0[0], 0);
636        let (d1, carry) = adc(self.0[1], rhs.0[1], carry);
637        let (d2, carry) = adc(self.0[2], rhs.0[2], carry);
638        let (d3, _) = adc(self.0[3], rhs.0[3], carry);
639
640        // Attempt to subtract the modulus, to ensure the value
641        // is smaller than the modulus.
642        (&Scalar([d0, d1, d2, d3])).sub(&MODULUS)
643    }
644
645    /// Negates `self`.
646    #[inline]
647    pub const fn neg(&self) -> Self {
648        // Subtract `self` from `MODULUS` to negate. Ignore the final
649        // borrow because it cannot underflow; self is guaranteed to
650        // be in the field.
651        let (d0, borrow) = sbb(MODULUS.0[0], self.0[0], 0);
652        let (d1, borrow) = sbb(MODULUS.0[1], self.0[1], borrow);
653        let (d2, borrow) = sbb(MODULUS.0[2], self.0[2], borrow);
654        let (d3, _) = sbb(MODULUS.0[3], self.0[3], borrow);
655
656        // `tmp` could be `MODULUS` if `self` was zero. Create a mask that is
657        // zero if `self` was zero, and `u64::max_value()` if self was nonzero.
658        let mask = (((self.0[0] | self.0[1] | self.0[2] | self.0[3]) == 0) as u64).wrapping_sub(1);
659
660        Scalar([d0 & mask, d1 & mask, d2 & mask, d3 & mask])
661    }
662}
663
664impl From<Scalar> for [u8; 32] {
665    fn from(value: Scalar) -> [u8; 32] {
666        value.to_bytes()
667    }
668}
669
670impl<'a> From<&'a Scalar> for [u8; 32] {
671    fn from(value: &'a Scalar) -> [u8; 32] {
672        value.to_bytes()
673    }
674}
675
676impl Field for Scalar {
677    const ZERO: Self = Self::zero();
678    const ONE: Self = Self::one();
679
680    fn random(mut rng: impl RngCore) -> Self {
681        let mut buf = [0; 64];
682        rng.fill_bytes(&mut buf);
683        Self::from_bytes_wide(&buf)
684    }
685
686    #[must_use]
687    fn square(&self) -> Self {
688        self.square()
689    }
690
691    #[must_use]
692    fn double(&self) -> Self {
693        self.double()
694    }
695
696    fn invert(&self) -> CtOption<Self> {
697        self.invert()
698    }
699
700    fn sqrt_ratio(num: &Self, div: &Self) -> (Choice, Self) {
701        ff::helpers::sqrt_ratio_generic(num, div)
702    }
703
704    fn sqrt(&self) -> CtOption<Self> {
705        // (t - 1) // 2 = 6104339283789297388802252303364915521546564123189034618274734669823
706        ff::helpers::sqrt_tonelli_shanks(
707            self,
708            [
709                0x7fff_2dff_7fff_ffff,
710                0x04d0_ec02_a9de_d201,
711                0x94ce_bea4_199c_ec04,
712                0x0000_0000_39f6_d3a9,
713            ],
714        )
715    }
716
717    fn is_zero_vartime(&self) -> bool {
718        self.0 == Self::zero().0
719    }
720}
721
722impl PrimeField for Scalar {
723    type Repr = [u8; 32];
724
725    fn from_repr(r: Self::Repr) -> CtOption<Self> {
726        Self::from_bytes(&r)
727    }
728
729    fn to_repr(&self) -> Self::Repr {
730        self.to_bytes()
731    }
732
733    fn is_odd(&self) -> Choice {
734        Choice::from(self.to_bytes()[0] & 1)
735    }
736
737    const MODULUS: &'static str =
738        "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001";
739    const NUM_BITS: u32 = MODULUS_BITS;
740    const CAPACITY: u32 = Self::NUM_BITS - 1;
741    const TWO_INV: Self = TWO_INV;
742    const MULTIPLICATIVE_GENERATOR: Self = GENERATOR;
743    const S: u32 = S;
744    const ROOT_OF_UNITY: Self = ROOT_OF_UNITY;
745    const ROOT_OF_UNITY_INV: Self = ROOT_OF_UNITY_INV;
746    const DELTA: Self = DELTA;
747}
748
749impl WithSmallOrderMulGroup<3> for Scalar {
750    const ZETA: Self = ZETA;
751}
752
753#[cfg(all(feature = "bits", not(target_pointer_width = "64")))]
754type ReprBits = [u32; 8];
755
756#[cfg(all(feature = "bits", target_pointer_width = "64"))]
757type ReprBits = [u64; 4];
758
759#[cfg(feature = "bits")]
760impl PrimeFieldBits for Scalar {
761    type ReprBits = ReprBits;
762
763    fn to_le_bits(&self) -> FieldBits<Self::ReprBits> {
764        let bytes = self.to_bytes();
765
766        #[cfg(not(target_pointer_width = "64"))]
767        let limbs = [
768            u32::from_le_bytes(bytes[0..4].try_into().unwrap()),
769            u32::from_le_bytes(bytes[4..8].try_into().unwrap()),
770            u32::from_le_bytes(bytes[8..12].try_into().unwrap()),
771            u32::from_le_bytes(bytes[12..16].try_into().unwrap()),
772            u32::from_le_bytes(bytes[16..20].try_into().unwrap()),
773            u32::from_le_bytes(bytes[20..24].try_into().unwrap()),
774            u32::from_le_bytes(bytes[24..28].try_into().unwrap()),
775            u32::from_le_bytes(bytes[28..32].try_into().unwrap()),
776        ];
777
778        #[cfg(target_pointer_width = "64")]
779        let limbs = [
780            u64::from_le_bytes(bytes[0..8].try_into().unwrap()),
781            u64::from_le_bytes(bytes[8..16].try_into().unwrap()),
782            u64::from_le_bytes(bytes[16..24].try_into().unwrap()),
783            u64::from_le_bytes(bytes[24..32].try_into().unwrap()),
784        ];
785
786        FieldBits::new(limbs)
787    }
788
789    fn char_le_bits() -> FieldBits<Self::ReprBits> {
790        #[cfg(not(target_pointer_width = "64"))]
791        {
792            FieldBits::new(MODULUS_LIMBS_32)
793        }
794
795        #[cfg(target_pointer_width = "64")]
796        FieldBits::new(MODULUS.0)
797    }
798}
799
800impl<T> core::iter::Sum<T> for Scalar
801where
802    T: core::borrow::Borrow<Scalar>,
803{
804    fn sum<I>(iter: I) -> Self
805    where
806        I: Iterator<Item = T>,
807    {
808        iter.fold(Self::zero(), |acc, item| acc + item.borrow())
809    }
810}
811
812impl<T> core::iter::Product<T> for Scalar
813where
814    T: core::borrow::Borrow<Scalar>,
815{
816    fn product<I>(iter: I) -> Self
817    where
818        I: Iterator<Item = T>,
819    {
820        iter.fold(Self::one(), |acc, item| acc * item.borrow())
821    }
822}
823
824impl From<[u64; 4]> for Scalar {
825    fn from(digits: [u64; 4]) -> Self {
826        Self::from_raw(digits)
827    }
828}
829
830impl ff::FromUniformBytes<64> for Scalar {
831    /// Converts a 512-bit little endian integer into
832    /// an `Fq` by reducing by the modulus.
833    fn from_uniform_bytes(bytes: &[u8; 64]) -> Self {
834        Self::from_u512([
835            u64::from_le_bytes(bytes[0..8].try_into().unwrap()),
836            u64::from_le_bytes(bytes[8..16].try_into().unwrap()),
837            u64::from_le_bytes(bytes[16..24].try_into().unwrap()),
838            u64::from_le_bytes(bytes[24..32].try_into().unwrap()),
839            u64::from_le_bytes(bytes[32..40].try_into().unwrap()),
840            u64::from_le_bytes(bytes[40..48].try_into().unwrap()),
841            u64::from_le_bytes(bytes[48..56].try_into().unwrap()),
842            u64::from_le_bytes(bytes[56..64].try_into().unwrap()),
843        ])
844    }
845}
846
847impl From<bool> for Scalar {
848    fn from(bit: bool) -> Scalar {
849        if bit {
850            Scalar::one()
851        } else {
852            Scalar::zero()
853        }
854    }
855}
856
857//test mod
858#[cfg(test)]
859mod tests {
860    use super::*;
861
862    use std::ops::AddAssign;
863
864    #[test]
865    fn test_constants() {
866        assert_eq!(
867            Scalar::MODULUS,
868            "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001",
869        );
870
871        assert_eq!(Scalar::from(2) * Scalar::TWO_INV, Scalar::ONE);
872
873        assert_eq!(
874            Scalar::ROOT_OF_UNITY * Scalar::ROOT_OF_UNITY_INV,
875            Scalar::ONE,
876        );
877
878        // ROOT_OF_UNITY^{2^s} mod m == 1
879        assert_eq!(
880            Scalar::ROOT_OF_UNITY.pow(&[1u64 << Scalar::S, 0, 0, 0]),
881            Scalar::ONE,
882        );
883
884        // DELTA^{t} mod m == 1
885        assert_eq!(
886            Scalar::DELTA.pow(&[
887                0xfffe_5bfe_ffff_ffff,
888                0x09a1_d805_53bd_a402,
889                0x299d_7d48_3339_d808,
890                0x0000_0000_73ed_a753,
891            ]),
892            Scalar::ONE,
893        );
894    }
895
896    #[test]
897    fn test_inv() {
898        // Compute -(q^{-1} mod 2^64) mod 2^64 by exponentiating
899        // by totient(2**64) - 1
900
901        let mut inv = 1u64;
902        for _ in 0..63 {
903            inv = inv.wrapping_mul(inv);
904            inv = inv.wrapping_mul(MODULUS.0[0]);
905        }
906        inv = inv.wrapping_neg();
907
908        assert_eq!(inv, INV);
909    }
910
911    #[cfg(feature = "std")]
912    #[test]
913    fn test_debug() {
914        assert_eq!(
915            format!("{:?}", Scalar::zero()),
916            "0x0000000000000000000000000000000000000000000000000000000000000000"
917        );
918        assert_eq!(
919            format!("{:?}", Scalar::one()),
920            "0x0000000000000000000000000000000000000000000000000000000000000001"
921        );
922        assert_eq!(
923            format!("{:?}", R2),
924            "0x1824b159acc5056f998c4fefecbc4ff55884b7fa0003480200000001fffffffe"
925        );
926    }
927
928    #[test]
929    fn test_equality() {
930        assert_eq!(Scalar::zero(), Scalar::zero());
931        assert_eq!(Scalar::one(), Scalar::one());
932        assert_eq!(R2, R2);
933
934        assert!(Scalar::zero() != Scalar::one());
935        assert!(Scalar::one() != R2);
936    }
937
938    #[test]
939    fn test_to_bytes() {
940        assert_eq!(
941            Scalar::zero().to_bytes(),
942            [
943                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
944                0, 0, 0, 0
945            ]
946        );
947
948        assert_eq!(
949            Scalar::one().to_bytes(),
950            [
951                1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
952                0, 0, 0, 0
953            ]
954        );
955
956        assert_eq!(
957            R2.to_bytes(),
958            [
959                254, 255, 255, 255, 1, 0, 0, 0, 2, 72, 3, 0, 250, 183, 132, 88, 245, 79, 188, 236,
960                239, 79, 140, 153, 111, 5, 197, 172, 89, 177, 36, 24
961            ]
962        );
963
964        assert_eq!(
965            (-&Scalar::one()).to_bytes(),
966            [
967                0, 0, 0, 0, 255, 255, 255, 255, 254, 91, 254, 255, 2, 164, 189, 83, 5, 216, 161, 9,
968                8, 216, 57, 51, 72, 125, 157, 41, 83, 167, 237, 115
969            ]
970        );
971    }
972
973    #[test]
974    fn test_from_bytes() {
975        assert_eq!(
976            Scalar::from_bytes(&[
977                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
978                0, 0, 0, 0
979            ])
980            .unwrap(),
981            Scalar::zero()
982        );
983
984        assert_eq!(
985            Scalar::from_bytes(&[
986                1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
987                0, 0, 0, 0
988            ])
989            .unwrap(),
990            Scalar::one()
991        );
992
993        assert_eq!(
994            Scalar::from_bytes(&[
995                254, 255, 255, 255, 1, 0, 0, 0, 2, 72, 3, 0, 250, 183, 132, 88, 245, 79, 188, 236,
996                239, 79, 140, 153, 111, 5, 197, 172, 89, 177, 36, 24
997            ])
998            .unwrap(),
999            R2
1000        );
1001
1002        // -1 should work
1003        assert!(bool::from(
1004            Scalar::from_bytes(&[
1005                0, 0, 0, 0, 255, 255, 255, 255, 254, 91, 254, 255, 2, 164, 189, 83, 5, 216, 161, 9,
1006                8, 216, 57, 51, 72, 125, 157, 41, 83, 167, 237, 115
1007            ])
1008            .is_some()
1009        ));
1010
1011        // modulus is invalid
1012        assert!(bool::from(
1013            Scalar::from_bytes(&[
1014                1, 0, 0, 0, 255, 255, 255, 255, 254, 91, 254, 255, 2, 164, 189, 83, 5, 216, 161, 9,
1015                8, 216, 57, 51, 72, 125, 157, 41, 83, 167, 237, 115
1016            ])
1017            .is_none()
1018        ));
1019
1020        // Anything larger than the modulus is invalid
1021        assert!(bool::from(
1022            Scalar::from_bytes(&[
1023                2, 0, 0, 0, 255, 255, 255, 255, 254, 91, 254, 255, 2, 164, 189, 83, 5, 216, 161, 9,
1024                8, 216, 57, 51, 72, 125, 157, 41, 83, 167, 237, 115
1025            ])
1026            .is_none()
1027        ));
1028        assert!(bool::from(
1029            Scalar::from_bytes(&[
1030                1, 0, 0, 0, 255, 255, 255, 255, 254, 91, 254, 255, 2, 164, 189, 83, 5, 216, 161, 9,
1031                8, 216, 58, 51, 72, 125, 157, 41, 83, 167, 237, 115
1032            ])
1033            .is_none()
1034        ));
1035        assert!(bool::from(
1036            Scalar::from_bytes(&[
1037                1, 0, 0, 0, 255, 255, 255, 255, 254, 91, 254, 255, 2, 164, 189, 83, 5, 216, 161, 9,
1038                8, 216, 57, 51, 72, 125, 157, 41, 83, 167, 237, 116
1039            ])
1040            .is_none()
1041        ));
1042    }
1043
1044    #[test]
1045    fn test_from_u512_zero() {
1046        assert_eq!(
1047            Scalar::zero(),
1048            Scalar::from_u512([
1049                MODULUS.0[0],
1050                MODULUS.0[1],
1051                MODULUS.0[2],
1052                MODULUS.0[3],
1053                0,
1054                0,
1055                0,
1056                0
1057            ])
1058        );
1059    }
1060
1061    #[test]
1062    fn test_from_u512_r() {
1063        assert_eq!(R, Scalar::from_u512([1, 0, 0, 0, 0, 0, 0, 0]));
1064    }
1065
1066    #[test]
1067    fn test_from_u512_r2() {
1068        assert_eq!(R2, Scalar::from_u512([0, 0, 0, 0, 1, 0, 0, 0]));
1069    }
1070
1071    #[test]
1072    fn test_from_u512_max() {
1073        let max_u64 = 0xffff_ffff_ffff_ffff;
1074        assert_eq!(
1075            R3 - R,
1076            Scalar::from_u512([
1077                max_u64, max_u64, max_u64, max_u64, max_u64, max_u64, max_u64, max_u64
1078            ])
1079        );
1080    }
1081
1082    #[test]
1083    fn test_from_bytes_wide_r2() {
1084        assert_eq!(
1085            R2,
1086            Scalar::from_bytes_wide(&[
1087                254, 255, 255, 255, 1, 0, 0, 0, 2, 72, 3, 0, 250, 183, 132, 88, 245, 79, 188, 236,
1088                239, 79, 140, 153, 111, 5, 197, 172, 89, 177, 36, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1089                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1090            ])
1091        );
1092    }
1093
1094    #[test]
1095    fn test_from_bytes_wide_negative_one() {
1096        assert_eq!(
1097            -&Scalar::one(),
1098            Scalar::from_bytes_wide(&[
1099                0, 0, 0, 0, 255, 255, 255, 255, 254, 91, 254, 255, 2, 164, 189, 83, 5, 216, 161, 9,
1100                8, 216, 57, 51, 72, 125, 157, 41, 83, 167, 237, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1101                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1102            ])
1103        );
1104    }
1105
1106    #[test]
1107    fn test_from_bytes_wide_maximum() {
1108        assert_eq!(
1109            Scalar([
1110                0xc62c_1805_439b_73b1,
1111                0xc2b9_551e_8ced_218e,
1112                0xda44_ec81_daf9_a422,
1113                0x5605_aa60_1c16_2e79,
1114            ]),
1115            Scalar::from_bytes_wide(&[0xff; 64])
1116        );
1117    }
1118
1119    #[test]
1120    fn test_zero() {
1121        assert_eq!(Scalar::zero(), -&Scalar::zero());
1122        assert_eq!(Scalar::zero(), Scalar::zero() + Scalar::zero());
1123        assert_eq!(Scalar::zero(), Scalar::zero() - Scalar::zero());
1124        assert_eq!(Scalar::zero(), Scalar::zero() * Scalar::zero());
1125    }
1126
1127    #[cfg(test)]
1128    const LARGEST: Scalar = Scalar([
1129        0xffff_ffff_0000_0000,
1130        0x53bd_a402_fffe_5bfe,
1131        0x3339_d808_09a1_d805,
1132        0x73ed_a753_299d_7d48,
1133    ]);
1134
1135    #[test]
1136    fn test_addition() {
1137        let mut tmp = LARGEST;
1138        tmp += &LARGEST;
1139
1140        assert_eq!(
1141            tmp,
1142            Scalar([
1143                0xffff_fffe_ffff_ffff,
1144                0x53bd_a402_fffe_5bfe,
1145                0x3339_d808_09a1_d805,
1146                0x73ed_a753_299d_7d48,
1147            ])
1148        );
1149
1150        let mut tmp = LARGEST;
1151        tmp += &Scalar([1, 0, 0, 0]);
1152
1153        assert_eq!(tmp, Scalar::zero());
1154    }
1155
1156    #[test]
1157    fn test_negation() {
1158        let tmp = -&LARGEST;
1159
1160        assert_eq!(tmp, Scalar([1, 0, 0, 0]));
1161
1162        let tmp = -&Scalar::zero();
1163        assert_eq!(tmp, Scalar::zero());
1164        let tmp = -&Scalar([1, 0, 0, 0]);
1165        assert_eq!(tmp, LARGEST);
1166    }
1167
1168    #[test]
1169    fn test_subtraction() {
1170        let mut tmp = LARGEST;
1171        tmp -= &LARGEST;
1172
1173        assert_eq!(tmp, Scalar::zero());
1174
1175        let mut tmp = Scalar::zero();
1176        tmp -= &LARGEST;
1177
1178        let mut tmp2 = MODULUS;
1179        tmp2 -= &LARGEST;
1180
1181        assert_eq!(tmp, tmp2);
1182    }
1183
1184    #[test]
1185    fn test_multiplication() {
1186        let mut cur = LARGEST;
1187
1188        for _ in 0..100 {
1189            let mut tmp = cur;
1190            tmp *= &cur;
1191
1192            let mut tmp2 = Scalar::zero();
1193            for b in cur
1194                .to_bytes()
1195                .iter()
1196                .rev()
1197                .flat_map(|byte| (0..8).rev().map(move |i| ((byte >> i) & 1u8) == 1u8))
1198            {
1199                let tmp3 = tmp2;
1200                tmp2.add_assign(&tmp3);
1201
1202                if b {
1203                    tmp2.add_assign(&cur);
1204                }
1205            }
1206
1207            assert_eq!(tmp, tmp2);
1208
1209            cur.add_assign(&LARGEST);
1210        }
1211    }
1212
1213    #[test]
1214    fn test_squaring() {
1215        let mut cur = LARGEST;
1216
1217        for _ in 0..100 {
1218            let mut tmp = cur;
1219            tmp = tmp.square();
1220
1221            let mut tmp2 = Scalar::zero();
1222            for b in cur
1223                .to_bytes()
1224                .iter()
1225                .rev()
1226                .flat_map(|byte| (0..8).rev().map(move |i| ((byte >> i) & 1u8) == 1u8))
1227            {
1228                let tmp3 = tmp2;
1229                tmp2.add_assign(&tmp3);
1230
1231                if b {
1232                    tmp2.add_assign(&cur);
1233                }
1234            }
1235
1236            assert_eq!(tmp, tmp2);
1237
1238            cur.add_assign(&LARGEST);
1239        }
1240    }
1241
1242    #[test]
1243    fn test_inversion() {
1244        assert!(bool::from(Scalar::zero().invert().is_none()));
1245        assert_eq!(Scalar::one().invert().unwrap(), Scalar::one());
1246        assert_eq!((-&Scalar::one()).invert().unwrap(), -&Scalar::one());
1247
1248        let mut tmp = R2;
1249
1250        for _ in 0..100 {
1251            let mut tmp2 = tmp.invert().unwrap();
1252            tmp2.mul_assign(&tmp);
1253
1254            assert_eq!(tmp2, Scalar::one());
1255
1256            tmp.add_assign(&R2);
1257        }
1258    }
1259
1260    #[test]
1261    fn test_invert_is_pow() {
1262        let q_minus_2 = [
1263            0xffff_fffe_ffff_ffff,
1264            0x53bd_a402_fffe_5bfe,
1265            0x3339_d808_09a1_d805,
1266            0x73ed_a753_299d_7d48,
1267        ];
1268
1269        let mut r1 = R;
1270        let mut r2 = R;
1271        let mut r3 = R;
1272
1273        for _ in 0..100 {
1274            r1 = r1.invert().unwrap();
1275            r2 = r2.pow_vartime(&q_minus_2);
1276            r3 = r3.pow(&q_minus_2);
1277
1278            assert_eq!(r1, r2);
1279            assert_eq!(r2, r3);
1280            // Add R so we check something different next time around
1281            r1.add_assign(&R);
1282            r2 = r1;
1283            r3 = r1;
1284        }
1285    }
1286
1287    #[test]
1288    fn test_sqrt() {
1289        {
1290            assert_eq!(Scalar::zero().sqrt().unwrap(), Scalar::zero());
1291        }
1292
1293        let mut square = Scalar([
1294            0x46cd_85a5_f273_077e,
1295            0x1d30_c47d_d68f_c735,
1296            0x77f6_56f6_0bec_a0eb,
1297            0x494a_a01b_df32_468d,
1298        ]);
1299
1300        let mut none_count = 0;
1301
1302        for _ in 0..100 {
1303            let square_root = square.sqrt();
1304            if bool::from(square_root.is_none()) {
1305                none_count += 1;
1306            } else {
1307                assert_eq!(square_root.unwrap() * square_root.unwrap(), square);
1308            }
1309            square -= Scalar::one();
1310        }
1311
1312        assert_eq!(49, none_count);
1313    }
1314
1315    #[test]
1316    fn test_from_raw() {
1317        assert_eq!(
1318            Scalar::from_raw([
1319                0x0001_ffff_fffd,
1320                0x5884_b7fa_0003_4802,
1321                0x998c_4fef_ecbc_4ff5,
1322                0x1824_b159_acc5_056f,
1323            ]),
1324            Scalar::from_raw([0xffff_ffff_ffff_ffff; 4])
1325        );
1326
1327        assert_eq!(Scalar::from_raw(MODULUS.0), Scalar::zero());
1328
1329        assert_eq!(Scalar::from_raw([1, 0, 0, 0]), R);
1330    }
1331
1332    #[test]
1333    fn test_double() {
1334        let a = Scalar::from_raw([
1335            0x1fff_3231_233f_fffd,
1336            0x4884_b7fa_0003_4802,
1337            0x998c_4fef_ecbc_4ff3,
1338            0x1824_b159_acc5_0562,
1339        ]);
1340
1341        assert_eq!(a.double(), a + a);
1342    }
1343
1344    #[cfg(feature = "zeroize")]
1345    #[test]
1346    fn test_zeroize() {
1347        use zeroize::Zeroize;
1348
1349        let mut a = Scalar::from_raw([
1350            0x1fff_3231_233f_fffd,
1351            0x4884_b7fa_0003_4802,
1352            0x998c_4fef_ecbc_4ff3,
1353            0x1824_b159_acc5_0562,
1354        ]);
1355        a.zeroize();
1356        assert!(bool::from(a.is_zero()));
1357    }
1358}