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},
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))]
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 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 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 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 Some(_) => Ok(Default::default()),
197 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 #[cfg(test)]
254 pub fn set_refcount(&mut self, refcount: u64) {
255 self.refcount = refcount;
256 }
257
258 #[cfg(test)]
260 pub fn refcount(&self) -> u64 {
261 self.refcount
262 }
263
264 pub fn deposit(&self) -> BalanceOf<T> {
266 self.deposit
267 }
268
269 pub fn owner(&self) -> &AccountIdOf<T> {
271 &self.owner
272 }
273
274 pub fn code_len(&self) -> u64 {
276 self.code_len.into()
277 }
278
279 pub fn is_pvm(&self) -> bool {
281 matches!(self.code_type, BytecodeType::Pvm)
282 }
283
284 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 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
381pub(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 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}