ark-r1cs-std/src/groups/curves/short_weierstrass/bls12/mod.rs
src/groups/curves/short_weierstrass/bls12/mod.rsRaw
1use ark_ec::{
2 bls12::{Bls12Parameters, G1Prepared, G2Prepared, TwistType},
3 short_weierstrass_jacobian::GroupAffine,
4};
5use ark_ff::{BitIteratorBE, Field, One};
6use ark_relations::r1cs::{Namespace, SynthesisError};
7
8use crate::{
9 fields::{fp::FpVar, fp2::Fp2Var, FieldVar},
10 groups::curves::short_weierstrass::*,
11 Vec,
12};
13use core::fmt::Debug;
14
15/// Represents a projective point in G1.
16pub type G1Var<P> =
17 ProjectiveVar<<P as Bls12Parameters>::G1Parameters, FpVar<<P as Bls12Parameters>::Fp>>;
18
19/// Represents an affine point on G1. Should be used only for comparison and
20/// when a canonical representation of a point is required, and not for
21/// arithmetic.
22pub type G1AffineVar<P> =
23 AffineVar<<P as Bls12Parameters>::G1Parameters, FpVar<<P as Bls12Parameters>::Fp>>;
24
25/// Represents a projective point in G2.
26pub type G2Var<P> = ProjectiveVar<<P as Bls12Parameters>::G2Parameters, Fp2G<P>>;
27/// Represents an affine point on G2. Should be used only for comparison and
28/// when a canonical representation of a point is required, and not for
29/// arithmetic.
30pub type G2AffineVar<P> = AffineVar<<P as Bls12Parameters>::G2Parameters, Fp2G<P>>;
31
32/// Represents the cached precomputation that can be performed on a G1 element
33/// which enables speeding up pairing computation.
34#[derive(Derivative)]
35#[derivative(Clone(bound = "G1Var<P>: Clone"), Debug(bound = "G1Var<P>: Debug"))]
36pub struct G1PreparedVar<P: Bls12Parameters>(pub AffineVar<P::G1Parameters, FpVar<P::Fp>>);
37
38impl<P: Bls12Parameters> G1PreparedVar<P> {
39 /// Returns the value assigned to `self` in the underlying constraint
40 /// system.
41 pub fn value(&self) -> Result<G1Prepared<P>, SynthesisError> {
42 let x = self.0.x.value()?;
43 let y = self.0.y.value()?;
44 let infinity = self.0.infinity.value()?;
45 let g = GroupAffine::new(x, y, infinity);
46 Ok(g.into())
47 }
48
49 /// Constructs `Self` from a `G1Var`.
50 pub fn from_group_var(q: &G1Var<P>) -> Result<Self, SynthesisError> {
51 let g = q.to_affine()?;
52 Ok(Self(g))
53 }
54}
55
56impl<P: Bls12Parameters> AllocVar<G1Prepared<P>, P::Fp> for G1PreparedVar<P> {
57 fn new_variable<T: Borrow<G1Prepared<P>>>(
58 cs: impl Into<Namespace<P::Fp>>,
59 f: impl FnOnce() -> Result<T, SynthesisError>,
60 mode: AllocationMode,
61 ) -> Result<Self, SynthesisError> {
62 let ns = cs.into();
63 let cs = ns.cs();
64 let g1_prep = f().map(|b| b.borrow().0);
65
66 let x = FpVar::new_variable(ark_relations::ns!(cs, "x"), || g1_prep.map(|g| g.x), mode)?;
67 let y = FpVar::new_variable(ark_relations::ns!(cs, "y"), || g1_prep.map(|g| g.y), mode)?;
68 let infinity = Boolean::new_variable(
69 ark_relations::ns!(cs, "inf"),
70 || g1_prep.map(|g| g.infinity),
71 mode,
72 )?;
73 let g = AffineVar::new(x, y, infinity);
74 Ok(Self(g))
75 }
76}
77
78impl<P: Bls12Parameters> ToBytesGadget<P::Fp> for G1PreparedVar<P> {
79 #[inline]
80 #[tracing::instrument(target = "r1cs")]
81 fn to_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
82 let mut bytes = self.0.x.to_bytes()?;
83 let y_bytes = self.0.y.to_bytes()?;
84 let inf_bytes = self.0.infinity.to_bytes()?;
85 bytes.extend_from_slice(&y_bytes);
86 bytes.extend_from_slice(&inf_bytes);
87 Ok(bytes)
88 }
89
90 #[tracing::instrument(target = "r1cs")]
91 fn to_non_unique_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
92 let mut bytes = self.0.x.to_non_unique_bytes()?;
93 let y_bytes = self.0.y.to_non_unique_bytes()?;
94 let inf_bytes = self.0.infinity.to_non_unique_bytes()?;
95 bytes.extend_from_slice(&y_bytes);
96 bytes.extend_from_slice(&inf_bytes);
97 Ok(bytes)
98 }
99}
100
101type Fp2G<P> = Fp2Var<<P as Bls12Parameters>::Fp2Config>;
102type LCoeff<P> = (Fp2G<P>, Fp2G<P>);
103/// Represents the cached precomputation that can be performed on a G2 element
104/// which enables speeding up pairing computation.
105#[derive(Derivative)]
106#[derivative(
107 Clone(bound = "Fp2Var<P::Fp2Config>: Clone"),
108 Debug(bound = "Fp2Var<P::Fp2Config>: Debug")
109)]
110pub struct G2PreparedVar<P: Bls12Parameters> {
111 #[doc(hidden)]
112 pub ell_coeffs: Vec<LCoeff<P>>,
113}
114
115impl<P: Bls12Parameters> AllocVar<G2Prepared<P>, P::Fp> for G2PreparedVar<P> {
116 #[tracing::instrument(target = "r1cs", skip(cs, f, mode))]
117 fn new_variable<T: Borrow<G2Prepared<P>>>(
118 cs: impl Into<Namespace<P::Fp>>,
119 f: impl FnOnce() -> Result<T, SynthesisError>,
120 mode: AllocationMode,
121 ) -> Result<Self, SynthesisError> {
122 let ns = cs.into();
123 let cs = ns.cs();
124 let g2_prep = f().map(|b| {
125 let projective_coeffs = &b.borrow().ell_coeffs;
126 match P::TWIST_TYPE {
127 TwistType::M => {
128 let mut z_s = projective_coeffs
129 .iter()
130 .map(|(_, _, z)| *z)
131 .collect::<Vec<_>>();
132 ark_ff::fields::batch_inversion(&mut z_s);
133 projective_coeffs
134 .iter()
135 .zip(z_s)
136 .map(|((x, y, _), z_inv)| (*x * &z_inv, *y * &z_inv))
137 .collect::<Vec<_>>()
138 },
139 TwistType::D => {
140 let mut z_s = projective_coeffs
141 .iter()
142 .map(|(z, _, _)| *z)
143 .collect::<Vec<_>>();
144 ark_ff::fields::batch_inversion(&mut z_s);
145 projective_coeffs
146 .iter()
147 .zip(z_s)
148 .map(|((_, x, y), z_inv)| (*x * &z_inv, *y * &z_inv))
149 .collect::<Vec<_>>()
150 },
151 }
152 });
153
154 let l = Vec::new_variable(
155 ark_relations::ns!(cs, "l"),
156 || {
157 g2_prep
158 .clone()
159 .map(|c| c.iter().map(|(l, _)| *l).collect::<Vec<_>>())
160 },
161 mode,
162 )?;
163 let r = Vec::new_variable(
164 ark_relations::ns!(cs, "r"),
165 || g2_prep.map(|c| c.iter().map(|(_, r)| *r).collect::<Vec<_>>()),
166 mode,
167 )?;
168 let ell_coeffs = l.into_iter().zip(r).collect();
169 Ok(Self { ell_coeffs })
170 }
171}
172
173impl<P: Bls12Parameters> ToBytesGadget<P::Fp> for G2PreparedVar<P> {
174 #[inline]
175 #[tracing::instrument(target = "r1cs")]
176 fn to_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
177 let mut bytes = Vec::new();
178 for coeffs in &self.ell_coeffs {
179 bytes.extend_from_slice(&coeffs.0.to_bytes()?);
180 bytes.extend_from_slice(&coeffs.1.to_bytes()?);
181 }
182 Ok(bytes)
183 }
184
185 #[tracing::instrument(target = "r1cs")]
186 fn to_non_unique_bytes(&self) -> Result<Vec<UInt8<P::Fp>>, SynthesisError> {
187 let mut bytes = Vec::new();
188 for coeffs in &self.ell_coeffs {
189 bytes.extend_from_slice(&coeffs.0.to_non_unique_bytes()?);
190 bytes.extend_from_slice(&coeffs.1.to_non_unique_bytes()?);
191 }
192 Ok(bytes)
193 }
194}
195
196impl<P: Bls12Parameters> G2PreparedVar<P> {
197 /// Constructs `Self` from a `G2Var`.
198 #[tracing::instrument(target = "r1cs")]
199 pub fn from_group_var(q: &G2Var<P>) -> Result<Self, SynthesisError> {
200 let q = q.to_affine()?;
201 let two_inv = P::Fp::one().double().inverse().unwrap();
202 // Enforce that `q` is not the point at infinity.
203 q.infinity.enforce_not_equal(&Boolean::Constant(true))?;
204 let mut ell_coeffs = vec![];
205 let mut r = q.clone();
206
207 for i in BitIteratorBE::new(P::X).skip(1) {
208 ell_coeffs.push(Self::double(&mut r, &two_inv)?);
209
210 if i {
211 ell_coeffs.push(Self::add(&mut r, &q)?);
212 }
213 }
214
215 Ok(Self { ell_coeffs })
216 }
217
218 #[tracing::instrument(target = "r1cs")]
219 fn double(r: &mut G2AffineVar<P>, two_inv: &P::Fp) -> Result<LCoeff<P>, SynthesisError> {
220 let a = r.y.inverse()?;
221 let mut b = r.x.square()?;
222 let b_tmp = b.clone();
223 b.mul_assign_by_base_field_constant(*two_inv);
224 b += &b_tmp;
225
226 let c = &a * &b;
227 let d = r.x.double()?;
228 let x3 = c.square()? - &d;
229 let e = &c * &r.x - &r.y;
230 let c_x3 = &c * &x3;
231 let y3 = &e - &c_x3;
232 let mut f = c;
233 f.negate_in_place()?;
234 r.x = x3;
235 r.y = y3;
236 match P::TWIST_TYPE {
237 TwistType::M => Ok((e, f)),
238 TwistType::D => Ok((f, e)),
239 }
240 }
241
242 #[tracing::instrument(target = "r1cs")]
243 fn add(r: &mut G2AffineVar<P>, q: &G2AffineVar<P>) -> Result<LCoeff<P>, SynthesisError> {
244 let a = (&q.x - &r.x).inverse()?;
245 let b = &q.y - &r.y;
246 let c = &a * &b;
247 let d = &r.x + &q.x;
248 let x3 = c.square()? - &d;
249
250 let e = (&r.x - &x3) * &c;
251 let y3 = e - &r.y;
252 let g = &c * &r.x - &r.y;
253 let mut f = c;
254 f.negate_in_place()?;
255 r.x = x3;
256 r.y = y3;
257 match P::TWIST_TYPE {
258 TwistType::M => Ok((g, f)),
259 TwistType::D => Ok((f, g)),
260 }
261 }
262}