This repository was archived by the owner on Oct 11, 2024. It is now read-only.
forked from bluealloy/revm
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathevm_impl.rs
More file actions
1266 lines (1145 loc) · 43.6 KB
/
evm_impl.rs
File metadata and controls
1266 lines (1145 loc) · 43.6 KB
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 crate::interpreter::{
analysis::to_analysed, gas, instruction_result::SuccessOrHalt, return_ok, return_revert,
CallContext, CallInputs, CallScheme, Contract, CreateInputs, CreateScheme, Gas, Host,
InstructionResult, Interpreter, SelfDestructResult, Transfer, CALL_STACK_LIMIT,
};
use crate::journaled_state::{is_precompile, JournalCheckpoint};
use crate::primitives::{
create2_address, create_address, keccak256, Account, AnalysisKind, Bytecode, Bytes, EVMError,
EVMResult, Env, ExecutionResult, HashMap, InvalidTransaction, Log, Output, ResultAndState,
Spec,
SpecId::{self, *},
TransactTo, B160, B256, U256,
};
use crate::{db::Database, journaled_state::JournaledState, precompile, Inspector};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::{cmp::min, marker::PhantomData};
use revm_interpreter::gas::initial_tx_gas;
use revm_interpreter::MAX_CODE_SIZE;
use revm_precompile::{Precompile, Precompiles};
#[cfg(feature = "optimism")]
use crate::optimism;
#[cfg(feature = "optimism")]
use core::ops::Mul;
pub struct EVMData<'a, DB: Database> {
pub env: &'a mut Env,
pub journaled_state: JournaledState,
pub db: &'a mut DB,
pub error: Option<DB::Error>,
pub precompiles: Precompiles,
}
pub struct EVMImpl<'a, GSPEC: Spec, DB: Database, const INSPECT: bool> {
data: EVMData<'a, DB>,
inspector: &'a mut dyn Inspector<DB>,
_phantomdata: PhantomData<GSPEC>,
}
struct PreparedCreate {
gas: Gas,
created_address: B160,
checkpoint: JournalCheckpoint,
contract: Box<Contract>,
}
struct CreateResult {
result: InstructionResult,
created_address: Option<B160>,
gas: Gas,
return_value: Bytes,
}
struct PreparedCall {
gas: Gas,
checkpoint: JournalCheckpoint,
contract: Box<Contract>,
}
struct CallResult {
result: InstructionResult,
gas: Gas,
return_value: Bytes,
}
pub trait Transact<DBError> {
/// Do checks that could make transaction fail before call/create
fn preverify_transaction(&mut self) -> Result<(), EVMError<DBError>>;
/// Skip preverification steps and do transaction
fn transact_preverified(&mut self) -> EVMResult<DBError>;
/// Do transaction.
/// InstructionResult InstructionResult, Output for call or Address if we are creating
/// contract, gas spend, gas refunded, State that needs to be applied.
fn transact(&mut self) -> EVMResult<DBError>;
}
impl<'a, GSPEC: Spec, DB: Database, const INSPECT: bool> EVMImpl<'a, GSPEC, DB, INSPECT> {
/// Load access list for berlin hardfork.
///
/// Loading of accounts/storages is needed to make them hot.
#[inline]
fn load_access_list(&mut self) -> Result<(), EVMError<DB::Error>> {
for (address, slots) in self.data.env.tx.access_list.iter() {
self.data
.journaled_state
.initial_account_load(*address, slots, self.data.db)
.map_err(EVMError::Database)?;
}
Ok(())
}
/// If the transaction is not a deposit transaction, subtract the L1 data fee from the
/// caller's balance directly after minting the requested amount of ETH.
#[cfg(feature = "optimism")]
fn remove_l1_cost(
is_deposit: bool,
tx_caller: B160,
l1_cost: U256,
db: &mut DB,
journal: &mut JournaledState,
) -> Result<(), EVMError<DB::Error>> {
if is_deposit {
return Ok(());
}
let acc = journal
.load_account(tx_caller, db)
.map_err(EVMError::Database)?
.0;
if l1_cost.gt(&acc.info.balance) {
let u64_cost = if U256::from(u64::MAX).lt(&l1_cost) {
u64::MAX
} else {
l1_cost.as_limbs()[0]
};
return Err(EVMError::Transaction(
InvalidTransaction::LackOfFundForMaxFee {
fee: u64_cost,
balance: acc.info.balance,
},
));
}
acc.info.balance = acc.info.balance.saturating_sub(l1_cost);
Ok(())
}
/// If the transaction is a deposit with a `mint` value, add the mint value
/// in wei to the caller's balance. This should be persisted to the database
/// prior to the rest of execution.
#[cfg(feature = "optimism")]
fn commit_mint_value(
tx_caller: B160,
tx_mint: Option<u128>,
db: &mut DB,
journal: &mut JournaledState,
) -> Result<(), EVMError<DB::Error>> {
if let Some(mint) = tx_mint {
journal
.load_account(tx_caller, db)
.map_err(EVMError::Database)?
.0
.info
.balance += U256::from(mint);
journal.checkpoint();
}
Ok(())
}
}
impl<'a, GSPEC: Spec, DB: Database, const INSPECT: bool> Transact<DB::Error>
for EVMImpl<'a, GSPEC, DB, INSPECT>
{
fn preverify_transaction(&mut self) -> Result<(), EVMError<DB::Error>> {
let env = self.env();
env.validate_block_env::<GSPEC, DB::Error>()?;
env.validate_tx::<GSPEC>()?;
let tx_caller = env.tx.caller;
let tx_data = &env.tx.data;
let tx_is_create = env.tx.transact_to.is_create();
let initial_gas_spend = initial_tx_gas::<GSPEC>(tx_data, tx_is_create, &env.tx.access_list);
// Additonal check to see if limit is big enought to cover initial gas.
if env.tx.gas_limit < initial_gas_spend {
return Err(InvalidTransaction::CallGasCostMoreThanGasLimit.into());
}
// load acc
let journal = &mut self.data.journaled_state;
let (caller_account, _) = journal
.load_account(tx_caller, self.data.db)
.map_err(EVMError::Database)?;
self.data.env.validate_tx_against_state(caller_account)?;
Ok(())
}
fn transact_preverified(&mut self) -> EVMResult<DB::Error> {
let env = &self.data.env;
let tx_caller = env.tx.caller;
let tx_value = env.tx.value;
let tx_data = env.tx.data.clone();
let tx_gas_limit = env.tx.gas_limit;
let tx_is_create = env.tx.transact_to.is_create();
let effective_gas_price = env.effective_gas_price();
#[cfg(feature = "optimism")]
let (tx_mint, tx_system, tx_l1_cost, is_deposit, l1_block_info) = {
let is_deposit = env.tx.optimism.source_hash.is_some();
let l1_block_info =
optimism::L1BlockInfo::try_fetch(self.data.db, self.data.env.cfg.optimism)
.map_err(EVMError::Database)?;
// Perform this calculation optimistically to avoid cloning the enveloped tx.
let tx_l1_cost = l1_block_info.as_ref().map(|l1_block_info| {
l1_block_info
.calculate_tx_l1_cost::<GSPEC>(&env.tx.optimism.enveloped_tx, is_deposit)
});
(
env.tx.optimism.mint,
env.tx.optimism.is_system_transaction,
tx_l1_cost,
is_deposit,
l1_block_info,
)
};
let initial_gas_spend =
initial_tx_gas::<GSPEC>(&tx_data, tx_is_create, &env.tx.access_list);
// load coinbase
// EIP-3651: Warm COINBASE. Starts the `COINBASE` address warm
if GSPEC::enabled(SHANGHAI) {
self.data
.journaled_state
.initial_account_load(self.data.env.block.coinbase, &[], self.data.db)
.map_err(EVMError::Database)?;
}
self.load_access_list()?;
// load acc
let journal = &mut self.data.journaled_state;
#[cfg(feature = "optimism")]
if self.data.env.cfg.optimism {
EVMImpl::<GSPEC, DB, INSPECT>::commit_mint_value(
tx_caller,
tx_mint,
self.data.db,
journal,
)?;
let Some(tx_l1_cost) = tx_l1_cost else {
panic!("[OPTIMISM] L1 Block Info could not be loaded from the DB.")
};
EVMImpl::<GSPEC, DB, INSPECT>::remove_l1_cost(
is_deposit,
tx_caller,
tx_l1_cost,
self.data.db,
journal,
)?;
}
let (caller_account, _) = journal
.load_account(tx_caller, self.data.db)
.map_err(EVMError::Database)?;
// Reduce gas_limit*gas_price amount of caller account.
// unwrap_or can only occur if disable_balance_check is enabled
caller_account.info.balance = caller_account
.info
.balance
.checked_sub(U256::from(tx_gas_limit).saturating_mul(effective_gas_price))
.unwrap_or(U256::ZERO);
// touch account so we know it is changed.
caller_account.mark_touch();
let transact_gas_limit = tx_gas_limit - initial_gas_spend;
// call inner handling of call/create
let (exit_reason, ret_gas, output) = match self.data.env.tx.transact_to {
TransactTo::Call(address) => {
// Nonce is already checked
caller_account.info.nonce =
caller_account.info.nonce.checked_add(1).unwrap_or(u64::MAX);
let (exit, gas, bytes) = self.call(&mut CallInputs {
contract: address,
transfer: Transfer {
source: tx_caller,
target: address,
value: tx_value,
},
input: tx_data,
gas_limit: transact_gas_limit,
context: CallContext {
caller: tx_caller,
address,
code_address: address,
apparent_value: tx_value,
scheme: CallScheme::Call,
},
is_static: false,
});
(exit, gas, Output::Call(bytes))
}
TransactTo::Create(scheme) => {
let (exit, address, ret_gas, bytes) = self.create(&mut CreateInputs {
caller: tx_caller,
scheme,
value: tx_value,
init_code: tx_data,
gas_limit: transact_gas_limit,
});
(exit, ret_gas, Output::Create(bytes, address))
}
};
// Spend the gas limit. Gas is reimbursed when the tx returns successfully.
let mut gas = Gas::new(tx_gas_limit);
gas.record_cost(tx_gas_limit);
if crate::USE_GAS {
match exit_reason {
return_ok!() => {
#[cfg(not(feature = "optimism"))]
gas.consume_gas(ret_gas);
#[cfg(feature = "optimism")]
gas.consume_gas(
self.data.env.cfg.optimism,
is_deposit,
GSPEC::enabled(SpecId::REGOLITH),
tx_system,
tx_gas_limit,
ret_gas,
);
}
return_revert!() => {
#[cfg(not(feature = "optimism"))]
gas.consume_revert_gas(ret_gas);
#[cfg(feature = "optimism")]
gas.consume_revert_gas(
self.data.env.cfg.optimism,
is_deposit,
GSPEC::enabled(SpecId::REGOLITH),
ret_gas,
);
}
_ => {}
}
}
let (state, logs, gas_used, gas_refunded) = self.finalize::<GSPEC>(
&gas,
#[cfg(feature = "optimism")]
l1_block_info.as_ref(),
);
let result = match exit_reason.into() {
SuccessOrHalt::Success(reason) => ExecutionResult::Success {
reason,
gas_used,
gas_refunded,
logs,
output,
},
SuccessOrHalt::Revert => ExecutionResult::Revert {
gas_used,
output: match output {
Output::Call(return_value) => return_value,
Output::Create(return_value, _) => return_value,
},
},
SuccessOrHalt::Halt(reason) => {
// Post-regolith, if the transaction is a deposit transaction and the
// output is a contract creation, increment the account nonce even if
// the transaction halts.
#[cfg(feature = "optimism")]
{
let is_creation = matches!(output, Output::Create(_, _));
let regolith_enabled = GSPEC::enabled(SpecId::REGOLITH);
let optimism_regolith = self.data.env.cfg.optimism && regolith_enabled;
if is_deposit && is_creation && optimism_regolith {
let (acc, _) = self
.data
.journaled_state
.load_account(tx_caller, self.data.db)
.map_err(EVMError::Database)?;
acc.info.nonce = acc.info.nonce.checked_add(1).unwrap_or(u64::MAX);
}
}
ExecutionResult::Halt { reason, gas_used }
}
SuccessOrHalt::FatalExternalError => {
return Err(EVMError::Database(self.data.error.take().unwrap()));
}
SuccessOrHalt::InternalContinue => {
panic!("Internal return flags should remain internal {exit_reason:?}")
}
};
Ok(ResultAndState { result, state })
}
fn transact(&mut self) -> EVMResult<DB::Error> {
self.preverify_transaction()
.and_then(|_| self.transact_preverified())
}
}
impl<'a, GSPEC: Spec, DB: Database, const INSPECT: bool> EVMImpl<'a, GSPEC, DB, INSPECT> {
pub fn new(
db: &'a mut DB,
env: &'a mut Env,
inspector: &'a mut dyn Inspector<DB>,
precompiles: Precompiles,
) -> Self {
let journaled_state = if GSPEC::enabled(SpecId::SPURIOUS_DRAGON) {
JournaledState::new(precompiles.len())
} else {
JournaledState::new_legacy(precompiles.len())
};
Self {
data: EVMData {
env,
journaled_state,
db,
error: None,
precompiles,
},
inspector,
_phantomdata: PhantomData {},
}
}
fn finalize<SPEC: Spec>(
&mut self,
gas: &Gas,
#[cfg(feature = "optimism")] l1_block_info: Option<&optimism::L1BlockInfo>,
) -> (HashMap<B160, Account>, Vec<Log>, u64, u64) {
let caller = self.data.env.tx.caller;
let coinbase = self.data.env.block.coinbase;
let (gas_used, gas_refunded) = if crate::USE_GAS {
let effective_gas_price = self.data.env.effective_gas_price();
let basefee = self.data.env.block.basefee;
let is_gas_refund_disabled = self.data.env.cfg.is_gas_refund_disabled();
#[cfg(feature = "optimism")]
let is_deposit =
self.data.env.cfg.optimism && self.data.env.tx.optimism.source_hash.is_some();
// Prior to Regolith, deposit transactions did not receive gas refunds.
#[cfg(feature = "optimism")]
let is_gas_refund_disabled = is_gas_refund_disabled
|| (self.data.env.cfg.optimism && is_deposit && !SPEC::enabled(SpecId::REGOLITH));
let gas_refunded = if is_gas_refund_disabled {
0
} else {
// EIP-3529: Reduction in refunds
let max_refund_quotient = if SPEC::enabled(LONDON) { 5 } else { 2 };
min(gas.refunded() as u64, gas.spend() / max_refund_quotient)
};
// return balance of not spend gas.
let Ok((caller_account, _)) =
self.data.journaled_state.load_account(caller, self.data.db)
else {
panic!("caller account not found");
};
caller_account.info.balance = caller_account
.info
.balance
.saturating_add(effective_gas_price * U256::from(gas.remaining() + gas_refunded));
let disable_coinbase_tip = self.data.env.cfg.disable_coinbase_tip;
// All deposit transactions skip the coinbase tip in favor of paying the
// various fee vaults.
#[cfg(feature = "optimism")]
let disable_coinbase_tip =
disable_coinbase_tip || (self.data.env.cfg.optimism && is_deposit);
// transfer fee to coinbase/beneficiary.
if !disable_coinbase_tip {
// EIP-1559 discard basefee for coinbase transfer. Basefee amount of gas is discarded.
let coinbase_gas_price = if SPEC::enabled(LONDON) {
effective_gas_price.saturating_sub(basefee)
} else {
effective_gas_price
};
let Ok((coinbase_account, _)) = self
.data
.journaled_state
.load_account(coinbase, self.data.db)
else {
panic!("coinbase account not found");
};
coinbase_account.mark_touch();
coinbase_account.info.balance = coinbase_account
.info
.balance
.saturating_add(coinbase_gas_price * U256::from(gas.spend() - gas_refunded));
}
#[cfg(feature = "optimism")]
if self.data.env.cfg.optimism && !is_deposit {
// If the transaction is not a deposit transaction, fees are paid out
// to both the Base Fee Vault as well as the L1 Fee Vault.
let Some(l1_block_info) = l1_block_info else {
panic!("[OPTIMISM] Failed to load L1 block information.");
};
let l1_cost = l1_block_info.calculate_tx_l1_cost::<SPEC>(
&self.data.env.tx.optimism.enveloped_tx,
is_deposit,
);
// Send the L1 cost of the transaction to the L1 Fee Vault.
let Ok((l1_fee_vault_account, _)) = self
.data
.journaled_state
.load_account(optimism::L1_FEE_RECIPIENT, self.data.db)
else {
panic!("[OPTIMISM] Failed to load L1 Fee Vault account");
};
l1_fee_vault_account.mark_touch();
l1_fee_vault_account.info.balance += l1_cost;
// Send the base fee of the transaction to the Base Fee Vault.
let Ok((base_fee_vault_account, _)) = self
.data
.journaled_state
.load_account(optimism::BASE_FEE_RECIPIENT, self.data.db)
else {
panic!("[OPTIMISM] Failed to load Base Fee Vault account");
};
base_fee_vault_account.mark_touch();
base_fee_vault_account.info.balance +=
l1_block_info.l1_base_fee.mul(U256::from(gas.spend()));
}
(gas.spend() - gas_refunded, gas_refunded)
} else {
// touch coinbase
let _ = self
.data
.journaled_state
.load_account(coinbase, self.data.db);
self.data.journaled_state.touch(&coinbase);
(0, 0)
};
let (new_state, logs) = self.data.journaled_state.finalize();
(new_state, logs, gas_used, gas_refunded)
}
fn prepare_create(&mut self, inputs: &CreateInputs) -> Result<PreparedCreate, CreateResult> {
let gas = Gas::new(inputs.gas_limit);
// Check depth of calls
if self.data.journaled_state.depth() > CALL_STACK_LIMIT {
return Err(CreateResult {
result: InstructionResult::CallTooDeep,
created_address: None,
gas,
return_value: Bytes::new(),
});
}
// Fetch balance of caller.
let Some((caller_balance, _)) = self.balance(inputs.caller) else {
return Err(CreateResult {
result: InstructionResult::FatalExternalError,
created_address: None,
gas,
return_value: Bytes::new(),
});
};
// Check if caller has enough balance to send to the crated contract.
if caller_balance < inputs.value {
return Err(CreateResult {
result: InstructionResult::OutOfFund,
created_address: None,
gas,
return_value: Bytes::new(),
});
}
// Increase nonce of caller and check if it overflows
let old_nonce;
if let Some(nonce) = self.data.journaled_state.inc_nonce(inputs.caller) {
old_nonce = nonce - 1;
} else {
return Err(CreateResult {
result: InstructionResult::Return,
created_address: None,
gas,
return_value: Bytes::new(),
});
}
// Create address
let code_hash = keccak256(&inputs.init_code);
let created_address = match inputs.scheme {
CreateScheme::Create => create_address(inputs.caller, old_nonce),
CreateScheme::Create2 { salt } => create2_address(inputs.caller, code_hash, salt),
};
// Load account so it needs to be marked as hot for access list.
if self
.data
.journaled_state
.load_account(created_address, self.data.db)
.map_err(|e| self.data.error = Some(e))
.is_err()
{
return Err(CreateResult {
result: InstructionResult::FatalExternalError,
created_address: None,
gas,
return_value: Bytes::new(),
});
}
// create account, transfer funds and make the journal checkpoint.
let checkpoint = match self
.data
.journaled_state
.create_account_checkpoint::<GSPEC>(inputs.caller, created_address, inputs.value)
{
Ok(checkpoint) => checkpoint,
Err(e) => {
return Err(CreateResult {
result: e,
created_address: None,
gas,
return_value: Bytes::new(),
});
}
};
let bytecode = Bytecode::new_raw(inputs.init_code.clone());
let contract = Box::new(Contract::new(
Bytes::new(),
bytecode,
code_hash,
created_address,
inputs.caller,
inputs.value,
));
Ok(PreparedCreate {
gas,
created_address,
checkpoint,
contract,
})
}
/// EVM create opcode for both initial crate and CREATE and CREATE2 opcodes.
fn create_inner(&mut self, inputs: &CreateInputs) -> CreateResult {
// Prepare crate.
let prepared_create = match self.prepare_create(inputs) {
Ok(o) => o,
Err(e) => return e,
};
// Create new interpreter and execute initcode
let (exit_reason, mut interpreter) =
self.run_interpreter(prepared_create.contract, prepared_create.gas.limit(), false);
// Host error if present on execution
match exit_reason {
return_ok!() => {
// if ok, check contract creation limit and calculate gas deduction on output len.
let mut bytes = interpreter.return_value();
// EIP-3541: Reject new contract code starting with the 0xEF byte
if GSPEC::enabled(LONDON) && !bytes.is_empty() && bytes.first() == Some(&0xEF) {
self.data
.journaled_state
.checkpoint_revert(prepared_create.checkpoint);
return CreateResult {
result: InstructionResult::CreateContractStartingWithEF,
created_address: Some(prepared_create.created_address),
gas: interpreter.gas,
return_value: bytes,
};
}
// EIP-170: Contract code size limit
// By default limit is 0x6000 (~25kb)
if GSPEC::enabled(SPURIOUS_DRAGON)
&& bytes.len()
> self
.data
.env
.cfg
.limit_contract_code_size
.unwrap_or(MAX_CODE_SIZE)
{
self.data
.journaled_state
.checkpoint_revert(prepared_create.checkpoint);
return CreateResult {
result: InstructionResult::CreateContractSizeLimit,
created_address: Some(prepared_create.created_address),
gas: interpreter.gas,
return_value: bytes,
};
}
if crate::USE_GAS {
let gas_for_code = bytes.len() as u64 * gas::CODEDEPOSIT;
if !interpreter.gas.record_cost(gas_for_code) {
// record code deposit gas cost and check if we are out of gas.
// EIP-2 point 3: If contract creation does not have enough gas to pay for the
// final gas fee for adding the contract code to the state, the contract
// creation fails (i.e. goes out-of-gas) rather than leaving an empty contract.
if GSPEC::enabled(HOMESTEAD) {
self.data
.journaled_state
.checkpoint_revert(prepared_create.checkpoint);
return CreateResult {
result: InstructionResult::OutOfGas,
created_address: Some(prepared_create.created_address),
gas: interpreter.gas,
return_value: bytes,
};
} else {
bytes = Bytes::new();
}
}
}
// if we have enough gas
self.data.journaled_state.checkpoint_commit();
// Do analysis of bytecode straight away.
let bytecode = match self.data.env.cfg.perf_analyse_created_bytecodes {
AnalysisKind::Raw => Bytecode::new_raw(bytes.clone()),
AnalysisKind::Check => Bytecode::new_raw(bytes.clone()).to_checked(),
AnalysisKind::Analyse => to_analysed(Bytecode::new_raw(bytes.clone())),
};
self.data
.journaled_state
.set_code(prepared_create.created_address, bytecode);
CreateResult {
result: InstructionResult::Return,
created_address: Some(prepared_create.created_address),
gas: interpreter.gas,
return_value: bytes,
}
}
_ => {
self.data
.journaled_state
.checkpoint_revert(prepared_create.checkpoint);
CreateResult {
result: exit_reason,
created_address: Some(prepared_create.created_address),
gas: interpreter.gas,
return_value: interpreter.return_value(),
}
}
}
}
/// Create a Interpreter and run it.
/// Returns the exit reason and created interpreter as it contains return values and gas spend.
pub fn run_interpreter(
&mut self,
contract: Box<Contract>,
gas_limit: u64,
is_static: bool,
) -> (InstructionResult, Box<Interpreter>) {
// Create inspector
#[cfg(feature = "memory_limit")]
let mut interpreter = Box::new(Interpreter::new_with_memory_limit(
contract,
gas_limit,
is_static,
self.data.env.cfg.memory_limit,
));
#[cfg(not(feature = "memory_limit"))]
let mut interpreter = Box::new(Interpreter::new(contract, gas_limit, is_static));
if INSPECT {
self.inspector
.initialize_interp(&mut interpreter, &mut self.data);
}
let exit_reason = if INSPECT {
interpreter.run_inspect::<Self, GSPEC>(self)
} else {
interpreter.run::<Self, GSPEC>(self)
};
(exit_reason, interpreter)
}
/// Call precompile contract
fn call_precompile(&mut self, inputs: &CallInputs, mut gas: Gas) -> CallResult {
let input_data = &inputs.input;
let contract = inputs.contract;
let precompile = self
.data
.precompiles
.get(&contract)
.expect("Check for precompile should be already done");
let out = match precompile {
Precompile::Standard(fun) => fun(input_data, gas.limit()),
Precompile::Custom(fun) => fun(input_data, gas.limit()),
};
match out {
Ok((gas_used, data)) => {
if !crate::USE_GAS || gas.record_cost(gas_used) {
CallResult {
result: InstructionResult::Return,
gas,
return_value: Bytes::from(data),
}
} else {
CallResult {
result: InstructionResult::PrecompileOOG,
gas,
return_value: Bytes::new(),
}
}
}
Err(e) => {
let result = if precompile::Error::OutOfGas == e {
InstructionResult::PrecompileOOG
} else {
InstructionResult::PrecompileError
};
CallResult {
result,
gas,
return_value: Bytes::new(),
}
}
}
}
fn prepare_call(&mut self, inputs: &CallInputs) -> Result<PreparedCall, CallResult> {
let gas = Gas::new(inputs.gas_limit);
let account = match self
.data
.journaled_state
.load_code(inputs.contract, self.data.db)
{
Ok((account, _)) => account,
Err(e) => {
self.data.error = Some(e);
return Err(CallResult {
result: InstructionResult::FatalExternalError,
gas,
return_value: Bytes::new(),
});
}
};
let code_hash = account.info.code_hash();
let bytecode = account.info.code.clone().unwrap_or_default();
// Check depth
if self.data.journaled_state.depth() > CALL_STACK_LIMIT {
return Err(CallResult {
result: InstructionResult::CallTooDeep,
gas,
return_value: Bytes::new(),
});
}
// Create subroutine checkpoint
let checkpoint = self.data.journaled_state.checkpoint();
// Touch address. For "EIP-158 State Clear", this will erase empty accounts.
if inputs.transfer.value == U256::ZERO {
self.load_account(inputs.context.address);
self.data.journaled_state.touch(&inputs.context.address);
}
// Transfer value from caller to called account
if let Err(e) = self.data.journaled_state.transfer(
&inputs.transfer.source,
&inputs.transfer.target,
inputs.transfer.value,
self.data.db,
) {
self.data.journaled_state.checkpoint_revert(checkpoint);
return Err(CallResult {
result: e,
gas,
return_value: Bytes::new(),
});
}
let contract = Box::new(Contract::new_with_context(
inputs.input.clone(),
bytecode,
code_hash,
&inputs.context,
));
Ok(PreparedCall {
gas,
checkpoint,
contract,
})
}
/// Main contract call of the EVM.
fn call_inner(&mut self, inputs: &CallInputs) -> CallResult {
// Prepare call
let prepared_call = match self.prepare_call(inputs) {
Ok(o) => o,
Err(e) => return e,
};
let ret = if is_precompile(inputs.contract, self.data.precompiles.len()) {
self.call_precompile(inputs, prepared_call.gas)
} else if !prepared_call.contract.bytecode.is_empty() {
// Create interpreter and execute subcall
let (exit_reason, interpreter) = self.run_interpreter(
prepared_call.contract,
prepared_call.gas.limit(),
inputs.is_static,
);
CallResult {
result: exit_reason,
gas: interpreter.gas,
return_value: interpreter.return_value(),
}
} else {
CallResult {
result: InstructionResult::Stop,
gas: prepared_call.gas,
return_value: Bytes::new(),
}
};
// revert changes or not.
if matches!(ret.result, return_ok!()) {
self.data.journaled_state.checkpoint_commit();
} else {
self.data
.journaled_state
.checkpoint_revert(prepared_call.checkpoint);
}
ret
}
}
impl<'a, GSPEC: Spec, DB: Database + 'a, const INSPECT: bool> Host
for EVMImpl<'a, GSPEC, DB, INSPECT>
{
fn step(&mut self, interp: &mut Interpreter) -> InstructionResult {
self.inspector.step(interp, &mut self.data)
}
fn step_end(&mut self, interp: &mut Interpreter, ret: InstructionResult) -> InstructionResult {
self.inspector.step_end(interp, &mut self.data, ret)
}
fn env(&mut self) -> &mut Env {
self.data.env
}
fn block_hash(&mut self, number: U256) -> Option<B256> {
self.data
.db
.block_hash(number)
.map_err(|e| self.data.error = Some(e))
.ok()
}
fn load_account(&mut self, address: B160) -> Option<(bool, bool)> {
self.data
.journaled_state
.load_account_exist(address, self.data.db)
.map_err(|e| self.data.error = Some(e))
.ok()
}
fn balance(&mut self, address: B160) -> Option<(U256, bool)> {
let db = &mut self.data.db;
let journal = &mut self.data.journaled_state;
let error = &mut self.data.error;
journal
.load_account(address, db)
.map_err(|e| *error = Some(e))
.ok()
.map(|(acc, is_cold)| (acc.info.balance, is_cold))
}
fn code(&mut self, address: B160) -> Option<(Bytecode, bool)> {
let journal = &mut self.data.journaled_state;
let db = &mut self.data.db;
let error = &mut self.data.error;
let (acc, is_cold) = journal
.load_code(address, db)
.map_err(|e| *error = Some(e))
.ok()?;
Some((acc.info.code.clone().unwrap(), is_cold))
}