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
use eth_types::Field;
use halo2::{circuit::Region, halo2curves::CurveExt};
use halo2_proofs::{
    circuit::{AssignedCell, Layouter, Value},
    halo2curves::{
        group::prime::PrimeCurveAffine, pairing::Engine, serde::SerdeObject, CurveAffine,
    },
    plonk::{ConstraintSystem, Error},
    poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG},
};
use itertools::Itertools;
use rand::{rngs::StdRng, SeedableRng};
use snark_verifier::{
    loader::{
        self,
        halo2::{
            halo2_wrong_ecc::{self, integer::rns::Rns, maingate::*, EccConfig},
            EcPoint, Scalar,
        },
        native::NativeLoader,
    },
    pcs::{
        kzg::*, AccumulationDecider, AccumulationScheme, AccumulationSchemeProver,
        PolynomialCommitmentScheme,
    },
    system::halo2::transcript,
    util::{
        arithmetic::{fe_to_limbs, FromUniformBytes, MultiMillerLoop, PrimeField},
        transcript::Transcript,
    },
    verifier::{
        self,
        plonk::{PlonkProof, PlonkProtocol},
        SnarkVerifier,
    },
};
use std::{io, iter, rc::Rc};

use super::UserChallenge;

/// Number of limbs to decompose a elliptic curve base field element into.
pub const LIMBS: usize = 4;
/// Number of bits of each decomposed limb.
pub const BITS: usize = 68;

/// KZG accumulation scheme with GWC19 multiopen.
pub type Gwc<M> = KzgAs<M, Gwc19>;
/// KZG accumulation scheme with BDFG21 multiopen.
pub type Shplonk<M> = KzgAs<M, Bdfg21>;
/// KZG succinct verifying key
pub type KzgSvk<M> = KzgSuccinctVerifyingKey<<M as Engine>::G1Affine>;
/// KZG deciding key
pub type KzgDk<M> = KzgDecidingKey<M>;
/// Plonk succinct verifier with `KzgAs`
pub type PlonkSuccinctVerifier<As> = verifier::plonk::PlonkSuccinctVerifier<As>;
/// Plonk verifier with `KzgAs` and `LimbsEncoding<LIMBS, BITS>`.
pub type PlonkVerifier<As> = verifier::plonk::PlonkVerifier<As, LimbsEncoding<LIMBS, BITS>>;

const T: usize = 5;
const RATE: usize = 4;
const R_F: usize = 8;
const R_P: usize = 60;

/// `BaseFieldEccChip` with hardcoded `LIMBS` and `BITS` serving as `EccChip`
/// for `Halo2Loader`.
pub type EccChip<C> = halo2_wrong_ecc::BaseFieldEccChip<C, LIMBS, BITS>;
/// `Halo2Loader` with hardcoded `EccChip`.
pub type Halo2Loader<'a, C> = loader::halo2::Halo2Loader<'a, C, EccChip<C>>;
/// `LoadedScalar` with hardcoded `EccChip`.
pub type LoadedScalar<'a, C> = Scalar<'a, C, EccChip<C>>;
/// `PoseidonTranscript` with hardcoded parameter with 128-bits security.
pub type PoseidonTranscript<C, S> =
    transcript::halo2::PoseidonTranscript<C, NativeLoader, S, T, RATE, R_F, R_P>;

/// Snark contains the minimal information for verification
#[derive(Clone, Copy)]
pub struct Snark<'a, C: CurveAffine> {
    protocol: &'a PlonkProtocol<C>,
    pub(crate) instances: &'a Vec<Vec<C::Scalar>>,
    proof: &'a [u8],
}

impl<'a, C: CurveAffine> Snark<'a, C> {
    /// Construct `Snark` with each field.
    pub fn new(
        protocol: &'a PlonkProtocol<C>,
        instances: &'a Vec<Vec<C::Scalar>>,
        proof: &'a [u8],
    ) -> Self {
        Self {
            protocol,
            instances,
            proof,
        }
    }
}

