referrerpolicy=no-referrer-when-downgrade

pallet_revive/vm/
evm.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17use 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
45/// Hard-coded value returned by the EVM `DIFFICULTY` opcode.
46///
47/// After Ethereum's Merge (Sept 2022), the `DIFFICULTY` opcode was redefined to return
48/// `prevrandao`, a randomness value from the beacon chain. In Substrate pallet-revive
49/// a fixed constant is returned instead for compatibility with contracts that still read this
50/// opcode. The value is aligned with the difficulty hardcoded for PVM contracts.
51pub(crate) const DIFFICULTY: u64 = 2500000000000000_u64;
52
53/// Cost  for a single unit of EVM gas.
54#[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	/// Create a new contract from EVM init code.
66	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		// Code hash is not relevant for init code, since it is not stored on-chain.
89		let code_hash = H256::default();
90		Ok(ContractBlob { code, code_info, code_hash })
91	}
92
93	/// Create a new contract from EVM runtime code.
94	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	/// Create a new contract from EVM runtime code with an explicit owner and
104	/// deposit amount.
105	///
106	/// Used for `Origin::Root` uploads: there is no origin account to attribute
107	/// the deposit to, so the caller passes the pallet's own account as a
108	/// sentinel owner (no user can sign as it, so the code can't be removed via
109	/// the owner-gated path) and a zero deposit (both `charge_deposit` and
110	/// `refund_deposit` short-circuit at amount 0).
111	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		// EIP-3541: reject new contract code (runtime code) starting with the 0xEF byte.
123		// Reserved for EIP-7702 delegation indicators; clashing here would let a
124		// constructor return bytes that subsequent calls would misinterpret as a
125		// delegation pointer.
126		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
151/// Calls the EVM interpreter with the provided bytecode and inputs.
152pub 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}