bbs_plus 0.25.0

BBS, BBS+, threshold BBS+ signatures and protocols for proof of knowledge of signature
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
//! Proof of knowledge of BBS+ signature and corresponding messages as per section 4.5 of the BBS+ paper
//! # Examples
//!
//! Creating proof of knowledge of signature and verifying it:
//!
//! ```
//! use ark_bls12_381::Bls12_381;
//! use bbs_plus::setup::{SignatureParamsG1, KeypairG2};
//! use bbs_plus::signature::SignatureG1;
//! use bbs_plus::proof::PoKOfSignatureG1Protocol;
//! use ark_std::collections::{BTreeSet, BTreeMap};
//!
//! let params_g1 = SignatureParamsG1::<Bls12_381>::generate_using_rng(&mut rng, 5);
//! let keypair_g2 = KeypairG2::<Bls12_381>::generate(&mut rng, &params_g1);
//!
//! let pk_g2 = &keypair_g2.public_key;
//!
//! // Verifiers should check that the signature parameters and public key are valid before verifying
//! // any signatures. This just needs to be done once when the verifier fetches/receives them.
//!
//! assert!(params_g1.is_valid());
//! assert!(pk_g2.is_valid());
//!
//! // `messages` contains elements of the scalar field
//! let sig_g1 = SignatureG1::<Bls12_381>::new(&mut rng, &messages, &keypair_g2.secret_key, &params_g1).unwrap();
//!
//! let mut blindings = BTreeMap::new();
//! let mut revealed_indices = BTreeSet::new();
//!
//! // Populate `blindings` with message index and corresponding blinding
//! // Populate `revealed_indices` with 0-based indices of revealed messages
//!
//! let pok = PoKOfSignatureG1Protocol::init(
//!             &mut rng,
//!             &sig_g1,
//!             &params_g1,
//!             &messages,
//!             blindings,
//!             &revealed_indices,
//!         )
//!         .unwrap();
//!
//! // challenge is generated (see tests)
//! let proof = pok.gen_proof(&challenge).unwrap();
//!
//! let mut revealed_msgs = BTreeMap::new();
//! proof
//!             .verify(
//!                 &revealed_msgs,
//!                 &challenge,
//!                 pk_g2,
//!                 &params_g1,
//!             )
//!             .unwrap();
//!
//! // See tests for more examples
//! ```
use crate::{
    error::BBSPlusError,
    prelude::PreparedPublicKeyG2,
    setup::{PreparedSignatureParamsG1, SignatureParamsG1},
    signature::SignatureG1,
};
use ark_ec::{pairing::Pairing, AffineRepr, CurveGroup, Group, VariableBaseMSM};
use ark_ff::{Field, PrimeField, Zero};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::{
    collections::{BTreeMap, BTreeSet},
    fmt::Debug,
    io::Write,
    rand::RngCore,
    vec::Vec,
    UniformRand,
};
use core::mem;
use dock_crypto_utils::{
    misc::rand,
    randomized_pairing_check::RandomizedPairingChecker,
    serde_utils::*,
    signature::{
        msg_index_map_to_schnorr_response_map, msg_index_to_schnorr_response_index,
        schnorr_responses_to_msg_index_map, split_messages_and_blindings, MessageOrBlinding,
        MultiMessageSignatureParams,
    },
};
use itertools::multiunzip;
use schnorr_pok::{
    discrete_log::{PokPedersenCommitment, PokPedersenCommitmentProtocol},
    error::SchnorrError,
    partial::PartialSchnorrResponse,
    SchnorrCommitment, SchnorrResponse,
};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use zeroize::{Zeroize, ZeroizeOnDrop};

/// Protocol to prove knowledge of BBS+ signature in group G1.
/// The BBS+ signature proves validity of a set of messages `m_i`, `i` in `I`. This stateful protocol proves knowledge of such
/// a signature whilst selectively disclosing only a subset of the messages, `m_i` for `i` in a disclosed set `D`. The
/// protocol randomizes the initial BBS+ signature, then conducts 2 Schnorr PoK protocols to prove exponent knowledge
/// for the relations in section 4.5 of the paper (refer to top). It contains commitments (Schnorr step 1; refer to schnorr_pok)
/// and witnesses to both Schnorr protocols in `sc_comm_` and `sc_wits_` respectively. The protocol executes in 2 phases,
/// pre-challenge (`init`) which is used to create the challenge and post-challenge (`gen_proof`). Thus, several instances of
/// the protocol can be used together where the pre-challenge phase of all protocols is used to create a combined challenge
/// and then that challenge is used in post-challenge phase of all protocols.
#[serde_as]
#[derive(
    Clone,
    PartialEq,
    Eq,
    Debug,
    Zeroize,
    ZeroizeOnDrop,
    CanonicalSerialize,
    CanonicalDeserialize,
    Serialize,
    Deserialize,
)]
pub struct PoKOfSignatureG1Protocol<E: Pairing> {
    #[zeroize(skip)]
    #[serde_as(as = "ArkObjectBytes")]
    pub A_prime: E::G1Affine,
    #[zeroize(skip)]
    #[serde_as(as = "ArkObjectBytes")]
    pub A_bar: E::G1Affine,
    #[zeroize(skip)]
    #[serde_as(as = "ArkObjectBytes")]
    pub d: E::G1Affine,
    /// For proving relation `A_bar - d = A_prime * -e + h_0 * r2`
    pub sc_comm_1: PokPedersenCommitmentProtocol<E::G1Affine>,
    /// For proving relation `g1 + \sum_{i in D}(h_i*m_i)` = `d*r3 + {h_0}*{-s'} + sum_{j notin D}(h_j*m_j)`
    pub sc_comm_2: SchnorrCommitment<E::G1Affine>,
    #[serde_as(as = "Vec<ArkObjectBytes>")]
    sc_wits_2: Vec<E::ScalarField>,
}

