sm9_core 0.4.2

SM9, identity-based cryptography
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
//! # sm9_core
//!
//! A pairing cryptography library written in pure Rust.
//! It makes use of the Barreto-Naehrig (BN) curve construction from "SM9 identity-based cryptographic algorithms" to provide two cyclic groups G<sub>1</sub> and G<sub>2</sub> , with a R-ate pairing.
//! - no_std
//! - no unsafe{}
//!
#![no_std]
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

#[cfg(test)]
#[macro_use]
extern crate std;

extern crate alloc;
extern crate hex_literal;
extern crate rand;

#[macro_use]
mod arith;
mod fields;
mod groups;
mod pairings;
mod u256;
mod u512;

use alloc::fmt::Debug;
use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use rand::Rng;

pub use crate::pairings::G2Prepared;
use crate::{
    fields::FieldElement,
    groups::{G1Params, G2Params, GroupElement, GroupParams},
    u256::U256,
};
pub use core::str::FromStr;
pub use hex_literal::hex;
pub use num_traits::{One, Zero};

#[derive(Debug)]
pub enum FieldError {
    InvalidSliceLength,
    InvalidU512Encoding,
    NotMember,
    InvalidDecimalString,
}

#[derive(Debug)]
pub enum CurveError {
    InvalidEncoding,
    NotMember,
    Field(FieldError),
    ToAffineConversion,
}

pub use crate::groups::Error as GroupError;

impl From<FieldError> for CurveError {
    fn from(fe: FieldError) -> Self {
        CurveError::Field(fe)
    }
}

/// Represents an element of the finite field F<sub>r</sub>
// where r = 0xB640000002A3A6F1D603AB4FF58EC74449F2934B18EA8BEEE56EE19CD69ECF25
// Elements of Fr are always in Montgomery form; i.e., Fr(a) = aR mod r, with R = 2^256.
/// # Examples
///
/// ```rust
/// use sm9_core::*;
/// use hex_literal::hex;
///
/// let ks = Fr::from_slice(&hex!("000130E78459D78545CB54C587E02CF480CE0B66340F319F348A1D5B1F2DC5F4")).unwrap();
/// let r = Fr::from_slice(&hex!("00033C86 16B06704 813203DF D0096502 2ED15975 C662337A ED648835 DC4B1CBE")).unwrap();
/// let pub_s = G2::one() * ks;
/// let g = pairing(G1::one(), pub_s).pow(r);
/// let r1 = g.to_slice();
/// println!("{:#?}", g);
/// let r0 = hex!(
/// "81377B8F DBC2839B 4FA2D0E0 F8AA6853 BBBE9E9C 4099608F 8612C607 8ACD7563"
/// "815AEBA2 17AD502D A0F48704 CC73CABB 3C06209B D87142E1 4CBD99E8 BCA1680F"
/// "30DADC5C D9E207AE E32209F6 C3CA3EC0 D800A1A4 2D33C731 53DED47C 70A39D2E"
/// "8EAF5D17 9A1836B3 59A9D1D9 BFC19F2E FCDB8293 28620962 BD3FDF15 F2567F58"
/// "A543D256 09AE9439 20679194 ED30328B B33FD156 60BDE485 C6B79A7B 32B01398"
/// "3F012DB0 4BA59FE8 8DB88932 1CC2373D 4C0C35E8 4F7AB1FF 33679BCA 575D6765"
/// "4F8624EB 435B838C CA77B2D0 347E65D5 E4696441 2A096F41 50D8C5ED E5440DDF"
/// "0656FCB6 63D24731 E8029218 8A2471B8 B68AA993 89926849 9D23C897 55A1A897"
/// "44643CEA D40F0965 F28E1CD2 895C3D11 8E4F65C9 A0E3E741 B6DD52C0 EE2D25F5"
/// "898D6084 8026B7EF B8FCC1B2 442ECF07 95F8A81C EE99A624 8F294C82 C90D26BD"
/// "6A814AAF 475F128A EF43A128 E37F8015 4AE6CB92 CAD7D150 1BAE30F7 50B3A9BD"
/// "1F96B08E 97997363 91131470 5BFB9A9D BB97F755 53EC90FB B2DDAE53 C8F68E42"
/// );
/// assert_eq!(r0, r1);
/// // test  fast_pairing
/// let g1 = fast_pairing(G1::one(), pub_s).pow(r);
/// let r1 = g1.to_slice();
/// assert_eq!(r0, r1);
/// ```

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Fr(pub(crate) fields::Fr);

