forked from privacy-scaling-explorations/zkevm-circuits
-
Notifications
You must be signed in to change notification settings - Fork 391
/
Copy pathexecution.rs
1956 lines (1868 loc) · 78.3 KB
/
execution.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 super::{
param::{
BLOCK_TABLE_LOOKUPS, BYTECODE_TABLE_LOOKUPS, COPY_TABLE_LOOKUPS, ECC_TABLE_LOOKUPS,
EXP_TABLE_LOOKUPS, FIXED_TABLE_LOOKUPS, KECCAK_TABLE_LOOKUPS, MODEXP_TABLE_LOOKUPS,
N_BYTE_LOOKUPS, N_COPY_COLUMNS, N_PHASE1_COLUMNS, POW_OF_RAND_TABLE_LOOKUPS,
RW_TABLE_LOOKUPS, SHA256_TABLE_LOOKUPS, SIG_TABLE_LOOKUPS, TX_TABLE_LOOKUPS,
},
util::{instrumentation::Instrument, CachedRegion, CellManager, Inverter, StoredExpression},
EvmCircuitExports,
};
use crate::{
evm_circuit::{
param::{EVM_LOOKUP_COLS, MAX_STEP_HEIGHT, N_PHASE2_COLUMNS, STEP_WIDTH},
step::{ExecutionState, Step},
table::Table,
util::{
constraint_builder::{
BaseConstraintBuilder, ConstrainBuilderCommon, EVMConstraintBuilder,
},
rlc, CellType,
},
witness::{Block, Call, ExecStep, Transaction},
},
table::{LookupTable, RwTableTag, TxReceiptFieldTag},
util::{query_expression, Challenges, Expr, Field},
};
use bus_mapping::util::read_env_var;
use eth_types::ToLittleEndian;
use gadgets::util::not;
use halo2_proofs::{
circuit::{Layouter, Region, Value},
plonk::{
Advice, Assigned, Column, ConstraintSystem, Error, Expression, FirstPhase, Fixed, Selector,
VirtualCells,
},
poly::Rotation,
};
use itertools::Itertools;
use std::{
collections::{BTreeSet, HashMap},
iter,
sync::LazyLock,
};
#[cfg(feature = "onephase")]
use halo2_proofs::plonk::FirstPhase as SecondPhase;
#[cfg(feature = "onephase")]
use halo2_proofs::plonk::FirstPhase as ThirdPhase;
#[cfg(not(feature = "onephase"))]
use halo2_proofs::plonk::SecondPhase;
#[cfg(not(feature = "onephase"))]
use halo2_proofs::plonk::ThirdPhase;
use strum::{EnumCount, IntoEnumIterator};
pub(crate) static CHECK_RW_LOOKUP: LazyLock<bool> =
LazyLock::new(|| read_env_var("CHECK_RW_LOOKUP", false));
#[cfg(any(feature = "test", test))]
mod tests;
mod add_sub;
mod addmod;
mod address;
mod balance;
mod begin_tx;
mod bitwise;
mod block_ctx;
mod blockhash;
mod byte;
mod calldatacopy;
mod calldataload;
mod calldatasize;
mod caller;
mod callop;
mod callvalue;
mod chainid;
mod codecopy;
mod codesize;
mod comparator;
mod create;
#[cfg(not(feature = "scroll"))]
mod dummy;
mod dup;
mod end_block;
mod end_inner_block;
mod end_tx;
mod error_code_store;
mod error_invalid_creation_code;
mod error_invalid_jump;
mod error_invalid_opcode;
mod error_oog_account_access;
mod error_oog_call;
mod error_oog_constant;
mod error_oog_create;
mod error_oog_dynamic_memory;
mod error_oog_exp;
mod error_oog_log;
mod error_oog_memory_copy;
mod error_oog_precompile;
mod error_oog_sha3;
mod error_oog_sload_sstore;
mod error_oog_static_memory;
mod error_precompile_failed;
mod error_return_data_oo_bound;
mod error_stack;
mod error_write_protection;
mod exp;
mod extcodecopy;
mod extcodehash;
mod extcodesize;
mod gas;
mod gasprice;
mod is_zero;
mod jump;
mod jumpdest;
mod jumpi;
mod logs;
mod mcopy;
mod memory;
mod msize;
mod mul_div_mod;
mod mulmod;
#[path = "execution/not.rs"]
mod opcode_not;
mod origin;
mod padding;
mod pc;
mod pop;
mod precompiles;
mod push;
mod return_revert;
mod returndatacopy;
mod returndatasize;
mod sar;
mod sdiv_smod;
mod selfbalance;
mod sha3;
mod shl_shr;
mod signed_comparator;
mod signextend;
mod sload;
mod sstore;
mod stop;
mod swap;
mod tload;
mod tstore;
use add_sub::AddSubGadget;
use addmod::AddModGadget;
use address::AddressGadget;
use balance::BalanceGadget;
use begin_tx::BeginTxGadget;
use bitwise::BitwiseGadget;
#[cfg(feature = "scroll")]
use block_ctx::DifficultyGadget;
use block_ctx::{BlockCtxU160Gadget, BlockCtxU256Gadget, BlockCtxU64Gadget};
use blockhash::BlockHashGadget;
use byte::ByteGadget;
use calldatacopy::CallDataCopyGadget;
use calldataload::CallDataLoadGadget;
use calldatasize::CallDataSizeGadget;
use caller::CallerGadget;
use callop::CallOpGadget;
use callvalue::CallValueGadget;
use chainid::ChainIdGadget;
use codecopy::CodeCopyGadget;
use codesize::CodesizeGadget;
use comparator::ComparatorGadget;
use create::CreateGadget;
#[cfg(not(feature = "scroll"))]
use dummy::DummyGadget;
use dup::DupGadget;
use end_block::EndBlockGadget;
use end_inner_block::EndInnerBlockGadget;
use end_tx::EndTxGadget;
use error_code_store::ErrorCodeStoreGadget;
use error_invalid_creation_code::ErrorInvalidCreationCodeGadget;
use error_invalid_jump::ErrorInvalidJumpGadget;
use error_invalid_opcode::ErrorInvalidOpcodeGadget;
use error_oog_account_access::ErrorOOGAccountAccessGadget;
use error_oog_call::ErrorOOGCallGadget;
use error_oog_constant::ErrorOOGConstantGadget;
use error_oog_create::ErrorOOGCreateGadget;
use error_oog_dynamic_memory::ErrorOOGDynamicMemoryGadget;
use error_oog_exp::ErrorOOGExpGadget;
use error_oog_log::ErrorOOGLogGadget;
use error_oog_memory_copy::ErrorOOGMemoryCopyGadget;
use error_oog_precompile::ErrorOOGPrecompileGadget;
use error_oog_sha3::ErrorOOGSha3Gadget;
use error_oog_sload_sstore::ErrorOOGSloadSstoreGadget;
use error_oog_static_memory::ErrorOOGStaticMemoryGadget;
use error_precompile_failed::ErrorPrecompileFailedGadget;
use error_return_data_oo_bound::ErrorReturnDataOutOfBoundGadget;
use error_stack::ErrorStackGadget;
use error_write_protection::ErrorWriteProtectionGadget;
use exp::ExponentiationGadget;
use extcodecopy::ExtcodecopyGadget;
use extcodehash::ExtcodehashGadget;
use extcodesize::ExtcodesizeGadget;
use gas::GasGadget;
use gasprice::GasPriceGadget;
use is_zero::IsZeroGadget;
use jump::JumpGadget;
use jumpdest::JumpdestGadget;
use jumpi::JumpiGadget;
use logs::LogGadget;
use mcopy::MCopyGadget;
use memory::MemoryGadget;
use msize::MsizeGadget;
use mul_div_mod::MulDivModGadget;
use mulmod::MulModGadget;
use opcode_not::NotGadget;
use origin::OriginGadget;
use padding::PaddingGadget;
use pc::PcGadget;
use pop::PopGadget;
use precompiles::{
BasePrecompileGadget, EcAddGadget, EcMulGadget, EcPairingGadget, EcrecoverGadget,
IdentityGadget, ModExpGadget, P256VerifyGadget, SHA256Gadget,
};
use push::PushGadget;
use return_revert::ReturnRevertGadget;
use returndatacopy::ReturnDataCopyGadget;
use returndatasize::ReturnDataSizeGadget;
use sar::SarGadget;
use sdiv_smod::SignedDivModGadget;
use selfbalance::SelfbalanceGadget;
use sha3::Sha3Gadget;
use shl_shr::ShlShrGadget;
use signed_comparator::SignedComparatorGadget;
use signextend::SignextendGadget;
use sload::SloadGadget;
use sstore::SstoreGadget;
use stop::StopGadget;
use swap::SwapGadget;
use tload::TloadGadget;
use tstore::TstoreGadget;
pub(crate) trait ExecutionGadget<F: Field> {
const NAME: &'static str;
const EXECUTION_STATE: ExecutionState;
fn configure(cb: &mut EVMConstraintBuilder<F>) -> Self;
fn assign_exec_step(
&self,
region: &mut CachedRegion<'_, '_, F>,
offset: usize,
block: &Block,
transaction: &Transaction,
call: &Call,
step: &ExecStep,
) -> Result<(), Error>;
}
#[derive(Clone, Debug)]
pub(crate) struct ExecutionConfig<F> {
// EVM Circuit selector, which enables all usable rows. The rows where this selector is
// disabled won't verify any constraint (they can be unused rows or rows with blinding
// factors).
q_usable: Column<Fixed>,
// Dynamic selector that is enabled at the rows where each assigned execution step starts (a
// step has dynamic height).
q_step: Column<Advice>,
// Column to hold constant values used for copy constraints
constants: Column<Fixed>,
num_rows_until_next_step: Column<Advice>,
num_rows_inv: Column<Advice>,
// Selector enabled in the row where the first execution step starts.
q_step_first: Selector,
// Selector enabled in the row where the last execution step starts.
q_step_last: Selector,
advices: [Column<Advice>; STEP_WIDTH],
step: Step<F>,
pub(crate) height_map: HashMap<ExecutionState, usize>,
stored_expressions_map: HashMap<ExecutionState, Vec<StoredExpression<F>>>,
instrument: Instrument,
// internal state gadgets
begin_tx_gadget: Box<BeginTxGadget<F>>,
end_block_gadget: Box<EndBlockGadget<F>>,
padding_gadget: Box<PaddingGadget<F>>,
end_inner_block_gadget: Box<EndInnerBlockGadget<F>>,
end_tx_gadget: Box<EndTxGadget<F>>,
// opcode gadgets
add_sub_gadget: Box<AddSubGadget<F>>,
addmod_gadget: Box<AddModGadget<F>>,
address_gadget: Box<AddressGadget<F>>,
balance_gadget: Box<BalanceGadget<F>>,
bitwise_gadget: Box<BitwiseGadget<F>>,
byte_gadget: Box<ByteGadget<F>>,
call_op_gadget: Box<CallOpGadget<F>>,
call_value_gadget: Box<CallValueGadget<F>>,
calldatacopy_gadget: Box<CallDataCopyGadget<F>>,
calldataload_gadget: Box<CallDataLoadGadget<F>>,
calldatasize_gadget: Box<CallDataSizeGadget<F>>,
caller_gadget: Box<CallerGadget<F>>,
chainid_gadget: Box<ChainIdGadget<F>>,
codecopy_gadget: Box<CodeCopyGadget<F>>,
codesize_gadget: Box<CodesizeGadget<F>>,
comparator_gadget: Box<ComparatorGadget<F>>,
dup_gadget: Box<DupGadget<F>>,
exp_gadget: Box<ExponentiationGadget<F>>,
extcodehash_gadget: Box<ExtcodehashGadget<F>>,
extcodesize_gadget: Box<ExtcodesizeGadget<F>>,
extcodecopy_gadget: Box<ExtcodecopyGadget<F>>,
gas_gadget: Box<GasGadget<F>>,
gasprice_gadget: Box<GasPriceGadget<F>>,
iszero_gadget: Box<IsZeroGadget<F>>,
jump_gadget: Box<JumpGadget<F>>,
jumpdest_gadget: Box<JumpdestGadget<F>>,
jumpi_gadget: Box<JumpiGadget<F>>,
log_gadget: Box<LogGadget<F>>,
memory_gadget: Box<MemoryGadget<F>>,
mcopy_gadget: Box<MCopyGadget<F>>,
msize_gadget: Box<MsizeGadget<F>>,
mul_div_mod_gadget: Box<MulDivModGadget<F>>,
mulmod_gadget: Box<MulModGadget<F>>,
not_gadget: Box<NotGadget<F>>,
origin_gadget: Box<OriginGadget<F>>,
pc_gadget: Box<PcGadget<F>>,
pop_gadget: Box<PopGadget<F>>,
push_gadget: Box<PushGadget<F>>,
return_revert_gadget: Box<ReturnRevertGadget<F>>,
sar_gadget: Box<SarGadget<F>>,
sdiv_smod_gadget: Box<SignedDivModGadget<F>>,
selfbalance_gadget: Box<SelfbalanceGadget<F>>,
sha3_gadget: Box<Sha3Gadget<F>>,
shl_shr_gadget: Box<ShlShrGadget<F>>,
returndatasize_gadget: Box<ReturnDataSizeGadget<F>>,
returndatacopy_gadget: Box<ReturnDataCopyGadget<F>>,
create_gadget: Box<CreateGadget<F, false, { ExecutionState::CREATE }>>,
create2_gadget: Box<CreateGadget<F, true, { ExecutionState::CREATE2 }>>,
#[cfg(not(feature = "scroll"))]
selfdestruct_gadget: Box<DummyGadget<F, 1, 0, { ExecutionState::SELFDESTRUCT }>>,
signed_comparator_gadget: Box<SignedComparatorGadget<F>>,
signextend_gadget: Box<SignextendGadget<F>>,
sload_gadget: Box<SloadGadget<F>>,
sstore_gadget: Box<SstoreGadget<F>>,
tload_gadget: Box<TloadGadget<F>>,
tstore_gadget: Box<TstoreGadget<F>>,
stop_gadget: Box<StopGadget<F>>,
swap_gadget: Box<SwapGadget<F>>,
blockhash_gadget: Box<BlockHashGadget<F>>,
block_ctx_u64_gadget: Box<BlockCtxU64Gadget<F>>,
block_ctx_u160_gadget: Box<BlockCtxU160Gadget<F>>,
block_ctx_u256_gadget: Box<BlockCtxU256Gadget<F>>,
#[cfg(feature = "scroll")]
difficulty_gadget: Box<DifficultyGadget<F>>,
// error gadgets
error_oog_call: Box<ErrorOOGCallGadget<F>>,
error_oog_precompile: Box<ErrorOOGPrecompileGadget<F>>,
error_oog_constant: Box<ErrorOOGConstantGadget<F>>,
error_oog_exp: Box<ErrorOOGExpGadget<F>>,
error_oog_memory_copy: Box<ErrorOOGMemoryCopyGadget<F>>,
error_oog_sload_sstore: Box<ErrorOOGSloadSstoreGadget<F>>,
error_oog_static_memory_gadget: Box<ErrorOOGStaticMemoryGadget<F>>,
error_stack: Box<ErrorStackGadget<F>>,
error_write_protection: Box<ErrorWriteProtectionGadget<F>>,
error_oog_dynamic_memory_gadget: Box<ErrorOOGDynamicMemoryGadget<F>>,
error_oog_log: Box<ErrorOOGLogGadget<F>>,
error_oog_account_access: Box<ErrorOOGAccountAccessGadget<F>>,
error_oog_sha3: Box<ErrorOOGSha3Gadget<F>>,
error_oog_create: Box<ErrorOOGCreateGadget<F>>,
error_code_store: Box<ErrorCodeStoreGadget<F>>,
#[cfg(not(feature = "scroll"))]
error_oog_self_destruct:
Box<DummyGadget<F, 0, 0, { ExecutionState::ErrorOutOfGasSELFDESTRUCT }>>,
error_invalid_jump: Box<ErrorInvalidJumpGadget<F>>,
error_invalid_opcode: Box<ErrorInvalidOpcodeGadget<F>>,
error_invalid_creation_code: Box<ErrorInvalidCreationCodeGadget<F>>,
error_precompile_failed: Box<ErrorPrecompileFailedGadget<F>>,
error_return_data_out_of_bound: Box<ErrorReturnDataOutOfBoundGadget<F>>,
// precompile calls
precompile_ecrecover_gadget: Box<EcrecoverGadget<F>>,
precompile_sha2_gadget: Box<SHA256Gadget<F>>,
precompile_ripemd_gadget: Box<BasePrecompileGadget<F, { ExecutionState::PrecompileRipemd160 }>>,
precompile_identity_gadget: Box<IdentityGadget<F>>,
precompile_modexp_gadget: Box<ModExpGadget<F>>,
precompile_bn128add_gadget: Box<EcAddGadget<F>>,
precompile_bn128mul_gadget: Box<EcMulGadget<F>>,
precompile_bn128pairing_gadget: Box<EcPairingGadget<F>>,
precompile_blake2f_gadget: Box<BasePrecompileGadget<F, { ExecutionState::PrecompileBlake2f }>>,
precompile_p256verify_gadget: Box<P256VerifyGadget<F>>,
}
impl<F: Field> ExecutionConfig<F> {
#[allow(clippy::too_many_arguments)]
#[allow(clippy::redundant_closure_call)]
pub(crate) fn configure(
meta: &mut ConstraintSystem<F>,
challenges: Challenges<Expression<F>>,
fixed_table: &dyn LookupTable<F>,
byte_table: &dyn LookupTable<F>,
tx_table: &dyn LookupTable<F>,
rw_table: &dyn LookupTable<F>,
bytecode_table: &dyn LookupTable<F>,
#[cfg(feature = "dual-bytecode")] bytecode_table1: &dyn LookupTable<F>,
block_table: &dyn LookupTable<F>,
copy_table: &dyn LookupTable<F>,
keccak_table: &dyn LookupTable<F>,
sha256_table: &dyn LookupTable<F>,
exp_table: &dyn LookupTable<F>,
sig_table: &dyn LookupTable<F>,
modexp_table: &dyn LookupTable<F>,
ecc_table: &dyn LookupTable<F>,
pow_of_rand_table: &dyn LookupTable<F>,
) -> Self {
let mut instrument = Instrument::default();
let q_usable = meta.fixed_column();
let q_step = meta.advice_column();
let constants = meta.fixed_column();
meta.enable_constant(constants);
let num_rows_until_next_step = meta.advice_column();
let num_rows_inv = meta.advice_column();
let q_step_first = meta.complex_selector();
let q_step_last = meta.complex_selector();
let advices = [(); STEP_WIDTH]
.iter()
.enumerate()
.map(|(n, _)| {
if n < EVM_LOOKUP_COLS {
meta.advice_column_in(ThirdPhase)
} else if n < EVM_LOOKUP_COLS + N_PHASE2_COLUMNS {
meta.advice_column_in(SecondPhase)
} else {
meta.advice_column_in(FirstPhase)
}
})
.collect::<Vec<_>>()
.try_into()
.unwrap();
let step_curr = Step::new(meta, advices, 0, false);
let mut height_map = HashMap::new();
meta.create_gate("Constrain execution state", |meta| {
let q_usable = meta.query_fixed(q_usable, Rotation::cur());
let q_step = meta.query_advice(q_step, Rotation::cur());
let q_step_first = meta.query_selector(q_step_first);
let q_step_last = meta.query_selector(q_step_last);
let execution_state_selector_constraints = step_curr.state.execution_state.configure();
// NEW: Enabled, this will break hand crafted tests, maybe we can remove them?
let first_step_check = {
let begin_tx_or_padding_selector = step_curr
.execution_state_selector([ExecutionState::BeginTx, ExecutionState::Padding]);
iter::once((
"First step should be BeginTx or Padding",
q_step_first * (1.expr() - begin_tx_or_padding_selector),
))
};
let last_step_check = {
let end_block_selector =
step_curr.execution_state_selector([ExecutionState::EndBlock]);
iter::once((
"Last step should be EndBlock",
q_step_last * (1.expr() - end_block_selector),
))
};
execution_state_selector_constraints
.into_iter()
.map(move |(name, poly)| (name, q_usable.clone() * q_step.clone() * poly))
.chain(first_step_check)
.chain(last_step_check)
});
meta.create_gate("q_step_first", |meta| {
let q_usable = meta.query_fixed(q_usable, Rotation::cur());
let q_step_first = meta.query_selector(q_step_first);
let q_step = meta.query_advice(q_step, Rotation::cur());
let mut cb = BaseConstraintBuilder::default();
// q_step needs to be enabled on the first row
// rw_counter starts at 1
cb.condition(q_usable, |cb| {
cb.require_equal("q_step == 1", q_step.clone(), 1.expr());
cb.require_equal(
"rw_counter is initialized to be 1",
step_curr.state.rw_counter.expr(),
1.expr(),
)
});
cb.gate(q_step_first)
});
meta.create_gate("q_step_last", |meta| {
let q_usable = meta.query_fixed(q_usable, Rotation::cur());
let q_step_last = meta.query_selector(q_step_last);
let q_step = meta.query_advice(q_step, Rotation::cur());
let mut cb = BaseConstraintBuilder::default();
// q_step needs to be enabled on the last row
cb.condition(q_usable, |cb| {
cb.require_equal("q_step == 1", q_step.clone(), 1.expr());
});
cb.gate(q_step_last)
});
meta.create_gate("q_step", |meta| {
let q_usable = meta.query_fixed(q_usable, Rotation::cur());
let q_step = meta.query_advice(q_step, Rotation::cur());
let num_rows_left_cur = meta.query_advice(num_rows_until_next_step, Rotation::cur());
let num_rows_left_next = meta.query_advice(num_rows_until_next_step, Rotation::next());
let num_rows_left_inverse = meta.query_advice(num_rows_inv, Rotation::cur());
let mut cb = BaseConstraintBuilder::default();
// For every step, is_create and is_root are boolean.
cb.condition(q_step.clone(), |cb| {
cb.require_boolean(
"step.is_create is boolean",
step_curr.state.is_create.expr(),
);
cb.require_boolean("step.is_root is boolean", step_curr.state.is_root.expr());
});
// Except when step is enabled, the step counter needs to decrease by 1
cb.condition(not::expr(q_step.clone()), |cb| {
cb.require_equal(
"num_rows_left_cur := num_rows_left_next + 1",
num_rows_left_cur.clone(),
num_rows_left_next + 1.expr(),
);
});
// Enforce that q_step := num_rows_until_next_step == 0
let is_zero = 1.expr() - (num_rows_left_cur.clone() * num_rows_left_inverse.clone());
cb.require_zero(
"num_rows_left_cur * is_zero == 0",
num_rows_left_cur * is_zero.clone(),
);
cb.require_zero(
"num_rows_left_inverse * is_zero == 0",
num_rows_left_inverse * is_zero.clone(),
);
cb.require_equal("q_step == is_zero", q_step, is_zero);
// On each usable row
cb.gate(q_usable)
});
let mut stored_expressions_map = HashMap::new();
macro_rules! configure_gadget {
() => {
// We create each gadget in a closure so that the stack required to hold
// the gadget value before being copied to the box is freed immediately after
// the boxed gadget is returned.
// We put each gadget in a box so that they stay in the heap to keep
// ExecutionConfig at a manageable size.
(|| {
Box::new(Self::configure_gadget(
meta,
advices,
q_usable,
q_step,
num_rows_until_next_step,
q_step_first,
q_step_last,
&challenges,
&step_curr,
&mut height_map,
&mut stored_expressions_map,
&mut instrument,
))
})()
};
}
let cell_manager = step_curr.cell_manager.clone();
let config = Self {
q_usable,
q_step,
constants,
num_rows_until_next_step,
num_rows_inv,
q_step_first,
q_step_last,
advices,
// internal states
begin_tx_gadget: configure_gadget!(),
end_block_gadget: configure_gadget!(),
end_inner_block_gadget: configure_gadget!(),
end_tx_gadget: configure_gadget!(),
padding_gadget: configure_gadget!(),
// opcode gadgets
add_sub_gadget: configure_gadget!(),
addmod_gadget: configure_gadget!(),
bitwise_gadget: configure_gadget!(),
byte_gadget: configure_gadget!(),
call_op_gadget: configure_gadget!(),
call_value_gadget: configure_gadget!(),
calldatacopy_gadget: configure_gadget!(),
calldataload_gadget: configure_gadget!(),
calldatasize_gadget: configure_gadget!(),
caller_gadget: configure_gadget!(),
chainid_gadget: configure_gadget!(),
codecopy_gadget: configure_gadget!(),
codesize_gadget: configure_gadget!(),
comparator_gadget: configure_gadget!(),
dup_gadget: configure_gadget!(),
extcodehash_gadget: configure_gadget!(),
extcodesize_gadget: configure_gadget!(),
gas_gadget: configure_gadget!(),
gasprice_gadget: configure_gadget!(),
iszero_gadget: configure_gadget!(),
jump_gadget: configure_gadget!(),
jumpdest_gadget: configure_gadget!(),
jumpi_gadget: configure_gadget!(),
log_gadget: configure_gadget!(),
memory_gadget: configure_gadget!(),
mcopy_gadget: configure_gadget!(),
msize_gadget: configure_gadget!(),
mul_div_mod_gadget: configure_gadget!(),
mulmod_gadget: configure_gadget!(),
not_gadget: configure_gadget!(),
origin_gadget: configure_gadget!(),
pc_gadget: configure_gadget!(),
pop_gadget: configure_gadget!(),
push_gadget: configure_gadget!(),
return_revert_gadget: configure_gadget!(),
sdiv_smod_gadget: configure_gadget!(),
selfbalance_gadget: configure_gadget!(),
sha3_gadget: configure_gadget!(),
address_gadget: configure_gadget!(),
balance_gadget: configure_gadget!(),
blockhash_gadget: configure_gadget!(),
exp_gadget: configure_gadget!(),
sar_gadget: configure_gadget!(),
extcodecopy_gadget: configure_gadget!(),
returndatasize_gadget: configure_gadget!(),
returndatacopy_gadget: configure_gadget!(),
create_gadget: configure_gadget!(),
create2_gadget: configure_gadget!(),
#[cfg(not(feature = "scroll"))]
selfdestruct_gadget: configure_gadget!(),
shl_shr_gadget: configure_gadget!(),
signed_comparator_gadget: configure_gadget!(),
signextend_gadget: configure_gadget!(),
sload_gadget: configure_gadget!(),
sstore_gadget: configure_gadget!(),
tload_gadget: configure_gadget!(),
tstore_gadget: configure_gadget!(),
stop_gadget: configure_gadget!(),
swap_gadget: configure_gadget!(),
block_ctx_u64_gadget: configure_gadget!(),
block_ctx_u160_gadget: configure_gadget!(),
block_ctx_u256_gadget: configure_gadget!(),
#[cfg(feature = "scroll")]
difficulty_gadget: configure_gadget!(),
// error gadgets
error_oog_constant: configure_gadget!(),
error_oog_static_memory_gadget: configure_gadget!(),
error_stack: configure_gadget!(),
error_oog_dynamic_memory_gadget: configure_gadget!(),
error_oog_log: configure_gadget!(),
error_oog_sload_sstore: configure_gadget!(),
error_oog_call: configure_gadget!(),
error_oog_precompile: configure_gadget!(),
error_oog_memory_copy: configure_gadget!(),
error_oog_account_access: configure_gadget!(),
error_oog_sha3: configure_gadget!(),
error_oog_exp: configure_gadget!(),
error_oog_create: configure_gadget!(),
#[cfg(not(feature = "scroll"))]
error_oog_self_destruct: configure_gadget!(),
error_code_store: configure_gadget!(),
error_invalid_jump: configure_gadget!(),
error_invalid_opcode: configure_gadget!(),
error_write_protection: configure_gadget!(),
error_invalid_creation_code: configure_gadget!(),
error_return_data_out_of_bound: configure_gadget!(),
error_precompile_failed: configure_gadget!(),
// precompile calls
precompile_ecrecover_gadget: configure_gadget!(),
precompile_sha2_gadget: configure_gadget!(),
precompile_ripemd_gadget: configure_gadget!(),
precompile_identity_gadget: configure_gadget!(),
precompile_modexp_gadget: configure_gadget!(),
precompile_bn128add_gadget: configure_gadget!(),
precompile_bn128mul_gadget: configure_gadget!(),
precompile_bn128pairing_gadget: configure_gadget!(),
precompile_blake2f_gadget: configure_gadget!(),
precompile_p256verify_gadget: configure_gadget!(),
// step and presets
step: step_curr,
height_map,
stored_expressions_map,
instrument,
};
Self::configure_lookup(
meta,
fixed_table,
byte_table,
tx_table,
rw_table,
bytecode_table,
#[cfg(feature = "dual-bytecode")]
bytecode_table1,
block_table,
copy_table,
keccak_table,
sha256_table,
exp_table,
sig_table,
modexp_table,
ecc_table,
pow_of_rand_table,
&challenges,
&cell_manager,
);
config
}
pub(crate) fn instrument(&self) -> &Instrument {
&self.instrument
}
#[allow(clippy::too_many_arguments)]
fn configure_gadget<G: ExecutionGadget<F>>(
meta: &mut ConstraintSystem<F>,
advices: [Column<Advice>; STEP_WIDTH],
q_usable: Column<Fixed>,
q_step: Column<Advice>,
num_rows_until_next_step: Column<Advice>,
q_step_first: Selector,
q_step_last: Selector,
challenges: &Challenges<Expression<F>>,
step_curr: &Step<F>,
height_map: &mut HashMap<ExecutionState, usize>,
stored_expressions_map: &mut HashMap<ExecutionState, Vec<StoredExpression<F>>>,
instrument: &mut Instrument,
) -> G {
// Configure the gadget with the max height first so we can find out the actual
// height
let height = {
let dummy_step_next = Step::new(meta, advices, MAX_STEP_HEIGHT, true);
let mut cb = EVMConstraintBuilder::new(
step_curr.clone(),
dummy_step_next,
challenges,
G::EXECUTION_STATE,
);
cb.annotation(G::NAME, |cb| G::configure(cb));
let (_, _, _, height) = cb.build();
height
};
// Now actually configure the gadget with the correct minimal height
let step_next = &Step::new(meta, advices, height, true);
let mut cb = EVMConstraintBuilder::new(
step_curr.clone(),
step_next.clone(),
challenges,
G::EXECUTION_STATE,
);
let gadget = cb.annotation(G::NAME, |cb| G::configure(cb));
Self::configure_gadget_impl(
meta,
q_usable,
q_step,
num_rows_until_next_step,
q_step_first,
q_step_last,
step_curr,
step_next,
height_map,
stored_expressions_map,
instrument,
G::NAME,
G::EXECUTION_STATE,
height,
cb,
);
gadget
}
#[allow(clippy::too_many_arguments)]
fn configure_gadget_impl(
meta: &mut ConstraintSystem<F>,
q_usable: Column<Fixed>,
q_step: Column<Advice>,
num_rows_until_next_step: Column<Advice>,
q_step_first: Selector,
q_step_last: Selector,
step_curr: &Step<F>,
step_next: &Step<F>,
height_map: &mut HashMap<ExecutionState, usize>,
stored_expressions_map: &mut HashMap<ExecutionState, Vec<StoredExpression<F>>>,
instrument: &mut Instrument,
name: &'static str,
execution_state: ExecutionState,
height: usize,
mut cb: EVMConstraintBuilder<F>,
) {
// Enforce the step height for this opcode
let num_rows_until_next_step_next = query_expression(meta, |meta| {
meta.query_advice(num_rows_until_next_step, Rotation::next())
});
cb.require_equal(
"num_rows_until_next_step_next := height - 1",
num_rows_until_next_step_next,
(height - 1).expr(),
);
instrument.on_gadget_built(execution_state, &cb);
let (state_selector, constraints, stored_expressions, _) = cb.build();
debug_assert!(
!height_map.contains_key(&execution_state),
"execution state already configured"
);
height_map.insert(execution_state, height);
debug_assert!(
!stored_expressions_map.contains_key(&execution_state),
"execution state already configured"
);
stored_expressions_map.insert(execution_state, stored_expressions);
// Enforce the logic for this opcode
let sel_step: &dyn Fn(&mut VirtualCells<F>) -> Expression<F> =
&|meta| meta.query_advice(q_step, Rotation::cur());
let sel_step_first: &dyn Fn(&mut VirtualCells<F>) -> Expression<F> =
&|meta| meta.query_selector(q_step_first);
let sel_step_last: &dyn Fn(&mut VirtualCells<F>) -> Expression<F> =
&|meta| meta.query_selector(q_step_last);
let sel_not_step_last: &dyn Fn(&mut VirtualCells<F>) -> Expression<F> = &|meta| {
meta.query_advice(q_step, Rotation::cur()) * not::expr(meta.query_selector(q_step_last))
};
let state_selector = &state_selector;
for (selector, constraints) in [
(sel_step, constraints.step),
(sel_step_first, constraints.step_first),
(sel_step_last, constraints.step_last),
(sel_not_step_last, constraints.not_step_last),
] {
if !constraints.is_empty() {
meta.create_gate(name, |meta| {
let q_usable = meta.query_fixed(q_usable, Rotation::cur());
let selector = selector(meta);
constraints.into_iter().map(move |(name, constraint)| {
(
name,
q_usable.clone()
* selector.clone()
* state_selector.clone()
* constraint,
)
})
});
}
}
// Enforce the state transitions for this opcode
meta.create_gate("Constrain state machine transitions", |meta| {
let q_usable = meta.query_fixed(q_usable, Rotation::cur());
let q_step = meta.query_advice(q_step, Rotation::cur());
let q_step_last = meta.query_selector(q_step_last);
// ExecutionState transition should be correct.
iter::empty()
.chain(
IntoIterator::into_iter([
(
"EndTx can only transit to BeginTx or EndInnerBlock",
ExecutionState::EndTx,
vec![ExecutionState::BeginTx, ExecutionState::EndInnerBlock],
),
(
"EndInnerBlock can only transition to BeginTx, EndInnerBlock or Padding",
ExecutionState::EndInnerBlock,
vec![ExecutionState::BeginTx, ExecutionState::EndInnerBlock, ExecutionState::Padding],
),
(
"Padding can only transit to Padding or EndBlock",
ExecutionState::Padding,
vec![ExecutionState::Padding, ExecutionState::EndBlock],
),
])
.filter(move |(_, from, _)| *from == execution_state)
.map(|(_, _, to)| 1.expr() - step_next.execution_state_selector(to)),
)
.chain(
IntoIterator::into_iter([
(
"Only EndTx or EndInnerBlock can transit to BeginTx",
ExecutionState::BeginTx,
vec![ExecutionState::EndTx, ExecutionState::EndInnerBlock],
),
(
"Only ExecutionState which halts / precompile or BeginTx can transit to EndTx",
ExecutionState::EndTx,
ExecutionState::iter()
.filter(ExecutionState::halts)
.chain(ExecutionState::iter().filter(ExecutionState::is_precompiled))
.chain(iter::once(ExecutionState::BeginTx))
.collect(),
),
(
"Only Padding can transit to EndBlock",
ExecutionState::EndBlock,
vec![ExecutionState::Padding],
),
(
// Empty block can result multiple EndInnerBlock states.
"Only EndTx or EndInnerBlock can transit to EndInnerBlock",
ExecutionState::EndInnerBlock,
vec![ExecutionState::EndTx, ExecutionState::EndInnerBlock],
),
])
.filter(move |(_, _, from)| !from.contains(&execution_state))
.map(|(_, to, _)| step_next.execution_state_selector([to])),
)
.chain(
IntoIterator::into_iter([
(
"EndInnerBlock -> BeginTx/EndInnerBlock: block number increases by one",
ExecutionState::EndInnerBlock,
vec![ExecutionState::BeginTx, ExecutionState::EndInnerBlock],
step_next.state.block_number.expr() - step_curr.state.block_number.expr() - 1.expr(),
),
(
"EndInnerBlock -> Padding: block number does not change",
ExecutionState::EndInnerBlock,
vec![ExecutionState::Padding],
step_next.state.block_number.expr() - step_curr.state.block_number.expr(),
),
])
.filter(move |(_, from, _, _)| *from == execution_state)
.map(|(_, _, to, expr)| step_next.execution_state_selector(to) * expr)
)
.chain(
IntoIterator::into_iter([
(
"step_cur != EndInnerBlock: block number does not change",
ExecutionState::EndInnerBlock,
step_next.state.block_number.expr() - step_curr.state.block_number.expr(),
),
])
.filter(move |(_, from, _)| *from != execution_state)
.map(|(_, _, expr)| expr)
)
// Accumulate all state transition checks.
// This can be done because all summed values are enforced to be boolean.
.reduce(|accum, poly| accum + poly)
.map(move |poly| {
q_usable.clone()
* q_step.clone()
* (1.expr() - q_step_last.clone())
* step_curr.execution_state_selector([execution_state])
* poly
})
});
}
#[allow(clippy::too_many_arguments)]
fn configure_lookup(
meta: &mut ConstraintSystem<F>,
fixed_table: &dyn LookupTable<F>,
byte_table: &dyn LookupTable<F>,
tx_table: &dyn LookupTable<F>,
rw_table: &dyn LookupTable<F>,
bytecode_table: &dyn LookupTable<F>,
#[cfg(feature = "dual-bytecode")] bytecode_table1: &dyn LookupTable<F>,
block_table: &dyn LookupTable<F>,
copy_table: &dyn LookupTable<F>,
keccak_table: &dyn LookupTable<F>,
sha256_table: &dyn LookupTable<F>,
exp_table: &dyn LookupTable<F>,
sig_table: &dyn LookupTable<F>,
modexp_table: &dyn LookupTable<F>,
ecc_table: &dyn LookupTable<F>,
pow_of_rand_table: &dyn LookupTable<F>,
challenges: &Challenges<Expression<F>>,
cell_manager: &CellManager<F>,
) {
for column in cell_manager.columns().iter() {
if let CellType::Lookup(table) = column.cell_type {
let name = format!("{table:?}");
meta.lookup_any(Box::leak(name.into_boxed_str()), |meta| {
let table_expressions = match table {
Table::Fixed => fixed_table,
Table::Tx => tx_table,
Table::Rw => rw_table,
Table::Bytecode => bytecode_table,
#[cfg(feature = "dual-bytecode")]
Table::Bytecode1 => bytecode_table1,
Table::Block => block_table,
Table::Copy => copy_table,
Table::Keccak => keccak_table,
Table::Sha256 => sha256_table,
Table::Exp => exp_table,
Table::Sig => sig_table,
Table::ModExp => modexp_table,
Table::Ecc => ecc_table,
Table::PowOfRand => pow_of_rand_table,
}