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
//! The Root circuit implementation.
use eth_types::Field;
use halo2_proofs::{
    arithmetic::Field as Halo2Field,
    circuit::{Layouter, SimpleFloorPlanner, Value},
    halo2curves::{serde::SerdeObject, CurveAffine, CurveExt},
    plonk::{Any, Circuit, Column, ConstraintSystem, Error},
    poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG},
};
use itertools::Itertools;
use maingate::{MainGateInstructions, RegionCtx};

use snark_verifier::{
    pcs::{
        kzg::{KzgAccumulator, KzgAsProvingKey, KzgAsVerifyingKey, KzgDecidingKey},
        AccumulationDecider, AccumulationScheme, AccumulationSchemeProver,
        PolynomialCommitmentScheme,
    },
    util::arithmetic::MultiMillerLoop,
    verifier::plonk::PlonkProtocol,
};
use std::{marker::PhantomData, rc::Rc};

mod aggregation;

#[cfg(any(test, feature = "test-circuits"))]
mod dev;
#[cfg(test)]
mod test;

#[cfg(feature = "test-circuits")]
pub use self::RootCircuit as TestRootCircuit;

#[cfg(any(feature = "test-circuits", test))]
pub use dev::TestAggregationCircuit;

pub use aggregation::{
    aggregate, AggregationConfig, EccChip, Gwc, Halo2Loader, KzgDk, KzgSvk, PlonkSuccinctVerifier,
    PlonkVerifier, PoseidonTranscript, Shplonk, Snark, SnarkWitness, BITS, LIMBS,
};
pub use snark_verifier::{
    loader::native::NativeLoader,
    system::halo2::{compile, transcript::evm::EvmTranscript, Config},
};

const NUM_OF_SUPERCIRCUIT_INSTANCES: usize = 2;

/// SuperCircuitInstance is to demystifying supercircuit instance to meaningful name.
#[derive(Clone)]
struct SuperCircuitInstance<T> {
    // chunk_ctx
    pub chunk_index: T,
    pub chunk_index_next: T,
    pub total_chunk: T,
    pub initial_rwc: T,
    pub end_rwc: T,

    // pi circuit
    pub pi_digest_lo: T,
    pub pi_digest_hi: T,

    // state circuit
    pub sc_permu_alpha: T,
    pub sc_permu_gamma: T,
    pub sc_rwtable_row_prev_fingerprint: T,
    pub sc_rwtable_row_curr_fingerprint: T,
    pub sc_rwtable_prev_fingerprint: T,
    pub sc_rwtable_curr_fingerprint: T,

    // evm circuit
    pub ec_permu_alpha: T,
    pub ec_permu_gamma: T,
    pub ec_rwtable_row_prev_fingerprint: T,
    pub ec_rwtable_row_curr_fingerprint: T,
    pub ec_rwtable_prev_fingerprint: T,
    pub ec_rwtable_curr_fingerprint: T,
}

impl<T: Clone + Copy> SuperCircuitInstance<T> {
    /// Construct `SnarkInstance` with vector
    pub fn new(instances: impl IntoIterator<Item = T>) -> Self {
        let mut iter_instances = instances.into_iter();
        Self {
            chunk_index: iter_instances.next().unwrap(),
            total_chunk: iter_instances.next().unwrap(),
            initial_rwc: iter_instances.next().unwrap(),
            chunk_index_next: iter_instances.next().unwrap(),
            end_rwc: iter_instances.next().unwrap(),
            pi_digest_lo: iter_instances.next().unwrap(),
            pi_digest_hi: iter_instances.next().unwrap(),
            sc_permu_alpha: iter_instances.next().unwrap(),
            sc_permu_gamma: iter_instances.next().unwrap(),
            sc_rwtable_row_prev_fingerprint: iter_instances.next().unwrap(),
            sc_rwtable_row_curr_fingerprint: iter_instances.next().unwrap(),
            sc_rwtable_prev_fingerprint: iter_instances.next().unwrap(),
            sc_rwtable_curr_fingerprint: iter_instances.next().unwrap(),
            ec_permu_alpha: iter_instances.next().unwrap(),
            ec_permu_gamma: iter_instances.next().unwrap(),
            ec_rwtable_row_prev_fingerprint: iter_instances.next().unwrap(),
            ec_rwtable_row_curr_fingerprint: iter_instances.next().unwrap(),
            ec_rwtable_prev_fingerprint: iter_instances.next().unwrap(),
            ec_rwtable_curr_fingerprint: iter_instances.next().unwrap(),
        }
    }
}

