arnaucube
arnaucube/ark-curves-cherry-pickedPublic Self-hosted repository
ark-curves-cherry-picked/bls12_381/src/curves/g1.rs
bls12_381/src/curves/g1.rsRaw
  1use crate::*;
  2use ark_ec::{
  3    bls12,
  4    bls12::Bls12Config,
  5    models::CurveConfig,
  6    short_weierstrass::{Affine, SWCurveConfig},
  7    AffineRepr, Group,
  8};
  9use ark_ff::{Field, MontFp, PrimeField, Zero};
 10use ark_serialize::{Compress, SerializationError};
 11use ark_std::{ops::Neg, One};
 12
 13use crate::util::{
 14    read_g1_compressed, read_g1_uncompressed, serialize_fq, EncodingFlags, G1_SERIALIZED_SIZE,
 15};
 16
 17pub type G1Affine = bls12::G1Affine<crate::Config>;
 18pub type G1Projective = bls12::G1Projective<crate::Config>;
 19
 20#[derive(Clone, Default, PartialEq, Eq)]
 21pub struct Config;
 22
 23impl CurveConfig for Config {
 24    type BaseField = Fq;
 25    type ScalarField = Fr;
 26
 27    /// COFACTOR = (x - 1)^2 / 3  = 76329603384216526031706109802092473003
 28    const COFACTOR: &'static [u64] = &[0x8c00aaab0000aaab, 0x396c8c005555e156];
 29
 30    /// COFACTOR_INV = COFACTOR^{-1} mod r
 31    /// = 52435875175126190458656871551744051925719901746859129887267498875565241663483
 32    const COFACTOR_INV: Fr =
 33        MontFp!("52435875175126190458656871551744051925719901746859129887267498875565241663483");
 34}
 35
 36impl SWCurveConfig for Config {
 37    /// COEFF_A = 0
 38    const COEFF_A: Fq = Fq::ZERO;
 39
 40    /// COEFF_B = 4
 41    const COEFF_B: Fq = MontFp!("4");
 42
 43    /// AFFINE_GENERATOR_COEFFS = (G1_GENERATOR_X, G1_GENERATOR_Y)
 44    const GENERATOR: G1Affine = G1Affine::new_unchecked(G1_GENERATOR_X, G1_GENERATOR_Y);
 45
 46    #[inline(always)]
 47    fn mul_by_a(_: Self::BaseField) -> Self::BaseField {
 48        Self::BaseField::zero()
 49    }
 50
 51    #[inline]
 52    fn is_in_correct_subgroup_assuming_on_curve(p: &G1Affine) -> bool {
 53        // Algorithm from Section 6 of https://eprint.iacr.org/2021/1130.
 54        //
 55        // Check that endomorphism_p(P) == -[X^2]P
 56
 57        // An early-out optimization described in Section 6.
 58        // If uP == P but P != point of infinity, then the point is not in the right
 59        // subgroup.
 60        let x_times_p = p.mul_bigint(crate::Config::X);
 61        if x_times_p.eq(p) && !p.infinity {
 62            return false;
 63        }
 64
 65        let minus_x_squared_times_p = x_times_p.mul_bigint(crate::Config::X).neg();
 66        let endomorphism_p = endomorphism(p);
 67        minus_x_squared_times_p.eq(&endomorphism_p)
 68    }
 69
 70    #[inline]
 71    fn clear_cofactor(p: &G1Affine) -> G1Affine {
 72        // Using the effective cofactor, as explained in
 73        // Section 5 of https://eprint.iacr.org/2019/403.pdf.
 74        //
 75        // It is enough to multiply by (1 - x), instead of (x - 1)^2 / 3
 76        let h_eff = one_minus_x().into_bigint();
 77        Config::mul_affine(&p, h_eff.as_ref()).into()
 78    }
 79
 80    fn deserialize_with_mode<R: ark_serialize::Read>(
 81        mut reader: R,
 82        compress: ark_serialize::Compress,
 83        validate: ark_serialize::Validate,
 84    ) -> Result<Affine<Self>, ark_serialize::SerializationError> {
 85        let p = if compress == ark_serialize::Compress::Yes {
 86            read_g1_compressed(&mut reader)?
 87        } else {
 88            read_g1_uncompressed(&mut reader)?
 89        };
 90
 91        if validate == ark_serialize::Validate::Yes && !p.is_in_correct_subgroup_assuming_on_curve()
 92        {
 93            return Err(SerializationError::InvalidData);
 94        }
 95        Ok(p)
 96    }
 97
 98    fn serialize_with_mode<W: ark_serialize::Write>(
 99        item: &Affine<Self>,
100        mut writer: W,
101        compress: ark_serialize::Compress,
102    ) -> Result<(), SerializationError> {
103        let encoding = EncodingFlags {
104            is_compressed: compress == ark_serialize::Compress::Yes,
105            is_infinity: item.is_zero(),
106            is_lexographically_largest: item.y > -item.y,
107        };
108        let mut p = *item;
109        if encoding.is_infinity {
110            p = G1Affine::zero();
111        }
112        // need to access the field struct `x` directly, otherwise we get None from xy()
113        // method
114        let x_bytes = serialize_fq(p.x);
115        if encoding.is_compressed {
116            let mut bytes: [u8; G1_SERIALIZED_SIZE] = x_bytes;
117
118            encoding.encode_flags(&mut bytes);
119            writer.write_all(&bytes)?;
120        } else {
121            let mut bytes = [0u8; 2 * G1_SERIALIZED_SIZE];
122            bytes[0..G1_SERIALIZED_SIZE].copy_from_slice(&x_bytes[..]);
123            bytes[G1_SERIALIZED_SIZE..].copy_from_slice(&serialize_fq(p.y)[..]);
124
125            encoding.encode_flags(&mut bytes);
126            writer.write_all(&bytes)?;
127        };
128
129        Ok(())
130    }
131
132    fn serialized_size(compress: Compress) -> usize {
133        if compress == Compress::Yes {
134            G1_SERIALIZED_SIZE
135        } else {
136            G1_SERIALIZED_SIZE * 2
137        }
138    }
139}
140
141fn one_minus_x() -> Fr {
142    const X: Fr = Fr::from_sign_and_limbs(!crate::Config::X_IS_NEGATIVE, crate::Config::X);
143    Fr::one() - X
144}
145
146/// G1_GENERATOR_X =
147/// 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507
148pub const G1_GENERATOR_X: Fq = MontFp!("3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507");
149
150/// G1_GENERATOR_Y =
151/// 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569
152pub const G1_GENERATOR_Y: Fq = MontFp!("1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569");
153
154/// BETA is a non-trivial cubic root of unity in Fq.
155pub const BETA: Fq = MontFp!("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350");
156
157pub fn endomorphism(p: &Affine<Config>) -> Affine<Config> {
158    // Endomorphism of the points on the curve.
159    // endomorphism_p(x,y) = (BETA * x, y)
160    // where BETA is a non-trivial cubic root of unity in Fq.
161    let mut res = (*p).clone();
162    res.x *= BETA;
163    res
164}
165
166#[cfg(test)]
167mod test {
168
169    use super::*;
170    use ark_std::{rand::Rng, UniformRand};
171
172    fn sample_unchecked() -> Affine<g1::Config> {
173        let mut rng = ark_std::test_rng();
174        loop {
175            let x = Fq::rand(&mut rng);
176            let greatest = rng.gen();
177
178            if let Some(p) = Affine::get_point_from_x_unchecked(x, greatest) {
179                return p;
180            }
181        }
182    }
183
184    #[test]
185    fn test_cofactor_clearing() {
186        const SAMPLES: usize = 100;
187        for _ in 0..SAMPLES {
188            let p: Affine<g1::Config> = sample_unchecked();
189            let p = p.clear_cofactor();
190            assert!(p.is_on_curve());
191            assert!(p.is_in_correct_subgroup_assuming_on_curve());
192        }
193    }
194}