dusk-curves 0.2.0

Backend-agnostic elliptic curve primitives
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
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

//! G2 affine and projective point types for the blst backend.

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

use alloc::vec::Vec;
use dusk_bytes::Serializable;
use group::prime::{PrimeCurve, PrimeCurveAffine, PrimeGroup};
use group::{Curve, Group, GroupEncoding, UncompressedEncoding, WnafGroup};
use rand_core::RngCore;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};

use super::{BlsScalar, G2Compressed, G2Uncompressed};

#[cfg(feature = "rkyv-impl")]
mod rkyv;
#[cfg(feature = "rkyv-impl")]
pub use self::rkyv::{ArchivedG2Affine, G2AffineResolver, InvalidG2Affine};

const UNCOMPRESSED_REJECTED_FLAGS: u8 = 0x80 | 0x20;

// h_eff_G2 from RFC 9380 §8.8.2, little-endian. Matches blst's disabled
// scalar-multiplication fallback in map_to_g2.c.
const H_EFF_G2: [u8; 80] = [
    0x51, 0x55, 0xa9, 0xaa, 0x05, 0x00, 0x02, 0xe8, 0xb4, 0xf6, 0xbb, 0xde, 0x0a, 0x4c, 0x89, 0x59,
    0xa3, 0xf6, 0x89, 0x66, 0xc0, 0xcb, 0x54, 0xe9, 0x1a, 0x7c, 0x47, 0xd7, 0x69, 0xec, 0xc0, 0x2e,
    0xb0, 0x12, 0x12, 0x5d, 0x01, 0xbf, 0x82, 0x6d, 0x95, 0xdb, 0x31, 0x87, 0x17, 0x2f, 0x9c, 0x32,
    0xe1, 0xff, 0x08, 0x15, 0x03, 0xff, 0x86, 0x99, 0x68, 0xd7, 0x5a, 0x14, 0xe9, 0xa8, 0xe2, 0x88,
    0x28, 0x35, 0x1b, 0xa9, 0x0e, 0x6a, 0x4c, 0x58, 0xb3, 0x75, 0xee, 0xf2, 0x08, 0x9f, 0xc6, 0x0b,
];
const H_EFF_G2_BITS: usize = 636;

fn has_valid_uncompressed_flags(first_byte: u8) -> bool {
    first_byte & UNCOMPRESSED_REJECTED_FLAGS == 0
}

// ═══════════════════════════════════════════════════════════════════════════════
//  G2Affine
// ═══════════════════════════════════════════════════════════════════════════════

/// G2 affine point wrapping `blst_p2_affine`.
#[derive(Copy, Clone, Default, PartialEq, Eq)]
pub struct G2Affine(pub(crate) ::blst::blst_p2_affine);

impl G2Affine {
    /// The identity (point-at-infinity).
    #[must_use]
    pub fn identity() -> Self {
        Self(::blst::blst_p2_affine::default())
    }

    /// The standard generator of G2.
    #[must_use]
    pub fn generator() -> Self {
        Self(unsafe { *::blst::blst_p2_affine_generator() })
    }

    /// Size of the raw representation.
    pub const RAW_SIZE: usize = 193;

    /// Serialize to the dusk-compatible raw representation.
    /// Encoding uses Montgomery-form little-endian limbs, identical to dusk_bls12_381's internal Fp layout.
    #[must_use]
    pub fn to_raw_bytes(&self) -> [u8; Self::RAW_SIZE] {
        let mut out = [0u8; Self::RAW_SIZE];
        if bool::from(self.is_identity()) {
            let dusk_identity = dusk_bls12_381::G2Affine::identity();
            return dusk_identity.to_raw_bytes();
        }
        super::write_raw_limbs(
            &mut out[..Self::RAW_SIZE - 1],
            self.0.x.fp[0]
                .l
                .iter()
                .chain(self.0.x.fp[1].l.iter())
                .chain(self.0.y.fp[0].l.iter())
                .chain(self.0.y.fp[1].l.iter()),
        );
        out[Self::RAW_SIZE - 1] = self.is_identity().unwrap_u8();
        out
    }

    /// Create a `G2Affine` from bytes created by `G2Affine::to_raw_bytes`.
    ///
    /// # Safety
    /// The caller must guarantee that `bytes` contains the exact trusted raw
    /// representation produced by `G2Affine::to_raw_bytes`, or an equivalent
    /// valid Montgomery-limb encoding of a point on the BLS12-381 G2 curve.
    ///
    /// No validation or constant-time parsing is performed. If the resulting
    /// point is used where subgroup membership is required, the caller must
    /// also guarantee that it is in the prime-order subgroup.
    #[must_use]
    pub unsafe fn from_slice_unchecked(bytes: &[u8]) -> Self {
        if bytes.len() >= Self::RAW_SIZE && bytes[Self::RAW_SIZE - 1] != 0 {
            return Self::identity();
        }
        let mut out = ::blst::blst_p2_affine::default();
        let raw = &bytes[..core::cmp::min(bytes.len(), Self::RAW_SIZE - 1)];
        let xc0_end = core::cmp::min(raw.len(), 48);
        super::read_raw_limbs(&raw[..xc0_end], out.x.fp[0].l.iter_mut());
        if raw.len() > 48 {
            let xc1_end = core::cmp::min(raw.len(), 96);
            super::read_raw_limbs(&raw[48..xc1_end], out.x.fp[1].l.iter_mut());
        }
        if raw.len() > 96 {
            let yc0_end = core::cmp::min(raw.len(), 144);
            super::read_raw_limbs(&raw[96..yc0_end], out.y.fp[0].l.iter_mut());
        }
        if raw.len() > 144 {
            let yc1_end = core::cmp::min(raw.len(), 192);
            super::read_raw_limbs(&raw[144..yc1_end], out.y.fp[1].l.iter_mut());
        }
        Self(out)
    }

    /// Returns true if this element is the identity.
    #[must_use]
    pub fn is_identity(&self) -> Choice {
        let inf = unsafe { ::blst::blst_p2_affine_is_inf(&raw const self.0) };
        Choice::from(inf as u8)
    }

