arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
ark-r1cs-std/r1cs-std/src/fields/fp2.rs
r1cs-std/src/fields/fp2.rsRaw
  1use algebra::{
  2    fields::{Fp2, Fp2Parameters},
  3    PrimeField,
  4};
  5use core::{borrow::Borrow, marker::PhantomData};
  6use r1cs_core::{ConstraintSystem, ConstraintVar, SynthesisError};
  7
  8use crate::{fields::fp::FpGadget, prelude::*, Vec};
  9
 10#[derive(Derivative)]
 11#[derivative(Debug(bound = "P: Fp2Parameters, ConstraintF: PrimeField"))]
 12#[must_use]
 13pub struct Fp2Gadget<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> {
 14    pub c0: FpGadget<ConstraintF>,
 15    pub c1: FpGadget<ConstraintF>,
 16    #[derivative(Debug = "ignore")]
 17    _params: PhantomData<P>,
 18}
 19
 20impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> Fp2Gadget<P, ConstraintF> {
 21    pub fn new(c0: FpGadget<ConstraintF>, c1: FpGadget<ConstraintF>) -> Self {
 22        Self {
 23            c0,
 24            c1,
 25            _params: PhantomData,
 26        }
 27    }
 28
 29    /// Multiply a FpGadget by quadratic nonresidue P::NONRESIDUE.
 30    #[inline]
 31    pub fn mul_fp_gadget_by_nonresidue<CS: ConstraintSystem<ConstraintF>>(
 32        cs: CS,
 33        fe: &FpGadget<ConstraintF>,
 34    ) -> Result<FpGadget<ConstraintF>, SynthesisError> {
 35        fe.mul_by_constant(cs, &P::NONRESIDUE)
 36    }
 37
 38    /// Multiply a Fp2Gadget by an element of fp.
 39    #[inline]
 40    pub fn mul_by_fp_constant_in_place<CS: ConstraintSystem<ConstraintF>>(
 41        &mut self,
 42        mut cs: CS,
 43        fe: &P::Fp,
 44    ) -> Result<&mut Self, SynthesisError> {
 45        self.c0.mul_by_constant_in_place(cs.ns(|| "c0"), fe)?;
 46        self.c1.mul_by_constant_in_place(cs.ns(|| "c1"), fe)?;
 47        Ok(self)
 48    }
 49
 50    /// Multiply a Fp2Gadget by an element of fp.
 51    #[inline]
 52    pub fn mul_by_fp_constant<CS: ConstraintSystem<ConstraintF>>(
 53        &self,
 54        cs: CS,
 55        fe: &P::Fp,
 56    ) -> Result<Self, SynthesisError> {
 57        let mut result = self.clone();
 58        result.mul_by_fp_constant_in_place(cs, fe)?;
 59        Ok(result)
 60    }
 61}
 62
 63impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> FieldGadget<Fp2<P>, ConstraintF>
 64    for Fp2Gadget<P, ConstraintF>
 65{
 66    type Variable = (ConstraintVar<ConstraintF>, ConstraintVar<ConstraintF>);
 67
 68    #[inline]
 69    fn get_value(&self) -> Option<Fp2<P>> {
 70        match (self.c0.value, self.c1.value) {
 71            (Some(c0), Some(c1)) => Some(Fp2::new(c0, c1)),
 72            (..) => None,
 73        }
 74    }
 75
 76    #[inline]
 77    fn get_variable(&self) -> Self::Variable {
 78        (self.c0.get_variable(), self.c1.get_variable())
 79    }
 80
 81    #[inline]
 82    fn zero<CS: ConstraintSystem<ConstraintF>>(mut cs: CS) -> Result<Self, SynthesisError> {
 83        let c0 = FpGadget::zero(cs.ns(|| "c0"))?;
 84        let c1 = FpGadget::zero(cs.ns(|| "c1"))?;
 85        Ok(Self::new(c0, c1))
 86    }
 87
 88    #[inline]
 89    fn one<CS: ConstraintSystem<ConstraintF>>(mut cs: CS) -> Result<Self, SynthesisError> {
 90        let c0 = FpGadget::one(cs.ns(|| "c0"))?;
 91        let c1 = FpGadget::zero(cs.ns(|| "c1"))?;
 92        Ok(Self::new(c0, c1))
 93    }
 94
 95    #[inline]
 96    fn conditionally_add_constant<CS: ConstraintSystem<ConstraintF>>(
 97        &self,
 98        mut cs: CS,
 99        bit: &Boolean,
100        coeff: Fp2<P>,
101    ) -> Result<Self, SynthesisError> {
102        let c0 = self
103            .c0
104            .conditionally_add_constant(cs.ns(|| "c0"), bit, coeff.c0)?;
105        let c1 = self
106            .c1
107            .conditionally_add_constant(cs.ns(|| "c1"), bit, coeff.c1)?;
108        Ok(Self::new(c0, c1))
109    }
110
111    #[inline]
112    fn add<CS: ConstraintSystem<ConstraintF>>(
113        &self,
114        mut cs: CS,
115        other: &Self,
116    ) -> Result<Self, SynthesisError> {
117        let c0 = self.c0.add(&mut cs.ns(|| "add c0"), &other.c0)?;
118        let c1 = self.c1.add(&mut cs.ns(|| "add c1"), &other.c1)?;
119        Ok(Self::new(c0, c1))
120    }
121
122    #[inline]
123    fn sub<CS: ConstraintSystem<ConstraintF>>(
124        &self,
125        mut cs: CS,
126        other: &Self,
127    ) -> Result<Self, SynthesisError> {
128        let c0 = self.c0.sub(&mut cs.ns(|| "sub c0"), &other.c0)?;
129        let c1 = self.c1.sub(&mut cs.ns(|| "sub c1"), &other.c1)?;
130        Ok(Self::new(c0, c1))
131    }
132
133    #[inline]
134    fn double<CS: ConstraintSystem<ConstraintF>>(&self, cs: CS) -> Result<Self, SynthesisError> {
135        let mut result = self.clone();
136        result.double_in_place(cs)?;
137        Ok(result)
138    }
139
140    #[inline]
141    fn double_in_place<CS: ConstraintSystem<ConstraintF>>(
142        &mut self,
143        mut cs: CS,
144    ) -> Result<&mut Self, SynthesisError> {
145        self.c0.double_in_place(&mut cs.ns(|| "double c0"))?;
146        self.c1.double_in_place(&mut cs.ns(|| "double c1"))?;
147        Ok(self)
148    }
149
150    #[inline]
151    fn negate<CS: ConstraintSystem<ConstraintF>>(&self, cs: CS) -> Result<Self, SynthesisError> {
152        let mut result = self.clone();
153        result.negate_in_place(cs)?;
154        Ok(result)
155    }
156
157    #[inline]
158    fn negate_in_place<CS: ConstraintSystem<ConstraintF>>(
159        &mut self,
160        mut cs: CS,
161    ) -> Result<&mut Self, SynthesisError> {
162        self.c0.negate_in_place(&mut cs.ns(|| "negate c0"))?;
163        self.c1.negate_in_place(&mut cs.ns(|| "negate c1"))?;
164        Ok(self)
165    }
166
167    #[inline]
168    fn mul<CS: ConstraintSystem<ConstraintF>>(
169        &self,
170        mut cs: CS,
171        other: &Self,
172    ) -> Result<Self, SynthesisError> {
173        // Karatsuba multiplication for Fp2:
174        //     v0 = A.c0 * B.c0
175        //     v1 = A.c1 * B.c1
176        //     result.c0 = v0 + non_residue * v1
177        //     result.c1 = (A.c0 + A.c1) * (B.c0 + B.c1) - v0 - v1
178        // Enforced with 3 constraints:
179        //     A.c1 * B.c1 = v1
180        //     A.c0 * B.c0 = result.c0 - non_residue * v1
181        //     (A.c0+A.c1)*(B.c0+B.c1) = result.c1 + result.c0 + (1 - non_residue) * v1
182        // Reference:
183        // "Multiplication and Squaring on Pairing-Friendly Fields"
184        // Devegili, OhEigeartaigh, Scott, Dahab
185        let mul_cs = &mut cs.ns(|| "mul");
186
187        let v0 = self.c0.mul(mul_cs.ns(|| "v0"), &other.c0)?;
188        let v1 = self.c1.mul(mul_cs.ns(|| "v1"), &other.c1)?;
189        let c0 = {
190            let non_residue_times_v1 =
191                v1.mul_by_constant(mul_cs.ns(|| "non_residue * v0"), &P::NONRESIDUE)?;
192            v0.add(mul_cs.ns(|| "v0 + beta * v1"), &non_residue_times_v1)?
193        };
194        let c1 = {
195            let a0_plus_a1 = self.c0.add(mul_cs.ns(|| "a0 + a1"), &self.c1)?;
196            let b0_plus_b1 = other.c0.add(mul_cs.ns(|| "b0 + b1"), &other.c1)?;
197            let a0_plus_a1_times_b0_plus_b1 =
198                a0_plus_a1.mul(&mut mul_cs.ns(|| "(a0 + a1) * (b0 + b1)"), &b0_plus_b1)?;
199            a0_plus_a1_times_b0_plus_b1
200                .sub(mul_cs.ns(|| "res - v0"), &v0)?
201                .sub(mul_cs.ns(|| "res - v0 - v1"), &v1)?
202        };
203        Ok(Self::new(c0, c1))
204    }
205
206    #[inline]
207    fn square<CS: ConstraintSystem<ConstraintF>>(
208        &self,
209        mut cs: CS,
210    ) -> Result<Self, SynthesisError> {
211        // From Libsnark/fp2_gadget.tcc
212        // Complex multiplication for Fp2:
213        //     v0 = A.c0 * A.c1
214        //     result.c0 = (A.c0 + A.c1) * (A.c0 + non_residue * A.c1) - (1 +
215        // non_residue) * v0     result.c1 = 2 * v0
216        // Enforced with 2 constraints:
217        //     (2*A.c0) * A.c1 = result.c1
218        //     (A.c0 + A.c1) * (A.c0 + non_residue * A.c1) = result.c0 + result.c1 * (1
219        // + non_residue)/2 Reference:
220        //     "Multiplication and Squaring on Pairing-Friendly Fields"
221        //     Devegili, OhEigeartaigh, Scott, Dahab
222
223        let mut v0 = self.c0.mul(cs.ns(|| "v0"), &self.c1)?;
224        let a0_plus_a1 = self.c0.add(cs.ns(|| "a0 + a1"), &self.c1)?;
225
226        let non_residue_c1 = self
227            .c1
228            .mul_by_constant(cs.ns(|| "non_residue * a1"), &P::NONRESIDUE)?;
229        let a0_plus_non_residue_c1 = self
230            .c0
231            .add(cs.ns(|| "a0 + non_residue * a1"), &non_residue_c1)?;
232        let one_plus_non_residue_v0 = v0.mul_by_constant(
233            cs.ns(|| "1 + non_residue * v0"),
234            &(P::Fp::one() + &P::NONRESIDUE),
235        )?;
236
237        let c0 = a0_plus_a1
238            .mul(
239                cs.ns(|| "(a0 + a1) * (a0 + non_residue * a1)"),
240                &a0_plus_non_residue_c1,
241            )?
242            .sub(cs.ns(|| "- (1 + non_residue) v0"), &one_plus_non_residue_v0)?;
243
244        v0.double_in_place(cs.ns(|| "2v0"))?;
245        let c1 = v0;
246
247        Ok(Self::new(c0, c1))
248    }
249
250    #[inline]
251    fn square_in_place<CS: ConstraintSystem<ConstraintF>>(
252        &mut self,
253        mut cs: CS,
254    ) -> Result<&mut Self, SynthesisError> {
255        // From Libsnark/fp2_gadget.tcc
256        // Complex multiplication for Fp2:
257        //     v0 = A.c0 * A.c1
258        //     result.c0 = (A.c0 + A.c1) * (A.c0 + non_residue * A.c1) - (1 +
259        // non_residue) * v0     result.c1 = 2 * v0
260        // Enforced with 2 constraints:
261        //     (2*A.c0) * A.c1 = result.c1
262        //     (A.c0 + A.c1) * (A.c0 + non_residue * A.c1) = result.c0 + result.c1 * (1
263        // + non_residue)/2 Reference:
264        //     "Multiplication and Squaring on Pairing-Friendly Fields"
265        //     Devegili, OhEigeartaigh, Scott, Dahab
266
267        let mut v0 = self.c0.mul(cs.ns(|| "v0"), &self.c1)?;
268        let a0_plus_a1 = self.c0.add(cs.ns(|| "a0 + a1"), &self.c1)?;
269
270        let _ = self
271            .c1
272            .mul_by_constant_in_place(cs.ns(|| "non_residue * a1"), &P::NONRESIDUE)?;
273        let a0_plus_non_residue_c1 = self.c0.add(cs.ns(|| "a0 + non_residue * a1"), &self.c1)?;
274        let one_plus_non_residue_v0 = v0.mul_by_constant(
275            cs.ns(|| "1 + non_residue * v0"),
276            &(P::Fp::one() + &P::NONRESIDUE),
277        )?;
278
279        self.c0 = a0_plus_a1
280            .mul(
281                cs.ns(|| "(a0 + a1) * (a0 + non_residue * a1)"),
282                &a0_plus_non_residue_c1,
283            )?
284            .sub(cs.ns(|| "- (1 + non_residue) v0"), &one_plus_non_residue_v0)?;
285
286        v0.double_in_place(cs.ns(|| "2v0"))?;
287        self.c1 = v0;
288
289        Ok(self)
290    }
291
292    fn mul_equals<CS: ConstraintSystem<ConstraintF>>(
293        &self,
294        mut cs: CS,
295        other: &Self,
296        result: &Self,
297    ) -> Result<(), SynthesisError> {
298        // Karatsuba multiplication for Fp2:
299        //     v0 = A.c0 * B.c0
300        //     v1 = A.c1 * B.c1
301        //     result.c0 = v0 + non_residue * v1
302        //     result.c1 = (A.c0 + A.c1) * (B.c0 + B.c1) - v0 - v1
303        // Enforced with 3 constraints:
304        //     A.c1 * B.c1 = v1
305        //     A.c0 * B.c0 = result.c0 - non_residue * v1
306        //     (A.c0+A.c1)*(B.c0+B.c1) = result.c1 + result.c0 + (1 - non_residue) * v1
307        // Reference:
308        // "Multiplication and Squaring on Pairing-Friendly Fields"
309        // Devegili, OhEigeartaigh, Scott, Dahab
310        let mul_cs = &mut cs.ns(|| "mul");
311
312        // Compute v1
313        let mut v1 = self.c1.mul(mul_cs.ns(|| "v1"), &other.c1)?;
314
315        // Perform second check
316        let non_residue_times_v1 =
317            v1.mul_by_constant(mul_cs.ns(|| "non_residue * v0"), &P::NONRESIDUE)?;
318        let rhs = result
319            .c0
320            .sub(mul_cs.ns(|| "sub from result.c0"), &non_residue_times_v1)?;
321        self.c0
322            .mul_equals(mul_cs.ns(|| "second check"), &other.c0, &rhs)?;
323
324        // Last check
325        let a0_plus_a1 = self.c0.add(mul_cs.ns(|| "a0 + a1"), &self.c1)?;
326        let b0_plus_b1 = other.c0.add(mul_cs.ns(|| "b0 + b1"), &other.c1)?;
327        let one_minus_non_residue_v1 =
328            v1.sub_in_place(mul_cs.ns(|| "sub from v1"), &non_residue_times_v1)?;
329
330        let result_c1_plus_result_c0_plus_one_minus_non_residue_v1 = result
331            .c1
332            .add(mul_cs.ns(|| "c1 + c0"), &result.c0)?
333            .add(mul_cs.ns(|| "rest of stuff"), one_minus_non_residue_v1)?;
334
335        a0_plus_a1.mul_equals(
336            mul_cs.ns(|| "third check"),
337            &b0_plus_b1,
338            &result_c1_plus_result_c0_plus_one_minus_non_residue_v1,
339        )?;
340
341        Ok(())
342    }
343
344    fn frobenius_map<CS: ConstraintSystem<ConstraintF>>(
345        &self,
346        cs: CS,
347        power: usize,
348    ) -> Result<Self, SynthesisError> {
349        let mut result = self.clone();
350        let _ = result.frobenius_map_in_place(cs, power)?;
351        Ok(result)
352    }
353
354    fn frobenius_map_in_place<CS: ConstraintSystem<ConstraintF>>(
355        &mut self,
356        cs: CS,
357        power: usize,
358    ) -> Result<&mut Self, SynthesisError> {
359        self.c1
360            .mul_by_constant_in_place(cs, &P::FROBENIUS_COEFF_FP2_C1[power % 2])?;
361        Ok(self)
362    }
363
364    #[inline]
365    fn add_constant<CS: ConstraintSystem<ConstraintF>>(
366        &self,
367        cs: CS,
368        other: &Fp2<P>,
369    ) -> Result<Self, SynthesisError> {
370        let mut result = self.clone();
371        let _ = result.add_constant_in_place(cs, other)?;
372        Ok(result)
373    }
374
375    #[inline]
376    fn add_constant_in_place<CS: ConstraintSystem<ConstraintF>>(
377        &mut self,
378        mut cs: CS,
379        other: &Fp2<P>,
380    ) -> Result<&mut Self, SynthesisError> {
381        self.c0.add_constant_in_place(cs.ns(|| "c0"), &other.c0)?;
382        self.c1.add_constant_in_place(cs.ns(|| "c1"), &other.c1)?;
383        Ok(self)
384    }
385
386    fn mul_by_constant<CS: ConstraintSystem<ConstraintF>>(
387        &self,
388        mut cs: CS,
389        fe: &Fp2<P>,
390    ) -> Result<Self, SynthesisError> {
391        // Karatsuba multiplication (see mul above).
392        // Doesn't need any constraints; returns linear combinations of
393        // `self`'s variables.
394        //
395        // (The operations below are guaranteed to return linear combinations)
396        let (a0, a1) = (&self.c0, &self.c1);
397        let (b0, b1) = (fe.c0, fe.c1);
398        let mut v0 = a0.mul_by_constant(&mut cs.ns(|| "v0"), &b0)?;
399        let beta_v1 = a1.mul_by_constant(&mut cs.ns(|| "v1"), &(b1 * &P::NONRESIDUE))?;
400
401        v0.add_in_place(&mut cs.ns(|| "c0"), &beta_v1)?;
402        let c0 = v0;
403
404        let mut a0b1 = a0.mul_by_constant(&mut cs.ns(|| "a0b1"), &b1)?;
405        let a1b0 = a1.mul_by_constant(&mut cs.ns(|| "a1b0"), &b0)?;
406        a0b1.add_in_place(&mut cs.ns(|| "c1"), &a1b0)?;
407        let c1 = a0b1;
408        Ok(Self::new(c0, c1))
409    }
410
411    fn cost_of_mul() -> usize {
412        3 * FpGadget::<ConstraintF>::cost_of_mul()
413    }
414
415    fn cost_of_mul_equals() -> usize {
416        Self::cost_of_mul()
417    }
418}
419
420impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> PartialEq
421    for Fp2Gadget<P, ConstraintF>
422{
423    fn eq(&self, other: &Self) -> bool {
424        self.c0 == other.c0 && self.c1 == other.c1
425    }
426}
427
428impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> Eq for Fp2Gadget<P, ConstraintF> {}
429
430impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> EqGadget<ConstraintF>
431    for Fp2Gadget<P, ConstraintF>
432{
433}
434
435impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> ConditionalEqGadget<ConstraintF>
436    for Fp2Gadget<P, ConstraintF>
437{
438    #[inline]
439    fn conditional_enforce_equal<CS: ConstraintSystem<ConstraintF>>(
440        &self,
441        mut cs: CS,
442        other: &Self,
443        condition: &Boolean,
444    ) -> Result<(), SynthesisError> {
445        self.c0
446            .conditional_enforce_equal(&mut cs.ns(|| "c0"), &other.c0, condition)?;
447        self.c1
448            .conditional_enforce_equal(&mut cs.ns(|| "c1"), &other.c1, condition)?;
449        Ok(())
450    }
451
452    fn cost() -> usize {
453        2
454    }
455}
456
457impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> NEqGadget<ConstraintF>
458    for Fp2Gadget<P, ConstraintF>
459{
460    #[inline]
461    fn enforce_not_equal<CS: ConstraintSystem<ConstraintF>>(
462        &self,
463        mut cs: CS,
464        other: &Self,
465    ) -> Result<(), SynthesisError> {
466        self.c0.enforce_not_equal(&mut cs.ns(|| "c0"), &other.c0)?;
467        self.c1.enforce_not_equal(&mut cs.ns(|| "c1"), &other.c1)?;
468        Ok(())
469    }
470
471    fn cost() -> usize {
472        2
473    }
474}
475
476impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> ToBitsGadget<ConstraintF>
477    for Fp2Gadget<P, ConstraintF>
478{
479    fn to_bits<CS: ConstraintSystem<ConstraintF>>(
480        &self,
481        mut cs: CS,
482    ) -> Result<Vec<Boolean>, SynthesisError> {
483        let mut c0 = self.c0.to_bits(cs.ns(|| "c0"))?;
484        let mut c1 = self.c1.to_bits(cs.ns(|| "c1"))?;
485        c0.append(&mut c1);
486        Ok(c0)
487    }
488
489    fn to_non_unique_bits<CS: ConstraintSystem<ConstraintF>>(
490        &self,
491        mut cs: CS,
492    ) -> Result<Vec<Boolean>, SynthesisError> {
493        let mut c0 = self.c0.to_non_unique_bits(cs.ns(|| "c0"))?;
494        let mut c1 = self.c1.to_non_unique_bits(cs.ns(|| "c1"))?;
495        c0.append(&mut c1);
496        Ok(c0)
497    }
498}
499
500impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> ToBytesGadget<ConstraintF>
501    for Fp2Gadget<P, ConstraintF>
502{
503    fn to_bytes<CS: ConstraintSystem<ConstraintF>>(
504        &self,
505        mut cs: CS,
506    ) -> Result<Vec<UInt8>, SynthesisError> {
507        let mut c0 = self.c0.to_bytes(cs.ns(|| "c0"))?;
508        let mut c1 = self.c1.to_bytes(cs.ns(|| "c1"))?;
509        c0.append(&mut c1);
510        Ok(c0)
511    }
512
513    fn to_non_unique_bytes<CS: ConstraintSystem<ConstraintF>>(
514        &self,
515        mut cs: CS,
516    ) -> Result<Vec<UInt8>, SynthesisError> {
517        let mut c0 = self.c0.to_non_unique_bytes(cs.ns(|| "c0"))?;
518        let mut c1 = self.c1.to_non_unique_bytes(cs.ns(|| "c1"))?;
519        c0.append(&mut c1);
520        Ok(c0)
521    }
522}
523
524impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> Clone
525    for Fp2Gadget<P, ConstraintF>
526{
527    fn clone(&self) -> Self {
528        Self {
529            c0: self.c0.clone(),
530            c1: self.c1.clone(),
531            _params: PhantomData,
532        }
533    }
534}
535
536impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> CondSelectGadget<ConstraintF>
537    for Fp2Gadget<P, ConstraintF>
538{
539    #[inline]
540    fn conditionally_select<CS: ConstraintSystem<ConstraintF>>(
541        mut cs: CS,
542        cond: &Boolean,
543        true_value: &Self,
544        false_value: &Self,
545    ) -> Result<Self, SynthesisError> {
546        let c0 = FpGadget::<ConstraintF>::conditionally_select(
547            &mut cs.ns(|| "c0"),
548            cond,
549            &true_value.c0,
550            &false_value.c0,
551        )?;
552        let c1 = FpGadget::<ConstraintF>::conditionally_select(
553            &mut cs.ns(|| "c1"),
554            cond,
555            &true_value.c1,
556            &false_value.c1,
557        )?;
558
559        Ok(Self::new(c0, c1))
560    }
561
562    fn cost() -> usize {
563        2
564    }
565}
566
567impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> TwoBitLookupGadget<ConstraintF>
568    for Fp2Gadget<P, ConstraintF>
569{
570    type TableConstant = Fp2<P>;
571    fn two_bit_lookup<CS: ConstraintSystem<ConstraintF>>(
572        mut cs: CS,
573        b: &[Boolean],
574        c: &[Self::TableConstant],
575    ) -> Result<Self, SynthesisError> {
576        let c0s = c.iter().map(|f| f.c0).collect::<Vec<_>>();
577        let c1s = c.iter().map(|f| f.c1).collect::<Vec<_>>();
578        let c0 = FpGadget::two_bit_lookup(cs.ns(|| "Lookup c0"), b, &c0s)?;
579        let c1 = FpGadget::two_bit_lookup(cs.ns(|| "Lookup c1"), b, &c1s)?;
580        Ok(Self::new(c0, c1))
581    }
582
583    fn cost() -> usize {
584        2 * <FpGadget<ConstraintF> as TwoBitLookupGadget<ConstraintF>>::cost()
585    }
586}
587
588impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField>
589    ThreeBitCondNegLookupGadget<ConstraintF> for Fp2Gadget<P, ConstraintF>
590{
591    type TableConstant = Fp2<P>;
592
593    fn three_bit_cond_neg_lookup<CS: ConstraintSystem<ConstraintF>>(
594        mut cs: CS,
595        b: &[Boolean],
596        b0b1: &Boolean,
597        c: &[Self::TableConstant],
598    ) -> Result<Self, SynthesisError> {
599        let c0s = c.iter().map(|f| f.c0).collect::<Vec<_>>();
600        let c1s = c.iter().map(|f| f.c1).collect::<Vec<_>>();
601        let c0 = FpGadget::three_bit_cond_neg_lookup(cs.ns(|| "Lookup c0"), b, b0b1, &c0s)?;
602        let c1 = FpGadget::three_bit_cond_neg_lookup(cs.ns(|| "Lookup c1"), b, b0b1, &c1s)?;
603        Ok(Self::new(c0, c1))
604    }
605
606    fn cost() -> usize {
607        2 * <FpGadget<ConstraintF> as ThreeBitCondNegLookupGadget<ConstraintF>>::cost()
608    }
609}
610
611impl<P: Fp2Parameters<Fp = ConstraintF>, ConstraintF: PrimeField> AllocGadget<Fp2<P>, ConstraintF>
612    for Fp2Gadget<P, ConstraintF>
613{
614    #[inline]
615    fn alloc_constant<T, CS: ConstraintSystem<ConstraintF>>(
616        mut cs: CS,
617        t: T,
618    ) -> Result<Self, SynthesisError>
619    where
620        T: Borrow<Fp2<P>>,
621    {
622        Self::zero(cs.ns(|| "zero"))?.add_constant(cs.ns(|| "add constant"), t.borrow())
623    }
624
625    #[inline]
626    fn alloc<F, T, CS: ConstraintSystem<ConstraintF>>(
627        mut cs: CS,
628        value_gen: F,
629    ) -> Result<Self, SynthesisError>
630    where
631        F: FnOnce() -> Result<T, SynthesisError>,
632        T: Borrow<Fp2<P>>,
633    {
634        let (c0, c1) = match value_gen() {
635            Ok(fe) => {
636                let fe = *fe.borrow();
637                (Ok(fe.c0), Ok(fe.c1))
638            }
639            Err(_) => (
640                Err(SynthesisError::AssignmentMissing),
641                Err(SynthesisError::AssignmentMissing),
642            ),
643        };
644
645        let c0 = FpGadget::alloc(&mut cs.ns(|| "c0"), || c0)?;
646        let c1 = FpGadget::alloc(&mut cs.ns(|| "c1"), || c1)?;
647        Ok(Self::new(c0, c1))
648    }
649
650    #[inline]
651    fn alloc_input<F, T, CS: ConstraintSystem<ConstraintF>>(
652        mut cs: CS,
653        value_gen: F,
654    ) -> Result<Self, SynthesisError>
655    where
656        F: FnOnce() -> Result<T, SynthesisError>,
657        T: Borrow<Fp2<P>>,
658    {
659        let (c0, c1) = match value_gen() {
660            Ok(fe) => {
661                let fe = *fe.borrow();
662                (Ok(fe.c0), Ok(fe.c1))
663            }
664            Err(_) => (
665                Err(SynthesisError::AssignmentMissing),
666                Err(SynthesisError::AssignmentMissing),
667            ),
668        };
669
670        let c0 = FpGadget::alloc_input(&mut cs.ns(|| "c0"), || c0)?;
671        let c1 = FpGadget::alloc_input(&mut cs.ns(|| "c1"), || c1)?;
672        Ok(Self::new(c0, c1))
673    }
674}