triptych 0.1.1

An experimental Rust implementation of the Triptych zero-knowledge proving system
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
// Copyright (c) 2024, The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use alloc::{vec, vec::Vec};
use core::{iter::once, slice, slice::ChunksExact};

use curve25519_dalek::{
    ristretto::CompressedRistretto,
    traits::{Identity, MultiscalarMul, VartimeMultiscalarMul},
    RistrettoPoint,
    Scalar,
};
use itertools::{izip, Itertools};
use rand_core::CryptoRngCore;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use snafu::prelude::*;
use subtle::{ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroizing;

use crate::{
    gray::GrayIterator,
    transcript::ProofTranscript,
    util::{delta, NullRng, OperationTiming},
    Transcript,
    TriptychStatement,
    TriptychWitness,
};

// Size of serialized proof elements in bytes
const SERIALIZED_BYTES: usize = 32;

/// A Triptych proof.
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TriptychProof {
    A: RistrettoPoint,
    B: RistrettoPoint,
    C: RistrettoPoint,
    D: RistrettoPoint,
    X: Vec<RistrettoPoint>,
    Y: Vec<RistrettoPoint>,
    f: Vec<Vec<Scalar>>,
    z_A: Scalar,
    z_C: Scalar,
    z: Scalar,
}

/// Errors that can arise relating to [`TriptychProof`].
#[derive(Debug, Snafu)]
pub enum ProofError {
    /// An invalid parameter was provided.
    #[snafu(display("An invalid parameter was provided"))]
    InvalidParameter,
    /// A transcript challenge was invalid.
    #[snafu(display("A transcript challenge was invalid"))]
    InvalidChallenge,
    /// Proof deserialization failed.
    #[snafu(display("Proof deserialization failed"))]
    FailedDeserialization,
    /// Single proof verification failed.
    #[snafu[display("Single proof verification failed")]]
    FailedVerification,
    /// Batch proof verification failed.
    #[snafu[display("Batch proof verification failed")]]
    FailedBatchVerification,
    /// Batch proof verification failed.
    #[snafu[display("Batch proof verification failed")]]
    FailedBatchVerificationWithSingleBlame {
        /// The index of a failed proof, or `None` if no such index was found due to an internal error.
        index: Option<usize>,
    },
    /// Batch proof verification failed.
    #[snafu[display("Batch proof verification failed")]]
    FailedBatchVerificationWithFullBlame {
        /// The indexes of all failed proofs.
        indexes: Vec<usize>,
    },
}

impl TriptychProof {
    /// Generate a Triptych [`TriptychProof`].
    ///
    /// The proof is generated by supplying a [`TriptychWitness`] `witness` and corresponding [`TriptychStatement`]
    /// `statement`. If the witness and statement do not share the same parameters, or if the statement is invalid
    /// for the witness, returns a [`ProofError`].
    ///
    /// This function provides a cryptographically-secure random number generator for you.
    ///
    /// You must also supply a [`Transcript`] `transcript`.
    ///
    /// This function specifically avoids constant-time operations for efficiency.
    #[cfg(feature = "rand")]
    pub fn prove_vartime(
        witness: &TriptychWitness,
        statement: &TriptychStatement,
        transcript: &mut Transcript,
    ) -> Result<Self, ProofError> {
        use rand_core::OsRng;

        Self::prove_internal(witness, statement, &mut OsRng, transcript, OperationTiming::Variable)
    }

    /// Generate a Triptych [`TriptychProof`].
    ///
    /// The proof is generated by supplying a [`TriptychWitness`] `witness` and corresponding [`TriptychStatement`]
    /// `statement`. If the witness and statement do not share the same parameters, or if the statement is invalid
    /// for the witness, returns a [`ProofError`].
    ///
    /// You must also supply a [`CryptoRngCore`] random number generator `rng` and a [`Transcript`] `transcript`.
    ///
    /// This function specifically avoids constant-time operations for efficiency.
    pub fn prove_with_rng_vartime<R: CryptoRngCore>(
        witness: &TriptychWitness,
        statement: &TriptychStatement,
        rng: &mut R,
        transcript: &mut Transcript,
    ) -> Result<Self, ProofError> {
        Self::prove_internal(witness, statement, rng, transcript, OperationTiming::Variable)
    }

    /// Generate a Triptych [`TriptychProof`].
    ///
    /// The proof is generated by supplying a [`TriptychWitness`] `witness` and corresponding [`TriptychStatement`]
    /// `statement`. If the witness and statement do not share the same parameters, or if the statement is invalid
    /// for the witness, returns a [`ProofError`].
    ///
    /// This function provides a cryptographically-secure random number generator for you.
    ///
    /// You must also supply a [`Transcript`] `transcript`.
    ///
    /// This function makes some attempt at avoiding timing side-channel attacks using constant-time operations.
    #[cfg(feature = "rand")]
    pub fn prove(
        witness: &TriptychWitness,
        statement: &TriptychStatement,
        transcript: &mut Transcript,
    ) -> Result<Self, ProofError> {
        use rand_core::OsRng;

        Self::prove_internal(witness, statement, &mut OsRng, transcript, OperationTiming::Constant)
    }

    /// Generate a Triptych [`TriptychProof`].
    ///
    /// The proof is generated by supplying a [`TriptychWitness`] `witness` and corresponding [`TriptychStatement`]
    /// `statement`. If the witness and statement do not share the same parameters, or if the statement is invalid
    /// for the witness, returns a [`ProofError`].
    ///
    /// You must also supply a [`CryptoRngCore`] random number generator `rng` and a [`Transcript`] `transcript`.
    ///
    /// This function makes some attempt at avoiding timing side-channel attacks using constant-time operations.
    pub fn prove_with_rng<R: CryptoRngCore>(
        witness: &TriptychWitness,
        statement: &TriptychStatement,
        rng: &mut R,
        transcript: &mut Transcript,
    ) -> Result<Self, ProofError> {
        Self::prove_internal(witness, statement, rng, transcript, OperationTiming::Constant)
    }

    /// The actual prover functionality.
    #[allow(clippy::too_many_lines, non_snake_case)]
    fn prove_internal<R: CryptoRngCore>(
        witness: &TriptychWitness,
        statement: &TriptychStatement,
        rng: &mut R,
        transcript: &mut Transcript,
        timing: OperationTiming,
    ) -> Result<Self, ProofError> {
        // Check that the witness and statement have identical parameters
        if witness.get_params() != statement.get_params() {
            return Err(ProofError::InvalidParameter);
        }

        // Extract values for convenience
        let r = witness.get_r();
        let l = witness.get_l();
        let M = statement.get_input_set().get_keys();
        let params = statement.get_params();
        let J = statement.get_J();

        // Check that the witness is valid against the statement, in constant time if needed
        let mut M_l = RistrettoPoint::identity();

        match timing {
            OperationTiming::Constant => {
                for (index, item) in M.iter().enumerate() {
                    M_l.conditional_assign(item, index.ct_eq(&(l as usize)));
                }
            },
            OperationTiming::Variable => {
                M_l = M[l as usize];
            },
        }

        if M_l != r * params.get_G() {
            return Err(ProofError::InvalidParameter);
        }
        if &(r * J) != params.get_U() {
            return Err(ProofError::InvalidParameter);
        }

        // Set up the transcript
        let mut transcript = ProofTranscript::new(transcript, statement, rng, Some(witness));

        // Compute the `A` matrix commitment
        let r_A = Scalar::random(transcript.as_mut_rng());
        let mut a = (0..params.get_m())
            .map(|_| {
                (0..params.get_n())
                    .map(|_| Scalar::random(transcript.as_mut_rng()))
                    .collect::<Vec<Scalar>>()
            })
            .collect::<Vec<Vec<Scalar>>>();
        for j in (0..params.get_m()).map(|j| j as usize) {
            a[j][0] = -a[j][1..].iter().sum::<Scalar>();
        }
        let A = params
            .commit_matrix(&a, &r_A, timing)
            .map_err(|_| ProofError::InvalidParameter)?;

        // Compute the `B` matrix commitment
        let r_B = Scalar::random(transcript.as_mut_rng());
        let l_decomposed = match timing {
            OperationTiming::Constant => {
                GrayIterator::decompose(params.get_n(), params.get_m(), l).ok_or(ProofError::InvalidParameter)?
            },
            OperationTiming::Variable => GrayIterator::decompose_vartime(params.get_n(), params.get_m(), l)
                .ok_or(ProofError::InvalidParameter)?,
        };
        let sigma = (0..params.get_m())
            .map(|j| {
                (0..params.get_n())
                    .map(|i| delta(l_decomposed[j as usize], i, timing))
                    .collect::<Vec<Scalar>>()
            })
            .collect::<Vec<Vec<Scalar>>>();
        let B = params
            .commit_matrix(&sigma, &r_B, timing)
            .map_err(|_| ProofError::InvalidParameter)?;

        // Compute the `C` matrix commitment
        let two = Scalar::from(2u32);
        let r_C = Scalar::random(transcript.as_mut_rng());
        let a_sigma = (0..params.get_m())
            .map(|j| {
                (0..params.get_n())
                    .map(|i| a[j as usize][i as usize] * (Scalar::ONE - two * sigma[j as usize][i as usize]))
                    .collect::<Vec<Scalar>>()
            })
            .collect::<Vec<Vec<Scalar>>>();
        let C = params
            .commit_matrix(&a_sigma, &r_C, timing)
            .map_err(|_| ProofError::InvalidParameter)?;

        // Compute the `D` matrix commitment
        let r_D = Scalar::random(transcript.as_mut_rng());
        let a_square = (0..params.get_m())
            .map(|j| {
                (0..params.get_n())
                    .map(|i| -a[j as usize][i as usize] * a[j as usize][i as usize])
                    .collect::<Vec<Scalar>>()
            })
            .collect::<Vec<Vec<Scalar>>>();
        let D = params
            .commit_matrix(&a_square, &r_D, timing)
            .map_err(|_| ProofError::InvalidParameter)?;

        // Random masks
        let rho = Zeroizing::new(
            (0..params.get_m())
                .map(|_| Scalar::random(transcript.as_mut_rng()))
                .collect::<Vec<Scalar>>(),
        );

        // Compute `p` polynomial vector coefficients using repeated convolution
        let mut p = Vec::<Vec<Scalar>>::with_capacity(params.get_N() as usize);
        let mut k_decomposed = vec![0; params.get_m() as usize];
        for (gray_index, _, gray_new) in
            GrayIterator::new(params.get_n(), params.get_m()).ok_or(ProofError::InvalidParameter)?
        {
            k_decomposed[gray_index] = gray_new;

            // Set the initial coefficients using the first degree-one polynomial (`j = 0`)
            let mut coefficients = Vec::new();
            coefficients.resize(
                (params.get_m() as usize)
                    .checked_add(1)
                    .ok_or(ProofError::InvalidParameter)?,
                Scalar::ZERO,
            );
            coefficients[0] = a[0][k_decomposed[0] as usize];
            coefficients[1] = sigma[0][k_decomposed[0] as usize];

            // Use convolution against each remaining degree-one polynomial
            for j in 1..params.get_m() {
                // For the degree-zero portion, simply multiply each coefficient accordingly
                let degree_0_portion = coefficients
                    .iter()
                    .map(|c| a[j as usize][k_decomposed[j as usize] as usize] * c)
                    .collect::<Vec<Scalar>>();

                // For the degree-one portion, we also need to increase each exponent by one
                // Rotating the coefficients is fine here since the highest is always zero!
                let mut shifted_coefficients = coefficients.clone();
                shifted_coefficients.rotate_right(1);
                let degree_1_portion = shifted_coefficients
                    .iter()
                    .map(|c| sigma[j as usize][k_decomposed[j as usize] as usize] * c)
                    .collect::<Vec<Scalar>>();

                coefficients = degree_0_portion
                    .iter()
                    .zip(degree_1_portion.iter())
                    .map(|(x, y)| x + y)
                    .collect::<Vec<Scalar>>();
            }

            p.push(coefficients);
        }

        // Compute `X` vector
        let X = rho
            .iter()
            .enumerate()
            .map(|(j, rho)| {
                let X_points = M.iter().chain(once(params.get_G()));
                let X_scalars = p.iter().map(|p| &p[j]).chain(once(rho));

                match timing {
                    OperationTiming::Constant => RistrettoPoint::multiscalar_mul(X_scalars, X_points),
                    OperationTiming::Variable => RistrettoPoint::vartime_multiscalar_mul(X_scalars, X_points),
                }
            })
            .collect::<Vec<RistrettoPoint>>();

        // Compute `Y` vector
        let Y = rho.iter().map(|rho| rho * J).collect::<Vec<RistrettoPoint>>();

        // Run the Fiat-Shamir commitment phase to get the challenge powers
        let xi_powers = transcript.commit(params, &A, &B, &C, &D, &X, &Y)?;

        // Compute the `f` matrix
        let f = (0..params.get_m())
            .map(|j| {
                (1..params.get_n())
                    .map(|i| sigma[j as usize][i as usize] * xi_powers[1] + a[j as usize][i as usize])
                    .collect::<Vec<Scalar>>()
            })
            .collect::<Vec<Vec<Scalar>>>();

        // Compute the remaining response values
        let z_A = r_A + xi_powers[1] * r_B;
        let z_C = xi_powers[1] * r_C + r_D;
        let z = r * xi_powers[params.get_m() as usize] -
            rho.iter()
                .zip(xi_powers.iter())
                .map(|(rho, xi_power)| rho * xi_power)
                .sum::<Scalar>();

        Ok(Self {
            A,
            B,
            C,
            D,
            X,
            Y,
            f,
            z_A,
            z_C,
            z,
        })
    }

    /// Verify a Triptych [`TriptychProof`].
    ///
    /// Verification requires that the `statement` and `transcript` match those used when the proof was generated.
    ///
    /// If this requirement is not met, or if the proof is invalid, returns a [`ProofError`].
    pub fn verify(&self, statement: &TriptychStatement, transcript: &mut Transcript) -> Result<(), ProofError> {
        // Verify as a trivial batch
        Self::verify_batch(
            slice::from_ref(statement),
            slice::from_ref(self),
            slice::from_mut(transcript),
        )
    }

    /// Verify a batch of Triptych [`TriptychProofs`](`TriptychProof`), identifying a single invalid proof if
    /// verification fails.
    ///
    /// An empty batch is valid by definition.
    ///
    /// If verification fails, this performs a subsequent number of verifications logarithmic in the size of the batch.
    ///
    /// Verification requires that the `statements` and `transcripts` match those used when the `proofs` were generated,
    /// and that they share a common [`TriptychInputSet`](`crate::statement::TriptychInputSet`) and
    /// [`TriptychParameters`](`crate::parameters::TriptychParameters`).
    ///
    /// If any of the above requirements are not met, returns a [`ProofError`].
    /// If any batch in the proof is invalid, returns a [`ProofError`] containing the index of an invalid proof.
    /// It is not guaranteed that this index represents the _only_ invalid proof in the batch.
    pub fn verify_batch_with_single_blame(
        statements: &[TriptychStatement],
        proofs: &[TriptychProof],
        transcripts: &mut [Transcript],
    ) -> Result<(), ProofError> {
        // Try to verify the full batch
        if Self::verify_batch(statements, proofs, &mut transcripts.to_vec()).is_ok() {
            return Ok(());
        }

        // The batch failed, so find an invalid proof using a binary search
        let mut left = 0;
        let mut right = proofs.len();

        while left < right {
            #[allow(clippy::arithmetic_side_effects)]
            let average = left
                .checked_add(
                    // This cannot underflow since `left < right`
                    (right - left) / 2,
                )
                .ok_or(ProofError::FailedBatchVerificationWithSingleBlame { index: None })?;

            #[allow(clippy::arithmetic_side_effects)]
            // This cannot underflow since `left < right`
            let mid = if (right - left) % 2 == 0 {
                average
            } else {
                average
                    .checked_add(1)
                    .ok_or(ProofError::FailedBatchVerificationWithSingleBlame { index: None })?
            };

            let failure_on_left = Self::verify_batch(
                &statements[left..mid],
                &proofs[left..mid],
                &mut transcripts.to_vec()[left..mid],
            )
            .is_err();

            if failure_on_left {
                let left_check = mid
                    .checked_sub(1)
                    .ok_or(ProofError::FailedBatchVerificationWithSingleBlame { index: None })?;
                if left == left_check {
                    return Err(ProofError::FailedBatchVerificationWithSingleBlame { index: Some(left) });
                }

                right = mid;
            } else {
                let right_check = mid
                    .checked_add(1)
                    .ok_or(ProofError::FailedBatchVerificationWithSingleBlame { index: None })?;
                if right == right_check {
                    let right_result = right
                        .checked_sub(1)
                        .ok_or(ProofError::FailedBatchVerificationWithSingleBlame { index: None })?;
                    return Err(ProofError::FailedBatchVerificationWithSingleBlame {
                        index: Some(right_result),
                    });
                }

                left = mid
            }
        }

        // The batch failed, but we couldn't find a single failure! This should never happen.
        Err(ProofError::FailedBatchVerificationWithSingleBlame { index: None })
    }

    /// Verify a batch of Triptych [`TriptychProofs`](`TriptychProof`), identifying all invalid proofs if verification
    /// fails.
    ///
    /// An empty batch is valid by definition.
    ///
    /// If verification fails, this performs a subsequent number of verifications linear in the size of the batch.
    ///
    /// Verification requires that the `statements` and `transcripts` match those used when the `proofs` were generated,
    /// and that they share a common [`TriptychInputSet`](`crate::statement::TriptychInputSet`) and
    /// [`TriptychParameters`](`crate::parameters::TriptychParameters`).
    ///
    /// If any of the above requirements are not met, returns a [`ProofError`].
    /// If any batch in the proof is invalid, returns a [`ProofError`] containing the indexes of all invalid proofs.
    pub fn verify_batch_with_full_blame(
        statements: &[TriptychStatement],
        proofs: &[TriptychProof],
        transcripts: &mut [Transcript],
    ) -> Result<(), ProofError> {
        // Try to verify the full batch
        if Self::verify_batch(statements, proofs, &mut transcripts.to_vec()).is_ok() {
            return Ok(());
        }

        // The batch failed, so check each proof and keep track of which are invalid
        let mut failures = Vec::with_capacity(proofs.len());
        for (index, (statement, proof, transcript)) in izip!(statements, proofs, transcripts.iter_mut()).enumerate() {
            if proof.verify(statement, transcript).is_err() {
                failures.push(index);
            }
        }

        Err(ProofError::FailedBatchVerificationWithFullBlame { indexes: failures })
    }

    /// Verify a batch of Triptych [`TriptychProofs`](`TriptychProof`).
    ///
    /// An empty batch is valid by definition.
    ///
    /// Verification requires that the `statements` and `transcripts` match those used when the `proofs` were generated,
    /// and that they share a common [`TriptychInputSet`](`crate::statement::TriptychInputSet`) and
    /// [`TriptychParameters`](`crate::parameters::TriptychParameters`).
    ///
    /// If any of the above requirements are not met, or if any proof is invalid, returns a [`ProofError`].
    #[allow(clippy::too_many_lines, non_snake_case)]
    pub fn verify_batch(
        statements: &[TriptychStatement],
        proofs: &[TriptychProof],
        transcripts: &mut [Transcript],
    ) -> Result<(), ProofError> {
        // Check that we have the same number of statements, proofs, and transcripts
        if statements.len() != proofs.len() {
            return Err(ProofError::InvalidParameter);
        }
        if statements.len() != transcripts.len() {
            return Err(ProofError::InvalidParameter);
        }

        // An empty batch is considered trivially valid
        let first_statement = match statements.first() {
            Some(statement) => statement,
            None => return Ok(()),
        };

        // Each statement must use the same input set (checked using the hash for efficiency)
        if !statements.iter().map(|s| s.get_input_set().get_hash()).all_equal() {
            return Err(ProofError::InvalidParameter);
        }

        // Each statement must use the same parameters (checked using the hash for efficiency)
        if !statements.iter().map(|s| s.get_params().get_hash()).all_equal() {
            return Err(ProofError::InvalidParameter);
        }

        // Extract common values for convenience
        let M = first_statement.get_input_set().get_keys();
        let params = first_statement.get_params();

        // Check that all proof semantics are valid for the statement
        for proof in proofs {
            if proof.X.len() != params.get_m() as usize {
                return Err(ProofError::InvalidParameter);
            }
            if proof.Y.len() != params.get_m() as usize {
                return Err(ProofError::InvalidParameter);
            }
            if proof.f.len() != params.get_m() as usize {
                return Err(ProofError::InvalidParameter);
            }
            for f_row in &proof.f {
                if f_row.len() != params.get_n().checked_sub(1).ok_or(ProofError::InvalidParameter)? as usize {
                    return Err(ProofError::InvalidParameter);
                }
            }
        }

        // Determine the size of the final check vector, which must not overflow `usize`
        let batch_size = u32::try_from(proofs.len()).map_err(|_| ProofError::InvalidParameter)?;

        // This is unlikely to overflow; even if it does, the only effect is unnecessary reallocation
        #[allow(clippy::arithmetic_side_effects)]
        let final_size = usize::try_from(
            1 // G
            + params.get_n() * params.get_m() // CommitmentG
            + 1 // CommitmentH
            + params.get_N() // M
            + 1 // U
            + batch_size * (
                4 // A, B, C, D
                + 1 // J
                + 2 * params.get_m() // X, Y
            ),
        )
        .map_err(|_| ProofError::InvalidParameter)?;

        // Set up the point vector for the final check
        let points = proofs
            .iter()
            .zip(statements.iter())
            .flat_map(|(p, s)| {
                once(&p.A)
                    .chain(once(&p.B))
                    .chain(once(&p.C))
                    .chain(once(&p.D))
                    .chain(once(s.get_J()))
                    .chain(p.X.iter())
                    .chain(p.Y.iter())
            })
            .chain(once(params.get_G()))
            .chain(params.get_CommitmentG().iter())
            .chain(once(params.get_CommitmentH()))
            .chain(M.iter())
            .chain(once(params.get_U()))
            .collect::<Vec<&RistrettoPoint>>();

        // Start the scalar vector, putting the common elements last
        let mut scalars = Vec::with_capacity(final_size);

        // Set up common scalars
        let mut G_scalar = Scalar::ZERO;
        let mut CommitmentG_scalars = vec![Scalar::ZERO; params.get_CommitmentG().len()];
        let mut CommitmentH_scalar = Scalar::ZERO;
        let mut M_scalars = vec![Scalar::ZERO; M.len()];
        let mut U_scalar = Scalar::ZERO;

        // Set up a transcript generator for use in weighting
        let mut transcript_weights = Transcript::new(b"Triptych verifier weights");

        let mut null_rng = NullRng;

        // Generate all verifier challenges
        let mut xi_powers_all = Vec::with_capacity(proofs.len());
        for (statement, proof, transcript) in izip!(statements.iter(), proofs.iter(), transcripts.iter_mut()) {
            // Set up the transcript
            let mut transcript = ProofTranscript::new(transcript, statement, &mut null_rng, None);

            // Run the Fiat-Shamir commitment phase to get the challenge powers
            xi_powers_all.push(transcript.commit(params, &proof.A, &proof.B, &proof.C, &proof.D, &proof.X, &proof.Y)?);

            // Run the Fiat-Shamir response phase to get the transcript generator and weight
            let mut transcript_rng = transcript.response(&proof.f, &proof.z_A, &proof.z_C, &proof.z);
            transcript_weights.append_u64(b"proof", transcript_rng.as_rngcore().next_u64());
        }

        // Finalize the weighting transcript into a pseudorandom number generator
        let mut transcript_weights_rng = transcript_weights.build_rng().finalize(&mut null_rng);

        // Process each proof
        for (proof, xi_powers) in proofs.iter().zip(xi_powers_all.iter()) {
            // Reconstruct the remaining `f` terms
            let f = (0..params.get_m())
                .map(|j| {
                    let mut f_j = Vec::with_capacity(params.get_n() as usize);
                    f_j.push(xi_powers[1] - proof.f[j as usize].iter().sum::<Scalar>());
                    f_j.extend(proof.f[j as usize].iter());
                    f_j
                })
                .collect::<Vec<Vec<Scalar>>>();

            // Check that `f` does not contain zero, which breaks batch inversion
            for f_row in &f {
                if f_row.contains(&Scalar::ZERO) {
                    return Err(ProofError::InvalidParameter);
                }
            }

            // Generate nonzero weights for this proof's verification equations
            let mut w1 = Scalar::ZERO;
            let mut w2 = Scalar::ZERO;
            let mut w3 = Scalar::ZERO;
            let mut w4 = Scalar::ZERO;
            while w1 == Scalar::ZERO || w2 == Scalar::ZERO || w3 == Scalar::ZERO || w4 == Scalar::ZERO {
                w1 = Scalar::random(&mut transcript_weights_rng);
                w2 = Scalar::random(&mut transcript_weights_rng);
                w3 = Scalar::random(&mut transcript_weights_rng);
                w4 = Scalar::random(&mut transcript_weights_rng);
            }

            // Get the challenge for convenience
            let xi = xi_powers[1];

            // G
            G_scalar -= w3 * proof.z;

            // CommitmentG
            for (CommitmentG_scalar, f_item) in CommitmentG_scalars
                .iter_mut()
                .zip(f.iter().flatten().map(|f| w1 * f + w2 * f * (xi - f)))
            {
                *CommitmentG_scalar += f_item;
            }

            // CommitmentH
            CommitmentH_scalar += w1 * proof.z_A + w2 * proof.z_C;

            // A
            scalars.push(-w1);

            // B
            scalars.push(-w1 * xi_powers[1]);

            // C
            scalars.push(-w2 * xi_powers[1]);

            // D
            scalars.push(-w2);

            // J
            scalars.push(-w4 * proof.z);

            // X
            for xi_power in &xi_powers[0..(params.get_m() as usize)] {
                scalars.push(-w3 * xi_power);
            }

            // Y
            for xi_power in &xi_powers[0..(params.get_m() as usize)] {
                scalars.push(-w4 * xi_power);
            }

            // Set up the initial `f` product and Gray iterator
            let mut f_product = f.iter().map(|f_row| f_row[0]).product::<Scalar>();
            let gray_iterator =
                GrayIterator::new(params.get_n(), params.get_m()).ok_or(ProofError::InvalidParameter)?;

            // Invert each element of `f` for efficiency
            let mut f_inverse_flat = f.iter().flatten().copied().collect::<Vec<Scalar>>();
            Scalar::batch_invert(&mut f_inverse_flat);
            let f_inverse = f_inverse_flat
                .chunks_exact(params.get_n() as usize)
                .collect::<Vec<&[Scalar]>>();

            // M
            let mut U_scalar_proof = Scalar::ZERO;
            for (M_scalar, (gray_index, gray_old, gray_new)) in M_scalars.iter_mut().zip(gray_iterator) {
                // Update the `f` product
                f_product *= f_inverse[gray_index][gray_old as usize] * f[gray_index][gray_new as usize];

                *M_scalar += w3 * f_product;
                U_scalar_proof += f_product;
            }

            // U
            U_scalar += w4 * U_scalar_proof;
        }

        // Add all common elements to the scalar vector
        scalars.push(G_scalar);
        scalars.extend(CommitmentG_scalars);
        scalars.push(CommitmentH_scalar);
        scalars.extend(M_scalars);
        scalars.push(U_scalar);

        // Perform the final check; this can be done in variable time since it holds no secrets
        if RistrettoPoint::vartime_multiscalar_mul(scalars.iter(), points) == RistrettoPoint::identity() {
            Ok(())
        } else {
            Err(ProofError::FailedVerification)
        }
    }

    /// Serialize a [`TriptychProof`] to a canonical byte vector.
    #[allow(non_snake_case)]
    pub fn to_bytes(&self) -> Vec<u8> {
        // This cannot overflow
        #[allow(clippy::arithmetic_side_effects)]
        let mut result = Vec::with_capacity(
            8 // `n - 1`, `m`
            + SERIALIZED_BYTES * (
                4 // `A, B, C, D`
                + self.X.len()
                + self.Y.len()
                + 3 // `z_A, z_C, z`
                + self.f.len() * self.f[0].len()
            ),
        );
        #[allow(clippy::cast_possible_truncation)]
        let n_minus_1 = self.f[0].len() as u32;
        #[allow(clippy::cast_possible_truncation)]
        let m = self.f.len() as u32;
        result.extend(n_minus_1.to_le_bytes());
        result.extend(m.to_le_bytes());

        result.extend_from_slice(self.A.compress().as_bytes());
        result.extend_from_slice(self.B.compress().as_bytes());
        result.extend_from_slice(self.C.compress().as_bytes());
        result.extend_from_slice(self.D.compress().as_bytes());
        result.extend_from_slice(self.z_A.as_bytes());
        result.extend_from_slice(self.z_C.as_bytes());
        result.extend_from_slice(self.z.as_bytes());
        for X in &self.X {
            result.extend_from_slice(X.compress().as_bytes());
        }
        for Y in &self.Y {
            result.extend_from_slice(Y.compress().as_bytes());
        }
        for f_row in &self.f {
            for f in f_row {
                result.extend_from_slice(f.as_bytes());
            }
        }

        result
    }

    /// Deserialize a [`TriptychProof`] from a canonical byte slice.
    ///
    /// If `bytes` does not represent a canonical encoding, returns a [`ProofError`].
    #[allow(non_snake_case)]
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ProofError> {
        // Helper to parse a `u32` from a `u8` iterator
        let parse_u32 = |iter: &mut dyn Iterator<Item = &u8>| {
            // Get the next four bytes
            let bytes = iter.take(4).copied().collect::<Vec<u8>>();
            if bytes.len() != 4 {
                return Err(ProofError::FailedDeserialization);
            }
            let array: [u8; 4] = bytes.try_into().map_err(|_| ProofError::FailedDeserialization)?;

            // Parse the bytes into a `u32`
            Ok(u32::from_le_bytes(array))
        };

        // Helper to parse a scalar from a chunk iterator
        let parse_scalar = |chunks: &mut ChunksExact<'_, u8>| -> Result<Scalar, ProofError> {
            chunks
                .next()
                .ok_or(ProofError::FailedDeserialization)
                .and_then(|slice| {
                    let bytes: [u8; SERIALIZED_BYTES] =
                        slice.try_into().map_err(|_| ProofError::FailedDeserialization)?;
                    Option::<Scalar>::from(Scalar::from_canonical_bytes(bytes)).ok_or(ProofError::FailedDeserialization)
                })
        };

        // Helper to parse a compressed point from a chunk iterator
        let parse_point = |chunks: &mut ChunksExact<'_, u8>| -> Result<RistrettoPoint, ProofError> {
            chunks
                .next()
                .ok_or(ProofError::FailedDeserialization)
                .and_then(|slice| {
                    let bytes: [u8; SERIALIZED_BYTES] =
                        slice.try_into().map_err(|_| ProofError::FailedDeserialization)?;

                    CompressedRistretto::from_slice(&bytes)
                        .map_err(|_| ProofError::FailedDeserialization)?
                        .decompress()
                        .ok_or(ProofError::FailedDeserialization)
                })
        };

        // Set up the slice iterator
        let mut iter = bytes.iter();

        // Parse the encoded vector dimensions and check that `n, m > 1` and that they do not overflow
        let n_minus_1 = parse_u32(&mut iter)?;
        if n_minus_1.checked_add(1).ok_or(ProofError::FailedDeserialization)? < 2 {
            return Err(ProofError::FailedDeserialization);
        }
        let m = parse_u32(&mut iter)?;
        if m < 2 {
            return Err(ProofError::FailedDeserialization);
        }

        // The rest of the serialization is of encoded proof elements
        let mut chunks = iter.as_slice().chunks_exact(SERIALIZED_BYTES);

        // Extract the fixed proof elements
        let A = parse_point(&mut chunks)?;
        let B = parse_point(&mut chunks)?;
        let C = parse_point(&mut chunks)?;
        let D = parse_point(&mut chunks)?;
        let z_A = parse_scalar(&mut chunks)?;
        let z_C = parse_scalar(&mut chunks)?;
        let z = parse_scalar(&mut chunks)?;

        // Extract the `X` and `Y` vectors
        let X = (0..m)
            .map(|_| parse_point(&mut chunks))
            .collect::<Result<Vec<RistrettoPoint>, ProofError>>()?;
        let Y = (0..m)
            .map(|_| parse_point(&mut chunks))
            .collect::<Result<Vec<RistrettoPoint>, ProofError>>()?;

        // Extract the `f` matrix
        let f = (0..m)
            .map(|_| {
                (0..n_minus_1)
                    .map(|_| parse_scalar(&mut chunks))
                    .collect::<Result<Vec<Scalar>, ProofError>>()
            })
            .collect::<Result<Vec<Vec<Scalar>>, ProofError>>()?;

        // Ensure no data is left over
        if !chunks.remainder().is_empty() {
            return Err(ProofError::FailedDeserialization);
        }
        if chunks.next().is_some() {
            return Err(ProofError::FailedDeserialization);
        }

        // Perform a sanity check on all vectors
        if X.len() != m as usize || Y.len() != m as usize {
            return Err(ProofError::FailedDeserialization);
        }
        if f.len() != m as usize {
            return Err(ProofError::FailedDeserialization);
        }
        for f_row in &f {
            if f_row.len() != n_minus_1 as usize {
                return Err(ProofError::FailedDeserialization);
            }
        }

        Ok(TriptychProof {
            A,
            B,
            C,
            D,
            X,
            Y,
            f,
            z_A,
            z_C,
            z,
        })
    }
}