    /// Returns true if this point is in the prime-order subgroup.
    #[must_use]
    pub fn is_torsion_free(&self) -> Choice {
        let in_group = unsafe { ::blst::blst_p2_affine_in_g2(&raw const self.0) };
        Choice::from(in_group as u8)
    }

    /// Returns true if this point is on the curve.
    #[must_use]
    pub fn is_on_curve(&self) -> Choice {
        let on_curve = unsafe { ::blst::blst_p2_affine_on_curve(&raw const self.0) };
        Choice::from(on_curve as u8)
    }

    /// Serialize this element into compressed form (96 bytes).
    ///
    /// Mirrors `dusk_bls12_381::G2Affine::to_compressed`. Equivalent to
    /// `<G2Affine as dusk_bytes::Serializable<96>>::to_bytes(self)`.
    #[must_use]
    pub fn to_compressed(&self) -> [u8; 96] {
        <Self as Serializable<96>>::to_bytes(self)
    }

    /// Serialize this element into uncompressed canonical form (192 bytes).
    #[must_use]
    pub fn to_uncompressed(&self) -> [u8; 192] {
        let mut out = [0u8; 192];
        unsafe { ::blst::blst_p2_affine_serialize(out.as_mut_ptr(), &raw const self.0) };
        out
    }

    /// Attempt to deserialize a compressed element. Performs both on-curve and
    /// subgroup-membership checks; matches the safe `dusk_bls12_381` API.
    #[must_use]
    pub fn from_compressed(bytes: &[u8; 96]) -> CtOption<Self> {
        <Self as GroupEncoding>::from_bytes(&G2Compressed(*bytes))
    }

    /// Attempt to deserialize a compressed element without subgroup checks.
    #[must_use]
    pub fn from_compressed_unchecked(bytes: &[u8; 96]) -> CtOption<Self> {
        <Self as GroupEncoding>::from_bytes_unchecked(&G2Compressed(*bytes))
    }

    /// Attempt to deserialize an uncompressed element. Performs both on-curve
    /// and subgroup-membership checks.
    #[must_use]
    pub fn from_uncompressed(bytes: &[u8; 192]) -> CtOption<Self> {
        <Self as UncompressedEncoding>::from_uncompressed(&G2Uncompressed(*bytes))
    }

    /// Attempt to deserialize an uncompressed element without subgroup checks.
    #[must_use]
    pub fn from_uncompressed_unchecked(bytes: &[u8; 192]) -> CtOption<Self> {
        <Self as UncompressedEncoding>::from_uncompressed_unchecked(&G2Uncompressed(*bytes))
    }
}

// -- Serializable (compressed, 96 bytes) ------------------------------------

impl Serializable<96> for G2Affine {
    type Error = dusk_bytes::Error;

    fn to_bytes(&self) -> [u8; 96] {
        let mut out = [0u8; 96];
        unsafe { ::blst::blst_p2_affine_compress(out.as_mut_ptr(), &raw const self.0) };
        out
    }

    fn from_bytes(buf: &[u8; 96]) -> Result<Self, Self::Error> {
        let mut out = ::blst::blst_p2_affine::default();
        let err = unsafe { ::blst::blst_p2_uncompress(&raw mut out, buf.as_ptr()) };
        if err != ::blst::BLST_ERROR::BLST_SUCCESS {
            return Err(dusk_bytes::Error::InvalidData);
        }
        let in_group = unsafe { ::blst::blst_p2_affine_in_g2(&raw const out) };
        if !in_group {
            return Err(dusk_bytes::Error::InvalidData);
        }
        Ok(Self(out))
    }
}

// -- Trait helpers -----------------------------------------------------------

impl fmt::Debug for G2Affine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let b = <Self as Serializable<96>>::to_bytes(self);
        write!(f, "G2Affine({:?})", &b[..8])
    }
}

// -- Conversions between affine ↔ projective --------------------------------

impl From<G2Projective> for G2Affine {
    fn from(p: G2Projective) -> Self {
        let mut out = ::blst::blst_p2_affine::default();
        unsafe { ::blst::blst_p2_to_affine(&raw mut out, &raw const p.0) };
        Self(out)
    }
}

impl From<&G2Projective> for G2Affine {
    fn from(p: &G2Projective) -> Self {
        Self::from(*p)
    }
}

// -- Arithmetic for G2Affine ------------------------------------------------

impl Neg for G2Affine {
    type Output = Self;
    fn neg(self) -> Self {
        let mut p = ::blst::blst_p2::default();
        unsafe {
            ::blst::blst_p2_from_affine(&raw mut p, &raw const self.0);
            ::blst::blst_p2_cneg(&raw mut p, true);
        }
        Self::from(G2Projective(p))
    }
}

impl Neg for &G2Affine {
    type Output = G2Affine;
    fn neg(self) -> G2Affine {
        -(*self)
    }
}

impl Mul<BlsScalar> for G2Affine {
    type Output = G2Projective;
    fn mul(self, rhs: BlsScalar) -> G2Projective {
        G2Projective::from(self) * rhs
    }
}

impl Mul<BlsScalar> for &G2Affine {
    type Output = G2Projective;
    fn mul(self, rhs: BlsScalar) -> G2Projective {
        (*self) * rhs
    }
}

impl Mul<&BlsScalar> for G2Affine {
    type Output = G2Projective;
    fn mul(self, rhs: &BlsScalar) -> G2Projective {
        self * (*rhs)
    }
}

impl Mul<&BlsScalar> for &G2Affine {
    type Output = G2Projective;
    fn mul(self, rhs: &BlsScalar) -> G2Projective {
        (*self) * (*rhs)
    }
}

impl Add<G2Affine> for G2Affine {
    type Output = G2Projective;
    fn add(self, rhs: G2Affine) -> G2Projective {
        G2Projective::from(self) + G2Projective::from(rhs)
    }
}

impl Add<G2Projective> for G2Affine {
    type Output = G2Projective;
    fn add(self, rhs: G2Projective) -> G2Projective {
        G2Projective::from(self) + rhs
    }
}

