Skip to main content

snarkvm_fields/
fp6_3over2.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::{Field, Fp2, Fp2Parameters, One, Zero};
17use snarkvm_utilities::{
18    FromBytes,
19    ToBits,
20    ToBytes,
21    rand::Uniform,
22    serialize::{SerializationError, *},
23};
24
25use rand::{
26    Rng,
27    distr::{Distribution, StandardUniform},
28};
29use serde::{Deserialize, Serialize};
30use std::{
31    cmp::Ordering,
32    fmt::Debug,
33    hash::Hash,
34    io::{Read, Result as IoResult, Write},
35    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
36};
37
38pub trait Fp6Parameters: 'static + Copy + Clone + Default + Debug + PartialEq + Eq + Hash + Send + Sync {
39    type Fp2Params: Fp2Parameters;
40
41    /// Coefficients for the Frobenius automorphism.
42    const FROBENIUS_COEFF_FP6_C1: [Fp2<Self::Fp2Params>; 6];
43    const FROBENIUS_COEFF_FP6_C2: [Fp2<Self::Fp2Params>; 6];
44
45    const NONRESIDUE: Fp2<Self::Fp2Params>;
46
47    #[inline(always)]
48    fn mul_fp2_by_nonresidue(fe: &Fp2<Self::Fp2Params>) -> Fp2<Self::Fp2Params> {
49        Self::NONRESIDUE * fe
50    }
51}
52
53/// An element of Fp6, represented by c0 + c1 * v + c2 * v^(2).
54#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
55pub struct Fp6<P: Fp6Parameters> {
56    pub c0: Fp2<P::Fp2Params>,
57    pub c1: Fp2<P::Fp2Params>,
58    pub c2: Fp2<P::Fp2Params>,
59}
60
61impl<P: Fp6Parameters> Fp6<P> {
62    /// Initializes an element of `Fp6` from 3 `Fp2` elements.
63    pub const fn new(c0: Fp2<P::Fp2Params>, c1: Fp2<P::Fp2Params>, c2: Fp2<P::Fp2Params>) -> Self {
64        Self { c0, c1, c2 }
65    }
66
67    pub fn mul_by_fp(&mut self, element: &<P::Fp2Params as Fp2Parameters>::Fp) {
68        self.c0.mul_by_fp(element);
69        self.c1.mul_by_fp(element);
70        self.c2.mul_by_fp(element);
71    }
72
73    pub fn mul_by_fp2(&mut self, element: &Fp2<P::Fp2Params>) {
74        self.c0.mul_assign(element);
75        self.c1.mul_assign(element);
76        self.c2.mul_assign(element);
77    }
78
79    pub fn mul_by_1(&mut self, c1: &Fp2<P::Fp2Params>) {
80        let mut b_b = self.c1;
81        b_b.mul_assign(c1);
82
83        let mut t1 = *c1;
84        {
85            let mut tmp = self.c1;
86            tmp.add_assign(self.c2);
87
88            t1.mul_assign(&tmp);
89            t1.sub_assign(&b_b);
90            t1 = P::mul_fp2_by_nonresidue(&t1);
91        }
92
93        let mut t2 = *c1;
94        {
95            let mut tmp = self.c0;
96            tmp.add_assign(self.c1);
97
98            t2.mul_assign(&tmp);
99            t2.sub_assign(&b_b);
100        }
101
102        self.c0 = t1;
103        self.c1 = t2;
104        self.c2 = b_b;
105    }
106
107    pub fn mul_by_01(&mut self, c0: &Fp2<P::Fp2Params>, c1: &Fp2<P::Fp2Params>) {
108        let mut a_a = self.c0;
109        let mut b_b = self.c1;
110        a_a.mul_assign(c0);
111        b_b.mul_assign(c1);
112
113        let mut t1 = *c1;
114        {
115            let mut tmp = self.c1;
116            tmp.add_assign(self.c2);
117
118            t1.mul_assign(&tmp);
119            t1.sub_assign(&b_b);
120            t1 = P::mul_fp2_by_nonresidue(&t1);
121            t1.add_assign(a_a);
122        }
123
124        let mut t3 = *c0;
125        {
126            let mut tmp = self.c0;
127            tmp.add_assign(self.c2);
128
129            t3.mul_assign(&tmp);
130            t3.sub_assign(&a_a);
131            t3.add_assign(b_b);
132        }
133
134        let mut t2 = *c0;
135        t2.add_assign(c1);
136        {
137            let mut tmp = self.c0;
138            tmp.add_assign(self.c1);
139
140            t2.mul_assign(&tmp);
141            t2.sub_assign(&a_a);
142            t2.sub_assign(&b_b);
143        }
144
145        self.c0 = t1;
146        self.c1 = t2;
147        self.c2 = t3;
148    }
149}
150
151impl<P: Fp6Parameters> Zero for Fp6<P> {
152    fn zero() -> Self {
153        Self::new(Fp2::zero(), Fp2::zero(), Fp2::zero())
154    }
155
156    fn is_zero(&self) -> bool {
157        self.c0.is_zero() && self.c1.is_zero() && self.c2.is_zero()
158    }
159}
160
161impl<P: Fp6Parameters> One for Fp6<P> {
162    fn one() -> Self {
163        Self::new(Fp2::one(), Fp2::zero(), Fp2::zero())
164    }
165
166    fn is_one(&self) -> bool {
167        self.c0.is_one() && self.c1.is_zero() && self.c2.is_zero()
168    }
169}
170
171impl<P: Fp6Parameters> Field for Fp6<P> {
172    type BasePrimeField = <Fp2<P::Fp2Params> as Field>::BasePrimeField;
173
174    fn from_base_prime_field(other: Self::BasePrimeField) -> Self {
175        Self::new(Fp2::from_base_prime_field(other), Fp2::zero(), Fp2::zero())
176    }
177
178    #[inline]
179    fn characteristic<'a>() -> &'a [u64] {
180        Fp2::<P::Fp2Params>::characteristic()
181    }
182
183    fn double(&self) -> Self {
184        let mut result = *self;
185        result.double_in_place();
186        result
187    }
188
189    fn double_in_place(&mut self) {
190        self.c0.double_in_place();
191        self.c1.double_in_place();
192        self.c2.double_in_place();
193    }
194
195    #[inline]
196    fn from_random_bytes_with_flags<F: Flags>(bytes: &[u8]) -> Option<(Self, F)> {
197        let split_at = bytes.len() / 3;
198        if let Some(c0) = Fp2::<P::Fp2Params>::from_random_bytes(&bytes[..split_at])
199            && let Some(c1) = Fp2::<P::Fp2Params>::from_random_bytes(&bytes[split_at..2 * split_at])
200            && let Some((c2, flags)) = Fp2::<P::Fp2Params>::from_random_bytes_with_flags::<F>(&bytes[2 * split_at..])
201        {
202            return Some((Fp6::new(c0, c1, c2), flags));
203        }
204        None
205    }
206
207    #[inline]
208    fn from_random_bytes(bytes: &[u8]) -> Option<Self> {
209        Self::from_random_bytes_with_flags::<EmptyFlags>(bytes).map(|f| f.0)
210    }
211
212    fn square(&self) -> Self {
213        let mut result = *self;
214        result.square_in_place();
215        result
216    }
217
218    fn square_in_place(&mut self) -> &mut Self {
219        let s0 = self.c0.square();
220        let s1 = (self.c0 * self.c1).double();
221        let s2 = (self.c0 - self.c1 + self.c2).square();
222        let s3 = (self.c1 * self.c2).double();
223        let s4 = self.c2.square();
224
225        self.c0 = s0 + P::mul_fp2_by_nonresidue(&s3);
226        self.c1 = s1 + P::mul_fp2_by_nonresidue(&s4);
227        self.c2 = s1 + s2 + s3 - s0 - s4;
228
229        self
230    }
231
232    fn inverse(&self) -> Option<Self> {
233        if self.is_zero() {
234            None
235        } else {
236            let mut c0 = self.c2;
237            c0 = P::mul_fp2_by_nonresidue(&c0);
238            c0.mul_assign(&self.c1);
239            c0 = c0.neg();
240            {
241                let mut c0s = self.c0;
242                c0s.square_in_place();
243                c0.add_assign(c0s);
244            }
245            let mut c1 = self.c2;
246            c1.square_in_place();
247            c1 = P::mul_fp2_by_nonresidue(&c1);
248            {
249                let mut c01 = self.c0;
250                c01.mul_assign(&self.c1);
251                c1.sub_assign(&c01);
252            }
253            let mut c2 = self.c1;
254            c2.square_in_place();
255            {
256                let mut c02 = self.c0;
257                c02.mul_assign(&self.c2);
258                c2.sub_assign(&c02);
259            }
260
261            let mut tmp1 = self.c2;
262            tmp1.mul_assign(&c1);
263            let mut tmp2 = self.c1;
264            tmp2.mul_assign(&c2);
265            tmp1.add_assign(tmp2);
266            tmp1 = P::mul_fp2_by_nonresidue(&tmp1);
267            tmp2 = self.c0;
268            tmp2.mul_assign(&c0);
269            tmp1.add_assign(tmp2);
270
271            tmp1.inverse().map(|t| Self::new(t * c0, t * c1, t * c2))
272        }
273    }
274
275    fn inverse_in_place(&mut self) -> Option<&mut Self> {
276        if let Some(inverse) = self.inverse() {
277            *self = inverse;
278            Some(self)
279        } else {
280            None
281        }
282    }
283
284    fn frobenius_map(&mut self, power: usize) {
285        self.c0.frobenius_map(power);
286        self.c1.frobenius_map(power);
287        self.c2.frobenius_map(power);
288
289        self.c1.mul_assign(&P::FROBENIUS_COEFF_FP6_C1[power % 6]);
290        self.c2.mul_assign(&P::FROBENIUS_COEFF_FP6_C2[power % 6]);
291    }
292}
293
294impl<P: Fp6Parameters> std::fmt::Display for Fp6<P> {
295    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        write!(f, "Fq6_3over2({} + {} * v, {} * v^2)", self.c0, self.c1, self.c2)
297    }
298}
299
300impl<P: Fp6Parameters> Distribution<Fp6<P>> for StandardUniform {
301    #[inline]
302    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Fp6<P> {
303        Fp6::new(Uniform::rand(rng), Uniform::rand(rng), Uniform::rand(rng))
304    }
305}
306
307impl<P: Fp6Parameters> Neg for Fp6<P> {
308    type Output = Self;
309
310    #[inline]
311    fn neg(self) -> Self {
312        let mut copy = Self::zero();
313        copy.c0 = self.c0.neg();
314        copy.c1 = self.c1.neg();
315        copy.c2 = self.c2.neg();
316        copy
317    }
318}
319
320impl_add_sub_from_field_ref!(Fp6, Fp6Parameters);
321impl_mul_div_from_field_ref!(Fp6, Fp6Parameters);
322
323impl<P: Fp6Parameters> Add<&'_ Self> for Fp6<P> {
324    type Output = Self;
325
326    #[inline]
327    fn add(self, other: &Self) -> Self {
328        let mut result = self;
329        result.add_assign(other);
330        result
331    }
332}
333
334impl<P: Fp6Parameters> Sub<&'_ Self> for Fp6<P> {
335    type Output = Self;
336
337    #[inline]
338    fn sub(self, other: &Self) -> Self {
339        let mut result = self;
340        result.sub_assign(&other);
341        result
342    }
343}
344
345impl<P: Fp6Parameters> Mul<&'_ Self> for Fp6<P> {
346    type Output = Self;
347
348    #[inline]
349    fn mul(self, other: &Self) -> Self {
350        let mut result = self;
351        result.mul_assign(&other);
352        result
353    }
354}
355
356impl<P: Fp6Parameters> Div<&'_ Self> for Fp6<P> {
357    type Output = Self;
358
359    #[inline]
360    fn div(self, other: &Self) -> Self {
361        let mut result = self;
362        result.mul_assign(&other.inverse().unwrap());
363        result
364    }
365}
366
367impl<P: Fp6Parameters> AddAssign<&'_ Self> for Fp6<P> {
368    #[inline]
369    fn add_assign(&mut self, other: &Self) {
370        self.c0 += &other.c0;
371        self.c1 += &other.c1;
372        self.c2 += &other.c2;
373    }
374}
375
376impl<P: Fp6Parameters> SubAssign<&'_ Self> for Fp6<P> {
377    #[inline]
378    fn sub_assign(&mut self, other: &Self) {
379        self.c0 -= &other.c0;
380        self.c1 -= &other.c1;
381        self.c2 -= &other.c2;
382    }
383}
384
385impl<P: Fp6Parameters> MulAssign<&'_ Self> for Fp6<P> {
386    #[inline]
387    fn mul_assign(&mut self, other: &Self) {
388        let v0 = self.c0 * other.c0;
389        let v1 = self.c1 * other.c1;
390        let v2 = self.c2 * other.c2;
391
392        let c0 = P::mul_fp2_by_nonresidue(&((self.c1 + self.c2) * (other.c1 + other.c2) - v1 - v2)) + v0;
393        let c1 = (self.c0 + self.c1) * (other.c0 + other.c1) - v0 - v1 + P::mul_fp2_by_nonresidue(&v2);
394        let c2 = (self.c0 + self.c2) * (other.c0 + other.c2) - v0 - v2 + v1;
395
396        self.c0 = c0;
397        self.c1 = c1;
398        self.c2 = c2;
399    }
400}
401
402impl<P: Fp6Parameters> DivAssign<&'_ Self> for Fp6<P> {
403    #[inline]
404    fn div_assign(&mut self, other: &Self) {
405        self.mul_assign(&other.inverse().unwrap());
406    }
407}
408
409impl<P: Fp6Parameters> From<&'_ [bool]> for Fp6<P> {
410    fn from(_bits: &[bool]) -> Self {
411        unimplemented!()
412    }
413}
414
415/// `Fp3` elements are ordered lexicographically.
416impl<P: Fp6Parameters> Ord for Fp6<P> {
417    #[inline(always)]
418    fn cmp(&self, other: &Self) -> Ordering {
419        let c2_cmp = self.c2.cmp(&other.c2);
420        let c1_cmp = self.c1.cmp(&other.c1);
421        let c0_cmp = self.c0.cmp(&other.c0);
422        match c2_cmp {
423            Ordering::Equal => match c1_cmp {
424                Ordering::Equal => c0_cmp,
425                _ => c1_cmp,
426            },
427            _ => c2_cmp,
428        }
429    }
430}
431
432impl<P: Fp6Parameters> PartialOrd for Fp6<P> {
433    #[inline(always)]
434    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
435        Some(self.cmp(other))
436    }
437}
438
439impl<P: Fp6Parameters> From<u128> for Fp6<P> {
440    fn from(other: u128) -> Self {
441        Self::new(other.into(), Fp2::zero(), Fp2::zero())
442    }
443}
444
445impl<P: Fp6Parameters> From<u64> for Fp6<P> {
446    fn from(other: u64) -> Self {
447        Self::new(other.into(), Fp2::zero(), Fp2::zero())
448    }
449}
450
451impl<P: Fp6Parameters> From<u32> for Fp6<P> {
452    fn from(other: u32) -> Self {
453        Self::new(other.into(), Fp2::zero(), Fp2::zero())
454    }
455}
456
457impl<P: Fp6Parameters> From<u16> for Fp6<P> {
458    fn from(other: u16) -> Self {
459        Self::new(other.into(), Fp2::zero(), Fp2::zero())
460    }
461}
462
463impl<P: Fp6Parameters> From<u8> for Fp6<P> {
464    fn from(other: u8) -> Self {
465        Self::new(other.into(), Fp2::zero(), Fp2::zero())
466    }
467}
468
469impl<P: Fp6Parameters> ToBits for Fp6<P> {
470    fn write_bits_le(&self, vec: &mut Vec<bool>) {
471        self.c0.write_bits_le(vec);
472        self.c1.write_bits_le(vec);
473        self.c2.write_bits_le(vec);
474    }
475
476    fn write_bits_be(&self, vec: &mut Vec<bool>) {
477        self.c0.write_bits_be(vec);
478        self.c1.write_bits_be(vec);
479        self.c2.write_bits_be(vec);
480    }
481}
482
483impl<P: Fp6Parameters> ToBytes for Fp6<P> {
484    #[inline]
485    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
486        self.c0.write_le(&mut writer)?;
487        self.c1.write_le(&mut writer)?;
488        self.c2.write_le(&mut writer)
489    }
490}
491
492impl<P: Fp6Parameters> FromBytes for Fp6<P> {
493    #[inline]
494    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
495        let c0 = Fp2::read_le(&mut reader)?;
496        let c1 = Fp2::read_le(&mut reader)?;
497        let c2 = Fp2::read_le(&mut reader)?;
498        Ok(Fp6::new(c0, c1, c2))
499    }
500}
501
502impl<P: Fp6Parameters> CanonicalSerializeWithFlags for Fp6<P> {
503    #[inline]
504    fn serialize_with_flags<W: Write, F: Flags>(&self, mut writer: W, flags: F) -> Result<(), SerializationError> {
505        CanonicalSerialize::serialize_uncompressed(&self.c0, &mut writer)?;
506        CanonicalSerialize::serialize_uncompressed(&self.c1, &mut writer)?;
507        self.c2.serialize_with_flags(writer, flags)?;
508        Ok(())
509    }
510
511    fn serialized_size_with_flags<F: Flags>(&self) -> usize {
512        self.c0.uncompressed_size() + self.c1.uncompressed_size() + self.c2.serialized_size_with_flags::<F>()
513    }
514}
515
516impl<P: Fp6Parameters> CanonicalSerialize for Fp6<P> {
517    #[inline]
518    fn serialize_with_mode<W: Write>(&self, writer: W, _compress: Compress) -> Result<(), SerializationError> {
519        self.serialize_with_flags(writer, EmptyFlags)
520    }
521
522    #[inline]
523    fn serialized_size(&self, compress: Compress) -> usize {
524        self.c0.serialized_size(compress) + self.c1.serialized_size(compress) + self.c2.serialized_size(compress)
525    }
526}
527
528impl<P: Fp6Parameters> Valid for Fp6<P> {
529    fn check(&self) -> Result<(), snarkvm_utilities::SerializationError> {
530        Ok(())
531    }
532
533    fn batch_check<'a>(_batch: impl Iterator<Item = &'a Self>) -> Result<(), snarkvm_utilities::SerializationError>
534    where
535        Self: 'a,
536    {
537        Ok(())
538    }
539}
540
541impl<P: Fp6Parameters> CanonicalDeserializeWithFlags for Fp6<P> {
542    #[inline]
543    fn deserialize_with_flags<R: Read, F: Flags>(mut reader: R) -> Result<(Self, F), SerializationError> {
544        let c0 = CanonicalDeserialize::deserialize_uncompressed(&mut reader)?;
545        let c1 = CanonicalDeserialize::deserialize_uncompressed(&mut reader)?;
546        let (c2, flags): (_, _) = CanonicalDeserializeWithFlags::deserialize_with_flags(&mut reader)?;
547        Ok((Fp6::new(c0, c1, c2), flags))
548    }
549}
550
551impl<P: Fp6Parameters> CanonicalDeserialize for Fp6<P> {
552    #[inline]
553    fn deserialize_with_mode<R: Read>(
554        mut reader: R,
555        compress: Compress,
556        validate: Validate,
557    ) -> Result<Self, SerializationError> {
558        let c0 = CanonicalDeserialize::deserialize_with_mode(&mut reader, compress, validate)?;
559        let c1 = CanonicalDeserialize::deserialize_with_mode(&mut reader, compress, validate)?;
560        let c2 = CanonicalDeserialize::deserialize_with_mode(&mut reader, compress, validate)?;
561        Ok(Fp6::new(c0, c1, c2))
562    }
563}