/// Proof of knowledge of BBS+ signature in G1. It contains the randomized signature, commitment (Schnorr step 1)
/// and response (Schnorr step 3) to both Schnorr protocols in `T_` and `sc_resp_`
#[serde_as]
#[derive(
    Clone, PartialEq, Eq, Debug, CanonicalSerialize, CanonicalDeserialize, Serialize, Deserialize,
)]
pub struct PoKOfSignatureG1Proof<E: Pairing> {
    #[serde_as(as = "ArkObjectBytes")]
    pub A_prime: E::G1Affine,
    #[serde_as(as = "ArkObjectBytes")]
    pub A_bar: E::G1Affine,
    #[serde_as(as = "ArkObjectBytes")]
    pub d: E::G1Affine,
    /// Proof of relation `A_bar - d = A_prime * -e + h_0 * r2`
    pub sc_resp_1: PokPedersenCommitment<E::G1Affine>,
    /// Proof of relation `g1 + h1*m1 + h2*m2 +.... + h_i*m_i` = `d*r3 + {h_0}*{-s'} + h1*{-m1} + h2*{-m2} + .... + h_j*{-m_j}` for all disclosed messages `m_i` and for all undisclosed messages `m_j`
    #[serde_as(as = "ArkObjectBytes")]
    pub T2: E::G1Affine,
    /// The following could be achieved by using Either<SchnorrResponse, PartialSchnorrResponse> but serialization
    /// for Either is not supported out of the box and had to be implemented
    pub sc_resp_2: Option<SchnorrResponse<E::G1Affine>>,
    pub sc_partial_resp_2: Option<PartialSchnorrResponse<E::G1Affine>>,
}

impl<E: Pairing> PoKOfSignatureG1Protocol<E> {
    /// Initiate the protocol, i.e. pre-challenge phase. This will generate the randomized signature and execute
    /// the commit-to-randomness step (Step 1) of both Schnorr protocols.
    /// Accepts an iterator of messages. Each message can be either randomly blinded, revealed, or blinded using supplied blinding.
    pub fn init<'a, MBI, R: RngCore>(
        rng: &mut R,
        signature: &SignatureG1<E>,
        params: &SignatureParamsG1<E>,
        messages_and_blindings: MBI,
    ) -> Result<Self, BBSPlusError>
    where
        MBI: IntoIterator<Item = MessageOrBlinding<'a, E::ScalarField>>,
    {
        let (messages, indexed_blindings) =
            match split_messages_and_blindings(rng, messages_and_blindings, params) {
                Ok(t) => t,
                Err(l) => {
                    return Err(BBSPlusError::MessageCountIncompatibleWithSigParams(
                        l,
                        params.supported_message_count(),
                    ))
                }
            };

        let mut r1 = E::ScalarField::rand(rng);
        while r1.is_zero() {
            r1 = E::ScalarField::rand(rng);
        }
        let r2 = E::ScalarField::rand(rng);
        let r3 = r1.inverse().unwrap();

        // b = (e+x) * A = g1 + h_0*s + sum(h_i*m_i) for all i in I
        let b = params.b(messages.iter().enumerate(), &signature.s)?;

        // A' = A * r1
        let A_prime = signature.A.mul_bigint(r1.into_bigint());
        // A_bar = r1 * b - e * A'
        let b_r1 = b * r1;
        let A_bar = b_r1 - (A_prime.mul_bigint(signature.e.into_bigint()));
        // d = r1 * b - r2 * h_0
        let d = b_r1 - params.h_0.mul_bigint(r2.into_bigint());
        let d_affine = d.into_affine();
        // s' = s - r2*r3
        let s_prime = signature.s - (r2 * r3);

        // Following is the 1st step of the Schnorr protocol for the relation pi in the paper. pi is a
        // conjunction of 2 relations:
        // 1. `A_bar - d == A'*{-e} + h_0*r2`
        // 2. `g1 + \sum_{i \in D}(h_i*m_i)` = `d*r3 + {h_0}*{-s'} + \sum_{j \notin D}(h_j*{-m_j})`
        // for all disclosed messages `m_i` and for all undisclosed messages `m_j`.
        // For each of the above relations, a Schnorr protocol is executed; the first to prove knowledge
        // of `(e, r2)`, and the second of `(r3, s', {m_j}_{j \notin D})`. The secret knowledge items are
        // referred to as witnesses, and the public items as instances.
        let A_prime_affine = A_prime.into_affine();

        // Commit to randomness with `h_0` and `A'`, i.e. `bases_1[0]*randomness_1[0] + bases_1[1]*randomness_1[1]`
        let sc_comm_1 = PokPedersenCommitmentProtocol::init(
            -signature.e,
            E::ScalarField::rand(rng),
            &A_prime_affine,
            r2,
            E::ScalarField::rand(rng),
            &params.h_0,
        );

        // For proving relation `g1 + \sum_{i \in D}(h_i*m_i)` = `d*r3 + {h_0}*{-s_prime} + \sum_{j \notin D}(h_j*{-m_j})`
        // for all disclosed messages `m_i` and for all undisclosed messages `m_j`, usually the number of disclosed
        // messages is much less than the number of undisclosed messages; so it is better to avoid negations in
        // undisclosed messages and do them in disclosed messaged. So negate both sides of the relation to get:
        // `d*{-r3} + h_0*s_prime + \sum_{j \notin D}(h_j*m_j)` = `-g1 + \sum_{i \in D}(h_i*{-m_i})`
        // Moreover `-g1 + \sum_{i \in D}(h_i*{-m_i})` is public and can be efficiently computed as -(g1 + \sum_{i \in D}(h_i*{m_i}))
        // Knowledge of all unrevealed messages `m_j` need to be proven in addition to knowledge of `-r3` and `s'`. Thus
        // all `m_j`, `-r3` and `s'` are the witnesses, while all `h_j`, `d`, `h_0` and `-g1 + \sum_{i \in D}(h_i*{-m_i})` is the instance.

        // Iterator of tuples of form `(h_i, blinding_i, message_i)`
        let h_blinding_message = indexed_blindings
            .into_iter()
            .map(|(idx, blinding)| (params.h[idx], blinding, messages[idx]));

        let (bases_2, randomness_2, wits_2): (Vec<_>, Vec<_>, Vec<_>) = multiunzip(
            h_blinding_message
                .into_iter()
                .chain([(d_affine, rand(rng), -r3), (params.h_0, rand(rng), s_prime)]),
        );

        // Commit to randomness, i.e. `bases_2[0]*randomness_2[0] + bases_2[1]*randomness_2[1] + .... bases_2[j]*randomness_2[j]`
        let sc_comm_2 = SchnorrCommitment::new(&bases_2, randomness_2);

        Ok(Self {
            A_prime: A_prime_affine,
            A_bar: A_bar.into_affine(),
            d: d_affine,
            sc_comm_1,
            sc_comm_2,
            sc_wits_2: wits_2,
        })
    }

    /// Get the contribution of this protocol towards the challenge, i.e. bytecode of items that will be hashed
    pub fn challenge_contribution<W: Write>(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        params: &SignatureParamsG1<E>,
        writer: W,
    ) -> Result<(), BBSPlusError> {
        Self::compute_challenge_contribution(
            &self.A_prime,
            &self.A_bar,
            &self.d,
            &self.sc_comm_1.t,
            &self.sc_comm_2.t,
            revealed_msgs,
            params,
            writer,
        )
    }

    /// Generate proof. Post-challenge phase of the protocol.
    pub fn gen_proof(
        mut self,
        challenge: &E::ScalarField,
    ) -> Result<PoKOfSignatureG1Proof<E>, BBSPlusError> {
        // Schnorr response for relation `A_bar - d == A'*{-e} + h_0*r2`
        let sc_resp_1 = mem::take(&mut self.sc_comm_1).gen_proof(challenge);
        // Schnorr response for relation `g1 + \sum_{i in D}(h_i*m_i)` = `d*r3 + {h_0}*{-s'} + \sum_{j not in D}(h_j*{-m_j})`
        let sc_resp_2 = self.sc_comm_2.response(&self.sc_wits_2, challenge)?;

        Ok(PoKOfSignatureG1Proof {
            A_prime: self.A_prime,
            A_bar: self.A_bar,
            d: self.d,
            sc_resp_1,
            T2: self.sc_comm_2.t,
            sc_resp_2: Some(sc_resp_2),
            sc_partial_resp_2: None,
        })
    }

    /// Generate a partial proof, i.e. don't generate responses for message indices in `skip_responses_for` as these will be
    /// generated by some other protocol.
    pub fn gen_partial_proof(
        mut self,
        challenge: &E::ScalarField,
        revealed_msg_ids: &BTreeSet<usize>,
        skip_responses_for: &BTreeSet<usize>,
    ) -> Result<PoKOfSignatureG1Proof<E>, BBSPlusError> {
        if !skip_responses_for.is_disjoint(revealed_msg_ids) {
            return Err(BBSPlusError::CommonIndicesFoundInRevealedAndSkip);
        }
        // Schnorr response for relation `A_bar - d == A'*{-e} + h_0*r2`
        let sc_resp_1 = mem::take(&mut self.sc_comm_1).gen_proof(challenge);

        let wits = schnorr_responses_to_msg_index_map(
            mem::take(&mut self.sc_wits_2),
            revealed_msg_ids,
            skip_responses_for,
        );
        // Schnorr response for relation `g1 + \sum_{i in D}(h_i*m_i)` = `d*r3 + {h_0}*{-s'} + \sum_{j not in D}(h_j*{-m_j})`
        let sc_resp_2 = self.sc_comm_2.partial_response(wits, challenge)?;

        Ok(PoKOfSignatureG1Proof {
            A_prime: self.A_prime,
            A_bar: self.A_bar,
            d: self.d,
            sc_resp_1,
            T2: self.sc_comm_2.t,
            sc_resp_2: None,
            sc_partial_resp_2: Some(sc_resp_2),
        })
    }

    /// Helper that serializes state to get challenge contribution. Serialized the randomized signature,
    /// and commitments and instances for both Schnorr protocols
    pub fn compute_challenge_contribution<W: Write>(
        A_prime: &E::G1Affine,
        A_bar: &E::G1Affine,
        d: &E::G1Affine,
        T1: &E::G1Affine,
        T2: &E::G1Affine,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        params: &SignatureParamsG1<E>,
        mut writer: W,
    ) -> Result<(), BBSPlusError> {
        A_prime.serialize_compressed(&mut writer)?;
        A_bar.serialize_compressed(&mut writer)?;
        d.serialize_compressed(&mut writer)?;
        params.h_0.serialize_compressed(&mut writer)?;
        params.g1.serialize_compressed(&mut writer)?;
        T1.serialize_compressed(&mut writer)?;
        T2.serialize_compressed(&mut writer)?;
        for i in 0..params.h.len() {
            params.h[i].serialize_compressed(&mut writer)?;
            if let Some(m) = revealed_msgs.get(&i) {
                m.serialize_compressed(&mut writer)?;
            }
        }
        Ok(())
    }
}

