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::bls12::{Bls12Parameters, G1Prepared, TwistType},
  3    fields::Field,
  4    BitIterator, One, ProjectiveCurve,
  5};
  6use r1cs_core::{ConstraintSystem, SynthesisError};
  7
  8use crate::{
  9    fields::{fp::FpGadget, fp2::Fp2Gadget, FieldGadget},
 10    groups::curves::short_weierstrass::AffineGadget,
 11    prelude::*,
 12};
 13
 14use std::fmt::Debug;
 15
 16pub mod bls12_377;
 17
 18pub type G1Gadget<P> = AffineGadget<
 19    <P as Bls12Parameters>::G1Parameters,
 20    <P as Bls12Parameters>::Fp,
 21    FpGadget<<P as Bls12Parameters>::Fp>,
 22>;
 23pub type G2Gadget<P> =
 24    AffineGadget<<P as Bls12Parameters>::G2Parameters, <P as Bls12Parameters>::Fp, Fp2G<P>>;
 25
 26#[derive(Derivative)]
 27#[derivative(
 28    Clone(bound = "G1Gadget<P>: Clone"),
 29    Debug(bound = "G1Gadget<P>: Debug")
 30)]
 31pub struct G1PreparedGadget<P: Bls12Parameters>(pub G1Gadget<P>);
 32
 33impl<P: Bls12Parameters> G1PreparedGadget<P> {
 34    pub fn get_value(&self) -> Option<G1Prepared<P>> {
 35        Some(G1Prepared::from_affine(
 36            self.0.get_value().unwrap().into_affine(),
 37        ))
 38    }
 39
 40    pub fn from_affine<CS: ConstraintSystem<P::Fp>>(
 41        _cs: CS,
 42        q: &G1Gadget<P>,
 43    ) -> Result<Self, SynthesisError> {
 44        Ok(G1PreparedGadget(q.clone()))
 45    }
 46}
 47
 48impl<P: Bls12Parameters> ToBytesGadget<P::Fp> for G1PreparedGadget<P> {
 49    #[inline]
 50    fn to_bytes<CS: ConstraintSystem<P::Fp>>(
 51        &self,
 52        mut cs: CS,
 53    ) -> Result<Vec<UInt8>, SynthesisError> {
 54        self.0.to_bytes(&mut cs.ns(|| "g_alpha to bytes"))
 55    }
 56
 57    fn to_bytes_strict<CS: ConstraintSystem<P::Fp>>(
 58        &self,
 59        cs: CS,
 60    ) -> Result<Vec<UInt8>, SynthesisError> {
 61        self.to_bytes(cs)
 62    }
 63}
 64
 65type Fp2G<P> = Fp2Gadget<<P as Bls12Parameters>::Fp2Params, <P as Bls12Parameters>::Fp>;
 66type LCoeff<P> = (Fp2G<P>, Fp2G<P>);
 67#[derive(Derivative)]
 68#[derivative(
 69    Clone(bound = "Fp2Gadget<P::Fp2Params, P::Fp>: Clone"),
 70    Debug(bound = "Fp2Gadget<P::Fp2Params, P::Fp>: Debug")
 71)]
 72pub struct G2PreparedGadget<P: Bls12Parameters> {
 73    pub ell_coeffs: Vec<LCoeff<P>>,
 74}
 75
 76impl<P: Bls12Parameters> ToBytesGadget<P::Fp> for G2PreparedGadget<P> {
 77    #[inline]
 78    fn to_bytes<CS: ConstraintSystem<P::Fp>>(
 79        &self,
 80        mut cs: CS,
 81    ) -> Result<Vec<UInt8>, SynthesisError> {
 82        let mut bytes = Vec::new();
 83        for (i, coeffs) in self.ell_coeffs.iter().enumerate() {
 84            let mut cs = cs.ns(|| format!("Iteration {}", i));
 85            bytes.extend_from_slice(&coeffs.0.to_bytes(&mut cs.ns(|| "c0"))?);
 86            bytes.extend_from_slice(&coeffs.1.to_bytes(&mut cs.ns(|| "c1"))?);
 87        }
 88        Ok(bytes)
 89    }
 90
 91    fn to_bytes_strict<CS: ConstraintSystem<P::Fp>>(
 92        &self,
 93        cs: CS,
 94    ) -> Result<Vec<UInt8>, SynthesisError> {
 95        self.to_bytes(cs)
 96    }
 97}
 98
 99impl<P: Bls12Parameters> G2PreparedGadget<P> {
100    pub fn from_affine<CS: ConstraintSystem<P::Fp>>(
101        mut cs: CS,
102        q: &G2Gadget<P>,
103    ) -> Result<Self, SynthesisError> {
104        let two_inv = P::Fp::one().double().inverse().unwrap();
105        let zero = G2Gadget::<P>::zero(cs.ns(|| "zero"))?;
106        q.enforce_not_equal(cs.ns(|| "enforce not zero"), &zero)?;
107        let mut ell_coeffs = vec![];
108        let mut r = q.clone();
109
110        for (j, i) in BitIterator::new(P::X).skip(1).enumerate() {
111            let mut cs = cs.ns(|| format!("Iteration {}", j));
112            ell_coeffs.push(Self::double(cs.ns(|| "double"), &mut r, &two_inv)?);
113
114            if i {
115                ell_coeffs.push(Self::add(cs.ns(|| "add"), &mut r, &q)?);
116            }
117        }
118
119        Ok(Self { ell_coeffs })
120    }
121
122    fn double<CS: ConstraintSystem<P::Fp>>(
123        mut cs: CS,
124        r: &mut G2Gadget<P>,
125        two_inv: &P::Fp,
126    ) -> Result<LCoeff<P>, SynthesisError> {
127        let a = r.y.inverse(cs.ns(|| "Inverse"))?;
128        let mut b = r.x.square(cs.ns(|| "square x"))?;
129        let b_tmp = b.clone();
130        b.mul_by_fp_constant_in_place(cs.ns(|| "mul by two_inv"), two_inv)?;
131        b.add_in_place(cs.ns(|| "compute b"), &b_tmp)?;
132
133        let c = a.mul(cs.ns(|| "compute c"), &b)?;
134        let d = r.x.double(cs.ns(|| "compute d"))?;
135        let x3 = c.square(cs.ns(|| "c^2"))?.sub(cs.ns(|| "sub d"), &d)?;
136        let e = c
137            .mul(cs.ns(|| "c*r.x"), &r.x)?
138            .sub(cs.ns(|| "sub r.y"), &r.y)?;
139        let c_x3 = c.mul(cs.ns(|| "c*x_3"), &x3)?;
140        let y3 = e.sub(cs.ns(|| "e = c * x3"), &c_x3)?;
141        let mut f = c;
142        f.negate_in_place(cs.ns(|| "c = -c"))?;
143        r.x = x3;
144        r.y = y3;
145        match P::TWIST_TYPE {
146            TwistType::M => Ok((e, f)),
147            TwistType::D => Ok((f, e)),
148        }
149    }
150
151    fn add<CS: ConstraintSystem<P::Fp>>(
152        mut cs: CS,
153        r: &mut G2Gadget<P>,
154        q: &G2Gadget<P>,
155    ) -> Result<LCoeff<P>, SynthesisError> {
156        let a =
157            q.x.sub(cs.ns(|| "q.x - r.x"), &r.x)?
158                .inverse(cs.ns(|| "calc a"))?;
159        let b = q.y.sub(cs.ns(|| "q.y - r.y"), &r.y)?;
160        let c = a.mul(cs.ns(|| "compute c"), &b)?;
161        let d = r.x.add(cs.ns(|| "r.x + q.x"), &q.x)?;
162        let x3 = c.square(cs.ns(|| "c^2"))?.sub(cs.ns(|| "sub d"), &d)?;
163
164        let e =
165            r.x.sub(cs.ns(|| "r.x - x3"), &x3)?
166                .mul(cs.ns(|| "c * (r.x - x3)"), &c)?;
167        let y3 = e.sub(cs.ns(|| "calc y3"), &r.y)?;
168        let g = c
169            .mul(cs.ns(|| "c*r.x"), &r.x)?
170            .sub(cs.ns(|| "calc g"), &r.y)?;
171        let mut f = c;
172        f.negate_in_place(cs.ns(|| "c = -c"))?;
173        r.x = x3;
174        r.y = y3;
175        match P::TWIST_TYPE {
176            TwistType::M => Ok((g, f)),
177            TwistType::D => Ok((f, g)),
178        }
179    }
180}