impl<'a, C: CurveAffine> From<Snark<'a, C>> for SnarkWitness<'a, C> {
    fn from(snark: Snark<'a, C>) -> Self {
        Self {
            protocol: snark.protocol,
            instances: Value::known(snark.instances),
            proof: Value::known(snark.proof),
        }
    }
}

/// SnarkWitness
#[derive(Clone, Copy)]
pub struct SnarkWitness<'a, C: CurveAffine> {
    /// protocol
    pub protocol: &'a PlonkProtocol<C>,
    /// instance
    pub instances: Value<&'a Vec<Vec<C::Scalar>>>,
    /// proof
    pub proof: Value<&'a [u8]>,
}

impl<'a, C: CurveAffine> SnarkWitness<'a, C> {
    /// Construct `SnarkWitness` with each field.
    pub fn new(
        protocol: &'a PlonkProtocol<C>,
        instances: Value<&'a Vec<Vec<C::Scalar>>>,
        proof: Value<&'a [u8]>,
    ) -> Self {
        Self {
            protocol,
            instances,
            proof,
        }
    }

    /// Returns `SnarkWitness` with all witness as `Value::unknown()`.
    pub fn without_witnesses(&self) -> Self {
        SnarkWitness {
            protocol: self.protocol,
            instances: Value::unknown(),
            proof: Value::unknown(),
        }
    }

    /// Returns protocol as reference.
    pub fn protocol(&self) -> &PlonkProtocol<C> {
        self.protocol
    }

    /// Returns proof as reference.
    pub fn proof(&self) -> Value<&[u8]> {
        self.proof
    }

    fn loaded_instances<'b>(
        &self,
        loader: &Rc<Halo2Loader<'b, C>>,
    ) -> Vec<Vec<Scalar<'b, C, EccChip<C>>>> {
        self.instances
            .transpose_vec(self.protocol.num_instance.len())
            .into_iter()
            .zip(self.protocol.num_instance.iter())
            .map(|(instances, num_instance)| {
                instances
                    .transpose_vec(*num_instance)
                    .into_iter()
                    .map(|instance| loader.assign_scalar(instance.copied()))
                    .collect_vec()
            })
            .collect_vec()
    }
}

/// Aggregation configuration.
#[derive(Clone)]
pub struct AggregationConfig {
    /// MainGateConfig
    pub main_gate_config: MainGateConfig,
    /// RangeConfig
    pub range_config: RangeConfig,
}

impl AggregationConfig {
    /// Configure for `MainGate` and `RangeChip` with corresponding fixed lookup
    /// table.
    pub fn configure<C: CurveAffine>(meta: &mut ConstraintSystem<C::Scalar>) -> Self {
        let main_gate_config = MainGate::<C::Scalar>::configure(meta);
        let range_config = RangeChip::<C::Scalar>::configure(
            meta,
            &main_gate_config,
            vec![BITS / LIMBS],
            Rns::<C::Base, C::Scalar, LIMBS, BITS>::construct().overflow_lengths(),
        );
        Self {
            main_gate_config,
            range_config,
        }
    }

    /// Returns `MainGate`.
    pub fn main_gate<F: Field>(&self) -> MainGate<F> {
        MainGate::new(self.main_gate_config.clone())
    }

    /// Returns `RangeChip`.
    pub fn range_chip<F: Field>(&self) -> RangeChip<F> {
        RangeChip::new(self.range_config.clone())
    }

    /// Returns `EccChip`.
    pub fn ecc_chip<C: CurveAffine>(&self) -> EccChip<C> {
        EccChip::new(EccConfig::new(
            self.range_config.clone(),
            self.main_gate_config.clone(),
        ))
    }

    /// Load fixed lookup table for `RangeChip`
    pub fn load_table<F: Field>(&self, layouter: &mut impl Layouter<F>) -> Result<(), Error> {
        self.range_chip().load_table(layouter)
    }

