Skip to main content

snarkvm_fields/
fp_384.rs

1// Copyright (c) 2019-2026 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::{
17    FftField,
18    Field,
19    FieldError,
20    FieldParameters,
21    LegendreSymbol,
22    One,
23    PoseidonDefaultField,
24    PoseidonDefaultParameters,
25    PrimeField,
26    SquareRootField,
27    Zero,
28    impl_add_sub_from_field_ref,
29    impl_mul_div_from_field_ref,
30};
31use snarkvm_utilities::{
32    FromBytes,
33    ToBits,
34    ToBytes,
35    biginteger::{BigInteger as _BigInteger, BigInteger384 as BigInteger, arithmetic as fa},
36    serialize::CanonicalDeserialize,
37};
38
39use std::{
40    cmp::{Ord, Ordering, PartialOrd},
41    fmt::{Debug, Display, Formatter, Result as FmtResult},
42    io::{Read, Result as IoResult, Write},
43    marker::PhantomData,
44    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
45    str::FromStr,
46};
47use zeroize::Zeroize;
48
49pub trait Fp384Parameters: FieldParameters<BigInteger = BigInteger> {}
50
51#[derive(Copy, Clone, Default, PartialEq, Eq, Hash, Zeroize)]
52pub struct Fp384<P: Fp384Parameters>(pub BigInteger, #[doc(hidden)] pub PhantomData<P>);
53
54impl<P: Fp384Parameters> Fp384<P> {
55    #[inline]
56    pub fn is_valid(&self) -> bool {
57        self.0 < P::MODULUS
58    }
59
60    #[inline]
61    fn reduce(&mut self) {
62        if !self.is_valid() {
63            self.0.sub_noborrow(&P::MODULUS);
64        }
65    }
66
67    #[inline(always)]
68    #[allow(clippy::too_many_arguments)]
69    fn mont_reduce(
70        &mut self,
71        r0: u64,
72        mut r1: u64,
73        mut r2: u64,
74        mut r3: u64,
75        mut r4: u64,
76        mut r5: u64,
77        mut r6: u64,
78        mut r7: u64,
79        mut r8: u64,
80        mut r9: u64,
81        mut r10: u64,
82        mut r11: u64,
83    ) {
84        // The Montgomery reduction here is based on Algorithm 14.32 in
85        // Handbook of Applied Cryptography
86        // <http://cacr.uwaterloo.ca/hac/about/chap14.pdf>.
87
88        let k = r0.wrapping_mul(P::INV);
89        let mut carry = 0;
90        fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry);
91        r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry);
92        r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry);
93        r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry);
94        r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[4], &mut carry);
95        r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[5], &mut carry);
96        carry = fa::adc(&mut r6, 0, carry);
97        let carry2 = carry;
98        let k = r1.wrapping_mul(P::INV);
99        let mut carry = 0;
100        fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry);
101        r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry);
102        r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry);
103        r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry);
104        r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[4], &mut carry);
105        r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[5], &mut carry);
106        carry = fa::adc(&mut r7, carry2, carry);
107        let carry2 = carry;
108        let k = r2.wrapping_mul(P::INV);
109        let mut carry = 0;
110        fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry);
111        r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry);
112        r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry);
113        r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry);
114        r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[4], &mut carry);
115        r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[5], &mut carry);
116        carry = fa::adc(&mut r8, carry2, carry);
117        let carry2 = carry;
118        let k = r3.wrapping_mul(P::INV);
119        let mut carry = 0;
120        fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry);
121        r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry);
122        r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry);
123        r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry);
124        r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[4], &mut carry);
125        r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[5], &mut carry);
126        carry = fa::adc(&mut r9, carry2, carry);
127        let carry2 = carry;
128        let k = r4.wrapping_mul(P::INV);
129        let mut carry = 0;
130        fa::mac_with_carry(r4, k, P::MODULUS.0[0], &mut carry);
131        r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[1], &mut carry);
132        r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[2], &mut carry);
133        r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[3], &mut carry);
134        r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[4], &mut carry);
135        r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[5], &mut carry);
136        carry = fa::adc(&mut r10, carry2, carry);
137        let carry2 = carry;
138        let k = r5.wrapping_mul(P::INV);
139        let mut carry = 0;
140        fa::mac_with_carry(r5, k, P::MODULUS.0[0], &mut carry);
141        r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[1], &mut carry);
142        r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[2], &mut carry);
143        r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[3], &mut carry);
144        r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[4], &mut carry);
145        r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[5], &mut carry);
146        fa::adc(&mut r11, carry2, carry);
147        (self.0).0[0] = r6;
148        (self.0).0[1] = r7;
149        (self.0).0[2] = r8;
150        (self.0).0[3] = r9;
151        (self.0).0[4] = r10;
152        (self.0).0[5] = r11;
153        self.reduce();
154    }
155}
156
157impl<P: Fp384Parameters> Zero for Fp384<P> {
158    #[inline]
159    fn zero() -> Self {
160        Self(BigInteger::from(0), PhantomData)
161    }
162
163    #[inline]
164    fn is_zero(&self) -> bool {
165        self.0.is_zero()
166    }
167}
168
169impl<P: Fp384Parameters> One for Fp384<P> {
170    #[inline]
171    fn one() -> Self {
172        Self(P::R, PhantomData)
173    }
174
175    #[inline]
176    fn is_one(&self) -> bool {
177        self.0 == P::R
178    }
179}
180
181impl<P: Fp384Parameters> Field for Fp384<P> {
182    type BasePrimeField = Self;
183
184    // 384/64 = 6 limbs.
185    impl_field_from_random_bytes_with_flags!(6);
186
187    fn from_base_prime_field(other: Self::BasePrimeField) -> Self {
188        other
189    }
190
191    fn half() -> Self {
192        // Compute 1/2 `(p+1)/2` as `1/2`.
193        // This is cheaper than `Self::one().double().inverse()`
194        let mut two_inv = P::MODULUS;
195        two_inv.add_nocarry(&1u64.into());
196        two_inv.div2();
197        Self::from_bigint(two_inv).unwrap() // Guaranteed to be valid.
198    }
199
200    fn sum_of_products<'a>(a: &'a [Self], b: &'a [Self]) -> Self {
201        // For a single `a x b` multiplication, operand scanning (schoolbook) takes each
202        // limb of `a` in turn, and multiplies it by all of the limbs of `b` to compute
203        // the result as a double-width intermediate representation, which is then fully
204        // reduced at the end. Here however we have pairs of multiplications (a_i, b_i),
205        // the results of which are summed.
206        //
207        // The intuition for this algorithm is two-fold:
208        // - We can interleave the operand scanning for each pair, by processing the jth
209        //   limb of each `a_i` together. As these have the same offset within the overall
210        //   operand scanning flow, their results can be summed directly.
211        // - We can interleave the multiplication and reduction steps, resulting in a
212        //   single bitshift by the limb size after each iteration. This means we only
213        //   need to store a single extra limb overall, instead of keeping around all the
214        //   intermediate results and eventually having twice as many limbs.
215
216        // Algorithm 2, line 2
217        let (u0, u1, u2, u3, u4, u5) = (0..6).fold((0, 0, 0, 0, 0, 0), |(u0, u1, u2, u3, u4, u5), j| {
218            // Algorithm 2, line 3
219            // For each pair in the overall sum of products:
220            let (t0, t1, t2, t3, t4, t5, mut t6) =
221                a.iter().zip(b).fold((u0, u1, u2, u3, u4, u5, 0), |(t0, t1, t2, t3, t4, t5, mut t6), (a, b)| {
222                    // Compute digit_j x row and accumulate into `u`.
223                    let mut carry = 0;
224                    let t0 = fa::mac_with_carry(t0, a.0.0[j], b.0.0[0], &mut carry);
225                    let t1 = fa::mac_with_carry(t1, a.0.0[j], b.0.0[1], &mut carry);
226                    let t2 = fa::mac_with_carry(t2, a.0.0[j], b.0.0[2], &mut carry);
227                    let t3 = fa::mac_with_carry(t3, a.0.0[j], b.0.0[3], &mut carry);
228                    let t4 = fa::mac_with_carry(t4, a.0.0[j], b.0.0[4], &mut carry);
229                    let t5 = fa::mac_with_carry(t5, a.0.0[j], b.0.0[5], &mut carry);
230                    let _ = fa::adc(&mut t6, 0, carry);
231
232                    (t0, t1, t2, t3, t4, t5, t6)
233                });
234
235            // Algorithm 2, lines 4-5
236            // This is a single step of the usual Montgomery reduction process.
237            let k = t0.wrapping_mul(P::INV);
238            let mut carry = 0;
239            let _ = fa::mac_with_carry(t0, k, P::MODULUS.0[0], &mut carry);
240            let r1 = fa::mac_with_carry(t1, k, P::MODULUS.0[1], &mut carry);
241            let r2 = fa::mac_with_carry(t2, k, P::MODULUS.0[2], &mut carry);
242            let r3 = fa::mac_with_carry(t3, k, P::MODULUS.0[3], &mut carry);
243            let r4 = fa::mac_with_carry(t4, k, P::MODULUS.0[4], &mut carry);
244            let r5 = fa::mac_with_carry(t5, k, P::MODULUS.0[5], &mut carry);
245            let _ = fa::adc(&mut t6, 0, carry);
246            let r6 = t6;
247
248            (r1, r2, r3, r4, r5, r6)
249        });
250
251        // Because we represent F_p elements in non-redundant form, we need a final
252        // conditional subtraction to ensure the output is in range.
253        let mut result = Self(BigInteger([u0, u1, u2, u3, u4, u5]), PhantomData);
254        result.reduce();
255        result
256    }
257
258    #[inline]
259    fn double(&self) -> Self {
260        let mut temp = *self;
261        temp.double_in_place();
262        temp
263    }
264
265    #[inline]
266    fn double_in_place(&mut self) {
267        // This cannot exceed the backing capacity.
268        self.0.mul2();
269        // However, it may need to be reduced.
270        self.reduce();
271    }
272
273    #[inline]
274    fn characteristic<'a>() -> &'a [u64] {
275        P::MODULUS.as_ref()
276    }
277
278    #[inline]
279    fn square(&self) -> Self {
280        let mut temp = *self;
281        temp.square_in_place();
282        temp
283    }
284
285    #[inline]
286    fn square_in_place(&mut self) -> &mut Self {
287        let mut carry = 0;
288        let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry);
289        let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry);
290        let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry);
291        let r4 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[4], &mut carry);
292        let r5 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[5], &mut carry);
293        let r6 = carry;
294        let mut carry = 0;
295        let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry);
296        let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry);
297        let r5 = fa::mac_with_carry(r5, (self.0).0[1], (self.0).0[4], &mut carry);
298        let r6 = fa::mac_with_carry(r6, (self.0).0[1], (self.0).0[5], &mut carry);
299        let r7 = carry;
300        let mut carry = 0;
301        let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry);
302        let r6 = fa::mac_with_carry(r6, (self.0).0[2], (self.0).0[4], &mut carry);
303        let r7 = fa::mac_with_carry(r7, (self.0).0[2], (self.0).0[5], &mut carry);
304        let r8 = carry;
305        let mut carry = 0;
306        let r7 = fa::mac_with_carry(r7, (self.0).0[3], (self.0).0[4], &mut carry);
307        let r8 = fa::mac_with_carry(r8, (self.0).0[3], (self.0).0[5], &mut carry);
308        let r9 = carry;
309        let mut carry = 0;
310        let r9 = fa::mac_with_carry(r9, (self.0).0[4], (self.0).0[5], &mut carry);
311        let r10 = carry;
312
313        let mut r11 = r10 >> 63;
314        let r10 = (r10 << 1) | (r9 >> 63);
315        let mut r9 = (r9 << 1) | (r8 >> 63);
316        let r8 = (r8 << 1) | (r7 >> 63);
317        let mut r7 = (r7 << 1) | (r6 >> 63);
318        let r6 = (r6 << 1) | (r5 >> 63);
319        let mut r5 = (r5 << 1) | (r4 >> 63);
320        let r4 = (r4 << 1) | (r3 >> 63);
321        let mut r3 = (r3 << 1) | (r2 >> 63);
322        let r2 = (r2 << 1) | (r1 >> 63);
323        let mut r1 = r1 << 1;
324
325        let mut carry = 0;
326        let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry);
327        carry = fa::adc(&mut r1, 0, carry);
328        let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry);
329        carry = fa::adc(&mut r3, 0, carry);
330        let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry);
331        carry = fa::adc(&mut r5, 0, carry);
332        let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry);
333        carry = fa::adc(&mut r7, 0, carry);
334        let r8 = fa::mac_with_carry(r8, (self.0).0[4], (self.0).0[4], &mut carry);
335        carry = fa::adc(&mut r9, 0, carry);
336        let r10 = fa::mac_with_carry(r10, (self.0).0[5], (self.0).0[5], &mut carry);
337        fa::adc(&mut r11, 0, carry);
338        self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11);
339        self
340    }
341
342    #[inline]
343    fn inverse(&self) -> Option<Self> {
344        if self.is_zero() {
345            None
346        } else {
347            // Guajardo Kumar Paar Pelzl
348            // Efficient Software-Implementation of Finite Fields with Applications to
349            // Cryptography
350            // Algorithm 16 (BEA for Inversion in Fp)
351
352            let one = BigInteger::from(1);
353
354            let mut u = self.0;
355            let mut v = P::MODULUS;
356            let mut b = Self(P::R2, PhantomData); // Avoids unnecessary reduction step.
357            let mut c = Self::zero();
358
359            while u != one && v != one {
360                while u.is_even() {
361                    u.div2();
362
363                    if b.0.is_even() {
364                        b.0.div2();
365                    } else {
366                        b.0.add_nocarry(&P::MODULUS);
367                        b.0.div2();
368                    }
369                }
370
371                while v.is_even() {
372                    v.div2();
373
374                    if c.0.is_even() {
375                        c.0.div2();
376                    } else {
377                        c.0.add_nocarry(&P::MODULUS);
378                        c.0.div2();
379                    }
380                }
381
382                if v < u {
383                    u.sub_noborrow(&v);
384                    b.sub_assign(&c);
385                } else {
386                    v.sub_noborrow(&u);
387                    c.sub_assign(&b);
388                }
389            }
390
391            if u == one { Some(b) } else { Some(c) }
392        }
393    }
394
395    fn inverse_in_place(&mut self) -> Option<&mut Self> {
396        if let Some(inverse) = self.inverse() {
397            *self = inverse;
398            Some(self)
399        } else {
400            None
401        }
402    }
403
404    #[inline]
405    fn frobenius_map(&mut self, _: usize) {
406        // No-op: No effect in a prime field.
407    }
408}
409
410impl<P: Fp384Parameters> PrimeField for Fp384<P> {
411    type BigInteger = BigInteger;
412    type Parameters = P;
413
414    #[inline]
415    fn from_bigint(r: BigInteger) -> Option<Self> {
416        let mut r = Fp384(r, PhantomData);
417        if r.is_zero() {
418            Some(r)
419        } else if r.is_valid() {
420            r *= &Fp384(P::R2, PhantomData);
421            Some(r)
422        } else {
423            None
424        }
425    }
426
427    #[inline]
428    fn to_bigint(&self) -> BigInteger {
429        let mut tmp = self.0;
430        let mut r = tmp.0;
431        // Montgomery Reduction
432        let k = r[0].wrapping_mul(P::INV);
433        let mut carry = 0;
434        fa::mac_with_carry(r[0], k, P::MODULUS.0[0], &mut carry);
435        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry);
436        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry);
437        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry);
438        r[4] = fa::mac_with_carry(r[4], k, P::MODULUS.0[4], &mut carry);
439        r[5] = fa::mac_with_carry(r[5], k, P::MODULUS.0[5], &mut carry);
440        r[0] = carry;
441
442        let k = r[1].wrapping_mul(P::INV);
443        let mut carry = 0;
444        fa::mac_with_carry(r[1], k, P::MODULUS.0[0], &mut carry);
445        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[1], &mut carry);
446        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[2], &mut carry);
447        r[4] = fa::mac_with_carry(r[4], k, P::MODULUS.0[3], &mut carry);
448        r[5] = fa::mac_with_carry(r[5], k, P::MODULUS.0[4], &mut carry);
449        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[5], &mut carry);
450        r[1] = carry;
451
452        let k = r[2].wrapping_mul(P::INV);
453        let mut carry = 0;
454        fa::mac_with_carry(r[2], k, P::MODULUS.0[0], &mut carry);
455        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[1], &mut carry);
456        r[4] = fa::mac_with_carry(r[4], k, P::MODULUS.0[2], &mut carry);
457        r[5] = fa::mac_with_carry(r[5], k, P::MODULUS.0[3], &mut carry);
458        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[4], &mut carry);
459        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[5], &mut carry);
460        r[2] = carry;
461
462        let k = r[3].wrapping_mul(P::INV);
463        let mut carry = 0;
464        fa::mac_with_carry(r[3], k, P::MODULUS.0[0], &mut carry);
465        r[4] = fa::mac_with_carry(r[4], k, P::MODULUS.0[1], &mut carry);
466        r[5] = fa::mac_with_carry(r[5], k, P::MODULUS.0[2], &mut carry);
467        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[3], &mut carry);
468        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[4], &mut carry);
469        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[5], &mut carry);
470        r[3] = carry;
471
472        let k = r[4].wrapping_mul(P::INV);
473        let mut carry = 0;
474        fa::mac_with_carry(r[4], k, P::MODULUS.0[0], &mut carry);
475        r[5] = fa::mac_with_carry(r[5], k, P::MODULUS.0[1], &mut carry);
476        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[2], &mut carry);
477        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[3], &mut carry);
478        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[4], &mut carry);
479        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[5], &mut carry);
480        r[4] = carry;
481
482        let k = r[5].wrapping_mul(P::INV);
483        let mut carry = 0;
484        fa::mac_with_carry(r[5], k, P::MODULUS.0[0], &mut carry);
485        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[1], &mut carry);
486        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[2], &mut carry);
487        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[3], &mut carry);
488        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[4], &mut carry);
489        r[4] = fa::mac_with_carry(r[4], k, P::MODULUS.0[5], &mut carry);
490        r[5] = carry;
491
492        tmp.0 = r;
493        tmp
494    }
495
496    #[inline]
497    fn decompose(
498        &self,
499        _q1: &[u64; 4],
500        _q2: &[u64; 4],
501        _b1: Self,
502        _b2: Self,
503        _r128: Self,
504        _half_r: &[u64; 8],
505    ) -> (Self, Self, bool, bool) {
506        unimplemented!()
507    }
508}
509
510impl<P: Fp384Parameters> FftField for Fp384<P> {
511    type FftParameters = P;
512
513    #[inline]
514    fn two_adic_root_of_unity() -> Self {
515        Self(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData)
516    }
517
518    #[inline]
519    fn large_subgroup_root_of_unity() -> Option<Self> {
520        Some(Self(P::LARGE_SUBGROUP_ROOT_OF_UNITY?, PhantomData))
521    }
522
523    #[inline]
524    fn multiplicative_generator() -> Self {
525        Self(P::GENERATOR, PhantomData)
526    }
527}
528
529impl<P: Fp384Parameters> SquareRootField for Fp384<P> {
530    #[inline]
531    fn legendre(&self) -> LegendreSymbol {
532        use crate::LegendreSymbol::*;
533
534        // s = self^((MODULUS - 1) // 2)
535        let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO);
536
537        if s.is_zero() {
538            Zero
539        } else if s.is_one() {
540            QuadraticResidue
541        } else {
542            QuadraticNonResidue
543        }
544    }
545
546    #[inline]
547    fn sqrt(&self) -> Option<Self> {
548        sqrt_impl!(Self, P, self)
549    }
550
551    fn sqrt_in_place(&mut self) -> Option<&mut Self> {
552        (*self).sqrt().map(|sqrt| {
553            *self = sqrt;
554            self
555        })
556    }
557}
558
559/// `Fp` elements are ordered lexicographically.
560impl<P: Fp384Parameters> Ord for Fp384<P> {
561    #[inline(always)]
562    fn cmp(&self, other: &Self) -> Ordering {
563        self.to_bigint().cmp(&other.to_bigint())
564    }
565}
566
567impl<P: Fp384Parameters> PartialOrd for Fp384<P> {
568    #[inline(always)]
569    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
570        Some(self.cmp(other))
571    }
572}
573
574impl<P: Fp384Parameters + PoseidonDefaultParameters> PoseidonDefaultField for Fp384<P> {}
575
576impl_primefield_from_int!(Fp384, u128, Fp384Parameters);
577impl_primefield_from_int!(Fp384, u64, Fp384Parameters);
578impl_primefield_from_int!(Fp384, u32, Fp384Parameters);
579impl_primefield_from_int!(Fp384, u16, Fp384Parameters);
580impl_primefield_from_int!(Fp384, u8, Fp384Parameters);
581
582impl_primefield_standard_sample!(Fp384, Fp384Parameters);
583
584impl_add_sub_from_field_ref!(Fp384, Fp384Parameters);
585impl_mul_div_from_field_ref!(Fp384, Fp384Parameters);
586
587impl<P: Fp384Parameters> ToBits for Fp384<P> {
588    fn write_bits_le(&self, vec: &mut Vec<bool>) {
589        let initial_len = vec.len();
590        self.to_bigint().write_bits_le(vec);
591        vec.truncate(initial_len + P::MODULUS_BITS as usize);
592    }
593
594    fn write_bits_be(&self, vec: &mut Vec<bool>) {
595        let initial_len = vec.len();
596        self.write_bits_le(vec);
597        vec[initial_len..].reverse();
598    }
599
600    fn num_bits() -> Option<usize> {
601        Some(384)
602    }
603}
604
605impl<P: Fp384Parameters> ToBytes for Fp384<P> {
606    #[inline]
607    fn write_le<W: Write>(&self, writer: W) -> IoResult<()> {
608        self.to_bigint().write_le(writer)
609    }
610}
611
612impl<P: Fp384Parameters> FromBytes for Fp384<P> {
613    #[inline]
614    fn read_le<R: Read>(reader: R) -> IoResult<Self> {
615        BigInteger::read_le(reader).and_then(|b| match Self::from_bigint(b) {
616            Some(f) => Ok(f),
617            None => Err(FieldError::InvalidFieldElement.into()),
618        })
619    }
620}
621
622impl<P: Fp384Parameters> FromStr for Fp384<P> {
623    type Err = FieldError;
624
625    /// Interpret a string of numbers as a (congruent) prime field element.
626    /// Does not accept unnecessary leading zeroes or a blank string.
627    fn from_str(s: &str) -> Result<Self, Self::Err> {
628        if s.is_empty() {
629            return Err(FieldError::ParsingEmptyString);
630        }
631
632        if s == "0" {
633            return Ok(Self::zero());
634        }
635
636        let mut res = Self::zero();
637
638        let ten =
639            Self::from_bigint(<Self as PrimeField>::BigInteger::from(10)).ok_or(FieldError::InvalidFieldElement)?;
640
641        let mut first_digit = true;
642
643        for c in s.chars() {
644            match c.to_digit(10) {
645                Some(c) => {
646                    if first_digit {
647                        if c == 0 {
648                            return Err(FieldError::InvalidString);
649                        }
650
651                        first_digit = false;
652                    }
653
654                    res.mul_assign(&ten);
655                    res.add_assign(
656                        &Self::from_bigint(<Self as PrimeField>::BigInteger::from(u64::from(c)))
657                            .ok_or(FieldError::InvalidFieldElement)?,
658                    );
659                }
660                None => return Err(FieldError::ParsingNonDigitCharacter),
661            }
662        }
663
664        if !res.is_valid() { Err(FieldError::InvalidFieldElement) } else { Ok(res) }
665    }
666}
667
668impl<P: Fp384Parameters> Debug for Fp384<P> {
669    #[inline]
670    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
671        write!(f, "{}", self.to_bigint())
672    }
673}
674
675impl<P: Fp384Parameters> Display for Fp384<P> {
676    #[inline]
677    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
678        write!(f, "{}", self.to_bigint())
679    }
680}
681
682impl<P: Fp384Parameters> Neg for Fp384<P> {
683    type Output = Self;
684
685    #[inline]
686    fn neg(self) -> Self {
687        if !self.is_zero() {
688            let mut tmp = P::MODULUS;
689            tmp.sub_noborrow(&self.0);
690            Self(tmp, PhantomData)
691        } else {
692            self
693        }
694    }
695}
696
697impl<P: Fp384Parameters> Add<&'_ Fp384<P>> for Fp384<P> {
698    type Output = Self;
699
700    #[inline]
701    fn add(self, other: &Self) -> Self {
702        let mut result = self;
703        result.add_assign(other);
704        result
705    }
706}
707
708impl<P: Fp384Parameters> Sub<&'_ Fp384<P>> for Fp384<P> {
709    type Output = Self;
710
711    #[inline]
712    fn sub(self, other: &Self) -> Self {
713        let mut result = self;
714        result.sub_assign(other);
715        result
716    }
717}
718
719impl<P: Fp384Parameters> Mul<&'_ Fp384<P>> for Fp384<P> {
720    type Output = Self;
721
722    #[inline]
723    fn mul(self, other: &Self) -> Self {
724        let mut result = self;
725        result.mul_assign(other);
726        result
727    }
728}
729
730impl<P: Fp384Parameters> Div<&'_ Fp384<P>> for Fp384<P> {
731    type Output = Self;
732
733    #[inline]
734    fn div(self, other: &Self) -> Self {
735        let mut result = self;
736        result.mul_assign(&other.inverse().unwrap());
737        result
738    }
739}
740
741impl<P: Fp384Parameters> AddAssign<&'_ Self> for Fp384<P> {
742    #[inline]
743    fn add_assign(&mut self, other: &Self) {
744        // This cannot exceed the backing capacity.
745        self.0.add_nocarry(&other.0);
746        // However, it may need to be reduced.
747        self.reduce();
748    }
749}
750
751impl<P: Fp384Parameters> SubAssign<&'_ Self> for Fp384<P> {
752    #[inline]
753    fn sub_assign(&mut self, other: &Self) {
754        // If `other` is larger than `self`, add the modulus to self first.
755        if other.0 > self.0 {
756            self.0.add_nocarry(&P::MODULUS);
757        }
758
759        self.0.sub_noborrow(&other.0);
760    }
761}
762
763impl<P: Fp384Parameters> MulAssign<&'_ Self> for Fp384<P> {
764    #[inline]
765    fn mul_assign(&mut self, other: &Self) {
766        let mut r = [0u64; 6];
767        let mut carry1 = 0u64;
768        let mut carry2 = 0u64;
769
770        // Iteration 0.
771        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[0], &mut carry1);
772        let k = r[0].wrapping_mul(P::INV);
773        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
774        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[0], &mut carry1);
775        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
776
777        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[0], &mut carry1);
778        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
779
780        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[0], &mut carry1);
781        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
782
783        r[4] = fa::mac_with_carry(r[4], (self.0).0[4], (other.0).0[0], &mut carry1);
784        r[3] = fa::mac_with_carry(r[4], k, P::MODULUS.0[4], &mut carry2);
785
786        r[5] = fa::mac_with_carry(r[5], (self.0).0[5], (other.0).0[0], &mut carry1);
787        r[4] = fa::mac_with_carry(r[5], k, P::MODULUS.0[5], &mut carry2);
788        r[5] = carry1 + carry2;
789
790        // Iteration 1.
791        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[1], &mut carry1);
792        let k = r[0].wrapping_mul(P::INV);
793        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
794        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[1], &mut carry1);
795        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
796
797        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[1], &mut carry1);
798        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
799
800        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[1], &mut carry1);
801        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
802
803        r[4] = fa::mac_with_carry(r[4], (self.0).0[4], (other.0).0[1], &mut carry1);
804        r[3] = fa::mac_with_carry(r[4], k, P::MODULUS.0[4], &mut carry2);
805
806        r[5] = fa::mac_with_carry(r[5], (self.0).0[5], (other.0).0[1], &mut carry1);
807        r[4] = fa::mac_with_carry(r[5], k, P::MODULUS.0[5], &mut carry2);
808        r[5] = carry1 + carry2;
809
810        // Iteration 2.
811        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[2], &mut carry1);
812        let k = r[0].wrapping_mul(P::INV);
813        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
814        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[2], &mut carry1);
815        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
816
817        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[2], &mut carry1);
818        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
819
820        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[2], &mut carry1);
821        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
822
823        r[4] = fa::mac_with_carry(r[4], (self.0).0[4], (other.0).0[2], &mut carry1);
824        r[3] = fa::mac_with_carry(r[4], k, P::MODULUS.0[4], &mut carry2);
825
826        r[5] = fa::mac_with_carry(r[5], (self.0).0[5], (other.0).0[2], &mut carry1);
827        r[4] = fa::mac_with_carry(r[5], k, P::MODULUS.0[5], &mut carry2);
828        r[5] = carry1 + carry2;
829
830        // Iteration 3.
831        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[3], &mut carry1);
832        let k = r[0].wrapping_mul(P::INV);
833        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
834        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[3], &mut carry1);
835        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
836
837        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[3], &mut carry1);
838        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
839
840        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[3], &mut carry1);
841        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
842
843        r[4] = fa::mac_with_carry(r[4], (self.0).0[4], (other.0).0[3], &mut carry1);
844        r[3] = fa::mac_with_carry(r[4], k, P::MODULUS.0[4], &mut carry2);
845
846        r[5] = fa::mac_with_carry(r[5], (self.0).0[5], (other.0).0[3], &mut carry1);
847        r[4] = fa::mac_with_carry(r[5], k, P::MODULUS.0[5], &mut carry2);
848        r[5] = carry1 + carry2;
849
850        // Iteration 4.
851        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[4], &mut carry1);
852        let k = r[0].wrapping_mul(P::INV);
853        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
854        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[4], &mut carry1);
855        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
856
857        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[4], &mut carry1);
858        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
859
860        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[4], &mut carry1);
861        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
862
863        r[4] = fa::mac_with_carry(r[4], (self.0).0[4], (other.0).0[4], &mut carry1);
864        r[3] = fa::mac_with_carry(r[4], k, P::MODULUS.0[4], &mut carry2);
865
866        r[5] = fa::mac_with_carry(r[5], (self.0).0[5], (other.0).0[4], &mut carry1);
867        r[4] = fa::mac_with_carry(r[5], k, P::MODULUS.0[5], &mut carry2);
868        r[5] = carry1 + carry2;
869
870        // Iteration 5.
871        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[5], &mut carry1);
872        let k = r[0].wrapping_mul(P::INV);
873        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
874        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[5], &mut carry1);
875        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
876
877        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[5], &mut carry1);
878        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
879
880        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[5], &mut carry1);
881        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
882
883        r[4] = fa::mac_with_carry(r[4], (self.0).0[4], (other.0).0[5], &mut carry1);
884        r[3] = fa::mac_with_carry(r[4], k, P::MODULUS.0[4], &mut carry2);
885
886        r[5] = fa::mac_with_carry(r[5], (self.0).0[5], (other.0).0[5], &mut carry1);
887        r[4] = fa::mac_with_carry(r[5], k, P::MODULUS.0[5], &mut carry2);
888        r[5] = carry1 + carry2;
889
890        (self.0).0 = r;
891        self.reduce();
892    }
893}
894
895impl<P: Fp384Parameters> DivAssign<&'_ Self> for Fp384<P> {
896    #[inline]
897    fn div_assign(&mut self, other: &Self) {
898        self.mul_assign(&other.inverse().unwrap());
899    }
900}