impl Fr {
    /// Attempts to convert a big-endian byte slice
    /// into an element of `Fr`, slice's length must be in [1, 64]
    pub fn from_slice(hex: &[u8]) -> Option<Self> {
        let len = hex.len();
        match len {
            1..=31 => {
                let mut t = [0u8; 32];
                t[32 - len..].copy_from_slice(hex);
                fields::Fr::from_slice(t.as_ref()).map(Fr)
            }
            32 => U256::from_slice(hex).ok().map(Fr::new_mul_factor),
            33..=64 => {
                let mut t = [0u8; 64];
                t[64 - len..].copy_from_slice(hex);
                Some(Fr(fields::Fr::interpret(&t)))
            }
            _ => None,
        }
    }
    /// for H1() and H2(), Attempts to convert a HASH result (40 bytes) to a Fr element
    pub fn from_hash(hex: &[u8]) -> Option<Self> {
        fields::Fr::from_hash(hex).map(Fr)
    }
    /// Returns zero, the additive identity.
    pub fn zero() -> Self {
        Fr(fields::Fr::zero())
    }
    /// Returns one, the multiplicative identity.
    pub fn one() -> Self {
        Fr(fields::Fr::one())
    }
    /// Exponentiates `self` by `exp`, where `exp` is a
    /// Fr element exponent.
    pub fn pow(&self, exp: Fr) -> Self {
        Fr(self.0.pow(exp.0))
    }
    /// Computes the multiplicative inverse of this element,
    /// failing if the element is zero.
    pub fn inverse(&self) -> Option<Self> {
        self.0.inverse().map(Fr)
    }
    /// Get a random element
    pub fn random<R: Rng>(rng: &mut R) -> Self {
        Fr(fields::Fr::random(rng))
    }
    /// Returns true if element is the additive identity.
    pub fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
    /// Attempts to convert a big-endian byte representation of
    /// a field element into an element of `Fr`, slice length must be 64
    pub fn interpret(buf: &[u8; 64]) -> Fr {
        Fr(fields::Fr::interpret(buf))
    }
    /// Converts an element of `Fr` into a byte representation in
    /// big-endian byte order.
    pub fn to_slice(self) -> [u8; 32] {
        self.0.to_slice()
    }
    /// Set the specified bit to 0 or 1
    pub fn set_bit(&mut self, bit: usize, to: bool) {
        self.0.set_bit(bit, to);
    }
    pub(crate) fn new_mul_factor(val: U256) -> Self {
        Fr(fields::Fr::new_mul_factor(val))
    }
    /// Adds this element to another element.
    fn add_inplace(&self, other: &Fr) -> Fr {
        Fr(self.0.add(&other.0))
    }
    /// Subtracts another element from this element.
    fn sub_inplace(&self, other: &Fr) -> Fr {
        Fr(self.0.sub(&other.0))
    }
    /// Multiplies this element by another element
    fn mul_inplace(&self, other: &Fr) -> Fr {
        Fr(self.0.mul(&other.0))
    }
    /// Negates this element.
    fn neg_inplace(&self) -> Fr {
        Fr(self.0.neg())
    }
}

impl FromStr for Fr {
    type Err = FieldError;
    /// Attempts to convert a decimal base string to a element of `Fr`
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fields::Fr::from_str(s)
            .map(Fr)
            .ok_or(FieldError::InvalidDecimalString)
    }
}

impl From<Fr> for [u8; 32] {
    fn from(value: Fr) -> Self {
        value.to_slice()
    }
}
impl<'a> From<&'a Fr> for [u8; 32] {
    fn from(value: &'a Fr) -> [u8; 32] {
        value.to_slice()
    }
}

impl TryFrom<&[u8]> for Fr {
    type Error = FieldError;

    fn try_from(hex: &[u8]) -> Result<Self, Self::Error> {
        Fr::from_slice(hex).ok_or(FieldError::InvalidSliceLength)
    }
}

impl_binops_additive!(Fr, Fr);
impl_binops_multiplicative!(Fr, Fr);
impl_binops_negative!(Fr);

/// Represents an element of the finite field F<sub>q</sub>
// where q = 0xB640000002A3A6F1D603AB4FF58EC74521F2934B1A7AEEDBE56F9B27E351457D
// Elements of Fq are always in Montgomery form; i.e., Fq(a) = aR mod q, with R = 2^256.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Fq(fields::Fq);

