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 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 pub fn get_point_from_x(x: $basefield, greatest: bool) -> Option<$affine> {
103 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 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 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 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 let mut prod = Vec::with_capacity(v.len());
262 let mut tmp = $basefield::one();
263 for g in v
264 .iter_mut()
265 .filter(|g| !g.is_normalized())
267 {
268 tmp.mul_assign(&g.z);
269 prod.push(tmp);
270 }
271
272 tmp = tmp.inverse().unwrap(); for (g, s) in v
277 .iter_mut()
278 .rev()
280 .filter(|g| !g.is_normalized())
282 .zip(prod.into_iter().rev().skip(1).chain(Some($basefield::one())))
284 {
285 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 for g in v.iter_mut().filter(|g| !g.is_normalized()) {
295 let mut z = g.z; z.square(); g.x.mul_assign(&z); z.mul_assign(&g.z); g.y.mul_assign(&z); g.z = $basefield::one(); }
302 }
303
304 fn double(&mut self) {
305 if self.is_zero() {
306 return;
307 }
308
309 let mut a = self.x;
317 a.square();
318
319 let mut b = self.y;
321 b.square();
322
323 let mut c = b;
325 c.square();
326
327 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 let mut e = a;
337 e.double();
338 e.add_assign(&a);
339
340 let mut f = e;
342 f.square();
343
344 self.z.mul_assign(&self.y);
346 self.z.double();
347
348 self.x = f;
350 self.x.sub_assign(&d);
351 self.x.sub_assign(&d);
352
353 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 let mut z1z1 = self.z;
377 z1z1.square();
378
379 let mut z2z2 = other.z;
381 z2z2.square();
382
383 let mut u1 = self.x;
385 u1.mul_assign(&z2z2);
386
387 let mut u2 = other.x;
389 u2.mul_assign(&z1z1);
390
391 let mut s1 = self.y;
393 s1.mul_assign(&other.z);
394 s1.mul_assign(&z2z2);
395
396 let mut s2 = other.y;
398 s2.mul_assign(&self.z);
399 s2.mul_assign(&z1z1);
400
401 if u1 == u2 && s1 == s2 {
402 self.double();
404 } else {
405 if u1 == u2 {
408 (*self) = Self::zero();
410 return;
411 }
412
413 let mut h = u2;
415 h.sub_assign(&u1);
416
417 let mut i = h;
419 i.double();
420 i.square();
421
422 let mut j = h;
424 j.mul_assign(&i);
425
426 let mut r = s2;
428 r.sub_assign(&s1);
429 r.double();
430
431 let mut v = u1;
433 v.mul_assign(&i);
434
435 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 self.y = v;
444 self.y.sub_assign(&self.x);
445 self.y.mul_assign(&r);
446 s1.mul_assign(&j); s1.double();
448 self.y.sub_assign(&s1);
449
450 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 let mut z1z1 = self.z;
475 z1z1.square();
476
477 let mut u2 = other.x;
479 u2.mul_assign(&z1z1);
480
481 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 self.double();
489 } else {
490 let mut h = u2;
494 h.sub_assign(&self.x);
495
496 let mut hh = h;
498 hh.square();
499
500 let mut i = hh;
502 i.double();
503 i.double();
504
505 let mut j = h;
507 j.mul_assign(&i);
508
509 let mut r = s2;
511 r.sub_assign(&self.y);
512 r.double();
513
514 let mut v = self.x;
516 v.mul_assign(&i);
517
518 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 j.mul_assign(&self.y); 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 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 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 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 $affine { x: p.x, y: p.y, infinity: false }
621 } else {
622 let zinv = p.z.inverse().unwrap();
624 let mut zinv_powered = zinv;
625 zinv_powered.square();
626
627 let mut x = p.x;
629 x.mul_assign(&zinv_powered);
630
631 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 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 = ©[..];
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 let mut copy = self.0;
783
784 if copy[0] & (1 << 6) != 0 {
785 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 return Err(GroupDecodingError::UnexpectedInformation);
800 }
801
802 copy[0] &= 0x3f;
804
805 let mut x = FqRepr([0; 4]);
806 let mut y = FqRepr([0; 4]);
807
808 {
809 let mut reader = ©[..];
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 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 Ok(affine)
882 }
883 fn into_affine_unchecked(&self) -> Result<G1Affine, GroupDecodingError> {
884 let mut copy = self.0;
886
887 if copy[0] & (1 << 6) != 0 {
888 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 let greatest = copy[0] & (1 << 7) != 0;
902
903 copy[0] &= 0x3f;
905
906 let mut x = FqRepr([0; 4]);
907
908 {
909 let mut reader = ©[..];
910
911 x.read_be(&mut reader).unwrap();
912 }
913
914 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 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 if affine.y > negy {
940 res.0[0] |= 1 << 7;
941 }
942 }
943
944 res
945 }
946 }
947
948 impl G1Affine {
949 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 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 let mut copy = self.0;
1152
1153 if copy[0] & (1 << 7) != 0 {
1154 return Err(GroupDecodingError::UnexpectedCompressionMode);
1156 }
1157
1158 if copy[0] & (1 << 6) != 0 {
1159 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 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 = ©[..];
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 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 Ok(affine)
1262 }
1263 fn into_affine_unchecked(&self) -> Result<G2Affine, GroupDecodingError> {
1264 let mut copy = self.0;
1266
1267 if copy[0] & (1 << 6) != 0 {
1268 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 let greatest = copy[0] & (1 << 7) != 0;
1282
1283 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 = ©[..];
1291
1292 x_c1.read_be(&mut reader).unwrap();
1293 x_c0.read_be(&mut reader).unwrap();
1294 }
1295
1296 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 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 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 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 }
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 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 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 let mut x_r = alpha;
1421 x_r.square();
1422 x_r.sub_assign(&x1);
1423 x_r.sub_assign(&x2);
1424
1425 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 #[test]
1447 fn g2_generator() {
1448 use SqrtField;
1449
1450 let mut x = Fq2::zero();
1451 loop {
1452 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 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 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] 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 {
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 tmp[0] = a;
1626 tmp[0].add_assign(&b);
1627 tmp[0].add_assign(&c);
1628
1629 tmp[1] = b;
1631 tmp[1].add_assign(&c);
1632 tmp[1].add_assign(&a);
1633
1634 tmp[2] = a;
1636 tmp[2].add_assign(&c);
1637 tmp[2].add_assign(&b);
1638
1639 tmp[3] = a_affine.into_projective();
1643 tmp[3].add_assign_mixed(&b_affine);
1644 tmp[3].add_assign_mixed(&c_affine);
1645
1646 tmp[4] = b_affine.into_projective();
1648 tmp[4].add_assign_mixed(&c_affine);
1649 tmp[4].add_assign_mixed(&a_affine);
1650
1651 tmp[5] = a_affine.into_projective();
1653 tmp[5].add_assign_mixed(&c_affine);
1654 tmp[5].add_assign_mixed(&b_affine);
1655
1656 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 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 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::*;