referrerpolicy=no-referrer-when-downgrade

pallet_revive/vm/
mod.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.
17
18//! This module provides a means for executing contracts
19//! represented in vm bytecode.
20
21pub mod evm;
22pub mod pvm;
23mod runtime_costs;
24
25#[cfg(feature = "runtime-benchmarks")]
26pub use runtime_costs::BENCH_MIN_EVM_INIT_CODE_LEN;
27pub use runtime_costs::{RuntimeCosts, StorageAccessKind};
28
29use crate::{
30	AccountIdOf, BalanceOf, CodeInfoOf, CodeRemoved, Config, Error, ExecConfig, ExecError,
31	HoldReason, LOG_TARGET, Pallet, PristineCode, StorageDeposit, Weight, deposit_payment,
32	exec::{ExecResult, Executable, ExportedFunction, Ext},
33	frame_support::ensure,
34	metering::{ResourceMeter, State, Token, slope},
35	weights::WeightInfo,
36};
37use alloc::vec::Vec;
38use codec::{Decode, Encode, MaxEncodedLen};
39use frame_support::dispatch::DispatchResult;
40use pallet_revive_uapi::ReturnErrorCode;
41use sp_core::{Get, H256};
42use sp_runtime::{DispatchError, Saturating, traits::BadOrigin};
43
44/// Validated Vm module ready for execution.
45/// This data structure is immutable once created and stored.
46#[derive(Encode, Decode, scale_info::TypeInfo)]
47#[codec(mel_bound())]
48#[scale_info(skip_type_params(T))]
49pub struct ContractBlob<T: Config> {
50	code: Vec<u8>,
51	// This isn't needed for contract execution and is not stored alongside it.
52	#[codec(skip)]
53	code_info: CodeInfo<T>,
54	// This is for not calculating the hash every time we need it.
55	#[codec(skip)]
56	code_hash: H256,
57}
58
59#[derive(
60	PartialEq, Eq, Debug, Copy, Clone, Encode, Decode, MaxEncodedLen, scale_info::TypeInfo,
61)]
62pub enum BytecodeType {
63	/// The code is a PVM bytecode.
64	Pvm,
65	/// The code is an EVM bytecode.
66	Evm,
67}
68
69/// Contract code related data, such as:
70///
71/// - owner of the contract, i.e. account uploaded its code,
72/// - storage deposit amount,
73/// - reference count,
74///
75/// It is stored in a separate storage entry to avoid loading the code when not necessary.
76#[derive(
77	frame_support::DebugNoBound, Clone, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen,
78)]
79#[codec(mel_bound())]
80#[scale_info(skip_type_params(T))]
81pub struct CodeInfo<T: Config> {
82	/// The account that has uploaded the contract code and hence is allowed to remove it.
83	owner: AccountIdOf<T>,
84	/// The amount of balance that was deposited by the owner in order to store it on-chain.
85	#[codec(compact)]
86	deposit: BalanceOf<T>,
87	/// The number of instantiated contracts that use this as their code.
88	#[codec(compact)]
89	refcount: u64,
90	/// Length of the code in bytes.
91	code_len: u32,
92	/// Bytecode type
93	code_type: BytecodeType,
94	/// The behaviour version that this contract operates under.
95	///
96	/// Whenever any observeable change (with the exception of weights) are made we need
97	/// to make sure that already deployed contracts will not be affected. We do this by
98	/// exposing the old behaviour depending on the set behaviour version of the contract.
99	///
100	/// As of right now this is a reserved field that is always set to 0.
101	behaviour_version: u32,
102}
103
104/// Calculate the deposit required for storing code and its metadata.
105pub fn calculate_code_deposit<T: Config>(code_len: u32) -> BalanceOf<T> {
106	let bytes_added = code_len.saturating_add(<CodeInfo<T>>::max_encoded_len() as u32);
107	T::DepositPerByte::get()
108		.saturating_mul(bytes_added.into())
109		.saturating_add(T::DepositPerItem::get().saturating_mul(2u32.into()))
110}
111
112impl ExportedFunction {
113	/// The vm export name for the function.
114	fn identifier(&self) -> &str {
115		match self {
116			Self::Constructor => "deploy",
117			Self::Call => "call",
118		}
119	}
120}
121
122/// Cost of code loading from storage.
123///
124/// It is charged to the caller: the calling frame, or the transaction for the first frame. For
125/// PVM code it is the slope of `call_with_pvm_code_per_byte` per blob byte, which includes the
126/// callee's first allocation of the interpreter's map of compiled blocks. The interpreter charges
127/// that allocation as gas, and the callee's instance starts with a gas credit of the same size
128/// (see `ContractBlob::prepare_call`).
129#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
130#[derive(Clone, Copy)]
131struct CodeLoadToken {
132	code_len: u32,
133	code_type: BytecodeType,
134}
135
136impl CodeLoadToken {
137	fn from_code_info<T: Config>(code_info: &CodeInfo<T>) -> Self {
138		Self { code_len: code_info.code_len, code_type: code_info.code_type }
139	}
140}
141
142impl<T: Config> Token<T> for CodeLoadToken {
143	fn weight(&self) -> Weight {
144		match self.code_type {
145			BytecodeType::Pvm => slope(T::WeightInfo::call_with_pvm_code_per_byte, self.code_len),
146			BytecodeType::Evm => slope(T::WeightInfo::call_with_evm_code_per_byte, self.code_len),
147		}
148	}
149}
150
151#[cfg(test)]
152pub fn code_load_weight(code_len: u32) -> Weight {
153	Token::<crate::tests::Test>::weight(&CodeLoadToken { code_len, code_type: BytecodeType::Pvm })
154}
155
156impl<T: Config> ContractBlob<T> {
157	/// Remove the code from storage and refund the deposit to its owner.
158	///
159	/// Applies all necessary checks before removing the code.
160	pub fn remove(origin: &T::AccountId, code_hash: H256) -> DispatchResult {
161		<CodeInfoOf<T>>::try_mutate_exists(&code_hash, |existing| {
162			if let Some(code_info) = existing {
163				ensure!(code_info.refcount == 0, <Error<T>>::CodeInUse);
164				ensure!(&code_info.owner == origin, BadOrigin);
165				<Pallet<T>>::refund_deposit(
166					HoldReason::CodeUploadDepositReserve,
167					&Pallet::<T>::account_id(),
168					deposit_payment::Funds::Balance(&code_info.owner),
169					code_info.deposit,
170				)?;
171				*existing = None;
172				<PristineCode<T>>::remove(&code_hash);
173				Ok(())
174			} else {
175				Err(<Error<T>>::CodeNotFound.into())
176			}
177		})
178	}
179
180	/// Puts the module blob into storage, and returns the deposit collected for the storage.
181	pub fn store_code<S: State>(
182		&mut self,
183		exec_config: &ExecConfig<T>,
184		meter: &mut ResourceMeter<T, S>,
185	) -> Result<BalanceOf<T>, DispatchError> {
186		let code_hash = *self.code_hash();
187		ensure!(code_hash != H256::zero(), <Error<T>>::CodeNotFound);
188
189		<CodeInfoOf<T>>::mutate(code_hash, |stored_code_info| {
190			match stored_code_info {
191				// Contract code is already stored in storage. Nothing to be done here.
192				Some(_) => Ok(Default::default()),
193				// Upload a new contract code.
194				// We need to store the code and its code_info, and collect the deposit.
195				// This `None` case happens only with freshly uploaded modules. This means that
196				// the `owner` is always the origin of the current transaction.
197				None => {
198					let deposit = self.code_info.deposit;
199
200					<Pallet<T>>::charge_deposit(
201							HoldReason::CodeUploadDepositReserve,
202							&self.code_info.owner,
203							&Pallet::<T>::account_id(),
204							deposit,
205							exec_config,
206						)
207					 .inspect_err(|err| {
208							log::debug!(target: LOG_TARGET, "failed to hold store code deposit {deposit:?} for owner: {:?}: {err:?}", self.code_info.owner);
209					})?;
210
211					meter.charge_deposit(&StorageDeposit::Charge(deposit))?;
212
213					<PristineCode<T>>::insert(code_hash, &self.code.to_vec());
214					*stored_code_info = Some(self.code_info.clone());
215					Ok(deposit)
216				},
217			}
218		})
219	}
220}
221
222impl<T: Config> CodeInfo<T> {
223	#[cfg(test)]
224	pub fn new(owner: T::AccountId) -> Self {
225		CodeInfo {
226			owner,
227			deposit: Default::default(),
228			refcount: 0,
229			code_len: 0,
230			code_type: BytecodeType::Pvm,
231			behaviour_version: Default::default(),
232		}
233	}
234
235	#[cfg(any(feature = "runtime-benchmarks", test))]
236	pub fn new_with_deposit(owner: T::AccountId, deposit: BalanceOf<T>) -> Self {
237		CodeInfo {
238			owner,
239			deposit,
240			refcount: 0,
241			code_len: 0,
242			code_type: BytecodeType::Pvm,
243			behaviour_version: Default::default(),
244		}
245	}
246
247	/// Override the refcount. Test-only — used to engineer overflow scenarios on
248	/// `increment_refcount`.
249	#[cfg(test)]
250	pub fn set_refcount(&mut self, refcount: u64) {
251		self.refcount = refcount;
252	}
253
254	/// Returns reference count of the module.
255	#[cfg(test)]
256	pub fn refcount(&self) -> u64 {
257		self.refcount
258	}
259
260	/// Returns the deposit of the module.
261	pub fn deposit(&self) -> BalanceOf<T> {
262		self.deposit
263	}
264
265	/// Returns the account that uploaded the module.
266	pub fn owner(&self) -> &AccountIdOf<T> {
267		&self.owner
268	}
269
270	/// Returns the code length.
271	pub fn code_len(&self) -> u64 {
272		self.code_len.into()
273	}
274
275	/// Returns true if the executable is a PVM blob.
276	pub fn is_pvm(&self) -> bool {
277		matches!(self.code_type, BytecodeType::Pvm)
278	}
279
280	/// Returns the number of times the specified contract exists on the call stack. Delegated calls
281	/// Increment the reference count of a stored code by one.
282	///
283	/// # Errors
284	///
285	/// [`Error::CodeNotFound`] is returned if no stored code found having the specified
286	/// `code_hash`.
287	pub fn increment_refcount(code_hash: H256) -> DispatchResult {
288		<CodeInfoOf<T>>::mutate(code_hash, |existing| -> Result<(), DispatchError> {
289			if let Some(info) = existing {
290				info.refcount = info
291					.refcount
292					.checked_add(1)
293					.ok_or_else(|| <Error<T>>::RefcountOverOrUnderflow)?;
294				Ok(())
295			} else {
296				Err(Error::<T>::CodeNotFound.into())
297			}
298		})
299	}
300
301	/// Decrement the reference count of a stored code by one.
302	/// Remove the code from storage when the reference count is zero.
303	pub fn decrement_refcount(code_hash: H256) -> Result<CodeRemoved, DispatchError> {
304		<CodeInfoOf<T>>::try_mutate_exists(code_hash, |existing| {
305			let Some(code_info) = existing else { return Err(Error::<T>::CodeNotFound.into()) };
306
307			if code_info.refcount == 1 {
308				<Pallet<T>>::refund_deposit(
309					HoldReason::CodeUploadDepositReserve,
310					&Pallet::<T>::account_id(),
311					deposit_payment::Funds::Balance(&code_info.owner),
312					code_info.deposit,
313				)?;
314
315				*existing = None;
316				<PristineCode<T>>::remove(&code_hash);
317
318				Ok(CodeRemoved::Yes)
319			} else {
320				code_info.refcount = code_info
321					.refcount
322					.checked_sub(1)
323					.ok_or_else(|| <Error<T>>::RefcountOverOrUnderflow)?;
324				Ok(CodeRemoved::No)
325			}
326		})
327	}
328}
329
330impl<T: Config> Executable<T> for ContractBlob<T> {
331	fn from_storage<S: State>(
332		code_hash: H256,
333		meter: &mut ResourceMeter<T, S>,
334	) -> Result<Self, DispatchError> {
335		let code_info = <CodeInfoOf<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
336		meter.charge_weight_token(CodeLoadToken::from_code_info(&code_info))?;
337		let code = <PristineCode<T>>::get(&code_hash).ok_or(Error::<T>::CodeNotFound)?;
338		Ok(Self { code, code_info, code_hash })
339	}
340
341	fn from_evm_init_code(code: Vec<u8>, owner: AccountIdOf<T>) -> Result<Self, DispatchError> {
342		ContractBlob::from_evm_init_code(code, owner)
343	}
344
345	fn execute<E: Ext<T = T>>(
346		self,
347		ext: &mut E,
348		function: ExportedFunction,
349		input_data: Vec<u8>,
350	) -> ExecResult {
351		if self.code_info().is_pvm() {
352			let prepared_call = self.prepare_call(pvm::Runtime::new(ext, input_data), function)?;
353			prepared_call.call()
354		} else if T::AllowEVMBytecode::get() {
355			use revm::bytecode::Bytecode;
356			let bytecode = Bytecode::new_raw(self.code.into());
357			evm::call(bytecode, ext, input_data)
358		} else {
359			Err(Error::<T>::CodeRejected.into())
360		}
361	}
362
363	fn code(&self) -> &[u8] {
364		self.code.as_ref()
365	}
366
367	fn code_hash(&self) -> &H256 {
368		&self.code_hash
369	}
370
371	fn code_info(&self) -> &CodeInfo<T> {
372		&self.code_info
373	}
374}
375
376/// Fallible conversion of a `ExecError` to `ReturnErrorCode`.
377///
378/// This is used when converting the error returned from a subcall in order to decide
379/// whether to trap the caller or allow handling of the error.
380pub(crate) fn exec_error_into_return_code<E: Ext>(
381	from: ExecError,
382) -> Result<ReturnErrorCode, DispatchError> {
383	use crate::exec::ErrorOrigin::Callee;
384	use ReturnErrorCode::*;
385
386	let transfer_failed = Error::<E::T>::TransferFailed.into();
387	let out_of_gas = Error::<E::T>::OutOfGas.into();
388	let out_of_deposit = Error::<E::T>::StorageDepositLimitExhausted.into();
389	let duplicate_contract = Error::<E::T>::DuplicateContract.into();
390	let unsupported_precompile = Error::<E::T>::UnsupportedPrecompileAddress.into();
391
392	// errors in the callee do not trap the caller
393	match (from.error, from.origin) {
394		(err, _) if err == transfer_failed => Ok(TransferFailed),
395		(err, _) if err == duplicate_contract => Ok(DuplicateContractAddress),
396		(err, _) if err == unsupported_precompile => Err(err),
397		(err, Callee) if err == out_of_gas || err == out_of_deposit => Ok(OutOfResources),
398		(_, Callee) => Ok(CalleeTrapped),
399		(err, _) => Err(err),
400	}
401}