impl Fq {
    /// Attempts to convert a big-endian byte slice
    /// into an element of `Fq`, slice's length must be in [1, 64]
    pub fn from_slice(hex: &[u8]) -> Option<Self> {
        let len = hex.len();
        match len {
            1..=31 => {
                let mut t = [0u8; 32];
                t[32 - len..].copy_from_slice(hex);
                fields::Fq::from_slice(t.as_ref()).map(Fq)
            }
            32 => U256::from_slice(hex).ok().map(Fq::new_mul_factor),
            33..=64 => {
                let mut t = [0u8; 64];
                t[64 - len..].copy_from_slice(hex);
                Some(Fq(fields::Fq::interpret(&t)))
            }
            _ => None,
        }
    }
    /// Returns zero, the additive identity.
    pub fn zero() -> Self {
        Fq(fields::Fq::zero())
    }
    /// Returns one, the multiplicative identity.
    pub fn one() -> Self {
        Fq(fields::Fq::one())
    }
    /// Exponentiates `self` by `exp`, where `exp` is a
    /// Fq element exponent.
    pub fn pow(&self, exp: Fq) -> Self {
        Fq(self.0.pow(exp.0))
    }
    /// Converts an element of `Fq` into a byte representation in
    /// big-endian byte order.
    pub fn to_slice(self) -> [u8; 32] {
        self.0.into()
    }
    /// Computes the multiplicative inverse of this element,
    /// failing if the element is zero.
    pub fn inverse(&self) -> Option<Self> {
        self.0.inverse().map(Fq)
    }
    /// Returns true if element is the additive identity.
    pub fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
    /// Returns true if element is even.
    pub fn is_even(&self) -> bool {
        self.into_u256().is_even()
    }
    /// Attempts to convert a big-endian byte representation of
    /// a field element into an element of `Fq`, slice length must be 64
    pub fn interpret(buf: &[u8; 64]) -> Fq {
        Fq(fields::Fq::interpret(buf))
    }
    /// Converts an element into a slice of bytes in
    /// big-endian byte order.
    pub fn to_big_endian(self, slice: &mut [u8]) -> Result<(), FieldError> {
        self.into_u256()
            .to_big_endian(slice)
            .map_err(|_| FieldError::InvalidSliceLength)
    }
    /// Computes the square root of this element, if it exists.
    pub fn sqrt(&self) -> Option<Self> {
        self.0.sqrt().map(Fq)
    }
    /// Converts an element into a 256-bit big-endian integer(U256)
    /// Turn into canonical form by computing: (a.R) / R = a
    pub(crate) fn into_u256(self) -> U256 {
        (self.0).into()
    }
    pub(crate) fn new_mul_factor(val: U256) -> Self {
        Fq(fields::Fq::new_mul_factor(val))
    }
    fn add_inplace(&self, other: &Fq) -> Fq {
        Fq(self.0.add(&other.0))
    }
    fn sub_inplace(&self, other: &Fq) -> Fq {
        Fq(self.0.sub(&other.0))
    }
    fn mul_inplace(&self, other: &Fq) -> Fq {
        Fq(self.0.mul(&other.0))
    }
    fn neg_inplace(&self) -> Fq {
        Fq(self.0.neg())
    }
}

impl FromStr for Fq {
    type Err = FieldError;
    /// Attempts to convert a decimal base string to a element of `Fq`
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fields::Fq::from_str(s)
            .map(Fq)
            .ok_or(FieldError::InvalidDecimalString)
    }
}

impl From<Fq> for [u8; 32] {
    fn from(value: Fq) -> Self {
        value.to_slice()
    }
}

impl TryFrom<&[u8]> for Fq {
    type Error = FieldError;

    fn try_from(hex: &[u8]) -> Result<Self, Self::Error> {
        Fq::from_slice(hex).ok_or(FieldError::InvalidSliceLength)
    }
}

impl_binops_additive!(Fq, Fq);
impl_binops_multiplicative!(Fq, Fq);
impl_binops_negative!(Fq);

/// Represents an element of the finite field F<sub>q</sub>2
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Fq2(fields::Fq2);

impl Fq2 {
    pub fn one() -> Fq2 {
        Fq2(fields::Fq2::one())
    }
    pub fn zero() -> Fq2 {
        Fq2(fields::Fq2::zero())
    }
    /// Initalizes new Fq2(a + bi, a is real coeff, b is imaginary)
    pub fn new(a: Fq, b: Fq) -> Fq2 {
        Fq2(fields::Fq2::new(a.0, b.0))
    }
    /// Returns true if element is the additive identity.
    pub fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
    pub fn is_even(&self) -> bool {
        self.real().into_u256().is_even()
    }
    pub fn real(&self) -> Fq {
        Fq(*self.0.real())
    }
    pub fn imaginary(&self) -> Fq {
        Fq(*self.0.imaginary())
    }
    /// Computes the square root of this element, if it exists.
    pub fn sqrt(&self) -> Option<Self> {
        self.0.sqrt().map(Fq2)
    }
    /// Attempts to convert a big-endian byte representation of
    /// a field element into an element of `Fq2`,
    pub fn from_slice(hex: &[u8]) -> Option<Self> {
        fields::Fq2::from_slice(hex).map(Fq2).ok()
    }
    /// Converts an element into a slice of bytes in
    /// big-endian byte order.
    pub fn to_slice(self) -> [u8; 64] {
        self.0.to_slice()
    }
    fn add_inplace(&self, other: &Self) -> Self {
        Fq2(self.0 + other.0)
    }
    fn sub_inplace(&self, other: &Self) -> Self {
        Fq2(self.0 - other.0)
    }
    fn mul_inplace(&self, other: &Self) -> Self {
        Fq2(self.0 * other.0)
    }
    fn neg_inplace(&self) -> Self {
        Fq2(-self.0)
    }
}

impl From<Fq2> for [u8; 64] {
    fn from(value: Fq2) -> Self {
        value.to_slice()
    }
}

