zksync_pairing/bn256/
ec.rs

1macro_rules! curve_impl {
2    (
3        $name:expr,
4        $projective:ident,
5        $affine:ident,
6        $prepared:ident,
7        $basefield:ident,
8        $scalarfield:ident,
9        $uncompressed:ident,
10        $compressed:ident,
11        $pairing:ident
12    ) => {
13        #[derive(Copy, Clone, PartialEq, Eq, Debug, ::serde::Serialize, ::serde::Deserialize)]
14        pub struct $affine {
15            pub(crate) x: $basefield,
16            pub(crate) y: $basefield,
17            pub(crate) infinity: bool,
18        }
19
20        impl ::std::fmt::Display for $affine {
21            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
22                if self.infinity {
23                    write!(f, "{}(Infinity)", $name)
24                } else {
25                    write!(f, "{}(x={}, y={})", $name, self.x, self.y)
26                }
27            }
28        }
29
30        #[derive(Copy, Clone, Debug, Eq)]
31        pub struct $projective {
32            pub(crate) x: $basefield,
33            pub(crate) y: $basefield,
34            pub(crate) z: $basefield,
35        }
36
37        impl ::std::fmt::Display for $projective {
38            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
39                write!(f, "{}", self.into_affine())
40            }
41        }
42
43        impl PartialEq for $projective {
44            fn eq(&self, other: &$projective) -> bool {
45                if self.is_zero() {
46                    return other.is_zero();
47                }
48
49                if other.is_zero() {
50                    return false;
51                }
52
53                // The points (X, Y, Z) and (X', Y', Z')
54                // are equal when (X * Z^2) = (X' * Z'^2)
55                // and (Y * Z^3) = (Y' * Z'^3).
56
57                let mut z1 = self.z;
58                z1.square();
59                let mut z2 = other.z;
60                z2.square();
61
62                let mut tmp1 = self.x;
63                tmp1.mul_assign(&z2);
64
65                let mut tmp2 = other.x;
66                tmp2.mul_assign(&z1);
67
68                if tmp1 != tmp2 {
69                    return false;
70                }
71
72                z1.mul_assign(&self.z);
73                z2.mul_assign(&other.z);
74                z2.mul_assign(&self.y);
75                z1.mul_assign(&other.y);
76
77                if z1 != z2 {
78                    return false;
79                }
80
81                true
82            }
83        }
84
85        impl $affine {
86            fn mul_bits<S: AsRef<[u64]>>(&self, bits: BitIterator<S>) -> $projective {
87                let mut res = $projective::zero();
88                for i in bits {
89                    res.double();
90                    if i {
91                        res.add_assign_mixed(self)
92                    }
93                }
94                res
95            }
96
97            /// Attempts to construct an affine point given an x-coordinate. The
98            /// point is not guaranteed to be in the prime order subgroup.
99            ///
100            /// If and only if `greatest` is set will the lexicographically
101            /// largest y-coordinate be selected.
102            pub fn get_point_from_x(x: $basefield, greatest: bool) -> Option<$affine> {
103                // Compute x^3 + b
104                let mut x3b = x;
105                x3b.square();
106                x3b.mul_assign(&x);
107                x3b.add_assign(&$affine::get_coeff_b());
108
109                x3b.sqrt().map(|y| {
110                    let mut negy = y;
111                    negy.negate();
112
113                    $affine {
114                        x: x,
115                        y: if (y < negy) ^ greatest { y } else { negy },
116                        infinity: false,
117                    }
118                })
119            }
120
121            pub fn is_on_curve(&self) -> bool {
122                if self.is_zero() {
123                    true
124                } else {
125                    // Check that the point is on the curve
126                    let mut y2 = self.y;
127                    y2.square();
128
129                    let mut x3b = self.x;
130                    x3b.square();
131                    x3b.mul_assign(&self.x);
132                    x3b.add_assign(&Self::get_coeff_b());
133
134                    y2 == x3b
135                }
136            }
137        }
138
139        impl CurveAffine for $affine {
140            type Engine = Bn256;
141            type Scalar = $scalarfield;
142            type Base = $basefield;
143            type Prepared = $prepared;
144            type Projective = $projective;
145            type Uncompressed = $uncompressed;
146            type Compressed = $compressed;
147            type Pair = $pairing;
148            type PairingResult = Fq12;
149
150            fn zero() -> Self {
151                $affine {
152                    x: $basefield::zero(),
153                    y: $basefield::zero(),
154                    infinity: true,
155                }
156            }
157
158            fn one() -> Self {
159                Self::get_generator()
160            }
161
162            fn is_zero(&self) -> bool {
163                self.infinity
164            }
165
166            fn mul<S: Into<<Self::Scalar as PrimeField>::Repr>>(&self, by: S) -> $projective {
167                let bits = BitIterator::new(by.into());
168                self.mul_bits(bits)
169            }
170
171            fn negate(&mut self) {
172                if !self.is_zero() {
173                    self.y.negate();
174                }
175            }
176
177            fn prepare(&self) -> Self::Prepared {
178                $prepared::from_affine(*self)
179            }
180
181            fn pairing_with(&self, other: &Self::Pair) -> Self::PairingResult {
182                self.perform_pairing(other)
183            }
184
185            fn into_projective(&self) -> $projective {
186                (*self).into()
187            }
188
189            #[inline(always)]
190            fn as_xy(&self) -> (&Self::Base, &Self::Base) {
191                (&self.x, &self.y)
192            }
193
194            #[inline(always)]
195            fn into_xy_unchecked(self) -> (Self::Base, Self::Base) {
196                (self.x, self.y)
197            }
198
199            #[inline(always)]
200            fn from_xy_unchecked(x: Self::Base, y: Self::Base) -> Self {
201                let infinity = x.is_zero() && y.is_zero();
202                Self { x: x, y: y, infinity }
203            }
204
205            fn from_xy_checked(x: Self::Base, y: Self::Base) -> Result<Self, GroupDecodingError> {
206                let infinity = x.is_zero() && y.is_zero();
207                let affine = Self { x: x, y: y, infinity };
208
209                if !affine.is_on_curve() {
210                    Err(GroupDecodingError::NotOnCurve)
211                } else {
212                    Ok(affine)
213                }
214            }
215
216            fn a_coeff() -> Self::Base {
217                Self::Base::zero()
218            }
219
220            fn b_coeff() -> Self::Base {
221                $affine::get_coeff_b()
222            }
223        }
224
225        impl CurveProjective for $projective {
226            type Engine = Bn256;
227            type Scalar = $scalarfield;
228            type Base = $basefield;
229            type Affine = $affine;
230
231            // The point at infinity is always represented by
232            // Z = 0.
233            fn zero() -> Self {
234                $projective {
235                    x: $basefield::zero(),
236                    y: $basefield::one(),
237                    z: $basefield::zero(),
238                }
239            }
240
241            fn one() -> Self {
242                $affine::one().into()
243            }
244
245            // The point at infinity is always represented by
246            // Z = 0.
247            fn is_zero(&self) -> bool {
248                self.z.is_zero()
249            }
250
251            fn is_normalized(&self) -> bool {
252                self.is_zero() || self.z == $basefield::one()
253            }
254
255            fn batch_normalization(v: &mut [Self]) {
256                // Montgomery’s Trick and Fast Implementation of Masked AES
257                // Genelle, Prouff and Quisquater
258                // Section 3.2
259
260                // First pass: compute [a, ab, abc, ...]
261                let mut prod = Vec::with_capacity(v.len());
262                let mut tmp = $basefield::one();
263                for g in v
264                    .iter_mut()
265                    // Ignore normalized elements
266                    .filter(|g| !g.is_normalized())
267                {
268                    tmp.mul_assign(&g.z);
269                    prod.push(tmp);
270                }
271
272                // Invert `tmp`.
273                tmp = tmp.inverse().unwrap(); // Guaranteed to be nonzero.
274
275                // Second pass: iterate backwards to compute inverses
276                for (g, s) in v
277                    .iter_mut()
278                    // Backwards
279                    .rev()
280                    // Ignore normalized elements
281                    .filter(|g| !g.is_normalized())
282                    // Backwards, skip last element, fill in one for last term.
283                    .zip(prod.into_iter().rev().skip(1).chain(Some($basefield::one())))
284                {
285                    // tmp := tmp * g.z; g.z := tmp * s = 1/z
286                    let mut newtmp = tmp;
287                    newtmp.mul_assign(&g.z);
288                    g.z = tmp;
289                    g.z.mul_assign(&s);
290                    tmp = newtmp;
291                }
292
293                // Perform affine transformations
294                for g in v.iter_mut().filter(|g| !g.is_normalized()) {
295                    let mut z = g.z; // 1/z
296                    z.square(); // 1/z^2
297                    g.x.mul_assign(&z); // x/z^2
298                    z.mul_assign(&g.z); // 1/z^3
299                    g.y.mul_assign(&z); // y/z^3
300                    g.z = $basefield::one(); // z = 1
301                }
302            }
303
304            fn double(&mut self) {
305                if self.is_zero() {
306                    return;
307                }
308
309                // Other than the point at infinity, no points on E or E'
310                // can double to equal the point at infinity, as y=0 is
311                // never true for points on the curve.
312
313                // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
314
315                // A = X1^2
316                let mut a = self.x;
317                a.square();
318
319                // B = Y1^2
320                let mut b = self.y;
321                b.square();
322
323                // C = B^2
324                let mut c = b;
325                c.square();
326
327                // D = 2*((X1+B)2-A-C)
328                let mut d = self.x;
329                d.add_assign(&b);
330                d.square();
331                d.sub_assign(&a);
332                d.sub_assign(&c);
333                d.double();
334
335                // E = 3*A
336                let mut e = a;
337                e.double();
338                e.add_assign(&a);
339
340                // F = E^2
341                let mut f = e;
342                f.square();
343
344                // Z3 = 2*Y1*Z1
345                self.z.mul_assign(&self.y);
346                self.z.double();
347
348                // X3 = F-2*D
349                self.x = f;
350                self.x.sub_assign(&d);
351                self.x.sub_assign(&d);
352
353                // Y3 = E*(D-X3)-8*C
354                self.y = d;
355                self.y.sub_assign(&self.x);
356                self.y.mul_assign(&e);
357                c.double();
358                c.double();
359                c.double();
360                self.y.sub_assign(&c);
361            }
362
363            fn add_assign(&mut self, other: &Self) {
364                if self.is_zero() {
365                    *self = *other;
366                    return;
367                }
368
369                if other.is_zero() {
370                    return;
371                }
372
373                // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
374
375                // Z1Z1 = Z1^2
376                let mut z1z1 = self.z;
377                z1z1.square();
378
379                // Z2Z2 = Z2^2
380                let mut z2z2 = other.z;
381                z2z2.square();
382
383                // U1 = X1*Z2Z2
384                let mut u1 = self.x;
385                u1.mul_assign(&z2z2);
386
387                // U2 = X2*Z1Z1
388                let mut u2 = other.x;
389                u2.mul_assign(&z1z1);
390
391                // S1 = Y1*Z2*Z2Z2
392                let mut s1 = self.y;
393                s1.mul_assign(&other.z);
394                s1.mul_assign(&z2z2);
395
396                // S2 = Y2*Z1*Z1Z1
397                let mut s2 = other.y;
398                s2.mul_assign(&self.z);
399                s2.mul_assign(&z1z1);
400
401                if u1 == u2 && s1 == s2 {
402                    // The two points are equal, so we double.
403                    self.double();
404                } else {
405                    // If we're adding -a and a together, self.z becomes zero as H becomes zero.
406
407                    if u1 == u2 {
408                        // The two points are equal, so we double.
409                        (*self) = Self::zero();
410                        return;
411                    }
412
413                    // H = U2-U1
414                    let mut h = u2;
415                    h.sub_assign(&u1);
416
417                    // I = (2*H)^2
418                    let mut i = h;
419                    i.double();
420                    i.square();
421
422                    // J = H*I
423                    let mut j = h;
424                    j.mul_assign(&i);
425
426                    // r = 2*(S2-S1)
427                    let mut r = s2;
428                    r.sub_assign(&s1);
429                    r.double();
430
431                    // V = U1*I
432                    let mut v = u1;
433                    v.mul_assign(&i);
434
435                    // X3 = r^2 - J - 2*V
436                    self.x = r;
437                    self.x.square();
438                    self.x.sub_assign(&j);
439                    self.x.sub_assign(&v);
440                    self.x.sub_assign(&v);
441
442                    // Y3 = r*(V - X3) - 2*S1*J
443                    self.y = v;
444                    self.y.sub_assign(&self.x);
445                    self.y.mul_assign(&r);
446                    s1.mul_assign(&j); // S1 = S1 * J * 2
447                    s1.double();
448                    self.y.sub_assign(&s1);
449
450                    // Z3 = ((Z1+Z2)^2 - Z1Z1 - Z2Z2)*H
451                    self.z.add_assign(&other.z);
452                    self.z.square();
453                    self.z.sub_assign(&z1z1);
454                    self.z.sub_assign(&z2z2);
455                    self.z.mul_assign(&h);
456                }
457            }
458
459            fn add_assign_mixed(&mut self, other: &Self::Affine) {
460                if other.is_zero() {
461                    return;
462                }
463
464                if self.is_zero() {
465                    self.x = other.x;
466                    self.y = other.y;
467                    self.z = $basefield::one();
468                    return;
469                }
470
471                // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-madd-2007-bl
472
473                // Z1Z1 = Z1^2
474                let mut z1z1 = self.z;
475                z1z1.square();
476
477                // U2 = X2*Z1Z1
478                let mut u2 = other.x;
479                u2.mul_assign(&z1z1);
480
481                // S2 = Y2*Z1*Z1Z1
482                let mut s2 = other.y;
483                s2.mul_assign(&self.z);
484                s2.mul_assign(&z1z1);
485
486                if self.x == u2 && self.y == s2 {
487                    // The two points are equal, so we double.
488                    self.double();
489                } else {
490                    // If we're adding -a and a together, self.z becomes zero as H becomes zero.
491
492                    // H = U2-X1
493                    let mut h = u2;
494                    h.sub_assign(&self.x);
495
496                    // HH = H^2
497                    let mut hh = h;
498                    hh.square();
499
500                    // I = 4*HH
501                    let mut i = hh;
502                    i.double();
503                    i.double();
504
505                    // J = H*I
506                    let mut j = h;
507                    j.mul_assign(&i);
508
509                    // r = 2*(S2-Y1)
510                    let mut r = s2;
511                    r.sub_assign(&self.y);
512                    r.double();
513
514                    // V = X1*I
515                    let mut v = self.x;
516                    v.mul_assign(&i);
517
518                    // X3 = r^2 - J - 2*V
519                    self.x = r;
520                    self.x.square();
521                    self.x.sub_assign(&j);
522                    self.x.sub_assign(&v);
523                    self.x.sub_assign(&v);
524
525                    // Y3 = r*(V-X3)-2*Y1*J
526                    j.mul_assign(&self.y); // J = 2*Y1*J
527                    j.double();
528                    self.y = v;
529                    self.y.sub_assign(&self.x);
530                    self.y.mul_assign(&r);
531                    self.y.sub_assign(&j);
532
533                    // Z3 = (Z1+H)^2-Z1Z1-HH
534                    self.z.add_assign(&h);
535                    self.z.square();
536                    self.z.sub_assign(&z1z1);
537                    self.z.sub_assign(&hh);
538                }
539            }
540
541            fn negate(&mut self) {
542                if !self.is_zero() {
543                    self.y.negate()
544                }
545            }
546
547            fn mul_assign<S: Into<<Self::Scalar as PrimeField>::Repr>>(&mut self, other: S) {
548                let mut res = Self::zero();
549
550                let mut found_one = false;
551
552                for i in BitIterator::new(other.into()) {
553                    if found_one {
554                        res.double();
555                    } else {
556                        found_one = i;
557                    }
558
559                    if i {
560                        res.add_assign(self);
561                    }
562                }
563
564                *self = res;
565            }
566
567            fn into_affine(&self) -> $affine {
568                (*self).into()
569            }
570
571            fn recommended_wnaf_for_scalar(scalar: <Self::Scalar as PrimeField>::Repr) -> usize {
572                Self::empirical_recommended_wnaf_for_scalar(scalar)
573            }
574
575            fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
576                Self::empirical_recommended_wnaf_for_num_scalars(num_scalars)
577            }
578
579            fn as_xyz(&self) -> (&Self::Base, &Self::Base, &Self::Base) {
580                (&self.x, &self.y, &self.z)
581            }
582
583            fn into_xyz_unchecked(self) -> (Self::Base, Self::Base, Self::Base) {
584                (self.x, self.y, self.z)
585            }
586
587            fn from_xyz_unchecked(x: Self::Base, y: Self::Base, z: Self::Base) -> Self {
588                Self { x, y, z }
589            }
590
591            fn from_xyz_checked(_x: Self::Base, _y: Self::Base, _z: Self::Base) -> Result<Self, GroupDecodingError> {
592                unimplemented!("on curve check is not implemented for BLS12-381 projective")
593            }
594        }
595
596        // The affine point X, Y is represented in the jacobian
597        // coordinates with Z = 1.
598        impl From<$affine> for $projective {
599            fn from(p: $affine) -> $projective {
600                if p.is_zero() {
601                    $projective::zero()
602                } else {
603                    $projective {
604                        x: p.x,
605                        y: p.y,
606                        z: $basefield::one(),
607                    }
608                }
609            }
610        }
611
612        // The projective point X, Y, Z is represented in the affine
613        // coordinates as X/Z^2, Y/Z^3.
614        impl From<$projective> for $affine {
615            fn from(p: $projective) -> $affine {
616                if p.is_zero() {
617                    $affine::zero()
618                } else if p.z == $basefield::one() {
619                    // If Z is one, the point is already normalized.
620                    $affine { x: p.x, y: p.y, infinity: false }
621                } else {
622                    // Z is nonzero, so it must have an inverse in a field.
623                    let zinv = p.z.inverse().unwrap();
624                    let mut zinv_powered = zinv;
625                    zinv_powered.square();
626
627                    // X/Z^2
628                    let mut x = p.x;
629                    x.mul_assign(&zinv_powered);
630
631                    // Y/Z^3
632                    let mut y = p.y;
633                    zinv_powered.mul_assign(&zinv);
634                    y.mul_assign(&zinv_powered);
635
636                    $affine { x: x, y: y, infinity: false }
637                }
638            }
639        }
640    };
641}
642
643pub mod g1 {
644    use super::super::{Bn256, Fq, Fq12, FqRepr, Fr, FrRepr};
645    use super::g2::G2Affine;
646    use crate::{CurveAffine, CurveProjective, EncodedPoint, Engine, GroupDecodingError, RawEncodable};
647    use ff::{BitIterator, Field, PrimeField, PrimeFieldRepr, SqrtField};
648    use rand::{Rand, Rng};
649    use std::fmt;
650
651    curve_impl!("G1", G1, G1Affine, G1Prepared, Fq, Fr, G1Uncompressed, G1Compressed, G2Affine);
652
653    impl RawEncodable for G1Affine {
654        fn into_raw_uncompressed_le(&self) -> Self::Uncompressed {
655            let mut res = Self::Uncompressed::empty();
656            {
657                let mut writer = &mut res.0[..];
658
659                self.x.into_raw_repr().write_le(&mut writer).unwrap();
660                self.y.into_raw_repr().write_le(&mut writer).unwrap();
661            }
662
663            res
664        }
665
666        /// Creates a point from raw encoded coordinates without checking on curve
667        fn from_raw_uncompressed_le_unchecked(encoded: &Self::Uncompressed, _infinity: bool) -> Result<Self, GroupDecodingError> {
668            let copy = encoded.0;
669
670            if copy.iter().all(|b| *b == 0) {
671                return Ok(Self::zero());
672            }
673
674            let mut x = FqRepr([0; 4]);
675            let mut y = FqRepr([0; 4]);
676
677            {
678                let mut reader = &copy[..];
679                x.read_le(&mut reader).unwrap();
680                y.read_le(&mut reader).unwrap();
681            }
682
683            Ok(G1Affine {
684                x: Fq::from_raw_repr(x).map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate", e))?,
685                y: Fq::from_raw_repr(y).map_err(|e| GroupDecodingError::CoordinateDecodingError("y coordinate", e))?,
686                infinity: false,
687            })
688        }
689
690        fn from_raw_uncompressed_le(encoded: &Self::Uncompressed, _infinity: bool) -> Result<Self, GroupDecodingError> {
691            let affine = Self::from_raw_uncompressed_le_unchecked(&encoded, _infinity)?;
692
693            if !affine.is_on_curve() {
694                Err(GroupDecodingError::NotOnCurve)
695            } else {
696                Ok(affine)
697            }
698        }
699    }
700
701    #[derive(Copy, Clone)]
702    pub struct G1Uncompressed([u8; 64]);
703
704    impl Rand for G1 {
705        fn rand<R: Rng>(rng: &mut R) -> Self {
706            loop {
707                let x = rng.gen();
708                let greatest = rng.gen();
709
710                if let Some(p) = G1Affine::get_point_from_x(x, greatest) {
711                    if !p.is_zero() {
712                        if p.is_on_curve() {
713                            return p.into_projective();
714                        }
715                    }
716                }
717            }
718        }
719    }
720
721    impl Rand for G1Affine {
722        fn rand<R: Rng>(rng: &mut R) -> Self {
723            loop {
724                let x = rng.gen();
725                let greatest = rng.gen();
726
727                if let Some(p) = G1Affine::get_point_from_x(x, greatest) {
728                    if !p.is_zero() {
729                        if p.is_on_curve() {
730                            return p;
731                        }
732                    }
733                }
734            }
735        }
736    }
737
738    impl G1Uncompressed {
739        pub fn from_fixed_bytes(bytes: [u8; 64]) -> Self {
740            G1Uncompressed(bytes)
741        }
742    }
743
744    impl AsRef<[u8]> for G1Uncompressed {
745        fn as_ref(&self) -> &[u8] {
746            &self.0
747        }
748    }
749
750    impl AsMut<[u8]> for G1Uncompressed {
751        fn as_mut(&mut self) -> &mut [u8] {
752            &mut self.0
753        }
754    }
755
756    impl fmt::Debug for G1Uncompressed {
757        fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
758            self.0[..].fmt(formatter)
759        }
760    }
761
762    impl EncodedPoint for G1Uncompressed {
763        type Affine = G1Affine;
764
765        fn empty() -> Self {
766            G1Uncompressed([0; 64])
767        }
768        fn size() -> usize {
769            64
770        }
771        fn into_affine(&self) -> Result<G1Affine, GroupDecodingError> {
772            let affine = self.into_affine_unchecked()?;
773
774            if !affine.is_on_curve() {
775                Err(GroupDecodingError::NotOnCurve)
776            } else {
777                Ok(affine)
778            }
779        }
780        fn into_affine_unchecked(&self) -> Result<G1Affine, GroupDecodingError> {
781            // Create a copy of this representation.
782            let mut copy = self.0;
783
784            if copy[0] & (1 << 6) != 0 {
785                // This is the point at infinity, which means that if we mask away
786                // the first two bits, the entire representation should consist
787                // of zeroes.
788                copy[0] &= 0x3f;
789
790                if copy.iter().all(|b| *b == 0) {
791                    Ok(G1Affine::zero())
792                } else {
793                    Err(GroupDecodingError::UnexpectedInformation)
794                }
795            } else {
796                if copy[0] & (1 << 7) != 0 {
797                    // The bit indicating the y-coordinate should be lexicographically
798                    // largest is set, but this is an uncompressed element.
799                    return Err(GroupDecodingError::UnexpectedInformation);
800                }
801
802                // Unset the two most significant bits.
803                copy[0] &= 0x3f;
804
805                let mut x = FqRepr([0; 4]);
806                let mut y = FqRepr([0; 4]);
807
808                {
809                    let mut reader = &copy[..];
810
811                    x.read_be(&mut reader).unwrap();
812                    y.read_be(&mut reader).unwrap();
813                }
814
815                Ok(G1Affine {
816                    x: Fq::from_repr(x).map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate", e))?,
817                    y: Fq::from_repr(y).map_err(|e| GroupDecodingError::CoordinateDecodingError("y coordinate", e))?,
818                    infinity: false,
819                })
820            }
821        }
822        fn from_affine(affine: G1Affine) -> Self {
823            let mut res = Self::empty();
824
825            if affine.is_zero() {
826                // Set the second-most significant bit to indicate this point
827                // is at infinity.
828                res.0[0] |= 1 << 6;
829            } else {
830                let mut writer = &mut res.0[..];
831
832                affine.x.into_repr().write_be(&mut writer).unwrap();
833                affine.y.into_repr().write_be(&mut writer).unwrap();
834            }
835
836            res
837        }
838    }
839
840    #[derive(Copy, Clone)]
841    pub struct G1Compressed([u8; 32]);
842
843    impl G1Compressed {
844        pub fn from_fixed_bytes(bytes: [u8; 32]) -> Self {
845            G1Compressed(bytes)
846        }
847    }
848
849    impl AsRef<[u8]> for G1Compressed {
850        fn as_ref(&self) -> &[u8] {
851            &self.0
852        }
853    }
854
855    impl AsMut<[u8]> for G1Compressed {
856        fn as_mut(&mut self) -> &mut [u8] {
857            &mut self.0
858        }
859    }
860
861    impl fmt::Debug for G1Compressed {
862        fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
863            self.0[..].fmt(formatter)
864        }
865    }
866
867    impl EncodedPoint for G1Compressed {
868        type Affine = G1Affine;
869
870        fn empty() -> Self {
871            G1Compressed([0; 32])
872        }
873        fn size() -> usize {
874            32
875        }
876        fn into_affine(&self) -> Result<G1Affine, GroupDecodingError> {
877            let affine = self.into_affine_unchecked()?;
878
879            // NB: Decompression guarantees that it is on the curve already.
880
881            Ok(affine)
882        }
883        fn into_affine_unchecked(&self) -> Result<G1Affine, GroupDecodingError> {
884            // Create a copy of this representation.
885            let mut copy = self.0;
886
887            if copy[0] & (1 << 6) != 0 {
888                // This is the point at infinity, which means that if we mask away
889                // the first two bits, the entire representation should consist
890                // of zeroes.
891                copy[0] &= 0x3f;
892
893                if copy.iter().all(|b| *b == 0) {
894                    Ok(G1Affine::zero())
895                } else {
896                    Err(GroupDecodingError::UnexpectedInformation)
897                }
898            } else {
899                // Determine if the intended y coordinate must be greater
900                // lexicographically.
901                let greatest = copy[0] & (1 << 7) != 0;
902
903                // Unset the two most significant bits.
904                copy[0] &= 0x3f;
905
906                let mut x = FqRepr([0; 4]);
907
908                {
909                    let mut reader = &copy[..];
910
911                    x.read_be(&mut reader).unwrap();
912                }
913
914                // Interpret as Fq element.
915                let x = Fq::from_repr(x).map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate", e))?;
916
917                G1Affine::get_point_from_x(x, greatest).ok_or(GroupDecodingError::NotOnCurve)
918            }
919        }
920        fn from_affine(affine: G1Affine) -> Self {
921            let mut res = Self::empty();
922
923            if affine.is_zero() {
924                // Set the second-most significant bit to indicate this point
925                // is at infinity.
926                res.0[0] |= 1 << 6;
927            } else {
928                {
929                    let mut writer = &mut res.0[..];
930
931                    affine.x.into_repr().write_be(&mut writer).unwrap();
932                }
933
934                let mut negy = affine.y;
935                negy.negate();
936
937                // Set the third most significant bit if the correct y-coordinate
938                // is lexicographically largest.
939                if affine.y > negy {
940                    res.0[0] |= 1 << 7;
941                }
942            }
943
944            res
945        }
946    }
947
948    impl G1Affine {
949        // fn scale_by_cofactor(&self) -> G1 {
950        //     self.into_projective()
951        // }
952
953        fn get_generator() -> Self {
954            G1Affine {
955                x: super::super::fq::G1_GENERATOR_X,
956                y: super::super::fq::G1_GENERATOR_Y,
957                infinity: false,
958            }
959        }
960
961        fn get_coeff_b() -> Fq {
962            super::super::fq::B_COEFF
963        }
964
965        fn perform_pairing(&self, other: &G2Affine) -> Fq12 {
966            super::super::Bn256::pairing(*self, *other)
967        }
968    }
969
970    impl G1 {
971        fn empirical_recommended_wnaf_for_scalar(scalar: FrRepr) -> usize {
972            let num_bits = scalar.num_bits() as usize;
973
974            if num_bits >= 130 {
975                4
976            } else if num_bits >= 34 {
977                3
978            } else {
979                2
980            }
981        }
982
983        fn empirical_recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
984            const RECOMMENDATIONS: [usize; 12] = [1, 3, 7, 20, 43, 120, 273, 563, 1630, 3128, 7933, 62569];
985
986            let mut ret = 4;
987            for r in &RECOMMENDATIONS {
988                if num_scalars > *r {
989                    ret += 1;
990                } else {
991                    break;
992                }
993            }
994
995            ret
996        }
997    }
998
999    #[derive(Clone, Debug)]
1000    pub struct G1Prepared(pub(crate) G1Affine);
1001
1002    impl G1Prepared {
1003        pub fn is_zero(&self) -> bool {
1004            self.0.is_zero()
1005        }
1006
1007        pub fn from_affine(p: G1Affine) -> Self {
1008            G1Prepared(p)
1009        }
1010    }
1011
1012    #[test]
1013    fn g1_generator() {
1014        use SqrtField;
1015
1016        let mut x = Fq::zero();
1017        let mut i = 0;
1018        loop {
1019            // y^2 = x^3 + b
1020            let mut rhs = x;
1021            rhs.square();
1022            rhs.mul_assign(&x);
1023            rhs.add_assign(&G1Affine::get_coeff_b());
1024
1025            if let Some(y) = rhs.sqrt() {
1026                let yrepr = y.into_repr();
1027                let mut negy = y;
1028                negy.negate();
1029                let negyrepr = negy.into_repr();
1030
1031                let p = G1Affine {
1032                    x: x,
1033                    y: if yrepr < negyrepr { y } else { negy },
1034                    infinity: false,
1035                };
1036
1037                let g1 = p.into_projective();
1038                if !g1.is_zero() {
1039                    assert_eq!(i, 1);
1040                    let g1 = G1Affine::from(g1);
1041
1042                    assert_eq!(g1, G1Affine::one());
1043                    break;
1044                }
1045            }
1046
1047            i += 1;
1048            x.add_assign(&Fq::one());
1049        }
1050    }
1051
1052    #[test]
1053
1054    fn test_base_point_addition_and_doubling() {
1055        let mut a = G1::one();
1056        print!("{}\n\n", a);
1057
1058        a.add_assign(&G1::one());
1059
1060        print!("{}\n\n", a);
1061    }
1062
1063    #[test]
1064    fn g1_curve_tests() {
1065        crate::tests::curve::curve_tests::<G1>();
1066        crate::tests::curve::random_transformation_tests::<G1>();
1067    }
1068}
1069
1070pub mod g2 {
1071    use super::super::{Bn256, Fq, Fq12, Fq2, FqRepr, Fr, FrRepr};
1072    use super::g1::G1Affine;
1073    use crate::{CurveAffine, CurveProjective, EncodedPoint, Engine, GroupDecodingError};
1074    use ff::{BitIterator, Field, PrimeField, PrimeFieldRepr, SqrtField};
1075    use rand::{Rand, Rng};
1076    use std::fmt;
1077
1078    curve_impl!("G2", G2, G2Affine, G2Prepared, Fq2, Fr, G2Uncompressed, G2Compressed, G1Affine);
1079
1080    impl Rand for G2 {
1081        fn rand<R: Rng>(rng: &mut R) -> Self {
1082            loop {
1083                let x = rng.gen();
1084                let greatest = rng.gen();
1085
1086                if let Some(p) = G2Affine::get_point_from_x(x, greatest) {
1087                    if !p.is_zero() {
1088                        if p.is_on_curve() {
1089                            return p.scale_by_cofactor();
1090                        }
1091                    }
1092                }
1093            }
1094        }
1095    }
1096
1097    impl Rand for G2Affine {
1098        fn rand<R: Rng>(rng: &mut R) -> Self {
1099            let r = G2::rand(rng);
1100            return r.into_affine();
1101        }
1102    }
1103
1104    #[derive(Copy, Clone)]
1105    pub struct G2Uncompressed([u8; 128]);
1106
1107    impl G2Uncompressed {
1108        pub fn from_fixed_bytes(bytes: [u8; 128]) -> Self {
1109            G2Uncompressed(bytes)
1110        }
1111    }
1112
1113    impl AsRef<[u8]> for G2Uncompressed {
1114        fn as_ref(&self) -> &[u8] {
1115            &self.0
1116        }
1117    }
1118
1119    impl AsMut<[u8]> for G2Uncompressed {
1120        fn as_mut(&mut self) -> &mut [u8] {
1121            &mut self.0
1122        }
1123    }
1124
1125    impl fmt::Debug for G2Uncompressed {
1126        fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1127            self.0[..].fmt(formatter)
1128        }
1129    }
1130
1131    impl EncodedPoint for G2Uncompressed {
1132        type Affine = G2Affine;
1133
1134        fn empty() -> Self {
1135            G2Uncompressed([0; 128])
1136        }
1137        fn size() -> usize {
1138            128
1139        }
1140        fn into_affine(&self) -> Result<G2Affine, GroupDecodingError> {
1141            let affine = self.into_affine_unchecked()?;
1142
1143            if !affine.is_on_curve() {
1144                Err(GroupDecodingError::NotOnCurve)
1145            } else {
1146                Ok(affine)
1147            }
1148        }
1149        fn into_affine_unchecked(&self) -> Result<G2Affine, GroupDecodingError> {
1150            // Create a copy of this representation.
1151            let mut copy = self.0;
1152
1153            if copy[0] & (1 << 7) != 0 {
1154                // Distinguisher bit is set, but this should be uncompressed!
1155                return Err(GroupDecodingError::UnexpectedCompressionMode);
1156            }
1157
1158            if copy[0] & (1 << 6) != 0 {
1159                // This is the point at infinity, which means that if we mask away
1160                // the first two bits, the entire representation should consist
1161                // of zeroes.
1162                copy[0] &= 0x3f;
1163
1164                if copy.iter().all(|b| *b == 0) {
1165                    Ok(G2Affine::zero())
1166                } else {
1167                    Err(GroupDecodingError::UnexpectedInformation)
1168                }
1169            } else {
1170                // Unset the two most significant bits.
1171                copy[0] &= 0x3f;
1172
1173                let mut x_c0 = FqRepr([0; 4]);
1174                let mut x_c1 = FqRepr([0; 4]);
1175                let mut y_c0 = FqRepr([0; 4]);
1176                let mut y_c1 = FqRepr([0; 4]);
1177
1178                {
1179                    let mut reader = &copy[..];
1180
1181                    x_c1.read_be(&mut reader).unwrap();
1182                    x_c0.read_be(&mut reader).unwrap();
1183                    y_c1.read_be(&mut reader).unwrap();
1184                    y_c0.read_be(&mut reader).unwrap();
1185                }
1186
1187                Ok(G2Affine {
1188                    x: Fq2 {
1189                        c0: Fq::from_repr(x_c0).map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate (c0)", e))?,
1190                        c1: Fq::from_repr(x_c1).map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate (c1)", e))?,
1191                    },
1192                    y: Fq2 {
1193                        c0: Fq::from_repr(y_c0).map_err(|e| GroupDecodingError::CoordinateDecodingError("y coordinate (c0)", e))?,
1194                        c1: Fq::from_repr(y_c1).map_err(|e| GroupDecodingError::CoordinateDecodingError("y coordinate (c1)", e))?,
1195                    },
1196                    infinity: false,
1197                })
1198            }
1199        }
1200        fn from_affine(affine: G2Affine) -> Self {
1201            let mut res = Self::empty();
1202
1203            if affine.is_zero() {
1204                // Set the second-most significant bit to indicate this point
1205                // is at infinity.
1206                res.0[0] |= 1 << 6;
1207            } else {
1208                let mut writer = &mut res.0[..];
1209
1210                affine.x.c1.into_repr().write_be(&mut writer).unwrap();
1211                affine.x.c0.into_repr().write_be(&mut writer).unwrap();
1212                affine.y.c1.into_repr().write_be(&mut writer).unwrap();
1213                affine.y.c0.into_repr().write_be(&mut writer).unwrap();
1214            }
1215
1216            res
1217        }
1218    }
1219
1220    #[derive(Copy, Clone)]
1221    pub struct G2Compressed([u8; 64]);
1222
1223    impl G2Compressed {
1224        pub fn from_fixed_bytes(bytes: [u8; 64]) -> Self {
1225            G2Compressed(bytes)
1226        }
1227    }
1228
1229    impl AsRef<[u8]> for G2Compressed {
1230        fn as_ref(&self) -> &[u8] {
1231            &self.0
1232        }
1233    }
1234
1235    impl AsMut<[u8]> for G2Compressed {
1236        fn as_mut(&mut self) -> &mut [u8] {
1237            &mut self.0
1238        }
1239    }
1240
1241    impl fmt::Debug for G2Compressed {
1242        fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1243            self.0[..].fmt(formatter)
1244        }
1245    }
1246
1247    impl EncodedPoint for G2Compressed {
1248        type Affine = G2Affine;
1249
1250        fn empty() -> Self {
1251            G2Compressed([0; 64])
1252        }
1253        fn size() -> usize {
1254            64
1255        }
1256        fn into_affine(&self) -> Result<G2Affine, GroupDecodingError> {
1257            let affine = self.into_affine_unchecked()?;
1258
1259            // NB: Decompression guarantees that it is on the curve already.
1260
1261            Ok(affine)
1262        }
1263        fn into_affine_unchecked(&self) -> Result<G2Affine, GroupDecodingError> {
1264            // Create a copy of this representation.
1265            let mut copy = self.0;
1266
1267            if copy[0] & (1 << 6) != 0 {
1268                // This is the point at infinity, which means that if we mask away
1269                // the first two bits, the entire representation should consist
1270                // of zeroes.
1271                copy[0] &= 0x3f;
1272
1273                if copy.iter().all(|b| *b == 0) {
1274                    Ok(G2Affine::zero())
1275                } else {
1276                    Err(GroupDecodingError::UnexpectedInformation)
1277                }
1278            } else {
1279                // Determine if the intended y coordinate must be greater
1280                // lexicographically.
1281                let greatest = copy[0] & (1 << 7) != 0;
1282
1283                // Unset the two most significant bits.
1284                copy[0] &= 0x3f;
1285
1286                let mut x_c1 = FqRepr([0; 4]);
1287                let mut x_c0 = FqRepr([0; 4]);
1288
1289                {
1290                    let mut reader = &copy[..];
1291
1292                    x_c1.read_be(&mut reader).unwrap();
1293                    x_c0.read_be(&mut reader).unwrap();
1294                }
1295
1296                // Interpret as Fq element.
1297                let x = Fq2 {
1298                    c0: Fq::from_repr(x_c0).map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate (c0)", e))?,
1299                    c1: Fq::from_repr(x_c1).map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate (c1)", e))?,
1300                };
1301
1302                G2Affine::get_point_from_x(x, greatest).ok_or(GroupDecodingError::NotOnCurve)
1303            }
1304        }
1305        fn from_affine(affine: G2Affine) -> Self {
1306            let mut res = Self::empty();
1307
1308            if affine.is_zero() {
1309                // Set the second-most significant bit to indicate this point
1310                // is at infinity.
1311                res.0[0] |= 1 << 6;
1312            } else {
1313                {
1314                    let mut writer = &mut res.0[..];
1315
1316                    affine.x.c1.into_repr().write_be(&mut writer).unwrap();
1317                    affine.x.c0.into_repr().write_be(&mut writer).unwrap();
1318                }
1319
1320                let mut negy = affine.y;
1321                negy.negate();
1322
1323                // Set the third most significant bit if the correct y-coordinate
1324                // is lexicographically largest.
1325                if affine.y > negy {
1326                    res.0[0] |= 1 << 7;
1327                }
1328            }
1329
1330            res
1331        }
1332    }
1333
1334    impl G2Affine {
1335        pub fn scale_by_cofactor(&self) -> G2 {
1336            // G2 cofactor = 2p - n = 2q - r
1337            // 0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d
1338            let cofactor = BitIterator::new([0x345f2299c0f9fa8d, 0x06ceecda572a2489, 0xb85045b68181585e, 0x30644e72e131a029]);
1339            self.mul_bits(cofactor)
1340        }
1341
1342        fn get_generator() -> Self {
1343            G2Affine {
1344                x: Fq2 {
1345                    c0: super::super::fq::G2_GENERATOR_X_C0,
1346                    c1: super::super::fq::G2_GENERATOR_X_C1,
1347                },
1348                y: Fq2 {
1349                    c0: super::super::fq::G2_GENERATOR_Y_C0,
1350                    c1: super::super::fq::G2_GENERATOR_Y_C1,
1351                },
1352                infinity: false,
1353            }
1354        }
1355
1356        fn get_coeff_b() -> Fq2 {
1357            super::super::fq::B_COEFF_FQ2
1358            // Fq2 {
1359            //     c0: super::super::fq::B_COEFF,
1360            //     c1: super::super::fq::B_COEFF,
1361            // }
1362        }
1363
1364        fn perform_pairing(&self, other: &G1Affine) -> Fq12 {
1365            super::super::Bn256::pairing(*other, *self)
1366        }
1367    }
1368
1369    impl G2 {
1370        fn empirical_recommended_wnaf_for_scalar(scalar: FrRepr) -> usize {
1371            let num_bits = scalar.num_bits() as usize;
1372
1373            if num_bits >= 103 {
1374                4
1375            } else if num_bits >= 37 {
1376                3
1377            } else {
1378                2
1379            }
1380        }
1381
1382        fn empirical_recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
1383            const RECOMMENDATIONS: [usize; 11] = [1, 3, 8, 20, 47, 126, 260, 826, 1501, 4555, 84071];
1384
1385            let mut ret = 4;
1386            for r in &RECOMMENDATIONS {
1387                if num_scalars > *r {
1388                    ret += 1;
1389                } else {
1390                    break;
1391                }
1392            }
1393
1394            ret
1395        }
1396        pub fn double_with_alpha(&mut self, alpha: Fq2) {
1397            //x_r = alpha^2 - 2 * x
1398            let mut x_r = alpha;
1399            x_r.square();
1400            x_r.sub_assign(&self.x);
1401            x_r.sub_assign(&self.x);
1402
1403            // y_r = alpha * (x - x_r) - y
1404            let mut y_r = self.x;
1405            y_r.sub_assign(&x_r);
1406            y_r.mul_assign(&alpha);
1407            y_r.sub_assign(&self.y);
1408
1409            self.x = x_r;
1410            self.y = y_r;
1411        }
1412
1413        pub fn add_assign_mixed_with_alpha(&mut self, other: &G2Affine, alpha: Fq2) {
1414            let x1 = self.x;
1415            let y1 = self.y;
1416            let x2 = other.x;
1417            let y2 = other.y;
1418
1419            // x_r = alpha^2 - x1 - x2
1420            let mut x_r = alpha;
1421            x_r.square();
1422            x_r.sub_assign(&x1);
1423            x_r.sub_assign(&x2);
1424
1425            // y_r = alpha * (x1 - x_r) - y1
1426            let mut y_r = x1;
1427            y_r.sub_assign(&x_r);
1428            y_r.mul_assign(&alpha);
1429            y_r.sub_assign(&y1);
1430
1431            self.x = x_r;
1432            self.y = y_r;
1433        }
1434    }
1435
1436    #[derive(Clone, Debug)]
1437    pub struct G2Prepared {
1438        pub(crate) coeffs: Vec<(Fq2, Fq2, Fq2)>,
1439        pub(crate) infinity: bool,
1440    }
1441
1442    // This generator does not take a random element in Fp2
1443    // and tries to increment it to be on a curve, but
1444    // generates a random scalar and multiplies predefined generator by it
1445
1446    #[test]
1447    fn g2_generator() {
1448        use SqrtField;
1449
1450        let mut x = Fq2::zero();
1451        loop {
1452            // y^2 = x^3 + b
1453            let mut rhs = x;
1454            rhs.square();
1455            rhs.mul_assign(&x);
1456            rhs.add_assign(&G2Affine::get_coeff_b());
1457
1458            if let Some(y) = rhs.sqrt() {
1459                let mut negy = y;
1460                negy.negate();
1461
1462                let p = G2Affine {
1463                    x: x,
1464                    y: if y < negy { y } else { negy },
1465                    infinity: false,
1466                };
1467
1468                let g2 = p.into_projective();
1469                if !g2.is_zero() {
1470                    let _g2 = G2Affine::from(g2);
1471                    break;
1472                }
1473            }
1474
1475            x.add_assign(&Fq2::one());
1476        }
1477    }
1478
1479    #[test]
1480    fn test_generate_g2_in_subgroup() {
1481        use SqrtField;
1482
1483        let mut x = Fq2::zero();
1484        loop {
1485            // y^2 = x^3 + b
1486            let mut rhs = x;
1487            rhs.square();
1488            rhs.mul_assign(&x);
1489            rhs.add_assign(&G2Affine::get_coeff_b());
1490
1491            if let Some(y) = rhs.sqrt() {
1492                let mut negy = y;
1493                negy.negate();
1494
1495                let p = G2Affine {
1496                    x: x,
1497                    y: if y < negy { y } else { negy },
1498                    infinity: false,
1499                };
1500
1501                let g2 = p.into_projective();
1502                let mut minus_one = Fr::one();
1503                minus_one.negate();
1504
1505                let mut expected_zero = p.mul(minus_one);
1506                expected_zero.add_assign(&g2);
1507
1508                if !expected_zero.is_zero() {
1509                    let p = expected_zero.into_affine();
1510                    let scaled_by_cofactor = p.scale_by_cofactor();
1511                    if scaled_by_cofactor.is_zero() {
1512                        let g2 = G2Affine::from(expected_zero);
1513                        println!("Invalid subgroup point = {}", g2);
1514                        return;
1515                    }
1516                }
1517            }
1518
1519            x.add_assign(&Fq2::one());
1520        }
1521    }
1522
1523    #[cfg(test)]
1524    use rand::{SeedableRng, XorShiftRng};
1525
1526    #[test]
1527    fn g2_generator_on_curve() {
1528        use SqrtField;
1529
1530        let gen = G2Affine::get_generator();
1531        let x = gen.x;
1532        // y^2 = x^3 + 3/xi
1533        let mut rhs = x;
1534        rhs.square();
1535        rhs.mul_assign(&x);
1536        rhs.add_assign(&G2Affine::get_coeff_b());
1537
1538        if let Some(y) = rhs.sqrt() {
1539            let mut negy = y;
1540            negy.negate();
1541
1542            let p = G2Affine {
1543                x: x,
1544                y: if y < negy { y } else { negy },
1545                infinity: false,
1546            };
1547
1548            assert_eq!(p.y, gen.y);
1549            assert_eq!(p, G2Affine::one());
1550            return;
1551        }
1552        panic!();
1553    }
1554
1555    #[test]
1556    #[ignore] // TODO(ignored-test): Timeout.
1557    fn g2_curve_tests() {
1558        crate::tests::curve::curve_tests::<G2>();
1559        crate::tests::curve::random_transformation_tests::<G2>();
1560    }
1561
1562    #[test]
1563
1564    fn test_b_coeff() {
1565        let b2 = G2Affine::get_coeff_b();
1566        print!("{}\n\n", b2);
1567    }
1568
1569    #[test]
1570
1571    fn test_base_point_addition_and_doubling() {
1572        let mut two = G2::one();
1573        two.add_assign(&G2::one());
1574
1575        let one = G2::one();
1576
1577        let mut three21 = two;
1578        three21.add_assign(&one);
1579
1580        let mut three12 = one;
1581        three12.add_assign(&two);
1582
1583        assert_eq!(three12, three21);
1584    }
1585
1586    #[test]
1587    fn test_addition_and_doubling() {
1588        let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
1589
1590        for _ in 0..1000 {
1591            let a = G2::rand(&mut rng);
1592            assert!(a.into_affine().is_on_curve());
1593            let b = G2::rand(&mut rng);
1594            let c = G2::rand(&mut rng);
1595            let a_affine = a.into_affine();
1596            let b_affine = b.into_affine();
1597            let c_affine = c.into_affine();
1598
1599            // a + a should equal the doubling
1600            {
1601                let mut aplusa = a;
1602                aplusa.add_assign(&a);
1603
1604                let mut aplusamixed = a;
1605                aplusamixed.add_assign_mixed(&a.into_affine());
1606
1607                let mut adouble = a;
1608                adouble.double();
1609
1610                assert_eq!(aplusa, adouble);
1611                assert_eq!(aplusamixed, adouble);
1612            }
1613
1614            let mut ab = a;
1615            ab.add_assign(&b);
1616
1617            let mut ba = b;
1618            ba.add_assign(&a);
1619
1620            assert_eq!(ab, ba, "Addition should not depend on order");
1621
1622            let mut tmp = vec![G2::zero(); 6];
1623
1624            // (a + b) + c
1625            tmp[0] = a;
1626            tmp[0].add_assign(&b);
1627            tmp[0].add_assign(&c);
1628
1629            // a + (b + c)
1630            tmp[1] = b;
1631            tmp[1].add_assign(&c);
1632            tmp[1].add_assign(&a);
1633
1634            // (a + c) + b
1635            tmp[2] = a;
1636            tmp[2].add_assign(&c);
1637            tmp[2].add_assign(&b);
1638
1639            // Mixed addition
1640
1641            // (a + b) + c
1642            tmp[3] = a_affine.into_projective();
1643            tmp[3].add_assign_mixed(&b_affine);
1644            tmp[3].add_assign_mixed(&c_affine);
1645
1646            // a + (b + c)
1647            tmp[4] = b_affine.into_projective();
1648            tmp[4].add_assign_mixed(&c_affine);
1649            tmp[4].add_assign_mixed(&a_affine);
1650
1651            // (a + c) + b
1652            tmp[5] = a_affine.into_projective();
1653            tmp[5].add_assign_mixed(&c_affine);
1654            tmp[5].add_assign_mixed(&b_affine);
1655
1656            // Comparisons
1657            for i in 0..6 {
1658                for j in 0..6 {
1659                    assert_eq!(tmp[i], tmp[j]);
1660                    assert_eq!(tmp[i].into_affine(), tmp[j].into_affine());
1661                }
1662
1663                assert!(tmp[i] != a);
1664                assert!(tmp[i] != b);
1665                assert!(tmp[i] != c);
1666
1667                assert!(a != tmp[i]);
1668                assert!(b != tmp[i]);
1669                assert!(c != tmp[i]);
1670            }
1671        }
1672    }
1673
1674    #[test]
1675    fn random_negation_tests() {
1676        let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
1677
1678        for _ in 0..1000 {
1679            // let r = G2::rand(&mut rng);
1680            // assert!(r.into_affine().is_on_curve());
1681
1682            let mut r = G2::one();
1683            let k = Fr::rand(&mut rng);
1684            r.mul_assign(k);
1685
1686            let s = Fr::rand(&mut rng);
1687            let mut sneg = s;
1688            sneg.negate();
1689
1690            let mut t1 = r;
1691            t1.mul_assign(s);
1692
1693            let mut t2 = r;
1694            t2.mul_assign(sneg);
1695
1696            let mut t3 = t1;
1697            t3.add_assign(&t2);
1698            assert!(t3.is_zero());
1699
1700            let mut t4 = t1;
1701            t4.add_assign_mixed(&t2.into_affine());
1702            assert!(t4.is_zero());
1703
1704            t1.negate();
1705            assert_eq!(t1, t2);
1706        }
1707    }
1708
1709    #[test]
1710    fn mul_by_order_tests() {
1711        let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
1712
1713        for _ in 0..1000 {
1714            // let r = G2::rand(&mut rng);
1715
1716            let mut r = G2::one();
1717            let k = Fr::rand(&mut rng);
1718            r.mul_assign(k);
1719
1720            let order = Fr::char();
1721
1722            let mut q = G2::one();
1723            q.mul_assign(order);
1724            assert!(q.is_zero());
1725
1726            r.mul_assign(order);
1727            assert!(r.is_zero());
1728
1729            let mut t = G2::rand(&mut rng);
1730            t.mul_assign(order);
1731            assert!(t.is_zero());
1732        }
1733    }
1734}
1735
1736pub use self::g1::*;
1737pub use self::g2::*;