impl Sub<G2Projective> for G2Affine {
    type Output = G2Projective;
    fn sub(self, rhs: G2Projective) -> G2Projective {
        G2Projective::from(self) - rhs
    }
}

impl Sub<G2Affine> for G2Affine {
    type Output = G2Projective;
    fn sub(self, rhs: G2Affine) -> G2Projective {
        G2Projective::from(self) - G2Projective::from(rhs)
    }
}

impl Add<&G2Affine> for G2Affine {
    type Output = G2Projective;
    fn add(self, rhs: &G2Affine) -> G2Projective {
        self + *rhs
    }
}

impl Add<&G2Projective> for G2Affine {
    type Output = G2Projective;
    fn add(self, rhs: &G2Projective) -> G2Projective {
        self + *rhs
    }
}

impl Sub<&G2Affine> for G2Affine {
    type Output = G2Projective;
    fn sub(self, rhs: &G2Affine) -> G2Projective {
        self - *rhs
    }
}

impl Sub<&G2Projective> for G2Affine {
    type Output = G2Projective;
    fn sub(self, rhs: &G2Projective) -> G2Projective {
        self - *rhs
    }
}

impl_ref_binops!(Add, add, G2Affine, G2Affine, G2Projective);
impl_ref_binops!(Add, add, G2Affine, G2Projective, G2Projective);
impl_ref_binops!(Sub, sub, G2Affine, G2Affine, G2Projective);
impl_ref_binops!(Sub, sub, G2Affine, G2Projective, G2Projective);

// -- subtle: constant-time equality and selection ---------------------------

impl ConstantTimeEq for G2Affine {
    fn ct_eq(&self, other: &Self) -> Choice {
        <Self as Serializable<96>>::to_bytes(self)
            .ct_eq(&<Self as Serializable<96>>::to_bytes(other))
    }
}

impl ConditionallySelectable for G2Affine {
    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
        // Select directly on the inner Montgomery-form Fp2 limbs — no
        // compression, decompression, or subgroup re-check needed.
        let mut out = ::blst::blst_p2_affine::default();
        for i in 0..6 {
            out.x.fp[0].l[i] =
                u64::conditional_select(&a.0.x.fp[0].l[i], &b.0.x.fp[0].l[i], choice);
            out.x.fp[1].l[i] =
                u64::conditional_select(&a.0.x.fp[1].l[i], &b.0.x.fp[1].l[i], choice);
            out.y.fp[0].l[i] =
                u64::conditional_select(&a.0.y.fp[0].l[i], &b.0.y.fp[0].l[i], choice);
            out.y.fp[1].l[i] =
                u64::conditional_select(&a.0.y.fp[1].l[i], &b.0.y.fp[1].l[i], choice);
        }
        Self(out)
    }
}

// -- group: GroupEncoding (compressed, 96 bytes) ----------------------------

impl GroupEncoding for G2Affine {
    type Repr = G2Compressed;

    fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
        let mut out = ::blst::blst_p2_affine::default();
        let err = unsafe { ::blst::blst_p2_uncompress(&raw mut out, bytes.0.as_ptr()) };
        let on_curve = err == ::blst::BLST_ERROR::BLST_SUCCESS;
        let in_group = on_curve && unsafe { ::blst::blst_p2_affine_in_g2(&raw const out) };
        CtOption::new(Self(out), Choice::from(in_group as u8))
    }

    fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
        let mut out = ::blst::blst_p2_affine::default();
        let err = unsafe { ::blst::blst_p2_uncompress(&raw mut out, bytes.0.as_ptr()) };
        let is_ok = err == ::blst::BLST_ERROR::BLST_SUCCESS;
        CtOption::new(Self(out), Choice::from(is_ok as u8))
    }

    fn to_bytes(&self) -> Self::Repr {
        G2Compressed(<Self as Serializable<96>>::to_bytes(self))
    }
}

// -- group: UncompressedEncoding (192 bytes) --------------------------------

impl UncompressedEncoding for G2Affine {
    type Uncompressed = G2Uncompressed;

    fn from_uncompressed(bytes: &Self::Uncompressed) -> CtOption<Self> {
        let mut out = ::blst::blst_p2_affine::default();
        let valid_flags = has_valid_uncompressed_flags(bytes.0[0]);
        let err = if valid_flags {
            unsafe { ::blst::blst_p2_deserialize(&raw mut out, bytes.0.as_ptr()) }
        } else {
            ::blst::BLST_ERROR::BLST_BAD_ENCODING
        };
        let p = Self(out);
        let decoded = err == ::blst::BLST_ERROR::BLST_SUCCESS;
        let in_group = decoded && unsafe { ::blst::blst_p2_affine_in_g2(&raw const p.0) };
        let ok = decoded && in_group;
        CtOption::new(p, Choice::from(ok as u8))
    }

    fn from_uncompressed_unchecked(bytes: &Self::Uncompressed) -> CtOption<Self> {
        let mut out = ::blst::blst_p2_affine::default();
        let valid_flags = has_valid_uncompressed_flags(bytes.0[0]);
        let err = if valid_flags {
            unsafe { ::blst::blst_p2_deserialize(&raw mut out, bytes.0.as_ptr()) }
        } else {
            ::blst::BLST_ERROR::BLST_BAD_ENCODING
        };
        let ok = err == ::blst::BLST_ERROR::BLST_SUCCESS;
        CtOption::new(Self(out), Choice::from(ok as u8))
    }

    fn to_uncompressed(&self) -> Self::Uncompressed {
        let mut out = [0u8; 192];
        unsafe { ::blst::blst_p2_affine_serialize(out.as_mut_ptr(), &raw const self.0) };
        G2Uncompressed(out)
    }
}

// -- group: PrimeCurveAffine ------------------------------------------------

impl PrimeCurveAffine for G2Affine {
    type Scalar = BlsScalar;
    type Curve = G2Projective;

    fn identity() -> Self {
        Self::identity()
    }

    fn generator() -> Self {
        Self::generator()
    }

    fn is_identity(&self) -> Choice {
        self.is_identity()
    }

    fn to_curve(&self) -> G2Projective {
        G2Projective::from(*self)
    }
}

// -- scalar-on-left multiplication ------------------------------------------