impl TryFrom<&[u8]> for Fq2 {
    type Error = FieldError;

    fn try_from(hex: &[u8]) -> Result<Self, Self::Error> {
        Fq2::from_slice(hex).ok_or(FieldError::InvalidSliceLength)
    }
}

impl_binops_additive!(Fq2, Fq2);
impl_binops_multiplicative!(Fq2, Fq2);
impl_binops_negative!(Fq2);

pub trait Group:
    Send
    + Sync
    + Copy
    + Clone
    + PartialEq
    + Eq
    + Sized
    + Add<Self, Output = Self>
    + Sub<Self, Output = Self>
    + Neg<Output = Self>
    + Mul<Fr, Output = Self>
{
    fn zero() -> Self;
    fn one() -> Self;
    fn is_zero(&self) -> bool;
    fn normalize(&mut self);
}

/// an additive cyclic group of prime order r

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct G1(pub groups::G1);

impl G1 {
    pub fn new(x: Fq, y: Fq, z: Fq) -> Self {
        G1(groups::G1::new(x.0, y.0, z.0))
    }

    pub fn x(&self) -> Fq {
        Fq(*self.0.x())
    }

    pub fn set_x(&mut self, x: Fq) {
        *self.0.x_mut() = x.0
    }

    pub fn y(&self) -> Fq {
        Fq(*self.0.y())
    }

    pub fn set_y(&mut self, y: Fq) {
        *self.0.y_mut() = y.0
    }

    pub fn z(&self) -> Fq {
        Fq(*self.0.z())
    }

    pub fn set_z(&mut self, z: Fq) {
        *self.0.z_mut() = z.0
    }

    pub fn b() -> Fq {
        Fq(G1Params::coeff_b())
    }
    /// Attempts to convert a compressed point to an element of G1
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General
    // Annex A  A.4.2
    pub fn from_compressed(bytes: &[u8]) -> Result<Self, CurveError> {
        if bytes.len() != 33 {
            return Err(CurveError::InvalidEncoding);
        }

        let sign = bytes[0];
        debug_assert!(sign == 2 || sign == 3);
        let x = Fq::from_slice(&bytes[1..]).ok_or(CurveError::InvalidEncoding)?;
        let y_squared = (x * x * x) + Self::b();
        let mut y = y_squared.sqrt().ok_or(CurveError::NotMember)?;
        let is_even = sign & 1 == 0;

        if is_even != y.is_even() {
            y = -y;
        }

        AffineG1::new(x, y)
            .map_err(|_| CurveError::NotMember)
            .map(Into::into)
    }
    /// Serializes this element into compressed form.
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General 6.2.8
    pub fn to_compressed(self) -> [u8; 33] {
        let mut res = [0u8; 33];
        let ag1 = AffineG1::from_jacobian(self).unwrap();
        res[0] = 2; // compressed
        if !ag1.y().is_even() {
            res[0] |= 1;
        }
        res[1..].copy_from_slice(&ag1.x().to_slice());

        res
    }
    /// Serializes this element into uncompressed form.
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 2
    pub fn to_uncompressed(self) -> [u8; 65] {
        let mut res = [4u8; 65];
        res[1..].copy_from_slice(self.to_slice().as_ref());
        res
    }
    /// Attempts to deserialize an uncompressed element of G1
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 2
    pub fn from_uncompressed(bytes: &[u8]) -> Result<Self, CurveError> {
        if bytes.len() != 65 || bytes[0] != 4 {
            return Err(CurveError::InvalidEncoding);
        }
        Self::from_slice(bytes[1..].as_ref())
    }
    /// Serializes this element into uncompressed form.
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 1
    pub fn to_slice(self) -> [u8; 64] {
        let mut res = [0u8; 64];
        let ag1 = AffineG1::from_jacobian(self).unwrap();
        res[..32].copy_from_slice(&ag1.x().to_slice());
        res[32..].copy_from_slice(&ag1.y().to_slice());

        res
    }
    /// Attempts to convert a uncompressed point to an element of G1
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 1
    pub fn from_slice(bytes: &[u8]) -> Result<Self, CurveError> {
        if bytes.len() != 64 {
            return Err(CurveError::InvalidEncoding);
        }

        let x = Fq::from_slice(&bytes[..32]).ok_or(CurveError::InvalidEncoding)?;
        let y = Fq::from_slice(&bytes[32..]).ok_or(CurveError::InvalidEncoding)?;

        AffineG1::new(x, y)
            .map_err(|_| CurveError::NotMember)
            .map(Into::into)
    }
}

impl Group for G1 {
    fn zero() -> Self {
        G1(groups::G1::zero())
    }
    fn one() -> Self {
        G1(groups::G1::one())
    }
    fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
    fn normalize(&mut self) {
        let new = match self.0.to_affine() {
            Some(a) => a,
            None => return,
        };

        self.0 = new.to_jacobian();
    }
}

impl Add<G1> for G1 {
    type Output = G1;

    fn add(self, other: G1) -> G1 {
        G1(self.0 + other.0)
    }
}

