Skip to main content

starkom_ff/
bls12_381.rs

1use crate::fields::{Field, Field256, PrimeField, PrimeField256};
2use crate::helpers::{adc, add, mac, mul, sbb, sub};
3use anyhow::{self, Context};
4use getrandom;
5use primitive_types::{H512, U256, U512};
6use std::cmp::Ordering;
7use std::iter::{Product, Sum};
8use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
9use std::str::FromStr;
10use std::sync::LazyLock;
11use subtle::{
12    Choice, ConditionallySelectable, ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess,
13    CtOption,
14};
15
16/// The prime order of the BLS12-381 scalar field stored as four 64-bit limbs in little endian order.
17pub const MODULUS: [u64; 4] = [
18    0xffffffff00000001u64,
19    0x53bda402fffe5bfeu64,
20    0x3339d80809a1d805u64,
21    0x73eda753299d7d48u64,
22];
23
24/// Upper-case characters used in textual representations.
25static CHARACTERS_UPPER_CASE: &'static [u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
26
27/// Lower-case characters used in textual representations.
28static CHARACTERS_LOWER_CASE: &'static [u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
29
30/// The BLS12-381 scalar field.
31///
32/// The prime order of the field is:
33///
34///   0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
35///
36/// This implementation uses Montgomery form.
37#[derive(Default, Copy, Clone, PartialEq, Eq)]
38pub struct Scalar(u64, u64, u64, u64);
39
40impl Scalar {
41    /// The raw (non-Montgomery) little-endian representation of `MAX`.
42    const MAX_RAW: Self = Self(
43        0xffffffff00000000u64,
44        0x53bda402fffe5bfeu64,
45        0x3339d80809a1d805u64,
46        0x73eda753299d7d48u64,
47    );
48
49    /// R in raw form, ie. the four limbs of `2^256 mod p` in little-endian order.
50    const R: Self = Self(
51        0x00000001fffffffeu64,
52        0x5884b7fa00034802u64,
53        0x998c4fefecbc4ff5u64,
54        0x1824b159acc5056fu64,
55    );
56
57    /// R in Montgomery form, ie. R^2 mod p.
58    const R2: Self = Self(
59        0xc999e990f3f29c6du64,
60        0x2b6cedcb87925c23u64,
61        0x05d314967254398fu64,
62        0x0748d9d99f59ff11u64,
63    );
64
65    const P: [u64; 4] = MODULUS;
66
67    const P_INV: u64 = 0xfffffffeffffffff;
68
69    /// Subtracts p. Assumes no underflow, ie. `self` must be greater than or equal to p.
70    ///
71    /// Used in several algorithms to bring a value back into the [0, p) range.
72    const fn subp(&self) -> Self {
73        let (s0, b0) = sub(self.0, Self::P[0]);
74        let (s1, b1) = sbb(self.1, Self::P[1], b0);
75        let (s2, b2) = sbb(self.2, Self::P[2], b1);
76        let (s3, _) = sbb(self.3, Self::P[3], b2);
77        Self(s0, s1, s2, s3)
78    }
79
80    /// Compares raw scalars, ignoring Montgomery form.
81    const fn cmp_raw(&self, other: &Self) -> Ordering {
82        if self.3 < other.3 {
83            Ordering::Less
84        } else if self.3 > other.3 {
85            Ordering::Greater
86        } else if self.2 < other.2 {
87            Ordering::Less
88        } else if self.2 > other.2 {
89            Ordering::Greater
90        } else if self.1 < other.1 {
91            Ordering::Less
92        } else if self.1 > other.1 {
93            Ordering::Greater
94        } else if self.0 < other.0 {
95            Ordering::Less
96        } else if self.0 > other.0 {
97            Ordering::Greater
98        } else {
99            Ordering::Equal
100        }
101    }
102
103    const fn modp(self) -> Self {
104        let subp = self.subp();
105        match self.cmp_raw(&Self::MAX_RAW) {
106            Ordering::Greater => subp,
107            _ => self,
108        }
109    }
110
111    /// Performs Montgomery multiplication using CIOS over 64-bit limbs.
112    const fn mont_mul(lhs: &Self, rhs: &Self) -> Self {
113        let mut t0: u64;
114        let mut t1: u64;
115        let mut t2: u64;
116        let mut t3: u64;
117        let mut t4: u64;
118        let mut carry: u64;
119        let mut m: u64;
120
121        // row 0
122        (t0, carry) = mul(lhs.0, rhs.0, 0);
123        (t1, carry) = mul(lhs.1, rhs.0, carry);
124        (t2, carry) = mul(lhs.2, rhs.0, carry);
125        (t3, t4) = mul(lhs.3, rhs.0, carry);
126
127        // redc 0
128        m = t0.wrapping_mul(Self::P_INV);
129        (_, carry) = mac(t0, m, Self::P[0], 0);
130        (t0, carry) = mac(t1, m, Self::P[1], carry);
131        (t1, carry) = mac(t2, m, Self::P[2], carry);
132        (t2, carry) = mac(t3, m, Self::P[3], carry);
133        t3 = t4 + carry;
134
135        // row 1
136        (t0, carry) = mac(t0, lhs.0, rhs.1, 0);
137        (t1, carry) = mac(t1, lhs.1, rhs.1, carry);
138        (t2, carry) = mac(t2, lhs.2, rhs.1, carry);
139        (t3, t4) = mac(t3, lhs.3, rhs.1, carry);
140
141        // redc 1
142        m = t0.wrapping_mul(Self::P_INV);
143        (_, carry) = mac(t0, m, Self::P[0], 0);
144        (t0, carry) = mac(t1, m, Self::P[1], carry);
145        (t1, carry) = mac(t2, m, Self::P[2], carry);
146        (t2, carry) = mac(t3, m, Self::P[3], carry);
147        t3 = t4 + carry;
148
149        // row 2
150        (t0, carry) = mac(t0, lhs.0, rhs.2, 0);
151        (t1, carry) = mac(t1, lhs.1, rhs.2, carry);
152        (t2, carry) = mac(t2, lhs.2, rhs.2, carry);
153        (t3, t4) = mac(t3, lhs.3, rhs.2, carry);
154
155        // redc 2
156        m = t0.wrapping_mul(Self::P_INV);
157        (_, carry) = mac(t0, m, Self::P[0], 0);
158        (t0, carry) = mac(t1, m, Self::P[1], carry);
159        (t1, carry) = mac(t2, m, Self::P[2], carry);
160        (t2, carry) = mac(t3, m, Self::P[3], carry);
161        t3 = t4 + carry;
162
163        // row 3
164        (t0, carry) = mac(t0, lhs.0, rhs.3, 0);
165        (t1, carry) = mac(t1, lhs.1, rhs.3, carry);
166        (t2, carry) = mac(t2, lhs.2, rhs.3, carry);
167        (t3, t4) = mac(t3, lhs.3, rhs.3, carry);
168
169        // redc 3
170        m = t0.wrapping_mul(Self::P_INV);
171        (_, carry) = mac(t0, m, Self::P[0], 0);
172        (t0, carry) = mac(t1, m, Self::P[1], carry);
173        (t1, carry) = mac(t2, m, Self::P[2], carry);
174        (t2, carry) = mac(t3, m, Self::P[3], carry);
175        t3 = t4 + carry;
176
177        Self(t0, t1, t2, t3).modp()
178    }
179
180    /// Performs a Montgomery multiplication by 1, which results in converting from Montgomery form
181    /// to raw form.
182    ///
183    /// This is exactly the same as `mont_mul(Scalar(1, 0, 0, 0))` but slightly faster because it
184    /// exploits the fact that we're multiplying by (1, 0, 0, 0), so it skips all "row" phases and
185    /// only performs the "redc" phases.
186    const fn to_raw(&self) -> Self {
187        let mut t0 = self.0;
188        let mut t1 = self.1;
189        let mut t2 = self.2;
190        let mut t3 = self.3;
191        let mut carry: u64;
192        let mut m: u64;
193
194        // redc 0
195        m = t0.wrapping_mul(Self::P_INV);
196        (_, carry) = mac(t0, m, Self::P[0], 0);
197        (t0, carry) = mac(t1, m, Self::P[1], carry);
198        (t1, carry) = mac(t2, m, Self::P[2], carry);
199        (t2, carry) = mac(t3, m, Self::P[3], carry);
200        t3 = carry;
201
202        // redc 1
203        m = t0.wrapping_mul(Self::P_INV);
204        (_, carry) = mac(t0, m, Self::P[0], 0);
205        (t0, carry) = mac(t1, m, Self::P[1], carry);
206        (t1, carry) = mac(t2, m, Self::P[2], carry);
207        (t2, carry) = mac(t3, m, Self::P[3], carry);
208        t3 = carry;
209
210        // redc 2
211        m = t0.wrapping_mul(Self::P_INV);
212        (_, carry) = mac(t0, m, Self::P[0], 0);
213        (t0, carry) = mac(t1, m, Self::P[1], carry);
214        (t1, carry) = mac(t2, m, Self::P[2], carry);
215        (t2, carry) = mac(t3, m, Self::P[3], carry);
216        t3 = carry;
217
218        // redc 3
219        m = t0.wrapping_mul(Self::P_INV);
220        (_, carry) = mac(t0, m, Self::P[0], 0);
221        (t0, carry) = mac(t1, m, Self::P[1], carry);
222        (t1, carry) = mac(t2, m, Self::P[2], carry);
223        (t2, carry) = mac(t3, m, Self::P[3], carry);
224        t3 = carry;
225
226        Self(t0, t1, t2, t3).modp()
227    }
228
229    /// Constructs scalars at compile time.
230    pub const fn from_const(value: u64) -> Scalar {
231        let raw = Self(value, 0, 0, 0);
232        Self::mont_mul(&raw, &Self::R2)
233    }
234
235    fn to_string_impl(&self, radix: usize, pad_to: usize, upper_case: bool) -> String {
236        let characters = if upper_case {
237            CHARACTERS_UPPER_CASE
238        } else {
239            CHARACTERS_LOWER_CASE
240        };
241        let mut value = self.to_u256();
242        let mut s = String::default();
243        let radix = U256::from(radix);
244        while !value.is_zero() {
245            let digit = (value % radix).as_usize();
246            s.push(characters[digit] as char);
247            value /= radix;
248        }
249        if s.is_empty() {
250            s.push('0');
251        }
252        while s.len() < pad_to {
253            s.push('0');
254        }
255        s.chars().rev().collect()
256    }
257
258    fn to_string_impl_log2(&self, radix_log2: u32, pad_to: usize, upper_case: bool) -> String {
259        assert!(radix_log2 < 6);
260        let characters = if upper_case {
261            CHARACTERS_UPPER_CASE
262        } else {
263            CHARACTERS_LOWER_CASE
264        };
265        let mut value = self.to_u256();
266        let mut s = String::default();
267        let mask = U256::from((1 << radix_log2) - 1);
268        while !value.is_zero() {
269            let digit = (value & mask).as_usize();
270            s.push(characters[digit] as char);
271            value >>= radix_log2;
272        }
273        if s.is_empty() {
274            s.push('0');
275        }
276        while s.len() < pad_to {
277            s.push('0');
278        }
279        s.chars().rev().collect()
280    }
281}
282
283impl std::fmt::Debug for Scalar {
284    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285        write!(f, "Scalar({:#066x})", self)
286    }
287}
288
289impl std::fmt::Display for Scalar {
290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291        write!(f, "{:#066x}", self)
292    }
293}
294
295impl std::fmt::Binary for Scalar {
296    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297        let prefix = if f.alternate() { "0b" } else { "" };
298        f.pad_integral(true, prefix, &self.to_str_radix(2, 0, false))
299    }
300}
301
302impl std::fmt::Octal for Scalar {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        let prefix = if f.alternate() { "0o" } else { "" };
305        f.pad_integral(true, prefix, &self.to_str_radix(8, 0, false))
306    }
307}
308
309impl std::fmt::LowerHex for Scalar {
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        let prefix = if f.alternate() { "0x" } else { "" };
312        f.pad_integral(true, prefix, &self.to_str_radix(16, 0, false))
313    }
314}
315
316impl std::fmt::UpperHex for Scalar {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        let prefix = if f.alternate() { "0x" } else { "" };
319        f.pad_integral(true, prefix, &self.to_str_radix(16, 0, true))
320    }
321}
322
323impl Ord for Scalar {
324    fn cmp(&self, other: &Self) -> Ordering {
325        let lhs = self.to_raw();
326        let rhs = other.to_raw();
327        lhs.cmp_raw(&rhs)
328    }
329}
330
331impl PartialOrd for Scalar {
332    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
333        Some(self.cmp(other))
334    }
335}
336
337impl ConstantTimeEq for Scalar {
338    fn ct_eq(&self, other: &Self) -> Choice {
339        self.0.ct_eq(&other.0)
340            & self.1.ct_eq(&other.1)
341            & self.2.ct_eq(&other.2)
342            & self.3.ct_eq(&other.3)
343    }
344}
345
346impl ConstantTimeGreater for Scalar {
347    fn ct_gt(&self, other: &Self) -> Choice {
348        let lhs = self.to_raw();
349        let rhs = other.to_raw();
350        let gt3 = lhs.3.ct_gt(&rhs.3);
351        let gt2 = lhs.2.ct_gt(&rhs.2);
352        let gt1 = lhs.1.ct_gt(&rhs.1);
353        let gt0 = lhs.0.ct_gt(&rhs.0);
354        let eq3 = lhs.3.ct_eq(&rhs.3);
355        let eq2 = lhs.2.ct_eq(&rhs.2);
356        let eq1 = lhs.1.ct_eq(&rhs.1);
357        gt3 | eq3 & gt2 | eq3 & eq2 & gt1 | eq3 & eq2 & eq1 & gt0
358    }
359}
360
361impl ConstantTimeLess for Scalar {}
362
363impl ConditionallySelectable for Scalar {
364    fn conditional_select(a: &Self, b: &Self, choice: subtle::Choice) -> Self {
365        Scalar(
366            u64::conditional_select(&a.0, &b.0, choice),
367            u64::conditional_select(&a.1, &b.1, choice),
368            u64::conditional_select(&a.2, &b.2, choice),
369            u64::conditional_select(&a.3, &b.3, choice),
370        )
371    }
372}
373
374impl Add<&Scalar> for Scalar {
375    type Output = Self;
376
377    fn add(self, rhs: &Self) -> Self::Output {
378        let (r0, c0) = add(self.0, rhs.0);
379        let (r1, c1) = adc(self.1, rhs.1, c0);
380        let (r2, c2) = adc(self.2, rhs.2, c1);
381        let (r3, _) = adc(self.3, rhs.3, c2);
382        Self(r0, r1, r2, r3).modp()
383    }
384}
385
386impl Add for Scalar {
387    type Output = Self;
388
389    fn add(self, rhs: Self) -> Self::Output {
390        self.add(&rhs)
391    }
392}
393
394impl AddAssign<&Scalar> for Scalar {
395    fn add_assign(&mut self, rhs: &Self) {
396        *self = self.add(rhs);
397    }
398}
399
400impl AddAssign for Scalar {
401    fn add_assign(&mut self, rhs: Self) {
402        *self = self.add(&rhs);
403    }
404}
405
406impl Neg for Scalar {
407    type Output = Self;
408
409    fn neg(self) -> Self::Output {
410        if self.is_zero().into() {
411            return self;
412        }
413        let (r0, b0) = sub(Self::P[0], self.0);
414        let (r1, b1) = sbb(Self::P[1], self.1, b0);
415        let (r2, b2) = sbb(Self::P[2], self.2, b1);
416        let (r3, _) = sbb(Self::P[3], self.3, b2);
417        Self(r0, r1, r2, r3)
418    }
419}
420
421impl Sub<&Scalar> for Scalar {
422    type Output = Self;
423
424    fn sub(self, rhs: &Self) -> Self::Output {
425        let (r0, b0) = sub(self.0, rhs.0);
426        let (r1, b1) = sbb(self.1, rhs.1, b0);
427        let (r2, b2) = sbb(self.2, rhs.2, b1);
428        let (r3, b3) = sbb(self.3, rhs.3, b2);
429        if b3 == 0 {
430            return Self(r0, r1, r2, r3);
431        }
432        let (s0, c0) = add(r0, Self::P[0]);
433        let (s1, c1) = adc(r1, Self::P[1], c0);
434        let (s2, c2) = adc(r2, Self::P[2], c1);
435        let (s3, _) = adc(r3, Self::P[3], c2);
436        Self(s0, s1, s2, s3)
437    }
438}
439
440impl Sub for Scalar {
441    type Output = Self;
442
443    fn sub(self, rhs: Self) -> Self::Output {
444        self.sub(&rhs)
445    }
446}
447
448impl SubAssign<&Scalar> for Scalar {
449    fn sub_assign(&mut self, rhs: &Self) {
450        *self = self.sub(rhs);
451    }
452}
453
454impl SubAssign for Scalar {
455    fn sub_assign(&mut self, rhs: Self) {
456        *self = self.sub(&rhs);
457    }
458}
459
460impl Mul<&Scalar> for Scalar {
461    type Output = Self;
462
463    fn mul(self, rhs: &Self) -> Self::Output {
464        Self::mont_mul(&self, rhs)
465    }
466}
467
468impl Mul for Scalar {
469    type Output = Self;
470
471    fn mul(self, rhs: Self) -> Self::Output {
472        Self::mont_mul(&self, &rhs)
473    }
474}
475
476impl MulAssign<&Scalar> for Scalar {
477    fn mul_assign(&mut self, rhs: &Self) {
478        *self = Self::mont_mul(self, rhs);
479    }
480}
481
482impl MulAssign for Scalar {
483    fn mul_assign(&mut self, rhs: Self) {
484        *self = Self::mont_mul(self, &rhs);
485    }
486}
487
488impl Div<&Scalar> for Scalar {
489    type Output = Self;
490
491    fn div(self, rhs: &Self) -> Self::Output {
492        assert!(!bool::from(rhs.is_zero()), "division by zero");
493        Self::mont_mul(&self, &rhs.invert_unwrap())
494    }
495}
496
497impl Div for Scalar {
498    type Output = Self;
499
500    fn div(self, rhs: Self) -> Self::Output {
501        assert!(!bool::from(rhs.is_zero()), "division by zero");
502        Self::mont_mul(&self, &rhs.invert_unwrap())
503    }
504}
505
506impl DivAssign<&Scalar> for Scalar {
507    fn div_assign(&mut self, rhs: &Self) {
508        assert!(!bool::from(rhs.is_zero()), "division by zero");
509        *self = Self::mont_mul(self, &rhs.invert_unwrap());
510    }
511}
512
513impl DivAssign for Scalar {
514    fn div_assign(&mut self, rhs: Self) {
515        assert!(!bool::from(rhs.is_zero()), "division by zero");
516        *self = Self::mont_mul(self, &rhs.invert_unwrap());
517    }
518}
519
520impl Sum<Scalar> for Scalar {
521    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
522        iter.fold(Self::ZERO, |a, b| a + b)
523    }
524}
525
526impl<'a> Sum<&'a Scalar> for Scalar {
527    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
528        iter.fold(Self::ZERO, |a, b| a + b)
529    }
530}
531
532impl Product<Scalar> for Scalar {
533    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
534        iter.fold(Self::ONE, |a, b| a * b)
535    }
536}
537
538impl<'a> Product<&'a Scalar> for Scalar {
539    fn product<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
540        iter.fold(Self::ONE, |a, b| a * b)
541    }
542}
543
544impl FromStr for Scalar {
545    type Err = std::fmt::Error;
546
547    fn from_str(s: &str) -> Result<Self, Self::Err> {
548        if s.starts_with("0x") || s.starts_with("0X") {
549            Self::from_str_radix(&s[2..], 16)
550        } else if s.starts_with("0b") || s.starts_with("0B") {
551            Self::from_str_radix(&s[2..], 2)
552        } else if s.starts_with("0o") || s.starts_with("0O") {
553            Self::from_str_radix(&s[2..], 8)
554        } else if s.starts_with("0") {
555            Self::from_str_radix(s, 8)
556        } else {
557            Self::from_str_radix(s, 10)
558        }
559    }
560}
561
562impl From<u8> for Scalar {
563    fn from(value: u8) -> Self {
564        Self::mont_mul(&Self(value as u64, 0, 0, 0), &Self::R2)
565    }
566}
567
568impl From<u16> for Scalar {
569    fn from(value: u16) -> Self {
570        Self::mont_mul(&Self(value as u64, 0, 0, 0), &Self::R2)
571    }
572}
573
574impl From<u32> for Scalar {
575    fn from(value: u32) -> Self {
576        Self::mont_mul(&Self(value as u64, 0, 0, 0), &Self::R2)
577    }
578}
579
580impl From<u64> for Scalar {
581    fn from(value: u64) -> Self {
582        Self::mont_mul(&Self(value, 0, 0, 0), &Self::R2)
583    }
584}
585
586impl From<u128> for Scalar {
587    fn from(value: u128) -> Self {
588        Self::mont_mul(&Self(value as u64, (value >> 64) as u64, 0, 0), &Self::R2)
589    }
590}
591
592impl TryFrom<U256> for Scalar {
593    type Error = anyhow::Error;
594
595    fn try_from(value: U256) -> Result<Self, Self::Error> {
596        Self::try_from_le_bytes(&value.to_little_endian())
597            .into_option()
598            .context("overflow")
599    }
600}
601
602impl TryFrom<usize> for Scalar {
603    type Error = anyhow::Error;
604
605    fn try_from(value: usize) -> Result<Self, Self::Error> {
606        Ok(Self::mont_mul(&Self(value as u64, 0, 0, 0), &Self::R2))
607    }
608}
609
610impl Field for Scalar {
611    const LEN: usize = 32;
612
613    const ZERO: Self = Self(0, 0, 0, 0);
614
615    const ONE: Self = Self::R;
616
617    const MAX: Self = Self(
618        0xfffffffd00000003u64,
619        0xfb38ec08fffb13fcu64,
620        0x99ad88181ce5880fu64,
621        0x5bc8f5f97cd877d8u64,
622    );
623
624    fn is_odd(&self) -> Choice {
625        (self.to_le_bytes()[0] & 1).into()
626    }
627
628    fn try_random<R: rand_core::TryCryptoRng>(rng: &mut R) -> Result<Self, R::Error> {
629        let mut bytes = [0u8; 64];
630        rng.try_fill_bytes(&mut bytes)?;
631        Ok(Self::from_u512_mod_n(U512::from_little_endian(&bytes)))
632    }
633
634    fn random<R: rand_core::CryptoRng>(rng: &mut R) -> Self {
635        let mut bytes = [0u8; 64];
636        rng.fill_bytes(&mut bytes);
637        Self::from_u512_mod_n(U512::from_little_endian(&bytes))
638    }
639
640    fn random_default() -> Self {
641        let mut bytes = [0u8; 64];
642        getrandom::fill(&mut bytes).unwrap();
643        Self::from_h512(H512::from_slice(&bytes))
644    }
645
646    fn square(&self) -> Self {
647        Self::mont_mul(self, self)
648    }
649
650    fn double(&self) -> Self {
651        let mut value = *self;
652        value.3 = (value.3 << 1) | (value.2 >> 63);
653        value.2 = (value.2 << 1) | (value.1 >> 63);
654        value.1 = (value.1 << 1) | (value.0 >> 63);
655        value.0 = value.0 << 1;
656        value.modp()
657    }
658
659    fn invert(&self) -> CtOption<Self> {
660        CtOption::new(self.pow(Scalar::MINUS_TWO), !self.is_zero())
661    }
662
663    fn invert_vartime(&self) -> Option<Self> {
664        if self.is_zero().into() {
665            None
666        } else {
667            Some(self.pow(Scalar::MINUS_TWO))
668        }
669    }
670
671    fn pow(mut self, exp: Self) -> Self {
672        static ONE: U256 = U256::one();
673        let mut exp = exp.to_u256();
674        let mut result = Self::ONE;
675        for _ in 0..256 {
676            let product = result * self;
677            result = Scalar::conditional_select(
678                &result,
679                &product,
680                ((!(exp & ONE).is_zero()) as u8).into(),
681            );
682            exp >>= 1;
683            self = self.square();
684        }
685        result
686    }
687
688    fn pow_vartime(mut self, exp: Self) -> Self {
689        static ONE: U256 = U256::one();
690        let mut exp = exp.to_u256();
691        let mut result = Self::ONE;
692        while !exp.is_zero() {
693            if !(exp & ONE).is_zero() {
694                result *= self;
695            }
696            exp >>= 1;
697            self = self.square();
698        }
699        result
700    }
701
702    fn div_int(&self, rhs: &Self) -> (Self, Self) {
703        assert!(!bool::from(rhs.is_zero()));
704        let lhs = self.to_u256();
705        let rhs = rhs.to_u256();
706        let (quotient, remainder) = lhs.div_mod(rhs);
707        (quotient.try_into().unwrap(), remainder.try_into().unwrap())
708    }
709
710    fn try_from_le_bytes(bytes: &[u8]) -> CtOption<Self> {
711        assert!(bytes.len() == 32);
712        let raw = Self(
713            u64::from_le_bytes(bytes[0..8].try_into().unwrap()),
714            u64::from_le_bytes(bytes[8..16].try_into().unwrap()),
715            u64::from_le_bytes(bytes[16..24].try_into().unwrap()),
716            u64::from_le_bytes(bytes[24..32].try_into().unwrap()),
717        );
718        CtOption::new(
719            Self::mont_mul(&raw, &Self::R2),
720            Choice::from((raw.cmp_raw(&Self::MAX_RAW) != Ordering::Greater) as u8),
721        )
722    }
723
724    fn try_from_be_bytes(bytes: &[u8]) -> CtOption<Self> {
725        assert!(bytes.len() == 32);
726        let raw = Self(
727            u64::from_be_bytes(bytes[24..32].try_into().unwrap()),
728            u64::from_be_bytes(bytes[16..24].try_into().unwrap()),
729            u64::from_be_bytes(bytes[8..16].try_into().unwrap()),
730            u64::from_be_bytes(bytes[0..8].try_into().unwrap()),
731        );
732        CtOption::new(
733            Self::mont_mul(&raw, &Self::R2),
734            Choice::from((raw.cmp_raw(&Self::MAX_RAW) != Ordering::Greater) as u8),
735        )
736    }
737
738    fn from_str_radix(s: &str, radix: usize) -> Result<Self, std::fmt::Error> {
739        assert!(radix >= 2 && radix <= 36);
740        if s.is_empty() {
741            return Err(std::fmt::Error);
742        }
743        let radix_u256: U256 = radix.into();
744        let mut value = U256::zero();
745        for byte in s.bytes() {
746            let digit = CHARACTERS_UPPER_CASE[..radix]
747                .iter()
748                .position(|&c| c == byte)
749                .or_else(|| {
750                    CHARACTERS_LOWER_CASE[..radix]
751                        .iter()
752                        .position(|&c| c == byte)
753                })
754                .ok_or(std::fmt::Error)?;
755            value = value
756                .checked_mul(radix_u256)
757                .ok_or(std::fmt::Error)?
758                .checked_add(digit.into())
759                .ok_or(std::fmt::Error)?;
760        }
761        Scalar::try_from(value).map_err(|_| std::fmt::Error)
762    }
763
764    fn to_str_radix(&self, radix: usize, pad_to: usize, upper_case: bool) -> String {
765        assert!(radix >= 2 && radix <= 36);
766        match radix {
767            2 | 4 | 8 | 16 | 32 => self.to_string_impl_log2(radix.ilog2(), pad_to, upper_case),
768            _ => self.to_string_impl(radix, pad_to, upper_case),
769        }
770    }
771
772    fn try_to_u8(&self) -> Option<u8> {
773        let raw = self.to_raw();
774        if (raw.1, raw.2, raw.3) != (0, 0, 0) {
775            return None;
776        }
777        if raw.0 > u8::MAX as u64 {
778            return None;
779        }
780        Some(raw.0 as u8)
781    }
782
783    fn try_to_u16(&self) -> Option<u16> {
784        let raw = self.to_raw();
785        if (raw.1, raw.2, raw.3) != (0, 0, 0) {
786            return None;
787        }
788        if raw.0 > u16::MAX as u64 {
789            return None;
790        }
791        Some(raw.0 as u16)
792    }
793}
794
795impl Field256 for Scalar {
796    fn to_le_bytes(&self) -> [u8; 32] {
797        let raw = self.to_raw();
798        let mut bytes = [0u8; 32];
799        bytes[0..8].copy_from_slice(&raw.0.to_le_bytes());
800        bytes[8..16].copy_from_slice(&raw.1.to_le_bytes());
801        bytes[16..24].copy_from_slice(&raw.2.to_le_bytes());
802        bytes[24..32].copy_from_slice(&raw.3.to_le_bytes());
803        bytes
804    }
805
806    fn to_be_bytes(&self) -> [u8; 32] {
807        let raw = self.to_raw();
808        let mut bytes = [0u8; 32];
809        bytes[0..8].copy_from_slice(&raw.3.to_be_bytes());
810        bytes[8..16].copy_from_slice(&raw.2.to_be_bytes());
811        bytes[16..24].copy_from_slice(&raw.1.to_be_bytes());
812        bytes[24..32].copy_from_slice(&raw.0.to_be_bytes());
813        bytes
814    }
815
816    fn from_u512_mod_n(u512: U512) -> Self {
817        static P: LazyLock<U512> = LazyLock::new(|| Scalar::MODULUS.parse().unwrap());
818        let value = u512 % *P;
819        let bytes = value.to_little_endian();
820        Scalar::try_from_le_bytes(&bytes[0..32]).unwrap()
821    }
822
823    fn from_h512(h512: H512) -> Self {
824        let u512 = U512::from_little_endian(h512.as_bytes());
825        Self::from_u512_mod_n(u512)
826    }
827
828    fn try_to_u32(&self) -> CtOption<u32> {
829        let raw = self.to_raw();
830        CtOption::new(
831            raw.0 as u32,
832            Choice::from((raw.0 <= u32::MAX as u64) as u8)
833                & Choice::from((raw.1 == 0) as u8)
834                & Choice::from((raw.2 == 0) as u8)
835                & Choice::from((raw.3 == 0) as u8),
836        )
837    }
838
839    fn try_to_u64(&self) -> CtOption<u64> {
840        let raw = self.to_raw();
841        CtOption::new(
842            raw.0 as u64,
843            Choice::from((raw.1 == 0) as u8)
844                & Choice::from((raw.2 == 0) as u8)
845                & Choice::from((raw.3 == 0) as u8),
846        )
847    }
848
849    fn try_to_u128(&self) -> CtOption<u128> {
850        let raw = self.to_raw();
851        let mut bytes = [0u8; 16];
852        bytes[0..8].copy_from_slice(&raw.0.to_le_bytes());
853        bytes[8..16].copy_from_slice(&raw.1.to_le_bytes());
854        CtOption::new(
855            u128::from_le_bytes(bytes),
856            Choice::from((raw.2 == 0) as u8) & Choice::from((raw.3 == 0) as u8),
857        )
858    }
859
860    fn to_u256(&self) -> U256 {
861        U256::from_little_endian(&self.to_le_bytes())
862    }
863
864    fn to_u512(&self) -> U512 {
865        let mut bytes = [0u8; 64];
866        bytes[0..32].copy_from_slice(&self.to_le_bytes());
867        U512::from_little_endian(&bytes)
868    }
869}
870
871impl PrimeField for Scalar {
872    const MODULUS: &'static str =
873        "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001";
874
875    const S: usize = 32;
876
877    const MULTIPLICATIVE_GENERATOR: Self = Self(
878        0x0000000efffffff1u64,
879        0x17e363d300189c0fu64,
880        0xff9c57876f8457b0u64,
881        0x351332208fc5a8c4u64,
882    );
883
884    const MINUS_TWO: Self = Self(
885        0xfffffffb00000005u64,
886        0xa2b4340efff7cbfau64,
887        0x002138283029381au64,
888        0x43a4449fd0137269u64,
889    );
890
891    const TWO_INV: Self = Self(
892        0x00000000ffffffffu64,
893        0xac425bfd0001a401u64,
894        0xccc627f7f65e27fau64,
895        0x0c1258acd66282b7u64,
896    );
897
898    const ROOT_OF_UNITY: Self = Self(
899        0xb9b58d8c5f0e466au64,
900        0x5b1b4c801819d7ecu64,
901        0x0af53ae352a31e64u64,
902        0x5bf3adda19e9b27bu64,
903    );
904
905    const ROOT_OF_UNITY_INV: Self = Self(
906        0x4256481adcf3219au64,
907        0x45f37b7f96b6cad3u64,
908        0xf9c3f1d75f7a3b27u64,
909        0x2d2fc049658afd43u64,
910    );
911
912    const DELTA: Self = Self(
913        0x70e310d3d146f96au64,
914        0x4b64c08919e299e6u64,
915        0x51e114186a8b970du64,
916        0x6185d06627c067cbu64,
917    );
918}
919
920impl PrimeField256 for Scalar {}
921
922#[cfg(test)]
923mod tests {
924    use super::*;
925    use crate::PrimeField;
926    use blstrs::Scalar as BlstScalar;
927    use ff;
928
929    fn format_blst_scalar(value: BlstScalar) -> String {
930        let value = U256::from_little_endian(&value.to_bytes_le());
931        format!("{:#066x}", value)
932    }
933
934    fn from_const(value: u64) -> Scalar {
935        Scalar::from_const(value)
936    }
937
938    fn parse_scalar(s: &'static str) -> Scalar {
939        s.parse().unwrap()
940    }
941
942    #[test]
943    fn test_from_const() {
944        assert_eq!(from_const(0), Scalar::ZERO);
945        assert_eq!(from_const(1), Scalar::ONE);
946        assert_eq!(
947            from_const(0).to_string(),
948            "0x0000000000000000000000000000000000000000000000000000000000000000"
949        );
950        assert_eq!(
951            from_const(1).to_string(),
952            "0x0000000000000000000000000000000000000000000000000000000000000001"
953        );
954        assert_eq!(
955            from_const(2).to_string(),
956            "0x0000000000000000000000000000000000000000000000000000000000000002"
957        );
958        assert_eq!(
959            from_const(15).to_string(),
960            "0x000000000000000000000000000000000000000000000000000000000000000f"
961        );
962        assert_eq!(
963            from_const(16).to_string(),
964            "0x0000000000000000000000000000000000000000000000000000000000000010"
965        );
966        assert_eq!(
967            from_const(17).to_string(),
968            "0x0000000000000000000000000000000000000000000000000000000000000011"
969        );
970        assert_eq!(
971            from_const(u64::MAX - 1).to_string(),
972            "0x000000000000000000000000000000000000000000000000fffffffffffffffe"
973        );
974        assert_eq!(
975            from_const(u64::MAX).to_string(),
976            "0x000000000000000000000000000000000000000000000000ffffffffffffffff"
977        );
978    }
979
980    #[test]
981    fn test_modulus() {
982        assert_eq!(Scalar::MODULUS, <BlstScalar as ff::PrimeField>::MODULUS);
983    }
984
985    #[test]
986    fn test_zero() {
987        assert_eq!(Scalar::ZERO, Scalar::zero());
988        assert_eq!(Scalar::ZERO, from_const(0));
989        assert_eq!(Scalar::ZERO + from_const(0), from_const(0));
990        assert_eq!(Scalar::ZERO + from_const(1), from_const(1));
991        assert_eq!(Scalar::ZERO + from_const(2), from_const(2));
992        assert_eq!(Scalar::ZERO + from_const(3), from_const(3));
993        assert_eq!(Scalar::ZERO * from_const(0), Scalar::ZERO);
994        assert_eq!(Scalar::ZERO * from_const(1), Scalar::ZERO);
995        assert_eq!(Scalar::ZERO * from_const(2), Scalar::ZERO);
996        assert_eq!(Scalar::ZERO * from_const(3), Scalar::ZERO);
997    }
998
999    #[test]
1000    fn test_one() {
1001        assert_eq!(Scalar::ONE, Scalar::R);
1002        assert_eq!(Scalar::ONE, Scalar::one());
1003        assert_eq!(Scalar::ONE, from_const(1));
1004        assert_eq!(Scalar::ONE + from_const(0), from_const(1));
1005        assert_eq!(Scalar::ONE + from_const(1), from_const(2));
1006        assert_eq!(Scalar::ONE + from_const(2), from_const(3));
1007        assert_eq!(Scalar::ONE + from_const(3), from_const(4));
1008        assert_eq!(Scalar::ONE * from_const(0), from_const(0));
1009        assert_eq!(Scalar::ONE * from_const(1), from_const(1));
1010        assert_eq!(Scalar::ONE * from_const(2), from_const(2));
1011        assert_eq!(Scalar::ONE * from_const(3), from_const(3));
1012    }
1013
1014    #[test]
1015    fn test_max() {
1016        assert_eq!(Scalar::MAX, -Scalar::ONE);
1017    }
1018
1019    #[test]
1020    fn test_fmt_display() {
1021        assert_eq!(
1022            format!("{}", from_const(0)),
1023            "0x0000000000000000000000000000000000000000000000000000000000000000"
1024        );
1025        assert_eq!(
1026            format!("{}", from_const(1)),
1027            "0x0000000000000000000000000000000000000000000000000000000000000001"
1028        );
1029        assert_eq!(
1030            format!("{}", from_const(2)),
1031            "0x0000000000000000000000000000000000000000000000000000000000000002"
1032        );
1033        assert_eq!(
1034            format!(
1035                "{}",
1036                parse_scalar("0x17386c7200968ccab11e0a32e9b8c520b89637cc9b71975efe17b59138fe9c7b")
1037            ),
1038            "0x17386c7200968ccab11e0a32e9b8c520b89637cc9b71975efe17b59138fe9c7b"
1039        );
1040        assert_eq!(
1041            format!("{}", Scalar::MAX - Scalar::ONE),
1042            "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffeffffffff"
1043        );
1044        assert_eq!(
1045            format!("{}", Scalar::MAX),
1046            "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"
1047        );
1048    }
1049
1050    #[test]
1051    fn test_fmt_debug() {
1052        assert_eq!(
1053            format!("{:?}", from_const(0)),
1054            "Scalar(0x0000000000000000000000000000000000000000000000000000000000000000)"
1055        );
1056        assert_eq!(
1057            format!("{:?}", from_const(1)),
1058            "Scalar(0x0000000000000000000000000000000000000000000000000000000000000001)"
1059        );
1060        assert_eq!(
1061            format!("{:?}", from_const(2)),
1062            "Scalar(0x0000000000000000000000000000000000000000000000000000000000000002)"
1063        );
1064        assert_eq!(
1065            format!(
1066                "{:?}",
1067                parse_scalar("0x17386c7200968ccab11e0a32e9b8c520b89637cc9b71975efe17b59138fe9c7b")
1068            ),
1069            "Scalar(0x17386c7200968ccab11e0a32e9b8c520b89637cc9b71975efe17b59138fe9c7b)"
1070        );
1071        assert_eq!(
1072            format!("{:?}", Scalar::MAX - Scalar::ONE),
1073            "Scalar(0x73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffeffffffff)"
1074        );
1075        assert_eq!(
1076            format!("{:?}", Scalar::MAX),
1077            "Scalar(0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000)"
1078        );
1079    }
1080
1081    #[test]
1082    fn test_fmt_lower_hex() {
1083        assert_eq!(format!("{:x}", from_const(0)), "0");
1084        assert_eq!(format!("{:x}", from_const(1)), "1");
1085        assert_eq!(format!("{:x}", from_const(0xdeadbeef)), "deadbeef");
1086        assert_eq!(format!("{:#x}", from_const(0)), "0x0");
1087        assert_eq!(format!("{:#x}", from_const(0xdeadbeef)), "0xdeadbeef");
1088        assert_eq!(format!("{:10x}", from_const(0xdeadbeef)), "  deadbeef");
1089        assert_eq!(format!("{:010x}", from_const(0xdeadbeef)), "00deadbeef");
1090        assert_eq!(format!("{:#012x}", from_const(0xdeadbeef)), "0x00deadbeef");
1091        assert_eq!(format!("{:<10x}", from_const(0xdeadbeef)), "deadbeef  ");
1092        assert_eq!(format!("{:_<10x}", from_const(0xdeadbeef)), "deadbeef__");
1093    }
1094
1095    #[test]
1096    fn test_fmt_upper_hex() {
1097        assert_eq!(format!("{:X}", from_const(0)), "0");
1098        assert_eq!(format!("{:X}", from_const(0xdeadbeef)), "DEADBEEF");
1099        assert_eq!(format!("{:#X}", from_const(0xdeadbeef)), "0xDEADBEEF");
1100        assert_eq!(format!("{:010X}", from_const(0xdeadbeef)), "00DEADBEEF");
1101        assert_eq!(format!("{:#012X}", from_const(0xdeadbeef)), "0x00DEADBEEF");
1102        assert_eq!(format!("{:<10X}", from_const(0xdeadbeef)), "DEADBEEF  ");
1103    }
1104
1105    #[test]
1106    fn test_fmt_binary() {
1107        assert_eq!(format!("{:b}", from_const(0)), "0");
1108        assert_eq!(format!("{:b}", from_const(1)), "1");
1109        assert_eq!(format!("{:b}", from_const(0b1010)), "1010");
1110        assert_eq!(format!("{:#b}", from_const(0b1010)), "0b1010");
1111        assert_eq!(format!("{:10b}", from_const(0b1010)), "      1010");
1112        assert_eq!(format!("{:010b}", from_const(0b1010)), "0000001010");
1113        assert_eq!(format!("{:#012b}", from_const(0b1010)), "0b0000001010");
1114        assert_eq!(format!("{:<10b}", from_const(0b1010)), "1010      ");
1115    }
1116
1117    #[test]
1118    fn test_fmt_octal() {
1119        assert_eq!(format!("{:o}", from_const(0)), "0");
1120        assert_eq!(format!("{:o}", from_const(1)), "1");
1121        assert_eq!(format!("{:o}", from_const(0o755)), "755");
1122        assert_eq!(format!("{:#o}", from_const(0o755)), "0o755");
1123        assert_eq!(format!("{:10o}", from_const(0o755)), "       755");
1124        assert_eq!(format!("{:010o}", from_const(0o755)), "0000000755");
1125        assert_eq!(format!("{:#012o}", from_const(0o755)), "0o0000000755");
1126        assert_eq!(format!("{:<10o}", from_const(0o755)), "755       ");
1127    }
1128
1129    #[test]
1130    fn test_equality() {
1131        assert!(from_const(0) == from_const(0));
1132        assert!(from_const(0) != from_const(1));
1133        assert!(from_const(0) != from_const(2));
1134        assert!(from_const(0) != Scalar::MAX - Scalar::ONE);
1135        assert!(from_const(0) != Scalar::MAX);
1136        assert!(from_const(1) != from_const(0));
1137        assert!(from_const(1) == from_const(1));
1138        assert!(from_const(1) != from_const(2));
1139        assert!(from_const(0) != Scalar::MAX - Scalar::ONE);
1140        assert!(from_const(0) != Scalar::MAX);
1141        assert!(from_const(2) != from_const(0));
1142        assert!(from_const(2) != from_const(1));
1143        assert!(from_const(2) == from_const(2));
1144        assert!(from_const(0) != Scalar::MAX - Scalar::ONE);
1145        assert!(from_const(0) != Scalar::MAX);
1146        assert!(Scalar::MAX - Scalar::ONE != from_const(0));
1147        assert!(Scalar::MAX - Scalar::ONE != from_const(1));
1148        assert!(Scalar::MAX - Scalar::ONE != from_const(2));
1149        assert!(Scalar::MAX - Scalar::ONE == Scalar::MAX - Scalar::ONE);
1150        assert!(Scalar::MAX - Scalar::ONE != Scalar::MAX);
1151        assert!(Scalar::MAX != from_const(0));
1152        assert!(Scalar::MAX != from_const(1));
1153        assert!(Scalar::MAX != from_const(2));
1154        assert!(Scalar::MAX != Scalar::MAX - Scalar::ONE);
1155        assert!(Scalar::MAX == Scalar::MAX);
1156    }
1157
1158    #[test]
1159    fn test_total_order() {
1160        let v0 = from_const(0);
1161        let v1 = from_const(1);
1162        let v2 = from_const(42);
1163        let v3 = parse_scalar("0x318c1df8459d125dc54e1fe487bf23e8430221b69660d8ca9427235713f24de1");
1164        let v4 = Scalar::MAX - Scalar::ONE;
1165        let v5 = Scalar::MAX;
1166
1167        assert_eq!(v0.cmp(&v0), Ordering::Equal);
1168        assert_eq!(v0.cmp(&v1), Ordering::Less);
1169        assert_eq!(v0.cmp(&v2), Ordering::Less);
1170        assert_eq!(v0.cmp(&v3), Ordering::Less);
1171        assert_eq!(v0.cmp(&v4), Ordering::Less);
1172        assert_eq!(v0.cmp(&v5), Ordering::Less);
1173
1174        assert_eq!(v1.cmp(&v0), Ordering::Greater);
1175        assert_eq!(v1.cmp(&v1), Ordering::Equal);
1176        assert_eq!(v1.cmp(&v2), Ordering::Less);
1177        assert_eq!(v1.cmp(&v3), Ordering::Less);
1178        assert_eq!(v1.cmp(&v4), Ordering::Less);
1179        assert_eq!(v1.cmp(&v5), Ordering::Less);
1180
1181        assert_eq!(v2.cmp(&v0), Ordering::Greater);
1182        assert_eq!(v2.cmp(&v1), Ordering::Greater);
1183        assert_eq!(v2.cmp(&v2), Ordering::Equal);
1184        assert_eq!(v2.cmp(&v3), Ordering::Less);
1185        assert_eq!(v2.cmp(&v4), Ordering::Less);
1186        assert_eq!(v2.cmp(&v5), Ordering::Less);
1187
1188        assert_eq!(v3.cmp(&v0), Ordering::Greater);
1189        assert_eq!(v3.cmp(&v1), Ordering::Greater);
1190        assert_eq!(v3.cmp(&v2), Ordering::Greater);
1191        assert_eq!(v3.cmp(&v3), Ordering::Equal);
1192        assert_eq!(v3.cmp(&v4), Ordering::Less);
1193        assert_eq!(v3.cmp(&v5), Ordering::Less);
1194
1195        assert_eq!(v4.cmp(&v0), Ordering::Greater);
1196        assert_eq!(v4.cmp(&v1), Ordering::Greater);
1197        assert_eq!(v4.cmp(&v2), Ordering::Greater);
1198        assert_eq!(v4.cmp(&v3), Ordering::Greater);
1199        assert_eq!(v4.cmp(&v4), Ordering::Equal);
1200        assert_eq!(v4.cmp(&v5), Ordering::Less);
1201
1202        assert_eq!(v5.cmp(&v0), Ordering::Greater);
1203        assert_eq!(v5.cmp(&v1), Ordering::Greater);
1204        assert_eq!(v5.cmp(&v2), Ordering::Greater);
1205        assert_eq!(v5.cmp(&v3), Ordering::Greater);
1206        assert_eq!(v5.cmp(&v4), Ordering::Greater);
1207        assert_eq!(v5.cmp(&v5), Ordering::Equal);
1208    }
1209
1210    #[test]
1211    fn test_ct_eq() {
1212        let a = from_const(42);
1213        let b = from_const(42);
1214        let c = from_const(43);
1215
1216        assert_eq!(bool::from(a.ct_eq(&b)), true);
1217        assert_eq!(bool::from(a.ct_eq(&a)), true);
1218        assert_eq!(bool::from(a.ct_eq(&c)), false);
1219        assert_eq!(bool::from(c.ct_eq(&a)), false);
1220
1221        assert_eq!(bool::from(Scalar::ZERO.ct_eq(&Scalar::ZERO)), true);
1222        assert_eq!(bool::from(Scalar::ONE.ct_eq(&Scalar::ONE)), true);
1223        assert_eq!(bool::from(Scalar::MAX.ct_eq(&Scalar::MAX)), true);
1224        assert_eq!(bool::from(Scalar::ZERO.ct_eq(&Scalar::ONE)), false);
1225        assert_eq!(bool::from(Scalar::ONE.ct_eq(&Scalar::MAX)), false);
1226
1227        let v1 = parse_scalar("0x318c1df8459d125dc54e1fe487bf23e8430221b69660d8ca9427235713f24de1");
1228        let v2 = parse_scalar("0x318c1df8459d125dc54e1fe487bf23e8430221b69660d8ca9427235713f24de2");
1229        assert_eq!(bool::from(v1.ct_eq(&v2)), false);
1230        assert_eq!(bool::from(v1.ct_eq(&v1)), true);
1231    }
1232
1233    #[test]
1234    fn test_ct_gt() {
1235        let v0 = from_const(0);
1236        let v1 = from_const(1);
1237        let v2 = from_const(42);
1238        let v3 = Scalar::MAX - Scalar::ONE;
1239        let v4 = Scalar::MAX;
1240        assert_eq!(bool::from(v0.ct_gt(&v0)), false);
1241        assert_eq!(bool::from(v1.ct_gt(&v1)), false);
1242        assert_eq!(bool::from(v4.ct_gt(&v4)), false);
1243        assert_eq!(bool::from(v1.ct_gt(&v0)), true);
1244        assert_eq!(bool::from(v2.ct_gt(&v0)), true);
1245        assert_eq!(bool::from(v2.ct_gt(&v1)), true);
1246        assert_eq!(bool::from(v4.ct_gt(&v3)), true);
1247        assert_eq!(bool::from(v4.ct_gt(&v0)), true);
1248        assert_eq!(bool::from(v0.ct_gt(&v1)), false);
1249        assert_eq!(bool::from(v0.ct_gt(&v4)), false);
1250        assert_eq!(bool::from(v1.ct_gt(&v2)), false);
1251        assert_eq!(bool::from(v3.ct_gt(&v4)), false);
1252    }
1253
1254    #[test]
1255    fn test_ct_lt() {
1256        let v0 = from_const(0);
1257        let v1 = from_const(1);
1258        let v2 = from_const(42);
1259        let v3 = Scalar::MAX - Scalar::ONE;
1260        let v4 = Scalar::MAX;
1261        assert_eq!(bool::from(v0.ct_lt(&v0)), false);
1262        assert_eq!(bool::from(v1.ct_lt(&v1)), false);
1263        assert_eq!(bool::from(v4.ct_lt(&v4)), false);
1264        assert_eq!(bool::from(v0.ct_lt(&v1)), true);
1265        assert_eq!(bool::from(v0.ct_lt(&v4)), true);
1266        assert_eq!(bool::from(v1.ct_lt(&v2)), true);
1267        assert_eq!(bool::from(v2.ct_lt(&v3)), true);
1268        assert_eq!(bool::from(v3.ct_lt(&v4)), true);
1269        assert_eq!(bool::from(v1.ct_lt(&v0)), false);
1270        assert_eq!(bool::from(v4.ct_lt(&v3)), false);
1271        assert_eq!(bool::from(v4.ct_lt(&v0)), false);
1272    }
1273
1274    #[test]
1275    fn test_conditional_select() {
1276        let a = from_const(12);
1277        let b = from_const(34);
1278        assert_eq!(Scalar::conditional_select(&a, &b, Choice::from(0)), a);
1279        assert_eq!(Scalar::conditional_select(&a, &b, Choice::from(1)), b);
1280        assert_eq!(
1281            Scalar::conditional_select(&Scalar::ZERO, &Scalar::ONE, Choice::from(0)),
1282            Scalar::ZERO
1283        );
1284        assert_eq!(
1285            Scalar::conditional_select(&Scalar::ZERO, &Scalar::ONE, Choice::from(1)),
1286            Scalar::ONE
1287        );
1288        assert_eq!(Scalar::conditional_select(&a, &a, Choice::from(0)), a);
1289        assert_eq!(Scalar::conditional_select(&a, &a, Choice::from(1)), a);
1290    }
1291
1292    #[test]
1293    fn test_add() {
1294        let lhs =
1295            parse_scalar("0x35264695f12d2c6cefa453ccda4c1bc5051c7b8b648915cc889b9c7d7c162aa5");
1296        let rhs =
1297            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1298        assert_eq!(
1299            lhs + rhs,
1300            parse_scalar("0x6447adc64b17816528ee763e0b64ce7ee546304e19dd71176e7b468d8c9a6e7b")
1301        );
1302        assert_eq!(
1303            lhs + &rhs,
1304            parse_scalar("0x6447adc64b17816528ee763e0b64ce7ee546304e19dd71176e7b468d8c9a6e7b")
1305        );
1306    }
1307
1308    #[test]
1309    fn test_add_wraparound() {
1310        let lhs =
1311            parse_scalar("0x5445e022a3c13a026ec2378170357420280e21d24f537bca42830d1bb5823236");
1312        let rhs =
1313            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1314        assert_eq!(
1315            lhs + rhs,
1316            parse_scalar("0x0f799fffd40e11b274d281ea97ac4ed4b47a329204a97b162862b72cc606760b")
1317        );
1318        assert_eq!(
1319            lhs + &rhs,
1320            parse_scalar("0x0f799fffd40e11b274d281ea97ac4ed4b47a329204a97b162862b72cc606760b")
1321        );
1322    }
1323
1324    #[test]
1325    fn test_add_assign() {
1326        let mut lhs =
1327            parse_scalar("0x35264695f12d2c6cefa453ccda4c1bc5051c7b8b648915cc889b9c7d7c162aa5");
1328        let rhs =
1329            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1330        lhs += rhs;
1331        assert_eq!(
1332            lhs,
1333            parse_scalar("0x6447adc64b17816528ee763e0b64ce7ee546304e19dd71176e7b468d8c9a6e7b")
1334        );
1335    }
1336
1337    #[test]
1338    fn test_add_assign_ref() {
1339        let mut lhs =
1340            parse_scalar("0x35264695f12d2c6cefa453ccda4c1bc5051c7b8b648915cc889b9c7d7c162aa5");
1341        let rhs =
1342            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1343        lhs += &rhs;
1344        assert_eq!(
1345            lhs,
1346            parse_scalar("0x6447adc64b17816528ee763e0b64ce7ee546304e19dd71176e7b468d8c9a6e7b")
1347        );
1348    }
1349
1350    #[test]
1351    fn test_add_assign_wraparound() {
1352        let mut lhs =
1353            parse_scalar("0x5445e022a3c13a026ec2378170357420280e21d24f537bca42830d1bb5823236");
1354        let rhs =
1355            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1356        lhs += rhs;
1357        assert_eq!(
1358            lhs,
1359            parse_scalar("0x0f799fffd40e11b274d281ea97ac4ed4b47a329204a97b162862b72cc606760b")
1360        );
1361    }
1362
1363    #[test]
1364    fn test_add_assign_wraparound_ref() {
1365        let mut lhs =
1366            parse_scalar("0x5445e022a3c13a026ec2378170357420280e21d24f537bca42830d1bb5823236");
1367        let rhs =
1368            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1369        lhs += &rhs;
1370        assert_eq!(
1371            lhs,
1372            parse_scalar("0x0f799fffd40e11b274d281ea97ac4ed4b47a329204a97b162862b72cc606760b")
1373        );
1374    }
1375
1376    fn test_neg_impl(value: Scalar) {
1377        assert_eq!(-value, Scalar::MAX - value + Scalar::ONE);
1378    }
1379
1380    #[test]
1381    fn test_neg() {
1382        assert_eq!(-Scalar::ZERO, Scalar::ZERO);
1383        assert_eq!(-Scalar::ONE, Scalar::MAX);
1384        assert_eq!(-from_const(2), Scalar::MAX - Scalar::ONE);
1385        test_neg_impl(parse_scalar(
1386            "0x03674752fdab8efaa80c59f2a14e26dc01c3f8a2660c81cd6862b72bc606760b",
1387        ));
1388        test_neg_impl(parse_scalar(
1389            "0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6",
1390        ));
1391        test_neg_impl(parse_scalar(
1392            "0x5445e022a3c13a026ec2378170357420280e21d24f537bca42830d1bb5823236",
1393        ));
1394    }
1395
1396    #[test]
1397    fn test_sub() {
1398        let lhs =
1399            parse_scalar("0x6447adc64b17816528ee763e0b64ce7ee546304e19dd71176e7b468d8c9a6e7b");
1400        let rhs =
1401            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1402        assert_eq!(
1403            lhs - rhs,
1404            parse_scalar("0x35264695f12d2c6cefa453ccda4c1bc5051c7b8b648915cc889b9c7d7c162aa5")
1405        );
1406        assert_eq!(
1407            lhs - &rhs,
1408            parse_scalar("0x35264695f12d2c6cefa453ccda4c1bc5051c7b8b648915cc889b9c7d7c162aa5")
1409        );
1410    }
1411
1412    #[test]
1413    fn test_sub_wraparound() {
1414        let lhs =
1415            parse_scalar("0x03674752fdab8efaa80c59f2a14e26dc01c3f8a2660c81cd6862b72bc606760b");
1416        let rhs =
1417            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1418        assert_eq!(
1419            lhs - rhs,
1420            parse_scalar("0x48338775cd5eb74aa1fc0f8979d74c277557e7e2b0b6828182830d1ab5823236")
1421        );
1422        assert_eq!(
1423            lhs - &rhs,
1424            parse_scalar("0x48338775cd5eb74aa1fc0f8979d74c277557e7e2b0b6828182830d1ab5823236")
1425        );
1426    }
1427
1428    #[test]
1429    fn test_sub_assign() {
1430        let mut lhs =
1431            parse_scalar("0x6447adc64b17816528ee763e0b64ce7ee546304e19dd71176e7b468d8c9a6e7b");
1432        let rhs =
1433            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1434        lhs -= rhs;
1435        assert_eq!(
1436            lhs,
1437            parse_scalar("0x35264695f12d2c6cefa453ccda4c1bc5051c7b8b648915cc889b9c7d7c162aa5")
1438        );
1439    }
1440
1441    #[test]
1442    fn test_sub_assign_ref() {
1443        let mut lhs =
1444            parse_scalar("0x6447adc64b17816528ee763e0b64ce7ee546304e19dd71176e7b468d8c9a6e7b");
1445        let rhs =
1446            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1447        lhs -= &rhs;
1448        assert_eq!(
1449            lhs,
1450            parse_scalar("0x35264695f12d2c6cefa453ccda4c1bc5051c7b8b648915cc889b9c7d7c162aa5")
1451        );
1452    }
1453
1454    #[test]
1455    fn test_sub_assign_wraparound() {
1456        let mut lhs =
1457            parse_scalar("0x03674752fdab8efaa80c59f2a14e26dc01c3f8a2660c81cd6862b72bc606760b");
1458        let rhs =
1459            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1460        lhs -= rhs;
1461        assert_eq!(
1462            lhs,
1463            parse_scalar("0x48338775cd5eb74aa1fc0f8979d74c277557e7e2b0b6828182830d1ab5823236")
1464        );
1465    }
1466
1467    #[test]
1468    fn test_sub_assign_wraparound_ref() {
1469        let mut lhs =
1470            parse_scalar("0x03674752fdab8efaa80c59f2a14e26dc01c3f8a2660c81cd6862b72bc606760b");
1471        let rhs =
1472            parse_scalar("0x2f21673059ea54f8394a22713118b2b9e029b4c2b5545b4ae5dfaa10108443d6");
1473        lhs -= &rhs;
1474        assert_eq!(
1475            lhs,
1476            parse_scalar("0x48338775cd5eb74aa1fc0f8979d74c277557e7e2b0b6828182830d1ab5823236")
1477        );
1478    }
1479
1480    #[test]
1481    fn test_mul_by_zero() {
1482        assert_eq!(Scalar::ZERO * from_const(42), Scalar::ZERO);
1483        assert_eq!(Scalar::ZERO * &from_const(42), Scalar::ZERO);
1484        assert_eq!(Scalar::ZERO * from_const(43), Scalar::ZERO);
1485        assert_eq!(Scalar::ZERO * &from_const(43), Scalar::ZERO);
1486        assert_eq!(from_const(42) * Scalar::ZERO, Scalar::ZERO);
1487        assert_eq!(from_const(42) * &Scalar::ZERO, Scalar::ZERO);
1488        assert_eq!(from_const(43) * Scalar::ZERO, Scalar::ZERO);
1489        assert_eq!(from_const(43) * &Scalar::ZERO, Scalar::ZERO);
1490    }
1491
1492    #[test]
1493    fn test_mul_by_one() {
1494        assert_eq!(Scalar::ONE * from_const(42), from_const(42));
1495        assert_eq!(Scalar::ONE * &from_const(42), from_const(42));
1496        assert_eq!(Scalar::ONE * from_const(43), from_const(43));
1497        assert_eq!(Scalar::ONE * &from_const(43), from_const(43));
1498        assert_eq!(from_const(42) * Scalar::ONE, from_const(42));
1499        assert_eq!(from_const(42) * &Scalar::ONE, from_const(42));
1500        assert_eq!(from_const(43) * Scalar::ONE, from_const(43));
1501        assert_eq!(from_const(43) * &Scalar::ONE, from_const(43));
1502    }
1503
1504    #[test]
1505    fn test_mul() {
1506        assert_eq!(from_const(12) * from_const(34), from_const(408));
1507        assert_eq!(from_const(12) * &from_const(34), from_const(408));
1508        assert_eq!(from_const(12) * from_const(56), from_const(672));
1509        assert_eq!(from_const(12) * &from_const(56), from_const(672));
1510        assert_eq!(from_const(34) * from_const(12), from_const(408));
1511        assert_eq!(from_const(34) * &from_const(12), from_const(408));
1512        assert_eq!(from_const(56) * from_const(12), from_const(672));
1513        assert_eq!(from_const(56) * &from_const(12), from_const(672));
1514    }
1515
1516    fn test_mul_large_impl(v1: Scalar, v2: Scalar, v3: Scalar) {
1517        assert_eq!(v1 * v2, v3);
1518        assert_eq!(v1 * &v2, v3);
1519        assert_eq!(v2 * v1, v3);
1520        assert_eq!(v2 * &v1, v3);
1521    }
1522
1523    #[test]
1524    fn test_mul_large() {
1525        test_mul_large_impl(
1526            parse_scalar("0x1be5c79927a7c7c2c1057e99b51e26efc2bac5029c6322e20405fc9334c50a9f"),
1527            parse_scalar("0x395ff9efcaa35d618872a95b7244c4b3b2a7e1d9276d4e88db27217993014628"),
1528            parse_scalar("0x2bc49f0bc7dac8408df7cb52f041d006431cea0fdd40ffde5f0e3bdf60135d63"),
1529        );
1530        test_mul_large_impl(
1531            parse_scalar("0x233f7c593e331b2e1285f17013cd4b692d7219c10bf06adca229780913851577"),
1532            parse_scalar("0x4433ff6315d939cda16f055756432036cab445af8186bc60b243127905b84c73"),
1533            parse_scalar("0x4e113a27725b45acdc2e6dbdb80b523bf08e8b3717baad804bfe1ae04701ebab"),
1534        );
1535    }
1536
1537    #[test]
1538    fn test_div_by_one() {
1539        assert_eq!(Scalar::ONE / from_const(42), from_const(42).invert_unwrap());
1540        assert_eq!(
1541            Scalar::ONE / &from_const(42),
1542            from_const(42).invert_unwrap()
1543        );
1544        assert_eq!(Scalar::ONE / from_const(43), from_const(43).invert_unwrap());
1545        assert_eq!(
1546            Scalar::ONE / &from_const(43),
1547            from_const(43).invert_unwrap()
1548        );
1549        assert_eq!(from_const(42) / Scalar::ONE, from_const(42));
1550        assert_eq!(from_const(42) / &Scalar::ONE, from_const(42));
1551        assert_eq!(from_const(43) / Scalar::ONE, from_const(43));
1552        assert_eq!(from_const(43) / &Scalar::ONE, from_const(43));
1553    }
1554
1555    #[test]
1556    fn test_div() {
1557        assert_eq!(from_const(408) / from_const(34), from_const(12));
1558        assert_eq!(from_const(408) / &from_const(34), from_const(12));
1559        assert_eq!(from_const(672) / from_const(56), from_const(12));
1560        assert_eq!(from_const(672) / &from_const(56), from_const(12));
1561        assert_eq!(from_const(408) / from_const(12), from_const(34));
1562        assert_eq!(from_const(408) / &from_const(12), from_const(34));
1563        assert_eq!(from_const(672) / from_const(12), from_const(56));
1564        assert_eq!(from_const(672) / &from_const(12), from_const(56));
1565    }
1566
1567    #[test]
1568    fn test_sum_owned() {
1569        let values = vec![Scalar::ONE, from_const(2), from_const(3)];
1570        assert_eq!(values.into_iter().sum::<Scalar>(), from_const(6));
1571    }
1572
1573    #[test]
1574    fn test_sum_refs() {
1575        let values = vec![Scalar::ONE, from_const(2), from_const(3)];
1576        assert_eq!(values.iter().sum::<Scalar>(), from_const(6));
1577    }
1578
1579    #[test]
1580    fn test_sum_empty() {
1581        let values: Vec<Scalar> = vec![];
1582        assert_eq!(values.into_iter().sum::<Scalar>(), Scalar::ZERO);
1583    }
1584
1585    #[test]
1586    fn test_sum_empty_refs() {
1587        let values: Vec<Scalar> = vec![];
1588        assert_eq!(values.iter().sum::<Scalar>(), Scalar::ZERO);
1589    }
1590
1591    #[test]
1592    fn test_sum_single() {
1593        let values = vec![from_const(42)];
1594        assert_eq!(values.into_iter().sum::<Scalar>(), from_const(42));
1595    }
1596
1597    #[test]
1598    fn test_sum_wraps_modulo_p() {
1599        let values = vec![Scalar::MAX, Scalar::ONE];
1600        assert_eq!(values.into_iter().sum::<Scalar>(), Scalar::ZERO);
1601    }
1602
1603    #[test]
1604    fn test_product_owned() {
1605        let values = vec![from_const(2), from_const(3), from_const(4)];
1606        assert_eq!(values.into_iter().product::<Scalar>(), from_const(24));
1607    }
1608
1609    #[test]
1610    fn test_product_refs() {
1611        let values = vec![from_const(2), from_const(3), from_const(4)];
1612        assert_eq!(values.iter().product::<Scalar>(), from_const(24));
1613    }
1614
1615    #[test]
1616    fn test_product_empty() {
1617        let values: Vec<Scalar> = vec![];
1618        assert_eq!(values.into_iter().product::<Scalar>(), Scalar::ONE);
1619    }
1620
1621    #[test]
1622    fn test_product_empty_refs() {
1623        let values: Vec<Scalar> = vec![];
1624        assert_eq!(values.iter().product::<Scalar>(), Scalar::ONE);
1625    }
1626
1627    #[test]
1628    fn test_product_single() {
1629        let values = vec![from_const(42)];
1630        assert_eq!(values.into_iter().product::<Scalar>(), from_const(42));
1631    }
1632
1633    #[test]
1634    fn test_product_with_zero() {
1635        let values = vec![from_const(5), Scalar::ZERO, from_const(7)];
1636        assert_eq!(values.into_iter().product::<Scalar>(), Scalar::ZERO);
1637    }
1638
1639    #[test]
1640    fn test_product_with_one() {
1641        let values = vec![Scalar::ONE, from_const(5), Scalar::ONE];
1642        assert_eq!(values.into_iter().product::<Scalar>(), from_const(5));
1643    }
1644
1645    #[test]
1646    fn test_from_u8() {
1647        assert_eq!(Scalar::from(0u8), from_const(0));
1648        assert_eq!(Scalar::from(1u8), from_const(1));
1649        assert_eq!(Scalar::from(2u8), from_const(2));
1650        assert_eq!(Scalar::from(u8::MAX - 1), from_const((u8::MAX - 1) as u64));
1651        assert_eq!(Scalar::from(u8::MAX), from_const(u8::MAX as u64));
1652    }
1653
1654    #[test]
1655    fn test_from_u16() {
1656        assert_eq!(Scalar::from(0u16), from_const(0));
1657        assert_eq!(Scalar::from(1u16), from_const(1));
1658        assert_eq!(Scalar::from(2u16), from_const(2));
1659        assert_eq!(
1660            Scalar::from(u16::MAX - 1),
1661            from_const((u16::MAX - 1) as u64)
1662        );
1663        assert_eq!(Scalar::from(u16::MAX), from_const(u16::MAX as u64));
1664    }
1665
1666    #[test]
1667    fn test_from_u32() {
1668        assert_eq!(Scalar::from(0u32), from_const(0));
1669        assert_eq!(Scalar::from(1u32), from_const(1));
1670        assert_eq!(Scalar::from(2u32), from_const(2));
1671        assert_eq!(
1672            Scalar::from(u32::MAX - 1),
1673            from_const((u32::MAX - 1) as u64)
1674        );
1675        assert_eq!(Scalar::from(u32::MAX), from_const(u32::MAX as u64));
1676    }
1677
1678    #[test]
1679    fn test_from_u64() {
1680        assert_eq!(Scalar::from(0u64), from_const(0));
1681        assert_eq!(Scalar::from(1u64), from_const(1));
1682        assert_eq!(Scalar::from(2u64), from_const(2));
1683        assert_eq!(Scalar::from(u64::MAX - 1), from_const(u64::MAX - 1));
1684        assert_eq!(Scalar::from(u64::MAX), from_const(u64::MAX));
1685    }
1686
1687    #[test]
1688    fn test_from_u128() {
1689        assert_eq!(Scalar::from(0u128), from_const(0));
1690        assert_eq!(Scalar::from(1u128), from_const(1));
1691        assert_eq!(Scalar::from(2u128), from_const(2));
1692        assert_eq!(
1693            Scalar::from(u128::MAX - 1),
1694            parse_scalar("0x00000000000000000000000000000000fffffffffffffffffffffffffffffffe")
1695        );
1696        assert_eq!(
1697            Scalar::from(u128::MAX),
1698            parse_scalar("0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff")
1699        );
1700    }
1701
1702    #[test]
1703    fn test_try_from_u256() {
1704        assert_eq!(
1705            <Scalar as TryFrom<U256>>::try_from(0.into()).unwrap(),
1706            from_const(0)
1707        );
1708        assert_eq!(
1709            <Scalar as TryFrom<U256>>::try_from(1.into()).unwrap(),
1710            from_const(1)
1711        );
1712        assert_eq!(
1713            <Scalar as TryFrom<U256>>::try_from(2.into()).unwrap(),
1714            from_const(2)
1715        );
1716        let modulus: U256 = Scalar::MODULUS.parse().unwrap();
1717        assert_eq!(
1718            <Scalar as TryFrom<U256>>::try_from(modulus - 2).unwrap(),
1719            -from_const(2)
1720        );
1721        assert_eq!(
1722            <Scalar as TryFrom<U256>>::try_from(modulus - 1).unwrap(),
1723            -from_const(1)
1724        );
1725        assert!(<Scalar as TryFrom<U256>>::try_from(modulus).is_err());
1726        assert!(<Scalar as TryFrom<U256>>::try_from(modulus + 1).is_err());
1727    }
1728
1729    #[test]
1730    fn test_try_from_usize() {
1731        assert_eq!(Scalar::try_from(0usize).unwrap(), from_const(0));
1732        assert_eq!(Scalar::try_from(1usize).unwrap(), from_const(1));
1733        assert_eq!(Scalar::try_from(2usize).unwrap(), from_const(2));
1734        assert_eq!(
1735            Scalar::try_from(usize::MAX - 1).unwrap(),
1736            from_const(usize::MAX as u64 - 1)
1737        );
1738        assert_eq!(
1739            Scalar::try_from(usize::MAX).unwrap(),
1740            from_const(usize::MAX as u64)
1741        );
1742    }
1743
1744    #[test]
1745    fn test_is_zero() {
1746        assert!(bool::from(from_const(0).is_zero()));
1747        assert!(!bool::from(from_const(1).is_zero()));
1748        assert!(!bool::from(from_const(2).is_zero()));
1749        assert!(!bool::from((Scalar::MAX - Scalar::ONE).is_zero()));
1750        assert!(!bool::from(Scalar::MAX.is_zero()));
1751    }
1752
1753    #[test]
1754    fn test_is_even() {
1755        assert!(bool::from(from_const(0).is_even()));
1756        assert!(!bool::from(from_const(1).is_even()));
1757        assert!(bool::from(from_const(2).is_even()));
1758        assert!(!bool::from(from_const(3).is_even()));
1759        assert!(bool::from(from_const(100).is_even()));
1760        assert!(!bool::from(from_const(101).is_even()));
1761        assert!(!bool::from((Scalar::MAX - Scalar::ONE).is_even()));
1762        assert!(bool::from(Scalar::MAX.is_even()));
1763    }
1764
1765    #[test]
1766    fn test_is_odd() {
1767        assert!(!bool::from(from_const(0).is_odd()));
1768        assert!(bool::from(from_const(1).is_odd()));
1769        assert!(!bool::from(from_const(2).is_odd()));
1770        assert!(bool::from(from_const(3).is_odd()));
1771        assert!(!bool::from(from_const(100).is_odd()));
1772        assert!(bool::from(from_const(101).is_odd()));
1773        assert!(bool::from((Scalar::MAX - Scalar::ONE).is_odd()));
1774        assert!(!bool::from(Scalar::MAX.is_odd()));
1775    }
1776
1777    struct OsRng;
1778
1779    impl rand_core::TryRng for OsRng {
1780        type Error = getrandom::Error;
1781
1782        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
1783            getrandom::fill(dest)
1784        }
1785
1786        fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
1787            let mut bytes = [0u8; 4];
1788            getrandom::fill(&mut bytes)?;
1789            Ok(u32::from_le_bytes(bytes))
1790        }
1791
1792        fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
1793            let mut bytes = [0u8; 8];
1794            getrandom::fill(&mut bytes)?;
1795            Ok(u64::from_le_bytes(bytes))
1796        }
1797    }
1798
1799    impl rand_core::TryCryptoRng for OsRng {}
1800
1801    #[test]
1802    fn test_try_random() {
1803        let mut rng = OsRng;
1804        assert_ne!(
1805            Scalar::try_random(&mut rng).unwrap(),
1806            Scalar::try_random(&mut rng).unwrap()
1807        );
1808        assert_ne!(
1809            Scalar::try_random(&mut rng).unwrap(),
1810            Scalar::try_random(&mut rng).unwrap()
1811        );
1812        assert_ne!(
1813            Scalar::try_random(&mut rng).unwrap(),
1814            Scalar::try_random(&mut rng).unwrap()
1815        );
1816    }
1817
1818    #[test]
1819    fn test_random() {
1820        let mut rng = rand_core::UnwrapErr(OsRng);
1821        assert_ne!(Scalar::random(&mut rng), Scalar::random(&mut rng));
1822        assert_ne!(Scalar::random(&mut rng), Scalar::random(&mut rng));
1823        assert_ne!(Scalar::random(&mut rng), Scalar::random(&mut rng));
1824    }
1825
1826    #[test]
1827    fn test_random_default() {
1828        assert_ne!(Scalar::random_default(), Scalar::random_default());
1829        assert_ne!(Scalar::random_default(), Scalar::random_default());
1830        assert_ne!(Scalar::random_default(), Scalar::random_default());
1831    }
1832
1833    #[test]
1834    fn test_double() {
1835        assert_eq!(from_const(0).double(), from_const(0));
1836        assert_eq!(from_const(1).double(), from_const(2));
1837        assert_eq!(from_const(2).double(), from_const(4));
1838        assert_eq!((Scalar::MAX - from_const(2)).double(), -from_const(6));
1839        assert_eq!((Scalar::MAX - from_const(1)).double(), -from_const(4));
1840        assert_eq!((Scalar::MAX).double(), -from_const(2));
1841    }
1842
1843    #[test]
1844    fn test_square() {
1845        assert_eq!(from_const(0).square(), from_const(0));
1846        assert_eq!(from_const(1).square(), from_const(1));
1847        assert_eq!(from_const(2).square(), from_const(4));
1848        assert_eq!((Scalar::MAX - from_const(2)).square(), from_const(9));
1849        assert_eq!((Scalar::MAX - from_const(1)).square(), from_const(4));
1850        assert_eq!((Scalar::MAX).square(), from_const(1));
1851    }
1852
1853    #[test]
1854    fn test_cube() {
1855        assert_eq!(from_const(0).cube(), from_const(0));
1856        assert_eq!(from_const(1).cube(), from_const(1));
1857        assert_eq!(from_const(2).cube(), from_const(8));
1858        assert_eq!((Scalar::MAX - from_const(2)).cube(), -from_const(27));
1859        assert_eq!((Scalar::MAX - from_const(1)).cube(), -from_const(8));
1860        assert_eq!((Scalar::MAX).cube(), -from_const(1));
1861    }
1862
1863    fn test_inversion_impl(value: Scalar) {
1864        assert_ne!(value, Scalar::ZERO);
1865        assert_eq!(value * value.invert().unwrap(), Scalar::ONE);
1866        assert_eq!(value * value.invert_unwrap(), Scalar::ONE);
1867        assert_eq!(value * value.invert_or_zero(), Scalar::ONE);
1868        assert_eq!(value * value.invert_vartime().unwrap(), Scalar::ONE);
1869    }
1870
1871    #[test]
1872    fn test_inversion() {
1873        assert!(from_const(0).invert_vartime().is_none());
1874        assert_eq!(from_const(0).invert_or_zero(), Scalar::ZERO);
1875        assert!(bool::from(from_const(0).invert().is_none()));
1876        test_inversion_impl(1u64.into());
1877        test_inversion_impl(2u64.into());
1878        test_inversion_impl(42u64.into());
1879        test_inversion_impl(Scalar::MAX);
1880    }
1881
1882    fn test_invert_batch_impl(values: &[Scalar]) {
1883        let expected: Vec<Scalar> = values
1884            .iter()
1885            .map(|value| value.invert_vartime().unwrap())
1886            .collect();
1887
1888        let mut batch = values.to_vec();
1889        Scalar::invert_batch(&mut batch);
1890        assert_eq!(batch, expected);
1891
1892        batch = values.to_vec();
1893        Scalar::invert_batch_vartime(&mut batch);
1894        assert_eq!(batch, expected);
1895    }
1896
1897    #[test]
1898    fn test_invert_batch() {
1899        test_invert_batch_impl(&[]);
1900        test_invert_batch_impl(&[Scalar::ONE]);
1901        test_invert_batch_impl(&[from_const(42)]);
1902        test_invert_batch_impl(&[Scalar::MAX]);
1903        test_invert_batch_impl(&[from_const(1), from_const(2), from_const(3)]);
1904        test_invert_batch_impl(&[
1905            from_const(42),
1906            Scalar::ONE,
1907            Scalar::MAX,
1908            from_const(1),
1909            from_const(2),
1910            Scalar::MAX - from_const(1),
1911        ]);
1912    }
1913
1914    #[test]
1915    fn test_power() {
1916        assert_eq!(from_const(0).pow(from_const(0)), from_const(1));
1917        assert_eq!(from_const(0).pow(from_const(1)), from_const(0));
1918        assert_eq!(from_const(0).pow(from_const(2)), from_const(0));
1919        assert_eq!(from_const(1).pow(from_const(0)), from_const(1));
1920        assert_eq!(from_const(1).pow(from_const(1)), from_const(1));
1921        assert_eq!(from_const(1).pow(from_const(2)), from_const(1));
1922        assert_eq!(from_const(2).pow(from_const(0)), from_const(1));
1923        assert_eq!(from_const(2).pow(from_const(1)), from_const(2));
1924        assert_eq!(from_const(2).pow(from_const(2)), from_const(4));
1925        assert_eq!(from_const(2).pow(from_const(3)), from_const(8));
1926    }
1927
1928    #[test]
1929    fn test_power_vartime() {
1930        assert_eq!(from_const(0).pow_vartime(from_const(0)), from_const(1));
1931        assert_eq!(from_const(0).pow_vartime(from_const(1)), from_const(0));
1932        assert_eq!(from_const(0).pow_vartime(from_const(2)), from_const(0));
1933        assert_eq!(from_const(1).pow_vartime(from_const(0)), from_const(1));
1934        assert_eq!(from_const(1).pow_vartime(from_const(1)), from_const(1));
1935        assert_eq!(from_const(1).pow_vartime(from_const(2)), from_const(1));
1936        assert_eq!(from_const(2).pow_vartime(from_const(0)), from_const(1));
1937        assert_eq!(from_const(2).pow_vartime(from_const(1)), from_const(2));
1938        assert_eq!(from_const(2).pow_vartime(from_const(2)), from_const(4));
1939        assert_eq!(from_const(2).pow_vartime(from_const(3)), from_const(8));
1940    }
1941
1942    #[test]
1943    fn test_small_power() {
1944        assert_eq!(from_const(0).pow_small(0), from_const(1));
1945        assert_eq!(from_const(0).pow_small(1), from_const(0));
1946        assert_eq!(from_const(0).pow_small(2), from_const(0));
1947        assert_eq!(from_const(1).pow_small(0), from_const(1));
1948        assert_eq!(from_const(1).pow_small(1), from_const(1));
1949        assert_eq!(from_const(1).pow_small(2), from_const(1));
1950        assert_eq!(from_const(2).pow_small(0), from_const(1));
1951        assert_eq!(from_const(2).pow_small(1), from_const(2));
1952        assert_eq!(from_const(2).pow_small(2), from_const(4));
1953        assert_eq!(from_const(2).pow_small(3), from_const(8));
1954    }
1955
1956    #[test]
1957    fn test_small_power_vartime() {
1958        assert_eq!(from_const(0).pow_small_vartime(0), from_const(1));
1959        assert_eq!(from_const(0).pow_small_vartime(1), from_const(0));
1960        assert_eq!(from_const(0).pow_small_vartime(2), from_const(0));
1961        assert_eq!(from_const(1).pow_small_vartime(0), from_const(1));
1962        assert_eq!(from_const(1).pow_small_vartime(1), from_const(1));
1963        assert_eq!(from_const(1).pow_small_vartime(2), from_const(1));
1964        assert_eq!(from_const(2).pow_small_vartime(0), from_const(1));
1965        assert_eq!(from_const(2).pow_small_vartime(1), from_const(2));
1966        assert_eq!(from_const(2).pow_small_vartime(2), from_const(4));
1967        assert_eq!(from_const(2).pow_small_vartime(3), from_const(8));
1968    }
1969
1970    #[test]
1971    fn test_u32_power() {
1972        assert_eq!(from_const(0).pow_u32(0), from_const(1));
1973        assert_eq!(from_const(0).pow_u32(1), from_const(0));
1974        assert_eq!(from_const(0).pow_u32(2), from_const(0));
1975        assert_eq!(from_const(1).pow_u32(0), from_const(1));
1976        assert_eq!(from_const(1).pow_u32(1), from_const(1));
1977        assert_eq!(from_const(1).pow_u32(2), from_const(1));
1978        assert_eq!(from_const(2).pow_u32(0), from_const(1));
1979        assert_eq!(from_const(2).pow_u32(1), from_const(2));
1980        assert_eq!(from_const(2).pow_u32(2), from_const(4));
1981        assert_eq!(from_const(2).pow_u32(3), from_const(8));
1982    }
1983
1984    #[test]
1985    fn test_u32_power_vartime() {
1986        assert_eq!(from_const(0).pow_u32_vartime(0), from_const(1));
1987        assert_eq!(from_const(0).pow_u32_vartime(1), from_const(0));
1988        assert_eq!(from_const(0).pow_u32_vartime(2), from_const(0));
1989        assert_eq!(from_const(1).pow_u32_vartime(0), from_const(1));
1990        assert_eq!(from_const(1).pow_u32_vartime(1), from_const(1));
1991        assert_eq!(from_const(1).pow_u32_vartime(2), from_const(1));
1992        assert_eq!(from_const(2).pow_u32_vartime(0), from_const(1));
1993        assert_eq!(from_const(2).pow_u32_vartime(1), from_const(2));
1994        assert_eq!(from_const(2).pow_u32_vartime(2), from_const(4));
1995        assert_eq!(from_const(2).pow_u32_vartime(3), from_const(8));
1996    }
1997
1998    #[test]
1999    fn test_u64_power() {
2000        assert_eq!(from_const(0).pow_u64(0), from_const(1));
2001        assert_eq!(from_const(0).pow_u64(1), from_const(0));
2002        assert_eq!(from_const(0).pow_u64(2), from_const(0));
2003        assert_eq!(from_const(1).pow_u64(0), from_const(1));
2004        assert_eq!(from_const(1).pow_u64(1), from_const(1));
2005        assert_eq!(from_const(1).pow_u64(2), from_const(1));
2006        assert_eq!(from_const(2).pow_u64(0), from_const(1));
2007        assert_eq!(from_const(2).pow_u64(1), from_const(2));
2008        assert_eq!(from_const(2).pow_u64(2), from_const(4));
2009        assert_eq!(from_const(2).pow_u64(3), from_const(8));
2010    }
2011
2012    #[test]
2013    fn test_u64_power_vartime() {
2014        assert_eq!(from_const(0).pow_u64_vartime(0), from_const(1));
2015        assert_eq!(from_const(0).pow_u64_vartime(1), from_const(0));
2016        assert_eq!(from_const(0).pow_u64_vartime(2), from_const(0));
2017        assert_eq!(from_const(1).pow_u64_vartime(0), from_const(1));
2018        assert_eq!(from_const(1).pow_u64_vartime(1), from_const(1));
2019        assert_eq!(from_const(1).pow_u64_vartime(2), from_const(1));
2020        assert_eq!(from_const(2).pow_u64_vartime(0), from_const(1));
2021        assert_eq!(from_const(2).pow_u64_vartime(1), from_const(2));
2022        assert_eq!(from_const(2).pow_u64_vartime(2), from_const(4));
2023        assert_eq!(from_const(2).pow_u64_vartime(3), from_const(8));
2024    }
2025
2026    #[test]
2027    fn test_integer_division() {
2028        assert_eq!(
2029            from_const(13).div_int(&from_const(5)),
2030            (from_const(2), from_const(3))
2031        );
2032        assert_eq!(
2033            from_const(61).div_int(&from_const(7)),
2034            (from_const(8), from_const(5))
2035        );
2036    }
2037
2038    #[test]
2039    fn test_try_from_le_bytes() {
2040        assert_eq!(
2041            Scalar::try_from_le_bytes(&[
2042                134, 217, 203, 162, 4, 73, 55, 251, 211, 179, 190, 229, 147, 65, 246, 233, 246, 34,
2043                124, 231, 166, 122, 247, 92, 185, 41, 60, 53, 21, 52, 225, 38
2044            ])
2045            .unwrap(),
2046            parse_scalar("0x26e13415353c29b95cf77aa6e77c22f6e9f64193e5beb3d3fb374904a2cbd986")
2047        );
2048        assert_eq!(
2049            Scalar::try_from_le_bytes(&[
2050                94, 15, 32, 74, 182, 189, 242, 78, 168, 143, 91, 154, 184, 98, 85, 163, 142, 220,
2051                154, 67, 53, 216, 247, 158, 226, 97, 86, 13, 82, 137, 175, 54
2052            ])
2053            .unwrap(),
2054            parse_scalar("0x36af89520d5661e29ef7d835439adc8ea35562b89a5b8fa84ef2bdb64a200f5e")
2055        );
2056    }
2057
2058    #[test]
2059    fn test_try_from_be_bytes() {
2060        assert_eq!(
2061            Scalar::try_from_be_bytes(&[
2062                79, 234, 193, 25, 67, 246, 138, 164, 3, 189, 35, 158, 1, 117, 190, 191, 241, 43,
2063                207, 155, 72, 12, 169, 119, 131, 204, 73, 22, 224, 246, 241, 210
2064            ])
2065            .unwrap(),
2066            parse_scalar("0x4feac11943f68aa403bd239e0175bebff12bcf9b480ca97783cc4916e0f6f1d2")
2067        );
2068        assert_eq!(
2069            Scalar::try_from_be_bytes(&[
2070                1, 116, 38, 26, 115, 42, 57, 217, 140, 177, 67, 128, 123, 20, 67, 224, 47, 204,
2071                201, 64, 41, 58, 242, 162, 99, 50, 143, 217, 160, 22, 179, 45
2072            ])
2073            .unwrap(),
2074            parse_scalar("0x0174261a732a39d98cb143807b1443e02fccc940293af2a263328fd9a016b32d")
2075        );
2076    }
2077
2078    #[test]
2079    fn test_parse_binary() {
2080        assert_eq!(Scalar::from_str_radix("0", 2).unwrap(), from_const(0));
2081        assert_eq!(Scalar::from_str_radix("1", 2).unwrap(), from_const(1));
2082        assert_eq!(Scalar::from_str_radix("00", 2).unwrap(), from_const(0));
2083        assert_eq!(Scalar::from_str_radix("01", 2).unwrap(), from_const(1));
2084        assert_eq!(Scalar::from_str_radix("10", 2).unwrap(), from_const(2));
2085        assert_eq!(Scalar::from_str_radix("11", 2).unwrap(), from_const(3));
2086        assert_eq!(
2087            Scalar::from_str_radix("111001111101101101001110101001100101001100111010111110101001000001100110011100111011000000010000000100110100001110110000000010101010011101111011010010000000010111111111111111001011011111111101111111111111111111111111111111011111111111111111111111111111111", 2).unwrap(),
2088            Scalar::MAX - Scalar::ONE
2089        );
2090        assert_eq!(
2091            Scalar::from_str_radix("111001111101101101001110101001100101001100111010111110101001000001100110011100111011000000010000000100110100001110110000000010101010011101111011010010000000010111111111111111001011011111111101111111111111111111111111111111100000000000000000000000000000000", 2).unwrap(),
2092            Scalar::MAX
2093        );
2094        assert!(
2095            Scalar::from_str_radix("111001111101101101001110101001100101001100111010111110101001000001100110011100111011000000010000000100110100001110110000000010101010011101111011010010000000010111111111111111001011011111111101111111111111111111111111111111100000000000000000000000000000001", 2).is_err(),
2096        );
2097    }
2098
2099    #[test]
2100    fn test_print_binary() {
2101        assert_eq!(from_const(0).to_str_radix(2, 0, false), "0");
2102        assert_eq!(from_const(1).to_str_radix(2, 0, false), "1");
2103        assert_eq!(from_const(2).to_str_radix(2, 0, false), "10");
2104        assert_eq!(from_const(3).to_str_radix(2, 0, false), "11");
2105        assert_eq!(from_const(0).to_str_radix(2, 1, false), "0");
2106        assert_eq!(from_const(1).to_str_radix(2, 1, false), "1");
2107        assert_eq!(from_const(2).to_str_radix(2, 1, false), "10");
2108        assert_eq!(from_const(3).to_str_radix(2, 1, false), "11");
2109        assert_eq!(from_const(0).to_str_radix(2, 2, false), "00");
2110        assert_eq!(from_const(1).to_str_radix(2, 2, false), "01");
2111        assert_eq!(from_const(2).to_str_radix(2, 2, false), "10");
2112        assert_eq!(from_const(3).to_str_radix(2, 2, false), "11");
2113        assert_eq!(from_const(0).to_str_radix(2, 3, false), "000");
2114        assert_eq!(from_const(1).to_str_radix(2, 3, false), "001");
2115        assert_eq!(from_const(2).to_str_radix(2, 3, false), "010");
2116        assert_eq!(from_const(3).to_str_radix(2, 3, false), "011");
2117        assert_eq!(
2118            (Scalar::MAX - Scalar::ONE).to_str_radix(2, 0, false),
2119            "111001111101101101001110101001100101001100111010111110101001000001100110011100111011000000010000000100110100001110110000000010101010011101111011010010000000010111111111111111001011011111111101111111111111111111111111111111011111111111111111111111111111111"
2120        );
2121        assert_eq!(
2122            Scalar::MAX.to_str_radix(2, 0, false),
2123            "111001111101101101001110101001100101001100111010111110101001000001100110011100111011000000010000000100110100001110110000000010101010011101111011010010000000010111111111111111001011011111111101111111111111111111111111111111100000000000000000000000000000000"
2124        );
2125    }
2126
2127    #[test]
2128    fn test_parse_octal() {
2129        assert_eq!(Scalar::from_str_radix("0", 8).unwrap(), from_const(0));
2130        assert_eq!(Scalar::from_str_radix("1", 8).unwrap(), from_const(1));
2131        assert_eq!(Scalar::from_str_radix("2", 8).unwrap(), from_const(2));
2132        assert_eq!(Scalar::from_str_radix("6", 8).unwrap(), from_const(6));
2133        assert_eq!(Scalar::from_str_radix("7", 8).unwrap(), from_const(7));
2134        assert!(Scalar::from_str_radix("8", 8).is_err());
2135        assert_eq!(Scalar::from_str_radix("00", 8).unwrap(), from_const(0));
2136        assert_eq!(Scalar::from_str_radix("01", 8).unwrap(), from_const(1));
2137        assert_eq!(Scalar::from_str_radix("02", 8).unwrap(), from_const(2));
2138        assert_eq!(Scalar::from_str_radix("10", 8).unwrap(), from_const(8));
2139        assert_eq!(Scalar::from_str_radix("11", 8).unwrap(), from_const(9));
2140        assert_eq!(Scalar::from_str_radix("12", 8).unwrap(), from_const(10));
2141        assert_eq!(Scalar::from_str_radix("20", 8).unwrap(), from_const(16));
2142        assert_eq!(Scalar::from_str_radix("21", 8).unwrap(), from_const(17));
2143        assert_eq!(Scalar::from_str_radix("22", 8).unwrap(), from_const(18));
2144        assert_eq!(
2145            Scalar::from_str_radix("7175551651451472765101463473002004641660025235732200277777133775777777777737777777777", 8).unwrap(),
2146            Scalar::MAX - Scalar::ONE
2147        );
2148        assert_eq!(
2149            Scalar::from_str_radix("7175551651451472765101463473002004641660025235732200277777133775777777777740000000000", 8).unwrap(),
2150            Scalar::MAX
2151        );
2152        assert!(
2153            Scalar::from_str_radix("7175551651451472765101463473002004641660025235732200277777133775777777777740000000001", 8).is_err(),
2154        );
2155    }
2156
2157    #[test]
2158    fn test_print_octal() {
2159        assert_eq!(from_const(0).to_str_radix(8, 0, false), "0");
2160        assert_eq!(from_const(1).to_str_radix(8, 0, false), "1");
2161        assert_eq!(from_const(2).to_str_radix(8, 0, false), "2");
2162        assert_eq!(from_const(6).to_str_radix(8, 0, false), "6");
2163        assert_eq!(from_const(7).to_str_radix(8, 0, false), "7");
2164        assert_eq!(from_const(8).to_str_radix(8, 0, false), "10");
2165        assert_eq!(from_const(9).to_str_radix(8, 0, false), "11");
2166        assert_eq!(from_const(10).to_str_radix(8, 0, false), "12");
2167        assert_eq!(from_const(0).to_str_radix(8, 1, false), "0");
2168        assert_eq!(from_const(1).to_str_radix(8, 1, false), "1");
2169        assert_eq!(from_const(2).to_str_radix(8, 1, false), "2");
2170        assert_eq!(from_const(6).to_str_radix(8, 1, false), "6");
2171        assert_eq!(from_const(7).to_str_radix(8, 1, false), "7");
2172        assert_eq!(from_const(8).to_str_radix(8, 1, false), "10");
2173        assert_eq!(from_const(9).to_str_radix(8, 1, false), "11");
2174        assert_eq!(from_const(10).to_str_radix(8, 1, false), "12");
2175        assert_eq!(from_const(0).to_str_radix(8, 2, false), "00");
2176        assert_eq!(from_const(1).to_str_radix(8, 2, false), "01");
2177        assert_eq!(from_const(2).to_str_radix(8, 2, false), "02");
2178        assert_eq!(from_const(6).to_str_radix(8, 2, false), "06");
2179        assert_eq!(from_const(7).to_str_radix(8, 2, false), "07");
2180        assert_eq!(from_const(8).to_str_radix(8, 2, false), "10");
2181        assert_eq!(from_const(9).to_str_radix(8, 2, false), "11");
2182        assert_eq!(from_const(10).to_str_radix(8, 2, false), "12");
2183        assert_eq!(from_const(0).to_str_radix(8, 3, false), "000");
2184        assert_eq!(from_const(1).to_str_radix(8, 3, false), "001");
2185        assert_eq!(from_const(2).to_str_radix(8, 3, false), "002");
2186        assert_eq!(from_const(6).to_str_radix(8, 3, false), "006");
2187        assert_eq!(from_const(7).to_str_radix(8, 3, false), "007");
2188        assert_eq!(from_const(8).to_str_radix(8, 3, false), "010");
2189        assert_eq!(from_const(9).to_str_radix(8, 3, false), "011");
2190        assert_eq!(from_const(10).to_str_radix(8, 3, false), "012");
2191        assert_eq!(
2192            (Scalar::MAX - Scalar::ONE).to_str_radix(8, 0, false),
2193            "7175551651451472765101463473002004641660025235732200277777133775777777777737777777777"
2194        );
2195        assert_eq!(
2196            Scalar::MAX.to_str_radix(8, 0, false),
2197            "7175551651451472765101463473002004641660025235732200277777133775777777777740000000000"
2198        );
2199    }
2200
2201    #[test]
2202    fn test_parse_decimal() {
2203        assert_eq!(Scalar::from_str_radix("0", 10).unwrap(), from_const(0));
2204        assert_eq!(Scalar::from_str_radix("1", 10).unwrap(), from_const(1));
2205        assert_eq!(Scalar::from_str_radix("2", 10).unwrap(), from_const(2));
2206        assert_eq!(Scalar::from_str_radix("00", 10).unwrap(), from_const(0));
2207        assert_eq!(Scalar::from_str_radix("01", 10).unwrap(), from_const(1));
2208        assert_eq!(Scalar::from_str_radix("02", 10).unwrap(), from_const(2));
2209        assert_eq!(Scalar::from_str_radix("10", 10).unwrap(), from_const(10));
2210        assert_eq!(Scalar::from_str_radix("11", 10).unwrap(), from_const(11));
2211        assert_eq!(Scalar::from_str_radix("12", 10).unwrap(), from_const(12));
2212        assert_eq!(Scalar::from_str_radix("20", 10).unwrap(), from_const(20));
2213        assert_eq!(Scalar::from_str_radix("21", 10).unwrap(), from_const(21));
2214        assert_eq!(Scalar::from_str_radix("22", 10).unwrap(), from_const(22));
2215        assert_eq!(
2216            Scalar::from_str_radix(
2217                "52435875175126190479447740508185965837690552500527637822603658699938581184511",
2218                10
2219            )
2220            .unwrap(),
2221            Scalar::MAX - Scalar::ONE
2222        );
2223        assert_eq!(
2224            Scalar::from_str_radix(
2225                "52435875175126190479447740508185965837690552500527637822603658699938581184512",
2226                10
2227            )
2228            .unwrap(),
2229            Scalar::MAX
2230        );
2231        assert!(
2232            Scalar::from_str_radix(
2233                "52435875175126190479447740508185965837690552500527637822603658699938581184513",
2234                10
2235            )
2236            .is_err(),
2237        );
2238    }
2239
2240    #[test]
2241    fn test_print_decimal() {
2242        assert_eq!(from_const(0).to_str_radix(10, 0, false), "0");
2243        assert_eq!(from_const(1).to_str_radix(10, 0, false), "1");
2244        assert_eq!(from_const(2).to_str_radix(10, 0, false), "2");
2245        assert_eq!(from_const(9).to_str_radix(10, 0, false), "9");
2246        assert_eq!(from_const(10).to_str_radix(10, 0, false), "10");
2247        assert_eq!(from_const(11).to_str_radix(10, 0, false), "11");
2248        assert_eq!(from_const(0).to_str_radix(10, 1, false), "0");
2249        assert_eq!(from_const(1).to_str_radix(10, 1, false), "1");
2250        assert_eq!(from_const(2).to_str_radix(10, 1, false), "2");
2251        assert_eq!(from_const(9).to_str_radix(10, 1, false), "9");
2252        assert_eq!(from_const(10).to_str_radix(10, 1, false), "10");
2253        assert_eq!(from_const(11).to_str_radix(10, 1, false), "11");
2254        assert_eq!(from_const(0).to_str_radix(10, 2, false), "00");
2255        assert_eq!(from_const(1).to_str_radix(10, 2, false), "01");
2256        assert_eq!(from_const(2).to_str_radix(10, 2, false), "02");
2257        assert_eq!(from_const(9).to_str_radix(10, 2, false), "09");
2258        assert_eq!(from_const(10).to_str_radix(10, 2, false), "10");
2259        assert_eq!(from_const(11).to_str_radix(10, 2, false), "11");
2260        assert_eq!(from_const(0).to_str_radix(10, 3, false), "000");
2261        assert_eq!(from_const(1).to_str_radix(10, 3, false), "001");
2262        assert_eq!(from_const(2).to_str_radix(10, 3, false), "002");
2263        assert_eq!(from_const(9).to_str_radix(10, 3, false), "009");
2264        assert_eq!(from_const(10).to_str_radix(10, 3, false), "010");
2265        assert_eq!(from_const(11).to_str_radix(10, 3, false), "011");
2266        assert_eq!(
2267            (Scalar::MAX - Scalar::ONE).to_str_radix(10, 0, false),
2268            "52435875175126190479447740508185965837690552500527637822603658699938581184511"
2269        );
2270        assert_eq!(
2271            Scalar::MAX.to_str_radix(10, 0, false),
2272            "52435875175126190479447740508185965837690552500527637822603658699938581184512"
2273        );
2274    }
2275
2276    #[test]
2277    fn test_parse_hexadecimal_lower_case() {
2278        assert_eq!(Scalar::from_str_radix("0", 16).unwrap(), from_const(0));
2279        assert_eq!(Scalar::from_str_radix("1", 16).unwrap(), from_const(1));
2280        assert_eq!(Scalar::from_str_radix("2", 16).unwrap(), from_const(2));
2281        assert_eq!(Scalar::from_str_radix("9", 16).unwrap(), from_const(9));
2282        assert_eq!(Scalar::from_str_radix("a", 16).unwrap(), from_const(10));
2283        assert_eq!(Scalar::from_str_radix("e", 16).unwrap(), from_const(14));
2284        assert_eq!(Scalar::from_str_radix("f", 16).unwrap(), from_const(15));
2285        assert!(Scalar::from_str_radix("8", 8).is_err());
2286        assert_eq!(Scalar::from_str_radix("00", 16).unwrap(), from_const(0));
2287        assert_eq!(Scalar::from_str_radix("01", 16).unwrap(), from_const(1));
2288        assert_eq!(Scalar::from_str_radix("02", 16).unwrap(), from_const(2));
2289        assert_eq!(Scalar::from_str_radix("09", 16).unwrap(), from_const(9));
2290        assert_eq!(Scalar::from_str_radix("0a", 16).unwrap(), from_const(10));
2291        assert_eq!(Scalar::from_str_radix("0e", 16).unwrap(), from_const(14));
2292        assert_eq!(Scalar::from_str_radix("0f", 16).unwrap(), from_const(15));
2293        assert_eq!(Scalar::from_str_radix("10", 16).unwrap(), from_const(16));
2294        assert_eq!(Scalar::from_str_radix("11", 16).unwrap(), from_const(17));
2295        assert_eq!(Scalar::from_str_radix("12", 16).unwrap(), from_const(18));
2296        assert_eq!(Scalar::from_str_radix("19", 16).unwrap(), from_const(25));
2297        assert_eq!(Scalar::from_str_radix("1a", 16).unwrap(), from_const(26));
2298        assert_eq!(Scalar::from_str_radix("1e", 16).unwrap(), from_const(30));
2299        assert_eq!(Scalar::from_str_radix("1f", 16).unwrap(), from_const(31));
2300        assert_eq!(Scalar::from_str_radix("20", 16).unwrap(), from_const(32));
2301        assert_eq!(Scalar::from_str_radix("21", 16).unwrap(), from_const(33));
2302        assert_eq!(Scalar::from_str_radix("22", 16).unwrap(), from_const(34));
2303        assert_eq!(
2304            Scalar::from_str_radix(
2305                "73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffeffffffff",
2306                16
2307            )
2308            .unwrap(),
2309            Scalar::MAX - Scalar::ONE
2310        );
2311        assert_eq!(
2312            Scalar::from_str_radix(
2313                "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000",
2314                16
2315            )
2316            .unwrap(),
2317            Scalar::MAX
2318        );
2319        assert!(
2320            Scalar::from_str_radix(
2321                "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001",
2322                16
2323            )
2324            .is_err(),
2325        );
2326    }
2327
2328    #[test]
2329    fn test_print_hexadecimal_lower_case() {
2330        assert_eq!(from_const(0).to_str_radix(16, 0, false), "0");
2331        assert_eq!(from_const(1).to_str_radix(16, 0, false), "1");
2332        assert_eq!(from_const(2).to_str_radix(16, 0, false), "2");
2333        assert_eq!(from_const(9).to_str_radix(16, 0, false), "9");
2334        assert_eq!(from_const(10).to_str_radix(16, 0, false), "a");
2335        assert_eq!(from_const(14).to_str_radix(16, 0, false), "e");
2336        assert_eq!(from_const(15).to_str_radix(16, 0, false), "f");
2337        assert_eq!(from_const(16).to_str_radix(16, 0, false), "10");
2338        assert_eq!(from_const(17).to_str_radix(16, 0, false), "11");
2339        assert_eq!(from_const(18).to_str_radix(16, 0, false), "12");
2340        assert_eq!(from_const(25).to_str_radix(16, 0, false), "19");
2341        assert_eq!(from_const(26).to_str_radix(16, 0, false), "1a");
2342        assert_eq!(from_const(30).to_str_radix(16, 0, false), "1e");
2343        assert_eq!(from_const(31).to_str_radix(16, 0, false), "1f");
2344        assert_eq!(from_const(0).to_str_radix(16, 1, false), "0");
2345        assert_eq!(from_const(1).to_str_radix(16, 1, false), "1");
2346        assert_eq!(from_const(2).to_str_radix(16, 1, false), "2");
2347        assert_eq!(from_const(9).to_str_radix(16, 1, false), "9");
2348        assert_eq!(from_const(10).to_str_radix(16, 1, false), "a");
2349        assert_eq!(from_const(14).to_str_radix(16, 1, false), "e");
2350        assert_eq!(from_const(15).to_str_radix(16, 1, false), "f");
2351        assert_eq!(from_const(16).to_str_radix(16, 1, false), "10");
2352        assert_eq!(from_const(17).to_str_radix(16, 1, false), "11");
2353        assert_eq!(from_const(18).to_str_radix(16, 1, false), "12");
2354        assert_eq!(from_const(25).to_str_radix(16, 1, false), "19");
2355        assert_eq!(from_const(26).to_str_radix(16, 1, false), "1a");
2356        assert_eq!(from_const(30).to_str_radix(16, 1, false), "1e");
2357        assert_eq!(from_const(31).to_str_radix(16, 1, false), "1f");
2358        assert_eq!(from_const(0).to_str_radix(16, 2, false), "00");
2359        assert_eq!(from_const(1).to_str_radix(16, 2, false), "01");
2360        assert_eq!(from_const(2).to_str_radix(16, 2, false), "02");
2361        assert_eq!(from_const(9).to_str_radix(16, 2, false), "09");
2362        assert_eq!(from_const(10).to_str_radix(16, 2, false), "0a");
2363        assert_eq!(from_const(14).to_str_radix(16, 2, false), "0e");
2364        assert_eq!(from_const(15).to_str_radix(16, 2, false), "0f");
2365        assert_eq!(from_const(16).to_str_radix(16, 2, false), "10");
2366        assert_eq!(from_const(17).to_str_radix(16, 2, false), "11");
2367        assert_eq!(from_const(18).to_str_radix(16, 2, false), "12");
2368        assert_eq!(from_const(25).to_str_radix(16, 2, false), "19");
2369        assert_eq!(from_const(26).to_str_radix(16, 2, false), "1a");
2370        assert_eq!(from_const(30).to_str_radix(16, 2, false), "1e");
2371        assert_eq!(from_const(31).to_str_radix(16, 2, false), "1f");
2372        assert_eq!(
2373            (Scalar::MAX - Scalar::ONE).to_str_radix(16, 0, false),
2374            "73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffeffffffff"
2375        );
2376        assert_eq!(
2377            Scalar::MAX.to_str_radix(16, 0, false),
2378            "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"
2379        );
2380    }
2381
2382    #[test]
2383    fn test_parse_hexadecimal_upper_case() {
2384        assert_eq!(Scalar::from_str_radix("0", 16).unwrap(), from_const(0));
2385        assert_eq!(Scalar::from_str_radix("1", 16).unwrap(), from_const(1));
2386        assert_eq!(Scalar::from_str_radix("2", 16).unwrap(), from_const(2));
2387        assert_eq!(Scalar::from_str_radix("9", 16).unwrap(), from_const(9));
2388        assert_eq!(Scalar::from_str_radix("a", 16).unwrap(), from_const(10));
2389        assert_eq!(Scalar::from_str_radix("e", 16).unwrap(), from_const(14));
2390        assert_eq!(Scalar::from_str_radix("f", 16).unwrap(), from_const(15));
2391        assert!(Scalar::from_str_radix("8", 8).is_err());
2392        assert_eq!(Scalar::from_str_radix("00", 16).unwrap(), from_const(0));
2393        assert_eq!(Scalar::from_str_radix("01", 16).unwrap(), from_const(1));
2394        assert_eq!(Scalar::from_str_radix("02", 16).unwrap(), from_const(2));
2395        assert_eq!(Scalar::from_str_radix("09", 16).unwrap(), from_const(9));
2396        assert_eq!(Scalar::from_str_radix("0a", 16).unwrap(), from_const(10));
2397        assert_eq!(Scalar::from_str_radix("0e", 16).unwrap(), from_const(14));
2398        assert_eq!(Scalar::from_str_radix("0f", 16).unwrap(), from_const(15));
2399        assert_eq!(Scalar::from_str_radix("10", 16).unwrap(), from_const(16));
2400        assert_eq!(Scalar::from_str_radix("11", 16).unwrap(), from_const(17));
2401        assert_eq!(Scalar::from_str_radix("12", 16).unwrap(), from_const(18));
2402        assert_eq!(Scalar::from_str_radix("19", 16).unwrap(), from_const(25));
2403        assert_eq!(Scalar::from_str_radix("1a", 16).unwrap(), from_const(26));
2404        assert_eq!(Scalar::from_str_radix("1e", 16).unwrap(), from_const(30));
2405        assert_eq!(Scalar::from_str_radix("1f", 16).unwrap(), from_const(31));
2406        assert_eq!(Scalar::from_str_radix("20", 16).unwrap(), from_const(32));
2407        assert_eq!(Scalar::from_str_radix("21", 16).unwrap(), from_const(33));
2408        assert_eq!(Scalar::from_str_radix("22", 16).unwrap(), from_const(34));
2409        assert_eq!(
2410            Scalar::from_str_radix(
2411                "73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFEFFFFFFFF",
2412                16
2413            )
2414            .unwrap(),
2415            Scalar::MAX - Scalar::ONE
2416        );
2417        assert_eq!(
2418            Scalar::from_str_radix(
2419                "73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000000",
2420                16
2421            )
2422            .unwrap(),
2423            Scalar::MAX
2424        );
2425        assert!(
2426            Scalar::from_str_radix(
2427                "73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001",
2428                16
2429            )
2430            .is_err(),
2431        );
2432    }
2433
2434    #[test]
2435    fn test_print_hexadecimal_upper_case() {
2436        assert_eq!(from_const(0).to_str_radix(16, 0, true), "0");
2437        assert_eq!(from_const(1).to_str_radix(16, 0, true), "1");
2438        assert_eq!(from_const(2).to_str_radix(16, 0, true), "2");
2439        assert_eq!(from_const(9).to_str_radix(16, 0, true), "9");
2440        assert_eq!(from_const(10).to_str_radix(16, 0, true), "A");
2441        assert_eq!(from_const(14).to_str_radix(16, 0, true), "E");
2442        assert_eq!(from_const(15).to_str_radix(16, 0, true), "F");
2443        assert_eq!(from_const(16).to_str_radix(16, 0, true), "10");
2444        assert_eq!(from_const(17).to_str_radix(16, 0, true), "11");
2445        assert_eq!(from_const(18).to_str_radix(16, 0, true), "12");
2446        assert_eq!(from_const(25).to_str_radix(16, 0, true), "19");
2447        assert_eq!(from_const(26).to_str_radix(16, 0, true), "1A");
2448        assert_eq!(from_const(30).to_str_radix(16, 0, true), "1E");
2449        assert_eq!(from_const(31).to_str_radix(16, 0, true), "1F");
2450        assert_eq!(from_const(0).to_str_radix(16, 1, true), "0");
2451        assert_eq!(from_const(1).to_str_radix(16, 1, true), "1");
2452        assert_eq!(from_const(2).to_str_radix(16, 1, true), "2");
2453        assert_eq!(from_const(9).to_str_radix(16, 1, true), "9");
2454        assert_eq!(from_const(10).to_str_radix(16, 1, true), "A");
2455        assert_eq!(from_const(14).to_str_radix(16, 1, true), "E");
2456        assert_eq!(from_const(15).to_str_radix(16, 1, true), "F");
2457        assert_eq!(from_const(16).to_str_radix(16, 1, true), "10");
2458        assert_eq!(from_const(17).to_str_radix(16, 1, true), "11");
2459        assert_eq!(from_const(18).to_str_radix(16, 1, true), "12");
2460        assert_eq!(from_const(25).to_str_radix(16, 1, true), "19");
2461        assert_eq!(from_const(26).to_str_radix(16, 1, true), "1A");
2462        assert_eq!(from_const(30).to_str_radix(16, 1, true), "1E");
2463        assert_eq!(from_const(31).to_str_radix(16, 1, true), "1F");
2464        assert_eq!(from_const(0).to_str_radix(16, 2, true), "00");
2465        assert_eq!(from_const(1).to_str_radix(16, 2, true), "01");
2466        assert_eq!(from_const(2).to_str_radix(16, 2, true), "02");
2467        assert_eq!(from_const(9).to_str_radix(16, 2, true), "09");
2468        assert_eq!(from_const(10).to_str_radix(16, 2, true), "0A");
2469        assert_eq!(from_const(14).to_str_radix(16, 2, true), "0E");
2470        assert_eq!(from_const(15).to_str_radix(16, 2, true), "0F");
2471        assert_eq!(from_const(16).to_str_radix(16, 2, true), "10");
2472        assert_eq!(from_const(17).to_str_radix(16, 2, true), "11");
2473        assert_eq!(from_const(18).to_str_radix(16, 2, true), "12");
2474        assert_eq!(from_const(25).to_str_radix(16, 2, true), "19");
2475        assert_eq!(from_const(26).to_str_radix(16, 2, true), "1A");
2476        assert_eq!(from_const(30).to_str_radix(16, 2, true), "1E");
2477        assert_eq!(from_const(31).to_str_radix(16, 2, true), "1F");
2478        assert_eq!(
2479            (Scalar::MAX - Scalar::ONE).to_str_radix(16, 0, true),
2480            "73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFEFFFFFFFF"
2481        );
2482        assert_eq!(
2483            Scalar::MAX.to_str_radix(16, 0, true),
2484            "73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000000"
2485        );
2486    }
2487
2488    #[test]
2489    fn test_try_to_u8() {
2490        assert_eq!(from_const(0).try_to_u8().unwrap(), 0);
2491        assert_eq!(from_const(1).try_to_u8().unwrap(), 1);
2492        assert_eq!(from_const(2).try_to_u8().unwrap(), 2);
2493        assert_eq!(
2494            from_const(u8::MAX as u64 - 1).try_to_u8().unwrap(),
2495            u8::MAX - 1
2496        );
2497        assert_eq!(from_const(u8::MAX as u64).try_to_u8().unwrap(), u8::MAX);
2498        assert!(from_const(u8::MAX as u64 + 1).try_to_u8().is_none());
2499        assert!(from_const(u8::MAX as u64 + 2).try_to_u8().is_none());
2500    }
2501
2502    #[test]
2503    fn test_try_to_u16() {
2504        assert_eq!(from_const(0).try_to_u16().unwrap(), 0);
2505        assert_eq!(from_const(1).try_to_u16().unwrap(), 1);
2506        assert_eq!(from_const(2).try_to_u16().unwrap(), 2);
2507        assert_eq!(
2508            from_const(u16::MAX as u64 - 1).try_to_u16().unwrap(),
2509            u16::MAX - 1
2510        );
2511        assert_eq!(from_const(u16::MAX as u64).try_to_u16().unwrap(), u16::MAX);
2512        assert!(from_const(u16::MAX as u64 + 1).try_to_u16().is_none());
2513        assert!(from_const(u16::MAX as u64 + 2).try_to_u16().is_none());
2514    }
2515
2516    #[test]
2517    fn test_to_le_bytes() {
2518        assert_eq!(
2519            parse_scalar("0x1caa16ab866063ef3c466732ba591aa9d6b3e7746611979e0219767cfa80fa45")
2520                .to_le_bytes(),
2521            [
2522                69, 250, 128, 250, 124, 118, 25, 2, 158, 151, 17, 102, 116, 231, 179, 214, 169, 26,
2523                89, 186, 50, 103, 70, 60, 239, 99, 96, 134, 171, 22, 170, 28
2524            ]
2525        );
2526        assert_eq!(
2527            parse_scalar("0x645752786f39a23dacbc0c9ff11eead2a96d50b51f4b9519be77e4640668292f")
2528                .to_le_bytes(),
2529            [
2530                47, 41, 104, 6, 100, 228, 119, 190, 25, 149, 75, 31, 181, 80, 109, 169, 210, 234,
2531                30, 241, 159, 12, 188, 172, 61, 162, 57, 111, 120, 82, 87, 100
2532            ]
2533        );
2534    }
2535
2536    #[test]
2537    fn test_to_be_bytes() {
2538        assert_eq!(
2539            parse_scalar("0x376d20d4a3fbc47ab59ecfb4f465eef303180ff9b9ed675492bed81f081d3da9")
2540                .to_be_bytes(),
2541            [
2542                55, 109, 32, 212, 163, 251, 196, 122, 181, 158, 207, 180, 244, 101, 238, 243, 3,
2543                24, 15, 249, 185, 237, 103, 84, 146, 190, 216, 31, 8, 29, 61, 169
2544            ]
2545        );
2546        assert_eq!(
2547            parse_scalar("0x249a87c2d46034a2111064344be35f69e21900a68d30b2e54a3e4e7145adeefa")
2548                .to_be_bytes(),
2549            [
2550                36, 154, 135, 194, 212, 96, 52, 162, 17, 16, 100, 52, 75, 227, 95, 105, 226, 25, 0,
2551                166, 141, 48, 178, 229, 74, 62, 78, 113, 69, 173, 238, 250
2552            ]
2553        );
2554    }
2555
2556    #[test]
2557    fn test_from_u512_mod_n() {
2558        assert_eq!(Scalar::from_u512_mod_n("0".parse().unwrap()), from_const(0));
2559        assert_eq!(Scalar::from_u512_mod_n("1".parse().unwrap()), from_const(1));
2560        assert_eq!(Scalar::from_u512_mod_n("2".parse().unwrap()), from_const(2));
2561        assert_eq!(
2562            Scalar::from_u512_mod_n(
2563                "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffeffffffff"
2564                    .parse()
2565                    .unwrap()
2566            ),
2567            Scalar::MAX - Scalar::ONE
2568        );
2569        assert_eq!(
2570            Scalar::from_u512_mod_n(
2571                "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"
2572                    .parse()
2573                    .unwrap()
2574            ),
2575            Scalar::MAX
2576        );
2577        assert_eq!(
2578            Scalar::from_u512_mod_n(
2579                "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"
2580                    .parse()
2581                    .unwrap()
2582            ),
2583            from_const(0)
2584        );
2585        assert_eq!(
2586            Scalar::from_u512_mod_n(
2587                "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000002"
2588                    .parse()
2589                    .unwrap()
2590            ),
2591            from_const(1)
2592        );
2593    }
2594
2595    #[test]
2596    fn test_try_to_u32() {
2597        assert_eq!(from_const(0).try_to_u32().unwrap(), 0);
2598        assert_eq!(from_const(1).try_to_u32().unwrap(), 1);
2599        assert_eq!(from_const(2).try_to_u32().unwrap(), 2);
2600        assert_eq!(
2601            from_const(u32::MAX as u64 - 1).try_to_u32().unwrap(),
2602            u32::MAX - 1
2603        );
2604        assert_eq!(from_const(u32::MAX as u64).try_to_u32().unwrap(), u32::MAX);
2605        assert!(bool::from(
2606            from_const(u32::MAX as u64 + 1).try_to_u32().is_none()
2607        ));
2608        assert!(bool::from(
2609            from_const(u32::MAX as u64 + 2).try_to_u32().is_none()
2610        ));
2611    }
2612
2613    #[test]
2614    fn test_try_to_u64() {
2615        assert_eq!(from_const(0).try_to_u64().unwrap(), 0);
2616        assert_eq!(from_const(1).try_to_u64().unwrap(), 1);
2617        assert_eq!(from_const(2).try_to_u64().unwrap(), 2);
2618        assert_eq!(from_const(u64::MAX - 1).try_to_u64().unwrap(), u64::MAX - 1);
2619        assert_eq!(from_const(u64::MAX).try_to_u64().unwrap(), u64::MAX);
2620        assert_eq!(
2621            parse_scalar("0xffffffffffffffff").try_to_u64().unwrap(),
2622            u64::MAX
2623        );
2624        assert!(bool::from(
2625            parse_scalar("0x10000000000000000").try_to_u64().is_none()
2626        ));
2627        assert!(bool::from(
2628            parse_scalar("0x10000000000000001").try_to_u64().is_none()
2629        ));
2630    }
2631
2632    #[test]
2633    fn test_try_to_u128() {
2634        assert_eq!(from_const(0).try_to_u128().unwrap(), 0);
2635        assert_eq!(from_const(1).try_to_u128().unwrap(), 1);
2636        assert_eq!(from_const(2).try_to_u128().unwrap(), 2);
2637        assert_eq!(
2638            parse_scalar("0xfffffffffffffffffffffffffffffffe")
2639                .try_to_u128()
2640                .unwrap(),
2641            u128::MAX - 1
2642        );
2643        assert_eq!(
2644            parse_scalar("0xffffffffffffffffffffffffffffffff")
2645                .try_to_u128()
2646                .unwrap(),
2647            u128::MAX
2648        );
2649        assert!(bool::from(
2650            parse_scalar("0x100000000000000000000000000000000")
2651                .try_to_u128()
2652                .is_none()
2653        ));
2654        assert!(bool::from(
2655            parse_scalar("0x100000000000000000000000000000001")
2656                .try_to_u128()
2657                .is_none()
2658        ));
2659    }
2660
2661    #[test]
2662    fn test_to_u256() {
2663        assert_eq!(from_const(0).to_u256(), "0".parse().unwrap());
2664        assert_eq!(from_const(1).to_u256(), "1".parse().unwrap());
2665        assert_eq!(from_const(2).to_u256(), "2".parse().unwrap());
2666        assert_eq!(
2667            (Scalar::MAX - Scalar::ONE).to_u256(),
2668            "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffeffffffff"
2669                .parse()
2670                .unwrap()
2671        );
2672        assert_eq!(
2673            Scalar::MAX.to_u256(),
2674            "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"
2675                .parse()
2676                .unwrap()
2677        );
2678    }
2679
2680    #[test]
2681    fn test_to_u512() {
2682        assert_eq!(from_const(0).to_u512(), "0".parse().unwrap());
2683        assert_eq!(from_const(1).to_u512(), "1".parse().unwrap());
2684        assert_eq!(from_const(2).to_u512(), "2".parse().unwrap());
2685        assert_eq!(
2686            (Scalar::MAX - Scalar::ONE).to_u512(),
2687            "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffeffffffff"
2688                .parse()
2689                .unwrap()
2690        );
2691        assert_eq!(
2692            Scalar::MAX.to_u512(),
2693            "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"
2694                .parse()
2695                .unwrap()
2696        );
2697    }
2698
2699    #[test]
2700    fn test_multiplicative_generator() {
2701        assert_eq!(
2702            Scalar::MULTIPLICATIVE_GENERATOR.to_string(),
2703            format_blst_scalar(<BlstScalar as ff::PrimeField>::MULTIPLICATIVE_GENERATOR)
2704        );
2705        assert_eq!(Scalar::MULTIPLICATIVE_GENERATOR, from_const(7));
2706        assert_eq!(
2707            Scalar::MULTIPLICATIVE_GENERATOR.pow(Scalar::MAX / from_const(1u64 << Scalar::S)),
2708            Scalar::ROOT_OF_UNITY
2709        );
2710    }
2711
2712    #[test]
2713    fn test_minus_two() {
2714        assert_eq!(Scalar::MINUS_TWO, -from_const(2));
2715        assert_eq!(
2716            from_const(42).invert_unwrap(),
2717            from_const(42).pow(Scalar::MINUS_TWO)
2718        );
2719    }
2720
2721    #[test]
2722    fn test_two_inv() {
2723        assert_eq!(Scalar::TWO_INV, from_const(2).invert_unwrap());
2724        assert_eq!(Scalar::TWO_INV.invert_unwrap(), from_const(2));
2725    }
2726
2727    #[test]
2728    fn test_root_of_unity() {
2729        assert_eq!(
2730            Scalar::ROOT_OF_UNITY.to_string(),
2731            format_blst_scalar(<BlstScalar as ff::PrimeField>::ROOT_OF_UNITY)
2732        );
2733        for i in 0..Scalar::S {
2734            assert_ne!(
2735                Scalar::ROOT_OF_UNITY.pow(from_const(1u64 << i)),
2736                Scalar::ONE
2737            );
2738        }
2739        assert_eq!(
2740            Scalar::ROOT_OF_UNITY.pow(from_const(1u64 << Scalar::S)),
2741            Scalar::ONE
2742        );
2743    }
2744
2745    #[test]
2746    fn test_root_of_unity_inverse() {
2747        assert_eq!(
2748            Scalar::ROOT_OF_UNITY_INV.to_string(),
2749            format_blst_scalar(<BlstScalar as ff::PrimeField>::ROOT_OF_UNITY_INV)
2750        );
2751        assert_eq!(
2752            Scalar::ROOT_OF_UNITY_INV,
2753            Scalar::ROOT_OF_UNITY.invert_unwrap()
2754        );
2755    }
2756
2757    #[test]
2758    fn test_delta() {
2759        assert_eq!(
2760            Scalar::DELTA.to_string(),
2761            format_blst_scalar(<BlstScalar as ff::PrimeField>::DELTA)
2762        );
2763        assert_eq!(
2764            Scalar::DELTA,
2765            Scalar::MULTIPLICATIVE_GENERATOR.pow(from_const(1u64 << Scalar::S))
2766        );
2767    }
2768}