/// UserChallenge
#[derive(Clone)]
pub struct UserChallenge {
    /// column_indexes
    pub column_indexes: Vec<Column<Any>>,
    /// num_challenges
    pub num_challenges: usize,
}

/// RootCircuit for aggregating SuperCircuit into a much smaller proof.
#[derive(Clone)]
pub struct RootCircuit<'a, M: MultiMillerLoop, As>
where
    M::G1Affine: CurveAffine,
{
    svk: KzgSvk<M>,
    protocol: &'a PlonkProtocol<M::G1Affine>,
    snark_witnesses: Vec<SnarkWitness<'a, M::G1Affine>>,
    instance: Vec<M::Fr>,
    user_challenges: Option<&'a UserChallenge>,
    _marker: PhantomData<As>,
}

impl<'a, M, As> RootCircuit<'a, M, As>
where
    M: MultiMillerLoop,
    M::Fr: Field,
    M::G1: CurveExt<AffineExt = M::G1Affine, ScalarExt = M::Fr>,
    M::G1Affine: SerdeObject + CurveAffine<ScalarExt = M::Fr, CurveExt = M::G1>,
    M::G2Affine: SerdeObject + CurveAffine,
    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>>,
{
    /// Create a `RootCircuit` with accumulator computed given a `SuperCircuit`
    /// proof and its instance. Returns `None` if given proof is invalid.
    pub fn new(
        params: &ParamsKZG<M>,
        protocol: &'a PlonkProtocol<M::G1Affine>,
        snark_witnesses: Vec<SnarkWitness<'a, M::G1Affine>>,
        user_challenges: Option<&'a UserChallenge>,
    ) -> Result<Self, snark_verifier::Error> {
        let num_raw_instances = protocol.num_instance.iter().sum::<usize>();

        // compute real instance value
        let (flatten_first_chunk_instances, accumulator_limbs) = {
            let (mut instance, mut accumulator_limbs) = (
                vec![M::Fr::ZERO; num_raw_instances],
                Ok(vec![M::Fr::ZERO; 4 * LIMBS]),
            );
            // compute aggregate_limbs
            snark_witnesses
                .iter()
                .fold(Value::known(vec![]), |acc_snark, snark_witness| {
                    snark_witness
                        .instances
                        .as_ref()
                        .zip(snark_witness.proof.as_ref())
                        .map(|(super_circuit_instances, super_circuit_proof)| {
                            Snark::new(protocol, super_circuit_instances, super_circuit_proof)
                        })
                        .zip(acc_snark)
                        .map(|(snark, mut acc_snark)| {
                            acc_snark.push(snark);
                            acc_snark
                        })
                })
                .map(|snarks| {
                    if !snarks.is_empty() {
                        accumulator_limbs = aggregate::<M, As>(params, snarks)
                            .map(|accumulator_limbs| accumulator_limbs.to_vec());
                    }
                });

            // retrieve first instance
            if let Some(snark_witness) = snark_witnesses.first() {
                snark_witness
                    .instances
                    .map(|instances| instance = instances.iter().flatten().cloned().collect_vec());
            }

            (instance, accumulator_limbs?)
        };

        debug_assert_eq!(flatten_first_chunk_instances.len(), num_raw_instances);
        let mut flatten_instance =
            exposed_instances(&SuperCircuitInstance::new(flatten_first_chunk_instances));
        flatten_instance.extend(accumulator_limbs);

        Ok(Self {
            svk: KzgSvk::<M>::new(params.get_g()[0]),
            protocol,
            snark_witnesses,
            instance: flatten_instance,
            user_challenges,
            _marker: PhantomData,
        })
    }

    /// Returns accumulator indices in instance columns, which will be in
    /// the last `4 * LIMBS` rows of instance column in `MainGate`.
    pub fn accumulator_indices(&self) -> Vec<(usize, usize)> {
        (NUM_OF_SUPERCIRCUIT_INSTANCES..)
            .map(|idx| (0, idx))
            .take(4 * LIMBS)
            .collect()
    }

    /// Returns number of instance
    pub fn num_instance(&self) -> Vec<usize> {
        vec![self.instance.len()]
    }

    /// Returns instance
    pub fn instance(&self) -> Vec<Vec<M::Fr>> {
        vec![self.instance.clone()]
    }
}

