arnaucube
arnaucube/ark-curves-cherry-pickedPublic Self-hosted repository
ark-curves-cherry-picked/bls12_381/src/curves/g2.rs
bls12_381/src/curves/g2.rsRaw
  1use ark_std::ops::Neg;
  2
  3use ark_ec::{
  4    bls12,
  5    bls12::Bls12Config,
  6    hashing::curve_maps::wb::{IsogenyMap, WBConfig},
  7    models::CurveConfig,
  8    short_weierstrass::{Affine, Projective, SWCurveConfig},
  9    AffineRepr, CurveGroup, PrimeGroup,
 10};
 11use ark_ff::{AdditiveGroup, Field, MontFp, Zero};
 12use ark_serialize::{Compress, SerializationError};
 13
 14use super::{
 15    g2_swu_iso,
 16    util::{serialize_fq, EncodingFlags, G2_SERIALIZED_SIZE},
 17};
 18use crate::{
 19    util::{read_g2_compressed, read_g2_uncompressed},
 20    *,
 21};
 22
 23pub type G2Affine = bls12::G2Affine<crate::Config>;
 24pub type G2Projective = bls12::G2Projective<crate::Config>;
 25
 26#[derive(Clone, Default, PartialEq, Eq)]
 27pub struct Config;
 28
 29impl CurveConfig for Config {
 30    type BaseField = Fq2;
 31    type ScalarField = Fr;
 32
 33    /// COFACTOR = (x^8 - 4 x^7 + 5 x^6) - (4 x^4 + 6 x^3 - 4 x^2 - 4 x + 13) //
 34    /// 9
 35    /// = 305502333931268344200999753193121504214466019254188142667664032982267604182971884026507427359259977847832272839041616661285803823378372096355777062779109
 36    #[rustfmt::skip]
 37    const COFACTOR: &'static [u64] = &[
 38        0xcf1c38e31c7238e5,
 39        0x1616ec6e786f0c70,
 40        0x21537e293a6691ae,
 41        0xa628f1cb4d9e82ef,
 42        0xa68a205b2e5a7ddf,
 43        0xcd91de4547085aba,
 44        0x91d50792876a202,
 45        0x5d543a95414e7f1,
 46    ];
 47
 48    /// COFACTOR_INV = COFACTOR^{-1} mod r
 49    /// 26652489039290660355457965112010883481355318854675681319708643586776743290055
 50    const COFACTOR_INV: Fr =
 51        MontFp!("26652489039290660355457965112010883481355318854675681319708643586776743290055");
 52}
 53
 54impl SWCurveConfig for Config {
 55    /// COEFF_A = [0, 0]
 56    const COEFF_A: Fq2 = Fq2::new(g1::Config::COEFF_A, g1::Config::COEFF_A);
 57
 58    /// COEFF_B = [4, 4]
 59    const COEFF_B: Fq2 = Fq2::new(g1::Config::COEFF_B, g1::Config::COEFF_B);
 60
 61    /// AFFINE_GENERATOR_COEFFS = (G2_GENERATOR_X, G2_GENERATOR_Y)
 62    const GENERATOR: G2Affine = G2Affine::new_unchecked(G2_GENERATOR_X, G2_GENERATOR_Y);
 63
 64    #[inline(always)]
 65    fn mul_by_a(_: Self::BaseField) -> Self::BaseField {
 66        Self::BaseField::zero()
 67    }
 68
 69    fn is_in_correct_subgroup_assuming_on_curve(point: &G2Affine) -> bool {
 70        // Algorithm from Section 4 of https://eprint.iacr.org/2021/1130.
 71        //
 72        // Checks that [p]P = [X]P
 73
 74        let mut x_times_point = point.mul_bigint(crate::Config::X);
 75        if crate::Config::X_IS_NEGATIVE {
 76            x_times_point = -x_times_point;
 77        }
 78
 79        let p_times_point = p_power_endomorphism(point);
 80
 81        x_times_point.eq(&p_times_point)
 82    }
 83
 84    #[inline]
 85    fn clear_cofactor(p: &G2Affine) -> G2Affine {
 86        // Based on Section 4.1 of https://eprint.iacr.org/2017/419.pdf
 87        // [h(ψ)]P = [x^2 − x − 1]P + [x − 1]ψ(P) + (ψ^2)(2P)
 88
 89        // x = -15132376222941642752
 90        // When multiplying, use -c1 instead, and then negate the result. That's much
 91        // more efficient, since the scalar -c1 has less limbs and a much lower Hamming
 92        // weight.
 93        let x: &'static [u64] = crate::Config::X;
 94        let p_projective = p.into_group();
 95
 96        // [x]P
 97        let x_p = Config::mul_affine(p, &x).neg();
 98        // ψ(P)
 99        let psi_p = p_power_endomorphism(&p);
100        // (ψ^2)(2P)
101        let mut psi2_p2 = double_p_power_endomorphism(&p_projective.double());
102
103        // tmp = [x]P + ψ(P)
104        let mut tmp = x_p.clone();
105        tmp += &psi_p;
106
107        // tmp2 = [x^2]P + [x]ψ(P)
108        let mut tmp2: Projective<Config> = tmp;
109        tmp2 = tmp2.mul_bigint(x).neg();
110
111        // add up all the terms
112        psi2_p2 += tmp2;
113        psi2_p2 -= x_p;
114        psi2_p2 += &-psi_p;
115        (psi2_p2 - p_projective).into_affine()
116    }
117
118    fn deserialize_with_mode<R: ark_serialize::Read>(
119        mut reader: R,
120        compress: ark_serialize::Compress,
121        validate: ark_serialize::Validate,
122    ) -> Result<Affine<Self>, ark_serialize::SerializationError> {
123        let p = if compress == ark_serialize::Compress::Yes {
124            read_g2_compressed(&mut reader)?
125        } else {
126            read_g2_uncompressed(&mut reader)?
127        };
128
129        if validate == ark_serialize::Validate::Yes && !p.is_in_correct_subgroup_assuming_on_curve()
130        {
131            return Err(SerializationError::InvalidData);
132        }
133        Ok(p)
134    }
135
136    fn serialize_with_mode<W: ark_serialize::Write>(
137        item: &Affine<Self>,
138        mut writer: W,
139        compress: ark_serialize::Compress,
140    ) -> Result<(), SerializationError> {
141        let encoding = EncodingFlags {
142            is_compressed: compress == ark_serialize::Compress::Yes,
143            is_infinity: item.is_zero(),
144            is_lexographically_largest: item.y > -item.y,
145        };
146        let mut p = *item;
147        if encoding.is_infinity {
148            p = G2Affine::zero();
149        }
150
151        let mut x_bytes = [0u8; G2_SERIALIZED_SIZE];
152        let c1_bytes = serialize_fq(p.x.c1);
153        let c0_bytes = serialize_fq(p.x.c0);
154        x_bytes[0..48].copy_from_slice(&c1_bytes[..]);
155        x_bytes[48..96].copy_from_slice(&c0_bytes[..]);
156        if encoding.is_compressed {
157            let mut bytes: [u8; G2_SERIALIZED_SIZE] = x_bytes;
158
159            encoding.encode_flags(&mut bytes);
160            writer.write_all(&bytes)?;
161        } else {
162            let mut bytes = [0u8; 2 * G2_SERIALIZED_SIZE];
163
164            let mut y_bytes = [0u8; G2_SERIALIZED_SIZE];
165            let c1_bytes = serialize_fq(p.y.c1);
166            let c0_bytes = serialize_fq(p.y.c0);
167            y_bytes[0..48].copy_from_slice(&c1_bytes[..]);
168            y_bytes[48..96].copy_from_slice(&c0_bytes[..]);
169            bytes[0..G2_SERIALIZED_SIZE].copy_from_slice(&x_bytes);
170            bytes[G2_SERIALIZED_SIZE..].copy_from_slice(&y_bytes);
171
172            encoding.encode_flags(&mut bytes);
173            writer.write_all(&bytes)?;
174        };
175
176        Ok(())
177    }
178
179    fn serialized_size(compress: ark_serialize::Compress) -> usize {
180        if compress == Compress::Yes {
181            G2_SERIALIZED_SIZE
182        } else {
183            2 * G2_SERIALIZED_SIZE
184        }
185    }
186}
187
188pub const G2_GENERATOR_X: Fq2 = Fq2::new(G2_GENERATOR_X_C0, G2_GENERATOR_X_C1);
189pub const G2_GENERATOR_Y: Fq2 = Fq2::new(G2_GENERATOR_Y_C0, G2_GENERATOR_Y_C1);
190
191/// G2_GENERATOR_X_C0 =
192/// 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160
193pub const G2_GENERATOR_X_C0: Fq = MontFp!("352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160");
194
195/// G2_GENERATOR_X_C1 =
196/// 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758
197pub const G2_GENERATOR_X_C1: Fq = MontFp!("3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758");
198
199/// G2_GENERATOR_Y_C0 =
200/// 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905
201pub const G2_GENERATOR_Y_C0: Fq = MontFp!("1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905");
202
203/// G2_GENERATOR_Y_C1 =
204/// 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582
205pub const G2_GENERATOR_Y_C1: Fq = MontFp!("927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582");
206
207// PSI_X = 1/(u+1)^((p-1)/3)
208const P_POWER_ENDOMORPHISM_COEFF_0 : Fq2 = Fq2::new(
209    Fq::ZERO,
210    MontFp!(
211                "4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"
212    )
213);
214
215// PSI_Y = 1/(u+1)^((p-1)/2)
216const P_POWER_ENDOMORPHISM_COEFF_1: Fq2 = Fq2::new(
217    MontFp!(
218                "2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530"),
219    MontFp!(
220       "1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257")
221);
222
223// PSI_2_X = (u+1)^((1-p^2)/3)
224const DOUBLE_P_POWER_ENDOMORPHISM_COEFF_0: Fq2 = Fq2::new(
225    MontFp!("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"),
226    Fq::ZERO
227);
228
229/// psi(P) is the untwist-Frobenius-twist endomorhism on E'(Fq2)
230fn p_power_endomorphism(p: &Affine<Config>) -> Affine<Config> {
231    // The p-power endomorphism for G2 is defined as follows:
232    // 1. Note that G2 is defined on curve E': y^2 = x^3 + 4(u+1).
233    //    To map a point (x, y) in E' to (s, t) in E,
234    //    set s = x / ((u+1) ^ (1/3)), t = y / ((u+1) ^ (1/2)),
235    //    because E: y^2 = x^3 + 4.
236    // 2. Apply the Frobenius endomorphism (s, t) => (s', t'),
237    //    another point on curve E, where s' = s^p, t' = t^p.
238    // 3. Map the point from E back to E'; that is,
239    //    set x' = s' * ((u+1) ^ (1/3)), y' = t' * ((u+1) ^ (1/2)).
240    //
241    // To sum up, it maps
242    // (x,y) -> (x^p / ((u+1)^((p-1)/3)), y^p / ((u+1)^((p-1)/2)))
243    // as implemented in the code as follows.
244
245    let mut res = *p;
246    res.x.frobenius_map_in_place(1);
247    res.y.frobenius_map_in_place(1);
248
249    let tmp_x = res.x.clone();
250    res.x.c0 = -P_POWER_ENDOMORPHISM_COEFF_0.c1 * &tmp_x.c1;
251    res.x.c1 = P_POWER_ENDOMORPHISM_COEFF_0.c1 * &tmp_x.c0;
252    res.y *= P_POWER_ENDOMORPHISM_COEFF_1;
253
254    res
255}
256
257/// For a p-power endomorphism psi(P), compute psi(psi(P))
258fn double_p_power_endomorphism(p: &Projective<Config>) -> Projective<Config> {
259    let mut res = *p;
260
261    res.x *= DOUBLE_P_POWER_ENDOMORPHISM_COEFF_0;
262    res.y = res.y.neg();
263
264    res
265}
266
267// Parametres from the [IETF draft v16, section E.3](https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-3-isogeny-map-for-bls12-381).
268impl WBConfig for Config {
269    type IsogenousCurve = g2_swu_iso::SwuIsoConfig;
270
271    const ISOGENY_MAP: IsogenyMap<'static, Self::IsogenousCurve, Self> =
272        g2_swu_iso::ISOGENY_MAP_TO_G2;
273}
274
275#[cfg(test)]
276mod test {
277
278    use super::*;
279    use ark_std::{rand::Rng, UniformRand};
280
281    fn sample_unchecked() -> Affine<g2::Config> {
282        let mut rng = ark_std::test_rng();
283        loop {
284            let x1 = Fq::rand(&mut rng);
285            let x2 = Fq::rand(&mut rng);
286            let greatest = rng.gen();
287            let x = Fq2::new(x1, x2);
288
289            if let Some(p) = Affine::get_point_from_x_unchecked(x, greatest) {
290                return p;
291            }
292        }
293    }
294
295    #[test]
296    fn test_psi_2() {
297        let p = sample_unchecked();
298        let psi_p = p_power_endomorphism(&p);
299        let psi2_p_composed = p_power_endomorphism(&psi_p);
300        let psi2_p_optimised = double_p_power_endomorphism(&p.into());
301
302        assert_eq!(psi2_p_composed, psi2_p_optimised);
303    }
304
305    #[test]
306    fn test_cofactor_clearing() {
307        // multiplying by h_eff and clearing the cofactor by the efficient
308        // endomorphism-based method should yield the same result.
309        let h_eff: &'static [u64] = &[
310            0xe8020005aaa95551,
311            0x59894c0adebbf6b4,
312            0xe954cbc06689f6a3,
313            0x2ec0ec69d7477c1a,
314            0x6d82bf015d1212b0,
315            0x329c2f178731db95,
316            0x9986ff031508ffe1,
317            0x88e2a8e9145ad768,
318            0x584c6a0ea91b3528,
319            0xbc69f08f2ee75b3,
320        ];
321
322        const SAMPLES: usize = 10;
323        for _ in 0..SAMPLES {
324            let p: Affine<g2::Config> = sample_unchecked();
325            let optimised = p.clear_cofactor();
326            let naive = g2::Config::mul_affine(&p, h_eff);
327            assert_eq!(optimised.into_group(), naive);
328            assert!(optimised.is_on_curve());
329            assert!(optimised.is_in_correct_subgroup_assuming_on_curve());
330        }
331    }
332}