arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
ark-r1cs-std/r1cs-std/src/groups/curves/twisted_edwards/mod.rs
r1cs-std/src/groups/curves/twisted_edwards/mod.rsRaw
  1use algebra::{
  2    curves::{
  3        twisted_edwards_extended::{GroupAffine as TEAffine, GroupProjective as TEProjective},
  4        AffineCurve, MontgomeryModelParameters, ProjectiveCurve, TEModelParameters,
  5    },
  6    BigInteger, BitIteratorBE, Field, One, PrimeField, Zero,
  7};
  8
  9use r1cs_core::{ConstraintSystemRef, Namespace, SynthesisError};
 10
 11use crate::{prelude::*, Vec};
 12
 13use core::{borrow::Borrow, marker::PhantomData};
 14
 15#[derive(Derivative)]
 16#[derivative(Debug, Clone)]
 17#[must_use]
 18pub struct MontgomeryAffineVar<
 19    P: TEModelParameters,
 20    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
 21> where
 22    for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
 23{
 24    pub x: F,
 25    pub y: F,
 26    #[derivative(Debug = "ignore")]
 27    _params: PhantomData<P>,
 28}
 29
 30mod montgomery_affine_impl {
 31    use super::*;
 32    use algebra::{twisted_edwards_extended::GroupAffine, Field};
 33    use core::ops::Add;
 34
 35    impl<P, F> R1CSVar<<P::BaseField as Field>::BasePrimeField> for MontgomeryAffineVar<P, F>
 36    where
 37        P: TEModelParameters,
 38        F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
 39        for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
 40    {
 41        type Value = (P::BaseField, P::BaseField);
 42
 43        fn cs(&self) -> Option<ConstraintSystemRef<<P::BaseField as Field>::BasePrimeField>> {
 44            self.x.cs().or(self.y.cs())
 45        }
 46
 47        fn value(&self) -> Result<Self::Value, SynthesisError> {
 48            let x = self.x.value()?;
 49            let y = self.y.value()?;
 50            Ok((x, y))
 51        }
 52    }
 53
 54    impl<
 55            P: TEModelParameters,
 56            F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
 57        > MontgomeryAffineVar<P, F>
 58    where
 59        for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
 60    {
 61        pub fn new(x: F, y: F) -> Self {
 62            Self {
 63                x,
 64                y,
 65                _params: PhantomData,
 66            }
 67        }
 68
 69        pub fn from_edwards_to_coords(
 70            p: &TEAffine<P>,
 71        ) -> Result<(P::BaseField, P::BaseField), SynthesisError> {
 72            let montgomery_point: GroupAffine<P> = if p.y == P::BaseField::one() {
 73                GroupAffine::zero()
 74            } else if p.x == P::BaseField::zero() {
 75                GroupAffine::new(P::BaseField::zero(), P::BaseField::zero())
 76            } else {
 77                let u =
 78                    (P::BaseField::one() + &p.y) * &(P::BaseField::one() - &p.y).inverse().unwrap();
 79                let v = u * &p.x.inverse().unwrap();
 80                GroupAffine::new(u, v)
 81            };
 82
 83            Ok((montgomery_point.x, montgomery_point.y))
 84        }
 85
 86        pub fn new_witness_from_edwards(
 87            cs: ConstraintSystemRef<<P::BaseField as Field>::BasePrimeField>,
 88            p: &TEAffine<P>,
 89        ) -> Result<Self, SynthesisError> {
 90            let montgomery_coords = Self::from_edwards_to_coords(p)?;
 91            let u = F::new_witness(cs.ns("u"), || Ok(montgomery_coords.0))?;
 92            let v = F::new_witness(cs.ns("v"), || Ok(montgomery_coords.1))?;
 93            Ok(Self::new(u, v))
 94        }
 95
 96        pub fn into_edwards(&self) -> Result<AffineVar<P, F>, SynthesisError> {
 97            let cs = self.cs().unwrap_or(ConstraintSystemRef::None);
 98            // Compute u = x / y
 99            let u = F::new_witness(cs.ns("u"), || {
100                let y_inv = self
101                    .y
102                    .value()?
103                    .inverse()
104                    .ok_or(SynthesisError::DivisionByZero)?;
105                Ok(self.x.value()? * &y_inv)
106            })?;
107
108            u.mul_equals(&self.y, &self.x)?;
109
110            let v = F::new_witness(cs.ns("v"), || {
111                let mut t0 = self.x.value()?;
112                let mut t1 = t0;
113                t0 -= &P::BaseField::one();
114                t1 += &P::BaseField::one();
115
116                Ok(t0 * &t1.inverse().ok_or(SynthesisError::DivisionByZero)?)
117            })?;
118
119            let xplusone = &self.x + P::BaseField::one();
120            let xminusone = &self.x - P::BaseField::one();
121            v.mul_equals(&xplusone, &xminusone)?;
122
123            Ok(AffineVar::new(u, v))
124        }
125    }
126
127    impl<'a, P, F> Add<&'a MontgomeryAffineVar<P, F>> for MontgomeryAffineVar<P, F>
128    where
129        P: TEModelParameters,
130        F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
131        for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
132    {
133        type Output = MontgomeryAffineVar<P, F>;
134        fn add(self, other: &'a Self) -> Self::Output {
135            let cs = [&self, other].cs();
136            let mode = if cs.is_none() || matches!(cs, Some(ConstraintSystemRef::None)) {
137                AllocationMode::Constant
138            } else {
139                AllocationMode::Witness
140            };
141            let cs = cs.unwrap_or(ConstraintSystemRef::None);
142
143            let coeff_b = P::MontgomeryModelParameters::COEFF_B;
144            let coeff_a = P::MontgomeryModelParameters::COEFF_A;
145
146            let lambda = F::new_variable(
147                cs.ns("lambda"),
148                || {
149                    let n = other.y.value()? - &self.y.value()?;
150                    let d = other.x.value()? - &self.x.value()?;
151                    Ok(n * &d.inverse().ok_or(SynthesisError::DivisionByZero)?)
152                },
153                mode,
154            )
155            .unwrap();
156            let lambda_n = &other.y - &self.y;
157            let lambda_d = &other.x - &self.x;
158            lambda_d.mul_equals(&lambda, &lambda_n).unwrap();
159
160            // Compute x'' = B*lambda^2 - A - x - x'
161            let xprime = F::new_variable(
162                cs.ns("xprime"),
163                || {
164                    Ok(lambda.value()?.square() * &coeff_b
165                        - &coeff_a
166                        - &self.x.value()?
167                        - &other.x.value()?)
168                },
169                mode,
170            )
171            .unwrap();
172
173            let xprime_lc = &self.x + &other.x + &xprime + coeff_a;
174            // (lambda) * (lambda) = (A + x + x' + x'')
175            let lambda_b = &lambda * coeff_b;
176            lambda_b.mul_equals(&lambda, &xprime_lc).unwrap();
177
178            let yprime = F::new_variable(
179                cs.ns("yprime"),
180                || {
181                    Ok(-(self.y.value()?
182                        + &(lambda.value()? * &(xprime.value()? - &self.x.value()?))))
183                },
184                mode,
185            )
186            .unwrap();
187
188            let xres = &self.x - &xprime;
189            let yres = &self.y + &yprime;
190            lambda.mul_equals(&xres, &yres).unwrap();
191            MontgomeryAffineVar::new(xprime, yprime)
192        }
193    }
194}
195
196#[derive(Derivative)]
197#[derivative(Debug, Clone)]
198#[must_use]
199pub struct AffineVar<
200    P: TEModelParameters,
201    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
202> where
203    for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
204{
205    pub x: F,
206    pub y: F,
207    #[derivative(Debug = "ignore")]
208    _params: PhantomData<P>,
209}
210
211impl<P: TEModelParameters, F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>>
212    AffineVar<P, F>
213where
214    for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
215{
216    pub fn new(x: F, y: F) -> Self {
217        Self {
218            x,
219            y,
220            _params: PhantomData,
221        }
222    }
223
224    /// Allocates a new variable without performing an on-curve check, which is
225    /// useful if the variable is known to be on the curve (eg., if the point
226    /// is a constant or is a public input).
227    pub fn new_variable_omit_on_curve_check<T: Into<TEAffine<P>>>(
228        cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
229        f: impl FnOnce() -> Result<T, SynthesisError>,
230        mode: AllocationMode,
231    ) -> Result<Self, SynthesisError> {
232        let ns = cs.into();
233        let cs = ns.cs();
234
235        let (x, y) = match f() {
236            Ok(ge) => {
237                let ge: TEAffine<P> = ge.into();
238                (Ok(ge.x), Ok(ge.y))
239            }
240            _ => (
241                Err(SynthesisError::AssignmentMissing),
242                Err(SynthesisError::AssignmentMissing),
243            ),
244        };
245
246        let x = F::new_variable(cs.ns("x"), || x, mode)?;
247        let y = F::new_variable(cs.ns("y"), || y, mode)?;
248
249        Ok(Self::new(x, y))
250    }
251}
252
253impl<P, F> R1CSVar<<P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
254where
255    P: TEModelParameters,
256    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
257    for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
258{
259    type Value = TEProjective<P>;
260
261    fn cs(&self) -> Option<ConstraintSystemRef<<P::BaseField as Field>::BasePrimeField>> {
262        self.x.cs().or(self.y.cs())
263    }
264
265    #[inline]
266    fn value(&self) -> Result<TEProjective<P>, SynthesisError> {
267        let (x, y) = (self.x.value()?, self.y.value()?);
268        let result = TEAffine::new(x, y);
269        Ok(result.into())
270    }
271}
272
273impl<P, F> CurveVar<TEProjective<P>, <P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
274where
275    P: TEModelParameters,
276    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>
277        + TwoBitLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>
278        + ThreeBitCondNegLookupGadget<
279            <P::BaseField as Field>::BasePrimeField,
280            TableConstant = P::BaseField,
281        >,
282    for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
283{
284    fn constant(g: TEProjective<P>) -> Self {
285        let cs = ConstraintSystemRef::None;
286        Self::new_variable_omit_on_curve_check(cs, || Ok(g), AllocationMode::Constant).unwrap()
287    }
288
289    fn zero() -> Self {
290        Self::new(F::zero(), F::one())
291    }
292
293    fn is_zero(&self) -> Result<Boolean<<P::BaseField as Field>::BasePrimeField>, SynthesisError> {
294        self.x.is_zero()?.and(&self.x.is_one()?)
295    }
296
297    fn new_variable_omit_prime_order_check(
298        cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
299        f: impl FnOnce() -> Result<TEProjective<P>, SynthesisError>,
300        mode: AllocationMode,
301    ) -> Result<Self, SynthesisError> {
302        let ns = cs.into();
303        let cs = ns.cs();
304
305        let g = Self::new_variable_omit_on_curve_check(cs, f, mode)?;
306
307        if mode != AllocationMode::Constant {
308            let d = P::COEFF_D;
309            let a = P::COEFF_A;
310            // Check that ax^2 + y^2 = 1 + dx^2y^2
311            // We do this by checking that ax^2 - 1 = y^2 * (dx^2 - 1)
312            let x2 = g.x.square()?;
313            let y2 = g.y.square()?;
314
315            let one = P::BaseField::one();
316            let d_x2_minus_one = &x2 * d - one;
317            let a_x2_minus_one = &x2 * a - one;
318
319            d_x2_minus_one.mul_equals(&y2, &a_x2_minus_one)?;
320        }
321        Ok(g)
322    }
323
324    /// Enforce that `self` is in the prime-order subgroup.
325    ///
326    /// Does so by multiplying by the prime order, and checking that the result
327    /// is unchanged.
328    fn enforce_prime_order(&self) -> Result<(), SynthesisError> {
329        let r_minus_1 = (-P::ScalarField::one()).into_repr();
330
331        let mut result = Self::zero();
332        for b in BitIteratorBE::without_leading_zeros(r_minus_1) {
333            result.double_in_place()?;
334
335            if b {
336                result += self;
337            }
338        }
339        self.negate()?.enforce_equal(&result)?;
340        Ok(())
341    }
342
343    #[inline]
344    fn double_in_place(&mut self) -> Result<(), SynthesisError> {
345        if let Some(cs) = self.cs() {
346            let a = P::COEFF_A;
347
348            // xy
349            let xy = &self.x * &self.y;
350            let x2 = self.x.square()?;
351            let y2 = self.y.square()?;
352
353            let a_x2 = &x2 * a;
354
355            // Compute x3 = (2xy) / (ax^2 + y^2)
356            let x3 = F::new_witness(cs.ns("x3"), || {
357                let t0 = xy.value()?.double();
358                let t1 = a * &x2.value()? + &y2.value()?;
359                Ok(t0 * &t1.inverse().ok_or(SynthesisError::DivisionByZero)?)
360            })?;
361
362            let a_x2_plus_y2 = &a_x2 + &y2;
363            let two_xy = xy.double()?;
364            x3.mul_equals(&a_x2_plus_y2, &two_xy)?;
365
366            // Compute y3 = (y^2 - ax^2) / (2 - ax^2 - y^2)
367            let two = P::BaseField::one().double();
368            let y3 = F::new_witness(cs.ns("y3"), || {
369                let a_x2 = a * &x2.value()?;
370                let t0 = y2.value()? - &a_x2;
371                let t1 = two - &a_x2 - &y2.value()?;
372                Ok(t0 * &t1.inverse().ok_or(SynthesisError::DivisionByZero)?)
373            })?;
374            let y2_minus_a_x2 = &y2 - &a_x2;
375            let two_minus_ax2_minus_y2 = (&a_x2 + &y2).negate()? + two;
376
377            y3.mul_equals(&two_minus_ax2_minus_y2, &y2_minus_a_x2)?;
378            self.x = x3;
379            self.y = y3;
380        } else {
381            let value = self.value()?;
382            *self = Self::constant(value.double());
383        }
384        Ok(())
385    }
386
387    fn negate(&self) -> Result<Self, SynthesisError> {
388        Ok(Self::new(self.x.negate()?, self.y.clone()))
389    }
390
391    fn precomputed_base_scalar_mul_le<'a, I, B>(
392        &mut self,
393        scalar_bits_with_base_powers: I,
394    ) -> Result<(), SynthesisError>
395    where
396        I: Iterator<Item = (B, &'a TEProjective<P>)>,
397        B: Borrow<Boolean<<P::BaseField as Field>::BasePrimeField>>,
398    {
399        let scalar_bits_with_base_powers = scalar_bits_with_base_powers
400            .map(|(bit, base)| (bit.borrow().clone(), (*base).into()))
401            .collect::<Vec<(_, TEProjective<P>)>>();
402        let zero = TEProjective::zero();
403        for bits_base_powers in scalar_bits_with_base_powers.chunks(2) {
404            if bits_base_powers.len() == 2 {
405                let bits = [bits_base_powers[0].0.clone(), bits_base_powers[1].0.clone()];
406                let base_powers = [&bits_base_powers[0].1, &bits_base_powers[1].1];
407
408                let mut table = [
409                    zero,
410                    *base_powers[0],
411                    *base_powers[1],
412                    *base_powers[0] + base_powers[1],
413                ];
414
415                TEProjective::batch_normalization(&mut table);
416                let x_s = [table[0].x, table[1].x, table[2].x, table[3].x];
417                let y_s = [table[0].y, table[1].y, table[2].y, table[3].y];
418
419                let x = F::two_bit_lookup(&bits, &x_s)?;
420                let y = F::two_bit_lookup(&bits, &y_s)?;
421                *self += Self::new(x, y);
422            } else if bits_base_powers.len() == 1 {
423                let bit = bits_base_powers[0].0.clone();
424                let base_power = bits_base_powers[0].1;
425                let new_encoded = &*self + base_power;
426                *self = bit.select(&new_encoded, &self)?;
427            }
428        }
429
430        Ok(())
431    }
432
433    fn precomputed_base_3_bit_signed_digit_scalar_mul<'a, I, J, B>(
434        bases: &[B],
435        scalars: &[J],
436    ) -> Result<Self, SynthesisError>
437    where
438        I: Borrow<[Boolean<<P::BaseField as Field>::BasePrimeField>]>,
439        J: Borrow<[I]>,
440        B: Borrow<[TEProjective<P>]>,
441    {
442        const CHUNK_SIZE: usize = 3;
443        let mut ed_result: Option<AffineVar<P, F>> = None;
444        let mut result: Option<MontgomeryAffineVar<P, F>> = None;
445
446        let mut process_segment_result = |result: &MontgomeryAffineVar<P, F>| {
447            let sgmt_result = result.into_edwards()?;
448            ed_result = match ed_result.as_ref() {
449                None => Some(sgmt_result),
450                Some(r) => Some(sgmt_result + r),
451            };
452            Ok::<(), SynthesisError>(())
453        };
454
455        // Compute ∏(h_i^{m_i}) for all i.
456        for (segment_bits_chunks, segment_powers) in scalars.iter().zip(bases) {
457            for (bits, base_power) in segment_bits_chunks
458                .borrow()
459                .iter()
460                .zip(segment_powers.borrow())
461            {
462                let base_power = base_power.borrow();
463                let mut acc_power = *base_power;
464                let mut coords = vec![];
465                for _ in 0..4 {
466                    coords.push(acc_power);
467                    acc_power += base_power;
468                }
469
470                let bits = bits.borrow().to_bits_le()?;
471                if bits.len() != CHUNK_SIZE {
472                    return Err(SynthesisError::Unsatisfiable);
473                }
474
475                let coords = coords
476                    .iter()
477                    .map(|p| MontgomeryAffineVar::from_edwards_to_coords(&p.into_affine()))
478                    .collect::<Result<Vec<_>, _>>()?;
479
480                let x_coeffs = coords.iter().map(|p| p.0).collect::<Vec<_>>();
481                let y_coeffs = coords.iter().map(|p| p.1).collect::<Vec<_>>();
482
483                let precomp = bits[0].and(&bits[1])?;
484
485                let x = F::zero()
486                    + x_coeffs[0]
487                    + F::from(bits[0].clone()) * (x_coeffs[1] - &x_coeffs[0])
488                    + F::from(bits[1].clone()) * (x_coeffs[2] - &x_coeffs[0])
489                    + F::from(precomp.clone())
490                        * (x_coeffs[3] - &x_coeffs[2] - &x_coeffs[1] + &x_coeffs[0]);
491
492                let y = F::three_bit_cond_neg_lookup(&bits, &precomp, &y_coeffs)?;
493
494                let tmp = MontgomeryAffineVar::new(x, y);
495                result = match result.as_ref() {
496                    None => Some(tmp),
497                    Some(r) => Some(tmp + r),
498                };
499            }
500
501            process_segment_result(&result.unwrap())?;
502            result = None;
503        }
504        if result.is_some() {
505            process_segment_result(&result.unwrap())?;
506        }
507        Ok(ed_result.unwrap())
508    }
509}
510
511impl<P, F> AllocVar<TEProjective<P>, <P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
512where
513    P: TEModelParameters,
514    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>
515        + TwoBitLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>
516        + ThreeBitCondNegLookupGadget<
517            <P::BaseField as Field>::BasePrimeField,
518            TableConstant = P::BaseField,
519        >,
520    for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
521{
522    fn new_variable<Point: Borrow<TEProjective<P>>>(
523        cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
524        f: impl FnOnce() -> Result<Point, SynthesisError>,
525        mode: AllocationMode,
526    ) -> Result<Self, SynthesisError> {
527        let ns = cs.into();
528        let cs = ns.cs();
529        let f = || Ok(*f()?.borrow());
530        match mode {
531            AllocationMode::Constant => Self::new_variable_omit_prime_order_check(cs, f, mode),
532            AllocationMode::Input => Self::new_variable_omit_prime_order_check(cs, f, mode),
533            AllocationMode::Witness => {
534                // if cofactor.is_even():
535                //   divide until you've removed all even factors
536                // else:
537                //   just directly use double and add.
538                let mut power_of_2: u32 = 0;
539                let mut cofactor = P::COFACTOR.to_vec();
540                while cofactor[0] % 2 == 0 {
541                    div2(&mut cofactor);
542                    power_of_2 += 1;
543                }
544
545                let cofactor_weight = BitIteratorBE::new(cofactor.as_slice())
546                    .filter(|b| *b)
547                    .count();
548                let modulus_minus_1 = (-P::ScalarField::one()).into_repr(); // r - 1
549                let modulus_minus_1_weight =
550                    BitIteratorBE::new(modulus_minus_1).filter(|b| *b).count();
551
552                // We pick the most efficient method of performing the prime order check:
553                // If the cofactor has lower hamming weight than the scalar field's modulus,
554                // we first multiply by the inverse of the cofactor, and then, after allocating,
555                // multiply by the cofactor. This ensures the resulting point has no cofactors
556                //
557                // Else, we multiply by the scalar field's modulus and ensure that the result
558                // equals the identity.
559
560                let (mut ge, iter) = if cofactor_weight < modulus_minus_1_weight {
561                    let ge = Self::new_variable_omit_prime_order_check(
562                        cs.ns("Witness without subgroup check with cofactor mul"),
563                        || f().map(|g| g.borrow().into_affine().mul_by_cofactor_inv().into()),
564                        mode,
565                    )?;
566                    (
567                        ge,
568                        BitIteratorBE::without_leading_zeros(cofactor.as_slice()),
569                    )
570                } else {
571                    let ge = Self::new_variable_omit_prime_order_check(
572                        cs.ns("Witness without subgroup check with `r` check"),
573                        || {
574                            f().map(|g| {
575                                let g = g.into_affine();
576                                let mut power_of_two = P::ScalarField::one().into_repr();
577                                power_of_two.muln(power_of_2);
578                                let power_of_two_inv = P::ScalarField::from_repr(power_of_two)
579                                    .and_then(|n| n.inverse())
580                                    .unwrap();
581                                g.mul(power_of_two_inv)
582                            })
583                        },
584                        mode,
585                    )?;
586
587                    (
588                        ge,
589                        BitIteratorBE::without_leading_zeros(modulus_minus_1.as_ref()),
590                    )
591                };
592                // Remove the even part of the cofactor
593                for _ in 0..power_of_2 {
594                    ge.double_in_place()?;
595                }
596
597                let mut result = Self::zero();
598                for b in iter {
599                    result.double_in_place()?;
600                    if b {
601                        result += &ge;
602                    }
603                }
604                if cofactor_weight < modulus_minus_1_weight {
605                    Ok(result)
606                } else {
607                    ge.enforce_equal(&ge)?;
608                    Ok(ge)
609                }
610            }
611        }
612    }
613}
614
615impl<P, F> AllocVar<TEAffine<P>, <P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
616where
617    P: TEModelParameters,
618    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>
619        + TwoBitLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>
620        + ThreeBitCondNegLookupGadget<
621            <P::BaseField as Field>::BasePrimeField,
622            TableConstant = P::BaseField,
623        >,
624    for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
625{
626    fn new_variable<Point: Borrow<TEAffine<P>>>(
627        cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
628        f: impl FnOnce() -> Result<Point, SynthesisError>,
629        mode: AllocationMode,
630    ) -> Result<Self, SynthesisError> {
631        Self::new_variable(cs, || f().map(|b| b.borrow().into_projective()), mode)
632    }
633}
634
635#[inline]
636fn div2(limbs: &mut [u64]) {
637    let mut t = 0;
638    for i in limbs.iter_mut().rev() {
639        let t2 = *i << 63;
640        *i >>= 1;
641        *i |= t;
642        t = t2;
643    }
644}
645
646impl_bounded_ops!(
647    AffineVar<P, F>,
648    TEProjective<P>,
649    Add,
650    add,
651    AddAssign,
652    add_assign,
653    |this: &'a AffineVar<P, F>, other: &'a AffineVar<P, F>| {
654        if let Some(cs) = [this, other].cs() {
655            let a = P::COEFF_A;
656            let d = P::COEFF_D;
657
658            // Compute U = (x1 + y1) * (x2 + y2)
659            let u1 = (&this.x * -a) + &this.y;
660            let u2 = &other.x + &other.y;
661
662            let u = u1 *  &u2;
663
664            // Compute v0 = x1 * y2
665            let v0 = &other.y * &this.x;
666
667            // Compute v1 = x2 * y1
668            let v1 = &other.x * &this.y;
669
670            // Compute C = d*v0*v1
671            let v2 = &v0 * &v1 * d;
672
673            // Compute x3 = (v0 + v1) / (1 + v2)
674            let x3 = F::new_witness(cs.ns("x3"), || {
675                let t0 = v0.value()? + &v1.value()?;
676                let t1 = P::BaseField::one() + &v2.value()?;
677                Ok(t0 * &t1.inverse().ok_or(SynthesisError::DivisionByZero)?)
678            }).unwrap();
679
680            let v2_plus_one = &v2 + P::BaseField::one();
681            let v0_plus_v1 = &v0 + &v1;
682            x3.mul_equals(&v2_plus_one, &v0_plus_v1).unwrap();
683
684            // Compute y3 = (U + a * v0 - v1) / (1 - v2)
685            let y3 = F::new_witness(cs.ns("y3"), || {
686                let t0 = u.value()? + &(a * &v0.value()?) - &v1.value()?;
687                let t1 = P::BaseField::one() - &v2.value()?;
688                Ok(t0 * &t1.inverse().ok_or(SynthesisError::DivisionByZero)?)
689            }).unwrap();
690
691            let one_minus_v2 = (&v2 - P::BaseField::one()).negate().unwrap();
692            let a_v0 = &v0 * a;
693            let u_plus_a_v0_minus_v1 = &u + &a_v0 - &v1;
694
695            y3.mul_equals(&one_minus_v2, &u_plus_a_v0_minus_v1).unwrap();
696
697            AffineVar::new(x3, y3)
698        } else {
699            assert!(this.is_constant() && other.is_constant());
700            AffineVar::constant(this.value().unwrap() + &other.value().unwrap())
701        }
702    },
703    |this: &'a AffineVar<P, F>, other: TEProjective<P>| this + AffineVar::constant(other),
704    (
705        F :FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>
706            + TwoBitLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>
707            + ThreeBitCondNegLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>,
708        P: TEModelParameters,
709    ),
710    for <'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
711);
712
713impl_bounded_ops!(
714    AffineVar<P, F>,
715    TEProjective<P>,
716    Sub,
717    sub,
718    SubAssign,
719    sub_assign,
720    |this: &'a AffineVar<P, F>, other: &'a AffineVar<P, F>| this + other.negate().unwrap(),
721    |this: &'a AffineVar<P, F>, other: TEProjective<P>| this - AffineVar::constant(other),
722    (
723        F :FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>
724            + TwoBitLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>
725            + ThreeBitCondNegLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>,
726        P: TEModelParameters,
727    ),
728    for <'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>
729);
730
731impl<'a, P, F> GroupOpsBounds<'a, TEProjective<P>, AffineVar<P, F>> for AffineVar<P, F>
732where
733    P: TEModelParameters,
734    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>
735        + TwoBitLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>
736        + ThreeBitCondNegLookupGadget<
737            <P::BaseField as Field>::BasePrimeField,
738            TableConstant = P::BaseField,
739        >,
740    for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
741{
742}
743
744impl<'a, P, F> GroupOpsBounds<'a, TEProjective<P>, AffineVar<P, F>> for &'a AffineVar<P, F>
745where
746    P: TEModelParameters,
747    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>
748        + TwoBitLookupGadget<<P::BaseField as Field>::BasePrimeField, TableConstant = P::BaseField>
749        + ThreeBitCondNegLookupGadget<
750            <P::BaseField as Field>::BasePrimeField,
751            TableConstant = P::BaseField,
752        >,
753    for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
754{
755}
756
757impl<P, F> CondSelectGadget<<P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
758where
759    P: TEModelParameters,
760    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
761    for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
762{
763    #[inline]
764    fn conditionally_select(
765        cond: &Boolean<<P::BaseField as Field>::BasePrimeField>,
766        true_value: &Self,
767        false_value: &Self,
768    ) -> Result<Self, SynthesisError> {
769        let x = cond.select(&true_value.x, &false_value.x)?;
770        let y = cond.select(&true_value.y, &false_value.y)?;
771
772        Ok(Self::new(x, y))
773    }
774}
775
776impl<P, F> EqGadget<<P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
777where
778    P: TEModelParameters,
779    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
780    for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
781{
782    fn is_eq(
783        &self,
784        other: &Self,
785    ) -> Result<Boolean<<P::BaseField as Field>::BasePrimeField>, SynthesisError> {
786        let x_equal = self.x.is_eq(&other.x)?;
787        let y_equal = self.y.is_eq(&other.y)?;
788        x_equal.and(&y_equal)
789    }
790
791    #[inline]
792    fn conditional_enforce_equal(
793        &self,
794        other: &Self,
795        condition: &Boolean<<P::BaseField as Field>::BasePrimeField>,
796    ) -> Result<(), SynthesisError> {
797        self.x.conditional_enforce_equal(&other.x, condition)?;
798        self.y.conditional_enforce_equal(&other.y, condition)?;
799        Ok(())
800    }
801
802    #[inline]
803    fn conditional_enforce_not_equal(
804        &self,
805        other: &Self,
806        condition: &Boolean<<P::BaseField as Field>::BasePrimeField>,
807    ) -> Result<(), SynthesisError> {
808        self.is_eq(other)?
809            .and(condition)?
810            .enforce_equal(&Boolean::Constant(false))
811    }
812}
813
814impl<P, F> ToBitsGadget<<P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
815where
816    P: TEModelParameters,
817    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
818    for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
819{
820    fn to_bits_le(
821        &self,
822    ) -> Result<Vec<Boolean<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
823        let mut x_bits = self.x.to_bits_le()?;
824        let y_bits = self.y.to_bits_le()?;
825        x_bits.extend_from_slice(&y_bits);
826        Ok(x_bits)
827    }
828
829    fn to_non_unique_bits_le(
830        &self,
831    ) -> Result<Vec<Boolean<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
832        let mut x_bits = self.x.to_non_unique_bits_le()?;
833        let y_bits = self.y.to_non_unique_bits_le()?;
834        x_bits.extend_from_slice(&y_bits);
835
836        Ok(x_bits)
837    }
838}
839
840impl<P, F> ToBytesGadget<<P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
841where
842    P: TEModelParameters,
843    F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
844    for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
845{
846    fn to_bytes(
847        &self,
848    ) -> Result<Vec<UInt8<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
849        let mut x_bytes = self.x.to_bytes()?;
850        let y_bytes = self.y.to_bytes()?;
851        x_bytes.extend_from_slice(&y_bytes);
852        Ok(x_bytes)
853    }
854
855    fn to_non_unique_bytes(
856        &self,
857    ) -> Result<Vec<UInt8<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
858        let mut x_bytes = self.x.to_non_unique_bytes()?;
859        let y_bytes = self.y.to_non_unique_bytes()?;
860        x_bytes.extend_from_slice(&y_bytes);
861
862        Ok(x_bytes)
863    }
864}
865
866#[cfg(test)]
867#[allow(dead_code)]
868pub(crate) fn test<P, GG>() -> Result<(), SynthesisError>
869where
870    P: TEModelParameters,
871    GG: CurveVar<TEProjective<P>, <P::BaseField as Field>::BasePrimeField>,
872    for<'a> &'a GG: GroupOpsBounds<'a, TEProjective<P>, GG>,
873{
874    use crate::prelude::*;
875    use algebra::{test_rng, BitIteratorLE, Group, UniformRand};
876    use r1cs_core::ConstraintSystem;
877
878    crate::groups::test::group_test::<TEProjective<P>, _, GG>()?;
879
880    let mut rng = test_rng();
881
882    let cs = ConstraintSystem::<<P::BaseField as Field>::BasePrimeField>::new_ref();
883
884    let a = TEProjective::<P>::rand(&mut rng);
885    let b = TEProjective::<P>::rand(&mut rng);
886    let a_affine = a.into_affine();
887    let b_affine = b.into_affine();
888
889    println!("Allocating things");
890    let ns = cs.ns("allocating variables");
891    println!("{:?}", cs.current_namespace());
892    let mut gadget_a = GG::new_witness(cs.ns("a"), || Ok(a))?;
893    let gadget_b = GG::new_witness(cs.ns("b"), || Ok(b))?;
894    println!("{:?}", cs.current_namespace());
895    ns.leave_namespace();
896    println!("Done Allocating things");
897    assert_eq!(gadget_a.value()?.into_affine().x, a_affine.x);
898    assert_eq!(gadget_a.value()?.into_affine().y, a_affine.y);
899    assert_eq!(gadget_b.value()?.into_affine().x, b_affine.x);
900    assert_eq!(gadget_b.value()?.into_affine().y, b_affine.y);
901    assert_eq!(cs.which_is_unsatisfied(), None);
902
903    println!("Checking addition");
904    // Check addition
905    let ab = a + &b;
906    let ab_affine = ab.into_affine();
907    let gadget_ab = &gadget_a + &gadget_b;
908    let gadget_ba = &gadget_b + &gadget_a;
909    gadget_ba.enforce_equal(&gadget_ab)?;
910
911    let ab_val = gadget_ab.value()?.into_affine();
912    assert_eq!(ab_val, ab_affine, "Result of addition is unequal");
913    assert!(cs.is_satisfied().unwrap());
914    println!("Done checking addition");
915
916    println!("Checking doubling");
917    // Check doubling
918    let aa = Group::double(&a);
919    let aa_affine = aa.into_affine();
920    gadget_a.double_in_place()?;
921    let aa_val = gadget_a.value()?.into_affine();
922    assert_eq!(
923        aa_val, aa_affine,
924        "Gadget and native values are unequal after double."
925    );
926    assert!(cs.is_satisfied().unwrap());
927    println!("Done checking doubling");
928
929    println!("Checking mul_bits");
930    // Check mul_bits
931    let scalar = P::ScalarField::rand(&mut rng);
932    let native_result = AffineCurve::mul(&aa.into_affine(), scalar);
933    let native_result = native_result.into_affine();
934
935    let scalar: Vec<bool> = BitIteratorLE::new(scalar.into_repr()).collect();
936    let input: Vec<Boolean<_>> = Vec::new_witness(cs.ns("bits"), || Ok(scalar)).unwrap();
937    let result = gadget_a.scalar_mul_le(input.iter())?;
938    let result_val = result.value()?.into_affine();
939    assert_eq!(
940        result_val, native_result,
941        "gadget & native values are diff. after scalar mul"
942    );
943    assert!(cs.is_satisfied().unwrap());
944    println!("Done checking mul_bits");
945
946    if !cs.is_satisfied().unwrap() {
947        println!("Not satisfied");
948        println!("{:?}", cs.which_is_unsatisfied().unwrap());
949    }
950
951    assert!(cs.is_satisfied().unwrap());
952    Ok(())
953}