1use crate::{
18 AccountIdOf, BalanceOf, CodeInfo, Config, ContractBlob, DispatchError, Error, H256, LOG_TARGET,
19 Weight,
20 debug::DebugSettings,
21 precompiles::Token,
22 tracing,
23 vm::{BytecodeType, ExecResult, Ext, evm::instructions::exec_instruction},
24 weights::WeightInfo,
25};
26use alloc::vec::Vec;
27use core::{convert::Infallible, ops::ControlFlow};
28use revm::{bytecode::Bytecode, primitives::Bytes};
29
30#[cfg(feature = "runtime-benchmarks")]
31pub mod instructions;
32#[cfg(not(feature = "runtime-benchmarks"))]
33mod instructions;
34
35mod interpreter;
36pub use interpreter::{Halt, Interpreter};
37
38mod ext_bytecode;
39use ext_bytecode::ExtBytecode;
40
41mod memory;
42mod stack;
43mod util;
44
45pub(crate) const DIFFICULTY: u64 = 2500000000000000_u64;
52
53#[derive(Eq, PartialEq, Debug, Clone, Copy)]
55pub struct EVMGas(pub u64);
56
57impl<T: Config> Token<T> for EVMGas {
58 fn weight(&self) -> Weight {
59 let base_cost = T::WeightInfo::evm_opcode(1).saturating_sub(T::WeightInfo::evm_opcode(0));
60 base_cost.saturating_mul(self.0)
61 }
62}
63
64impl<T: Config> ContractBlob<T> {
65 pub fn from_evm_init_code(code: Vec<u8>, owner: AccountIdOf<T>) -> Result<Self, DispatchError> {
67 if code.len() > revm::primitives::eip3860::MAX_INITCODE_SIZE &&
68 !DebugSettings::is_unlimited_contract_size_allowed::<T>()
69 {
70 return Err(<Error<T>>::BlobTooLarge.into());
71 }
72
73 let code_len = code.len() as u32;
74 let code_info = CodeInfo {
75 owner,
76 deposit: Default::default(),
77 refcount: 0,
78 code_len,
79 code_type: BytecodeType::Evm,
80 behaviour_version: Default::default(),
81 };
82
83 Bytecode::new_raw_checked(Bytes::from(code.to_vec())).map_err(|err| {
84 log::debug!(target: LOG_TARGET, "failed to create evm bytecode from init code: {err:?}" );
85 <Error<T>>::CodeRejected
86 })?;
87
88 let code_hash = H256::default();
90 Ok(ContractBlob { code, code_info, code_hash })
91 }
92
93 pub fn from_evm_runtime_code(
95 code: Vec<u8>,
96 owner: AccountIdOf<T>,
97 ) -> Result<Self, DispatchError> {
98 let code_len = code.len() as u32;
99 let deposit = super::calculate_code_deposit::<T>(code_len);
100 Self::from_evm_runtime_code_with_deposit(code, owner, deposit)
101 }
102
103 pub fn from_evm_runtime_code_with_deposit(
112 code: Vec<u8>,
113 owner: AccountIdOf<T>,
114 deposit: BalanceOf<T>,
115 ) -> Result<Self, DispatchError> {
116 if code.len() > revm::primitives::eip170::MAX_CODE_SIZE &&
117 !DebugSettings::is_unlimited_contract_size_allowed::<T>()
118 {
119 return Err(<Error<T>>::BlobTooLarge.into());
120 }
121
122 if code.first() == Some(&0xEF) {
127 return Err(<Error<T>>::CodeRejected.into());
128 }
129
130 let code_len = code.len() as u32;
131
132 let code_info = CodeInfo {
133 owner,
134 deposit,
135 refcount: 0,
136 code_len,
137 code_type: BytecodeType::Evm,
138 behaviour_version: Default::default(),
139 };
140
141 Bytecode::new_raw_checked(Bytes::from(code.to_vec())).map_err(|err| {
142 log::debug!(target: LOG_TARGET, "failed to create evm bytecode from code: {err:?}" );
143 <Error<T>>::CodeRejected
144 })?;
145
146 let code_hash = H256(sp_io::hashing::keccak_256(&code));
147 Ok(ContractBlob { code, code_info, code_hash })
148 }
149}
150
151pub fn call<E: Ext>(bytecode: Bytecode, ext: &mut E, input: Vec<u8>) -> ExecResult {
153 let mut interpreter = Interpreter::new(ExtBytecode::new(bytecode), input, ext);
154 let tracing_enabled = tracing::if_tracing(|t| t.is_execution_tracer()).unwrap_or(false);
155
156 let ControlFlow::Break(halt) = if tracing_enabled {
157 run_plain_with_tracing(&mut interpreter)
158 } else {
159 run_plain(&mut interpreter)
160 };
161 halt.into()
162}
163
164fn run_plain<E: Ext>(interpreter: &mut Interpreter<E>) -> ControlFlow<Halt, Infallible> {
165 loop {
166 let opcode = interpreter.bytecode.opcode();
167 interpreter.bytecode.relative_jump(1);
168 exec_instruction(interpreter, opcode)?;
169 }
170}
171
172fn run_plain_with_tracing<E: Ext>(
173 interpreter: &mut Interpreter<E>,
174) -> ControlFlow<Halt, Infallible> {
175 loop {
176 let opcode = interpreter.bytecode.opcode();
177 tracing::if_tracing(|tracer| {
178 let pc = interpreter.bytecode.pc() as u64;
179 tracer.enter_opcode(pc, opcode, interpreter)
180 });
181
182 interpreter.bytecode.relative_jump(1);
183 let res = exec_instruction(interpreter, opcode);
184
185 tracing::if_tracing(|tracer| tracer.exit_step(interpreter, None));
186
187 res?;
188 }
189}