impl<E: Pairing> PoKOfSignatureG1Proof<E> {
    /// Verify if the proof is valid. Assumes that the public key and parameters have been
    /// validated already.
    pub fn verify(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        pk: impl Into<PreparedPublicKeyG2<E>>,
        params: impl Into<PreparedSignatureParamsG1<E>>,
    ) -> Result<(), BBSPlusError> {
        self._verify(revealed_msgs, challenge, pk, params, None)
    }

    pub fn verify_with_randomized_pairing_checker(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        pk: impl Into<PreparedPublicKeyG2<E>>,
        params: impl Into<PreparedSignatureParamsG1<E>>,
        pairing_checker: &mut RandomizedPairingChecker<E>,
    ) -> Result<(), BBSPlusError> {
        self._verify_with_randomized_pairing_checker(
            revealed_msgs,
            challenge,
            pk,
            params,
            pairing_checker,
            None,
        )
    }

    /// Similar to `Self::verify` but responses for some messages (witnesses) are provided in `missing_responses`.
    /// The keys of the map are message indices.
    pub fn verify_partial(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        pk: impl Into<PreparedPublicKeyG2<E>>,
        params: impl Into<PreparedSignatureParamsG1<E>>,
        missing_responses: BTreeMap<usize, E::ScalarField>,
    ) -> Result<(), BBSPlusError> {
        self._verify(
            revealed_msgs,
            challenge,
            pk,
            params,
            Some(missing_responses),
        )
    }

    /// Similar to `Self::verify_with_randomized_pairing_checker` but responses for some messages (witnesses) are provided in `missing_responses`.
    /// The keys of the map are message indices.
    pub fn verify_partial_with_randomized_pairing_checker(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        pk: impl Into<PreparedPublicKeyG2<E>>,
        params: impl Into<PreparedSignatureParamsG1<E>>,
        pairing_checker: &mut RandomizedPairingChecker<E>,
        missing_responses: BTreeMap<usize, E::ScalarField>,
    ) -> Result<(), BBSPlusError> {
        self._verify_with_randomized_pairing_checker(
            revealed_msgs,
            challenge,
            pk,
            params,
            pairing_checker,
            Some(missing_responses),
        )
    }

