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},
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#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
124#[derive(Clone, Copy)]
125struct CodeLoadToken {
126	code_len: u32,
127	code_type: BytecodeType,
128}
129
130impl CodeLoadToken {
131	fn from_code_info<T: Config>(code_info: &CodeInfo<T>) -> Self {
132		Self { code_len: code_info.code_len, code_type: code_info.code_type }
133	}
134}
135
136impl<T: Config> Token<T> for CodeLoadToken {
137	fn weight(&self) -> Weight {
138		match self.code_type {
139			// the proof size impact is accounted for in the `call_with_pvm_code_per_byte`
140			// strictly speaking we are double charging for the first BASIC_BLOCK_SIZE
141			// instructions here. Let's consider this as a safety margin.
142			BytecodeType::Pvm => T::WeightInfo::call_with_pvm_code_per_byte(self.code_len)
143				.saturating_sub(T::WeightInfo::call_with_pvm_code_per_byte(0))
144				.saturating_add(
145					T::WeightInfo::basic_block_compilation(1)
146						.saturating_sub(T::WeightInfo::basic_block_compilation(0))
147						.set_proof_size(0),
148				),
149			BytecodeType::Evm => T::WeightInfo::call_with_evm_code_per_byte(self.code_len)
150				.saturating_sub(T::WeightInfo::call_with_evm_code_per_byte(0)),
151		}
152	}
153}
154
155#[cfg(test)]
156pub fn code_load_weight(code_len: u32) -> Weight {
157	Token::<crate::tests::Test>::weight(&CodeLoadToken { code_len, code_type: BytecodeType::Pvm })
158}
159
160impl<T: Config> ContractBlob<T> {
161	/// Remove the code from storage and refund the deposit to its owner.
162	///
163	/// Applies all necessary checks before removing the code.
164	pub fn remove(origin: &T::AccountId, code_hash: H256) -> DispatchResult {
165		<CodeInfoOf<T>>::try_mutate_exists(&code_hash, |existing| {
166			if let Some(code_info) = existing {
167				ensure!(code_info.refcount == 0, <Error<T>>::CodeInUse);
168				ensure!(&code_info.owner == origin, BadOrigin);
169				<Pallet<T>>::refund_deposit(
170					HoldReason::CodeUploadDepositReserve,
171					&Pallet::<T>::account_id(),
172					deposit_payment::Funds::Balance(&code_info.owner),
173					code_info.deposit,
174				)?;
175				*existing = None;
176				<PristineCode<T>>::remove(&code_hash);
177				Ok(())
178			} else {
179				Err(<Error<T>>::CodeNotFound.into())
180			}
181		})
182	}
183
184	/// Puts the module blob into storage, and returns the deposit collected for the storage.
185	pub fn store_code<S: State>(
186		&mut self,
187		exec_config: &ExecConfig<T>,
188		meter: &mut ResourceMeter<T, S>,
189	) -> Result<BalanceOf<T>, DispatchError> {
190		let code_hash = *self.code_hash();
191		ensure!(code_hash != H256::zero(), <Error<T>>::CodeNotFound);
192
193		<CodeInfoOf<T>>::mutate(code_hash, |stored_code_info| {
194			match stored_code_info {
195				// Contract code is already stored in storage. Nothing to be done here.
196				Some(_) => Ok(Default::default()),
197				// Upload a new contract code.
198				// We need to store the code and its code_info, and collect the deposit.
199				// This `None` case happens only with freshly uploaded modules. This means that
200				// the `owner` is always the origin of the current transaction.
201				None => {
202					let deposit = self.code_info.deposit;
203
204					<Pallet<T>>::charge_deposit(
205							HoldReason::CodeUploadDepositReserve,
206							&self.code_info.owner,
207							&Pallet::<T>::account_id(),
208							deposit,
209							exec_config,
210						)
211					 .inspect_err(|err| {
212							log::debug!(target: LOG_TARGET, "failed to hold store code deposit {deposit:?} for owner: {:?}: {err:?}", self.code_info.owner);
213					})?;
214
215					meter.charge_deposit(&StorageDeposit::Charge(deposit))?;
216
217					<PristineCode<T>>::insert(code_hash, &self.code.to_vec());
218					*stored_code_info = Some(self.code_info.clone());
219					Ok(deposit)
220				},
221			}
222		})
223	}
224}
225
226impl<T: Config> CodeInfo<T> {
227	#[cfg(test)]
228	pub fn new(owner: T::AccountId) -> Self {
229		CodeInfo {
230			owner,
231			deposit: Default::default(),
232			refcount: 0,
233			code_len: 0,
234			code_type: BytecodeType::Pvm,
235			behaviour_version: Default::default(),
236		}
237	}
238
239	#[cfg(any(feature = "runtime-benchmarks", test))]
240	pub fn new_with_deposit(owner: T::AccountId, deposit: BalanceOf<T>) -> Self {
241		CodeInfo {
242			owner,
243			deposit,
244			refcount: 0,
245			code_len: 0,
246			code_type: BytecodeType::Pvm,
247			behaviour_version: Default::default(),
248		}
249	}
250
251	/// Override the refcount. Test-only — used to engineer overflow scenarios on
252	/// `increment_refcount`.
253	#[cfg(test)]
254	pub fn set_refcount(&mut self, refcount: u64) {
255		self.refcount = refcount;
256	}
257
258	/// Returns reference count of the module.
259	#[cfg(test)]
260	pub fn refcount(&self) -> u64 {
261		self.refcount
262	}
263
264	/// Returns the deposit of the module.
265	pub fn deposit(&self) -> BalanceOf<T> {
266		self.deposit
267	}
268
269	/// Returns the account that uploaded the module.
270	pub fn owner(&self) -> &AccountIdOf<T> {
271		&self.owner
272	}
273
274	/// Returns the code length.
275	pub fn code_len(&self) -> u64 {
276		self.code_len.into()
277	}
278
279	/// Returns true if the executable is a PVM blob.
280	pub fn is_pvm(&self) -> bool {
281		matches!(self.code_type, BytecodeType::Pvm)
282	}
283
284	/// Returns the number of times the specified contract exists on the call stack. Delegated calls
285	/// Increment the reference count of a stored code by one.
286	///
287	/// # Errors
288	///
289	/// [`Error::CodeNotFound`] is returned if no stored code found having the specified
290	/// `code_hash`.
291	pub fn increment_refcount(code_hash: H256) -> DispatchResult {
292		<CodeInfoOf<T>>::mutate(code_hash, |existing| -> Result<(), DispatchError> {
293			if let Some(info) = existing {
294				info.refcount = info
295					.refcount
296					.checked_add(1)
297					.ok_or_else(|| <Error<T>>::RefcountOverOrUnderflow)?;
298				Ok(())
299			} else {
300				Err(Error::<T>::CodeNotFound.into())
301			}
302		})
303	}
304
305	/// Decrement the reference count of a stored code by one.
306	/// Remove the code from storage when the reference count is zero.
307	pub fn decrement_refcount(code_hash: H256) -> Result<CodeRemoved, DispatchError> {
308		<CodeInfoOf<T>>::try_mutate_exists(code_hash, |existing| {
309			let Some(code_info) = existing else { return Err(Error::<T>::CodeNotFound.into()) };
310
311			if code_info.refcount == 1 {
312				<Pallet<T>>::refund_deposit(
313					HoldReason::CodeUploadDepositReserve,
314					&Pallet::<T>::account_id(),
315					deposit_payment::Funds::Balance(&code_info.owner),
316					code_info.deposit,
317				)?;
318
319				*existing = None;
320				<PristineCode<T>>::remove(&code_hash);
321
322				Ok(CodeRemoved::Yes)
323			} else {
324				code_info.refcount = code_info
325					.refcount
326					.checked_sub(1)
327					.ok_or_else(|| <Error<T>>::RefcountOverOrUnderflow)?;
328				Ok(CodeRemoved::No)
329			}
330		})
331	}
332}
333
334impl<T: Config> Executable<T> for ContractBlob<T> {
335	fn from_storage<S: State>(
336		code_hash: H256,
337		meter: &mut ResourceMeter<T, S>,
338	) -> Result<Self, DispatchError> {
339		let code_info = <CodeInfoOf<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
340		meter.charge_weight_token(CodeLoadToken::from_code_info(&code_info))?;
341		let code = <PristineCode<T>>::get(&code_hash).ok_or(Error::<T>::CodeNotFound)?;
342		Ok(Self { code, code_info, code_hash })
343	}
344
345	fn from_evm_init_code(code: Vec<u8>, owner: AccountIdOf<T>) -> Result<Self, DispatchError> {
346		ContractBlob::from_evm_init_code(code, owner)
347	}
348
349	fn execute<E: Ext<T = T>>(
350		self,
351		ext: &mut E,
352		function: ExportedFunction,
353		input_data: Vec<u8>,
354	) -> ExecResult {
355		if self.code_info().is_pvm() {
356			let prepared_call =
357				self.prepare_call(pvm::Runtime::new(ext, input_data), function, 0)?;
358			prepared_call.call()
359		} else if T::AllowEVMBytecode::get() {
360			use revm::bytecode::Bytecode;
361			let bytecode = Bytecode::new_raw(self.code.into());
362			evm::call(bytecode, ext, input_data)
363		} else {
364			Err(Error::<T>::CodeRejected.into())
365		}
366	}
367
368	fn code(&self) -> &[u8] {
369		self.code.as_ref()
370	}
371
372	fn code_hash(&self) -> &H256 {
373		&self.code_hash
374	}
375
376	fn code_info(&self) -> &CodeInfo<T> {
377		&self.code_info
378	}
379}
380
381/// Fallible conversion of a `ExecError` to `ReturnErrorCode`.
382///
383/// This is used when converting the error returned from a subcall in order to decide
384/// whether to trap the caller or allow handling of the error.
385pub(crate) fn exec_error_into_return_code<E: Ext>(
386	from: ExecError,
387) -> Result<ReturnErrorCode, DispatchError> {
388	use crate::exec::ErrorOrigin::Callee;
389	use ReturnErrorCode::*;
390
391	let transfer_failed = Error::<E::T>::TransferFailed.into();
392	let out_of_gas = Error::<E::T>::OutOfGas.into();
393	let out_of_deposit = Error::<E::T>::StorageDepositLimitExhausted.into();
394	let duplicate_contract = Error::<E::T>::DuplicateContract.into();
395	let unsupported_precompile = Error::<E::T>::UnsupportedPrecompileAddress.into();
396
397	// errors in the callee do not trap the caller
398	match (from.error, from.origin) {
399		(err, _) if err == transfer_failed => Ok(TransferFailed),
400		(err, _) if err == duplicate_contract => Ok(DuplicateContractAddress),
401		(err, _) if err == unsupported_precompile => Err(err),
402		(err, Callee) if err == out_of_gas || err == out_of_deposit => Ok(OutOfResources),
403		(_, Callee) => Ok(CalleeTrapped),
404		(err, _) => Err(err),
405	}
406}