impl Sub<G1> for G1 {
    type Output = G1;

    fn sub(self, other: G1) -> G1 {
        G1(self.0 - other.0)
    }
}

impl Neg for G1 {
    type Output = G1;

    fn neg(self) -> G1 {
        G1(-self.0)
    }
}

impl Mul<Fr> for G1 {
    type Output = G1;

    fn mul(self, other: Fr) -> G1 {
        G1(self.0 * other.0)
    }
}

impl Mul<G1> for Fr {
    type Output = G1;

    fn mul(self, other: G1) -> G1 {
        other * self
    }
}

/// an additive cyclic group of prime order r
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct G2(groups::G2);

impl G2 {
    pub fn new(x: Fq2, y: Fq2, z: Fq2) -> Self {
        G2(groups::G2::new(x.0, y.0, z.0))
    }

    pub fn x(&self) -> Fq2 {
        Fq2(*self.0.x())
    }

    pub fn set_x(&mut self, x: Fq2) {
        *self.0.x_mut() = x.0
    }

    pub fn y(&self) -> Fq2 {
        Fq2(*self.0.y())
    }

    pub fn set_y(&mut self, y: Fq2) {
        *self.0.y_mut() = y.0
    }

    pub fn z(&self) -> Fq2 {
        Fq2(*self.0.z())
    }

    pub fn set_z(&mut self, z: Fq2) {
        *self.0.z_mut() = z.0
    }

    pub fn b() -> Fq2 {
        Fq2(G2Params::coeff_b())
    }
    /// get the element from a compressed form.
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General
    // Annex A  A.4.3
    pub fn from_compressed(bytes: &[u8]) -> Result<Self, CurveError> {
        if bytes.len() != 65 {
            return Err(CurveError::InvalidEncoding);
        }
        let sign = bytes[0];
        debug_assert!(sign == 2 || sign == 3);
        let x = Fq2::from_slice(&bytes[1..]).ok_or(CurveError::InvalidEncoding)?;
        let y_squared = (x * x * x) + Self::b();
        let mut y = y_squared.sqrt().ok_or(CurveError::NotMember)?;
        let is_even = sign & 1 == 0;

        if is_even != y.is_even() {
            y = -y;
        }

        AffineG2::new(x, y)
            .map_err(|_| CurveError::NotMember)
            .map(Into::into)
    }
    /// Serializes this element into compressed form.
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General 6.2.8
    pub fn to_compressed(self) -> [u8; 65] {
        let mut res = [0u8; 65];
        let ag1 = AffineG2::from_jacobian(self).unwrap();
        res[0] = 2; // compressed
        if !ag1.y().is_even() {
            res[0] |= 1;
        }
        res[1..].copy_from_slice(&ag1.x().to_slice());

        res
    }
    /// Serializes this element into uncompressed form.
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 2
    pub fn to_uncompressed(self) -> [u8; 129] {
        let mut res = [4u8; 129];
        res[1..].copy_from_slice(self.to_slice().as_ref());
        res
    }
    /// Attempts to deserialize an uncompressed element of G2
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 2
    pub fn from_uncompressed(bytes: &[u8]) -> Result<Self, CurveError> {
        if bytes.len() != 129 || bytes[0] != 4 {
            return Err(CurveError::InvalidEncoding);
        }
        Self::from_slice(bytes[1..].as_ref())
    }
    /// Serializes this element into uncompressed form.
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 1
    pub fn to_slice(self) -> [u8; 128] {
        let mut res = [0u8; 128];
        let ag = AffineG2::from_jacobian(self).unwrap();
        res[..64].copy_from_slice(&ag.x().to_slice());
        res[64..].copy_from_slice(&ag.y().to_slice());

        res
    }
    /// Attempts to convert a uncompressed point to an element of G2
    // SM9 dentity-based cryptographic algorithms
    // Part 1: General, 6.2.8 , case 1
    pub fn from_slice(bytes: &[u8]) -> Result<Self, CurveError> {
        if bytes.len() != 128 {
            return Err(CurveError::InvalidEncoding);
        }

        let x = Fq2::from_slice(&bytes[..64]).ok_or(CurveError::InvalidEncoding)?;
        let y = Fq2::from_slice(&bytes[64..]).ok_or(CurveError::InvalidEncoding)?;

        AffineG2::new(x, y)
            .map_err(|_| CurveError::NotMember)
            .map(Into::into)
    }
}

impl Group for G2 {
    fn zero() -> Self {
        G2(groups::G2::zero())
    }
    fn one() -> Self {
        G2(groups::G2::one())
    }

    fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
    fn normalize(&mut self) {
        let new = match self.0.to_affine() {
            Some(a) => a,
            None => return,
        };

        self.0 = new.to_jacobian();
    }
}

impl Add<G2> for G2 {
    type Output = G2;

    fn add(self, other: G2) -> G2 {
        G2(self.0 + other.0)
    }
}