    /// named columns in region
    pub fn named_column_in_region<F: Field>(&self, region: &mut Region<'_, F>) {
        // annotate advices columns of `main_gate`. We can't annotate fixed_columns of
        // `main_gate` bcs there is no methods exported.
        for (i, col) in self.main_gate_config.advices().iter().enumerate() {
            region.name_column(|| format!("ROOT_main_gate_{}", i), *col);
        }
    }

    /// Aggregate witnesses into challenge and return
    #[allow(clippy::type_complexity)]
    pub fn aggregate_user_challenges<'c, M, As>(
        &self,
        loader: Rc<Halo2Loader<'c, M::G1Affine>>,
        user_challenges: Option<&UserChallenge>,
        proofs: Vec<PlonkProof<M::G1Affine, Rc<Halo2Loader<'c, M::G1Affine>>, As>>,
    ) -> Result<
        (
            Vec<LoadedScalar<'c, M::G1Affine>>,
            Vec<EcPoint<'c, M::G1Affine, EccChip<M::G1Affine>>>,
        ),
        Error,
    >
    where
        M: MultiMillerLoop,
        M::Fr: Field,
        M::G1Affine: CurveAffine<ScalarExt = M::Fr>,
        for<'b> As: PolynomialCommitmentScheme<
                M::G1Affine,
                Rc<Halo2Loader<'b, M::G1Affine>>,
                VerifyingKey = KzgSvk<M>,
                Output = KzgAccumulator<M::G1Affine, Rc<Halo2Loader<'b, M::G1Affine>>>,
            > + AccumulationScheme<
                M::G1Affine,
                Rc<Halo2Loader<'b, M::G1Affine>>,
                Accumulator = KzgAccumulator<M::G1Affine, Rc<Halo2Loader<'b, M::G1Affine>>>,
                VerifyingKey = KzgAsVerifyingKey,
            >,
    {
        type PoseidonTranscript<'a, C, S> =
            transcript::halo2::PoseidonTranscript<C, Rc<Halo2Loader<'a, C>>, S, T, RATE, R_F, R_P>;

        let witnesses = proofs
            .iter()
            .flat_map(|proof| {
                user_challenges
                    .map(|user_challenges| {
                        user_challenges
                            .column_indexes
                            .iter()
                            .map(|col| &proof.witnesses[col.index()])
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            })
            .collect_vec();

        let empty_proof = Vec::new();
        let mut transcript = PoseidonTranscript::new(&loader, Value::known(empty_proof.as_slice()));
        witnesses.iter().for_each(|rwtable_col_ec_point| {
            transcript.common_ec_point(rwtable_col_ec_point).unwrap();
        });
        let num_challenges = user_challenges
            .map(|user_challenges| user_challenges.num_challenges)
            .unwrap_or_default();

        let witnesses = witnesses
            .into_iter()
            .cloned()
            .collect::<Vec<EcPoint<'c, M::G1Affine, EccChip<M::G1Affine>>>>();
        Ok((transcript.squeeze_n_challenges(num_challenges), witnesses))
    }

    /// Aggregate snarks into a single accumulator and decompose it into
    /// `4 * LIMBS` limbs.
    /// Returns assigned instances of snarks and aggregated accumulator limbs.
    #[allow(clippy::type_complexity)]
    pub fn aggregate<'a, 'c, M, As>(
        &self,
        ctx: RegionCtx<'c, M::Fr>,
        svk: &KzgSvk<M>,
        snarks: &[SnarkWitness<'a, M::G1Affine>],
    ) -> Result<
        (
            Vec<Vec<Scalar<'c, M::G1Affine, EccChip<M::G1Affine>>>>,
            Vec<AssignedCell<M::Fr, M::Fr>>,
            Rc<Halo2Loader<'c, M::G1Affine>>,
            Vec<PlonkProof<M::G1Affine, Rc<Halo2Loader<'c, M::G1Affine>>, As>>,
        ),
        Error,
    >
    where
        M: MultiMillerLoop,
        M::Fr: Field,
        M::G1Affine: CurveAffine<ScalarExt = M::Fr>,
        for<'b> As: PolynomialCommitmentScheme<
                M::G1Affine,
                Rc<Halo2Loader<'b, M::G1Affine>>,
                VerifyingKey = KzgSvk<M>,
                Output = KzgAccumulator<M::G1Affine, Rc<Halo2Loader<'b, M::G1Affine>>>,
            > + AccumulationScheme<
                M::G1Affine,
                Rc<Halo2Loader<'b, M::G1Affine>>,
                Accumulator = KzgAccumulator<M::G1Affine, Rc<Halo2Loader<'b, M::G1Affine>>>,
                VerifyingKey = KzgAsVerifyingKey,
            >,
    {
        let ecc_chip = self.ecc_chip::<M::G1Affine>();
        let loader = Halo2Loader::<'c, _>::new(ecc_chip, ctx);

        type PoseidonTranscript<'a, C, S> =
            transcript::halo2::PoseidonTranscript<C, Rc<Halo2Loader<'a, C>>, S, T, RATE, R_F, R_P>;

        let mut plonk_svp = vec![];
        // Verify the cheap part and get accumulator (left-hand and right-hand side of
        // pairing) of individual proof.
        // Verify the cheap part and get accumulator (left-hand and right-hand side of
        // pairing) of individual proof.
        let (instances, accumulators) = snarks
            .iter()
            .map(|snark| {
                let protocol = snark.protocol.loaded(&loader);

                let instances = snark.loaded_instances(&loader);
                let mut transcript = PoseidonTranscript::new(&loader, snark.proof());
                let proof = PlonkSuccinctVerifier::<As>::read_proof(
                    svk,
                    &protocol,
                    &instances,
                    &mut transcript,
                )
                .unwrap();
                let accumulators =
                    PlonkSuccinctVerifier::verify(svk, &protocol, &instances, &proof).unwrap();
                plonk_svp.push(proof);
                (instances, accumulators)
            })
            .collect_vec()
            .into_iter()
            .unzip::<_, _, Vec<_>, Vec<_>>();

        // Verify proof for accumulation of all accumulators into new one.
        let accumulator = {
            let as_vk = Default::default();
            let as_proof = Vec::new();
            let accumulators = accumulators.into_iter().flatten().collect_vec();
            let mut transcript =
                PoseidonTranscript::new(&loader, Value::known(as_proof.as_slice()));
            let proof = <As as AccumulationScheme<_, _>>::read_proof(
                &as_vk,
                &accumulators,
                &mut transcript,
            )
            .unwrap();
            <As as AccumulationScheme<_, _>>::verify(&as_vk, &accumulators, &proof).unwrap()
        };

        let instances = instances
            .iter()
            .map(|instances| {
                instances
                    .iter()
                    .flat_map(|instances| {
                        instances
                            .iter()
                            .map(|instance| instance.to_owned())
                            .collect_vec()
                    })
                    .collect_vec()
            })
            .collect_vec();

        let accumulator_limbs = [accumulator.lhs, accumulator.rhs]
            .iter()
            .map(|ec_point| {
                loader
                    .ecc_chip()
                    .assign_ec_point_to_limbs(&mut loader.ctx_mut(), ec_point.assigned())
            })
            .collect::<Result<Vec<_>, Error>>()?
            .into_iter()
            .flatten()
            .collect();

        Ok((instances, accumulator_limbs, loader, plonk_svp))
    }
}

/// Aggregate snarks into a single accumulator and decompose it into
/// `4 * LIMBS` limbs.
/// Returns `None` if any given snarks is invalid.
pub fn aggregate<'a, M, As>(
    params: &ParamsKZG<M>,
    snarks: impl IntoIterator<Item = Snark<'a, M::G1Affine>>,
) -> Result<[M::Fr; 4 * LIMBS], snark_verifier::Error>
where
    M: MultiMillerLoop,
    M::Fr: PrimeField + FromUniformBytes<64>,
    M::G1: CurveExt<AffineExt = M::G1Affine, ScalarExt = M::Fr>,
    M::G1Affine: SerdeObject + CurveAffine<ScalarExt = M::Fr, CurveExt = M::G1>,
    M::G2Affine: SerdeObject + CurveAffine,
    for<'b> As: PolynomialCommitmentScheme<
            M::G1Affine,
            NativeLoader,
            VerifyingKey = KzgSvk<M>,
            Output = KzgAccumulator<M::G1Affine, NativeLoader>,
        > + AccumulationSchemeProver<
            M::G1Affine,
            Accumulator = KzgAccumulator<M::G1Affine, NativeLoader>,
            ProvingKey = KzgAsProvingKey<M::G1Affine>,
        > + AccumulationDecider<M::G1Affine, NativeLoader, DecidingKey = KzgDecidingKey<M>>,
{
    let svk = KzgSvk::<M>::new(params.get_g()[0]);
    let dk = KzgDk::new(svk, params.g2(), params.s_g2());

    // Use the same logic of verifier to get accumulator (left-hand and right-hand
    // side of pairing) of individual proof.
    let accumulators = snarks
        .into_iter()
        .map(|snark| {
            let mut transcript = PoseidonTranscript::new(snark.proof);
            let proof = PlonkSuccinctVerifier::<As>::read_proof(
                &svk,
                snark.protocol,
                snark.instances,
                &mut transcript,
            )?;
            for commitment in iter::empty()
                .chain(snark.protocol.preprocessed.iter())
                .chain(proof.witnesses.iter())
                .chain(proof.quotients.iter())
            {
                if bool::from(commitment.is_identity()) {
                    return Err(snark_verifier::Error::Transcript(
                        io::ErrorKind::Other,
                        "Identity point in preprocessed or proof is not yet supported".to_string(),
                    ));
                }
            }
            PlonkSuccinctVerifier::verify(&svk, snark.protocol, snark.instances, &proof)
        })
        .try_collect::<_, Vec<_>, _>()?
        .into_iter()
        .flatten()
        .collect_vec();

    // Create proof for accumulation of all accumulators into new one.
    // In our case (KZG without zero-knowledge), it's no-ops since the verifier
    // could add up the accumulators into the new one itself in circuit.
    let accumulator = {
        let as_pk = Default::default();
        let rng = StdRng::from_seed(Default::default());
        let mut transcript = PoseidonTranscript::new(Vec::new());
        let accumulator = As::create_proof(&as_pk, &accumulators, &mut transcript, rng)?;
        assert!(transcript.finalize().is_empty());
        accumulator
    };
    As::decide(&dk, accumulator.clone())?;

    let KzgAccumulator { lhs, rhs } = accumulator;
    let accumulator_limbs = [lhs, rhs]
        .into_iter()
        .flat_map(|point| {
            let coordinates = point.coordinates().unwrap();
            [*coordinates.x(), *coordinates.y()]
        })
        .flat_map(fe_to_limbs::<_, _, LIMBS, BITS>)
        .collect_vec()
        .try_into()
        .unwrap();
    Ok(accumulator_limbs)
}

/// Contains TestAggregationCircuit to test whether aggregation is working for
/// any given inputs.
#[cfg(test)]
pub mod test {
    use crate::root_circuit::{
        aggregation::Gwc, PoseidonTranscript, Snark, TestAggregationCircuit,
    };
    use eth_types::Field;
    use halo2_proofs::{
        arithmetic::Field as Halo2Field,
        circuit::{floor_planner::V1, Layouter, Value},
        dev::{FailureLocation, MockProver, VerifyFailure},
        halo2curves::{
            bn256::{Bn256, Fr, G1Affine},
            CurveAffine,
        },
        plonk::{
            create_proof, keygen_pk, keygen_vk, Advice, Any, Circuit, Column, ConstraintSystem,
            Error, Fixed,
        },
        poly::{
            kzg::{
                commitment::{KZGCommitmentScheme, ParamsKZG},
                multiopen::ProverGWC,
            },
            Rotation,
        },
    };
    use itertools::Itertools;
    use rand::{rngs::OsRng, RngCore};
    use snark_verifier::{
        system::halo2::{compile, Config},
        verifier::plonk::PlonkProtocol,
    };
    use std::iter;

    #[derive(Clone)]
    pub struct SnarkOwned<C: CurveAffine> {
        protocol: PlonkProtocol<C>,
        instances: Vec<Vec<C::Scalar>>,
        proof: Vec<u8>,
    }

    impl<C: CurveAffine> SnarkOwned<C> {
        pub fn new(
            protocol: PlonkProtocol<C>,
            instances: Vec<Vec<C::Scalar>>,
            proof: Vec<u8>,
        ) -> Self {
            Self {
                protocol,
                instances,
                proof,
            }
        }

        pub fn as_snark(&self) -> Snark<C> {
            Snark {
                protocol: &self.protocol,
                instances: &self.instances,
                proof: &self.proof,
            }
        }
    }

    /// Configuration for `StandardPlonk`
    #[derive(Clone)]
    pub struct StandardPlonkConfig {
        selectors: [Column<Fixed>; 5],
        wires: [Column<Advice>; 3],
    }

    impl StandardPlonkConfig {
        /// Configure for `StandardPlonk`
        pub fn configure<F: Field>(meta: &mut ConstraintSystem<F>) -> Self {
            let [w_l, w_r, w_o] = [(); 3].map(|_| meta.advice_column());
            let [q_l, q_r, q_o, q_m, q_c] = [(); 5].map(|_| meta.fixed_column());
            let pi = meta.instance_column();
            [w_l, w_r, w_o].map(|column| meta.enable_equality(column));
            meta.create_gate(
                "q_l·w_l + q_r·w_r + q_o·w_o + q_m·w_l·w_r + q_c + pi = 0",
                |meta| {
                    let [w_l, w_r, w_o] =
                        [w_l, w_r, w_o].map(|column| meta.query_advice(column, Rotation::cur()));
                    let [q_l, q_r, q_o, q_m, q_c] = [q_l, q_r, q_o, q_m, q_c]
                        .map(|column| meta.query_fixed(column, Rotation::cur()));
                    let pi = meta.query_instance(pi, Rotation::cur());
                    Some(
                        q_l * w_l.clone()
                            + q_r * w_r.clone()
                            + q_o * w_o
                            + q_m * w_l * w_r
                            + q_c
                            + pi,
                    )
                },
            );
            StandardPlonkConfig {
                selectors: [q_l, q_r, q_o, q_m, q_c],
                wires: [w_l, w_r, w_o],
            }
        }
    }

    /// Standard plonk with few assignments for testing purpose.
    #[derive(Clone, Copy)]
    pub struct StandardPlonk<F>(F);

    impl<F: Field> StandardPlonk<F> {
        /// Create a `StandardPlonk` with random instance.
        pub fn rand<R: RngCore>(mut rng: R) -> Self {
            Self(F::from(rng.next_u32() as u64))
        }

        /// Returns instances.
        pub fn instances(&self) -> Vec<Vec<F>> {
            vec![vec![self.0]]
        }
    }

    impl<F: Field> Circuit<F> for StandardPlonk<F> {
        type Config = StandardPlonkConfig;
        type FloorPlanner = V1;
        type Params = ();

        fn without_witnesses(&self) -> Self {
            *self
        }

        fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
            meta.set_minimum_degree(4);
            StandardPlonkConfig::configure(meta)
        }

        fn synthesize(
            &self,
            config: Self::Config,
            mut layouter: impl Layouter<F>,
        ) -> Result<(), Error> {
            let [q_l, q_r, q_o, q_m, q_c] = config.selectors;
            let [w_l, w_r, w_o] = config.wires;
            layouter.assign_region(
                || "",
                |mut region| {
                    // Assign some non-zero values to make sure the advice/fixed columns have
                    // non-identity commitments.
                    let a = region.assign_advice(|| "", w_l, 0, || Value::known(self.0))?;
                    region.assign_fixed(|| "", q_l, 0, || Value::known(-F::ONE))?;
                    a.copy_advice(|| "", &mut region, w_r, 1)?;
                    a.copy_advice(|| "", &mut region, w_o, 2)?;
                    region.assign_advice(|| "", w_l, 3, || Value::known(-F::from(5)))?;
                    for (column, idx) in [q_l, q_r, q_o, q_m, q_c].iter().zip(1..) {
                        region.assign_fixed(|| "", *column, 3, || Value::known(F::from(idx)))?;
                    }
                    Ok(())
                },
            )
        }
    }

    /// Create random `StandardPlonk` and returns `Snark`s for them.
    pub fn rand_standard_plonk_snarks(
        params: &ParamsKZG<Bn256>,
        n: usize,
    ) -> Vec<SnarkOwned<G1Affine>> {
        // Preprocess
        let (pk, protocol) = {
            let standard_plonk = StandardPlonk(Fr::ZERO);
            let vk = keygen_vk(params, &standard_plonk).unwrap();
            let pk = keygen_pk(params, vk, &standard_plonk).unwrap();
            let protocol = compile(
                params,
                pk.get_vk(),
                Config::kzg().with_num_instance(
                    standard_plonk
                        .instances()
                        .iter()
                        .map(|instances| instances.len())
                        .collect(),
                ),
            );
            (pk, protocol)
        };

        // Create snarks
        iter::repeat_with(move || {
            let standard_plonk = StandardPlonk::<Fr>::rand(OsRng);
            let instances = standard_plonk.instances();
            let proof = {
                let mut transcript = PoseidonTranscript::new(Vec::new());
                create_proof::<KZGCommitmentScheme<_>, ProverGWC<_>, _, _, _, _>(
                    params,
                    &pk,
                    &[standard_plonk],
                    &[&instances.iter().map(Vec::as_slice).collect_vec()],
                    OsRng,
                    &mut transcript,
                )
                .unwrap();
                transcript.finalize()
            };
            SnarkOwned::new(protocol.clone(), instances, proof)
        })
        .take(n)
        .collect()
    }

    #[test]
    fn test_standard_plonk_aggregation() {
        let params = ParamsKZG::<Bn256>::setup(8, OsRng);

        // Create Aggregation circuit and compute aggregated accumulator
        let snarks = rand_standard_plonk_snarks(&params, 2);
        let aggregation = TestAggregationCircuit::<Bn256, Gwc<_>>::new(
            &params,
            snarks.iter().map(SnarkOwned::as_snark),
            None,
        )
        .unwrap();
        let instances = aggregation.instances();
        assert_eq!(
            MockProver::run(21, &aggregation, instances)
                .unwrap()
                .verify(),
            Ok(())
        );
    }

    #[test]
    fn test_standard_plonk_aggregation_unmatched_instance() {
        let params = ParamsKZG::<Bn256>::setup(8, OsRng);

        // Create Aggregation circuit and compute aggregated accumulator
        let snarks = rand_standard_plonk_snarks(&params, 2);
        let aggregation = TestAggregationCircuit::<Bn256, Gwc<_>>::new(
            &params,
            snarks.iter().map(SnarkOwned::as_snark),
            None,
        )
        .unwrap();
        let mut instances = aggregation.instances();
        // Change the propagated inner snark's instance
        instances[0][0] += Fr::ONE;
        // Then expect the verification to fail
        assert_eq!(
            MockProver::run(21, &aggregation, instances)
                .unwrap()
                .verify(),
            Err(vec![
                VerifyFailure::Permutation {
                    column: (Any::advice(), 0).into(),
                    location: FailureLocation::InRegion {
                        region: (1, "Aggregate snarks").into(),
                        offset: 0
                    }
                },
                VerifyFailure::Permutation {
                    column: (Any::Instance, 0).into(),
                    location: FailureLocation::OutsideRegion { row: 0 }
                }
            ])
        );
    }
}