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 }
18
19 impl ::std::fmt::Display for $affine
20 {
21 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
22 if self.x.is_zero() && self.y.is_zero() {
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 {
39 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
40 write!(f, "{}", self.into_affine())
41 }
42 }
43
44 impl PartialEq for $projective {
45 fn eq(&self, other: &$projective) -> bool {
46 if self.is_zero() {
47 return other.is_zero();
48 }
49
50 if other.is_zero() {
51 return false;
52 }
53
54 let mut z1 = self.z;
59 z1.square();
60 let mut z2 = other.z;
61 z2.square();
62
63 let mut tmp1 = self.x;
64 tmp1.mul_assign(&z2);
65
66 let mut tmp2 = other.x;
67 tmp2.mul_assign(&z1);
68
69 if tmp1 != tmp2 {
70 return false;
71 }
72
73 z1.mul_assign(&self.z);
74 z2.mul_assign(&other.z);
75 z2.mul_assign(&self.y);
76 z1.mul_assign(&other.y);
77
78 if z1 != z2 {
79 return false;
80 }
81
82 true
83 }
84 }
85
86 impl $affine {
87 fn mul_bits<S: AsRef<[u64]>>(&self, bits: BitIterator<S>) -> $projective {
88 let mut res = $projective::zero();
89 for i in bits {
90 res.double();
91 if i { res.add_assign_mixed(self) }
92 }
93 res
94 }
95
96 fn get_point_from_x(x: $basefield, greatest: bool) -> Option<$affine> {
102 let mut x3b = x;
104 x3b.square();
105 x3b.mul_assign(&x);
106 x3b.add_assign(&$affine::get_coeff_b());
107
108 x3b.sqrt().map(|y| {
109 let mut negy = y;
110 negy.negate();
111
112 $affine {
113 x: x,
114 y: if (y < negy) ^ greatest {
115 y
116 } else {
117 negy
118 },
119 }
120 })
121 }
122
123 fn is_on_curve(&self) -> bool {
124 if self.is_zero() {
125 true
126 } else {
127 let mut y2 = self.y;
129 y2.square();
130
131 let mut x3b = self.x;
132 x3b.square();
133 x3b.mul_assign(&self.x);
134 x3b.add_assign(&Self::get_coeff_b());
135
136 y2 == x3b
137 }
138 }
139
140 }
141
142 impl CurveAffine for $affine {
143 type Engine = Bn256;
144 type Scalar = $scalarfield;
145 type Base = $basefield;
146 type Prepared = $prepared;
147 type Projective = $projective;
148 type Uncompressed = $uncompressed;
149 type Compressed = $compressed;
150 type Pair = $pairing;
151 type PairingResult = Fq12;
152
153 fn zero() -> Self {
154 $affine {
155 x: $basefield::zero(),
156 y: $basefield::zero(),
157 }
158 }
159
160 fn one() -> Self {
161 Self::get_generator()
162 }
163
164 fn is_zero(&self) -> bool {
165 self.x.is_zero() && self.y.is_zero()
166 }
167
168 fn mul<S: Into<<Self::Scalar as PrimeField>::Repr>>(&self, by: S) -> $projective {
169 let bits = BitIterator::new(by.into());
170 self.mul_bits(bits)
171 }
172
173 fn negate(&mut self) {
174 if !self.is_zero() {
175 self.y.negate();
176 }
177 }
178
179 fn prepare(&self) -> Self::Prepared {
180 $prepared::from_affine(*self)
181 }
182
183 fn pairing_with(&self, other: &Self::Pair) -> Self::PairingResult {
184 self.perform_pairing(other)
185 }
186
187 fn into_projective(&self) -> $projective {
188 (*self).into()
189 }
190
191 #[inline(always)]
192 fn as_xy(&self) -> (&Self::Base, &Self::Base) {
193 (&self.x, &self.y)
194 }
195
196 #[inline(always)]
197 fn into_xy_unchecked(self) -> (Self::Base, Self::Base) {
198 (self.x, self.y)
199 }
200
201 #[inline(always)]
202 fn from_xy_unchecked(x: Self::Base, y: Self::Base) -> Self {
203 Self {
204 x: x,
205 y: y,
206 }
207 }
208
209 fn from_xy_checked(x: Self::Base, y: Self::Base) -> Result<Self, GroupDecodingError> {
210 let affine = Self {
211 x: x,
212 y: y,
213 };
214
215 if !affine.is_on_curve() {
216 Err(GroupDecodingError::NotOnCurve)
217 } else {
218 Ok(affine)
219 }
220 }
221
222 fn a_coeff() -> Self::Base {
223 Self::Base::zero()
224 }
225
226 fn b_coeff() -> Self::Base {
227 $affine::get_coeff_b()
228 }
229 }
230
231 impl CurveProjective for $projective {
232 type Engine = Bn256;
233 type Scalar = $scalarfield;
234 type Base = $basefield;
235 type Affine = $affine;
236
237 fn zero() -> Self {
240 $projective {
241 x: $basefield::zero(),
242 y: $basefield::one(),
243 z: $basefield::zero()
244 }
245 }
246
247 fn one() -> Self {
248 $affine::one().into()
249 }
250
251 fn is_zero(&self) -> bool {
254 self.z.is_zero()
255 }
256
257 fn is_normalized(&self) -> bool {
258 self.is_zero() || self.z == $basefield::one()
259 }
260
261 fn batch_normalization(v: &mut [Self])
262 {
263 let mut prod = Vec::with_capacity(v.len());
269 let mut tmp = $basefield::one();
270 for g in v.iter_mut()
271 .filter(|g| !g.is_normalized())
273 {
274 tmp.mul_assign(&g.z);
275 prod.push(tmp);
276 }
277
278 tmp = tmp.inverse().unwrap(); for (g, s) in v.iter_mut()
283 .rev()
285 .filter(|g| !g.is_normalized())
287 .zip(prod.into_iter().rev().skip(1).chain(Some($basefield::one())))
289 {
290 let mut newtmp = tmp;
292 newtmp.mul_assign(&g.z);
293 g.z = tmp;
294 g.z.mul_assign(&s);
295 tmp = newtmp;
296 }
297
298 for g in v.iter_mut()
300 .filter(|g| !g.is_normalized())
301 {
302 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(); }
309 }
310
311 fn double(&mut self) {
312 if self.is_zero() {
313 return;
314 }
315
316 let mut a = self.x;
324 a.square();
325
326 let mut b = self.y;
328 b.square();
329
330 let mut c = b;
332 c.square();
333
334 let mut d = self.x;
336 d.add_assign(&b);
337 d.square();
338 d.sub_assign(&a);
339 d.sub_assign(&c);
340 d.double();
341
342 let mut e = a;
344 e.double();
345 e.add_assign(&a);
346
347 let mut f = e;
349 f.square();
350
351 self.z.mul_assign(&self.y);
353 self.z.double();
354
355 self.x = f;
357 self.x.sub_assign(&d);
358 self.x.sub_assign(&d);
359
360 self.y = d;
362 self.y.sub_assign(&self.x);
363 self.y.mul_assign(&e);
364 c.double();
365 c.double();
366 c.double();
367 self.y.sub_assign(&c);
368 }
369
370 fn add_assign(&mut self, other: &Self) {
371 if self.is_zero() {
372 *self = *other;
373 return;
374 }
375
376 if other.is_zero() {
377 return;
378 }
379
380 let mut z1z1 = self.z;
384 z1z1.square();
385
386 let mut z2z2 = other.z;
388 z2z2.square();
389
390 let mut u1 = self.x;
392 u1.mul_assign(&z2z2);
393
394 let mut u2 = other.x;
396 u2.mul_assign(&z1z1);
397
398 let mut s1 = self.y;
400 s1.mul_assign(&other.z);
401 s1.mul_assign(&z2z2);
402
403 let mut s2 = other.y;
405 s2.mul_assign(&self.z);
406 s2.mul_assign(&z1z1);
407
408 if u1 == u2 && s1 == s2 {
409 self.double();
411 } else {
412 if u1 == u2 {
415 (*self) = Self::zero();
417 return;
418 }
419
420 let mut h = u2;
422 h.sub_assign(&u1);
423
424 let mut i = h;
426 i.double();
427 i.square();
428
429 let mut j = h;
431 j.mul_assign(&i);
432
433 let mut r = s2;
435 r.sub_assign(&s1);
436 r.double();
437
438 let mut v = u1;
440 v.mul_assign(&i);
441
442 self.x = r;
444 self.x.square();
445 self.x.sub_assign(&j);
446 self.x.sub_assign(&v);
447 self.x.sub_assign(&v);
448
449 self.y = v;
451 self.y.sub_assign(&self.x);
452 self.y.mul_assign(&r);
453 s1.mul_assign(&j); s1.double();
455 self.y.sub_assign(&s1);
456
457 self.z.add_assign(&other.z);
459 self.z.square();
460 self.z.sub_assign(&z1z1);
461 self.z.sub_assign(&z2z2);
462 self.z.mul_assign(&h);
463 }
464 }
465
466 fn add_assign_mixed(&mut self, other: &Self::Affine) {
467 if other.is_zero() {
468 return;
469 }
470
471 if self.is_zero() {
472 self.x = other.x;
473 self.y = other.y;
474 self.z = $basefield::one();
475 return;
476 }
477
478 let mut z1z1 = self.z;
482 z1z1.square();
483
484 let mut u2 = other.x;
486 u2.mul_assign(&z1z1);
487
488 let mut s2 = other.y;
490 s2.mul_assign(&self.z);
491 s2.mul_assign(&z1z1);
492
493 if self.x == u2 && self.y == s2 {
494 self.double();
496 } else {
497 let mut h = u2;
501 h.sub_assign(&self.x);
502
503 let mut hh = h;
505 hh.square();
506
507 let mut i = hh;
509 i.double();
510 i.double();
511
512 let mut j = h;
514 j.mul_assign(&i);
515
516 let mut r = s2;
518 r.sub_assign(&self.y);
519 r.double();
520
521 let mut v = self.x;
523 v.mul_assign(&i);
524
525 self.x = r;
527 self.x.square();
528 self.x.sub_assign(&j);
529 self.x.sub_assign(&v);
530 self.x.sub_assign(&v);
531
532 j.mul_assign(&self.y); j.double();
535 self.y = v;
536 self.y.sub_assign(&self.x);
537 self.y.mul_assign(&r);
538 self.y.sub_assign(&j);
539
540 self.z.add_assign(&h);
542 self.z.square();
543 self.z.sub_assign(&z1z1);
544 self.z.sub_assign(&hh);
545 }
546 }
547
548 fn negate(&mut self) {
549 if !self.is_zero() {
550 self.y.negate()
551 }
552 }
553
554 fn mul_assign<S: Into<<Self::Scalar as PrimeField>::Repr>>(&mut self, other: S) {
555 let mut res = Self::zero();
556
557 let mut found_one = false;
558
559 for i in BitIterator::new(other.into())
560 {
561 if found_one {
562 res.double();
563 } else {
564 found_one = i;
565 }
566
567 if i {
568 res.add_assign(self);
569 }
570 }
571
572 *self = res;
573 }
574
575 fn into_affine(&self) -> $affine {
576 (*self).into()
577 }
578
579 fn recommended_wnaf_for_scalar(scalar: <Self::Scalar as PrimeField>::Repr) -> usize {
580 Self::empirical_recommended_wnaf_for_scalar(scalar)
581 }
582
583 fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
584 Self::empirical_recommended_wnaf_for_num_scalars(num_scalars)
585 }
586
587 fn as_xyz(&self) -> (&Self::Base, &Self::Base, &Self::Base) {
588 (&self.x, &self.y, &self.z)
589 }
590
591 fn into_xyz_unchecked(self) -> (Self::Base, Self::Base, Self::Base) {
592 (self.x, self.y, self.z)
593 }
594
595 fn from_xyz_unchecked(x: Self::Base, y: Self::Base, z: Self::Base) -> Self {
596 Self {
597 x,
598 y,
599 z
600 }
601 }
602
603 fn from_xyz_checked(_x: Self::Base, _y: Self::Base, _z: Self::Base) -> Result<Self, GroupDecodingError> {
604 unimplemented!("on curve check is not implemented for BLS12-381 projective")
605 }
606 }
607
608 impl From<$affine> for $projective {
611 fn from(p: $affine) -> $projective {
612 if p.is_zero() {
613 $projective::zero()
614 } else {
615 $projective {
616 x: p.x,
617 y: p.y,
618 z: $basefield::one()
619 }
620 }
621 }
622 }
623
624 impl From<$projective> for $affine {
627 fn from(p: $projective) -> $affine {
628 if p.is_zero() {
629 $affine::zero()
630 } else if p.z == $basefield::one() {
631 $affine {
633 x: p.x,
634 y: p.y,
635 }
636 } else {
637 let zinv = p.z.inverse().unwrap();
639 let mut zinv_powered = zinv;
640 zinv_powered.square();
641
642 let mut x = p.x;
644 x.mul_assign(&zinv_powered);
645
646 let mut y = p.y;
648 zinv_powered.mul_assign(&zinv);
649 y.mul_assign(&zinv_powered);
650
651 $affine {
652 x: x,
653 y: y,
654 }
655 }
656 }
657 }
658 }
659}
660
661pub mod g1 {
662 use super::super::{Bn256, Fq, Fq12, FqRepr, Fr, FrRepr};
663 use super::g2::G2Affine;
664 use ff::{BitIterator, Field, PrimeField, PrimeFieldRepr, SqrtField};
665 use rand::{Rand, Rng};
666 use std::fmt;
667 use crate::{RawEncodable, CurveAffine, CurveProjective, EncodedPoint, Engine, GroupDecodingError};
668
669 curve_impl!(
670 "G1",
671 G1,
672 G1Affine,
673 G1Prepared,
674 Fq,
675 Fr,
676 G1Uncompressed,
677 G1Compressed,
678 G2Affine
679 );
680
681 impl RawEncodable for G1Affine {
682 fn into_raw_uncompressed_le(&self) -> Self::Uncompressed {
683 let mut res = Self::Uncompressed::empty();
684 {
685 let mut writer = &mut res.0[..];
686
687 self.x.into_raw_repr().write_le(&mut writer).unwrap();
688 self.y.into_raw_repr().write_le(&mut writer).unwrap();
689 }
690
691 res
692 }
693
694 fn from_raw_uncompressed_le_unchecked(
696 encoded: &Self::Uncompressed,
697 _infinity: bool
698 ) -> Result<Self, GroupDecodingError> {
699 let copy = encoded.0;
700
701 if copy.iter().all(|b| *b == 0) {
702 return Ok(Self::zero());
703 }
704
705 let mut x = FqRepr([0; 4]);
706 let mut y = FqRepr([0; 4]);
707
708 {
709 let mut reader = ©[..];
710 x.read_le(&mut reader).unwrap();
711 y.read_le(&mut reader).unwrap();
712 }
713
714 Ok(G1Affine {
715 x: Fq::from_raw_repr(x).map_err(|e| {
716 GroupDecodingError::CoordinateDecodingError("x coordinate", e)
717 })?,
718 y: Fq::from_raw_repr(y).map_err(|e| {
719 GroupDecodingError::CoordinateDecodingError("y coordinate", e)
720 })?,
721 })
722 }
723
724 fn from_raw_uncompressed_le(encoded: &Self::Uncompressed, _infinity: bool) -> Result<Self, GroupDecodingError> {
725 let affine = Self::from_raw_uncompressed_le_unchecked(&encoded, _infinity)?;
726
727 if !affine.is_on_curve() {
728 Err(GroupDecodingError::NotOnCurve)
729 } else {
730 Ok(affine)
731 }
732 }
733 }
734
735 #[derive(Copy, Clone)]
736 pub struct G1Uncompressed([u8; 64]);
737
738 impl Rand for G1 {
739 fn rand<R: Rng>(rng: &mut R) -> Self {
740 loop {
741 let x = rng.gen();
742 let greatest = rng.gen();
743
744 if let Some(p) = G1Affine::get_point_from_x(x, greatest) {
745 if !p.is_zero() {
746 if p.is_on_curve() {
747 return p.into_projective();
748 }
749 }
750 }
751 }
752 }
753 }
754
755 impl Rand for G1Affine {
756 fn rand<R: Rng>(rng: &mut R) -> Self {
757 loop {
758 let x = rng.gen();
759 let greatest = rng.gen();
760
761 if let Some(p) = G1Affine::get_point_from_x(x, greatest) {
762 if !p.is_zero() {
763 if p.is_on_curve() {
764 return p;
765 }
766 }
767 }
768 }
769 }
770 }
771
772 impl AsRef<[u8]> for G1Uncompressed {
773 fn as_ref(&self) -> &[u8] {
774 &self.0
775 }
776 }
777
778 impl AsMut<[u8]> for G1Uncompressed {
779 fn as_mut(&mut self) -> &mut [u8] {
780 &mut self.0
781 }
782 }
783
784 impl fmt::Debug for G1Uncompressed {
785 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
786 self.0[..].fmt(formatter)
787 }
788 }
789
790 impl EncodedPoint for G1Uncompressed {
791 type Affine = G1Affine;
792
793 fn empty() -> Self {
794 G1Uncompressed([0; 64])
795 }
796 fn size() -> usize {
797 64
798 }
799 fn into_affine(&self) -> Result<G1Affine, GroupDecodingError> {
800 let affine = self.into_affine_unchecked()?;
801
802 if !affine.is_on_curve() {
803 Err(GroupDecodingError::NotOnCurve)
804 } else {
805 Ok(affine)
806 }
807 }
808 fn into_affine_unchecked(&self) -> Result<G1Affine, GroupDecodingError> {
809 let mut copy = self.0;
811
812 if copy[0] & (1 << 6) != 0 {
813 copy[0] &= 0x3f;
817
818 if copy.iter().all(|b| *b == 0) {
819 Ok(G1Affine::zero())
820 } else {
821 Err(GroupDecodingError::UnexpectedInformation)
822 }
823 } else {
824 if copy[0] & (1 << 7) != 0 {
825 return Err(GroupDecodingError::UnexpectedInformation);
828 }
829
830 copy[0] &= 0x3f;
832
833 let mut x = FqRepr([0; 4]);
834 let mut y = FqRepr([0; 4]);
835
836 {
837 let mut reader = ©[..];
838
839 x.read_be(&mut reader).unwrap();
840 y.read_be(&mut reader).unwrap();
841 }
842
843 Ok(G1Affine {
844 x: Fq::from_repr(x).map_err(|e| {
845 GroupDecodingError::CoordinateDecodingError("x coordinate", e)
846 })?,
847 y: Fq::from_repr(y).map_err(|e| {
848 GroupDecodingError::CoordinateDecodingError("y coordinate", e)
849 })?,
850 })
851 }
852 }
853 fn from_affine(affine: G1Affine) -> Self {
854 let mut res = Self::empty();
855
856 if affine.is_zero() {
857 res.0[0] |= 1 << 6;
860 } else {
861 let mut writer = &mut res.0[..];
862
863 affine.x.into_repr().write_be(&mut writer).unwrap();
864 affine.y.into_repr().write_be(&mut writer).unwrap();
865 }
866
867 res
868 }
869 }
870
871 #[derive(Copy, Clone)]
872 pub struct G1Compressed([u8; 32]);
873
874 impl AsRef<[u8]> for G1Compressed {
875 fn as_ref(&self) -> &[u8] {
876 &self.0
877 }
878 }
879
880 impl AsMut<[u8]> for G1Compressed {
881 fn as_mut(&mut self) -> &mut [u8] {
882 &mut self.0
883 }
884 }
885
886 impl fmt::Debug for G1Compressed {
887 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
888 self.0[..].fmt(formatter)
889 }
890 }
891
892 impl EncodedPoint for G1Compressed {
893 type Affine = G1Affine;
894
895 fn empty() -> Self {
896 G1Compressed([0; 32])
897 }
898 fn size() -> usize {
899 32
900 }
901 fn into_affine(&self) -> Result<G1Affine, GroupDecodingError> {
902 let affine = self.into_affine_unchecked()?;
903
904 Ok(affine)
907 }
908 fn into_affine_unchecked(&self) -> Result<G1Affine, GroupDecodingError> {
909 let mut copy = self.0;
911
912 if copy[0] & (1 << 6) != 0 {
913 copy[0] &= 0x3f;
917
918 if copy.iter().all(|b| *b == 0) {
919 Ok(G1Affine::zero())
920 } else {
921 Err(GroupDecodingError::UnexpectedInformation)
922 }
923 } else {
924 let greatest = copy[0] & (1 << 7) != 0;
927
928 copy[0] &= 0x3f;
930
931 let mut x = FqRepr([0; 4]);
932
933 {
934 let mut reader = ©[..];
935
936 x.read_be(&mut reader).unwrap();
937 }
938
939 let x = Fq::from_repr(x)
941 .map_err(|e| GroupDecodingError::CoordinateDecodingError("x coordinate", e))?;
942
943 G1Affine::get_point_from_x(x, greatest).ok_or(GroupDecodingError::NotOnCurve)
944 }
945 }
946 fn from_affine(affine: G1Affine) -> Self {
947 let mut res = Self::empty();
948
949 if affine.is_zero() {
950 res.0[0] |= 1 << 6;
953 } else {
954 {
955 let mut writer = &mut res.0[..];
956
957 affine.x.into_repr().write_be(&mut writer).unwrap();
958 }
959
960 let mut negy = affine.y;
961 negy.negate();
962
963 if affine.y > negy {
966 res.0[0] |= 1 << 7;
967 }
968 }
969
970 res
971 }
972 }
973
974 impl G1Affine {
975 fn get_generator() -> Self {
980 G1Affine {
981 x: super::super::fq::G1_GENERATOR_X,
982 y: super::super::fq::G1_GENERATOR_Y,
983 }
984 }
985
986 fn get_coeff_b() -> Fq {
987 super::super::fq::B_COEFF
988 }
989
990 fn perform_pairing(&self, other: &G2Affine) -> Fq12 {
991 super::super::Bn256::pairing(*self, *other)
992 }
993 }
994
995 impl G1 {
996 fn empirical_recommended_wnaf_for_scalar(scalar: FrRepr) -> usize {
997 let num_bits = scalar.num_bits() as usize;
998
999 if num_bits >= 130 {
1000 4
1001 } else if num_bits >= 34 {
1002 3
1003 } else {
1004 2
1005 }
1006 }
1007
1008 fn empirical_recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
1009 const RECOMMENDATIONS: [usize; 12] =
1010 [1, 3, 7, 20, 43, 120, 273, 563, 1630, 3128, 7933, 62569];
1011
1012 let mut ret = 4;
1013 for r in &RECOMMENDATIONS {
1014 if num_scalars > *r {
1015 ret += 1;
1016 } else {
1017 break;
1018 }
1019 }
1020
1021 ret
1022 }
1023 }
1024
1025 #[derive(Clone, Debug)]
1026 pub struct G1Prepared(pub(crate) G1Affine);
1027
1028 impl G1Prepared {
1029 pub fn is_zero(&self) -> bool {
1030 self.0.is_zero()
1031 }
1032
1033 pub fn from_affine(p: G1Affine) -> Self {
1034 G1Prepared(p)
1035 }
1036 }
1037
1038 #[test]
1039 fn g1_generator() {
1040 use SqrtField;
1041
1042 let mut x = Fq::zero();
1043 let mut i = 0;
1044 loop {
1045 let mut rhs = x;
1047 rhs.square();
1048 rhs.mul_assign(&x);
1049 rhs.add_assign(&G1Affine::get_coeff_b());
1050
1051 if let Some(y) = rhs.sqrt() {
1052 let yrepr = y.into_repr();
1053 let mut negy = y;
1054 negy.negate();
1055 let negyrepr = negy.into_repr();
1056
1057 let p = G1Affine {
1058 x: x,
1059 y: if yrepr < negyrepr { y } else { negy },
1060 };
1061
1062 let g1 = p.into_projective();
1063 if !g1.is_zero() {
1064 assert_eq!(i, 1);
1065 let g1 = G1Affine::from(g1);
1066
1067 assert_eq!(g1, G1Affine::one());
1068 break;
1069 }
1070 }
1071
1072 i += 1;
1073 x.add_assign(&Fq::one());
1074 }
1075 }
1076
1077 #[test]
1078
1079 fn test_base_point_addition_and_doubling() {
1080 let mut a = G1::one();
1081 print!("{}\n\n", a);
1082
1083 a.add_assign(&G1::one());
1084
1085 print!("{}\n\n", a);
1086 }
1087
1088 #[test]
1089 fn g1_curve_tests() {
1090 crate::tests::curve::curve_tests::<G1>();
1091 crate::tests::curve::random_transformation_tests::<G1>();
1092 }
1093}
1094
1095pub mod g2 {
1096 use super::super::{Bn256, Fq, Fq12, Fq2, FqRepr, Fr, FrRepr};
1097 use super::g1::G1Affine;
1098 use ff::{BitIterator, Field, PrimeField, PrimeFieldRepr, SqrtField};
1099 use rand::{Rand, Rng};
1100 use std::fmt;
1101 use crate::{CurveAffine, CurveProjective, EncodedPoint, Engine, GroupDecodingError};
1102
1103 curve_impl!(
1104 "G2",
1105 G2,
1106 G2Affine,
1107 G2Prepared,
1108 Fq2,
1109 Fr,
1110 G2Uncompressed,
1111 G2Compressed,
1112 G1Affine
1113 );
1114
1115 impl Rand for G2 {
1116 fn rand<R: Rng>(rng: &mut R) -> Self {
1117 loop {
1118 let x = rng.gen();
1119 let greatest = rng.gen();
1120
1121 if let Some(p) = G2Affine::get_point_from_x(x, greatest) {
1122 if !p.is_zero() {
1123 if p.is_on_curve() {
1124 return p.scale_by_cofactor();
1125 }
1126 }
1127 }
1128 }
1129 }
1130 }
1131
1132 impl Rand for G2Affine {
1133 fn rand<R: Rng>(rng: &mut R) -> Self {
1134 let r = G2::rand(rng);
1135 return r.into_affine();
1136 }
1137 }
1138
1139 #[derive(Copy, Clone)]
1140 pub struct G2Uncompressed([u8; 128]);
1141
1142 impl AsRef<[u8]> for G2Uncompressed {
1143 fn as_ref(&self) -> &[u8] {
1144 &self.0
1145 }
1146 }
1147
1148 impl AsMut<[u8]> for G2Uncompressed {
1149 fn as_mut(&mut self) -> &mut [u8] {
1150 &mut self.0
1151 }
1152 }
1153
1154 impl fmt::Debug for G2Uncompressed {
1155 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1156 self.0[..].fmt(formatter)
1157 }
1158 }
1159
1160 impl EncodedPoint for G2Uncompressed {
1161 type Affine = G2Affine;
1162
1163 fn empty() -> Self {
1164 G2Uncompressed([0; 128])
1165 }
1166 fn size() -> usize {
1167 128
1168 }
1169 fn into_affine(&self) -> Result<G2Affine, GroupDecodingError> {
1170 let affine = self.into_affine_unchecked()?;
1171
1172 if !affine.is_on_curve() {
1173 Err(GroupDecodingError::NotOnCurve)
1174 } else {
1175 Ok(affine)
1176 }
1177 }
1178 fn into_affine_unchecked(&self) -> Result<G2Affine, GroupDecodingError> {
1179 let mut copy = self.0;
1181
1182 if copy[0] & (1 << 7) != 0 {
1183 return Err(GroupDecodingError::UnexpectedCompressionMode);
1185 }
1186
1187 if copy[0] & (1 << 6) != 0 {
1188 copy[0] &= 0x3f;
1192
1193 if copy.iter().all(|b| *b == 0) {
1194 Ok(G2Affine::zero())
1195 } else {
1196 Err(GroupDecodingError::UnexpectedInformation)
1197 }
1198 } else {
1199
1200 copy[0] &= 0x3f;
1202
1203 let mut x_c0 = FqRepr([0; 4]);
1204 let mut x_c1 = FqRepr([0; 4]);
1205 let mut y_c0 = FqRepr([0; 4]);
1206 let mut y_c1 = FqRepr([0; 4]);
1207
1208 {
1209 let mut reader = ©[..];
1210
1211 x_c1.read_be(&mut reader).unwrap();
1212 x_c0.read_be(&mut reader).unwrap();
1213 y_c1.read_be(&mut reader).unwrap();
1214 y_c0.read_be(&mut reader).unwrap();
1215 }
1216
1217 Ok(G2Affine {
1218 x: Fq2 {
1219 c0: Fq::from_repr(x_c0).map_err(|e| {
1220 GroupDecodingError::CoordinateDecodingError("x coordinate (c0)", e)
1221 })?,
1222 c1: Fq::from_repr(x_c1).map_err(|e| {
1223 GroupDecodingError::CoordinateDecodingError("x coordinate (c1)", e)
1224 })?,
1225 },
1226 y: Fq2 {
1227 c0: Fq::from_repr(y_c0).map_err(|e| {
1228 GroupDecodingError::CoordinateDecodingError("y coordinate (c0)", e)
1229 })?,
1230 c1: Fq::from_repr(y_c1).map_err(|e| {
1231 GroupDecodingError::CoordinateDecodingError("y coordinate (c1)", e)
1232 })?,
1233 },
1234 })
1235 }
1236 }
1237 fn from_affine(affine: G2Affine) -> Self {
1238 let mut res = Self::empty();
1239
1240 if affine.is_zero() {
1241 res.0[0] |= 1 << 6;
1244 } else {
1245 let mut writer = &mut res.0[..];
1246
1247 affine.x.c1.into_repr().write_be(&mut writer).unwrap();
1248 affine.x.c0.into_repr().write_be(&mut writer).unwrap();
1249 affine.y.c1.into_repr().write_be(&mut writer).unwrap();
1250 affine.y.c0.into_repr().write_be(&mut writer).unwrap();
1251 }
1252
1253 res
1254 }
1255 }
1256
1257 #[derive(Copy, Clone)]
1258 pub struct G2Compressed([u8; 64]);
1259
1260 impl AsRef<[u8]> for G2Compressed {
1261 fn as_ref(&self) -> &[u8] {
1262 &self.0
1263 }
1264 }
1265
1266 impl AsMut<[u8]> for G2Compressed {
1267 fn as_mut(&mut self) -> &mut [u8] {
1268 &mut self.0
1269 }
1270 }
1271
1272 impl fmt::Debug for G2Compressed {
1273 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1274 self.0[..].fmt(formatter)
1275 }
1276 }
1277
1278 impl EncodedPoint for G2Compressed {
1279 type Affine = G2Affine;
1280
1281 fn empty() -> Self {
1282 G2Compressed([0; 64])
1283 }
1284 fn size() -> usize {
1285 64
1286 }
1287 fn into_affine(&self) -> Result<G2Affine, GroupDecodingError> {
1288 let affine = self.into_affine_unchecked()?;
1289
1290 Ok(affine)
1293 }
1294 fn into_affine_unchecked(&self) -> Result<G2Affine, GroupDecodingError> {
1295 let mut copy = self.0;
1297
1298 if copy[0] & (1 << 6) != 0 {
1299 copy[0] &= 0x3f;
1303
1304 if copy.iter().all(|b| *b == 0) {
1305 Ok(G2Affine::zero())
1306 } else {
1307 Err(GroupDecodingError::UnexpectedInformation)
1308 }
1309 } else {
1310 let greatest = copy[0] & (1 << 7) != 0;
1313
1314 copy[0] &= 0x3f;
1316
1317 let mut x_c1 = FqRepr([0; 4]);
1318 let mut x_c0 = FqRepr([0; 4]);
1319
1320 {
1321 let mut reader = ©[..];
1322
1323 x_c1.read_be(&mut reader).unwrap();
1324 x_c0.read_be(&mut reader).unwrap();
1325 }
1326
1327 let x = Fq2 {
1329 c0: Fq::from_repr(x_c0).map_err(|e| {
1330 GroupDecodingError::CoordinateDecodingError("x coordinate (c0)", e)
1331 })?,
1332 c1: Fq::from_repr(x_c1).map_err(|e| {
1333 GroupDecodingError::CoordinateDecodingError("x coordinate (c1)", e)
1334 })?,
1335 };
1336
1337 G2Affine::get_point_from_x(x, greatest).ok_or(GroupDecodingError::NotOnCurve)
1338 }
1339 }
1340 fn from_affine(affine: G2Affine) -> Self {
1341 let mut res = Self::empty();
1342
1343 if affine.is_zero() {
1344 res.0[0] |= 1 << 6;
1347 } else {
1348 {
1349 let mut writer = &mut res.0[..];
1350
1351 affine.x.c1.into_repr().write_be(&mut writer).unwrap();
1352 affine.x.c0.into_repr().write_be(&mut writer).unwrap();
1353 }
1354
1355 let mut negy = affine.y;
1356 negy.negate();
1357
1358 if affine.y > negy {
1361 res.0[0] |= 1 << 7;
1362 }
1363 }
1364
1365 res
1366 }
1367 }
1368
1369 impl G2Affine {
1370 fn scale_by_cofactor(&self) -> G2 {
1371 let cofactor = BitIterator::new([
1374 0x345f2299c0f9fa8d,
1375 0x06ceecda572a2489,
1376 0xb85045b68181585e,
1377 0x30644e72e131a029,
1378 ]);
1379 self.mul_bits(cofactor)
1380 }
1381
1382 fn get_generator() -> Self {
1383 G2Affine {
1384 x: Fq2 {
1385 c0: super::super::fq::G2_GENERATOR_X_C0,
1386 c1: super::super::fq::G2_GENERATOR_X_C1,
1387 },
1388 y: Fq2 {
1389 c0: super::super::fq::G2_GENERATOR_Y_C0,
1390 c1: super::super::fq::G2_GENERATOR_Y_C1,
1391 },
1392 }
1393 }
1394
1395 fn get_coeff_b() -> Fq2 {
1396 super::super::fq::B_COEFF_FQ2
1397 }
1402
1403 fn perform_pairing(&self, other: &G1Affine) -> Fq12 {
1404 super::super::Bn256::pairing(*other, *self)
1405 }
1406 }
1407
1408 impl G2 {
1409 fn empirical_recommended_wnaf_for_scalar(scalar: FrRepr) -> usize {
1410 let num_bits = scalar.num_bits() as usize;
1411
1412 if num_bits >= 103 {
1413 4
1414 } else if num_bits >= 37 {
1415 3
1416 } else {
1417 2
1418 }
1419 }
1420
1421 fn empirical_recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
1422 const RECOMMENDATIONS: [usize; 11] =
1423 [1, 3, 8, 20, 47, 126, 260, 826, 1501, 4555, 84071];
1424
1425 let mut ret = 4;
1426 for r in &RECOMMENDATIONS {
1427 if num_scalars > *r {
1428 ret += 1;
1429 } else {
1430 break;
1431 }
1432 }
1433
1434 ret
1435 }
1436 }
1437
1438 #[derive(Clone, Debug)]
1439 pub struct G2Prepared {
1440 pub(crate) coeffs: Vec<(Fq2, Fq2, Fq2)>,
1441 pub(crate) infinity: bool,
1442 }
1443
1444 #[test]
1449 fn g2_generator() {
1450 use SqrtField;
1451
1452 let mut x = Fq2::zero();
1453 loop {
1454 let mut rhs = x;
1456 rhs.square();
1457 rhs.mul_assign(&x);
1458 rhs.add_assign(&G2Affine::get_coeff_b());
1459
1460 if let Some(y) = rhs.sqrt() {
1461 let mut negy = y;
1462 negy.negate();
1463
1464 let p = G2Affine {
1465 x: x,
1466 y: if y < negy { y } else { negy },
1467 };
1468
1469
1470 let g2 = p.into_projective();
1471 if !g2.is_zero() {
1472 let _g2 = G2Affine::from(g2);
1473 break;
1474 }
1475 }
1476
1477 x.add_assign(&Fq2::one());
1478 }
1479 }
1480
1481 #[test]
1482 fn test_generate_g2_in_subgroup() {
1483 use SqrtField;
1484
1485 let mut x = Fq2::zero();
1486 loop {
1487 let mut rhs = x;
1489 rhs.square();
1490 rhs.mul_assign(&x);
1491 rhs.add_assign(&G2Affine::get_coeff_b());
1492
1493 if let Some(y) = rhs.sqrt() {
1494 let mut negy = y;
1495 negy.negate();
1496
1497 let p = G2Affine {
1498 x: x,
1499 y: if y < negy { y } else { negy },
1500 };
1501
1502 let g2 = p.into_projective();
1503 let mut minus_one = Fr::one();
1504 minus_one.negate();
1505
1506 let mut expected_zero = p.mul(minus_one);
1507 expected_zero.add_assign(&g2);
1508
1509 if !expected_zero.is_zero() {
1510 let p = expected_zero.into_affine();
1511 let scaled_by_cofactor = p.scale_by_cofactor();
1512 if scaled_by_cofactor.is_zero() {
1513 let g2 = G2Affine::from(expected_zero);
1514 println!("Invalid subgroup point = {}", g2);
1515 return;
1516 }
1517 }
1518 }
1519
1520 x.add_assign(&Fq2::one());
1521 }
1522 }
1523
1524 #[cfg(test)]
1525 use rand::{SeedableRng, XorShiftRng};
1526
1527 #[test]
1528 fn g2_generator_on_curve() {
1529 use SqrtField;
1530
1531 let gen = G2Affine::get_generator();
1532 let x = gen.x;
1533 let mut rhs = x;
1535 rhs.square();
1536 rhs.mul_assign(&x);
1537 rhs.add_assign(&G2Affine::get_coeff_b());
1538
1539 if let Some(y) = rhs.sqrt() {
1540 let mut negy = y;
1541 negy.negate();
1542
1543 let p = G2Affine {
1544 x: x,
1545 y: if y < negy { y } else { negy },
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 fn g2_curve_tests() {
1557 crate::tests::curve::curve_tests::<G2>();
1558 crate::tests::curve::random_transformation_tests::<G2>();
1559 }
1560
1561 #[test]
1562
1563 fn test_b_coeff() {
1564 let b2 = G2Affine::get_coeff_b();
1565 print!("{}\n\n", b2);
1566 }
1567
1568 #[test]
1569
1570 fn test_base_point_addition_and_doubling() {
1571 let mut two = G2::one();
1572 two.add_assign(&G2::one());
1573
1574 let one = G2::one();
1575
1576 let mut three21 = two;
1577 three21.add_assign(&one);
1578
1579 let mut three12 = one;
1580 three12.add_assign(&two);
1581
1582 assert_eq!(three12, three21);
1583 }
1584
1585 #[test]
1586 fn test_addition_and_doubling() {
1587
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
1675 #[test]
1676 fn random_negation_tests() {
1677 let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
1678
1679 for _ in 0..1000 {
1680 let mut r = G2::one();
1684 let k = Fr::rand(&mut rng);
1685 r.mul_assign(k);
1686
1687 let s = Fr::rand(&mut rng);
1688 let mut sneg = s;
1689 sneg.negate();
1690
1691 let mut t1 = r;
1692 t1.mul_assign(s);
1693
1694 let mut t2 = r;
1695 t2.mul_assign(sneg);
1696
1697 let mut t3 = t1;
1698 t3.add_assign(&t2);
1699 assert!(t3.is_zero());
1700
1701 let mut t4 = t1;
1702 t4.add_assign_mixed(&t2.into_affine());
1703 assert!(t4.is_zero());
1704
1705 t1.negate();
1706 assert_eq!(t1, t2);
1707 }
1708 }
1709
1710 #[test]
1711 fn mul_by_order_tests() {
1712 let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
1713
1714 for _ in 0..1000 {
1715 let mut r = G2::one();
1718 let k = Fr::rand(&mut rng);
1719 r.mul_assign(k);
1720
1721 let order = Fr::char();
1722
1723 let mut q = G2::one();
1724 q.mul_assign(order);
1725 assert!(q.is_zero());
1726
1727 r.mul_assign(order);
1728 assert!(r.is_zero());
1729
1730 let mut t = G2::rand(&mut rng);
1731 t.mul_assign(order);
1732 assert!(t.is_zero());
1733 }
1734 }
1735
1736}
1737
1738pub use self::g1::*;
1739pub use self::g2::*;