-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathfixed_recursive_verifier.rs
1700 lines (1568 loc) · 64.9 KB
/
fixed_recursive_verifier.rs
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
use core::mem::{self, MaybeUninit};
use core::ops::Range;
use std::collections::BTreeMap;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use anyhow::anyhow;
use hashbrown::HashMap;
use itertools::{zip_eq, Itertools};
use mpt_trie::partial_trie::{HashedPartialTrie, Node, PartialTrie};
use plonky2::field::extension::Extendable;
use plonky2::fri::FriParams;
use plonky2::gates::constant::ConstantGate;
use plonky2::gates::noop::NoopGate;
use plonky2::hash::hash_types::RichField;
use plonky2::iop::challenger::RecursiveChallenger;
use plonky2::iop::target::{BoolTarget, Target};
use plonky2::iop::witness::{PartialWitness, WitnessWrite};
use plonky2::plonk::circuit_builder::CircuitBuilder;
use plonky2::plonk::circuit_data::{
CircuitConfig, CircuitData, CommonCircuitData, VerifierCircuitData, VerifierCircuitTarget,
};
use plonky2::plonk::config::{AlgebraicHasher, GenericConfig};
use plonky2::plonk::proof::{ProofWithPublicInputs, ProofWithPublicInputsTarget};
use plonky2::recursion::cyclic_recursion::check_cyclic_proof_verifier_data;
use plonky2::recursion::dummy_circuit::cyclic_base_proof;
use plonky2::util::serialization::{
Buffer, GateSerializer, IoResult, Read, WitnessGeneratorSerializer, Write,
};
use plonky2::util::timing::TimingTree;
use plonky2_util::log2_ceil;
use starky::config::StarkConfig;
use starky::cross_table_lookup::{verify_cross_table_lookups_circuit, CrossTableLookup};
use starky::lookup::{get_grand_product_challenge_set_target, GrandProductChallengeSet};
use starky::proof::StarkProofWithMetadata;
use starky::stark::Stark;
use crate::all_stark::{all_cross_table_lookups, AllStark, Table, NUM_TABLES};
use crate::generation::GenerationInputs;
use crate::get_challenges::observe_public_values_target;
use crate::proof::{
AllProof, BlockHashesTarget, BlockMetadataTarget, ExtraBlockData, ExtraBlockDataTarget,
PublicValues, PublicValuesTarget, TrieRoots, TrieRootsTarget,
};
use crate::prover::{check_abort_signal, prove};
use crate::recursive_verifier::{
add_common_recursion_gates, add_virtual_public_values, get_memory_extra_looking_sum_circuit,
recursive_stark_circuit, set_public_value_targets, PlonkWrapperCircuit, PublicInputs,
StarkWrapperCircuit,
};
use crate::util::h256_limbs;
/// The recursion threshold. We end a chain of recursive proofs once we reach
/// this size.
const THRESHOLD_DEGREE_BITS: usize = 13;
/// Contains all recursive circuits used in the system. For each STARK and each
/// initial `degree_bits`, this contains a chain of recursive circuits for
/// shrinking that STARK from `degree_bits` to a constant
/// `THRESHOLD_DEGREE_BITS`. It also contains a special root circuit
/// for combining each STARK's shrunk wrapper proof into a single proof.
#[derive(Eq, PartialEq, Debug)]
pub struct AllRecursiveCircuits<F, C, const D: usize>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F>,
C::Hasher: AlgebraicHasher<F>,
{
/// The EVM root circuit, which aggregates the (shrunk) per-table recursive
/// proofs.
pub root: RootCircuitData<F, C, D>,
/// The aggregation circuit, which verifies two proofs that can either be
/// root or aggregation proofs.
pub aggregation: AggregationCircuitData<F, C, D>,
/// The block circuit, which verifies an aggregation root proof and an
/// optional previous block proof.
pub block: BlockCircuitData<F, C, D>,
/// Holds chains of circuits for each table and for each initial
/// `degree_bits`.
pub by_table: [RecursiveCircuitsForTable<F, C, D>; NUM_TABLES],
}
/// Data for the EVM root circuit, which is used to combine each STARK's shrunk
/// wrapper proof into a single proof.
#[derive(Eq, PartialEq, Debug)]
pub struct RootCircuitData<F, C, const D: usize>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F>,
{
pub circuit: CircuitData<F, C, D>,
proof_with_pis: [ProofWithPublicInputsTarget<D>; NUM_TABLES],
/// For each table, various inner circuits may be used depending on the
/// initial table size. This target holds the index of the circuit
/// (within `final_circuits()`) that was used.
index_verifier_data: [Target; NUM_TABLES],
/// Public inputs containing public values.
public_values: PublicValuesTarget,
/// Public inputs used for cyclic verification. These aren't actually used
/// for EVM root proofs; the circuit has them just to match the
/// structure of aggregation proofs.
cyclic_vk: VerifierCircuitTarget,
}
impl<F, C, const D: usize> RootCircuitData<F, C, D>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F>,
{
fn to_buffer(
&self,
buffer: &mut Vec<u8>,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<()> {
buffer.write_circuit_data(&self.circuit, gate_serializer, generator_serializer)?;
for proof in &self.proof_with_pis {
buffer.write_target_proof_with_public_inputs(proof)?;
}
for index in self.index_verifier_data {
buffer.write_target(index)?;
}
self.public_values.to_buffer(buffer)?;
buffer.write_target_verifier_circuit(&self.cyclic_vk)?;
Ok(())
}
fn from_buffer(
buffer: &mut Buffer,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<Self> {
let circuit = buffer.read_circuit_data(gate_serializer, generator_serializer)?;
let mut proof_with_pis = Vec::with_capacity(NUM_TABLES);
for _ in 0..NUM_TABLES {
proof_with_pis.push(buffer.read_target_proof_with_public_inputs()?);
}
let mut index_verifier_data = Vec::with_capacity(NUM_TABLES);
for _ in 0..NUM_TABLES {
index_verifier_data.push(buffer.read_target()?);
}
let public_values = PublicValuesTarget::from_buffer(buffer)?;
let cyclic_vk = buffer.read_target_verifier_circuit()?;
Ok(Self {
circuit,
proof_with_pis: proof_with_pis.try_into().unwrap(),
index_verifier_data: index_verifier_data.try_into().unwrap(),
public_values,
cyclic_vk,
})
}
}
/// Data for the aggregation circuit, which is used to compress two proofs into
/// one. Each inner proof can be either an EVM root proof or another aggregation
/// proof.
#[derive(Eq, PartialEq, Debug)]
pub struct AggregationCircuitData<F, C, const D: usize>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F>,
{
pub circuit: CircuitData<F, C, D>,
lhs: AggregationChildTarget<D>,
rhs: AggregationChildTarget<D>,
public_values: PublicValuesTarget,
cyclic_vk: VerifierCircuitTarget,
}
impl<F, C, const D: usize> AggregationCircuitData<F, C, D>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F>,
{
fn to_buffer(
&self,
buffer: &mut Vec<u8>,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<()> {
buffer.write_circuit_data(&self.circuit, gate_serializer, generator_serializer)?;
buffer.write_target_verifier_circuit(&self.cyclic_vk)?;
self.public_values.to_buffer(buffer)?;
self.lhs.to_buffer(buffer)?;
self.rhs.to_buffer(buffer)?;
Ok(())
}
fn from_buffer(
buffer: &mut Buffer,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<Self> {
let circuit = buffer.read_circuit_data(gate_serializer, generator_serializer)?;
let cyclic_vk = buffer.read_target_verifier_circuit()?;
let public_values = PublicValuesTarget::from_buffer(buffer)?;
let lhs = AggregationChildTarget::from_buffer(buffer)?;
let rhs = AggregationChildTarget::from_buffer(buffer)?;
Ok(Self {
circuit,
lhs,
rhs,
public_values,
cyclic_vk,
})
}
}
#[derive(Eq, PartialEq, Debug)]
struct AggregationChildTarget<const D: usize> {
is_agg: BoolTarget,
agg_proof: ProofWithPublicInputsTarget<D>,
evm_proof: ProofWithPublicInputsTarget<D>,
}
impl<const D: usize> AggregationChildTarget<D> {
fn to_buffer(&self, buffer: &mut Vec<u8>) -> IoResult<()> {
buffer.write_target_bool(self.is_agg)?;
buffer.write_target_proof_with_public_inputs(&self.agg_proof)?;
buffer.write_target_proof_with_public_inputs(&self.evm_proof)?;
Ok(())
}
fn from_buffer(buffer: &mut Buffer) -> IoResult<Self> {
let is_agg = buffer.read_target_bool()?;
let agg_proof = buffer.read_target_proof_with_public_inputs()?;
let evm_proof = buffer.read_target_proof_with_public_inputs()?;
Ok(Self {
is_agg,
agg_proof,
evm_proof,
})
}
fn public_values<F: RichField + Extendable<D>>(
&self,
builder: &mut CircuitBuilder<F, D>,
) -> PublicValuesTarget {
let agg_pv = PublicValuesTarget::from_public_inputs(&self.agg_proof.public_inputs);
let evm_pv = PublicValuesTarget::from_public_inputs(&self.evm_proof.public_inputs);
PublicValuesTarget::select(builder, self.is_agg, agg_pv, evm_pv)
}
}
/// Data for the block circuit, which is used to generate a final block proof,
/// and compress it with an optional parent proof if present.
#[derive(Eq, PartialEq, Debug)]
pub struct BlockCircuitData<F, C, const D: usize>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F>,
{
pub circuit: CircuitData<F, C, D>,
has_parent_block: BoolTarget,
parent_block_proof: ProofWithPublicInputsTarget<D>,
agg_root_proof: ProofWithPublicInputsTarget<D>,
public_values: PublicValuesTarget,
cyclic_vk: VerifierCircuitTarget,
}
impl<F, C, const D: usize> BlockCircuitData<F, C, D>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F>,
{
fn to_buffer(
&self,
buffer: &mut Vec<u8>,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<()> {
buffer.write_circuit_data(&self.circuit, gate_serializer, generator_serializer)?;
buffer.write_target_bool(self.has_parent_block)?;
buffer.write_target_proof_with_public_inputs(&self.parent_block_proof)?;
buffer.write_target_proof_with_public_inputs(&self.agg_root_proof)?;
self.public_values.to_buffer(buffer)?;
buffer.write_target_verifier_circuit(&self.cyclic_vk)?;
Ok(())
}
fn from_buffer(
buffer: &mut Buffer,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<Self> {
let circuit = buffer.read_circuit_data(gate_serializer, generator_serializer)?;
let has_parent_block = buffer.read_target_bool()?;
let parent_block_proof = buffer.read_target_proof_with_public_inputs()?;
let agg_root_proof = buffer.read_target_proof_with_public_inputs()?;
let public_values = PublicValuesTarget::from_buffer(buffer)?;
let cyclic_vk = buffer.read_target_verifier_circuit()?;
Ok(Self {
circuit,
has_parent_block,
parent_block_proof,
agg_root_proof,
public_values,
cyclic_vk,
})
}
}
impl<F, C, const D: usize> AllRecursiveCircuits<F, C, D>
where
F: RichField + Extendable<D>,
C: GenericConfig<D, F = F> + 'static,
C::Hasher: AlgebraicHasher<F>,
{
/// Serializes all these preprocessed circuits into a sequence of bytes.
///
/// # Arguments
///
/// - `skip_tables`: a boolean indicating whether to serialize only the
/// upper circuits or the entire prover state, including recursive
/// circuits to shrink STARK proofs.
/// - `gate_serializer`: a custom gate serializer needed to serialize
/// recursive circuits common data.
/// - `generator_serializer`: a custom generator serializer needed to
/// serialize recursive circuits proving data.
pub fn to_bytes(
&self,
skip_tables: bool,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<Vec<u8>> {
// TODO: would be better to initialize it dynamically based on the supported max
// degree.
let mut buffer = Vec::with_capacity(1 << 34);
self.root
.to_buffer(&mut buffer, gate_serializer, generator_serializer)?;
self.aggregation
.to_buffer(&mut buffer, gate_serializer, generator_serializer)?;
self.block
.to_buffer(&mut buffer, gate_serializer, generator_serializer)?;
if !skip_tables {
for table in &self.by_table {
table.to_buffer(&mut buffer, gate_serializer, generator_serializer)?;
}
}
Ok(buffer)
}
/// Deserializes a sequence of bytes into an entire prover state containing
/// all recursive circuits.
///
/// # Arguments
///
/// - `bytes`: a slice of bytes to deserialize this prover state from.
/// - `skip_tables`: a boolean indicating whether to deserialize only the
/// upper circuits or the entire prover state, including recursive
/// circuits to shrink STARK proofs.
/// - `gate_serializer`: a custom gate serializer needed to serialize
/// recursive circuits common data.
/// - `generator_serializer`: a custom generator serializer needed to
/// serialize recursive circuits proving data.
pub fn from_bytes(
bytes: &[u8],
skip_tables: bool,
gate_serializer: &dyn GateSerializer<F, D>,
generator_serializer: &dyn WitnessGeneratorSerializer<F, D>,
) -> IoResult<Self> {
let mut buffer = Buffer::new(bytes);
let root =
RootCircuitData::from_buffer(&mut buffer, gate_serializer, generator_serializer)?;
let aggregation = AggregationCircuitData::from_buffer(
&mut buffer,
gate_serializer,
generator_serializer,
)?;
let block =
BlockCircuitData::from_buffer(&mut buffer, gate_serializer, generator_serializer)?;
let by_table = match skip_tables {
true => (0..NUM_TABLES)
.map(|_| RecursiveCircuitsForTable {
by_stark_size: BTreeMap::default(),
})
.collect_vec()
.try_into()
.unwrap(),
false => {
// Tricky use of MaybeUninit to remove the need for implementing Debug
// for all underlying types, necessary to convert a by_table Vec to an array.
let mut by_table: [MaybeUninit<RecursiveCircuitsForTable<F, C, D>>; NUM_TABLES] =
unsafe { MaybeUninit::uninit().assume_init() };
for table in &mut by_table[..] {
let value = RecursiveCircuitsForTable::from_buffer(
&mut buffer,
gate_serializer,
generator_serializer,
)?;
*table = MaybeUninit::new(value);
}
unsafe {
mem::transmute::<
[std::mem::MaybeUninit<RecursiveCircuitsForTable<F, C, D>>; NUM_TABLES],
[RecursiveCircuitsForTable<F, C, D>; NUM_TABLES],
>(by_table)
}
}
};
Ok(Self {
root,
aggregation,
block,
by_table,
})
}
/// Preprocess all recursive circuits used by the system.
///
/// # Arguments
///
/// - `all_stark`: a structure defining the logic of all STARK modules and
/// their associated cross-table lookups.
/// - `degree_bits_ranges`: the logarithmic ranges to be supported for the
/// recursive tables.
///
/// Transactions may yield arbitrary trace lengths for each STARK module
/// (within some bounds), unknown prior generating the witness to create
/// a proof. Thus, for each STARK module, we construct a map from
/// `2^{degree_bits} = length` to a chain of shrinking recursion circuits,
/// starting from that length, for each `degree_bits` in the range specified
/// for this STARK module. Specifying a wide enough range allows a
/// prover to cover all possible scenarios.
/// - `stark_config`: the configuration to be used for the STARK prover. It
/// will usually be a fast one yielding large proofs.
pub fn new(
all_stark: &AllStark<F, D>,
degree_bits_ranges: &[Range<usize>; NUM_TABLES],
stark_config: &StarkConfig,
) -> Self {
let arithmetic = RecursiveCircuitsForTable::new(
Table::Arithmetic,
&all_stark.arithmetic_stark,
degree_bits_ranges[*Table::Arithmetic].clone(),
&all_stark.cross_table_lookups,
stark_config,
);
let byte_packing = RecursiveCircuitsForTable::new(
Table::BytePacking,
&all_stark.byte_packing_stark,
degree_bits_ranges[*Table::BytePacking].clone(),
&all_stark.cross_table_lookups,
stark_config,
);
let cpu = RecursiveCircuitsForTable::new(
Table::Cpu,
&all_stark.cpu_stark,
degree_bits_ranges[*Table::Cpu].clone(),
&all_stark.cross_table_lookups,
stark_config,
);
let keccak = RecursiveCircuitsForTable::new(
Table::Keccak,
&all_stark.keccak_stark,
degree_bits_ranges[*Table::Keccak].clone(),
&all_stark.cross_table_lookups,
stark_config,
);
let keccak_sponge = RecursiveCircuitsForTable::new(
Table::KeccakSponge,
&all_stark.keccak_sponge_stark,
degree_bits_ranges[*Table::KeccakSponge].clone(),
&all_stark.cross_table_lookups,
stark_config,
);
let logic = RecursiveCircuitsForTable::new(
Table::Logic,
&all_stark.logic_stark,
degree_bits_ranges[*Table::Logic].clone(),
&all_stark.cross_table_lookups,
stark_config,
);
let memory = RecursiveCircuitsForTable::new(
Table::Memory,
&all_stark.memory_stark,
degree_bits_ranges[*Table::Memory].clone(),
&all_stark.cross_table_lookups,
stark_config,
);
let by_table = [
arithmetic,
byte_packing,
cpu,
keccak,
keccak_sponge,
logic,
memory,
];
let root = Self::create_root_circuit(&by_table, stark_config);
let aggregation = Self::create_aggregation_circuit(&root);
let block = Self::create_block_circuit(&aggregation);
Self {
root,
aggregation,
block,
by_table,
}
}
/// Outputs the `VerifierCircuitData` needed to verify any block proof
/// generated by an honest prover.
/// While the [`AllRecursiveCircuits`] prover state can also verify proofs,
/// verifiers only need a fraction of the state to verify proofs. This
/// allows much less powerful entities to behave as verifiers, by only
/// loading the necessary data to verify block proofs.
///
/// # Usage
///
/// ```ignore
/// let prover_state = AllRecursiveCircuits { ... };
/// let verifier_state = prover_state.final_verifier_data();
///
/// // Verify a provided block proof
/// assert!(verifier_state.verify(&block_proof).is_ok());
/// ```
pub fn final_verifier_data(&self) -> VerifierCircuitData<F, C, D> {
self.block.circuit.verifier_data()
}
fn create_root_circuit(
by_table: &[RecursiveCircuitsForTable<F, C, D>; NUM_TABLES],
stark_config: &StarkConfig,
) -> RootCircuitData<F, C, D> {
let inner_common_data: [_; NUM_TABLES] =
core::array::from_fn(|i| &by_table[i].final_circuits()[0].common);
let mut builder = CircuitBuilder::new(CircuitConfig::standard_recursion_config());
let public_values = add_virtual_public_values(&mut builder);
let recursive_proofs =
core::array::from_fn(|i| builder.add_virtual_proof_with_pis(inner_common_data[i]));
let pis: [_; NUM_TABLES] = core::array::from_fn(|i| {
PublicInputs::<Target, <C::Hasher as AlgebraicHasher<F>>::AlgebraicPermutation>::from_vec(
&recursive_proofs[i].public_inputs,
stark_config,
)
});
let index_verifier_data = core::array::from_fn(|_i| builder.add_virtual_target());
let mut challenger = RecursiveChallenger::<F, C::Hasher, D>::new(&mut builder);
for pi in &pis {
for h in &pi.trace_cap {
challenger.observe_elements(h);
}
}
observe_public_values_target::<F, C, D>(&mut challenger, &public_values);
let ctl_challenges = get_grand_product_challenge_set_target(
&mut builder,
&mut challenger,
stark_config.num_challenges,
);
// Check that the correct CTL challenges are used in every proof.
for pi in &pis {
for i in 0..stark_config.num_challenges {
builder.connect(
ctl_challenges.challenges[i].beta,
pi.ctl_challenges.challenges[i].beta,
);
builder.connect(
ctl_challenges.challenges[i].gamma,
pi.ctl_challenges.challenges[i].gamma,
);
}
}
let state = challenger.compact(&mut builder);
for (&before, &s) in zip_eq(state.as_ref(), pis[0].challenger_state_before.as_ref()) {
builder.connect(before, s);
}
// Check that the challenger state is consistent between proofs.
for i in 1..NUM_TABLES {
for (&before, &after) in zip_eq(
pis[i].challenger_state_before.as_ref(),
pis[i - 1].challenger_state_after.as_ref(),
) {
builder.connect(before, after);
}
}
// Extra sums to add to the looked last value.
// Only necessary for the Memory values.
let mut extra_looking_sums =
vec![vec![builder.zero(); stark_config.num_challenges]; NUM_TABLES];
// Memory
extra_looking_sums[*Table::Memory] = (0..stark_config.num_challenges)
.map(|c| {
get_memory_extra_looking_sum_circuit(
&mut builder,
&public_values,
ctl_challenges.challenges[c],
)
})
.collect_vec();
// Verify the CTL checks.
verify_cross_table_lookups_circuit::<F, D, NUM_TABLES>(
&mut builder,
all_cross_table_lookups(),
pis.map(|p| p.ctl_zs_first),
Some(&extra_looking_sums),
stark_config,
);
for (i, table_circuits) in by_table.iter().enumerate() {
let final_circuits = table_circuits.final_circuits();
for final_circuit in &final_circuits {
assert_eq!(
&final_circuit.common, inner_common_data[i],
"common_data mismatch"
);
}
let mut possible_vks = final_circuits
.into_iter()
.map(|c| builder.constant_verifier_data(&c.verifier_only))
.collect_vec();
// random_access_verifier_data expects a vector whose length is a power of two.
// To satisfy this, we will just add some duplicates of the first VK.
while !possible_vks.len().is_power_of_two() {
possible_vks.push(possible_vks[0].clone());
}
let inner_verifier_data =
builder.random_access_verifier_data(index_verifier_data[i], possible_vks);
builder.verify_proof::<C>(
&recursive_proofs[i],
&inner_verifier_data,
inner_common_data[i],
);
}
// We want EVM root proofs to have the exact same structure as aggregation
// proofs, so we add public inputs for cyclic verification, even though
// they'll be ignored.
let cyclic_vk = builder.add_verifier_data_public_inputs();
builder.add_gate(
ConstantGate::new(inner_common_data[0].config.num_constants),
vec![],
);
RootCircuitData {
circuit: builder.build::<C>(),
proof_with_pis: recursive_proofs,
index_verifier_data,
public_values,
cyclic_vk,
}
}
fn create_aggregation_circuit(
root: &RootCircuitData<F, C, D>,
) -> AggregationCircuitData<F, C, D> {
let mut builder = CircuitBuilder::<F, D>::new(root.circuit.common.config.clone());
let public_values = add_virtual_public_values(&mut builder);
let cyclic_vk = builder.add_verifier_data_public_inputs();
let lhs = Self::add_agg_child(&mut builder, root);
let rhs = Self::add_agg_child(&mut builder, root);
let lhs_public_values = lhs.public_values(&mut builder);
let rhs_public_values = rhs.public_values(&mut builder);
// Connect all block hash values
BlockHashesTarget::connect(
&mut builder,
public_values.block_hashes,
lhs_public_values.block_hashes,
);
BlockHashesTarget::connect(
&mut builder,
public_values.block_hashes,
rhs_public_values.block_hashes,
);
// Connect all block metadata values.
BlockMetadataTarget::connect(
&mut builder,
public_values.block_metadata,
lhs_public_values.block_metadata,
);
BlockMetadataTarget::connect(
&mut builder,
public_values.block_metadata,
rhs_public_values.block_metadata,
);
// Connect aggregation `trie_roots_before` with lhs `trie_roots_before`.
TrieRootsTarget::connect(
&mut builder,
public_values.trie_roots_before,
lhs_public_values.trie_roots_before,
);
// Connect aggregation `trie_roots_after` with rhs `trie_roots_after`.
TrieRootsTarget::connect(
&mut builder,
public_values.trie_roots_after,
rhs_public_values.trie_roots_after,
);
// Connect lhs `trie_roots_after` with rhs `trie_roots_before`.
TrieRootsTarget::connect(
&mut builder,
lhs_public_values.trie_roots_after,
rhs_public_values.trie_roots_before,
);
Self::connect_extra_public_values(
&mut builder,
&public_values.extra_block_data,
&lhs_public_values.extra_block_data,
&rhs_public_values.extra_block_data,
);
// Pad to match the root circuit's degree.
while log2_ceil(builder.num_gates()) < root.circuit.common.degree_bits() {
builder.add_gate(NoopGate, vec![]);
}
let circuit = builder.build::<C>();
AggregationCircuitData {
circuit,
lhs,
rhs,
public_values,
cyclic_vk,
}
}
fn connect_extra_public_values(
builder: &mut CircuitBuilder<F, D>,
pvs: &ExtraBlockDataTarget,
lhs: &ExtraBlockDataTarget,
rhs: &ExtraBlockDataTarget,
) {
// Connect checkpoint state root values.
for (&limb0, &limb1) in pvs
.checkpoint_state_trie_root
.iter()
.zip(&rhs.checkpoint_state_trie_root)
{
builder.connect(limb0, limb1);
}
for (&limb0, &limb1) in pvs
.checkpoint_state_trie_root
.iter()
.zip(&lhs.checkpoint_state_trie_root)
{
builder.connect(limb0, limb1);
}
// Connect the transaction number in public values to the lhs and rhs values
// correctly.
builder.connect(pvs.txn_number_before, lhs.txn_number_before);
builder.connect(pvs.txn_number_after, rhs.txn_number_after);
// Connect lhs `txn_number_after` with rhs `txn_number_before`.
builder.connect(lhs.txn_number_after, rhs.txn_number_before);
// Connect the gas used in public values to the lhs and rhs values correctly.
builder.connect(pvs.gas_used_before, lhs.gas_used_before);
builder.connect(pvs.gas_used_after, rhs.gas_used_after);
// Connect lhs `gas_used_after` with rhs `gas_used_before`.
builder.connect(lhs.gas_used_after, rhs.gas_used_before);
}
fn add_agg_child(
builder: &mut CircuitBuilder<F, D>,
root: &RootCircuitData<F, C, D>,
) -> AggregationChildTarget<D> {
let common = &root.circuit.common;
let root_vk = builder.constant_verifier_data(&root.circuit.verifier_only);
let is_agg = builder.add_virtual_bool_target_safe();
let agg_proof = builder.add_virtual_proof_with_pis(common);
let evm_proof = builder.add_virtual_proof_with_pis(common);
builder
.conditionally_verify_cyclic_proof::<C>(
is_agg, &agg_proof, &evm_proof, &root_vk, common,
)
.expect("Failed to build cyclic recursion circuit");
AggregationChildTarget {
is_agg,
agg_proof,
evm_proof,
}
}
fn create_block_circuit(agg: &AggregationCircuitData<F, C, D>) -> BlockCircuitData<F, C, D> {
// The block circuit is similar to the agg circuit; both verify two inner
// proofs. We need to adjust a few things, but it's easier than making a
// new CommonCircuitData.
let expected_common_data = CommonCircuitData {
fri_params: FriParams {
degree_bits: 14,
..agg.circuit.common.fri_params.clone()
},
..agg.circuit.common.clone()
};
let mut builder = CircuitBuilder::<F, D>::new(CircuitConfig::standard_recursion_config());
let public_values = add_virtual_public_values(&mut builder);
let has_parent_block = builder.add_virtual_bool_target_safe();
let parent_block_proof = builder.add_virtual_proof_with_pis(&expected_common_data);
let agg_root_proof = builder.add_virtual_proof_with_pis(&agg.circuit.common);
// Connect block hashes
Self::connect_block_hashes(&mut builder, &parent_block_proof, &agg_root_proof);
let parent_pv = PublicValuesTarget::from_public_inputs(&parent_block_proof.public_inputs);
let agg_pv = PublicValuesTarget::from_public_inputs(&agg_root_proof.public_inputs);
// Connect block `trie_roots_before` with parent_pv `trie_roots_before`.
TrieRootsTarget::connect(
&mut builder,
public_values.trie_roots_before,
parent_pv.trie_roots_before,
);
// Connect the rest of block `public_values` with agg_pv.
TrieRootsTarget::connect(
&mut builder,
public_values.trie_roots_after,
agg_pv.trie_roots_after,
);
BlockMetadataTarget::connect(
&mut builder,
public_values.block_metadata,
agg_pv.block_metadata,
);
BlockHashesTarget::connect(
&mut builder,
public_values.block_hashes,
agg_pv.block_hashes,
);
ExtraBlockDataTarget::connect(
&mut builder,
public_values.extra_block_data,
agg_pv.extra_block_data,
);
// Make connections between block proofs, and check initial and final block
// values.
Self::connect_block_proof(&mut builder, has_parent_block, &parent_pv, &agg_pv);
let cyclic_vk = builder.add_verifier_data_public_inputs();
builder
.conditionally_verify_cyclic_proof_or_dummy::<C>(
has_parent_block,
&parent_block_proof,
&expected_common_data,
)
.expect("Failed to build cyclic recursion circuit");
let agg_verifier_data = builder.constant_verifier_data(&agg.circuit.verifier_only);
builder.verify_proof::<C>(&agg_root_proof, &agg_verifier_data, &agg.circuit.common);
let circuit = builder.build::<C>();
BlockCircuitData {
circuit,
has_parent_block,
parent_block_proof,
agg_root_proof,
public_values,
cyclic_vk,
}
}
/// Connect the 256 block hashes between two blocks
fn connect_block_hashes(
builder: &mut CircuitBuilder<F, D>,
lhs: &ProofWithPublicInputsTarget<D>,
rhs: &ProofWithPublicInputsTarget<D>,
) {
let lhs_public_values = PublicValuesTarget::from_public_inputs(&lhs.public_inputs);
let rhs_public_values = PublicValuesTarget::from_public_inputs(&rhs.public_inputs);
for i in 0..255 {
for j in 0..8 {
builder.connect(
lhs_public_values.block_hashes.prev_hashes[8 * (i + 1) + j],
rhs_public_values.block_hashes.prev_hashes[8 * i + j],
);
}
}
let expected_hash = lhs_public_values.block_hashes.cur_hash;
let prev_block_hash = &rhs_public_values.block_hashes.prev_hashes[255 * 8..256 * 8];
for i in 0..expected_hash.len() {
builder.connect(expected_hash[i], prev_block_hash[i]);
}
}
fn connect_block_proof(
builder: &mut CircuitBuilder<F, D>,
has_parent_block: BoolTarget,
lhs: &PublicValuesTarget,
rhs: &PublicValuesTarget,
) {
// Between blocks, we only connect state tries.
for (&limb0, limb1) in lhs
.trie_roots_after
.state_root
.iter()
.zip(rhs.trie_roots_before.state_root)
{
builder.connect(limb0, limb1);
}
// Between blocks, the checkpoint state trie remains unchanged.
for (&limb0, limb1) in lhs
.extra_block_data
.checkpoint_state_trie_root
.iter()
.zip(rhs.extra_block_data.checkpoint_state_trie_root)
{
builder.connect(limb0, limb1);
}
// Connect block numbers.
let one = builder.one();
let prev_block_nb = builder.sub(rhs.block_metadata.block_number, one);
builder.connect(lhs.block_metadata.block_number, prev_block_nb);
// Check initial block values.
Self::connect_initial_values_block(builder, rhs);
// Connect intermediary values for gas_used and bloom filters to the block's
// final values. We only plug on the right, so there is no need to check the
// left-handside block.
Self::connect_final_block_values_to_intermediary(builder, rhs);
let has_not_parent_block = builder.sub(one, has_parent_block.target);
// Check that the checkpoint block has the predetermined state trie root in
// `ExtraBlockData`.
Self::connect_checkpoint_block(builder, rhs, has_not_parent_block);
}
fn connect_checkpoint_block(
builder: &mut CircuitBuilder<F, D>,
x: &PublicValuesTarget,
has_not_parent_block: Target,
) where
F: RichField + Extendable<D>,
{
for (&limb0, limb1) in x
.trie_roots_before
.state_root
.iter()
.zip(x.extra_block_data.checkpoint_state_trie_root)
{
let mut constr = builder.sub(limb0, limb1);
constr = builder.mul(has_not_parent_block, constr);
builder.assert_zero(constr);
}
}
fn connect_final_block_values_to_intermediary(
builder: &mut CircuitBuilder<F, D>,
x: &PublicValuesTarget,
) where
F: RichField + Extendable<D>,
{
builder.connect(
x.block_metadata.block_gas_used,
x.extra_block_data.gas_used_after,
);
}
fn connect_initial_values_block(builder: &mut CircuitBuilder<F, D>, x: &PublicValuesTarget)
where
F: RichField + Extendable<D>,
{
// The initial number of transactions is 0.
builder.assert_zero(x.extra_block_data.txn_number_before);
// The initial gas used is 0.
builder.assert_zero(x.extra_block_data.gas_used_before);
// The transactions and receipts tries are empty at the beginning of the block.
let initial_trie = HashedPartialTrie::from(Node::Empty).hash();
for (i, limb) in h256_limbs::<F>(initial_trie).into_iter().enumerate() {
let limb_target = builder.constant(limb);
builder.connect(x.trie_roots_before.transactions_root[i], limb_target);
builder.connect(x.trie_roots_before.receipts_root[i], limb_target);
}
}
/// For a given transaction payload passed as [`GenerationInputs`], create a
/// proof for each STARK module, then recursively shrink and combine
/// them, eventually culminating in a transaction proof, also called
/// root proof.
///
/// # Arguments
///
/// - `all_stark`: a structure defining the logic of all STARK modules and
/// their associated cross-table lookups.
/// - `config`: the configuration to be used for the STARK prover. It will
/// usually be a fast one yielding large proofs.