ark_r1cs_std/groups/curves/twisted_edwards/
mod.rs

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