This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
forked from filecoin-project/blstrs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
g1.rs
1414 lines (1185 loc) · 40.8 KB
/
g1.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! An implementation of the $\mathbb{G}_1$ group of BLS12-381.
use core::{
borrow::Borrow,
fmt,
iter::Sum,
ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign},
};
use std::io::Read;
use blst::*;
use group::{
prime::{PrimeCurve, PrimeCurveAffine, PrimeGroup},
Curve, Group, GroupEncoding, UncompressedEncoding, WnafGroup,
};
use rand_core::RngCore;
use subtle::{Choice, ConditionallySelectable, CtOption};
use crate::{fp::Fp, Bls12, Engine, G2Affine, Gt, PairingCurveAffine, Scalar};
/// This is an element of $\mathbb{G}_1$ represented in the affine coordinate space.
/// It is ideal to keep elements in this representation to reduce memory usage and
/// improve performance through the use of mixed curve model arithmetic.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct G1Affine(pub(crate) blst_p1_affine);
const COMPRESSED_SIZE: usize = 48;
const UNCOMPRESSED_SIZE: usize = 96;
impl fmt::Debug for G1Affine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let is_ident: bool = self.is_identity().into();
f.debug_struct("G1Affine")
.field("x", &self.x())
.field("y", &self.y())
.field("infinity", &is_ident)
.finish()
}
}
impl fmt::Display for G1Affine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_identity().into() {
write!(f, "G1Affine(Infinity)")
} else {
write!(f, "G1Affine(x={}, y={})", self.x(), self.y())
}
}
}
impl Default for G1Affine {
fn default() -> G1Affine {
G1Affine::identity()
}
}
impl From<&G1Projective> for G1Affine {
fn from(p: &G1Projective) -> G1Affine {
let mut out = blst_p1_affine::default();
unsafe { blst_p1_to_affine(&mut out, &p.0) };
G1Affine(out)
}
}
impl From<G1Projective> for G1Affine {
fn from(p: G1Projective) -> G1Affine {
G1Affine::from(&p)
}
}
impl AsRef<blst_p1_affine> for G1Affine {
fn as_ref(&self) -> &blst_p1_affine {
&self.0
}
}
impl AsMut<blst_p1_affine> for G1Affine {
fn as_mut(&mut self) -> &mut blst_p1_affine {
&mut self.0
}
}
impl Eq for G1Affine {}
impl PartialEq for G1Affine {
#[inline]
fn eq(&self, other: &Self) -> bool {
unsafe { blst_p1_affine_is_equal(&self.0, &other.0) }
}
}
impl Neg for &G1Projective {
type Output = G1Projective;
#[inline]
fn neg(self) -> G1Projective {
-*self
}
}
impl Neg for G1Projective {
type Output = G1Projective;
#[inline]
fn neg(mut self) -> G1Projective {
unsafe { blst_p1_cneg(&mut self.0, true) };
self
}
}
impl Neg for &G1Affine {
type Output = G1Affine;
#[inline]
fn neg(self) -> G1Affine {
-*self
}
}
impl Neg for G1Affine {
type Output = G1Affine;
#[inline]
fn neg(mut self) -> G1Affine {
// Missing for affine in blst
if (!self.is_identity()).into() {
unsafe {
blst_fp_cneg(&mut self.0.y, &self.0.y, true);
}
}
self
}
}
impl Add<&G1Projective> for &G1Projective {
type Output = G1Projective;
#[inline]
fn add(self, rhs: &G1Projective) -> G1Projective {
let mut out = blst_p1::default();
unsafe { blst_p1_add_or_double(&mut out, &self.0, &rhs.0) };
G1Projective(out)
}
}
impl Add<&G1Projective> for &G1Affine {
type Output = G1Projective;
#[inline]
fn add(self, rhs: &G1Projective) -> G1Projective {
rhs.add_mixed(self)
}
}
impl Add<&G1Affine> for &G1Projective {
type Output = G1Projective;
#[inline]
fn add(self, rhs: &G1Affine) -> G1Projective {
self.add_mixed(rhs)
}
}
impl Sub<&G1Projective> for &G1Projective {
type Output = G1Projective;
#[inline]
fn sub(self, rhs: &G1Projective) -> G1Projective {
self + (-rhs)
}
}
impl Sub<&G1Projective> for &G1Affine {
type Output = G1Projective;
#[inline]
fn sub(self, rhs: &G1Projective) -> G1Projective {
self + (-rhs)
}
}
impl Sub<&G1Affine> for &G1Projective {
type Output = G1Projective;
#[inline]
fn sub(self, rhs: &G1Affine) -> G1Projective {
self + (-rhs)
}
}
impl AddAssign<&G1Projective> for G1Projective {
#[inline]
fn add_assign(&mut self, rhs: &G1Projective) {
unsafe { blst_p1_add_or_double(&mut self.0, &self.0, &rhs.0) };
}
}
impl SubAssign<&G1Projective> for G1Projective {
#[inline]
fn sub_assign(&mut self, rhs: &G1Projective) {
*self += &-rhs;
}
}
impl AddAssign<&G1Affine> for G1Projective {
#[inline]
fn add_assign(&mut self, rhs: &G1Affine) {
unsafe { blst_p1_add_or_double_affine(&mut self.0, &self.0, &rhs.0) };
}
}
impl SubAssign<&G1Affine> for G1Projective {
#[inline]
fn sub_assign(&mut self, rhs: &G1Affine) {
*self += &-rhs;
}
}
impl Mul<&Scalar> for &G1Projective {
type Output = G1Projective;
fn mul(self, scalar: &Scalar) -> Self::Output {
self.multiply(scalar)
}
}
impl Mul<&Scalar> for &G1Affine {
type Output = G1Projective;
fn mul(self, scalar: &Scalar) -> Self::Output {
G1Projective::from(self).multiply(scalar)
}
}
impl MulAssign<&Scalar> for G1Projective {
#[inline]
fn mul_assign(&mut self, rhs: &Scalar) {
*self = *self * rhs;
}
}
impl MulAssign<&Scalar> for G1Affine {
#[inline]
fn mul_assign(&mut self, rhs: &Scalar) {
*self = (*self * rhs).into();
}
}
impl_add_sub!(G1Projective);
impl_add_sub!(G1Projective, G1Affine);
impl_add_sub!(G1Affine, G1Projective, G1Projective);
impl_add_sub_assign!(G1Projective);
impl_add_sub_assign!(G1Projective, G1Affine);
impl_mul!(G1Projective, Scalar);
impl_mul!(G1Affine, Scalar, G1Projective);
impl_mul_assign!(G1Projective, Scalar);
impl_mul_assign!(G1Affine, Scalar);
impl<T> Sum<T> for G1Projective
where
T: Borrow<G1Projective>,
{
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = T>,
{
iter.fold(Self::identity(), |acc, item| acc + item.borrow())
}
}
impl ConditionallySelectable for G1Affine {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
G1Affine(blst_p1_affine {
x: Fp::conditional_select(&a.x(), &b.x(), choice).0,
y: Fp::conditional_select(&a.y(), &b.y(), choice).0,
})
}
}
impl ConditionallySelectable for G1Projective {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
G1Projective(blst_p1 {
x: Fp::conditional_select(&a.x(), &b.x(), choice).0,
y: Fp::conditional_select(&a.y(), &b.y(), choice).0,
z: Fp::conditional_select(&a.z(), &b.z(), choice).0,
})
}
}
impl G1Affine {
/// Serializes this element into compressed form.
pub fn to_compressed(&self) -> [u8; COMPRESSED_SIZE] {
let mut out = [0u8; COMPRESSED_SIZE];
unsafe {
blst_p1_affine_compress(out.as_mut_ptr(), &self.0);
}
out
}
/// Serializes this element into uncompressed form.
pub fn to_uncompressed(&self) -> [u8; UNCOMPRESSED_SIZE] {
let mut out = [0u8; UNCOMPRESSED_SIZE];
unsafe {
blst_p1_affine_serialize(out.as_mut_ptr(), &self.0);
}
out
}
/// Attempts to deserialize an uncompressed element.
pub fn from_uncompressed(bytes: &[u8; UNCOMPRESSED_SIZE]) -> CtOption<Self> {
G1Affine::from_uncompressed_unchecked(bytes)
.and_then(|p| CtOption::new(p, p.is_on_curve() & p.is_torsion_free()))
}
/// Attempts to deserialize an uncompressed element, not checking if the
/// element is on the curve and not checking if it is in the correct subgroup.
///
/// **This is dangerous to call unless you trust the bytes you are reading; otherwise,
/// API invariants may be broken.** Please consider using `from_uncompressed()` instead.
pub fn from_uncompressed_unchecked(bytes: &[u8; UNCOMPRESSED_SIZE]) -> CtOption<Self> {
let mut raw = blst_p1_affine::default();
let success =
unsafe { blst_p1_deserialize(&mut raw, bytes.as_ptr()) == BLST_ERROR::BLST_SUCCESS };
CtOption::new(G1Affine(raw), Choice::from(success as u8))
}
/// Attempts to deserialize a compressed element.
pub fn from_compressed(bytes: &[u8; COMPRESSED_SIZE]) -> CtOption<Self> {
G1Affine::from_compressed_unchecked(bytes)
.and_then(|p| CtOption::new(p, p.is_on_curve() & p.is_torsion_free()))
}
/// Attempts to deserialize an uncompressed element, not checking if the
/// element is in the correct subgroup.
///
/// **This is dangerous to call unless you trust the bytes you are reading; otherwise,
/// API invariants may be broken.** Please consider using `from_compressed()` instead.
pub fn from_compressed_unchecked(bytes: &[u8; COMPRESSED_SIZE]) -> CtOption<Self> {
let mut raw = blst_p1_affine::default();
let success =
unsafe { blst_p1_uncompress(&mut raw, bytes.as_ptr()) == BLST_ERROR::BLST_SUCCESS };
CtOption::new(G1Affine(raw), Choice::from(success as u8))
}
/// Returns true if this point is free of an $h$-torsion component, and so it
/// exists within the $q$-order subgroup $\mathbb{G}_1$. This should always return true
/// unless an "unchecked" API was used.
pub fn is_torsion_free(&self) -> Choice {
unsafe { Choice::from(blst_p1_affine_in_g1(&self.0) as u8) }
}
/// Returns true if this point is on the curve. This should always return
/// true unless an "unchecked" API was used.
pub fn is_on_curve(&self) -> Choice {
unsafe { Choice::from(blst_p1_affine_on_curve(&self.0) as u8) }
}
pub fn from_raw_unchecked(x: Fp, y: Fp, _infinity: bool) -> Self {
// FIXME: what about infinity?
let raw = blst_p1_affine { x: x.0, y: y.0 };
G1Affine(raw)
}
/// Returns the x coordinate.
pub fn x(&self) -> Fp {
Fp(self.0.x)
}
/// Returns the y coordinate.
pub fn y(&self) -> Fp {
Fp(self.0.y)
}
pub const fn uncompressed_size() -> usize {
UNCOMPRESSED_SIZE
}
pub const fn compressed_size() -> usize {
COMPRESSED_SIZE
}
#[inline]
pub fn raw_fmt_size() -> usize {
let s = G1Affine::uncompressed_size();
s + 1
}
pub fn write_raw<W: std::io::Write>(&self, mut writer: W) -> Result<usize, std::io::Error> {
if self.is_identity().into() {
writer.write_all(&[1])?;
} else {
writer.write_all(&[0])?;
}
let raw = self.to_uncompressed();
writer.write_all(&raw)?;
Ok(Self::raw_fmt_size())
}
pub fn read_raw<R: Read>(mut reader: R) -> Result<Self, std::io::Error> {
let mut buf = [0u8];
reader.read_exact(&mut buf)?;
let _infinity = buf[0] == 1;
let mut buf = [0u8; UNCOMPRESSED_SIZE];
reader.read_exact(&mut buf)?;
let res = Self::from_uncompressed_unchecked(&buf);
if res.is_some().into() {
Ok(res.unwrap())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"not on curve",
))
}
}
pub fn read_raw_checked<R: Read>(mut reader: R) -> Result<Self, std::io::Error> {
let mut buf = [0u8];
reader.read_exact(&mut buf)?;
let _infinity = buf[0] == 1;
let mut buf = [0u8; UNCOMPRESSED_SIZE];
reader.read_exact(&mut buf)?;
let res = Self::from_uncompressed(&buf);
if res.is_some().into() {
Ok(res.unwrap())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"not on curve",
))
}
}
}
/// This is an element of $\mathbb{G}_1$ represented in the projective coordinate space.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct G1Projective(pub(crate) blst_p1);
impl fmt::Debug for G1Projective {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("G1Projective")
.field("x", &self.x())
.field("y", &self.y())
.field("z", &self.z())
.finish()
}
}
impl fmt::Display for G1Projective {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", G1Affine::from(self))
}
}
impl AsRef<blst_p1> for G1Projective {
fn as_ref(&self) -> &blst_p1 {
&self.0
}
}
impl AsMut<blst_p1> for G1Projective {
fn as_mut(&mut self) -> &mut blst_p1 {
&mut self.0
}
}
impl From<&G1Affine> for G1Projective {
fn from(p: &G1Affine) -> G1Projective {
let mut out = blst_p1::default();
unsafe { blst_p1_from_affine(&mut out, &p.0) };
G1Projective(out)
}
}
impl From<G1Affine> for G1Projective {
fn from(p: G1Affine) -> G1Projective {
G1Projective::from(&p)
}
}
impl Eq for G1Projective {}
impl PartialEq for G1Projective {
#[inline]
fn eq(&self, other: &Self) -> bool {
let self_is_zero: bool = self.is_identity().into();
let other_is_zero: bool = other.is_identity().into();
(self_is_zero && other_is_zero)
|| (!self_is_zero && !other_is_zero && unsafe { blst_p1_is_equal(&self.0, &other.0) })
}
}
impl G1Projective {
/// Serializes this element into compressed form.
pub fn to_compressed(&self) -> [u8; COMPRESSED_SIZE] {
let mut out = [0u8; COMPRESSED_SIZE];
unsafe {
blst_p1_compress(out.as_mut_ptr(), &self.0);
}
out
}
/// Serializes this element into uncompressed form.
pub fn to_uncompressed(&self) -> [u8; UNCOMPRESSED_SIZE] {
let mut out = [0u8; UNCOMPRESSED_SIZE];
unsafe {
blst_p1_serialize(out.as_mut_ptr(), &self.0);
}
out
}
/// Attempts to deserialize an uncompressed element.
pub fn from_uncompressed(bytes: &[u8; UNCOMPRESSED_SIZE]) -> CtOption<Self> {
G1Affine::from_uncompressed(bytes).map(Into::into)
}
/// Attempts to deserialize an uncompressed element, not checking if the
/// element is on the curve and not checking if it is in the correct subgroup.
///
/// **This is dangerous to call unless you trust the bytes you are reading; otherwise,
/// API invariants may be broken.** Please consider using `from_uncompressed()` instead.
pub fn from_uncompressed_unchecked(bytes: &[u8; UNCOMPRESSED_SIZE]) -> CtOption<Self> {
G1Affine::from_uncompressed_unchecked(bytes).map(Into::into)
}
/// Attempts to deserialize a compressed element.
pub fn from_compressed(bytes: &[u8; COMPRESSED_SIZE]) -> CtOption<Self> {
G1Affine::from_compressed(bytes).map(Into::into)
}
/// Attempts to deserialize an uncompressed element, not checking if the
/// element is in the correct subgroup.
///
/// **This is dangerous to call unless you trust the bytes you are reading; otherwise,
/// API invariants may be broken.** Please consider using `from_compressed()` instead.
pub fn from_compressed_unchecked(bytes: &[u8; COMPRESSED_SIZE]) -> CtOption<Self> {
G1Affine::from_compressed_unchecked(bytes).map(Into::into)
}
/// Adds this point to another point in the affine model.
fn add_mixed(&self, rhs: &G1Affine) -> G1Projective {
let mut out = blst_p1::default();
unsafe { blst_p1_add_or_double_affine(&mut out, &self.0, &rhs.0) };
G1Projective(out)
}
/// Returns true if this point is on the curve. This should always return
/// true unless an "unchecked" API was used.
pub fn is_on_curve(&self) -> Choice {
let is_on_curve = unsafe { Choice::from(blst_p1_on_curve(&self.0) as u8) };
is_on_curve | self.is_identity()
}
fn multiply(&self, scalar: &Scalar) -> G1Projective {
let mut out = blst_p1::default();
// Scalar is 255 bits wide.
const NBITS: usize = 255;
unsafe { blst_p1_mult(&mut out, &self.0, scalar.to_bytes_le().as_ptr(), NBITS) };
G1Projective(out)
}
pub fn from_raw_unchecked(x: Fp, y: Fp, z: Fp) -> Self {
let raw = blst_p1 {
x: x.0,
y: y.0,
z: z.0,
};
G1Projective(raw)
}
/// Returns the x coordinate.
pub fn x(&self) -> Fp {
Fp(self.0.x)
}
/// Returns the y coordinate.
pub fn y(&self) -> Fp {
Fp(self.0.y)
}
/// Returns the z coordinate.
pub fn z(&self) -> Fp {
Fp(self.0.z)
}
/// Hash to curve algorithm.
pub fn hash_to_curve(msg: &[u8], dst: &[u8], aug: &[u8]) -> Self {
let mut res = Self::identity();
unsafe {
blst_hash_to_g1(
&mut res.0,
msg.as_ptr(),
msg.len(),
dst.as_ptr(),
dst.len(),
aug.as_ptr(),
aug.len(),
);
}
res
}
pub fn multi_exp(points: &[G1Affine], scalars: &[Scalar]) -> Self {
let points_ptrs: Vec<*const blst_p1_affine> = points.iter().map(|g| &g.0 as *const blst_p1_affine).collect();
let scalars_bytes: Vec<[u8; 32]> = scalars.iter().map(|s| s.to_bytes_be()).collect();
let scalars_bytes_ptrs: Vec<*const u8> = scalars_bytes.iter().map(|s| s.as_ptr()).collect();
let scratch_size = unsafe { blst_p1s_mult_pippenger_scratch_sizeof(points.len()) };
let mut scratch: Vec<limb_t> = vec![0; scratch_size];
let mut res = G1Projective(blst_p1::default());
unsafe { blst_p1s_mult_pippenger(&mut res.0 as *mut blst_p1, points_ptrs.as_ptr(), points.len(), scalars_bytes_ptrs.as_ptr(), 255, scratch.as_mut_ptr()) };
res
}
}
impl Group for G1Projective {
type Scalar = Scalar;
fn random(mut rng: impl RngCore) -> Self {
let mut out = blst_p1::default();
let mut msg = [0u8; 64];
rng.fill_bytes(&mut msg);
const DST: [u8; 16] = [0; 16];
const AUG: [u8; 16] = [0; 16];
unsafe {
blst_encode_to_g1(
&mut out,
msg.as_ptr(),
msg.len(),
DST.as_ptr(),
DST.len(),
AUG.as_ptr(),
AUG.len(),
)
};
G1Projective(out)
}
fn identity() -> Self {
G1Projective(blst_p1::default())
}
fn generator() -> Self {
G1Projective(unsafe { *blst_p1_generator() })
}
fn is_identity(&self) -> Choice {
unsafe { Choice::from(blst_p1_is_inf(&self.0) as u8) }
}
fn double(&self) -> Self {
let mut double = blst_p1::default();
unsafe { blst_p1_double(&mut double, &self.0) };
G1Projective(double)
}
}
impl WnafGroup for G1Projective {
fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
const RECOMMENDATIONS: [usize; 12] =
[1, 3, 7, 20, 43, 120, 273, 563, 1630, 3128, 7933, 62569];
let mut ret = 4;
for r in &RECOMMENDATIONS {
if num_scalars > *r {
ret += 1;
} else {
break;
}
}
ret
}
}
impl PrimeGroup for G1Projective {}
impl Curve for G1Projective {
type AffineRepr = G1Affine;
fn to_affine(&self) -> Self::AffineRepr {
self.into()
}
}
impl PrimeCurve for G1Projective {
type Affine = G1Affine;
}
impl PrimeCurveAffine for G1Affine {
type Scalar = Scalar;
type Curve = G1Projective;
fn identity() -> Self {
G1Affine(blst_p1_affine::default())
}
fn generator() -> Self {
G1Affine(unsafe { *blst_p1_affine_generator() })
}
fn is_identity(&self) -> Choice {
unsafe { Choice::from(blst_p1_affine_is_inf(&self.0) as u8) }
}
fn to_curve(&self) -> Self::Curve {
self.into()
}
}
impl GroupEncoding for G1Projective {
type Repr = G1Compressed;
fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
Self::from_compressed(&bytes.0)
}
fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
Self::from_compressed_unchecked(&bytes.0)
}
fn to_bytes(&self) -> Self::Repr {
G1Compressed(self.to_compressed())
}
}
impl GroupEncoding for G1Affine {
type Repr = G1Compressed;
fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
Self::from_compressed(&bytes.0)
}
fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
Self::from_compressed_unchecked(&bytes.0)
}
fn to_bytes(&self) -> Self::Repr {
G1Compressed(self.to_compressed())
}
}
impl UncompressedEncoding for G1Affine {
type Uncompressed = G1Uncompressed;
fn from_uncompressed(bytes: &Self::Uncompressed) -> CtOption<Self> {
Self::from_uncompressed(&bytes.0)
}
fn from_uncompressed_unchecked(bytes: &Self::Uncompressed) -> CtOption<Self> {
Self::from_uncompressed_unchecked(&bytes.0)
}
fn to_uncompressed(&self) -> Self::Uncompressed {
G1Uncompressed(self.to_uncompressed())
}
}
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct G1Uncompressed([u8; UNCOMPRESSED_SIZE]);
encoded_point_delegations!(G1Uncompressed);
impl Default for G1Uncompressed {
fn default() -> Self {
G1Uncompressed([0u8; UNCOMPRESSED_SIZE])
}
}
impl fmt::Debug for G1Uncompressed {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
self.0[..].fmt(formatter)
}
}
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct G1Compressed([u8; COMPRESSED_SIZE]);
encoded_point_delegations!(G1Compressed);
impl Default for G1Compressed {
fn default() -> Self {
G1Compressed([0u8; COMPRESSED_SIZE])
}
}
impl fmt::Debug for G1Compressed {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
self.0[..].fmt(formatter)
}
}
impl PairingCurveAffine for G1Affine {
type Pair = G2Affine;
type PairingResult = Gt;
fn pairing_with(&self, other: &Self::Pair) -> Self::PairingResult {
<Bls12 as Engine>::pairing(self, other)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::eq_op)]
use super::*;
use ff::Field;
use rand_core::SeedableRng;
use rand_xorshift::XorShiftRng;
#[test]
fn curve_tests() {
let mut rng = XorShiftRng::from_seed([
0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06,
0xbc, 0xe5,
]);
{
let z = G1Projective::identity();
assert_eq!(z.is_identity().unwrap_u8(), 1);
}
// Negation edge case with zero.
{
let mut z = G1Projective::identity();
z = z.neg();
assert_eq!(z.is_identity().unwrap_u8(), 1);
}
// Doubling edge case with zero.
{
let mut z = G1Projective::identity();
z = z.double();
assert_eq!(z.is_identity().unwrap_u8(), 1);
}
// Addition edge cases with zero
{
let mut r = G1Projective::random(&mut rng);
let rcopy = r;
r += &G1Projective::identity();
assert_eq!(r, rcopy);
r += &G1Affine::identity();
assert_eq!(r, rcopy);
let mut z = G1Projective::identity();
z += &G1Projective::identity();
assert_eq!(z.is_identity().unwrap_u8(), 1);
z += &G1Affine::identity();
assert_eq!(z.is_identity().unwrap_u8(), 1);
let mut z2 = z;
z2 += &r;
z += &G1Affine::from(r);
assert_eq!(z, z2);
assert_eq!(z, r);
}
// Transformations
{
let a = G1Projective::random(&mut rng);
let b: G1Projective = G1Affine::from(a).into();
let c = G1Projective::from(G1Affine::from(G1Projective::from(G1Affine::from(a))));
assert_eq!(a, b);
assert_eq!(b, c);
}
}
#[test]
fn test_is_on_curve() {
assert_eq!(G1Projective::identity().is_on_curve().unwrap_u8(), 1);
assert_eq!(G1Projective::generator().is_on_curve().unwrap_u8(), 1);
assert_eq!(G1Affine::identity().is_on_curve().unwrap_u8(), 1);
assert_eq!(G1Affine::generator().is_on_curve().unwrap_u8(), 1);
let z = Fp::from_raw_unchecked([
0xba7afa1f9a6fe250,
0xfa0f5b595eafe731,
0x3bdc477694c306e7,
0x2149be4b3949fa24,
0x64aa6e0649b2078c,
0x12b108ac33643c3e,
]);
let gen = G1Affine::generator();
let z2 = z.square();
let mut test = G1Projective::from_raw_unchecked(gen.x() * z2, gen.y() * (z2 * z), z);
assert_eq!(test.is_on_curve().unwrap_u8(), 1);
test.0.x = z.0;
assert_eq!(test.is_on_curve().unwrap_u8(), 0);
}
#[test]
fn test_affine_point_equality() {
let a = G1Affine::generator();
let b = G1Affine::identity();
assert_eq!(a, a);
assert_eq!(b, b);
assert_ne!(a, b);
assert_ne!(b, a);
}
#[test]
fn test_projective_point_equality() {
let a = G1Projective::generator();
let b = G1Projective::identity();
assert_eq!(a, a);
assert_eq!(b, b);
assert_ne!(a, b);
assert_ne!(b, a);
let z = Fp::from_raw_unchecked([
0xba7afa1f9a6fe250,
0xfa0f5b595eafe731,
0x3bdc477694c306e7,
0x2149be4b3949fa24,
0x64aa6e0649b2078c,
0x12b108ac33643c3e,
]);
let z2 = z.square();
let mut c = G1Projective::from_raw_unchecked(a.x() * z2, a.y() * (z2 * z), z);
assert_eq!(c.is_on_curve().unwrap_u8(), 1);
assert_eq!(a, c);
assert_eq!(c, a);
assert_ne!(b, c);
assert_ne!(c, b);
c.0.y = (-c.y()).0;
assert_eq!(c.is_on_curve().unwrap_u8(), 1);
assert_ne!(a, c);
assert_ne!(b, c);
assert_ne!(c, a);
assert_ne!(c, b);
c.0.y = (-c.y()).0;
c.0.x = z.0;
assert_eq!(c.is_on_curve().unwrap_u8(), 0);
assert_ne!(a, b);
assert_ne!(a, c);
assert_ne!(b, c);
}
#[test]
fn test_projective_to_affine() {
let a = G1Projective::generator();
let b = G1Projective::identity();
assert_eq!(G1Affine::from(a).is_on_curve().unwrap_u8(), 1);
assert_eq!(G1Affine::from(a).is_identity().unwrap_u8(), 0);
assert_eq!(G1Affine::from(b).is_on_curve().unwrap_u8(), 1);
assert_eq!(G1Affine::from(b).is_identity().unwrap_u8(), 1);
let z = Fp::from_raw_unchecked([
0xba7afa1f9a6fe250,
0xfa0f5b595eafe731,
0x3bdc477694c306e7,
0x2149be4b3949fa24,