#[cfg(test)]
mod test {
    use alloc::{sync::Arc, vec::Vec};

    use curve25519_dalek::{traits::Identity, RistrettoPoint, Scalar};
    use itertools::izip;
    use rand_chacha::ChaCha12Rng;
    use rand_core::{CryptoRngCore, SeedableRng};

    use crate::{
        proof::{ProofError, SERIALIZED_BYTES},
        Transcript,
        TriptychInputSet,
        TriptychParameters,
        TriptychProof,
        TriptychStatement,
        TriptychWitness,
    };

    // Check that the serialized proof element size constant is correct
    #[test]
    fn test_serialized_bytes() {
        // Check the scalar encoding size
        assert_eq!(Scalar::ZERO.as_bytes().len(), SERIALIZED_BYTES);

        // Check the group element encoding size
        assert_eq!(RistrettoPoint::identity().compress().as_bytes().len(), SERIALIZED_BYTES);
    }

    // Generate a batch of witnesses, statements, and transcripts
    #[allow(non_snake_case)]
    #[allow(clippy::arithmetic_side_effects)]
    fn generate_data<R: CryptoRngCore>(
        n: u32,
        m: u32,
        b: usize,
        rng: &mut R,
    ) -> (Vec<TriptychWitness>, Vec<TriptychStatement>, Vec<Transcript>) {
        // Generate parameters
        let params = Arc::new(TriptychParameters::new(n, m).unwrap());

        // Generate witnesses; for this test, we use adjacent indexes for simplicity
        // This means the batch size must not exceed the input set size!
        assert!(b <= params.get_N() as usize);
        let mut witnesses = Vec::with_capacity(b);
        witnesses.push(TriptychWitness::random(&params, rng));
        for _ in 1..b {
            let r = Scalar::random(rng);
            let l = (witnesses.last().unwrap().get_l() + 1) % params.get_N();
            witnesses.push(TriptychWitness::new(&params, l, &r).unwrap());
        }

        // Generate input set from all witnesses
        let mut M = (0..params.get_N())
            .map(|_| RistrettoPoint::random(rng))
            .collect::<Vec<RistrettoPoint>>();
        for witness in &witnesses {
            M[witness.get_l() as usize] = witness.compute_verification_key();
        }
        let input_set = Arc::new(TriptychInputSet::new(&M).unwrap());

        // Generate statements
        let mut statements = Vec::with_capacity(b);
        for witness in &witnesses {
            let J = witness.compute_linking_tag();
            statements.push(TriptychStatement::new(&params, &input_set, &J).unwrap());
        }

        // Generate transcripts
        let transcripts = (0..b)
            .map(|i| {
                let mut transcript = Transcript::new(b"Test transcript");
                transcript.append_u64(b"index", i as u64);

                transcript
            })
            .collect::<Vec<Transcript>>();

        (witnesses, statements, transcripts)
    }