    /// For the verifier to independently calculate the challenge
    pub fn challenge_contribution<W: Write>(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        params: &SignatureParamsG1<E>,
        writer: W,
    ) -> Result<(), BBSPlusError> {
        PoKOfSignatureG1Protocol::compute_challenge_contribution(
            &self.A_prime,
            &self.A_bar,
            &self.d,
            &self.sc_resp_1.t,
            &self.T2,
            revealed_msgs,
            params,
            writer,
        )
    }

    /// Get the response from post-challenge phase of the Schnorr protocol for the given message index
    /// `msg_idx`. Used when comparing message equality
    pub fn get_resp_for_message(
        &self,
        msg_idx: usize,
        revealed_msg_ids: &BTreeSet<usize>,
    ) -> Result<&E::ScalarField, BBSPlusError> {
        let adjusted_idx = msg_index_to_schnorr_response_index(msg_idx, revealed_msg_ids)
            .ok_or_else(|| BBSPlusError::InvalidMsgIdxForResponse(msg_idx))?;
        if let Some(resp) = self.sc_resp_2.as_ref() {
            Ok(resp.get_response(adjusted_idx)?)
        } else if let Some(resp) = self.sc_partial_resp_2.as_ref() {
            Ok(resp.get_response(adjusted_idx)?)
        } else {
            Err(BBSPlusError::NeedEitherPartialOrCompleteSchnorrResponse)
        }
    }

    pub fn get_responses(
        &self,
        msg_ids: &BTreeSet<usize>,
        revealed_msg_ids: &BTreeSet<usize>,
    ) -> Result<BTreeMap<usize, E::ScalarField>, BBSPlusError> {
        let mut resps = BTreeMap::new();
        for msg_idx in msg_ids {
            resps.insert(
                *msg_idx,
                *self.get_resp_for_message(*msg_idx, revealed_msg_ids)?,
            );
        }
        Ok(resps)
    }

    pub fn _verify(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        pk: impl Into<PreparedPublicKeyG2<E>>,
        params: impl Into<PreparedSignatureParamsG1<E>>,
        missing_responses: Option<BTreeMap<usize, E::ScalarField>>,
    ) -> Result<(), BBSPlusError> {
        let params = params.into();
        let g1 = params.g1;
        let g2 = params.g2;
        let h0 = params.h_0;
        let h = params.h;
        self.verify_except_pairings(revealed_msgs, challenge, g1, h0, h, missing_responses)?;

        // Verify the randomized signature
        if !E::multi_pairing(
            [
                E::G1Prepared::from(self.A_prime),
                E::G1Prepared::from(-(self.A_bar.into_group())),
            ],
            [pk.into().0, g2],
        )
        .is_zero()
        {
            return Err(BBSPlusError::PairingCheckFailed);
        }
        Ok(())
    }

    pub fn _verify_with_randomized_pairing_checker(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        pk: impl Into<PreparedPublicKeyG2<E>>,
        params: impl Into<PreparedSignatureParamsG1<E>>,
        pairing_checker: &mut RandomizedPairingChecker<E>,
        missing_responses: Option<BTreeMap<usize, E::ScalarField>>,
    ) -> Result<(), BBSPlusError> {
        let params = params.into();
        let g1 = params.g1;
        let g2 = params.g2;
        let h0 = params.h_0;
        let h = params.h;
        self.verify_except_pairings(revealed_msgs, challenge, g1, h0, h, missing_responses)?;
        pairing_checker.add_sources(&self.A_prime, pk.into().0, &self.A_bar, g2);
        Ok(())
    }

    /// Verify the proof except the pairing equations. This is useful when doing several verifications (of this
    /// protocol or others) and the pairing equations are combined in a randomized pairing check.
    fn verify_except_pairings(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        g1: E::G1Affine,
        h_0: E::G1Affine,
        h: Vec<E::G1Affine>,
        missing_responses: Option<BTreeMap<usize, E::ScalarField>>,
    ) -> Result<(), BBSPlusError> {
        if self.A_prime.is_zero() {
            return Err(BBSPlusError::ZeroSignature);
        }
        self.verify_schnorr_proofs(revealed_msgs, challenge, g1, h_0, h, missing_responses)
    }

