ark-r1cs-std/src/groups/curves/short_weierstrass/mod.rs
src/groups/curves/short_weierstrass/mod.rsRaw
1use ark_ec::{
2 short_weierstrass::{
3 Affine as SWAffine, Projective as SWProjective, SWCurveConfig as SWModelParameters,
4 },
5 AffineRepr, CurveGroup,
6};
7use ark_ff::{AdditiveGroup, BigInteger, BitIteratorBE, Field, One, PrimeField, Zero};
8use ark_relations::r1cs::{ConstraintSystemRef, Namespace, SynthesisError};
9use ark_std::{borrow::Borrow, marker::PhantomData, ops::Mul};
10use non_zero_affine::NonZeroAffineVar;
11
12use crate::{fields::fp::FpVar, prelude::*, ToConstraintFieldGadget, Vec};
13
14/// This module provides a generic implementation of G1 and G2 for
15/// the [\[BLS12]\](<https://eprint.iacr.org/2002/088.pdf>) family of bilinear groups.
16pub mod bls12;
17
18/// This module provides a generic implementation of G1 and G2 for
19/// the [\[MNT4]\](<https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.20.8113&rep=rep1&type=pdf>)
20/// family of bilinear groups.
21pub mod mnt4;
22/// This module provides a generic implementation of G1 and G2 for
23/// the [\[MNT6]\](<https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.20.8113&rep=rep1&type=pdf>)
24/// family of bilinear groups.
25pub mod mnt6;
26
27/// This module provides a generic implementation of elliptic curve operations
28/// for points on short-weierstrass curves in affine coordinates that **are
29/// not** equal to zero.
30///
31/// Note: this module is **unsafe** in general: it can synthesize unsatisfiable
32/// or underconstrained constraint systems when a represented point _is_ equal
33/// to zero. The [ProjectiveVar] gadget is the recommended way of working with
34/// elliptic curve points.
35pub mod non_zero_affine;
36/// An implementation of arithmetic for Short Weierstrass curves that relies on
37/// the complete formulae derived in the paper of
38/// [[Renes, Costello, Batina 2015]](<https://eprint.iacr.org/2015/1060>).
39#[derive(Derivative)]
40#[derivative(Debug, Clone)]
41#[must_use]
42pub struct ProjectiveVar<
43 P: SWModelParameters,
44 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
45> where
46 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
47{
48 /// The x-coordinate.
49 pub x: F,
50 /// The y-coordinate.
51 pub y: F,
52 /// The z-coordinate.
53 pub z: F,
54 #[derivative(Debug = "ignore")]
55 _params: PhantomData<P>,
56}
57
58/// An affine representation of a curve point.
59#[derive(Derivative)]
60#[derivative(Debug, Clone)]
61#[must_use]
62pub struct AffineVar<
63 P: SWModelParameters,
64 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
65> where
66 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
67{
68 /// The x-coordinate.
69 pub x: F,
70 /// The y-coordinate.
71 pub y: F,
72 /// Is `self` the point at infinity.
73 pub infinity: Boolean<<P::BaseField as Field>::BasePrimeField>,
74 #[derivative(Debug = "ignore")]
75 _params: PhantomData<P>,
76}
77
78impl<P, F> AffineVar<P, F>
79where
80 P: SWModelParameters,
81 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
82 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
83{
84 fn new(x: F, y: F, infinity: Boolean<<P::BaseField as Field>::BasePrimeField>) -> Self {
85 Self {
86 x,
87 y,
88 infinity,
89 _params: PhantomData,
90 }
91 }
92
93 /// Returns the value assigned to `self` in the underlying
94 /// constraint system.
95 pub fn value(&self) -> Result<SWAffine<P>, SynthesisError> {
96 Ok(match self.infinity.value()? {
97 true => SWAffine::identity(),
98 false => SWAffine::new(self.x.value()?, self.y.value()?),
99 })
100 }
101}
102
103impl<P, F> ToConstraintFieldGadget<<P::BaseField as Field>::BasePrimeField> for AffineVar<P, F>
104where
105 P: SWModelParameters,
106 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
107 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
108 F: ToConstraintFieldGadget<<P::BaseField as Field>::BasePrimeField>,
109{
110 fn to_constraint_field(
111 &self,
112 ) -> Result<Vec<FpVar<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
113 let mut res = Vec::<FpVar<<P::BaseField as Field>::BasePrimeField>>::new();
114
115 res.extend_from_slice(&self.x.to_constraint_field()?);
116 res.extend_from_slice(&self.y.to_constraint_field()?);
117 res.extend_from_slice(&self.infinity.to_constraint_field()?);
118
119 Ok(res)
120 }
121}
122
123impl<P, F> R1CSVar<<P::BaseField as Field>::BasePrimeField> for ProjectiveVar<P, F>
124where
125 P: SWModelParameters,
126 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
127 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
128{
129 type Value = SWProjective<P>;
130
131 fn cs(&self) -> ConstraintSystemRef<<P::BaseField as Field>::BasePrimeField> {
132 self.x.cs().or(self.y.cs()).or(self.z.cs())
133 }
134
135 fn value(&self) -> Result<Self::Value, SynthesisError> {
136 let (x, y, z) = (self.x.value()?, self.y.value()?, self.z.value()?);
137 let result = if let Some(z_inv) = z.inverse() {
138 SWAffine::new(x * &z_inv, y * &z_inv)
139 } else {
140 SWAffine::identity()
141 };
142 Ok(result.into())
143 }
144}
145
146impl<P: SWModelParameters, F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>>
147 ProjectiveVar<P, F>
148where
149 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
150{
151 /// Constructs `Self` from an `(x, y, z)` coordinate triple.
152 pub fn new(x: F, y: F, z: F) -> Self {
153 Self {
154 x,
155 y,
156 z,
157 _params: PhantomData,
158 }
159 }
160
161 /// Convert this point into affine form.
162 #[tracing::instrument(target = "r1cs")]
163 pub fn to_affine(&self) -> Result<AffineVar<P, F>, SynthesisError> {
164 if self.is_constant() {
165 let point = self.value()?.into_affine();
166 let x = F::new_constant(ConstraintSystemRef::None, point.x)?;
167 let y = F::new_constant(ConstraintSystemRef::None, point.y)?;
168 let infinity = Boolean::constant(point.infinity);
169 Ok(AffineVar::new(x, y, infinity))
170 } else {
171 let cs = self.cs();
172 let infinity = self.is_zero()?;
173 let zero_affine = SWAffine::<P>::zero();
174 let zero_x = F::new_constant(cs.clone(), &zero_affine.x)?;
175 let zero_y = F::new_constant(cs.clone(), &zero_affine.y)?;
176 // Allocate a variable whose value is either `self.z.inverse()` if the inverse
177 // exists, and is zero otherwise.
178 let z_inv = F::new_witness(ark_relations::ns!(cs, "z_inverse"), || {
179 Ok(self.z.value()?.inverse().unwrap_or_else(P::BaseField::zero))
180 })?;
181 // The inverse exists if `!self.is_zero()`.
182 // This means that `z_inv * self.z = 1` if `self.is_not_zero()`, and
183 // `z_inv * self.z = 0` if `self.is_zero()`.
184 //
185 // Thus, `z_inv * self.z = !self.is_zero()`.
186 z_inv.mul_equals(&self.z, &F::from(infinity.not()))?;
187
188 let non_zero_x = &self.x * &z_inv;
189 let non_zero_y = &self.y * &z_inv;
190
191 let x = infinity.select(&zero_x, &non_zero_x)?;
192 let y = infinity.select(&zero_y, &non_zero_y)?;
193
194 Ok(AffineVar::new(x, y, infinity))
195 }
196 }
197
198 /// Allocates a new variable without performing an on-curve check, which is
199 /// useful if the variable is known to be on the curve (eg., if the point
200 /// is a constant or is a public input).
201 #[tracing::instrument(target = "r1cs", skip(cs, f))]
202 pub fn new_variable_omit_on_curve_check(
203 cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
204 f: impl FnOnce() -> Result<SWProjective<P>, SynthesisError>,
205 mode: AllocationMode,
206 ) -> Result<Self, SynthesisError> {
207 let ns = cs.into();
208 let cs = ns.cs();
209
210 let (x, y, z) = match f() {
211 Ok(ge) => {
212 let ge = ge.into_affine();
213 if ge.is_zero() {
214 // These values are convenient since the point satisfies
215 // curve equation.
216 (
217 Ok(P::BaseField::zero()),
218 Ok(P::BaseField::one()),
219 Ok(P::BaseField::zero()),
220 )
221 } else {
222 (Ok(ge.x), Ok(ge.y), Ok(P::BaseField::one()))
223 }
224 },
225 _ => (
226 Err(SynthesisError::AssignmentMissing),
227 Err(SynthesisError::AssignmentMissing),
228 Err(SynthesisError::AssignmentMissing),
229 ),
230 };
231
232 let x = F::new_variable(ark_relations::ns!(cs, "x"), || x, mode)?;
233 let y = F::new_variable(ark_relations::ns!(cs, "y"), || y, mode)?;
234 let z = F::new_variable(ark_relations::ns!(cs, "z"), || z, mode)?;
235
236 Ok(Self::new(x, y, z))
237 }
238
239 /// Mixed addition, which is useful when `other = (x2, y2)` is known to have
240 /// z = 1.
241 #[tracing::instrument(target = "r1cs", skip(self, other))]
242 pub(crate) fn add_mixed(&self, other: &NonZeroAffineVar<P, F>) -> Result<Self, SynthesisError> {
243 // Complete mixed addition formula from Renes-Costello-Batina 2015
244 // Algorithm 2
245 // (https://eprint.iacr.org/2015/1060).
246 // Below, comments at the end of a line denote the corresponding
247 // step(s) of the algorithm
248 //
249 // Adapted from code in
250 // https://github.com/RustCrypto/elliptic-curves/blob/master/p256/src/arithmetic/projective.rs
251 let three_b = P::COEFF_B.double() + &P::COEFF_B;
252 let (x1, y1, z1) = (&self.x, &self.y, &self.z);
253 let (x2, y2) = (&other.x, &other.y);
254
255 let xx = x1 * x2; // 1
256 let yy = y1 * y2; // 2
257 let xy_pairs = ((x1 + y1) * &(x2 + y2)) - (&xx + &yy); // 4, 5, 6, 7, 8
258 let xz_pairs = (x2 * z1) + x1; // 8, 9
259 let yz_pairs = (y2 * z1) + y1; // 10, 11
260
261 let axz = mul_by_coeff_a::<P, F>(&xz_pairs); // 12
262
263 let bz3_part = &axz + z1 * three_b; // 13, 14
264
265 let yy_m_bz3 = &yy - &bz3_part; // 15
266 let yy_p_bz3 = &yy + &bz3_part; // 16
267
268 let azz = mul_by_coeff_a::<P, F>(z1); // 20
269 let xx3_p_azz = xx.double().unwrap() + &xx + &azz; // 18, 19, 22
270
271 let bxz3 = &xz_pairs * three_b; // 21
272 let b3_xz_pairs = mul_by_coeff_a::<P, F>(&(&xx - &azz)) + &bxz3; // 23, 24, 25
273
274 let x = (&yy_m_bz3 * &xy_pairs) - &yz_pairs * &b3_xz_pairs; // 28,29, 30
275 let y = (&yy_p_bz3 * &yy_m_bz3) + &xx3_p_azz * b3_xz_pairs; // 17, 26, 27
276 let z = (&yy_p_bz3 * &yz_pairs) + xy_pairs * xx3_p_azz; // 31, 32, 33
277
278 Ok(ProjectiveVar::new(x, y, z))
279 }
280
281 /// Computes a scalar multiplication with a little-endian scalar of size
282 /// `P::ScalarField::MODULUS_BITS`.
283 #[tracing::instrument(
284 target = "r1cs",
285 skip(self, mul_result, multiple_of_power_of_two, bits)
286 )]
287 fn fixed_scalar_mul_le(
288 &self,
289 mul_result: &mut Self,
290 multiple_of_power_of_two: &mut NonZeroAffineVar<P, F>,
291 bits: &[&Boolean<<P::BaseField as Field>::BasePrimeField>],
292 ) -> Result<(), SynthesisError> {
293 let scalar_modulus_bits = <P::ScalarField as PrimeField>::MODULUS_BIT_SIZE as usize;
294
295 assert!(scalar_modulus_bits >= bits.len());
296 let split_len = ark_std::cmp::min(scalar_modulus_bits - 2, bits.len());
297 let (affine_bits, proj_bits) = bits.split_at(split_len);
298 // Computes the standard little-endian double-and-add algorithm
299 // (Algorithm 3.26, Guide to Elliptic Curve Cryptography)
300 //
301 // We rely on *incomplete* affine formulae for partially computing this.
302 // However, we avoid exceptional edge cases because we partition the scalar
303 // into two chunks: one guaranteed to be less than p - 2, and the rest.
304 // We only use incomplete formulae for the first chunk, which means we avoid
305 // exceptions:
306 //
307 // `add_unchecked(a, b)` is incomplete when either `b.is_zero()`, or when
308 // `b = ±a`. During scalar multiplication, we don't hit either case:
309 // * `b = ±a`: `b = accumulator = k * a`, where `2 <= k < p - 1`. This implies
310 // that `k != p ± 1`, and so `b != (p ± 1) * a`. Because the group is finite,
311 // this in turn means that `b != ±a`, as required.
312 // * `a` or `b` is zero: for `a`, we handle the zero case after the loop; for
313 // `b`, notice that it is monotonically increasing, and furthermore, equals `k
314 // * a`, where `k != p = 0 mod p`.
315
316 // Unlike normal double-and-add, here we start off with a non-zero
317 // `accumulator`, because `NonZeroAffineVar::add_unchecked` doesn't
318 // support addition with `zero`. In more detail, we initialize
319 // `accumulator` to be the initial value of `multiple_of_power_of_two`.
320 // This ensures that all unchecked additions of `accumulator` with later
321 // values of `multiple_of_power_of_two` are safe. However, to do this
322 // correctly, we need to perform two steps:
323 // * We must skip the LSB, and instead proceed assuming that it was 1. Later, we
324 // will conditionally subtract the initial value of `accumulator`: if LSB ==
325 // 0: subtract initial_acc_value; else, subtract 0.
326 // * Because we are assuming the first bit, we must double
327 // `multiple_of_power_of_two`.
328
329 let mut accumulator = multiple_of_power_of_two.clone();
330 let initial_acc_value = accumulator.into_projective();
331
332 // The powers start at 2 (instead of 1) because we're skipping the first bit.
333 multiple_of_power_of_two.double_in_place()?;
334
335 // As mentioned, we will skip the LSB, and will later handle it via a
336 // conditional subtraction.
337 for bit in affine_bits.iter().skip(1) {
338 if bit.is_constant() {
339 if *bit == &Boolean::TRUE {
340 accumulator = accumulator.add_unchecked(multiple_of_power_of_two)?;
341 }
342 } else {
343 let temp = accumulator.add_unchecked(multiple_of_power_of_two)?;
344 accumulator = bit.select(&temp, &accumulator)?;
345 }
346 multiple_of_power_of_two.double_in_place()?;
347 }
348 // Perform conditional subtraction:
349
350 // We can convert to projective safely because the result is guaranteed to be
351 // non-zero by the condition on `affine_bits.len()`, and by the fact
352 // that `accumulator` is non-zero
353 let result = accumulator.into_projective();
354 // If bits[0] is 0, then we have to subtract `self`; else, we subtract zero.
355 let subtrahend = bits[0].select(&Self::zero(), &initial_acc_value)?;
356 *mul_result += result - subtrahend;
357
358 // Now, let's finish off the rest of the bits using our complete formulae
359 for bit in proj_bits {
360 if bit.is_constant() {
361 if *bit == &Boolean::TRUE {
362 *mul_result += &multiple_of_power_of_two.into_projective();
363 }
364 } else {
365 let temp = &*mul_result + &multiple_of_power_of_two.into_projective();
366 *mul_result = bit.select(&temp, &mul_result)?;
367 }
368 multiple_of_power_of_two.double_in_place()?;
369 }
370 Ok(())
371 }
372}
373
374impl<P, F> CurveVar<SWProjective<P>, <P::BaseField as Field>::BasePrimeField>
375 for ProjectiveVar<P, F>
376where
377 P: SWModelParameters,
378 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
379 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
380{
381 fn constant(g: SWProjective<P>) -> Self {
382 let cs = ConstraintSystemRef::None;
383 Self::new_variable_omit_on_curve_check(cs, || Ok(g), AllocationMode::Constant).unwrap()
384 }
385
386 fn zero() -> Self {
387 Self::new(F::zero(), F::one(), F::zero())
388 }
389
390 fn is_zero(&self) -> Result<Boolean<<P::BaseField as Field>::BasePrimeField>, SynthesisError> {
391 self.z.is_zero()
392 }
393
394 #[tracing::instrument(target = "r1cs", skip(cs, f))]
395 fn new_variable_omit_prime_order_check(
396 cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
397 f: impl FnOnce() -> Result<SWProjective<P>, SynthesisError>,
398 mode: AllocationMode,
399 ) -> Result<Self, SynthesisError> {
400 let ns = cs.into();
401 let cs = ns.cs();
402 // Curve equation in projective form:
403 // E: Y² * Z = X³ + aX * Z² + bZ³
404 //
405 // This can be re-written as
406 // E: Y² * Z - bZ³ = X³ + aX * Z²
407 // E: Z * (Y² - bZ²) = X * (X² + aZ²)
408 // so, compute X², Y², Z²,
409 // compute temp = X * (X² + aZ²)
410 // check Z.mul_equals((Y² - bZ²), temp)
411 //
412 // A total of 5 multiplications
413
414 let g = Self::new_variable_omit_on_curve_check(cs, f, mode)?;
415
416 if mode != AllocationMode::Constant {
417 // Perform on-curve check.
418 let b = P::COEFF_B;
419 let a = P::COEFF_A;
420
421 let x2 = g.x.square()?;
422 let y2 = g.y.square()?;
423 let z2 = g.z.square()?;
424 let t = &g.x * (x2 + &z2 * a);
425
426 g.z.mul_equals(&(y2 - z2 * b), &t)?;
427 }
428 Ok(g)
429 }
430
431 /// Enforce that `self` is in the prime-order subgroup.
432 ///
433 /// Does so by multiplying by the prime order, and checking that the result
434 /// is unchanged.
435 // TODO: at the moment this doesn't work, because the addition and doubling
436 // formulae are incomplete for even-order points.
437 #[tracing::instrument(target = "r1cs")]
438 fn enforce_prime_order(&self) -> Result<(), SynthesisError> {
439 unimplemented!("cannot enforce prime order");
440 // let r_minus_1 = (-P::ScalarField::one()).into_bigint();
441
442 // let mut result = Self::zero();
443 // for b in BitIteratorBE::without_leading_zeros(r_minus_1) {
444 // result.double_in_place()?;
445
446 // if b {
447 // result += self;
448 // }
449 // }
450 // self.negate()?.enforce_equal(&result)?;
451 // Ok(())
452 }
453
454 #[inline]
455 #[tracing::instrument(target = "r1cs")]
456 fn double_in_place(&mut self) -> Result<(), SynthesisError> {
457 // Complete doubling formula from Renes-Costello-Batina 2015
458 // Algorithm 3
459 // (https://eprint.iacr.org/2015/1060).
460 // Below, comments at the end of a line denote the corresponding
461 // step(s) of the algorithm
462 //
463 // Adapted from code in
464 // https://github.com/RustCrypto/elliptic-curves/blob/master/p256/src/arithmetic/projective.rs
465 let three_b = P::COEFF_B.double() + &P::COEFF_B;
466
467 let xx = self.x.square()?; // 1
468 let yy = self.y.square()?; // 2
469 let zz = self.z.square()?; // 3
470 let xy2 = (&self.x * &self.y).double()?; // 4, 5
471 let xz2 = (&self.x * &self.z).double()?; // 6, 7
472
473 let axz2 = mul_by_coeff_a::<P, F>(&xz2); // 8
474
475 let bzz3_part = &axz2 + &zz * three_b; // 9, 10
476 let yy_m_bzz3 = &yy - &bzz3_part; // 11
477 let yy_p_bzz3 = &yy + &bzz3_part; // 12
478 let y_frag = yy_p_bzz3 * &yy_m_bzz3; // 13
479 let x_frag = yy_m_bzz3 * &xy2; // 14
480
481 let bxz3 = xz2 * three_b; // 15
482 let azz = mul_by_coeff_a::<P, F>(&zz); // 16
483 let b3_xz_pairs = mul_by_coeff_a::<P, F>(&(&xx - &azz)) + &bxz3; // 15, 16, 17, 18, 19
484 let xx3_p_azz = (xx.double()? + &xx + &azz) * &b3_xz_pairs; // 23, 24, 25
485
486 let y = y_frag + &xx3_p_azz; // 26, 27
487 let yz2 = (&self.y * &self.z).double()?; // 28, 29
488 let x = x_frag - &(b3_xz_pairs * &yz2); // 30, 31
489 let z = (yz2 * &yy).double()?.double()?; // 32, 33, 34
490 self.x = x;
491 self.y = y;
492 self.z = z;
493 Ok(())
494 }
495
496 #[tracing::instrument(target = "r1cs")]
497 fn negate(&self) -> Result<Self, SynthesisError> {
498 Ok(Self::new(self.x.clone(), self.y.negate()?, self.z.clone()))
499 }
500
501 /// Computes `bits * self`, where `bits` is a little-endian
502 /// `Boolean` representation of a scalar.
503 #[tracing::instrument(target = "r1cs", skip(bits))]
504 fn scalar_mul_le<'a>(
505 &self,
506 bits: impl Iterator<Item = &'a Boolean<<P::BaseField as Field>::BasePrimeField>>,
507 ) -> Result<Self, SynthesisError> {
508 if self.is_constant() {
509 if self.value().unwrap().is_zero() {
510 return Ok(self.clone());
511 }
512 }
513 let self_affine = self.to_affine()?;
514 let (x, y, infinity) = (self_affine.x, self_affine.y, self_affine.infinity);
515 // We first handle the non-zero case, and then later
516 // will conditionally select zero if `self` was zero.
517 let non_zero_self = NonZeroAffineVar::new(x, y);
518
519 let mut bits = bits.collect::<Vec<_>>();
520 if bits.len() == 0 {
521 return Ok(Self::zero());
522 }
523 // Remove unnecessary constant zeros in the most-significant positions.
524 bits = bits
525 .into_iter()
526 // We iterate from the MSB down.
527 .rev()
528 // Skip leading zeros, if they are constants.
529 .skip_while(|b| b.is_constant() && (b.value().unwrap() == false))
530 .collect();
531 // After collecting we are in big-endian form; we have to reverse to get back to
532 // little-endian.
533 bits.reverse();
534
535 let scalar_modulus_bits = <P::ScalarField as PrimeField>::MODULUS_BIT_SIZE;
536 let mut mul_result = Self::zero();
537 let mut power_of_two_times_self = non_zero_self;
538 // We chunk up `bits` into `p`-sized chunks.
539 for bits in bits.chunks(scalar_modulus_bits as usize) {
540 self.fixed_scalar_mul_le(&mut mul_result, &mut power_of_two_times_self, bits)?;
541 }
542
543 // The foregoing algorithm relies on incomplete addition, and so does not
544 // work when the input (`self`) is zero. We hence have to perform
545 // a check to ensure that if the input is zero, then so is the output.
546 // The cost of this check should be less than the benefit of using
547 // mixed addition in almost all cases.
548 infinity.select(&Self::zero(), &mul_result)
549 }
550
551 #[tracing::instrument(target = "r1cs", skip(scalar_bits_with_bases))]
552 fn precomputed_base_scalar_mul_le<'a, I, B>(
553 &mut self,
554 scalar_bits_with_bases: I,
555 ) -> Result<(), SynthesisError>
556 where
557 I: Iterator<Item = (B, &'a SWProjective<P>)>,
558 B: Borrow<Boolean<<P::BaseField as Field>::BasePrimeField>>,
559 {
560 // We just ignore the provided bases and use the faster scalar multiplication.
561 let (bits, bases): (Vec<_>, Vec<_>) = scalar_bits_with_bases
562 .map(|(b, c)| (b.borrow().clone(), *c))
563 .unzip();
564 let base = bases[0];
565 *self += Self::constant(base).scalar_mul_le(bits.iter())?;
566 Ok(())
567 }
568}
569
570impl<P, F> ToConstraintFieldGadget<<P::BaseField as Field>::BasePrimeField> for ProjectiveVar<P, F>
571where
572 P: SWModelParameters,
573 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
574 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
575 F: ToConstraintFieldGadget<<P::BaseField as Field>::BasePrimeField>,
576{
577 fn to_constraint_field(
578 &self,
579 ) -> Result<Vec<FpVar<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
580 self.to_affine()?.to_constraint_field()
581 }
582}
583
584fn mul_by_coeff_a<
585 P: SWModelParameters,
586 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
587>(
588 f: &F,
589) -> F
590where
591 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
592{
593 if !P::COEFF_A.is_zero() {
594 f * P::COEFF_A
595 } else {
596 F::zero()
597 }
598}
599
600impl_bounded_ops!(
601 ProjectiveVar<P, F>,
602 SWProjective<P>,
603 Add,
604 add,
605 AddAssign,
606 add_assign,
607 |mut this: &'a ProjectiveVar<P, F>, mut other: &'a ProjectiveVar<P, F>| {
608 // Implement complete addition for Short Weierstrass curves, following
609 // the complete addition formula from Renes-Costello-Batina 2015
610 // (https://eprint.iacr.org/2015/1060).
611 //
612 // We special case handling of constants to get better constraint weight.
613 if this.is_constant() {
614 // we'll just act like `other` is constant.
615 core::mem::swap(&mut this, &mut other);
616 }
617
618 if other.is_constant() {
619 // The value should exist because `other` is a constant.
620 let other = other.value().unwrap();
621 if other.is_zero() {
622 // this + 0 = this
623 this.clone()
624 } else {
625 // We'll use mixed addition to add non-zero constants.
626 let x = F::constant(other.x);
627 let y = F::constant(other.y);
628 this.add_mixed(&NonZeroAffineVar::new(x, y)).unwrap()
629 }
630 } else {
631 // Complete addition formula from Renes-Costello-Batina 2015
632 // Algorithm 1
633 // (https://eprint.iacr.org/2015/1060).
634 // Below, comments at the end of a line denote the corresponding
635 // step(s) of the algorithm
636 //
637 // Adapted from code in
638 // https://github.com/RustCrypto/elliptic-curves/blob/master/p256/src/arithmetic/projective.rs
639 let three_b = P::COEFF_B.double() + &P::COEFF_B;
640 let (x1, y1, z1) = (&this.x, &this.y, &this.z);
641 let (x2, y2, z2) = (&other.x, &other.y, &other.z);
642
643 let xx = x1 * x2; // 1
644 let yy = y1 * y2; // 2
645 let zz = z1 * z2; // 3
646 let xy_pairs = ((x1 + y1) * &(x2 + y2)) - (&xx + &yy); // 4, 5, 6, 7, 8
647 let xz_pairs = ((x1 + z1) * &(x2 + z2)) - (&xx + &zz); // 9, 10, 11, 12, 13
648 let yz_pairs = ((y1 + z1) * &(y2 + z2)) - (&yy + &zz); // 14, 15, 16, 17, 18
649
650 let axz = mul_by_coeff_a::<P, F>(&xz_pairs); // 19
651
652 let bzz3_part = &axz + &zz * three_b; // 20, 21
653
654 let yy_m_bzz3 = &yy - &bzz3_part; // 22
655 let yy_p_bzz3 = &yy + &bzz3_part; // 23
656
657 let azz = mul_by_coeff_a::<P, F>(&zz);
658 let xx3_p_azz = xx.double().unwrap() + &xx + &azz; // 25, 26, 27, 29
659
660 let bxz3 = &xz_pairs * three_b; // 28
661 let b3_xz_pairs = mul_by_coeff_a::<P, F>(&(&xx - &azz)) + &bxz3; // 30, 31, 32
662
663 let x = (&yy_m_bzz3 * &xy_pairs) - &yz_pairs * &b3_xz_pairs; // 35, 39, 40
664 let y = (&yy_p_bzz3 * &yy_m_bzz3) + &xx3_p_azz * b3_xz_pairs; // 24, 36, 37, 38
665 let z = (&yy_p_bzz3 * &yz_pairs) + xy_pairs * xx3_p_azz; // 41, 42, 43
666
667 ProjectiveVar::new(x, y, z)
668 }
669
670 },
671 |this: &'a ProjectiveVar<P, F>, other: SWProjective<P>| {
672 this + ProjectiveVar::constant(other)
673 },
674 (F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>, P: SWModelParameters),
675 for <'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
676);
677
678impl_bounded_ops!(
679 ProjectiveVar<P, F>,
680 SWProjective<P>,
681 Sub,
682 sub,
683 SubAssign,
684 sub_assign,
685 |this: &'a ProjectiveVar<P, F>, other: &'a ProjectiveVar<P, F>| this + other.negate().unwrap(),
686 |this: &'a ProjectiveVar<P, F>, other: SWProjective<P>| this - ProjectiveVar::constant(other),
687 (F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>, P: SWModelParameters),
688 for <'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>
689);
690
691impl<'a, P, F> GroupOpsBounds<'a, SWProjective<P>, ProjectiveVar<P, F>> for ProjectiveVar<P, F>
692where
693 P: SWModelParameters,
694 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
695 for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
696{
697}
698
699impl<'a, P, F> GroupOpsBounds<'a, SWProjective<P>, ProjectiveVar<P, F>> for &'a ProjectiveVar<P, F>
700where
701 P: SWModelParameters,
702 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
703 for<'b> &'b F: FieldOpsBounds<'b, P::BaseField, F>,
704{
705}
706
707impl<P, F> CondSelectGadget<<P::BaseField as Field>::BasePrimeField> for ProjectiveVar<P, F>
708where
709 P: SWModelParameters,
710 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
711 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
712{
713 #[inline]
714 #[tracing::instrument(target = "r1cs")]
715 fn conditionally_select(
716 cond: &Boolean<<P::BaseField as Field>::BasePrimeField>,
717 true_value: &Self,
718 false_value: &Self,
719 ) -> Result<Self, SynthesisError> {
720 let x = cond.select(&true_value.x, &false_value.x)?;
721 let y = cond.select(&true_value.y, &false_value.y)?;
722 let z = cond.select(&true_value.z, &false_value.z)?;
723
724 Ok(Self::new(x, y, z))
725 }
726}
727
728impl<P, F> EqGadget<<P::BaseField as Field>::BasePrimeField> for ProjectiveVar<P, F>
729where
730 P: SWModelParameters,
731 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
732 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
733{
734 #[tracing::instrument(target = "r1cs")]
735 fn is_eq(
736 &self,
737 other: &Self,
738 ) -> Result<Boolean<<P::BaseField as Field>::BasePrimeField>, SynthesisError> {
739 let x_equal = (&self.x * &other.z).is_eq(&(&other.x * &self.z))?;
740 let y_equal = (&self.y * &other.z).is_eq(&(&other.y * &self.z))?;
741 let coordinates_equal = x_equal.and(&y_equal)?;
742 let both_are_zero = self.is_zero()?.and(&other.is_zero()?)?;
743 both_are_zero.or(&coordinates_equal)
744 }
745
746 #[inline]
747 #[tracing::instrument(target = "r1cs")]
748 fn conditional_enforce_equal(
749 &self,
750 other: &Self,
751 condition: &Boolean<<P::BaseField as Field>::BasePrimeField>,
752 ) -> Result<(), SynthesisError> {
753 let x_equal = (&self.x * &other.z).is_eq(&(&other.x * &self.z))?;
754 let y_equal = (&self.y * &other.z).is_eq(&(&other.y * &self.z))?;
755 let coordinates_equal = x_equal.and(&y_equal)?;
756 let both_are_zero = self.is_zero()?.and(&other.is_zero()?)?;
757 both_are_zero
758 .or(&coordinates_equal)?
759 .conditional_enforce_equal(&Boolean::Constant(true), condition)?;
760 Ok(())
761 }
762
763 #[inline]
764 #[tracing::instrument(target = "r1cs")]
765 fn conditional_enforce_not_equal(
766 &self,
767 other: &Self,
768 condition: &Boolean<<P::BaseField as Field>::BasePrimeField>,
769 ) -> Result<(), SynthesisError> {
770 let is_equal = self.is_eq(other)?;
771 is_equal
772 .and(condition)?
773 .enforce_equal(&Boolean::Constant(false))
774 }
775}
776
777impl<P, F> AllocVar<SWAffine<P>, <P::BaseField as Field>::BasePrimeField> for ProjectiveVar<P, F>
778where
779 P: SWModelParameters,
780 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
781 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
782{
783 fn new_variable<T: Borrow<SWAffine<P>>>(
784 cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
785 f: impl FnOnce() -> Result<T, SynthesisError>,
786 mode: AllocationMode,
787 ) -> Result<Self, SynthesisError> {
788 Self::new_variable(
789 cs,
790 || f().map(|b| SWProjective::from((*b.borrow()).clone())),
791 mode,
792 )
793 }
794}
795
796impl<P, F> AllocVar<SWProjective<P>, <P::BaseField as Field>::BasePrimeField>
797 for ProjectiveVar<P, F>
798where
799 P: SWModelParameters,
800 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
801 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
802{
803 fn new_variable<T: Borrow<SWProjective<P>>>(
804 cs: impl Into<Namespace<<P::BaseField as Field>::BasePrimeField>>,
805 f: impl FnOnce() -> Result<T, SynthesisError>,
806 mode: AllocationMode,
807 ) -> Result<Self, SynthesisError> {
808 let ns = cs.into();
809 let cs = ns.cs();
810 let f = || Ok(*f()?.borrow());
811 match mode {
812 AllocationMode::Constant => Self::new_variable_omit_prime_order_check(cs, f, mode),
813 AllocationMode::Input => Self::new_variable_omit_prime_order_check(cs, f, mode),
814 AllocationMode::Witness => {
815 // if cofactor.is_even():
816 // divide until you've removed all even factors
817 // else:
818 // just directly use double and add.
819 let mut power_of_2: u32 = 0;
820 let mut cofactor = P::COFACTOR.to_vec();
821 while cofactor[0] % 2 == 0 {
822 div2(&mut cofactor);
823 power_of_2 += 1;
824 }
825
826 let cofactor_weight = BitIteratorBE::new(cofactor.as_slice())
827 .filter(|b| *b)
828 .count();
829 let modulus_minus_1 = (-P::ScalarField::one()).into_bigint(); // r - 1
830 let modulus_minus_1_weight =
831 BitIteratorBE::new(modulus_minus_1).filter(|b| *b).count();
832
833 // We pick the most efficient method of performing the prime order check:
834 // If the cofactor has lower hamming weight than the scalar field's modulus,
835 // we first multiply by the inverse of the cofactor, and then, after allocating,
836 // multiply by the cofactor. This ensures the resulting point has no cofactors
837 //
838 // Else, we multiply by the scalar field's modulus and ensure that the result
839 // equals the identity.
840
841 let (mut ge, iter) = if cofactor_weight < modulus_minus_1_weight {
842 let ge = Self::new_variable_omit_prime_order_check(
843 ark_relations::ns!(cs, "Witness without subgroup check with cofactor mul"),
844 || f().map(|g| g.into_affine().mul_by_cofactor_inv().into()),
845 mode,
846 )?;
847 (
848 ge,
849 BitIteratorBE::without_leading_zeros(cofactor.as_slice()),
850 )
851 } else {
852 let ge = Self::new_variable_omit_prime_order_check(
853 ark_relations::ns!(cs, "Witness without subgroup check with `r` check"),
854 || {
855 f().map(|g| {
856 let g = g.into_affine();
857 let mut power_of_two = P::ScalarField::one().into_bigint();
858 power_of_two.muln(power_of_2);
859 let power_of_two_inv = P::ScalarField::from_bigint(power_of_two)
860 .and_then(|n| n.inverse())
861 .unwrap();
862 g.mul(power_of_two_inv)
863 })
864 },
865 mode,
866 )?;
867
868 (
869 ge,
870 BitIteratorBE::without_leading_zeros(modulus_minus_1.as_ref()),
871 )
872 };
873 // Remove the even part of the cofactor
874 for _ in 0..power_of_2 {
875 ge.double_in_place()?;
876 }
877
878 let mut result = Self::zero();
879 for b in iter {
880 result.double_in_place()?;
881
882 if b {
883 result += &ge
884 }
885 }
886 if cofactor_weight < modulus_minus_1_weight {
887 Ok(result)
888 } else {
889 ge.enforce_equal(&ge)?;
890 Ok(ge)
891 }
892 },
893 }
894 }
895}
896
897#[inline]
898fn div2(limbs: &mut [u64]) {
899 let mut t = 0;
900 for i in limbs.iter_mut().rev() {
901 let t2 = *i << 63;
902 *i >>= 1;
903 *i |= t;
904 t = t2;
905 }
906}
907
908impl<P, F> ToBitsGadget<<P::BaseField as Field>::BasePrimeField> for ProjectiveVar<P, F>
909where
910 P: SWModelParameters,
911 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
912 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
913{
914 #[tracing::instrument(target = "r1cs")]
915 fn to_bits_le(
916 &self,
917 ) -> Result<Vec<Boolean<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
918 let g = self.to_affine()?;
919 let mut bits = g.x.to_bits_le()?;
920 let y_bits = g.y.to_bits_le()?;
921 bits.extend_from_slice(&y_bits);
922 bits.push(g.infinity);
923 Ok(bits)
924 }
925
926 #[tracing::instrument(target = "r1cs")]
927 fn to_non_unique_bits_le(
928 &self,
929 ) -> Result<Vec<Boolean<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
930 let g = self.to_affine()?;
931 let mut bits = g.x.to_non_unique_bits_le()?;
932 let y_bits = g.y.to_non_unique_bits_le()?;
933 bits.extend_from_slice(&y_bits);
934 bits.push(g.infinity);
935 Ok(bits)
936 }
937}
938
939impl<P, F> ToBytesGadget<<P::BaseField as Field>::BasePrimeField> for ProjectiveVar<P, F>
940where
941 P: SWModelParameters,
942 F: FieldVar<P::BaseField, <P::BaseField as Field>::BasePrimeField>,
943 for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
944{
945 #[tracing::instrument(target = "r1cs")]
946 fn to_bytes(
947 &self,
948 ) -> Result<Vec<UInt8<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
949 let g = self.to_affine()?;
950 let mut bytes = g.x.to_bytes()?;
951 let y_bytes = g.y.to_bytes()?;
952 let inf_bytes = g.infinity.to_bytes()?;
953 bytes.extend_from_slice(&y_bytes);
954 bytes.extend_from_slice(&inf_bytes);
955 Ok(bytes)
956 }
957
958 #[tracing::instrument(target = "r1cs")]
959 fn to_non_unique_bytes(
960 &self,
961 ) -> Result<Vec<UInt8<<P::BaseField as Field>::BasePrimeField>>, SynthesisError> {
962 let g = self.to_affine()?;
963 let mut bytes = g.x.to_non_unique_bytes()?;
964 let y_bytes = g.y.to_non_unique_bytes()?;
965 let inf_bytes = g.infinity.to_non_unique_bytes()?;
966 bytes.extend_from_slice(&y_bytes);
967 bytes.extend_from_slice(&inf_bytes);
968 Ok(bytes)
969 }
970}