impl<'a, M, As> Circuit<M::Fr> for RootCircuit<'a, M, As>
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 Config = AggregationConfig;
    type FloorPlanner = SimpleFloorPlanner;
    type Params = ();

    fn without_witnesses(&self) -> Self {
        Self {
            svk: self.svk,
            protocol: self.protocol,
            snark_witnesses: self
                .snark_witnesses
                .iter()
                .map(|snark_witness| snark_witness.without_witnesses())
                .collect_vec(),
            user_challenges: self.user_challenges,
            instance: vec![M::Fr::ZERO; self.instance.len()],
            _marker: PhantomData,
        }
    }

    fn configure(meta: &mut ConstraintSystem<M::Fr>) -> Self::Config {
        AggregationConfig::configure::<M::G1Affine>(meta)
    }

    fn synthesize(
        &self,
        config: Self::Config,
        mut layouter: impl Layouter<M::Fr>,
    ) -> Result<(), Error> {
        config.load_table(&mut layouter)?;
        let key = &self.svk;
        let (instances, accumulator_limbs) = layouter.assign_region(
            || "Aggregate snarks",
            |mut region| {
                config.named_column_in_region(&mut region);
                let ctx = RegionCtx::new(region, 0);
                let (loaded_instances, accumulator_limbs, loader, proofs) =
                    config.aggregate::<M, As>(ctx, &key.clone(), &self.snark_witnesses)?;

                // aggregate user challenge for rwtable permutation challenge
                let (alpha, gamma) = {
                    let (mut challenges, _) = config.aggregate_user_challenges::<M, As>(
                        loader.clone(),
                        self.user_challenges,
                        proofs,
                    )?;
                    (challenges.remove(0), challenges.remove(0))
                };

                // convert vector instances SuperCircuitInstance struct
                let supercircuit_instances = loaded_instances
                    .iter()
                    .map(SuperCircuitInstance::new)
                    .collect::<Vec<SuperCircuitInstance<_>>>();

                // constraint first and last chunk
                supercircuit_instances
                    .first()
                    .zip(supercircuit_instances.last())
                    .map(|(first_chunk, _last)| {
                        // `last.sc_rwtable_next_fingerprint ==
                        // last.ec_rwtable_next_fingerprint` will be checked inside super circuit so
                        // here no need to checked
                        // Other field in last instances already be checked in chunk
                        // continuity

                        // define 0, 1, total_chunk as constant
                        let (zero_const, one_const, total_chunk_const) = {
                            let zero_const = loader
                                .scalar_chip()
                                .assign_constant(&mut loader.ctx_mut(), M::Fr::from(0))
                                .unwrap();
                            let one_const = loader
                                .scalar_chip()
                                .assign_constant(&mut loader.ctx_mut(), M::Fr::from(1))
                                .unwrap();
                            let total_chunk_const = loader
                                .scalar_chip()
                                .assign_constant(&mut loader.ctx_mut(), M::Fr::from(1))
                                .unwrap();

                            (zero_const, one_const, total_chunk_const)
                        };

                        // `first.sc_rwtable_row_prev_fingerprint ==
                        // first.ec_rwtable_row_prev_fingerprint` will be checked inside circuit
                        vec![
                            // chunk ctx
                            (first_chunk.chunk_index.assigned(), &zero_const),
                            (first_chunk.total_chunk.assigned(), &total_chunk_const),
                            // rwc
                            (first_chunk.initial_rwc.assigned(), &one_const),
                            // constraint permutation fingerprint
                            // challenge: alpha
                            (first_chunk.sc_permu_alpha.assigned(), &alpha.assigned()),
                            (first_chunk.ec_permu_alpha.assigned(), &alpha.assigned()),
                            // challenge: gamma
                            (first_chunk.sc_permu_gamma.assigned(), &gamma.assigned()),
                            (first_chunk.ec_permu_gamma.assigned(), &gamma.assigned()),
                            // fingerprint
                            (
                                first_chunk.ec_rwtable_prev_fingerprint.assigned(),
                                &one_const,
                            ),
                            (
                                first_chunk.sc_rwtable_prev_fingerprint.assigned(),
                                &one_const,
                            ),
                        ]
                        .iter()
                        .for_each(|(a, b)| {
                            loader
                                .scalar_chip()
                                .assert_equal(&mut loader.ctx_mut(), a, b)
                                .unwrap();
                        });

                        first_chunk
                    })
                    .expect("error");

                // constraint consistency between chunk
                supercircuit_instances.iter().tuple_windows().for_each(
                    |(instance_i, instance_i_plus_one)| {
                        vec![
                            (
                                instance_i.chunk_index_next.assigned(),
                                instance_i_plus_one.chunk_index.assigned(),
                            ),
                            (
                                instance_i.total_chunk.assigned(),
                                instance_i_plus_one.total_chunk.assigned(),
                            ),
                            (
                                instance_i.end_rwc.assigned(),
                                instance_i_plus_one.initial_rwc.assigned(),
                            ),
                            (
                                instance_i.pi_digest_lo.assigned(),
                                instance_i_plus_one.pi_digest_lo.assigned(),
                            ),
                            (
                                instance_i.pi_digest_hi.assigned(),
                                instance_i_plus_one.pi_digest_hi.assigned(),
                            ),
                            // state circuit
                            (
                                instance_i.sc_permu_alpha.assigned(),
                                instance_i_plus_one.sc_permu_alpha.assigned(),
                            ),
                            (
                                instance_i.sc_permu_gamma.assigned(),
                                instance_i_plus_one.sc_permu_gamma.assigned(),
                            ),
                            (
                                instance_i.sc_rwtable_row_curr_fingerprint.assigned(),
                                instance_i_plus_one
                                    .sc_rwtable_row_prev_fingerprint
                                    .assigned(),
                            ),
                            (
                                instance_i.sc_rwtable_curr_fingerprint.assigned(),
                                instance_i_plus_one.sc_rwtable_prev_fingerprint.assigned(),
                            ),
                            // evm circuit
                            (
                                instance_i.ec_permu_alpha.assigned(),
                                instance_i_plus_one.ec_permu_alpha.assigned(),
                            ),
                            (
                                instance_i.ec_permu_gamma.assigned(),
                                instance_i_plus_one.ec_permu_gamma.assigned(),
                            ),
                            (
                                instance_i.ec_rwtable_curr_fingerprint.assigned(),
                                instance_i_plus_one.ec_rwtable_prev_fingerprint.assigned(),
                            ),
                            (
                                instance_i.ec_rwtable_row_curr_fingerprint.assigned(),
                                instance_i_plus_one
                                    .ec_rwtable_row_prev_fingerprint
                                    .assigned(),
                            ),
                        ]
                        .iter()
                        .for_each(|(a, b)| {
                            loader
                                .scalar_chip()
                                .assert_equal(&mut loader.ctx_mut(), a, b)
                                .unwrap();
                        });
                    },
                );

                Ok((
                    exposed_instances(supercircuit_instances.first().unwrap())
                        .iter()
                        .map(|instance| instance.assigned().to_owned())
                        .collect_vec(),
                    accumulator_limbs,
                ))
            },
        )?;

        // Constrain equality to instance values
        let main_gate = config.main_gate();
        for (row, limb) in instances.into_iter().chain(accumulator_limbs).enumerate() {
            main_gate.expose_public(layouter.namespace(|| ""), limb, row)?;
        }

        Ok(())
    }
}

/// get instances to expose
fn exposed_instances<T: Copy>(supercircuit_instances: &SuperCircuitInstance<T>) -> Vec<T> {
    let instances = vec![
        // pi circuit
        supercircuit_instances.pi_digest_lo,
        supercircuit_instances.pi_digest_hi,
    ];
    assert_eq!(NUM_OF_SUPERCIRCUIT_INSTANCES, instances.len());
    instances
}