impl Sub<G2> for G2 {
    type Output = G2;

    fn sub(self, other: G2) -> G2 {
        G2(self.0 - other.0)
    }
}

impl Neg for G2 {
    type Output = G2;

    fn neg(self) -> G2 {
        G2(-self.0)
    }
}

impl Mul<Fr> for G2 {
    type Output = G2;

    fn mul(self, other: Fr) -> G2 {
        G2(self.0 * other.0)
    }
}

impl Mul<G2> for Fr {
    type Output = G2;

    fn mul(self, other: G2) -> G2 {
        other * self
    }
}

/// a multiplicative cyclic group of prime order r
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Gt(fields::Fq12);

impl Gt {
    pub fn one() -> Self {
        Gt(fields::Fq12::one())
    }
    /// Compute exponentiation, where `exp` is a Fr element exponent.
    pub fn pow(&self, exp: Fr) -> Self {
        Gt(self.0.pow(exp.0))
    }
    pub fn inverse(&self) -> Option<Self> {
        self.0.inverse().map(Gt)
    }
    /// Converts an element into a byte representation in
    /// big-endian byte order.
    pub fn to_slice(self) -> [u8; 384] {
        self.0.to_slice()
    }
}

impl Mul<Gt> for Gt {
    type Output = Gt;

    fn mul(self, other: Gt) -> Gt {
        Gt(self.0 * other.0)
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct AffineG1(groups::AffineG1);

impl AffineG1 {
    pub fn new(x: Fq, y: Fq) -> Result<Self, GroupError> {
        Ok(AffineG1(groups::AffineG1::new(x.0, y.0)?))
    }

    pub fn x(&self) -> Fq {
        Fq(*self.0.x())
    }

    pub fn set_x(&mut self, x: Fq) {
        *self.0.x_mut() = x.0
    }

    pub fn y(&self) -> Fq {
        Fq(*self.0.y())
    }

    pub fn set_y(&mut self, y: Fq) {
        *self.0.y_mut() = y.0
    }

    pub fn from_jacobian(g1: G1) -> Option<Self> {
        g1.0.to_affine().map(AffineG1)
    }
}

impl From<AffineG1> for G1 {
    fn from(affine: AffineG1) -> Self {
        G1(affine.0.to_jacobian())
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct AffineG2(groups::AffineG2);

impl AffineG2 {
    pub fn new(x: Fq2, y: Fq2) -> Result<Self, GroupError> {
        Ok(AffineG2(groups::AffineG2::new(x.0, y.0)?))
    }

    pub fn x(&self) -> Fq2 {
        Fq2(*self.0.x())
    }

    pub fn set_x(&mut self, x: Fq2) {
        *self.0.x_mut() = x.0
    }

    pub fn y(&self) -> Fq2 {
        Fq2(*self.0.y())
    }

    pub fn set_y(&mut self, y: Fq2) {
        *self.0.y_mut() = y.0
    }

    pub fn from_jacobian(g2: G2) -> Option<Self> {
        g2.0.to_affine().map(AffineG2)
    }
}

impl From<AffineG2> for G2 {
    fn from(affine: AffineG2) -> Self {
        G2(affine.0.to_jacobian())
    }
}
impl From<G2> for G2Prepared {
    fn from(g2: G2) -> G2Prepared {
        let mut g = g2;
        g.normalize();
        G2Prepared::from(g.0)
    }
}
impl G2Prepared {
    pub fn pairing(&self, g1: &G1) -> Gt {
        let mut g = *g1;
        g.normalize();
        Gt(self
            .miller_loop(&g.0)
            .final_exp()
            .expect("miller loop cannot produce zero"))
    }
}
/// compute R-ate Pairing G2 x G1 -> GT
pub fn pairing(p: G1, q: G2) -> Gt {
    Gt(pairings::pairing(&p.0, &q.0))
}
/// compute R-ate Pairing G2 x G1 -> GT
pub fn fast_pairing(mut p: G1, mut q: G2) -> Gt {
    p.normalize();
    q.normalize();
    Gt(pairings::fast_pairing(&p.0, &q.0))
}

/************************************************************************************************ */
#[cfg(test)]
mod tests {
    use super::*;
    use crate::fields;
    use hex_literal::hex;

    #[test]
    fn test_fq_from_to_slice() {
        let hex = hex!("00000130E78459D78545CB54C587E02CF480CE0B66340F319F348A1D5B1F2DC5F4");
        let f1 = Fq::from_slice(&hex).unwrap();
        let f2 = Fq::from_slice(&hex[1..]).unwrap();
        let f3 = Fq::from_slice(&hex[2..]).unwrap();
        let f4 = Fq::from_slice(&f3.to_slice()).unwrap();
        assert_eq!(f1, f3);
        assert_eq!(f2, f3);
        assert_eq!(f4, f3);
    }
    #[test]
    fn test_fr_from_to_slice() {
        let hex = hex!("00000130E78459D78545CB54C587E02CF480CE0B66340F319F348A1D5B1F2DC5F4");
        let f1 = Fr::from_slice(&hex).unwrap();
        let f2 = Fr::from_slice(&hex[1..]).unwrap();
        let f3 = Fr::from_slice(&hex[2..]).unwrap();
        let f4 = Fr::from_slice(&f3.to_slice()).unwrap();
        assert_eq!(f1, f3);
        assert_eq!(f2, f3);
        assert_eq!(f4, f3);
    }
    #[test]
    fn test_fq2_from_to_slice() {
        let f1 = Fq2::new(
            Fq::from_slice(&hex!(
                "29DBA116 152D1F78 6CE843ED 24A3B573 414D2177 386A92DD 8F14D656 96EA5E32"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "9F64080B 3084F733 E48AFF4B 41B56501 1CE0711C 5E392CFB 0AB1B679 1B94C408"
            ))
            .unwrap(),
        );
        let s = f1.to_slice();
        let f2 = Fq2::from_slice(&s).unwrap();
        assert_eq!(f1, f2);
    }
    #[test]
    fn test_fq_to_big_endian() {
        let a = Fq::from_str("1").unwrap();
        let mut b = [0u8; 32];
        let mut c = [0u8; 32];
        c[31] = 1;
        a.to_big_endian(&mut b[..]).unwrap();
        assert_eq!(b, c);
    }

    #[test]
    fn lib_g1_mul() {
        let t2 = Fr::from_slice(&hex!(
            "291FE3CA C8F58AD2 DC462C8D 4D578A94 DAFD5624 DDC28E32 8D293668 8A86CF1A"
        ))
        .unwrap();
        let mut ds = G1::one() * t2;
        ds.normalize();

        let r = G1::new(
            Fq::from_slice(&hex!(
                "A5702F05 CF131530 5E2D6EB6 4B0DEB92 3DB1A0BC F0CAFF90 523AC875 4AA69820"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "78559A84 4411F982 5C109F5E E3F52D72 0DD01785 392A727B B1556952 B2B013D3"
            ))
            .unwrap(),
            Fq::one(),
        );
        assert_eq!(r, ds);
        let mut ds2 = t2 * G1::one();
        ds2.normalize();
        assert_eq!(r, ds2)
    }

    #[test]
    fn lib_g2_mul() {
        let ks = Fr::from_slice(&hex!(
            "000130E78459D78545CB54C587E02CF480CE0B66340F319F348A1D5B1F2DC5F4"
        ))
        .unwrap();
        let mut pub_s = G2::one() * ks;
        pub_s.normalize();

        let x = Fq2::new(
            Fq::from_slice(&hex!(
                "29DBA116 152D1F78 6CE843ED 24A3B573 414D2177 386A92DD 8F14D656 96EA5E32"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "9F64080B 3084F733 E48AFF4B 41B56501 1CE0711C 5E392CFB 0AB1B679 1B94C408"
            ))
            .unwrap(),
        );
        let y = Fq2::new(
            Fq::from_slice(&hex!(
                "41E00A53 DDA532DA 1A7CE027 B7A46F74 1006E85F 5CDFF073 0E75C05F B4E3216D"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "69850938 ABEA0112 B57329F4 47E3A0CB AD3E2FDB 1A77F335 E89E1408 D0EF1C25"
            ))
            .unwrap(),
        );
        let r = G2::new(x, y, Fq2::one());

        println!("pub_s {:?}", pub_s);
        assert_eq!(r, pub_s);

        let mut ps = ks * G2::one();
        ps.normalize();
        assert_eq!(ps, pub_s);
    }

    #[test]
    fn lib_pairing_test() {
        let ks = Fr::from_slice(&hex!(
            "000130E78459D78545CB54C587E02CF480CE0B66340F319F348A1D5B1F2DC5F4"
        ))
        .unwrap();
        let pub_s = G2::one() * ks;
        let g = pairing(G1::one(), pub_s);
        // println!(" {:#?}", g);
        let r0 = Fq2::new(
            Fq::from_slice(&hex!(
                "AAB9F06A 4EEBA432 3A7833DB 202E4E35 639D93FA 3305AF73 F0F071D7 D284FCFB"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "84B87422 330D7936 EABA1109 FA5A7A71 81EE16F2 438B0AEB 2F38FD5F 7554E57A"
            ))
            .unwrap(),
        );
        let r1 = Fq2::new(
            Fq::from_slice(&hex!(
                "4C744E69 C4A2E1C8 ED72F796 D151A17C E2325B94 3260FC46 0B9F73CB 57C9014B"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "B3129A75 D31D1719 4675A1BC 56947920 898FBF39 0A5BF5D9 31CE6CBB 3340F66D"
            ))
            .unwrap(),
        );
        let a = fields::Fq4::new(r0.0, r1.0);
        let r0 = Fq2::new(
            Fq::from_slice(&hex!(
                "93634F44 FA13AF76 169F3CC8 FBEA880A DAFF8475 D5FD28A7 5DEB83C4 4362B439"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "1604A3FC FA9783E6 67CE9FCB 1062C2A5 C6685C31 6DDA62DE 0548BAA6 BA30038B"
            ))
            .unwrap(),
        );
        let r1 = Fq2::new(
            Fq::from_slice(&hex!(
                "5A1AE172 102EFD95 DF7338DB C577C66D 8D6C15E0 A0158C75 07228EFB 078F42A6"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "67E0E0C2 EED7A699 3DCE28FE 9AA2EF56 83430786 0839677F 96685F2B 44D0911F"
            ))
            .unwrap(),
        );
        let b = fields::Fq4::new(r0.0, r1.0);
        let r0 = Fq2::new(
            Fq::from_slice(&hex!(
                "A01F2C8B EE817696 09462C69 C96AA923 FD863E20 9D3CE26D D889B55E 2E3873DB"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "38BFFE40 A22D529A 0C66124B 2C308DAC 92299126 56F62B4F ACFCED40 8E02380F"
            ))
            .unwrap(),
        );
        let r1 = Fq2::new(
            Fq::from_slice(&hex!(
                "28B3404A 61908F5D 6198815C 99AF1990 C8AF3865 5930058C 28C21BB5 39CE0000"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "4E378FB5 561CD066 8F906B73 1AC58FEE 25738EDF 09CADC7A 29C0ABC0 177AEA6D"
            ))
            .unwrap(),
        );
        let c = fields::Fq4::new(r0.0, r1.0);
        let r = fields::Fq12::new(a, b, c);
        assert_eq!(r, g.0);
        let g1 = fast_pairing(G1::one(), pub_s);
        assert_eq!(r, g1.0);
    }

    #[test]
    fn lib_gt_pow_test() {
        let ks = Fr::from_slice(&hex!(
            "000130E78459D78545CB54C587E02CF480CE0B66340F319F348A1D5B1F2DC5F4"
        ))
        .unwrap();
        let r = Fr::from_slice(&hex!(
            "00033C86 16B06704 813203DF D0096502 2ED15975 C662337A ED648835 DC4B1CBE"
        ))
        .unwrap();
        let pub_s = G2::one() * ks;
        let g = pairing(G1::one(), pub_s).pow(r);
        // println!(" {:#?}", g);
        let r0 = Fq2::new(
            Fq::from_slice(&hex!(
                "1F96B08E 97997363 91131470 5BFB9A9D BB97F755 53EC90FB B2DDAE53 C8F68E42"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "6A814AAF 475F128A EF43A128 E37F8015 4AE6CB92 CAD7D150 1BAE30F7 50B3A9BD"
            ))
            .unwrap(),
        );
        let r1 = Fq2::new(
            Fq::from_slice(&hex!(
                "898D6084 8026B7EF B8FCC1B2 442ECF07 95F8A81C EE99A624 8F294C82 C90D26BD"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "44643CEA D40F0965 F28E1CD2 895C3D11 8E4F65C9 A0E3E741 B6DD52C0 EE2D25F5"
            ))
            .unwrap(),
        );
        let a = fields::Fq4::new(r0.0, r1.0);
        let r0 = Fq2::new(
            Fq::from_slice(&hex!(
                "0656FCB6 63D24731 E8029218 8A2471B8 B68AA993 89926849 9D23C897 55A1A897"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "4F8624EB 435B838C CA77B2D0 347E65D5 E4696441 2A096F41 50D8C5ED E5440DDF"
            ))
            .unwrap(),
        );
        let r1 = Fq2::new(
            Fq::from_slice(&hex!(
                "3F012DB0 4BA59FE8 8DB88932 1CC2373D 4C0C35E8 4F7AB1FF 33679BCA 575D6765"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "A543D256 09AE9439 20679194 ED30328B B33FD156 60BDE485 C6B79A7B 32B01398"
            ))
            .unwrap(),
        );
        let b = fields::Fq4::new(r0.0, r1.0);
        let r0 = Fq2::new(
            Fq::from_slice(&hex!(
                "8EAF5D17 9A1836B3 59A9D1D9 BFC19F2E FCDB8293 28620962 BD3FDF15 F2567F58"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "30DADC5C D9E207AE E32209F6 C3CA3EC0 D800A1A4 2D33C731 53DED47C 70A39D2E"
            ))
            .unwrap(),
        );
        let r1 = Fq2::new(
            Fq::from_slice(&hex!(
                "815AEBA2 17AD502D A0F48704 CC73CABB 3C06209B D87142E1 4CBD99E8 BCA1680F"
            ))
            .unwrap(),
            Fq::from_slice(&hex!(
                "81377B8F DBC2839B 4FA2D0E0 F8AA6853 BBBE9E9C 4099608F 8612C607 8ACD7563"
            ))
            .unwrap(),
        );
        let c = fields::Fq4::new(r0.0, r1.0);
        let w = fields::Fq12::new(a, b, c);
        assert_eq!(w, g.0)
    }
}