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