    #[test]
    #[cfg(feature = "rand")]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate and verify a proof
        let proof = TriptychProof::prove(&witnesses[0], &statements[0], &mut transcripts[0].clone()).unwrap();
        assert!(proof.verify(&statements[0], &mut transcripts[0]).is_ok());
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify_with_rng() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate and verify a proof
        let proof = TriptychProof::prove_with_rng(&witnesses[0], &statements[0], &mut rng, &mut transcripts[0].clone())
            .unwrap();
        assert!(proof.verify(&statements[0], &mut transcripts[0]).is_ok());
    }

    #[test]
    #[cfg(feature = "rand")]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify_vartime() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate and verify a proof
        let proof = TriptychProof::prove_vartime(&witnesses[0], &statements[0], &mut transcripts[0].clone()).unwrap();
        assert!(proof.verify(&statements[0], &mut transcripts[0]).is_ok());
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify_vartime_with_rng() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate and verify a proof
        let proof =
            TriptychProof::prove_with_rng_vartime(&witnesses[0], &statements[0], &mut rng, &mut transcripts[0].clone())
                .unwrap();
        assert!(proof.verify(&statements[0], &mut transcripts[0]).is_ok());
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_serialize_deserialize() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate and verify a proof
        let proof =
            TriptychProof::prove_with_rng_vartime(&witnesses[0], &statements[0], &mut rng, &mut transcripts[0].clone())
                .unwrap();
        assert!(proof.verify(&statements[0], &mut transcripts[0]).is_ok());

        // Serialize the proof
        let serialized = proof.to_bytes();

        // Deserialize the proof
        let deserialized = TriptychProof::from_bytes(&serialized).unwrap();
        assert_eq!(deserialized, proof);
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify_batch() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        const batch: usize = 3; // batch size
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, batch, &mut rng);

        // Generate the proofs
        let proofs = izip!(witnesses.iter(), statements.iter(), transcripts.clone().iter_mut())
            .map(|(w, s, t)| TriptychProof::prove_with_rng_vartime(w, s, &mut rng, t).unwrap())
            .collect::<Vec<TriptychProof>>();

        // Verify the batch with and without blame
        assert!(TriptychProof::verify_batch(&statements, &proofs, &mut transcripts.clone()).is_ok());
        assert!(TriptychProof::verify_batch_with_single_blame(&statements, &proofs, &mut transcripts.clone()).is_ok());
        assert!(TriptychProof::verify_batch_with_full_blame(&statements, &proofs, &mut transcripts).is_ok());
    }

    #[test]
    fn test_prove_verify_empty_batch() {
        // An empty batch is valid by definition
        assert!(TriptychProof::verify_batch(&[], &[], &mut []).is_ok());
        assert!(TriptychProof::verify_batch_with_single_blame(&[], &[], &mut []).is_ok());
        assert!(TriptychProof::verify_batch_with_full_blame(&[], &[], &mut []).is_ok());
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify_invalid_batch() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        const batch: usize = 3; // batch size
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, batch, &mut rng);

        // Generate the proofs
        let proofs = izip!(witnesses.iter(), statements.iter(), transcripts.clone().iter_mut())
            .map(|(w, s, t)| TriptychProof::prove_with_rng_vartime(w, s, &mut rng, t).unwrap())
            .collect::<Vec<TriptychProof>>();

        // Manipulate a transcript so the corresponding proof is invalid
        transcripts[0] = Transcript::new(b"Evil transcript");

        // Verification should fail
        assert!(TriptychProof::verify_batch(&statements, &proofs, &mut transcripts).is_err());
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify_invalid_batch_single_blame() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;

        // Test against batches of even and odd size
        for batch in [4, 5] {
            let mut rng = ChaCha12Rng::seed_from_u64(8675309);
            let (witnesses, statements, transcripts) = generate_data(n, m, batch, &mut rng);

            // Generate the proofs
            let proofs = izip!(witnesses.iter(), statements.iter(), transcripts.clone().iter_mut())
                .map(|(w, s, t)| TriptychProof::prove_with_rng_vartime(w, s, &mut rng, t).unwrap())
                .collect::<Vec<TriptychProof>>();

            // Iteratively manipulate each transcript to make the corresponding proof invalid
            for i in 0..proofs.len() {
                let mut evil_transcripts = transcripts.clone();
                evil_transcripts[i] = Transcript::new(b"Evil transcript");

                // Verification should fail and blame the correct proof
                let error = TriptychProof::verify_batch_with_single_blame(&statements, &proofs, &mut evil_transcripts)
                    .unwrap_err();
                if let ProofError::FailedBatchVerificationWithSingleBlame { index: Some(index) } = error {
                    assert_eq!(index, i);
                } else {
                    panic!();
                }
            }
        }
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_prove_verify_invalid_batch_full_blame() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        const batch: usize = 4;
        const failures: [usize; 2] = [1, 3];

        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, batch, &mut rng);

        // Generate the proofs
        let proofs = izip!(witnesses.iter(), statements.iter(), transcripts.clone().iter_mut())
            .map(|(w, s, t)| TriptychProof::prove_with_rng_vartime(w, s, &mut rng, t).unwrap())
            .collect::<Vec<TriptychProof>>();

        // Manipulate some of the transcripts to make the corresponding proofs invalid
        for i in failures {
            transcripts[i] = Transcript::new(b"Evil transcript");
        }

        // Verification should fail and blame the correct proof
        let error = TriptychProof::verify_batch_with_full_blame(&statements, &proofs, &mut transcripts).unwrap_err();
        if let ProofError::FailedBatchVerificationWithFullBlame { indexes } = error {
            assert_eq!(indexes, failures);
        } else {
            panic!();
        }
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_evil_message() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate a proof
        let proof = TriptychProof::prove_with_rng_vartime(&witnesses[0], &statements[0], &mut rng, &mut transcripts[0])
            .unwrap();

        // Generate a modified transcript
        let mut evil_transcript = Transcript::new(b"Evil transcript");

        // Attempt to verify the proof against the new statement, which should fail
        assert!(proof.verify(&statements[0], &mut evil_transcript).is_err());
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_evil_input_set() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate a proof
        let proof =
            TriptychProof::prove_with_rng_vartime(&witnesses[0], &statements[0], &mut rng, &mut transcripts[0].clone())
                .unwrap();

        // Generate a statement with a modified input set
        let mut M = statements[0].get_input_set().get_keys().to_vec();
        let index = ((witnesses[0].get_l() + 1) % witnesses[0].get_params().get_N()) as usize;
        M[index] = RistrettoPoint::random(&mut rng);
        let evil_input_set = Arc::new(TriptychInputSet::new(&M).unwrap());
        let evil_statement =
            TriptychStatement::new(statements[0].get_params(), &evil_input_set, statements[0].get_J()).unwrap();

        // Attempt to verify the proof against the new statement, which should fail
        assert!(proof.verify(&evil_statement, &mut transcripts[0]).is_err());
    }

    #[test]
    #[allow(non_snake_case, non_upper_case_globals)]
    fn test_evil_linking_tag() {
        // Generate data
        const n: u32 = 2;
        const m: u32 = 4;
        let mut rng = ChaCha12Rng::seed_from_u64(8675309);
        let (witnesses, statements, mut transcripts) = generate_data(n, m, 1, &mut rng);

        // Generate a proof
        let proof =
            TriptychProof::prove_with_rng_vartime(&witnesses[0], &statements[0], &mut rng, &mut transcripts[0].clone())
                .unwrap();

        // Generate a statement with a modified linking tag
        let evil_statement = TriptychStatement::new(
            statements[0].get_params(),
            statements[0].get_input_set(),
            &RistrettoPoint::random(&mut rng),
        )
        .unwrap();

        // Attempt to verify the proof against the new statement, which should fail
        assert!(proof.verify(&evil_statement, &mut transcripts[0]).is_err());
    }
}