forked from privacy-scaling-explorations/zkevm-circuits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput_state_ref.rs
1771 lines (1635 loc) · 66 KB
/
input_state_ref.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
//! CircuitInput builder tooling module.
use super::{
get_call_memory_offset_length, get_create_init_code, Block, BlockContext, Call, CallContext,
CallKind, ChunkContext, CodeSource, CopyEvent, ExecState, ExecStep, ExpEvent, PrecompileEvent,
Transaction, TransactionContext,
};
use crate::{
error::{DepthError, ExecError, InsufficientBalanceError, NonceUintOverflowError},
exec_trace::OperationRef,
operation::{
AccountField, AccountOp, CallContextField, CallContextOp, MemoryOp, Op, OpEnum, Operation,
StackOp, Target, TxAccessListAccountOp, TxLogField, TxLogOp, TxReceiptField, TxReceiptOp,
RW,
},
precompile::{is_precompiled, PrecompileCalls},
state_db::{CodeDB, StateDB},
Error,
};
use eth_types::{
evm_types::{
gas_utils::memory_expansion_gas_cost, GasCost, MemoryAddress, OpcodeId, StackAddress,
},
Address, Bytecode, GethExecStep, ToAddress, ToBigEndian, ToWord, Word, H256, U256,
};
use ethers_core::utils::{get_contract_address, get_create2_address};
use std::cmp::max;
/// Reference to the internal state of the CircuitInputBuilder in a particular
/// [`ExecStep`].
pub struct CircuitInputStateRef<'a> {
/// StateDB
pub sdb: &'a mut StateDB,
/// CodeDB
pub code_db: &'a mut CodeDB,
/// Block
pub block: &'a mut Block,
/// Block Context
pub block_ctx: &'a mut BlockContext,
/// Chunk Context
pub chunk_ctx: &'a mut ChunkContext,
/// Transaction
pub tx: &'a mut Transaction,
/// Transaction Context
pub tx_ctx: &'a mut TransactionContext,
/// Max rw number limit
pub max_rws: Option<usize>,
}
impl<'a> CircuitInputStateRef<'a> {
/// Create a new step from a `GethExecStep`
pub fn new_step(&self, geth_step: &GethExecStep) -> Result<ExecStep, Error> {
let call_ctx = self.tx_ctx.call_ctx()?;
Ok(ExecStep::new(
geth_step,
call_ctx,
self.block_ctx.rwc,
self.chunk_ctx.rwc,
call_ctx.reversible_write_counter,
self.tx_ctx.log_id,
))
}
/// Create a new InvalidTx step
pub fn new_invalid_tx_step(&self) -> ExecStep {
ExecStep {
exec_state: ExecState::InvalidTx,
gas_left: self.tx.gas(),
rwc: self.block_ctx.rwc,
rwc_inner_chunk: self.chunk_ctx.rwc,
..Default::default()
}
}
/// Create a new BeginTx step
pub fn new_begin_tx_step(&self) -> ExecStep {
ExecStep {
exec_state: ExecState::BeginTx,
gas_left: self.tx.gas(),
rwc: self.block_ctx.rwc,
rwc_inner_chunk: self.chunk_ctx.rwc,
..Default::default()
}
}
/// Create a new EndTx step
pub fn new_end_tx_step(&self) -> ExecStep {
let prev_step = self
.tx
.steps()
.last()
.expect("steps should have at least one BeginTx step");
ExecStep {
exec_state: ExecState::EndTx,
gas_left: if prev_step.error.is_none() {
let mut gas_left = prev_step.gas_left - prev_step.gas_cost;
// for contract creation
let call = self.tx.calls()[0].clone();
if call.is_create() {
let code_hash = self.sdb.get_account(&call.address).1.code_hash;
let bytecode_len = self.code(code_hash).unwrap().len() as u64;
let deposit_cost = bytecode_len * GasCost::CODE_DEPOSIT_BYTE_COST;
assert!(
gas_left >= deposit_cost,
"gas left {gas_left} is not enough for deposit cost {deposit_cost}"
);
gas_left -= deposit_cost;
}
gas_left
} else {
// consume all remaining gas when non revert err happens
0
},
rwc: self.block_ctx.rwc,
rwc_inner_chunk: self.chunk_ctx.rwc,
// For tx without code execution
reversible_write_counter: if let Some(call_ctx) = self.tx_ctx.calls().last() {
call_ctx.reversible_write_counter
} else {
0
},
log_id: self.tx_ctx.log_id,
..Default::default()
}
}
/// Push an [`Operation`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter) and then adds a
/// reference to the stored operation ([`OperationRef`]) inside the
/// bus-mapping instance of the current [`ExecStep`]. Then increase the
/// block_ctx [`RWCounter`](crate::operation::RWCounter) by one.
pub fn push_op<T: Op>(&mut self, step: &mut ExecStep, rw: RW, op: T) -> Result<(), Error> {
if let OpEnum::Account(op) = op.clone().into_enum() {
self.check_update_sdb_account(rw, &op)
}
let op_ref = self.block.container.insert(Operation::new(
self.block_ctx.rwc.inc_pre(),
self.chunk_ctx.rwc.inc_pre(),
rw,
op,
));
step.bus_mapping_instance.push(op_ref);
self.check_rw_num_limit()
}
/// Check whether rws will overflow circuit limit.
pub fn check_rw_num_limit(&self) -> Result<(), Error> {
if let Some(max_rws) = self.max_rws {
let rwc = self.chunk_ctx.rwc.0;
if rwc > max_rws {
log::error!(
"chunk inner rwc > max_rws, rwc={}, max_rws={}",
rwc,
max_rws
);
return Err(Error::RwsNotEnough(max_rws, rwc));
};
}
Ok(())
}
/// Push a read type [`CallContextOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with
/// the next [`RWCounter`](crate::operation::RWCounter) and then adds a
/// reference to the stored operation ([`OperationRef`]) inside the
/// bus-mapping instance of the current [`ExecStep`]. Then increase the
/// block_ctx [`RWCounter`](crate::operation::RWCounter) by one.
pub fn call_context_read(
&mut self,
step: &mut ExecStep,
call_id: usize,
field: CallContextField,
value: Word,
) -> Result<(), Error> {
let op = CallContextOp {
call_id,
field,
value,
};
self.push_op(step, RW::READ, op)
}
/// Push a write type [`CallContextOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with
/// the next [`RWCounter`](crate::operation::RWCounter) and then adds a
/// reference to the stored operation ([`OperationRef`]) inside the
/// bus-mapping instance of the current [`ExecStep`]. Then increase the
/// block_ctx [`RWCounter`](crate::operation::RWCounter) by one.
pub fn call_context_write(
&mut self,
step: &mut ExecStep,
call_id: usize,
field: CallContextField,
value: Word,
) -> Result<(), Error> {
let op = CallContextOp {
call_id,
field,
value,
};
self.push_op(step, RW::WRITE, op)
}
/// Push an [`Operation`] with reversible to be true into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter) and then adds a
/// reference to the stored operation
/// ([`OperationRef`]) inside the
/// bus-mapping instance of the current [`ExecStep`]. Then increase the
/// block_ctx [`RWCounter`](crate::operation::RWCounter) by one.
/// This method should be used in `Opcode::gen_associated_ops` instead of
/// `push_op` when the operation is `RW::WRITE` and it can be reverted (for
/// example, a write [`StorageOp`](crate::operation::StorageOp)).
pub fn push_op_reversible<T: Op>(&mut self, step: &mut ExecStep, op: T) -> Result<(), Error> {
self.check_apply_op(&op.clone().into_enum());
let op_ref = self.block.container.insert(Operation::new_reversible(
self.block_ctx.rwc.inc_pre(),
self.chunk_ctx.rwc.inc_pre(),
RW::WRITE,
op,
));
step.bus_mapping_instance.push(op_ref);
// Increase reversible_write_counter
self.call_ctx_mut()?.reversible_write_counter += 1;
step.reversible_write_counter_delta += 1;
// Add the operation into reversible_ops if this call is not persistent
if !self.call()?.is_persistent {
self.tx_ctx
.reversion_groups
.last_mut()
.expect("reversion_groups should not be empty for non-persistent call")
.op_refs
.push((self.tx.steps().len(), op_ref));
}
self.check_rw_num_limit()
}
/// Push a read type [`MemoryOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter) and `call_id`, and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn memory_read(
&mut self,
step: &mut ExecStep,
address: MemoryAddress,
) -> Result<u8, Error> {
let byte = &self.call_ctx()?.memory.read_chunk(address, 1.into())[0];
let call_id = self.call()?.call_id;
self.push_op(step, RW::READ, MemoryOp::new(call_id, address, *byte))?;
Ok(*byte)
}
/// Almost the same as above memory_read, but read from the caller's context instead.
pub fn memory_read_caller(
&mut self,
step: &mut ExecStep,
address: MemoryAddress, // Caution: make sure this address = slot passing
) -> Result<u8, Error> {
let byte = &self.caller_ctx()?.memory.read_chunk(address, 1.into())[0];
let call_id = self.call()?.caller_id;
self.push_op(step, RW::READ, MemoryOp::new(call_id, address, *byte))?;
Ok(*byte)
}
/// Push a write type [`MemoryOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter) and `call_id`, and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn memory_write(
&mut self,
step: &mut ExecStep,
address: MemoryAddress,
value: u8,
) -> Result<u8, Error> {
let call_id = self.call()?.call_id;
let mem = &mut self.call_ctx_mut()?.memory;
let value_prev = mem.read_chunk(address, 1.into())[0];
mem.write_chunk(address, &[value]);
self.push_op(step, RW::WRITE, MemoryOp::new(call_id, address, value))?;
Ok(value_prev)
}
/// Almost the same as above memory_write, but write to the caller's context instead.
pub fn memory_write_caller(
&mut self,
step: &mut ExecStep,
address: MemoryAddress, // Caution: make sure this address = slot passing
value: u8,
) -> Result<u8, Error> {
let call_id = self.call()?.caller_id;
let mem = &mut self.caller_ctx_mut()?.memory;
let value_prev = mem.read_chunk(address, 1.into())[0];
mem.write_chunk(address, &[value_prev]);
self.push_op(step, RW::WRITE, MemoryOp::new(call_id, address, value))?;
Ok(value_prev)
}
/// Push a write type [`StackOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter) and `call_id`, and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn stack_write(
&mut self,
step: &mut ExecStep,
address: StackAddress,
value: Word,
) -> Result<(), Error> {
let call_id = self.call()?.call_id;
self.push_op(step, RW::WRITE, StackOp::new(call_id, address, value))?;
Ok(())
}
/// Push a read type [`StackOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter) and `call_id`, and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn stack_read(
&mut self,
step: &mut ExecStep,
address: StackAddress,
value: Word,
) -> Result<(), Error> {
let call_id = self.call()?.call_id;
self.push_op(step, RW::READ, StackOp::new(call_id, address, value))?;
Ok(())
}
/// First check the validity and consistency of the rw operation against the
/// account in the StateDB, then if the rw operation is a write, apply
/// it to the corresponding account in the StateDB.
fn check_update_sdb_account(&mut self, rw: RW, op: &AccountOp) {
let account = self.sdb.get_account_mut(&op.address).1;
// -- sanity check begin --
// Verify that a READ doesn't change the field value
if matches!(rw, RW::READ) && op.value_prev != op.value {
panic!(
"RWTable Account field read where value_prev != value rwc: {}, op: {:?}",
self.block_ctx.rwc.0, op
)
}
// NOTE: In the State Circuit we use code_hash=0 to encode non-existing
// accounts, but the corresponding account in the state DB is empty
// (which means code_hash=EMPTY_HASH).
let account_value_prev = match op.field {
AccountField::Nonce => account.nonce.to_word(),
AccountField::Balance => account.balance,
AccountField::CodeHash => {
if account.is_empty() {
if op.value.is_zero() {
// Writing code_hash=0 to empty account is a noop to the StateDB.
return;
}
// Reading a code_hash=EMPTY_HASH of an empty account in the StateDB is encoded
// as code_hash=0 (non-existing account encoding) in the State Circuit.
Word::zero()
} else {
account.code_hash.to_word()
}
}
};
// Verify that the previous value matches the account field value in the StateDB
if op.value_prev != account_value_prev {
panic!(
"RWTable Account field {:?} lookup doesn't match account value
account: {:?}, rwc: {}, op: {:?}",
rw, account, self.block_ctx.rwc.0, op
);
}
// Verify that no read is done to a field other than CodeHash to a non-existing
// account (only CodeHash reads with value=0 can be done to non-existing
// accounts, which the State Circuit translates to MPT
// AccountNonExisting proofs lookups).
if (!matches!(op.field, AccountField::CodeHash)
&& (matches!(rw, RW::READ) || (op.value_prev.is_zero() && op.value.is_zero())))
&& account.is_empty()
{
panic!(
"RWTable Account field {:?} lookup to non-existing account rwc: {}, op: {:?}",
rw, self.block_ctx.rwc.0, op
);
}
// -- sanity check end --
// Perform the write to the account in the StateDB
if matches!(rw, RW::WRITE) {
match op.field {
AccountField::Nonce => account.nonce = op.value.as_u64(),
AccountField::Balance => account.balance = op.value,
AccountField::CodeHash => account.code_hash = H256::from(op.value.to_be_bytes()),
}
}
}
/// Push a read type [`AccountOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter), and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn account_read(
&mut self,
step: &mut ExecStep,
address: Address,
field: AccountField,
value: Word,
) -> Result<(), Error> {
let op = AccountOp::new(address, field, value, value);
self.push_op(step, RW::READ, op)
}
/// Push a write type [`AccountOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter), and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn account_write(
&mut self,
step: &mut ExecStep,
address: Address,
field: AccountField,
value: Word,
value_prev: Word,
reversible: bool,
) -> Result<(), Error> {
let op = AccountOp::new(address, field, value, value_prev);
if reversible {
self.push_op_reversible(step, op)?;
} else {
self.push_op(step, RW::WRITE, op)?;
}
Ok(())
}
/// Push a write type [`TxLogOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter), and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn tx_log_write(
&mut self,
step: &mut ExecStep,
tx_id: usize,
log_id: usize,
field: TxLogField,
index: usize,
value: Word,
) -> Result<(), Error> {
self.push_op(
step,
RW::WRITE,
TxLogOp::new(tx_id, log_id, field, index, value),
)
}
/// Push a read type [`TxReceiptOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter), and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn tx_receipt_read(
&mut self,
step: &mut ExecStep,
tx_id: usize,
field: TxReceiptField,
value: u64,
) -> Result<(), Error> {
self.push_op(
step,
RW::READ,
TxReceiptOp {
tx_id,
field,
value,
},
)
}
/// Push a write type [`TxReceiptOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter), and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn tx_receipt_write(
&mut self,
step: &mut ExecStep,
tx_id: usize,
field: TxReceiptField,
value: u64,
) -> Result<(), Error> {
self.push_op(
step,
RW::WRITE,
TxReceiptOp {
tx_id,
field,
value,
},
)
}
/// Push a write type [`TxAccessListAccountOp`] into the
/// [`OperationContainer`](crate::operation::OperationContainer) with the
/// next [`RWCounter`](crate::operation::RWCounter), and then
/// adds a reference to the stored operation ([`OperationRef`]) inside
/// the bus-mapping instance of the current [`ExecStep`]. Then increase
/// the `block_ctx` [`RWCounter`](crate::operation::RWCounter) by one.
pub fn tx_accesslist_account_write(
&mut self,
step: &mut ExecStep,
tx_id: usize,
address: Address,
is_warm: bool,
is_warm_prev: bool,
) -> Result<(), Error> {
self.push_op(
step,
RW::WRITE,
TxAccessListAccountOp {
tx_id,
address,
is_warm,
is_warm_prev,
},
)
}
/// Add address to access list for the current transaction.
pub fn tx_access_list_write(
&mut self,
step: &mut ExecStep,
address: Address,
) -> Result<(), Error> {
let is_warm = self.sdb.check_account_in_access_list(&address);
self.push_op_reversible(
step,
TxAccessListAccountOp {
tx_id: self.tx_ctx.id(),
address,
is_warm: true,
is_warm_prev: is_warm,
},
)
}
/// Push 2 reversible [`AccountOp`] to update `sender` and `receiver`'s
/// balance by `value`. If `fee` is existing (not None), also need to push 1
/// non-reversible [`AccountOp`] to update `sender` balance by `fee`.
#[allow(clippy::too_many_arguments)]
pub fn transfer(
&mut self,
step: &mut ExecStep,
sender: Address,
receiver: Address,
receiver_exists: bool,
is_create: bool,
value: Word,
fee: Option<Word>,
) -> Result<(), Error> {
let (found, sender_account) = self.sdb.get_account(&sender);
if !found {
return Err(Error::AccountNotFound(sender));
}
let mut sender_balance_prev = sender_account.balance;
debug_assert!(
sender_account.balance >= value + fee.unwrap_or_default(),
"invalid amount balance {:?} value {:?} fee {:?}",
sender_balance_prev,
value,
fee
);
if let Some(fee) = fee {
let sender_balance = sender_balance_prev - fee;
log::trace!(
"sender balance update with fee (not reversible): {:?} {:?}->{:?}",
sender,
sender_balance_prev,
sender_balance
);
self.push_op(
step,
RW::WRITE,
AccountOp {
address: sender,
field: AccountField::Balance,
value: sender_balance,
value_prev: sender_balance_prev,
},
)?;
sender_balance_prev = sender_balance;
}
let sender_balance = sender_balance_prev - value;
log::trace!(
"sender balance update with value: {:?} {:?}->{:?}",
sender,
sender_balance_prev,
sender_balance
);
if !value.is_zero() {
self.push_op_reversible(
step,
AccountOp {
address: sender,
field: AccountField::Balance,
value: sender_balance,
value_prev: sender_balance_prev,
},
)?;
}
self.transfer_to(step, receiver, receiver_exists, is_create, value, true)?;
Ok(())
}
/// Transfer to an address. Create an account if it is not existed before.
pub fn transfer_to(
&mut self,
step: &mut ExecStep,
receiver: Address,
receiver_exists: bool,
is_create: bool,
value: Word,
reversible: bool,
) -> Result<(), Error> {
if !receiver_exists && (!value.is_zero() || is_create) {
self.account_write(
step,
receiver,
AccountField::CodeHash,
CodeDB::empty_code_hash().to_word(),
Word::zero(),
reversible,
)?;
}
if value.is_zero() {
// Skip transfer if value == 0
return Ok(());
}
let (_found, receiver_account) = self.sdb.get_account(&receiver);
let receiver_balance_prev = receiver_account.balance;
let receiver_balance = receiver_account.balance + value;
self.account_write(
step,
receiver,
AccountField::Balance,
receiver_balance,
receiver_balance_prev,
reversible,
)?;
Ok(())
}
/// Fetch and return code for the given code hash from the code DB.
pub fn code(&self, code_hash: H256) -> Result<Vec<u8>, Error> {
self.code_db
.get_from_h256(&code_hash)
.map(|bytecode| bytecode.code())
.ok_or(Error::CodeNotFound(code_hash))
}
/// Reference to the caller's Call
pub fn caller(&self) -> Result<&Call, Error> {
self.tx_ctx
.caller_index()
.map(|caller_idx| &self.tx.calls()[caller_idx])
}
/// Mutable reference to the current call's caller Call
pub fn caller_mut(&mut self) -> Result<&mut Call, Error> {
self.tx_ctx
.caller_index()
.map(|caller_idx| &mut self.tx.calls_mut()[caller_idx])
}
/// Reference to the current Call
pub fn call(&self) -> Result<&Call, Error> {
self.tx_ctx
.call_index()
.map(|call_idx| &self.tx.calls()[call_idx])
}
/// Mutable reference to the current Call
pub fn call_mut(&mut self) -> Result<&mut Call, Error> {
self.tx_ctx
.call_index()
.map(|call_idx| &mut self.tx.calls_mut()[call_idx])
}
/// Reference to the current CallContext
pub fn caller_ctx(&self) -> Result<&CallContext, Error> {
self.tx_ctx.caller_ctx()
}
/// Reference to the current CallContext
pub fn call_ctx(&self) -> Result<&CallContext, Error> {
self.tx_ctx.call_ctx()
}
/// Mutable reference to the call CallContext
pub fn call_ctx_mut(&mut self) -> Result<&mut CallContext, Error> {
self.tx_ctx.call_ctx_mut()
}
/// Mutable reference to the caller CallContext
pub fn caller_ctx_mut(&mut self) -> Result<&mut CallContext, Error> {
self.tx_ctx
.calls
.iter_mut()
.rev()
.nth(1)
.ok_or(Error::InternalError("caller id not found in call map"))
}
/// Push a new [`Call`] into the [`Transaction`], and add its index and
/// [`CallContext`] in the `call_stack` of the [`TransactionContext`]
pub fn push_call(&mut self, call: Call) {
let current_call = self.call_ctx().expect("current call not found");
let call_data = match call.kind {
CallKind::Call | CallKind::CallCode | CallKind::DelegateCall | CallKind::StaticCall => {
current_call
.memory
.read_chunk(call.call_data_offset.into(), call.call_data_length.into())
}
CallKind::Create | CallKind::Create2 => Vec::new(),
};
let call_id = call.call_id;
let call_idx = self.tx.calls().len();
self.tx_ctx.push_call_ctx(call_idx, call_data);
self.tx.push_call(call);
self.block_ctx
.call_map
.insert(call_id, (self.block.txs.len(), call_idx));
}
/// Return the contract address of a CREATE step. This is calculated by
/// inspecting the current address and its nonce from the StateDB.
pub(crate) fn create_address(&self) -> Result<Address, Error> {
let sender = self.call()?.address;
let (found, account) = self.sdb.get_account(&sender);
if !found {
return Err(Error::AccountNotFound(sender));
}
Ok(get_contract_address(sender, account.nonce))
}
/// Return the contract address of a CREATE2 step. This is calculated
/// deterministically from the arguments in the stack.
pub(crate) fn create2_address(&self, step: &GethExecStep) -> Result<Address, Error> {
let salt = step.stack.nth_last(3)?;
let call_ctx = self.call_ctx()?;
let init_code = get_create_init_code(call_ctx, step)?.to_vec();
Ok(get_create2_address(
self.call()?.address,
salt.to_be_bytes(),
init_code,
))
}
/// read reversion info
pub(crate) fn reversion_info_read(
&mut self,
step: &mut ExecStep,
call: &Call,
) -> Result<(), Error> {
for (field, value) in [
(
CallContextField::RwCounterEndOfReversion,
call.rw_counter_end_of_reversion.to_word(),
),
(CallContextField::IsPersistent, call.is_persistent.to_word()),
] {
self.call_context_read(step, call.call_id, field, value)?;
}
Ok(())
}
/// write reversion info
pub(crate) fn reversion_info_write(
&mut self,
step: &mut ExecStep,
call: &Call,
) -> Result<(), Error> {
for (field, value) in [
(
CallContextField::RwCounterEndOfReversion,
call.rw_counter_end_of_reversion.to_word(),
),
(CallContextField::IsPersistent, call.is_persistent.to_word()),
] {
self.call_context_write(step, call.call_id, field, value)?;
}
Ok(())
}
/// Check if address is a precompiled or not.
pub fn is_precompiled(&self, address: &Address) -> bool {
address.0[0..19] == [0u8; 19] && (1..=9).contains(&address.0[19])
}
/// Parse [`Call`] from a *CALL*/CREATE* step.
pub fn parse_call(&mut self, step: &GethExecStep) -> Result<Call, Error> {
let is_success = *self
.tx_ctx
.call_is_success
.get(self.tx.calls().len())
.unwrap();
let kind = CallKind::try_from(step.op)?;
let caller = self.call()?;
let caller_ctx = self.call_ctx()?;
let (caller_address, address, value) = match kind {
CallKind::Call => (
caller.address,
step.stack.nth_last(1)?.to_address(),
step.stack.nth_last(2)?,
),
CallKind::CallCode => (caller.address, caller.address, step.stack.nth_last(2)?),
CallKind::DelegateCall => (caller.caller_address, caller.address, caller.value),
CallKind::StaticCall => (
caller.address,
step.stack.nth_last(1)?.to_address(),
Word::zero(),
),
CallKind::Create => (caller.address, self.create_address()?, step.stack.last()?),
CallKind::Create2 => (
caller.address,
self.create2_address(step)?,
step.stack.last()?,
),
};
let (code_source, code_hash) = match kind {
CallKind::Create | CallKind::Create2 => {
let init_code = get_create_init_code(caller_ctx, step)?.to_vec();
let code_hash = self.code_db.insert(init_code);
(CodeSource::Memory, code_hash)
}
_ => {
let code_address = match kind {
CallKind::CallCode | CallKind::DelegateCall => {
step.stack.nth_last(1)?.to_address()
}
_ => address,
};
let (found, account) = self.sdb.get_account(&code_address);
if !found {
return Err(Error::AccountNotFound(code_address));
}
(CodeSource::Address(code_address), account.code_hash)
}
};
let (call_data_offset, call_data_length, return_data_offset, return_data_length) =
match kind {
CallKind::Call | CallKind::CallCode => {
let call_data = get_call_memory_offset_length(step, 3)?;
let return_data = get_call_memory_offset_length(step, 5)?;
(call_data.0, call_data.1, return_data.0, return_data.1)
}
CallKind::DelegateCall | CallKind::StaticCall => {
let call_data = get_call_memory_offset_length(step, 2)?;
let return_data = get_call_memory_offset_length(step, 4)?;
(call_data.0, call_data.1, return_data.0, return_data.1)
}
CallKind::Create | CallKind::Create2 => (0, 0, 0, 0),
};
let caller = self.call()?;
let call = Call {
call_id: self.block_ctx.rwc.0,
caller_id: caller.call_id,
last_callee_id: 0,
kind,
is_static: kind == CallKind::StaticCall || caller.is_static,
is_root: false,
is_persistent: caller.is_persistent && is_success,
is_success,
rw_counter_end_of_reversion: 0,
caller_address,
address,
code_source,
code_hash,
depth: caller.depth + 1,
value,
call_data_offset,
call_data_length,
return_data_offset,
return_data_length,
last_callee_return_data_offset: 0,
last_callee_return_data_length: 0,
};
Ok(call)
}
/// Return the reverted version of an op by op_ref only if the original op
/// was reversible.
fn get_rev_op_by_ref(&self, op_ref: &OperationRef) -> Option<OpEnum> {
match op_ref {
OperationRef(Target::Storage, idx) => {
let operation = &self.block.container.storage[*idx];
if operation.rw().is_write() && operation.reversible() {
Some(OpEnum::Storage(operation.op().reverse()))
} else {
None
}
}
OperationRef(Target::TxAccessListAccount, idx) => {
let operation = &self.block.container.tx_access_list_account[*idx];
if operation.rw().is_write() && operation.reversible() {
Some(OpEnum::TxAccessListAccount(operation.op().reverse()))
} else {
None
}
}
OperationRef(Target::TxAccessListAccountStorage, idx) => {
let operation = &self.block.container.tx_access_list_account_storage[*idx];
if operation.rw().is_write() && operation.reversible() {
Some(OpEnum::TxAccessListAccountStorage(operation.op().reverse()))
} else {
None
}
}
OperationRef(Target::TxRefund, idx) => {
let operation = &self.block.container.tx_refund[*idx];
if operation.rw().is_write() && operation.reversible() {
Some(OpEnum::TxRefund(operation.op().reverse()))
} else {
None
}
}
OperationRef(Target::Account, idx) => {
let operation = &self.block.container.account[*idx];
if operation.rw().is_write() && operation.reversible() {
Some(OpEnum::Account(operation.op().reverse()))
} else {
None
}
}
_ => None,
}
}
/// Check and apply op to state.
fn check_apply_op(&mut self, op: &OpEnum) {
match &op {
OpEnum::Storage(op) => {
self.sdb.set_storage(&op.address, &op.key, &op.value);
}
OpEnum::TransientStorage(op) => {
self.sdb
.set_transient_storage(&op.address, &op.key, &op.value)
}
OpEnum::TxAccessListAccount(op) => {
if !op.is_warm_prev && op.is_warm {
self.sdb.add_account_to_access_list(op.address);
}
if op.is_warm_prev && !op.is_warm {
self.sdb.remove_account_from_access_list(&op.address);
}
}
OpEnum::TxAccessListAccountStorage(op) => {
if !op.is_warm_prev && op.is_warm {
self.sdb
.add_account_storage_to_access_list((op.address, op.key));
}
if op.is_warm_prev && !op.is_warm {
self.sdb
.remove_account_storage_from_access_list(&(op.address, op.key));
}