forked from privacy-scaling-explorations/zkevm-circuits
-
Notifications
You must be signed in to change notification settings - Fork 391
/
Copy pathexecution.rs
1450 lines (1348 loc) · 45.6 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
//! Execution step related module.
use std::{
marker::PhantomData,
ops::{Add, Mul, Neg},
};
use crate::{
circuit_input_builder::CallContext,
error::{ExecError, OogError},
exec_trace::OperationRef,
operation::RWCounter,
precompile::{PrecompileAuxData, PrecompileCalls},
};
use eth_types::{
evm_types::{memory::MemoryWordRange, Gas, GasCost, MemoryAddress, OpcodeId, ProgramCounter},
sign_types::SignData,
Address, Field, GethExecStep, ToLittleEndian, Word, H256, U256,
};
use ethers_core::k256::elliptic_curve::subtle::CtOption;
use gadgets::impl_expr;
use halo2_proofs::{
arithmetic::{CurveAffine, Field as Halo2Field},
halo2curves::{
bn256::{Fq, Fq2, Fr, G1Affine, G2Affine},
group::prime::PrimeCurveAffine,
},
plonk::Expression,
};
/// An execution step of the EVM.
#[derive(Clone, Debug)]
pub struct ExecStep {
/// Execution state
pub exec_state: ExecState,
/// Program Counter
pub pc: ProgramCounter,
/// Stack size
pub stack_size: usize,
/// Memory size
pub memory_size: usize,
/// Gas left
pub gas_left: Gas,
/// Gas cost of the step. If the error is OutOfGas caused by a "gas uint64
/// overflow", this value will **not** be the actual Gas cost of the
/// step.
pub gas_cost: GasCost,
/// Accumulated gas refund
pub gas_refund: Gas,
/// Call index within the Transaction.
pub call_index: usize,
/// The global counter when this step was executed.
pub rwc: RWCounter,
/// Reversible Write Counter. Counter of write operations in the call that
/// will need to be undone in case of a revert. Value at the beginning of
/// the step.
pub reversible_write_counter: usize,
/// Number of reversible write operations done by this step.
pub reversible_write_counter_delta: usize,
/// Log index when this step was executed.
pub log_id: usize,
/// The list of references to Operations in the container
pub bus_mapping_instance: Vec<OperationRef>,
/// Number of rw operations performed via a copy event in this step.
pub copy_rw_counter_delta: u64,
/// Error generated by this step
pub error: Option<ExecError>,
/// Optional auxiliary data that is attached to precompile call internal states.
pub aux_data: Option<PrecompileAuxData>,
}
impl ExecStep {
/// Create a new Self from a `GethExecStep`.
pub fn new(
step: &GethExecStep,
call_ctx: &CallContext,
rwc: RWCounter,
reversible_write_counter: usize,
log_id: usize,
) -> Self {
ExecStep {
exec_state: ExecState::Op(step.op),
pc: step.pc,
stack_size: step.stack.0.len(),
memory_size: call_ctx.memory.len(),
gas_left: step.gas,
gas_cost: step.gas_cost,
gas_refund: step.refund,
call_index: call_ctx.index,
rwc,
reversible_write_counter,
reversible_write_counter_delta: 0,
log_id,
bus_mapping_instance: Vec::new(),
copy_rw_counter_delta: 0,
error: None,
aux_data: None,
}
}
/// Returns `true` if `error` is oog and stack related..
pub fn oog_or_stack_error(&self) -> bool {
matches!(
self.error,
Some(ExecError::OutOfGas(_) | ExecError::StackOverflow | ExecError::StackUnderflow)
)
}
/// Returns `true` if this is an execution step of Precompile.
pub fn is_precompiled(&self) -> bool {
matches!(self.exec_state, ExecState::Precompile(_))
}
/// Returns `true` if `error` is oog in precompile calls
pub fn is_precompile_oog_err(&self) -> bool {
matches!(self.error, Some(ExecError::OutOfGas(OogError::Precompile)))
}
}
impl Default for ExecStep {
fn default() -> Self {
Self {
exec_state: ExecState::Op(OpcodeId::INVALID(0)),
pc: ProgramCounter(0),
stack_size: 0,
memory_size: 0,
gas_left: Gas(0),
gas_cost: GasCost(0),
gas_refund: Gas(0),
call_index: 0,
rwc: RWCounter(0),
reversible_write_counter: 0,
reversible_write_counter_delta: 0,
log_id: 0,
bus_mapping_instance: Vec::new(),
copy_rw_counter_delta: 0,
error: None,
aux_data: None,
}
}
}
/// Execution state
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ExecState {
/// EVM Opcode ID
Op(OpcodeId),
/// Precompile call
Precompile(PrecompileCalls),
/// Virtual step Begin Tx
BeginTx,
/// Virtual step End Tx
EndTx,
/// Virtual step End Block
EndBlock,
}
impl ExecState {
/// Returns `true` if `ExecState` is an opcode and the opcode is a `PUSHn`.
pub fn is_push(&self) -> bool {
if let ExecState::Op(op) = self {
op.is_push()
} else {
false
}
}
/// Returns `true` if `ExecState` is an opcode and the opcode is a `DUPn`.
pub fn is_dup(&self) -> bool {
if let ExecState::Op(op) = self {
op.is_dup()
} else {
false
}
}
/// Returns `true` if `ExecState` is an opcode and the opcode is a `SWAPn`.
pub fn is_swap(&self) -> bool {
if let ExecState::Op(op) = self {
op.is_swap()
} else {
false
}
}
/// Returns `true` if `ExecState` is an opcode and the opcode is a `Logn`.
pub fn is_log(&self) -> bool {
if let ExecState::Op(op) = self {
op.is_log()
} else {
false
}
}
/// Returns `true` if the `ExecState` is one of the opcodes CALL, CALLCODE, STATICCALL or
/// DELEGATECALL.
pub fn is_call(&self) -> bool {
if let ExecState::Op(op) = self {
op.is_call_with_value() || op.is_call_without_value()
} else {
false
}
}
}
/// Defines the various source/destination types for a copy event.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CopyDataType {
/// When we need to pad the Copy rows of the circuit up to a certain maximum
/// with rows that are not "useful".
Padding,
/// When the source for the copy event is the bytecode table.
Bytecode,
/// When the source/destination for the copy event is memory.
Memory,
/// When the source for the copy event is tx's calldata.
TxCalldata,
/// When the destination for the copy event is tx's log.
TxLog,
/// When the destination rows are not directly for copying but for a special
/// scenario where we wish to accumulate the value (RLC) over all rows.
/// This is used for Copy Lookup from SHA3 opcode verification.
RlcAcc,
/// When copy event is access-list addresses (EIP-2930), source is tx-table
/// and destination is rw-table.
AccessListAddresses,
/// When copy event is access-list storage keys (EIP-2930), source is
/// tx-table and destination is rw-table.
AccessListStorageKeys,
}
impl CopyDataType {
/// How many bits are necessary to represent a copy data type.
pub const N_BITS: usize = 3usize;
}
const NUM_COPY_DATA_TYPES: usize = 8usize;
pub struct CopyDataTypeIter {
idx: usize,
back_idx: usize,
marker: PhantomData<()>,
}
impl CopyDataTypeIter {
fn get(&self, idx: usize) -> Option<CopyDataType> {
match idx {
0usize => Some(CopyDataType::Padding),
1usize => Some(CopyDataType::Bytecode),
2usize => Some(CopyDataType::Memory),
3usize => Some(CopyDataType::TxCalldata),
4usize => Some(CopyDataType::TxLog),
5usize => Some(CopyDataType::RlcAcc),
6usize => Some(CopyDataType::AccessListAddresses),
7usize => Some(CopyDataType::AccessListStorageKeys),
_ => None,
}
}
}
impl strum::IntoEnumIterator for CopyDataType {
type Iterator = CopyDataTypeIter;
fn iter() -> CopyDataTypeIter {
CopyDataTypeIter {
idx: 0,
back_idx: 0,
marker: PhantomData,
}
}
}
impl Iterator for CopyDataTypeIter {
type Item = CopyDataType;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
#[allow(clippy::iter_nth_zero)]
self.nth(0)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let t = if self.idx + self.back_idx >= NUM_COPY_DATA_TYPES {
0
} else {
NUM_COPY_DATA_TYPES - self.idx - self.back_idx
};
(t, Some(t))
}
fn nth(&mut self, n: usize) -> Option<<Self as Iterator>::Item> {
let idx = self.idx + n + 1;
if idx + self.back_idx > NUM_COPY_DATA_TYPES {
self.idx = NUM_COPY_DATA_TYPES;
None
} else {
self.idx = idx;
self.get(idx - 1)
}
}
}
impl ExactSizeIterator for CopyDataTypeIter {
fn len(&self) -> usize {
self.size_hint().0
}
}
impl DoubleEndedIterator for CopyDataTypeIter {
fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
let back_idx = self.back_idx + 1;
if self.idx + back_idx > NUM_COPY_DATA_TYPES {
self.back_idx = NUM_COPY_DATA_TYPES;
None
} else {
self.back_idx = back_idx;
self.get(NUM_COPY_DATA_TYPES - self.back_idx)
}
}
}
impl From<CopyDataType> for usize {
fn from(t: CopyDataType) -> Self {
match t {
CopyDataType::Padding => 0,
CopyDataType::Bytecode => 1,
CopyDataType::Memory => 2,
CopyDataType::TxCalldata => 3,
CopyDataType::TxLog => 4,
CopyDataType::RlcAcc => 5,
CopyDataType::AccessListAddresses => 6,
CopyDataType::AccessListStorageKeys => 7,
}
}
}
impl From<&CopyDataType> for u64 {
fn from(t: &CopyDataType) -> Self {
match t {
CopyDataType::Padding => 0,
CopyDataType::Bytecode => 1,
CopyDataType::Memory => 2,
CopyDataType::TxCalldata => 3,
CopyDataType::TxLog => 4,
CopyDataType::RlcAcc => 5,
CopyDataType::AccessListAddresses => 6,
CopyDataType::AccessListStorageKeys => 7,
}
}
}
impl Default for CopyDataType {
fn default() -> Self {
Self::Memory
}
}
impl_expr!(CopyDataType, u64::from);
/// Defines a single copy step in a copy event. This type is unified over the
/// source/destination row in the copy table.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CopyStep {
/// Byte value copied in this step.
pub half_word: [u8; 16],
/// Byte value before this step.
pub prev_half_word: [u8; 16],
/// mask indicates this byte won't be copied.
pub mask: [bool; 16],
}
impl From<&[(u8, bool, bool)]> for CopyStep {
fn from(steps: &[(u8, bool, bool)]) -> Self {
assert_eq!(steps.len(), 16, "steps length should be 16");
let bytes: [u8; 16] = steps
.iter()
.copied()
.map(|(v, _, _)| v)
.collect::<Vec<_>>()
.try_into()
.unwrap();
Self {
half_word: bytes,
prev_half_word: bytes,
mask: steps
.iter()
.copied()
.map(|(_, _, m)| m)
.collect::<Vec<_>>()
.try_into()
.unwrap(),
}
}
}
/// Defines an enum type that can hold either a number or a hash value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NumberOrHash {
/// Variant to indicate a number value.
Number(usize),
/// Variant to indicate a 256-bits hash value.
Hash(H256),
}
/// Represents all bytes related in one copy event.
///
/// - When the source is memory, `bytes` is the memory content, including masked areas. The
/// destination data is the non-masked bytes.
/// - When only the destination is memory or log, `bytes` is the memory content to write, including
/// masked areas. The source data is the non-masked bytes.
/// - When both source and destination are memory or log, it is `aux_bytes` that holds the
/// destination memory.
///
/// Additionally, when the destination is memory, `bytes_write_prev` holds the memory content
/// *before* the write.
#[derive(Clone, Debug, Default)]
pub struct CopyBytes {
/// Represents the list of (bytes, is_code, mask) copied during this copy event
pub bytes: Vec<(u8, bool, bool)>,
/// Represents the list of (bytes, is_code, mask) read to copy during this copy event, used for
/// memory to memory write case
pub aux_bytes: Option<Vec<(u8, bool, bool)>>,
/// Represents the list of bytes before this copy event, it is required for memory write copy
/// event
pub bytes_write_prev: Option<Vec<u8>>,
}
impl CopyBytes {
/// construct CopyBytes instance
pub fn new(
bytes: Vec<(u8, bool, bool)>,
aux_bytes: Option<Vec<(u8, bool, bool)>>,
bytes_write_prev: Option<Vec<u8>>,
) -> Self {
Self {
bytes,
aux_bytes,
bytes_write_prev,
}
}
}
/// Defines a copy event associated with EVM opcodes such as CALLDATACOPY,
/// CODECOPY, CREATE, etc. More information:
/// <https://github.com/privacy-scaling-explorations/zkevm-specs/blob/master/specs/copy-proof.md>.
#[derive(Clone, Debug)]
pub struct CopyEvent {
/// Represents the start address at the source of the copy event.
pub src_addr: u64,
/// Represents the end address at the source of the copy event.
/// It must be `src_addr_end >= src_addr`.
pub src_addr_end: u64,
/// Represents the source type.
pub src_type: CopyDataType,
/// Represents the relevant ID for source.
pub src_id: NumberOrHash,
/// Represents the start address at the destination of the copy event.
pub dst_addr: u64,
/// Represents the destination type.
pub dst_type: CopyDataType,
/// Represents the relevant ID for destination.
pub dst_id: NumberOrHash,
/// An optional field to hold the log ID in case of the destination being
/// TxLog.
pub log_id: Option<u64>,
/// Value of rw counter at start of this copy event
pub rw_counter_start: RWCounter,
/// Represents the list of bytes related during this copy event
pub copy_bytes: CopyBytes,
/// Represents transaction access list (EIP-2930), if copy data type is
/// address, the first item is access list address and second is zero, if
/// copy data type is storage key, the first item is access list address and
/// second is access list storage key.
pub access_list: Vec<(Address, Word)>,
}
pub type CopyEventSteps = Vec<(u8, bool, bool)>;
pub type CopyEventPrevBytes = Vec<u8>;
impl CopyEvent {
/// The full length of the event, including masked segments.
pub fn full_length(&self) -> u64 {
self.copy_bytes.bytes.len() as u64
}
/// The length of the copied data, excluding masked segments.
pub fn copy_length(&self) -> u64 {
self.copy_bytes.bytes.iter().filter(|&step| !step.2).count() as u64
}
/// Whether the source performs RW lookups in the state circuit.
pub fn is_source_rw(&self) -> bool {
self.src_type == CopyDataType::Memory
}
/// Whether the destination performs RW lookups in the state circuit.
pub fn is_destination_rw(&self) -> bool {
self.dst_type == CopyDataType::Memory
|| self.dst_type == CopyDataType::TxLog
|| self.dst_type == CopyDataType::AccessListAddresses
|| self.dst_type == CopyDataType::AccessListStorageKeys
}
/// Whether the RLC of data must be computed.
pub fn has_rlc(&self) -> bool {
matches!(
(self.src_type, self.dst_type),
(CopyDataType::RlcAcc, _) | (_, CopyDataType::RlcAcc) | (_, CopyDataType::Bytecode)
)
}
/// The RW counter of the first RW lookup performed by this copy event.
pub fn rw_counter_start(&self) -> u64 {
usize::from(self.rw_counter_start) as u64
}
/// The number of RW lookups performed by this copy event.
pub fn rw_counter_delta(&self) -> u64 {
if self.dst_type == CopyDataType::AccessListAddresses
|| self.dst_type == CopyDataType::AccessListStorageKeys
{
// For access list, the placeholder is used for copy bytes which
// value will be replaced by address and storage key, and no word
// operations.
return self.full_length();
}
(self.is_source_rw() as u64 + self.is_destination_rw() as u64) * (self.full_length() / 32)
}
}
/// Defines a builder to construct a copy event.
///
/// ```markdown
/// │◄──read_offset──►│
/// ├─────────────────┼───────────────┬──────┐
/// │ │ Source Bytes │ │
/// └─────────────────┼───────┬───────┼──────┘
/// get_padding │ mapper │
/// ┌─────────▼───────────┼───────▼───────┼─────────┐
/// │ Padding │ Copied Bytes │ Padding │
/// ├─────────────────────┼───────────────┼─────────┤
/// │◄────write_offset───►│◄───length────►│ │
/// │◄─────────────── step_length ─────────────────►│
/// ```
pub struct CopyEventStepsBuilder<
Source,
ReadOffset,
WriteOffset,
StepLength,
Length,
Padding,
Mapper,
> {
source: Source,
read_offset: ReadOffset,
write_offset: WriteOffset,
step_length: StepLength,
length: Length,
padding_byte_getter: Padding,
mapper: Mapper,
}
impl Default for CopyEventStepsBuilder<(), (), (), (), (), (), ()> {
fn default() -> Self {
Self::new()
}
}
impl CopyEventStepsBuilder<(), (), (), (), (), (), ()> {
/// Create a new copy steps builder.
pub fn new() -> Self {
CopyEventStepsBuilder {
source: (),
read_offset: (),
write_offset: (),
step_length: (),
length: (),
padding_byte_getter: (),
mapper: (),
}
}
/// Create a memory copy steps builder.
#[allow(clippy::type_complexity)]
pub fn memory() -> CopyEventStepsBuilder<
(),
(),
(),
(),
(),
Box<dyn Fn(&[u8], usize) -> u8>,
Box<dyn Fn(&u8) -> (u8, bool)>,
> {
Self::new()
.padding_byte_getter(
Box::new(|s: &[u8], idx: usize| s.get(idx).copied().unwrap_or(0))
as Box<dyn Fn(&[u8], usize) -> u8>,
)
.mapper(Box::new(|v: &u8| (*v, false)) as Box<dyn Fn(&u8) -> (u8, bool)>)
}
/// Create a memory copy steps builder from rage.
#[allow(clippy::type_complexity)]
pub fn memory_range(
range: MemoryWordRange,
) -> CopyEventStepsBuilder<
(),
MemoryAddress,
MemoryAddress,
MemoryAddress,
MemoryAddress,
Box<dyn Fn(&[u8], usize) -> u8>,
Box<dyn Fn(&u8) -> (u8, bool)>,
> {
Self::memory()
.read_offset(range.shift())
.write_offset(range.shift())
.step_length(range.full_length())
.length(range.original_length())
}
}
impl<Source, ReadOffset, WriteOffset, StepLength, Length, Padding, Mapper>
CopyEventStepsBuilder<Source, ReadOffset, WriteOffset, StepLength, Length, Padding, Mapper>
{
/// Set source
pub fn source<New>(
self,
source: New,
) -> CopyEventStepsBuilder<New, ReadOffset, WriteOffset, StepLength, Length, Padding, Mapper>
{
let CopyEventStepsBuilder {
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
..
} = self;
CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
}
}
/// Set read offset
pub fn read_offset<New>(
self,
read_offset: New,
) -> CopyEventStepsBuilder<Source, New, WriteOffset, StepLength, Length, Padding, Mapper> {
let CopyEventStepsBuilder {
source,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
..
} = self;
CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
}
}
/// Set write offset
pub fn write_offset<New>(
self,
write_offset: New,
) -> CopyEventStepsBuilder<Source, ReadOffset, New, StepLength, Length, Padding, Mapper> {
let CopyEventStepsBuilder {
source,
read_offset,
step_length,
length,
padding_byte_getter,
mapper,
..
} = self;
CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
}
}
/// Set step length
pub fn step_length<New>(
self,
step_length: New,
) -> CopyEventStepsBuilder<Source, ReadOffset, WriteOffset, New, Length, Padding, Mapper> {
let CopyEventStepsBuilder {
source,
read_offset,
write_offset,
length,
padding_byte_getter,
mapper,
..
} = self;
CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
}
}
/// Set length
pub fn length<New>(
self,
length: New,
) -> CopyEventStepsBuilder<Source, ReadOffset, WriteOffset, StepLength, New, Padding, Mapper>
{
let CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
padding_byte_getter,
mapper,
..
} = self;
CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
}
}
/// Set padding byte getter
pub fn padding_byte_getter<New>(
self,
padding_byte_getter: New,
) -> CopyEventStepsBuilder<Source, ReadOffset, WriteOffset, StepLength, Length, New, Mapper>
{
let CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
mapper,
..
} = self;
CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
}
}
/// Set mapper
pub fn mapper<New>(
self,
mapper: New,
) -> CopyEventStepsBuilder<Source, ReadOffset, WriteOffset, StepLength, Length, Padding, New>
{
let CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
..
} = self;
CopyEventStepsBuilder {
source,
read_offset,
write_offset,
step_length,
length,
padding_byte_getter,
mapper,
}
}
}
impl<'a, T: 'a, ReadOffset, WriteOffset, StepLength, Length, Padding, Mapper>
CopyEventStepsBuilder<&'a [T], ReadOffset, WriteOffset, StepLength, Length, Padding, Mapper>
where
ReadOffset: Into<MemoryAddress>,
WriteOffset: Into<MemoryAddress>,
StepLength: Into<MemoryAddress>,
Length: Into<MemoryAddress>,
Padding: Fn(&[T], usize) -> u8,
Mapper: Fn(&T) -> (u8, bool),
{
/// Build the copy event steps.
pub fn build(self) -> CopyEventSteps {
let read_offset = self.read_offset.into().0;
let write_offset = self.write_offset.into().0;
let step_length = self.step_length.into().0;
let length = self.length.into().0;
let read_end = read_offset
.checked_add(length)
.expect("unexpected overflow");
let mut steps = Vec::with_capacity(step_length);
for idx in 0..step_length {
if (idx < write_offset) || (idx >= write_offset + length) {
// padding bytes
let value = (self.padding_byte_getter)(self.source, idx);
steps.push((value, false, true));
} else {
let addr = read_offset
.checked_add(idx - write_offset)
.unwrap_or(read_end);
if addr < self.source.len() {
let (value, is_code) = (self.mapper)(&self.source[addr]);
steps.push((value, is_code, false));
} else {
// out range bytes
steps.push((0, false, false));
}
}
}
steps
}
}
/// Intermediary multiplication step, representing `a * b == d (mod 2^256)`
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExpStep {
/// First multiplicand.
pub a: Word,
/// Second multiplicand.
pub b: Word,
/// Multiplication result.
pub d: Word,
}
impl From<(Word, Word, Word)> for ExpStep {
fn from(values: (Word, Word, Word)) -> Self {
Self {
a: values.0,
b: values.1,
d: values.2,
}
}
}
/// Event representating an exponentiation `a ^ b == d (mod 2^256)`.
#[derive(Clone, Debug)]
pub struct ExpEvent {
/// Base `a` for the exponentiation.
pub base: Word,
/// Exponent `b` for the exponentiation.
pub exponent: Word,
/// Exponentiation result.
pub exponentiation: Word,
/// Intermediate multiplication results.
pub steps: Vec<ExpStep>,
}
impl Default for ExpEvent {
fn default() -> Self {
Self {
base: 2.into(),
exponent: 2.into(),
exponentiation: 4.into(),
steps: vec![ExpStep {
a: 2.into(),
b: 2.into(),
d: 4.into(),
}],
}
}
}
/// I/Os from all precompiled contract calls in a block.
#[derive(Clone, Debug, Default)]
pub struct PrecompileEvents {
/// All events.
pub events: Vec<PrecompileEvent>,
}
impl PrecompileEvents {
/// Get all ecrecover events.
pub fn get_ecrecover_events(&self) -> Vec<SignData> {
self.events
.iter()
.filter_map(|e| {
if let PrecompileEvent::Ecrecover(sign_data) = e {
Some(sign_data)
} else {
None
}
})
.cloned()
.collect()
}
/// Get all EcAdd events.
pub fn get_ec_add_events(&self) -> Vec<EcAddOp> {
self.events
.iter()
.filter_map(|e| {
if let PrecompileEvent::EcAdd(op) = e {
Some(op)
} else {
None
}
})
.cloned()
.collect()
}
/// Get all EcMul events.
pub fn get_ec_mul_events(&self) -> Vec<EcMulOp> {
self.events
.iter()
.filter_map(|e| {
if let PrecompileEvent::EcMul(op) = e {
Some(op)
} else {
None
}
})
.cloned()
.collect()
}
/// Get all EcPairing events.
pub fn get_ec_pairing_events(&self) -> Vec<EcPairingOp> {
self.events
.iter()
.cloned()
.filter_map(|e| {
if let PrecompileEvent::EcPairing(op) = e {
Some(*op)
} else {
None
}
})
.collect()
}
/// Get all Big Modexp events.
pub fn get_modexp_events(&self) -> Vec<BigModExp> {
self.events
.iter()
.filter_map(|e| {
if let PrecompileEvent::ModExp(op) = e {
Some(op)
} else {
None
}
})
.cloned()
.collect()
}
/// Get all SHA256 events.
pub fn get_sha256_events(&self) -> Vec<SHA256> {
self.events
.iter()
.filter_map(|e| {
if let PrecompileEvent::SHA256(op) = e {
Some(op)
} else {
None
}
})
.cloned()
.collect()
}
}
/// I/O from a precompiled contract call.
#[derive(Clone, Debug)]
pub enum PrecompileEvent {
/// Represents the I/O from Ecrecover call.
Ecrecover(SignData),
/// Represents the I/O from EcAdd call.
EcAdd(EcAddOp),
/// Represents the I/O from EcMul call.
EcMul(EcMulOp),
/// Represents the I/O from EcPairing call.
EcPairing(Box<EcPairingOp>),
/// Represents the I/O from Modexp call.
ModExp(BigModExp),
/// Represents the I/O from SHA256 call.
SHA256(SHA256),
}
impl Default for PrecompileEvent {
fn default() -> Self {
Self::Ecrecover(SignData::default())