impl Mul<G2Affine> for BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: G2Affine) -> G2Projective {
        rhs * self
    }
}

impl Mul<&G2Affine> for BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: &G2Affine) -> G2Projective {
        rhs * self
    }
}

impl Mul<G2Affine> for &BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: G2Affine) -> G2Projective {
        rhs * self
    }
}

impl Mul<&G2Affine> for &BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: &G2Affine) -> G2Projective {
        rhs * self
    }
}

// -- fmt::Display -----------------------------------------------------------

impl fmt::Display for G2Affine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let bytes = <Self as Serializable<96>>::to_bytes(self);
        write!(f, "G2Affine(0x")?;
        for b in &bytes {
            write!(f, "{b:02x}")?;
        }
        write!(f, ")")
    }
}

// -- zeroize ----------------------------------------------------------------

#[cfg(feature = "zeroize")]
impl ::zeroize::DefaultIsZeroes for G2Affine {}

// ═══════════════════════════════════════════════════════════════════════════════
//  G2Projective
// ═══════════════════════════════════════════════════════════════════════════════

/// G2 projective point wrapping `blst_p2`.
#[derive(Copy, Clone)]
pub struct G2Projective(pub(crate) ::blst::blst_p2);

impl PartialEq for G2Projective {
    fn eq(&self, other: &Self) -> bool {
        unsafe { ::blst::blst_p2_is_equal(&raw const self.0, &raw const other.0) }
    }
}

impl Eq for G2Projective {}

impl G2Projective {
    /// The identity element.
    #[must_use]
    pub fn identity() -> Self {
        Self::from(G2Affine::identity())
    }

    /// The standard generator.
    #[must_use]
    pub fn generator() -> Self {
        Self::from(G2Affine::generator())
    }

    /// Batch-convert an array of projective points to affine using blst's
    /// `blst_p2s_to_affine` (Montgomery batch inversion — one field
    /// inversion shared across all points).
    pub fn batch_normalize(points: &[Self], out: &mut [G2Affine]) {
        let n = core::cmp::min(points.len(), out.len());
        if n == 0 {
            return;
        }
        let blst_pts: Vec<::blst::blst_p2> = points[..n].iter().map(|p| p.0).collect();
        let affines = ::blst::p2_affines::from(&blst_pts);
        let affine_slice = affines.as_slice();
        for i in 0..n {
            out[i] = G2Affine(affine_slice[i]);
        }
    }

    /// Returns true if this element is the identity.
    #[must_use]
    pub fn is_identity(&self) -> Choice {
        let inf = unsafe { ::blst::blst_p2_is_inf(&raw const self.0) };
        Choice::from(inf as u8)
    }

    /// Returns true if this point lies on the curve.
    #[must_use]
    pub fn is_on_curve(&self) -> Choice {
        let on_curve = unsafe { ::blst::blst_p2_on_curve(&raw const self.0) };
        Choice::from(on_curve as u8)
    }

    /// Compute the doubling of this point.
    #[must_use]
    pub fn double(&self) -> Self {
        let mut out = ::blst::blst_p2::default();
        unsafe { ::blst::blst_p2_double(&raw mut out, &raw const self.0) };
        Self(out)
    }

    /// Add this point to another projective point.
    #[must_use]
    pub fn add(&self, rhs: &Self) -> Self {
        let mut out = ::blst::blst_p2::default();
        unsafe { ::blst::blst_p2_add_or_double(&raw mut out, &raw const self.0, &raw const rhs.0) };
        Self(out)
    }

    /// Add this point to an affine point (mixed addition).
    #[must_use]
    pub fn add_mixed(&self, rhs: &G2Affine) -> Self {
        let mut out = ::blst::blst_p2::default();
        unsafe {
            ::blst::blst_p2_add_or_double_affine(&raw mut out, &raw const self.0, &raw const rhs.0);
        }
        Self(out)
    }

    /// Clears the cofactor, projecting an on-curve point onto the prime-order
    /// G2 subgroup.
    ///
    /// For G2 this is multiplication by the RFC 9380 effective cofactor
    /// `h_eff_G2`.
    #[must_use]
    pub fn clear_cofactor(&self) -> Self {
        let mut out = ::blst::blst_p2::default();
        unsafe {
            ::blst::blst_p2_mult(
                &raw mut out,
                &raw const self.0,
                H_EFF_G2.as_ptr(),
                H_EFF_G2_BITS,
            );
        }
        Self(out)
    }
}

impl Default for G2Projective {
    fn default() -> Self {
        Self::identity()
    }
}

impl fmt::Debug for G2Projective {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "G2Projective({:?})", G2Affine::from(*self))
    }
}

// -- Conversions ------------------------------------------------------------

impl From<G2Affine> for G2Projective {
    fn from(p: G2Affine) -> Self {
        let mut out = ::blst::blst_p2::default();
        unsafe { ::blst::blst_p2_from_affine(&raw mut out, &raw const p.0) };
        Self(out)
    }
}

impl From<&G2Affine> for G2Projective {
    fn from(p: &G2Affine) -> Self {
        Self::from(*p)
    }
}

// -- Arithmetic for G2Projective --------------------------------------------

impl Add for G2Projective {
    type Output = Self;
    fn add(self, rhs: Self) -> Self {
        let mut out = ::blst::blst_p2::default();
        unsafe { ::blst::blst_p2_add_or_double(&raw mut out, &raw const self.0, &raw const rhs.0) };
        Self(out)
    }
}

impl AddAssign for G2Projective {
    fn add_assign(&mut self, rhs: Self) {
        *self = *self + rhs;
    }
}

impl Add<&G2Projective> for G2Projective {
    type Output = Self;
    fn add(self, rhs: &Self) -> Self {
        self + *rhs
    }
}

impl AddAssign<&G2Projective> for G2Projective {
    fn add_assign(&mut self, rhs: &Self) {
        *self = *self + *rhs;
    }
}

impl Add<G2Affine> for G2Projective {
    type Output = Self;
    fn add(self, rhs: G2Affine) -> Self {
        let mut out = ::blst::blst_p2::default();
        unsafe {
            ::blst::blst_p2_add_or_double_affine(&raw mut out, &raw const self.0, &raw const rhs.0);
        }
        Self(out)
    }
}

