1pub 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#[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 #[codec(skip)]
53 code_info: CodeInfo<T>,
54 #[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 Pvm,
65 Evm,
67}
68
69#[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 owner: AccountIdOf<T>,
84 #[codec(compact)]
86 deposit: BalanceOf<T>,
87 #[codec(compact)]
89 refcount: u64,
90 code_len: u32,
92 code_type: BytecodeType,
94 behaviour_version: u32,
102}
103
104pub 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 fn identifier(&self) -> &str {
115 match self {
116 Self::Constructor => "deploy",
117 Self::Call => "call",
118 }
119 }
120}
121
122#[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 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 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 Some(_) => Ok(Default::default()),
193 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 #[cfg(test)]
250 pub fn set_refcount(&mut self, refcount: u64) {
251 self.refcount = refcount;
252 }
253
254 #[cfg(test)]
256 pub fn refcount(&self) -> u64 {
257 self.refcount
258 }
259
260 pub fn deposit(&self) -> BalanceOf<T> {
262 self.deposit
263 }
264
265 pub fn owner(&self) -> &AccountIdOf<T> {
267 &self.owner
268 }
269
270 pub fn code_len(&self) -> u64 {
272 self.code_len.into()
273 }
274
275 pub fn is_pvm(&self) -> bool {
277 matches!(self.code_type, BytecodeType::Pvm)
278 }
279
280 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 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
376pub(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 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}