    pub fn verify_schnorr_proofs(
        &self,
        revealed_msgs: &BTreeMap<usize, E::ScalarField>,
        challenge: &E::ScalarField,
        g1: E::G1Affine,
        h_0: E::G1Affine,
        h: Vec<E::G1Affine>,
        missing_responses: Option<BTreeMap<usize, E::ScalarField>>,
    ) -> Result<(), BBSPlusError> {
        // Verify the 1st Schnorr proof
        // A_bar - d
        let A_bar_minus_d = (self.A_bar.into_group() - self.d.into_group()).into_affine();
        if !self
            .sc_resp_1
            .verify(&A_bar_minus_d, &self.A_prime, &h_0, challenge)
        {
            return Err(BBSPlusError::FirstSchnorrVerificationFailed);
        }

        // Verify the 2nd Schnorr proof
        let mut bases_2 = Vec::with_capacity(2 + h.len() - revealed_msgs.len());

        let mut bases_revealed = Vec::with_capacity(revealed_msgs.len());
        let mut exponents = Vec::with_capacity(revealed_msgs.len());
        for i in 0..h.len() {
            if revealed_msgs.contains_key(&i) {
                let message = revealed_msgs.get(&i).unwrap();
                bases_revealed.push(h[i]);
                exponents.push(*message);
            } else {
                bases_2.push(h[i]);
            }
        }
        bases_2.push(self.d);
        bases_2.push(h_0);
        // pr = -g1 + \sum_{i in D}(h_i*{-m_i}) = -(g1 + \sum_{i in D}(h_i*{m_i}))
        let pr = -E::G1::msm_unchecked(&bases_revealed, &exponents) - g1;
        let pr = pr.into_affine();
        if let Some(resp) = &self.sc_resp_2 {
            if missing_responses.is_some() {
                return Err(BBSPlusError::MissingResponsesProvidedForFullSchnorrProofVerification);
            }
            return match resp.is_valid(&bases_2, &pr, &self.T2, challenge) {
                Ok(()) => Ok(()),
                Err(SchnorrError::InvalidResponse) => {
                    Err(BBSPlusError::SecondSchnorrVerificationFailed)
                }
                Err(other) => Err(BBSPlusError::SchnorrError(other)),
            };
        } else if let Some(resp) = &self.sc_partial_resp_2 {
            if missing_responses.is_none() {
                return Err(BBSPlusError::MissingResponsesNeededForPartialSchnorrProofVerification);
            }
            let adjusted_missing = msg_index_map_to_schnorr_response_map(
                missing_responses.unwrap(),
                revealed_msgs.keys(),
            );
            return match resp.is_valid(&bases_2, &pr, &self.T2, challenge, adjusted_missing) {
                Ok(()) => Ok(()),
                Err(SchnorrError::InvalidResponse) => {
                    Err(BBSPlusError::SecondSchnorrVerificationFailed)
                }
                Err(other) => Err(BBSPlusError::SchnorrError(other)),
            };
        } else {
            Err(BBSPlusError::NeedEitherPartialOrCompleteSchnorrResponse)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{setup::KeypairG2, test_serialization};
    use ark_bls12_381::Bls12_381;
    use ark_serialize::CanonicalDeserialize;
    use ark_std::{
        rand::{rngs::StdRng, SeedableRng},
        UniformRand,
    };
    use blake2::Blake2b512;
    use schnorr_pok::compute_random_oracle_challenge;
    use std::time::{Duration, Instant};

    type Fr = <Bls12_381 as Pairing>::ScalarField;

    fn sig_setup<R: RngCore>(
        rng: &mut R,
        message_count: u32,
    ) -> (
        Vec<Fr>,
        SignatureParamsG1<Bls12_381>,
        KeypairG2<Bls12_381>,
        SignatureG1<Bls12_381>,
    ) {
        let messages: Vec<Fr> = (0..message_count).map(|_| Fr::rand(rng)).collect();
        let params = SignatureParamsG1::<Bls12_381>::generate_using_rng(rng, message_count);
        let keypair = KeypairG2::<Bls12_381>::generate_using_rng(rng, &params);
        let sig =
            SignatureG1::<Bls12_381>::new(rng, &messages, &keypair.secret_key, &params).unwrap();
        (messages, params, keypair, sig)
    }

    #[macro_export]
    macro_rules! gen_test_pok_signature_revealed_message {
        ($protocol: ident, $proof: ident) => {{
            // Create and verify proof of knowledge of a signature when some messages are revealed
            let mut rng = StdRng::seed_from_u64(0u64);
            let message_count = 20;
            let (messages, params, keypair, sig) = sig_setup(&mut rng, message_count);
            sig.verify(&messages, keypair.public_key.clone(), params.clone())
                .unwrap();

            let mut revealed_indices = BTreeSet::new();
            revealed_indices.insert(0);
            revealed_indices.insert(2);

            let mut revealed_msgs = BTreeMap::new();
            for i in revealed_indices.iter() {
                revealed_msgs.insert(*i, messages[*i]);
            }

            let mut proof_create_duration = Duration::default();
            let start = Instant::now();
            let pok = $protocol::init(
                &mut rng,
                &sig,
                &params,
                messages.iter().enumerate().map(|(idx, msg)| {
                    if revealed_indices.contains(&idx) {
                        MessageOrBlinding::RevealMessage(msg)
                    } else {
                        MessageOrBlinding::BlindMessageRandomly(msg)
                    }
                }),
            )
            .unwrap();
            proof_create_duration += start.elapsed();

            // Protocol can be serialized
            test_serialization!($protocol<Bls12_381>, pok);

            let start = Instant::now();
            let mut chal_bytes_prover = vec![];
            keypair
                .public_key
                .serialize_compressed(&mut chal_bytes_prover)
                .unwrap();
            pok.challenge_contribution(&revealed_msgs, &params, &mut chal_bytes_prover)
                .unwrap();
            let challenge_prover =
                compute_random_oracle_challenge::<Fr, Blake2b512>(&chal_bytes_prover);

            let proof = pok.gen_proof(&challenge_prover).unwrap();
            proof_create_duration += start.elapsed();

            let public_key = &keypair.public_key;
            assert!(params.is_valid());
            assert!(public_key.is_valid());

            let start = Instant::now();
            let mut chal_bytes_verifier = vec![];
            keypair
                .public_key
                .serialize_compressed(&mut chal_bytes_verifier)
                .unwrap();
            proof
                .challenge_contribution(&revealed_msgs, &params, &mut chal_bytes_verifier)
                .unwrap();
            let challenge_verifier =
                compute_random_oracle_challenge::<Fr, Blake2b512>(&chal_bytes_verifier);

            assert_eq!(chal_bytes_prover, chal_bytes_verifier);
            proof
                .verify(
                    &revealed_msgs,
                    &challenge_verifier,
                    public_key.clone(),
                    params.clone(),
                )
                .unwrap();
            let proof_verif_duration = start.elapsed();

            // Proof can be serialized
            test_serialization!($proof<Bls12_381>, proof);

            println!(
                "Time to create proof with message size {} and revealing {} messages is {:?}",
                message_count,
                revealed_indices.len(),
                proof_create_duration
            );
            println!(
                "Time to verify proof with message size {} and revealing {} messages is {:?}",
                message_count,
                revealed_indices.len(),
                proof_verif_duration
            );
        }};
    }

    #[macro_export]
    macro_rules! gen_test_PoK_multiple_sigs_with_same_msg {
        ($params: ident, $sig: ident, $fn_name: ident, $protocol: ident) => {{
            // Prove knowledge of multiple signatures and the equality of a specific message under both signatures.
            // Knowledge of 2 signatures and their corresponding messages is being proven.

            let mut rng = StdRng::seed_from_u64(0u64);
            let message_1_count = 10;
            let message_2_count = 9;
            let message_3_count = 8;
            let params_1 =
                $params::<Bls12_381>::new::<Blake2b512>("test".as_bytes(), message_1_count);
            let params_2 =
                $params::<Bls12_381>::new::<Blake2b512>("test-1".as_bytes(), message_2_count);
            let params_3 =
                $params::<Bls12_381>::new::<Blake2b512>("test-2".as_bytes(), message_3_count);
            let keypair_1 = KeypairG2::<Bls12_381>::$fn_name(&mut rng, &params_1);
            let keypair_2 = KeypairG2::<Bls12_381>::$fn_name(&mut rng, &params_2);
            let keypair_3 = KeypairG2::<Bls12_381>::$fn_name(&mut rng, &params_3);

            let same_msg_idx = BTreeSet::from([0, 3, 4, 7]);
            let mut messages_1: Vec<Fr> = (0..message_1_count - same_msg_idx.len() as u32)
                .map(|_| Fr::rand(&mut rng))
                .collect();
            let mut messages_2: Vec<Fr> = (0..message_2_count - same_msg_idx.len() as u32)
                .map(|_| Fr::rand(&mut rng))
                .collect();
            let mut messages_3: Vec<Fr> = (0..message_3_count - same_msg_idx.len() as u32)
                .map(|_| Fr::rand(&mut rng))
                .collect();

            let same_msgs = same_msg_idx.clone().into_iter().map(|i| (i, Fr::rand(&mut rng))).collect::<BTreeMap<usize, Fr>>();
            for (i, m) in &same_msgs {
                messages_1.insert(*i, m.clone());
                messages_2.insert(*i, m.clone());
                messages_3.insert(*i, m.clone());
            }

            let sig_1 =
                $sig::<Bls12_381>::new(&mut rng, &messages_1, &keypair_1.secret_key, &params_1)
                    .unwrap();
            sig_1
                .verify(&messages_1, keypair_1.public_key.clone(), params_1.clone())
                .unwrap();

            let sig_2 =
                $sig::<Bls12_381>::new(&mut rng, &messages_2, &keypair_2.secret_key, &params_2)
                    .unwrap();
            sig_2
                .verify(&messages_2, keypair_2.public_key.clone(), params_2.clone())
                .unwrap();

            let sig_3 =
                $sig::<Bls12_381>::new(&mut rng, &messages_3, &keypair_3.secret_key, &params_3)
                    .unwrap();
            sig_3
                .verify(&messages_3, keypair_3.public_key.clone(), params_3.clone())
                .unwrap();

            let revealed_indices = BTreeSet::from([2, 5, 6]);

            let mut revealed_msgs_1 = BTreeMap::new();
            let mut revealed_msgs_2 = BTreeMap::new();
            let mut revealed_msgs_3 = BTreeMap::new();
            for i in revealed_indices.iter() {
                revealed_msgs_1.insert(*i, messages_1[*i]);
                revealed_msgs_2.insert(*i, messages_2[*i]);
                revealed_msgs_3.insert(*i, messages_3[*i]);
            }

            // Add the same blinding for the message which has to be proven equal across signatures
            let same_blindings = same_msg_idx.clone().into_iter().map(|i| (i, Fr::rand(&mut rng))).collect::<BTreeMap<usize, Fr>>();

            let mut blindings_1 = BTreeMap::new();
            let mut blindings_2 = BTreeMap::new();
            let mut blindings_3 = BTreeMap::new();
            for (i, b) in &same_blindings {
                blindings_1.insert(*i, *b);
                blindings_2.insert(*i, *b);
                blindings_3.insert(*i, *b);
            }

            // Add some more blindings randomly,
            blindings_1.insert(1, Fr::rand(&mut rng));
            blindings_3.insert(2, Fr::rand(&mut rng));

            let pok_1 = $protocol::init(
                &mut rng,
                &sig_1,
                &params_1,
                messages_1.iter().enumerate().map(|(idx, message)| {
                    if revealed_indices.contains(&idx) {
                        MessageOrBlinding::RevealMessage(message)
                    } else if let Some(blinding) = blindings_1.remove(&idx) {
                        MessageOrBlinding::BlindMessageWithConcreteBlinding { message, blinding }
                    } else {
                        MessageOrBlinding::BlindMessageRandomly(message)
                    }
                }),
            )
            .unwrap();
            let pok_2 = $protocol::init(
                &mut rng,
                &sig_2,
                &params_2,
                messages_2.iter().enumerate().map(|(idx, message)| {
                    if revealed_indices.contains(&idx) {
                        MessageOrBlinding::RevealMessage(message)
                    } else if let Some(blinding) = blindings_2.remove(&idx) {
                        MessageOrBlinding::BlindMessageWithConcreteBlinding { message, blinding }
                    } else {
                        MessageOrBlinding::BlindMessageRandomly(message)
                    }
                }),
            )
            .unwrap();
            let pok_3 = $protocol::init(
                &mut rng,
                &sig_3,
                &params_3,
                messages_3.iter().enumerate().map(|(idx, message)| {
                    if revealed_indices.contains(&idx) {
                        MessageOrBlinding::RevealMessage(message)
                    } else if let Some(blinding) = blindings_3.remove(&idx) {
                        MessageOrBlinding::BlindMessageWithConcreteBlinding { message, blinding }
                    } else {
                        MessageOrBlinding::BlindMessageRandomly(message)
                    }
                }),
            )
            .unwrap();


            let mut chal_bytes_prover = vec![];
            keypair_1.public_key.serialize_compressed(&mut chal_bytes_prover).unwrap();
            keypair_2.public_key.serialize_compressed(&mut chal_bytes_prover).unwrap();
            keypair_3.public_key.serialize_compressed(&mut chal_bytes_prover).unwrap();
            pok_1
                .challenge_contribution(&revealed_msgs_1, &params_1, &mut chal_bytes_prover)
                .unwrap();
            pok_2
                .challenge_contribution(&revealed_msgs_2, &params_2, &mut chal_bytes_prover)
                .unwrap();
            pok_3
                .challenge_contribution(&revealed_msgs_3, &params_3, &mut chal_bytes_prover)
                .unwrap();
            let challenge_prover =
                compute_random_oracle_challenge::<Fr, Blake2b512>(&chal_bytes_prover);

            let proof_1 = pok_1.gen_proof(&challenge_prover).unwrap();
            let proof_2 = pok_2.gen_proof(&challenge_prover).unwrap();
            let proof_3 = pok_3.gen_partial_proof(&challenge_prover, &revealed_indices, &same_msg_idx).unwrap();

            // The verifier generates the challenge on its own.
            let mut chal_bytes_verifier = vec![];
            keypair_1.public_key.serialize_compressed(&mut chal_bytes_verifier).unwrap();
            keypair_2.public_key.serialize_compressed(&mut chal_bytes_verifier).unwrap();
            keypair_3.public_key.serialize_compressed(&mut chal_bytes_verifier).unwrap();
            proof_1
                .challenge_contribution(&revealed_msgs_1, &params_1, &mut chal_bytes_verifier)
                .unwrap();
            proof_2
                .challenge_contribution(&revealed_msgs_2, &params_2, &mut chal_bytes_verifier)
                .unwrap();
            proof_3
                .challenge_contribution(&revealed_msgs_3, &params_3, &mut chal_bytes_verifier)
                .unwrap();
            let challenge_verifier =
                compute_random_oracle_challenge::<Fr, Blake2b512>(&chal_bytes_verifier);

            // Response for the same message should be same (this check is made by the verifier)
            for i in &same_msg_idx {
             assert_eq!(
                proof_1
                    .get_resp_for_message(*i, &revealed_indices)
                    .unwrap(),
                proof_2
                    .get_resp_for_message(*i, &revealed_indices)
                    .unwrap()
                );
                assert!(proof_3.get_resp_for_message(*i, &revealed_indices).is_err())
            }

            let missing_resps = proof_1.get_responses(&same_msg_idx, &revealed_indices).unwrap();

            proof_1
                .verify(
                    &revealed_msgs_1,
                    &challenge_verifier,
                    keypair_1.public_key.clone(),
                    params_1,
                )
                .unwrap();
            proof_2
                .verify(
                    &revealed_msgs_2,
                    &challenge_verifier,
                    keypair_2.public_key.clone(),
                    params_2,
                )
                .unwrap();
            proof_3
                .verify_partial(
                    &revealed_msgs_3,
                    &challenge_verifier,
                    keypair_3.public_key.clone(),
                    params_3,
                    missing_resps
                )
                .unwrap();

            assert!(proof_3.get_responses(&same_msg_idx, &revealed_indices).is_err());

            let mut partial_resp_ids = BTreeSet::new();
            for i in 0..message_3_count as usize {
                if (!same_msg_idx.contains(&i)) && !revealed_indices.contains(&i) {
                    partial_resp_ids.insert(i);
                }
            }
            let partial_resps = proof_3.get_responses(&partial_resp_ids, &revealed_indices).unwrap();
            for i in partial_resp_ids {
                assert_eq!(proof_3.get_resp_for_message(i,&revealed_indices).unwrap(), partial_resps.get(&i).unwrap());
            }

        }}
    }

    #[macro_export]
    macro_rules! gen_test_PoK_multiple_sigs_with_randomized_pairing_check {
        ($params: ident, $prepared_params: ident, $sig: ident, $fn_name: ident, $protocol: ident) => {{
            let mut rng = StdRng::seed_from_u64(0u64);
            let message_count = 5;
            let params =
                $params::<Bls12_381>::new::<Blake2b512>("test".as_bytes(), message_count);
            let keypair = KeypairG2::<Bls12_381>::$fn_name(&mut rng, &params);

            let prepared_pk = PreparedPublicKeyG2::from(keypair.public_key.clone());
            let prepared_params = $prepared_params::from(params.clone());

            test_serialization!(PreparedPublicKeyG2<Bls12_381>, prepared_pk);
            test_serialization!($prepared_params<Bls12_381>, prepared_params);

            let sig_count = 10;
            let mut msgs = vec![];
            let mut sigs = vec![];
            let mut chal_bytes_prover = vec![];
            let mut poks = vec![];
            let mut proofs = vec![];

            keypair.public_key.serialize_compressed(&mut chal_bytes_prover).unwrap();

            for i in 0..sig_count {
                msgs.push(
                    (0..message_count)
                        .map(|_| Fr::rand(&mut rng))
                        .collect::<Vec<Fr>>(),
                );
                sigs.push(
                    $sig::<Bls12_381>::new(&mut rng, &msgs[i], &keypair.secret_key, &params)
                        .unwrap(),
                );
                let pok = $protocol::init(
                    &mut rng,
                    &sigs[i],
                    &params,
                    msgs[i].iter().map(MessageOrBlinding::BlindMessageRandomly),
                )
                .unwrap();
                pok.challenge_contribution(&BTreeMap::new(), &params, &mut chal_bytes_prover)
                    .unwrap();
                poks.push(pok);
            }

            let challenge_prover =
                compute_random_oracle_challenge::<Fr, Blake2b512>(&chal_bytes_prover);

            for pok in poks {
                proofs.push(pok.gen_proof(&challenge_prover).unwrap());
            }

            let mut chal_bytes_verifier = vec![];
            keypair.public_key.serialize_compressed(&mut chal_bytes_verifier).unwrap();

            for proof in &proofs {
                proof
                    .challenge_contribution(&BTreeMap::new(), &params, &mut chal_bytes_verifier)
                    .unwrap();
            }

            let challenge_verifier =
                compute_random_oracle_challenge::<Fr, Blake2b512>(&chal_bytes_verifier);

            let start = Instant::now();
            for proof in proofs.clone() {
                proof
                    .verify(
                        &BTreeMap::new(),
                        &challenge_verifier,
                        keypair.public_key.clone(),
                        params.clone(),
                    )
                    .unwrap();
            }
            println!("Time to verify {} sigs: {:?}", sig_count, start.elapsed());

            let start = Instant::now();
            for proof in proofs.clone() {
                proof
                    .verify(
                        &BTreeMap::new(),
                        &challenge_verifier,
                        prepared_pk.clone(),
                        prepared_params.clone(),
                    )
                    .unwrap();
            }
            println!(
                "Time to verify {} sigs using prepared public key and params: {:?}",
                sig_count,
                start.elapsed()
            );

            let mut pairing_checker = RandomizedPairingChecker::new_using_rng(&mut rng, true);
            let start = Instant::now();
            for proof in proofs.clone() {
                proof
                    .verify_with_randomized_pairing_checker(
                        &BTreeMap::new(),
                        &challenge_verifier,
                        keypair.public_key.clone(),
                        params.clone(),
                        &mut pairing_checker,
                    )
                    .unwrap();
            }
            assert!(pairing_checker.verify());
            println!(
                "Time to verify {} sigs using randomized pairing checker: {:?}",
                sig_count,
                start.elapsed()
            );

            let mut pairing_checker = RandomizedPairingChecker::new_using_rng(&mut rng, true);
            let start = Instant::now();
            for proof in proofs.clone() {
                proof
                    .verify_with_randomized_pairing_checker(
                        &BTreeMap::new(),
                        &challenge_verifier,
                        prepared_pk.clone(),
                        prepared_params.clone(),
                        &mut pairing_checker,
                    )
                    .unwrap();
            }
            assert!(pairing_checker.verify());
            println!(
                "Time to verify {} sigs using prepared public key and params and randomized pairing checker: {:?}",
                sig_count,
                start.elapsed()
            );
        }}
    }

    #[macro_export]
    macro_rules! gen_test_pok_signature_schnorr_response {
        ($setup_fn_name: ident, $protocol: ident, $resp_name: ident) => {{
            // Test response from Schnorr protocol from various messages
            let mut rng = StdRng::seed_from_u64(0u64);
            let message_count = 6;
            let (messages, params, _keypair, sig) = $setup_fn_name(&mut rng, message_count);

            let challenge = Fr::rand(&mut rng);

            // Test response when no hidden message
            let revealed_indices_1 = BTreeSet::new();
            let pok_1 = $protocol::init(
                &mut rng,
                &sig,
                &params,
                messages.iter().enumerate().map(|(idx, msg)| {
                    if revealed_indices_1.contains(&idx) {
                        MessageOrBlinding::RevealMessage(msg)
                    } else {
                        MessageOrBlinding::BlindMessageRandomly(msg)
                    }
                }),
            )
            .unwrap();
            let proof_1 = pok_1.gen_proof(&challenge).unwrap();
            let resps = proof_1.$resp_name.as_ref().unwrap();
            for i in 0..message_count as usize {
                assert_eq!(
                    *proof_1
                        .get_resp_for_message(i, &revealed_indices_1)
                        .unwrap(),
                    resps.0[i]
                );
            }

            // Test response when some messages are revealed
            let mut revealed_indices_2 = BTreeSet::new();
            revealed_indices_2.insert(0);
            revealed_indices_2.insert(2);
            revealed_indices_2.insert(5);
            let pok_2 = $protocol::init(
                &mut rng,
                &sig,
                &params,
                messages.iter().enumerate().map(|(idx, msg)| {
                    if revealed_indices_2.contains(&idx) {
                        MessageOrBlinding::RevealMessage(msg)
                    } else {
                        MessageOrBlinding::BlindMessageRandomly(msg)
                    }
                }),
            )
            .unwrap();
            let proof_2 = pok_2.gen_proof(&challenge).unwrap();

            // Getting response for messages that are revealed throws error as they are not included in
            // the proof of knowledge
            assert!(proof_2
                .get_resp_for_message(0, &revealed_indices_2)
                .is_err());
            assert!(proof_2
                .get_resp_for_message(2, &revealed_indices_2)
                .is_err());
            assert!(proof_2
                .get_resp_for_message(5, &revealed_indices_2)
                .is_err());

            let resps = proof_2.$resp_name.as_ref().unwrap();
            assert_eq!(
                *proof_2
                    .get_resp_for_message(1, &revealed_indices_2)
                    .unwrap(),
                resps.0[0]
            );
            assert_eq!(
                *proof_2
                    .get_resp_for_message(3, &revealed_indices_2)
                    .unwrap(),
                resps.0[1]
            );
            assert_eq!(
                *proof_2
                    .get_resp_for_message(4, &revealed_indices_2)
                    .unwrap(),
                resps.0[2]
            );

            let mut revealed_indices_3 = BTreeSet::new();
            revealed_indices_3.insert(0);
            revealed_indices_3.insert(3);
            let pok_3 = $protocol::init(
                &mut rng,
                &sig,
                &params,
                messages.iter().enumerate().map(|(idx, msg)| {
                    if revealed_indices_3.contains(&idx) {
                        MessageOrBlinding::RevealMessage(msg)
                    } else {
                        MessageOrBlinding::BlindMessageRandomly(msg)
                    }
                }),
            )
            .unwrap();
            let proof_3 = pok_3.gen_proof(&challenge).unwrap();

            // Getting response for messages that are revealed throws error as they are not included in
            // the proof of knowledge
            assert!(proof_3
                .get_resp_for_message(0, &revealed_indices_3)
                .is_err());
            assert!(proof_3
                .get_resp_for_message(3, &revealed_indices_3)
                .is_err());

            let resps = proof_3.$resp_name.as_ref().unwrap();
            assert_eq!(
                *proof_3
                    .get_resp_for_message(1, &revealed_indices_3)
                    .unwrap(),
                resps.0[0]
            );
            assert_eq!(
                *proof_3
                    .get_resp_for_message(2, &revealed_indices_3)
                    .unwrap(),
                resps.0[1]
            );
            assert_eq!(
                *proof_3
                    .get_resp_for_message(4, &revealed_indices_3)
                    .unwrap(),
                resps.0[2]
            );
            assert_eq!(
                *proof_3
                    .get_resp_for_message(5, &revealed_indices_3)
                    .unwrap(),
                resps.0[3]
            );

            // Reveal one message only
            for i in 0..message_count as usize {
                let mut revealed_indices = BTreeSet::new();
                revealed_indices.insert(i);
                let pok = $protocol::init(
                    &mut rng,
                    &sig,
                    &params,
                    messages.iter().enumerate().map(|(idx, msg)| {
                        if revealed_indices.contains(&idx) {
                            MessageOrBlinding::RevealMessage(msg)
                        } else {
                            MessageOrBlinding::BlindMessageRandomly(msg)
                        }
                    }),
                )
                .unwrap();
                let proof = pok.gen_proof(&challenge).unwrap();
                let resps = proof.$resp_name.as_ref().unwrap();
                for j in 0..message_count as usize {
                    if i == j {
                        assert!(proof.get_resp_for_message(j, &revealed_indices).is_err());
                    } else if i < j {
                        assert_eq!(
                            *proof.get_resp_for_message(j, &revealed_indices).unwrap(),
                            resps.0[j - 1]
                        );
                    } else {
                        assert_eq!(
                            *proof.get_resp_for_message(j, &revealed_indices).unwrap(),
                            resps.0[j]
                        );
                    }
                }
            }
        }}
    }

    #[test]
    fn pok_signature_revealed_message() {
        gen_test_pok_signature_revealed_message!(PoKOfSignatureG1Protocol, PoKOfSignatureG1Proof)
    }

    #[test]
    fn test_PoK_multiple_sigs_with_same_msg() {
        gen_test_PoK_multiple_sigs_with_same_msg!(
            SignatureParamsG1,
            SignatureG1,
            generate_using_rng,
            PoKOfSignatureG1Protocol
        )
    }

    #[test]
    fn pok_signature_schnorr_response() {
        gen_test_pok_signature_schnorr_response!(sig_setup, PoKOfSignatureG1Protocol, sc_resp_2);
    }

    #[test]
    fn test_PoK_multiple_sigs_with_randomized_pairing_check() {
        gen_test_PoK_multiple_sigs_with_randomized_pairing_check!(
            SignatureParamsG1,
            PreparedSignatureParamsG1,
            SignatureG1,
            generate_using_rng,
            PoKOfSignatureG1Protocol
        )
    }
}