impl AddAssign<G2Affine> for G2Projective {
    fn add_assign(&mut self, rhs: G2Affine) {
        *self = *self + rhs;
    }
}

impl Add<&G2Affine> for G2Projective {
    type Output = Self;
    fn add(self, rhs: &G2Affine) -> Self {
        self + *rhs
    }
}

impl AddAssign<&G2Affine> for G2Projective {
    fn add_assign(&mut self, rhs: &G2Affine) {
        *self = *self + *rhs;
    }
}

impl Neg for &G2Projective {
    type Output = G2Projective;

    fn neg(self) -> G2Projective {
        let mut out = self.0;
        unsafe { ::blst::blst_p2_cneg(&raw mut out, true) };
        G2Projective(out)
    }
}

impl Neg for G2Projective {
    type Output = Self;
    fn neg(self) -> Self {
        -&self
    }
}

impl Sub for G2Projective {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self {
        self + (-rhs)
    }
}

impl SubAssign for G2Projective {
    fn sub_assign(&mut self, rhs: Self) {
        *self = *self - rhs;
    }
}

impl Sub<&G2Projective> for G2Projective {
    type Output = Self;
    fn sub(self, rhs: &Self) -> Self {
        self - *rhs
    }
}

impl SubAssign<&G2Projective> for G2Projective {
    fn sub_assign(&mut self, rhs: &Self) {
        *self = *self - *rhs;
    }
}

impl Sub<G2Affine> for G2Projective {
    type Output = Self;
    fn sub(self, rhs: G2Affine) -> Self {
        self - Self::from(rhs)
    }
}

impl SubAssign<G2Affine> for G2Projective {
    fn sub_assign(&mut self, rhs: G2Affine) {
        *self = *self - rhs;
    }
}

impl Sub<&G2Affine> for G2Projective {
    type Output = Self;
    fn sub(self, rhs: &G2Affine) -> Self {
        self - *rhs
    }
}

impl SubAssign<&G2Affine> for G2Projective {
    fn sub_assign(&mut self, rhs: &G2Affine) {
        *self = *self - *rhs;
    }
}

impl_ref_binops!(Add, add, G2Projective, G2Projective, G2Projective);
impl_ref_binops!(Add, add, G2Projective, G2Affine, G2Projective);
impl_ref_binops!(Sub, sub, G2Projective, G2Projective, G2Projective);
impl_ref_binops!(Sub, sub, G2Projective, G2Affine, G2Projective);

impl Mul<BlsScalar> for G2Projective {
    type Output = Self;
    fn mul(self, rhs: BlsScalar) -> Self {
        let bytes = rhs.to_bytes();
        let mut out = ::blst::blst_p2::default();
        unsafe {
            ::blst::blst_p2_mult(&raw mut out, &raw const self.0, bytes.as_ptr(), 255);
        };
        Self(out)
    }
}

impl Mul<&BlsScalar> for G2Projective {
    type Output = Self;
    fn mul(self, rhs: &BlsScalar) -> Self {
        self * (*rhs)
    }
}

impl Mul<BlsScalar> for &G2Projective {
    type Output = G2Projective;
    fn mul(self, rhs: BlsScalar) -> G2Projective {
        (*self) * rhs
    }
}

impl Mul<&BlsScalar> for &G2Projective {
    type Output = G2Projective;
    fn mul(self, rhs: &BlsScalar) -> G2Projective {
        (*self) * (*rhs)
    }
}

impl MulAssign<BlsScalar> for G2Projective {
    fn mul_assign(&mut self, rhs: BlsScalar) {
        *self = *self * rhs;
    }
}

impl MulAssign<&BlsScalar> for G2Projective {
    fn mul_assign(&mut self, rhs: &BlsScalar) {
        *self = *self * *rhs;
    }
}

impl core::iter::Sum for G2Projective {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        iter.fold(Self::identity(), |acc, x| acc + x)
    }
}

impl<'a> core::iter::Sum<&'a G2Projective> for G2Projective {
    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
        iter.fold(Self::identity(), |acc, x| acc + *x)
    }
}

// -- subtle: constant-time equality and selection ---------------------------

impl ConstantTimeEq for G2Projective {
    fn ct_eq(&self, other: &Self) -> Choice {
        G2Affine::from(*self).ct_eq(&G2Affine::from(*other))
    }
}

impl ConditionallySelectable for G2Projective {
    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
        // Select directly on the projective (X, Y, Z) Fp2 limbs; avoids the
        // two blst_p2_to_affine calls the affine-delegate path would incur.
        let mut out = ::blst::blst_p2::default();
        for i in 0..6 {
            out.x.fp[0].l[i] =
                u64::conditional_select(&a.0.x.fp[0].l[i], &b.0.x.fp[0].l[i], choice);
            out.x.fp[1].l[i] =
                u64::conditional_select(&a.0.x.fp[1].l[i], &b.0.x.fp[1].l[i], choice);
            out.y.fp[0].l[i] =
                u64::conditional_select(&a.0.y.fp[0].l[i], &b.0.y.fp[0].l[i], choice);
            out.y.fp[1].l[i] =
                u64::conditional_select(&a.0.y.fp[1].l[i], &b.0.y.fp[1].l[i], choice);
            out.z.fp[0].l[i] =
                u64::conditional_select(&a.0.z.fp[0].l[i], &b.0.z.fp[0].l[i], choice);
            out.z.fp[1].l[i] =
                u64::conditional_select(&a.0.z.fp[1].l[i], &b.0.z.fp[1].l[i], choice);
        }
        Self(out)
    }
}

// -- group: GroupEncoding ---------------------------------------------------

impl GroupEncoding for G2Projective {
    type Repr = G2Compressed;

    fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
        <G2Affine as GroupEncoding>::from_bytes(bytes).map(Self::from)
    }

    fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
        <G2Affine as GroupEncoding>::from_bytes_unchecked(bytes).map(Self::from)
    }

    fn to_bytes(&self) -> Self::Repr {
        <G2Affine as GroupEncoding>::to_bytes(&G2Affine::from(*self))
    }
}

