ark-r1cs-std/src/groups/curves/short_weierstrass/mnt6/mod.rs
src/groups/curves/short_weierstrass/mnt6/mod.rsRaw
1use ark_ec::mnt6::{
2 g2::{AteAdditionCoefficients, AteDoubleCoefficients},
3 G1Prepared, G2Prepared, MNT6Parameters,
4};
5use ark_ff::Field;
6use ark_relations::r1cs::{Namespace, SynthesisError};
7
8use crate::{
9 fields::{fp::FpVar, fp3::Fp3Var, FieldVar},
10 groups::curves::short_weierstrass::ProjectiveVar,
11 pairing::mnt6::PairingVar,
12 prelude::*,
13 Vec,
14};
15use core::borrow::Borrow;
16
17/// Represents a projective point in G1.
18pub type G1Var<P> =
19 ProjectiveVar<<P as MNT6Parameters>::G1Parameters, FpVar<<P as MNT6Parameters>::Fp>>;
20
21/// Represents a projective point in G2.
22pub type G2Var<P> = ProjectiveVar<<P as MNT6Parameters>::G2Parameters, Fp3G<P>>;
23
24/// Represents the cached precomputation that can be performed on a G1 element
25/// which enables speeding up pairing computation.
26#[derive(Derivative)]
27#[derivative(Clone(bound = "P: MNT6Parameters"), Debug(bound = "P: MNT6Parameters"))]
28pub struct G1PreparedVar<P: MNT6Parameters> {
29 #[doc(hidden)]
30 pub x: FpVar<P::Fp>,
31 #[doc(hidden)]
32 pub y: FpVar<P::Fp>,
33 #[doc(hidden)]
34 pub x_twist: Fp3Var<P::Fp3Params>,
35 #[doc(hidden)]
36 pub y_twist: Fp3Var<P::Fp3Params>,
37}
38
39impl<P: MNT6Parameters> G1PreparedVar<P> {
40 /// Returns the value assigned to `self` in the underlying constraint
41 /// system.
42 pub fn value(&self) -> Result<G1Prepared<P>, SynthesisError> {
43 let x = self.x.value()?;
44 let y = self.y.value()?;
45 let x_twist = self.x_twist.value()?;
46 let y_twist = self.y_twist.value()?;
47 Ok(G1Prepared {
48 x,
49 y,
50 x_twist,
51 y_twist,
52 })
53 }
54
55 /// Constructs `Self` from a `G1Var`.
56 #[tracing::instrument(target = "r1cs")]
57 pub fn from_group_var(q: &G1Var<P>) -> Result<Self, SynthesisError> {
58 let q = q.to_affine()?;
59 let zero = FpVar::<P::Fp>::zero();
60 let x_twist = Fp3Var::new(q.x.clone(), zero.clone(), zero.clone()) * P::TWIST;
61 let y_twist = Fp3Var::new(q.y.clone(), zero.clone(), zero) * P::TWIST;
62 let result = G1PreparedVar {
63 x: q.x,
64 y: q.y,
65 x_twist,
66 y_twist,
67 };
68 Ok(result)
69 }
70}
71
72impl<P: MNT6Parameters> AllocVar<G1Prepared<P>, P::Fp> for G1PreparedVar<P> {
73 #[tracing::instrument(target = "r1cs", skip(cs, f))]
74 fn new_variable<T: Borrow<G1Prepared<P>>>(
75 cs: impl Into<Namespace<P::Fp>>,
76 f: impl FnOnce() -> Result<T, SynthesisError>,
77 mode: AllocationMode,
78 ) -> Result<Self, SynthesisError> {
79 let ns = cs.into();
80 let cs = ns.cs();
81
82 let g1_prep = f().map(|b| *b.borrow());
83
84 let x = FpVar::new_variable(ark_relations::ns!(cs, "x"), || g1_prep.map(|g| g.x), mode)?;
85 let y = FpVar::new_variable(ark_relations::ns!(cs, "y"), || g1_prep.map(|g| g.y), mode)?;
86 let x_twist = Fp3Var::new_variable(
87 ark_relations::ns!(cs, "x_twist"),
88 || g1_prep.map(|g| g.x_twist),
89 mode,
90 )?;
91 let y_twist = Fp3Var::new_variable(
92 ark_relations::ns!(cs, "y_twist"),
93 || g1_prep.map(|g| g.y_twist),
94 mode,
95 )?;
96 Ok(Self {
97 x,
98 y,
99 x_twist,
100 y_twist,
101 })
102 }
103}
104
105impl<P: MNT6Parameters> ToBytesGadget<P::Fp> for G1PreparedVar<P> {
106 #[inline]
107 #[tracing::instrument(target = "r1cs")]
108 fn to_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
109 let mut x = self.x.to_bytes()?;
110 let mut y = self.y.to_bytes()?;
111 let mut x_twist = self.x_twist.to_bytes()?;
112 let mut y_twist = self.y_twist.to_bytes()?;
113
114 x.append(&mut y);
115 x.append(&mut x_twist);
116 x.append(&mut y_twist);
117 Ok(x)
118 }
119
120 #[tracing::instrument(target = "r1cs")]
121 fn to_non_unique_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
122 let mut x = self.x.to_non_unique_bytes()?;
123 let mut y = self.y.to_non_unique_bytes()?;
124 let mut x_twist = self.x_twist.to_non_unique_bytes()?;
125 let mut y_twist = self.y_twist.to_non_unique_bytes()?;
126
127 x.append(&mut y);
128 x.append(&mut x_twist);
129 x.append(&mut y_twist);
130 Ok(x)
131 }
132}
133
134type Fp3G<P> = Fp3Var<<P as MNT6Parameters>::Fp3Params>;
135
136/// Represents the cached precomputation that can be performed on a G2 element
137/// which enables speeding up pairing computation.
138#[derive(Derivative)]
139#[derivative(Clone(bound = "P: MNT6Parameters"), Debug(bound = "P: MNT6Parameters"))]
140pub struct G2PreparedVar<P: MNT6Parameters> {
141 #[doc(hidden)]
142 pub x: Fp3Var<P::Fp3Params>,
143 #[doc(hidden)]
144 pub y: Fp3Var<P::Fp3Params>,
145 #[doc(hidden)]
146 pub x_over_twist: Fp3Var<P::Fp3Params>,
147 #[doc(hidden)]
148 pub y_over_twist: Fp3Var<P::Fp3Params>,
149 #[doc(hidden)]
150 pub double_coefficients: Vec<AteDoubleCoefficientsVar<P>>,
151 #[doc(hidden)]
152 pub addition_coefficients: Vec<AteAdditionCoefficientsVar<P>>,
153}
154
155impl<P: MNT6Parameters> AllocVar<G2Prepared<P>, P::Fp> for G2PreparedVar<P> {
156 #[tracing::instrument(target = "r1cs", skip(cs, f))]
157 fn new_variable<T: Borrow<G2Prepared<P>>>(
158 cs: impl Into<Namespace<P::Fp>>,
159 f: impl FnOnce() -> Result<T, SynthesisError>,
160 mode: AllocationMode,
161 ) -> Result<Self, SynthesisError> {
162 let ns = cs.into();
163 let cs = ns.cs();
164
165 let g2_prep = f().map(|b| b.borrow().clone());
166 let g2 = g2_prep.as_ref().map_err(|e| *e);
167
168 let x = Fp3Var::new_variable(ark_relations::ns!(cs, "x"), || g2.map(|g| g.x), mode)?;
169 let y = Fp3Var::new_variable(ark_relations::ns!(cs, "y"), || g2.map(|g| g.y), mode)?;
170 let x_over_twist = Fp3Var::new_variable(
171 ark_relations::ns!(cs, "x_over_twist"),
172 || g2.map(|g| g.x_over_twist),
173 mode,
174 )?;
175 let y_over_twist = Fp3Var::new_variable(
176 ark_relations::ns!(cs, "y_over_twist"),
177 || g2.map(|g| g.y_over_twist),
178 mode,
179 )?;
180 let double_coefficients = Vec::new_variable(
181 ark_relations::ns!(cs, "double coeffs"),
182 || g2.map(|g| g.double_coefficients.clone()),
183 mode,
184 )?;
185 let addition_coefficients = Vec::new_variable(
186 ark_relations::ns!(cs, "add coeffs"),
187 || g2.map(|g| g.addition_coefficients.clone()),
188 mode,
189 )?;
190 Ok(Self {
191 x,
192 y,
193 x_over_twist,
194 y_over_twist,
195 double_coefficients,
196 addition_coefficients,
197 })
198 }
199}
200
201impl<P: MNT6Parameters> ToBytesGadget<P::Fp> for G2PreparedVar<P> {
202 #[inline]
203 #[tracing::instrument(target = "r1cs")]
204 fn to_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
205 let mut x = self.x.to_bytes()?;
206 let mut y = self.y.to_bytes()?;
207 let mut x_over_twist = self.x_over_twist.to_bytes()?;
208 let mut y_over_twist = self.y_over_twist.to_bytes()?;
209
210 x.append(&mut y);
211 x.append(&mut x_over_twist);
212 x.append(&mut y_over_twist);
213
214 for coeff in self.double_coefficients.iter() {
215 x.extend_from_slice(&coeff.to_bytes()?);
216 }
217 for coeff in self.addition_coefficients.iter() {
218 x.extend_from_slice(&coeff.to_bytes()?);
219 }
220 Ok(x)
221 }
222
223 #[tracing::instrument(target = "r1cs")]
224 fn to_non_unique_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
225 let mut x = self.x.to_non_unique_bytes()?;
226 let mut y = self.y.to_non_unique_bytes()?;
227 let mut x_over_twist = self.x_over_twist.to_non_unique_bytes()?;
228 let mut y_over_twist = self.y_over_twist.to_non_unique_bytes()?;
229
230 x.append(&mut y);
231 x.append(&mut x_over_twist);
232 x.append(&mut y_over_twist);
233
234 for coeff in self.double_coefficients.iter() {
235 x.extend_from_slice(&coeff.to_non_unique_bytes()?);
236 }
237 for coeff in self.addition_coefficients.iter() {
238 x.extend_from_slice(&coeff.to_non_unique_bytes()?);
239 }
240 Ok(x)
241 }
242}
243
244impl<P: MNT6Parameters> G2PreparedVar<P> {
245 /// Returns the value assigned to `self` in the underlying constraint
246 /// system.
247 pub fn value(&self) -> Result<G2Prepared<P>, SynthesisError> {
248 let x = self.x.value()?;
249 let y = self.y.value()?;
250 let x_over_twist = self.x_over_twist.value()?;
251 let y_over_twist = self.y_over_twist.value()?;
252 let double_coefficients = self
253 .double_coefficients
254 .iter()
255 .map(|coeff| coeff.value())
256 .collect::<Result<Vec<_>, SynthesisError>>()?;
257 let addition_coefficients = self
258 .addition_coefficients
259 .iter()
260 .map(|coeff| coeff.value())
261 .collect::<Result<Vec<_>, SynthesisError>>()?;
262 Ok(G2Prepared {
263 x,
264 y,
265 x_over_twist,
266 y_over_twist,
267 double_coefficients,
268 addition_coefficients,
269 })
270 }
271
272 /// Constructs `Self` from a `G2Var`.
273 #[tracing::instrument(target = "r1cs")]
274 pub fn from_group_var(q: &G2Var<P>) -> Result<Self, SynthesisError> {
275 let q = q.to_affine()?;
276 let twist_inv = P::TWIST.inverse().unwrap();
277
278 let mut g2p = G2PreparedVar {
279 x: q.x.clone(),
280 y: q.y.clone(),
281 x_over_twist: &q.x * twist_inv,
282 y_over_twist: &q.y * twist_inv,
283 double_coefficients: vec![],
284 addition_coefficients: vec![],
285 };
286
287 let mut r = G2ProjectiveExtendedVar {
288 x: q.x.clone(),
289 y: q.y.clone(),
290 z: Fp3G::<P>::one(),
291 t: Fp3G::<P>::one(),
292 };
293
294 for (idx, value) in P::ATE_LOOP_COUNT.iter().rev().enumerate() {
295 let mut tmp = *value;
296 let skip_extraneous_bits = 64 - value.leading_zeros();
297 let mut v = Vec::with_capacity(16);
298 for i in 0..64 {
299 if idx == 0 && (i == 0 || i >= skip_extraneous_bits) {
300 continue;
301 }
302 v.push(tmp & 1 == 1);
303 tmp >>= 1;
304 }
305
306 for bit in v.iter().rev() {
307 let (r2, coeff) = PairingVar::<P>::doubling_step_for_flipped_miller_loop(&r)?;
308 g2p.double_coefficients.push(coeff);
309 r = r2;
310
311 if *bit {
312 let (r2, coeff) = PairingVar::<P>::mixed_addition_step_for_flipped_miller_loop(
313 &q.x, &q.y, &r,
314 )?;
315 g2p.addition_coefficients.push(coeff);
316 r = r2;
317 }
318
319 tmp >>= 1;
320 }
321 }
322
323 if P::ATE_IS_LOOP_COUNT_NEG {
324 let rz_inv = r.z.inverse()?;
325 let rz2_inv = rz_inv.square()?;
326 let rz3_inv = &rz_inv * &rz2_inv;
327
328 let minus_r_affine_x = &r.x * &rz2_inv;
329 let minus_r_affine_y = r.y.negate()? * &rz3_inv;
330
331 let add_result = PairingVar::<P>::mixed_addition_step_for_flipped_miller_loop(
332 &minus_r_affine_x,
333 &minus_r_affine_y,
334 &r,
335 )?;
336 g2p.addition_coefficients.push(add_result.1);
337 }
338
339 Ok(g2p)
340 }
341}
342
343#[doc(hidden)]
344#[derive(Derivative)]
345#[derivative(Clone(bound = "P: MNT6Parameters"), Debug(bound = "P: MNT6Parameters"))]
346pub struct AteDoubleCoefficientsVar<P: MNT6Parameters> {
347 pub c_h: Fp3Var<P::Fp3Params>,
348 pub c_4c: Fp3Var<P::Fp3Params>,
349 pub c_j: Fp3Var<P::Fp3Params>,
350 pub c_l: Fp3Var<P::Fp3Params>,
351}
352
353impl<P: MNT6Parameters> AllocVar<AteDoubleCoefficients<P>, P::Fp> for AteDoubleCoefficientsVar<P> {
354 #[tracing::instrument(target = "r1cs", skip(cs, f))]
355 fn new_variable<T: Borrow<AteDoubleCoefficients<P>>>(
356 cs: impl Into<Namespace<P::Fp>>,
357 f: impl FnOnce() -> Result<T, SynthesisError>,
358 mode: AllocationMode,
359 ) -> Result<Self, SynthesisError> {
360 let ns = cs.into();
361 let cs = ns.cs();
362
363 let c_prep = f().map(|c| c.borrow().clone());
364 let c = c_prep.as_ref().map_err(|e| *e);
365
366 let c_h = Fp3Var::new_variable(ark_relations::ns!(cs, "c_h"), || c.map(|c| c.c_h), mode)?;
367 let c_4c =
368 Fp3Var::new_variable(ark_relations::ns!(cs, "c_4c"), || c.map(|c| c.c_4c), mode)?;
369 let c_j = Fp3Var::new_variable(ark_relations::ns!(cs, "c_j"), || c.map(|c| c.c_j), mode)?;
370 let c_l = Fp3Var::new_variable(ark_relations::ns!(cs, "c_l"), || c.map(|c| c.c_l), mode)?;
371 Ok(Self {
372 c_h,
373 c_4c,
374 c_j,
375 c_l,
376 })
377 }
378}
379
380impl<P: MNT6Parameters> ToBytesGadget<P::Fp> for AteDoubleCoefficientsVar<P> {
381 #[inline]
382 #[tracing::instrument(target = "r1cs")]
383 fn to_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
384 let mut c_h = self.c_h.to_bytes()?;
385 let mut c_4c = self.c_4c.to_bytes()?;
386 let mut c_j = self.c_j.to_bytes()?;
387 let mut c_l = self.c_l.to_bytes()?;
388
389 c_h.append(&mut c_4c);
390 c_h.append(&mut c_j);
391 c_h.append(&mut c_l);
392 Ok(c_h)
393 }
394
395 #[tracing::instrument(target = "r1cs")]
396 fn to_non_unique_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
397 let mut c_h = self.c_h.to_non_unique_bytes()?;
398 let mut c_4c = self.c_4c.to_non_unique_bytes()?;
399 let mut c_j = self.c_j.to_non_unique_bytes()?;
400 let mut c_l = self.c_l.to_non_unique_bytes()?;
401
402 c_h.append(&mut c_4c);
403 c_h.append(&mut c_j);
404 c_h.append(&mut c_l);
405 Ok(c_h)
406 }
407}
408
409impl<P: MNT6Parameters> AteDoubleCoefficientsVar<P> {
410 /// Returns the value assigned to `self` in the underlying constraint
411 /// system.
412 pub fn value(&self) -> Result<AteDoubleCoefficients<P>, SynthesisError> {
413 let c_h = self.c_h.value()?;
414 let c_4c = self.c_4c.value()?;
415 let c_j = self.c_j.value()?;
416 let c_l = self.c_l.value()?;
417 Ok(AteDoubleCoefficients {
418 c_h,
419 c_4c,
420 c_j,
421 c_l,
422 })
423 }
424}
425
426#[doc(hidden)]
427#[derive(Derivative)]
428#[derivative(Clone(bound = "P: MNT6Parameters"), Debug(bound = "P: MNT6Parameters"))]
429pub struct AteAdditionCoefficientsVar<P: MNT6Parameters> {
430 pub c_l1: Fp3Var<P::Fp3Params>,
431 pub c_rz: Fp3Var<P::Fp3Params>,
432}
433
434impl<P: MNT6Parameters> AllocVar<AteAdditionCoefficients<P>, P::Fp>
435 for AteAdditionCoefficientsVar<P>
436{
437 #[tracing::instrument(target = "r1cs", skip(cs, f))]
438 fn new_variable<T: Borrow<AteAdditionCoefficients<P>>>(
439 cs: impl Into<Namespace<P::Fp>>,
440 f: impl FnOnce() -> Result<T, SynthesisError>,
441 mode: AllocationMode,
442 ) -> Result<Self, SynthesisError> {
443 let ns = cs.into();
444 let cs = ns.cs();
445
446 let c_prep = f().map(|c| c.borrow().clone());
447 let c = c_prep.as_ref().map_err(|e| *e);
448
449 let c_l1 =
450 Fp3Var::new_variable(ark_relations::ns!(cs, "c_l1"), || c.map(|c| c.c_l1), mode)?;
451 let c_rz =
452 Fp3Var::new_variable(ark_relations::ns!(cs, "c_rz"), || c.map(|c| c.c_rz), mode)?;
453 Ok(Self { c_l1, c_rz })
454 }
455}
456
457impl<P: MNT6Parameters> ToBytesGadget<P::Fp> for AteAdditionCoefficientsVar<P> {
458 #[inline]
459 #[tracing::instrument(target = "r1cs")]
460 fn to_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
461 let mut c_l1 = self.c_l1.to_bytes()?;
462 let mut c_rz = self.c_rz.to_bytes()?;
463
464 c_l1.append(&mut c_rz);
465 Ok(c_l1)
466 }
467
468 #[tracing::instrument(target = "r1cs")]
469 fn to_non_unique_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
470 let mut c_l1 = self.c_l1.to_non_unique_bytes()?;
471 let mut c_rz = self.c_rz.to_non_unique_bytes()?;
472
473 c_l1.append(&mut c_rz);
474 Ok(c_l1)
475 }
476}
477
478impl<P: MNT6Parameters> AteAdditionCoefficientsVar<P> {
479 /// Returns the value assigned to `self` in the underlying constraint
480 /// system.
481 pub fn value(&self) -> Result<AteAdditionCoefficients<P>, SynthesisError> {
482 let c_l1 = self.c_l1.value()?;
483 let c_rz = self.c_rz.value()?;
484 Ok(AteAdditionCoefficients { c_l1, c_rz })
485 }
486}
487
488#[doc(hidden)]
489pub struct G2ProjectiveExtendedVar<P: MNT6Parameters> {
490 pub x: Fp3Var<P::Fp3Params>,
491 pub y: Fp3Var<P::Fp3Params>,
492 pub z: Fp3Var<P::Fp3Params>,
493 pub t: Fp3Var<P::Fp3Params>,
494}