// -- group: Group -----------------------------------------------------------

impl Group for G2Projective {
    type Scalar = BlsScalar;

    fn random(mut rng: impl RngCore) -> Self {
        let mut buf = [0u8; 64];
        rng.fill_bytes(&mut buf);
        let mut out = ::blst::blst_p2::default();
        let dst = b"BLS12381G2_XMD:SHA-256_SSWU_RO_";
        unsafe {
            ::blst::blst_hash_to_g2(
                &raw mut out,
                buf.as_ptr(),
                buf.len(),
                dst.as_ptr(),
                dst.len(),
                core::ptr::null(),
                0,
            )
        };
        Self(out)
    }

    fn identity() -> Self {
        Self::identity()
    }

    fn generator() -> Self {
        Self::generator()
    }

    fn is_identity(&self) -> Choice {
        self.is_identity()
    }

    fn double(&self) -> Self {
        Self::double(self)
    }
}

// -- group: Curve + PrimeCurve + PrimeGroup + WnafGroup ---------------------

impl Curve for G2Projective {
    type AffineRepr = G2Affine;

    fn to_affine(&self) -> Self::AffineRepr {
        G2Affine::from(*self)
    }

    fn batch_normalize(points: &[Self], out: &mut [Self::AffineRepr]) {
        Self::batch_normalize(points, out);
    }
}

impl PrimeCurve for G2Projective {
    type Affine = G2Affine;
}

impl PrimeGroup for G2Projective {}

impl WnafGroup for G2Projective {
    fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize {
        match num_scalars {
            0 => 4,
            1 => 4,
            2..=3 => 5,
            4..=10 => 6,
            11..=32 => 7,
            _ => 8,
        }
    }
}

// -- scalar-on-left multiplication ------------------------------------------

impl Mul<G2Projective> for BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: G2Projective) -> G2Projective {
        rhs * self
    }
}

impl Mul<&G2Projective> for BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: &G2Projective) -> G2Projective {
        rhs * self
    }
}

impl Mul<G2Projective> for &BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: G2Projective) -> G2Projective {
        rhs * self
    }
}

impl Mul<&G2Projective> for &BlsScalar {
    type Output = G2Projective;
    fn mul(self, rhs: &G2Projective) -> G2Projective {
        rhs * self
    }
}

// -- fmt::Display -----------------------------------------------------------

impl fmt::Display for G2Projective {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&G2Affine::from(*self), f)
    }
}

// -- zeroize ----------------------------------------------------------------

#[cfg(feature = "zeroize")]
impl ::zeroize::DefaultIsZeroes for G2Projective {}

// ── Serde support ───────────────────────────────────────────────────────────

#[cfg(feature = "serde")]
mod serde_support {
    extern crate alloc;

    use alloc::format;
    use alloc::string::{String, ToString};

    use serde::de::Error as SerdeError;
    use serde::{self, Deserialize, Deserializer, Serialize, Serializer};

    use super::*;

    fn decode_hex<'de, D, const N: usize>(deserializer: D) -> Result<[u8; N], D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let decoded = hex::decode(&s).map_err(SerdeError::custom)?;
        let decoded_len = decoded.len();
        decoded
            .try_into()
            .map_err(|_| SerdeError::invalid_length(decoded_len, &N.to_string().as_str()))
    }

    impl Serialize for G2Affine {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            hex::encode(dusk_bytes::Serializable::to_bytes(self)).serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for G2Affine {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let bytes = decode_hex::<D, 96>(deserializer)?;
            <Self as dusk_bytes::Serializable<96>>::from_bytes(&bytes)
                .map_err(|err| SerdeError::custom(format!("{err:?}")))
        }
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use dusk_bytes::Serializable;

    fn clear_cofactor_via_dusk_roundtrip(point: &G2Projective) -> G2Projective {
        let bytes = <G2Affine as UncompressedEncoding>::to_uncompressed(&G2Affine::from(*point));
        let dusk_aff = dusk_bls12_381::G2Affine::from_uncompressed_unchecked(&bytes.0).unwrap();
        let cleared = dusk_bls12_381::G2Projective::from(dusk_aff).clear_cofactor();
        let cleared_bytes = dusk_bls12_381::G2Affine::from(cleared).to_uncompressed();
        let blst_aff = <G2Affine as UncompressedEncoding>::from_uncompressed(
            &super::super::G2Uncompressed(cleared_bytes),
        )
        .unwrap();
        G2Projective::from(blst_aff)
    }

    fn non_subgroup_g2_sample() -> G2Projective {
        // Mirrors the dusk torsion-free test vector using the same Montgomery limbs.
        G2Projective::from(G2Affine(::blst::blst_p2_affine {
            x: ::blst::blst_fp2 {
                fp: [
                    ::blst::blst_fp {
                        l: [
                            0x89f5_50c8_13db_6431,
                            0xa50b_e8c4_56cd_8a1a,
                            0xa45b_3741_14ca_e851,
                            0xbb61_90f5_bf7f_ff63,
                            0x970c_a02c_3ba8_0bc7,
                            0x02b8_5d24_e840_fbac,
                        ],
                    },
                    ::blst::blst_fp {
                        l: [
                            0x6888_bc53_d707_16dc,
                            0x3dea_6b41_1768_2d70,
                            0xd8f5_f930_500c_a354,
                            0x6b5e_cb65_56f5_c155,
                            0xc96b_ef04_3477_8ab0,
                            0x0508_1505_5150_06ad,
                        ],
                    },
                ],
            },
            y: ::blst::blst_fp2 {
                fp: [
                    ::blst::blst_fp {
                        l: [
                            0x3cf1_ea0d_434b_0f40,
                            0x1a0d_c610_e603_e333,
                            0x7f89_9561_60c7_2fa0,
                            0x25ee_03de_cf64_31c5,
                            0xeee8_e206_ec0f_e137,
                            0x0975_92b2_26df_ef28,
                        ],
                    },
                    ::blst::blst_fp {
                        l: [
                            0x71e8_bb5f_2924_7367,
                            0xa5fe_049e_2118_31ce,
                            0x0ce6_b354_502a_3896,
                            0x93b0_1200_0997_314e,
                            0x6759_f3b6_aa5b_42ac,
                            0x1569_44c4_dfe9_2bbb,
                        ],
                    },
                ],
            },
        }))
    }

    #[test]
    fn g2_affine_identity_roundtrip() {
        let id = G2Affine::identity();
        let bytes = <G2Affine as Serializable<96>>::to_bytes(&id);
        let decoded =
            <G2Affine as Serializable<96>>::from_bytes(&bytes).expect("identity should roundtrip");
        assert_eq!(id, decoded);
    }

    #[test]
    fn g2_affine_generator_roundtrip() {
        let g = G2Affine::generator();
        let bytes = <G2Affine as Serializable<96>>::to_bytes(&g);
        let decoded =
            <G2Affine as Serializable<96>>::from_bytes(&bytes).expect("generator should roundtrip");
        assert_eq!(g, decoded);
    }

    #[test]
    fn g2_affine_raw_roundtrip() {
        let g = G2Affine::generator();
        let raw = g.to_raw_bytes();
        let decoded = unsafe { G2Affine::from_slice_unchecked(&raw) };
        assert_eq!(g, decoded);
    }

    #[test]
    fn g2_affine_raw_matches_dusk() {
        let dusk_gen = dusk_bls12_381::G2Affine::generator();
        let dusk_id = dusk_bls12_381::G2Affine::identity();
        assert_eq!(
            G2Affine::generator().to_raw_bytes(),
            dusk_gen.to_raw_bytes()
        );
        assert_eq!(G2Affine::identity().to_raw_bytes(), dusk_id.to_raw_bytes());

        let dusk_double = dusk_bls12_381::G2Affine::from(
            dusk_bls12_381::G2Projective::generator() + dusk_bls12_381::G2Projective::generator(),
        );
        let blst_double = G2Affine::from(G2Projective::generator() + G2Projective::generator());
        assert_eq!(blst_double.to_raw_bytes(), dusk_double.to_raw_bytes());
    }

    #[test]
    fn g2_rejects_malformed_encodings() {
        let compressed = [0u8; 96];
        assert!(<G2Affine as Serializable<96>>::from_bytes(&compressed).is_err());
        assert!(!bool::from(
            G2Affine::from_compressed(&compressed).is_some()
        ));
        assert!(!bool::from(
            G2Affine::from_compressed_unchecked(&compressed).is_some()
        ));

        let uncompressed = [0xffu8; 192];
        assert!(!bool::from(
            G2Affine::from_uncompressed(&uncompressed).is_some()
        ));
        assert!(!bool::from(
            G2Affine::from_uncompressed_unchecked(&uncompressed).is_some()
        ));
    }

    #[test]
    fn g2_uncompressed_decoders_reject_compressed_encodings() {
        let compressed = G2Affine::generator().to_compressed();
        let mut uncompressed = [0u8; 192];
        uncompressed[..96].copy_from_slice(&compressed);

        assert!(!bool::from(
            G2Affine::from_uncompressed(&uncompressed).is_some()
        ));
        assert!(!bool::from(
            G2Affine::from_uncompressed_unchecked(&uncompressed).is_some()
        ));
    }

    #[test]
    fn g2_checked_decoders_reject_non_subgroup_points() {
        let affine = G2Affine::from(non_subgroup_g2_sample());
        let compressed = affine.to_compressed();
        let uncompressed = affine.to_uncompressed();

        assert!(<G2Affine as Serializable<96>>::from_bytes(&compressed).is_err());
        assert!(!bool::from(
            G2Affine::from_compressed(&compressed).is_some()
        ));
        assert!(!bool::from(
            G2Affine::from_uncompressed(&uncompressed).is_some()
        ));

        assert_eq!(
            G2Affine::from_compressed_unchecked(&compressed).unwrap(),
            affine
        );
        assert_eq!(
            G2Affine::from_uncompressed_unchecked(&uncompressed).unwrap(),
            affine
        );
    }

    #[test]
    fn g2_projective_eq() {
        let a = G2Projective::generator();
        let b = G2Projective::generator();
        assert_eq!(a, b);
        assert_ne!(a, G2Projective::identity());
    }

    #[test]
    fn g2_projective_add_assign() {
        let g = G2Projective::generator();
        let mut acc = G2Projective::identity();
        acc += g;
        assert_eq!(acc, g);
        acc += g;
        let expected = g + g;
        assert_eq!(acc, expected);
    }

    #[test]
    fn g2_projective_add_assign_ref() {
        let g = G2Projective::generator();
        let mut acc = G2Projective::identity();
        acc += &g;
        assert_eq!(acc, g);
    }

    #[test]
    fn g2_projective_add_affine() {
        let a = G2Affine::generator();
        let p = G2Projective::generator();
        let result = p + a;
        let expected = p + G2Projective::from(a);
        assert_eq!(result, expected);
    }

    #[test]
    fn g2_projective_add_assign_affine() {
        let a = G2Affine::generator();
        let mut p = G2Projective::generator();
        let expected = p + G2Projective::from(a);
        p += a;
        assert_eq!(p, expected);
    }

    #[test]
    fn g2_projective_sub_assign() {
        let g = G2Projective::generator();
        let mut acc = g + g;
        acc -= g;
        assert_eq!(acc, g);
    }

    #[test]
    fn g2_projective_mul_assign() {
        let g = G2Projective::generator();
        let two = BlsScalar::from(2u64);
        let mut p = g;
        p *= two;
        assert_eq!(p, g + g);
    }

    #[test]
    fn g2_projective_mul_assign_ref() {
        let g = G2Projective::generator();
        let two = BlsScalar::from(2u64);
        let mut p = g;
        p *= &two;
        assert_eq!(p, g + g);
    }

    #[test]
    fn g2_projective_sum() {
        let g = G2Projective::generator();
        let pts = [g, g, g];
        let total: G2Projective = pts.iter().copied().sum();
        assert_eq!(total, g + g + g);
    }

    #[test]
    fn g2_projective_sum_refs() {
        let g = G2Projective::generator();
        let pts = [g, g];
        let total: G2Projective = pts.iter().sum();
        assert_eq!(total, g + g);
    }

    #[test]
    fn g2_projective_group_trait() {
        let id = <G2Projective as group::Group>::identity();
        let generator = <G2Projective as group::Group>::generator();
        assert!(bool::from(id.is_identity()));
        assert!(!bool::from(generator.is_identity()));
        assert_eq!(generator.double(), generator + generator);
    }

    #[test]
    fn g2_projective_curve_trait() {
        let p = G2Projective::generator();
        let a = <G2Projective as group::Curve>::to_affine(&p);
        assert_eq!(a, G2Affine::generator());
    }

    #[test]
    fn g2_reference_variants_compile_and_match() {
        let a = G2Projective::generator();
        let b = G2Projective::generator();
        assert_eq!(&a + &b, a + b);
        assert_eq!(-&a, -a);
        assert_eq!(G2Affine::from(&a), G2Affine::from(a));

        let aa = G2Affine::generator();
        let bb = G2Affine::generator();
        assert_eq!(&aa + &bb, aa + bb);
        assert_eq!(&aa - &bb, aa - bb);
    }

    #[test]
    fn g2_affine_conditional_select_choice_0_returns_a() {
        let a = G2Affine::generator();
        let b = G2Affine::identity();
        let sel = G2Affine::conditional_select(&a, &b, Choice::from(0));
        assert_eq!(sel, a);
    }

    #[test]
    fn g2_affine_conditional_select_choice_1_returns_b() {
        let a = G2Affine::generator();
        let b = G2Affine::identity();
        let sel = G2Affine::conditional_select(&a, &b, Choice::from(1));
        assert_eq!(sel, b);
    }

    #[test]
    fn g2_projective_conditional_select() {
        let a = G2Projective::generator();
        let b = G2Projective::identity();
        assert_eq!(G2Projective::conditional_select(&a, &b, Choice::from(0)), a);
        assert_eq!(G2Projective::conditional_select(&a, &b, Choice::from(1)), b);
    }

    #[test]
    fn g2_conditional_select_non_identity_points() {
        let generator = G2Projective::generator();
        let a = generator + generator;
        let b = generator * BlsScalar::from(5u64);
        let sel_a = G2Projective::conditional_select(&a, &b, Choice::from(0));
        let sel_b = G2Projective::conditional_select(&a, &b, Choice::from(1));

        assert_ne!(a, b);
        assert_eq!(sel_a, a);
        assert_eq!(sel_b, b);
        assert_ne!(sel_a, sel_b);

        let a_affine = G2Affine::from(a);
        let b_affine = G2Affine::from(b);
        let sel_a_affine = G2Affine::conditional_select(&a_affine, &b_affine, Choice::from(0));
        let sel_b_affine = G2Affine::conditional_select(&a_affine, &b_affine, Choice::from(1));

        assert_ne!(a_affine, b_affine);
        assert_eq!(sel_a_affine, a_affine);
        assert_eq!(sel_b_affine, b_affine);
        assert_ne!(sel_a_affine, sel_b_affine);
    }

    #[test]
    fn g2_clear_cofactor_matches_dusk() {
        let blst_g = G2Projective::generator();
        let dusk_g = dusk_bls12_381::G2Projective::generator();
        let blst_cleared = G2Affine::from(blst_g.clear_cofactor());
        let dusk_cleared = dusk_bls12_381::G2Affine::from(dusk_g.clear_cofactor());
        assert_eq!(blst_cleared.to_raw_bytes(), dusk_cleared.to_raw_bytes());
        assert!(bool::from(blst_cleared.is_torsion_free()));
    }

    #[test]
    fn g2_clear_cofactor_identity_is_identity() {
        let cleared = G2Projective::identity().clear_cofactor();
        assert!(bool::from(cleared.is_identity()));
    }

    #[test]
    fn g2_clear_cofactor_non_subgroup_matches_dusk_roundtrip() {
        let point = non_subgroup_g2_sample();
        assert!(bool::from(point.is_on_curve()));
        assert!(!bool::from(G2Affine::from(point).is_torsion_free()));

        let blst_cleared = G2Affine::from(point.clear_cofactor());
        let dusk_cleared = G2Affine::from(clear_cofactor_via_dusk_roundtrip(&point));

        assert_eq!(blst_cleared.to_raw_bytes(), dusk_cleared.to_raw_bytes());
        assert!(bool::from(blst_cleared.is_torsion_free()));
    }

    #[test]
    fn g2_affine_inherent_encoding_matches_traits() {
        let g = G2Affine::generator();
        let compressed = g.to_compressed();
        let uncompressed = g.to_uncompressed();
        assert_eq!(compressed, <G2Affine as Serializable<96>>::to_bytes(&g));
        assert_eq!(
            uncompressed,
            <G2Affine as UncompressedEncoding>::to_uncompressed(&g).0
        );
        assert_eq!(G2Affine::from_compressed(&compressed).unwrap(), g);
        assert_eq!(G2Affine::from_compressed_unchecked(&compressed).unwrap(), g);
        assert_eq!(G2Affine::from_uncompressed(&uncompressed).unwrap(), g);
        assert_eq!(
            G2Affine::from_uncompressed_unchecked(&uncompressed).unwrap(),
            g
        );
    }

    #[test]
    fn g2_projective_inherent_arithmetic_matches_trait_impl() {
        let g = G2Projective::generator();
        assert_eq!(g.double(), g + g);
        assert_eq!(g.add(&g), g + g);
        let g_aff = G2Affine::generator();
        assert_eq!(g.add_mixed(&g_aff), g + G2Projective::from(g_aff));
        assert!(bool::from(g.is_on_curve()));
    }

    #[cfg(feature = "zeroize")]
    #[test]
    fn g2_zeroize_resets_points_to_default() {
        use zeroize::Zeroize;

        let mut affine = G2Affine::generator();
        affine.zeroize();
        assert_eq!(affine, G2Affine::default());

        let mut projective = G2Projective::generator();
        projective.zeroize();
        assert_eq!(projective, G2Projective::default());
    }
}