1234567891011121314151617#![cfg_attr(not(feature = "std"), no_std)]1819extern crate self as pallet_evm_coder_substrate;2021#[cfg(not(feature = "std"))]22extern crate alloc;23#[cfg(not(feature = "std"))]24use alloc::format;25use execution::PreDispatch;26use frame_support::dispatch::Weight;2728use core::marker::PhantomData;29use sp_std::cell::RefCell;3031use codec::Decode;32use frame_support::pallet_prelude::DispatchError;33use frame_support::traits::PalletInfo;34use frame_support::{ensure, sp_runtime::ModuleError};35use up_data_structs::budget;36use pallet_evm::{37 ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,38 PrecompileResult, PrecompileHandle,39};40use sp_core::{Get, H160};414243pub mod execution;44pub use evm_coder::*;4546#[doc(hidden)]47pub use spez::spez;4849use evm_coder::{50 abi::{AbiReader, AbiWrite, AbiWriter},51 types::{Msg, Value},52};5354pub use pallet::*;5556#[frame_support::pallet]57pub mod pallet {58 use super::*;5960 use frame_system::ensure_signed;61 pub use frame_support::dispatch::DispatchResult;62 use frame_system::pallet_prelude::*;6364 65 66 67 68 69 #[pallet::error]70 pub enum Error<T> {71 OutOfGas,72 OutOfFund,73 }7475 #[pallet::config]76 pub trait Config: frame_system::Config + pallet_evm::Config {}7778 #[pallet::pallet]79 pub struct Pallet<T>(_);8081 #[pallet::call]82 impl<T: Config> Pallet<T> {83 #[pallet::call_index(0)]84 #[pallet::weight(0)]85 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {86 let _sender = ensure_signed(origin)?;87 Ok(())88 }89 }90}919293pub const G_SLOAD_WORD: u64 = 800;94pub const G_SSTORE_WORD: u64 = 20000;9596pub struct GasCallsBudget<'r, T: Config> {97 recorder: &'r SubstrateRecorder<T>,98 gas_per_call: u64,99}100impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {101 fn consume_custom(&self, calls: u32) -> bool {102 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);103 if overflown {104 return false;105 }106 self.recorder.consume_gas(gas).is_ok()107 }108}109110#[derive(Default)]111pub struct SubstrateRecorder<T: Config> {112 initial_gas: u64,113 gas_limit: RefCell<u64>,114 _phantom: PhantomData<*const T>,115}116117impl<T: Config> SubstrateRecorder<T> {118 pub fn new(gas_limit: u64) -> Self {119 Self {120 initial_gas: gas_limit,121 gas_limit: RefCell::new(gas_limit),122 _phantom: PhantomData,123 }124 }125126 pub fn gas_left(&self) -> u64 {127 *self.gas_limit.borrow()128 }129 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {130 GasCallsBudget {131 recorder: self,132 gas_per_call,133 }134 }135 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {136 GasCallsBudget {137 recorder: self,138 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),139 }140 }141 pub fn consume_sload_sub(&self) -> DispatchResult {142 self.consume_gas_sub(G_SLOAD_WORD)143 }144 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {145 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))146 }147 pub fn consume_sstore_sub(&self) -> DispatchResult {148 self.consume_gas_sub(G_SSTORE_WORD)149 }150 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {151 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);152 let mut gas_limit = self.gas_limit.borrow_mut();153 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);154 *gas_limit -= gas;155 Ok(())156 }157158 pub fn consume_sload(&self) -> execution::Result<()> {159 self.consume_gas(G_SLOAD_WORD)160 }161 pub fn consume_sstore(&self) -> execution::Result<()> {162 self.consume_gas(G_SSTORE_WORD)163 }164 pub fn consume_gas(&self, gas: u64) -> execution::Result<()> {165 if gas == u64::MAX {166 return Err(execution::Error::Error(ExitError::OutOfGas));167 }168 let mut gas_limit = self.gas_limit.borrow_mut();169 if gas > *gas_limit {170 return Err(execution::Error::Error(ExitError::OutOfGas));171 }172 *gas_limit -= gas;173 Ok(())174 }175 pub fn return_gas(&self, gas: u64) {176 let mut gas_limit = self.gas_limit.borrow_mut();177 *gas_limit += gas;178 }179180 pub fn evm_to_precompile_output(181 self,182 handle: &mut impl PrecompileHandle,183 result: execution::Result<Option<AbiWriter>>,184 ) -> Option<PrecompileResult> {185 use execution::Error;186 187 let _ = handle.record_cost(self.initial_gas - self.gas_left());188 Some(match result {189 Ok(Some(v)) => Ok(PrecompileOutput {190 exit_status: ExitSucceed::Returned,191 output: v.finish(),192 }),193 Ok(None) => return None,194 Err(Error::Revert(e)) => {195 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));196 (&e as &str).abi_write(&mut writer);197198 Err(PrecompileFailure::Revert {199 exit_status: ExitRevert::Reverted,200 output: writer.finish(),201 })202 }203 Err(Error::Fatal(f)) => Err(PrecompileFailure::Fatal { exit_status: f }),204 Err(Error::Error(e)) => Err(e.into()),205 })206 }207208 209 pub fn consume_store_reads(&self, reads: u64) -> execution::Result<()> {210 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(211 <T as frame_system::Config>::DbWeight::get()212 .read213 .saturating_mul(reads),214 215 0,216 )))217 }218219 220 pub fn consume_store_writes(&self, writes: u64) -> execution::Result<()> {221 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(222 <T as frame_system::Config>::DbWeight::get()223 .write224 .saturating_mul(writes),225 226 0,227 )))228 }229230 231 pub fn consume_store_reads_and_writes(&self, reads: u64, writes: u64) -> execution::Result<()> {232 let weight = <T as frame_system::Config>::DbWeight::get();233 let reads = weight.read.saturating_mul(reads);234 let writes = weight.read.saturating_mul(writes);235 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(236 reads.saturating_add(writes),237 238 0,239 )))240 }241}242243pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> execution::Error {244 use execution::Error as ExError;245 match err {246 DispatchError::Module(ModuleError { index, error, .. })247 if index248 == T::PalletInfo::index::<Pallet<T>>()249 .expect("evm-coder-substrate is a pallet, which should be added to runtime")250 as u8 =>251 {252 let mut read = &error as &[u8];253 match Error::<T>::decode(&mut read) {254 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),255 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),256 _ => unreachable!("this pallet only defines two possible errors"),257 }258 }259 DispatchError::Module(ModuleError {260 message: Some(msg), ..261 }) => ExError::Revert(msg.into()),262 DispatchError::Module(ModuleError { index, error, .. }) => {263 ExError::Revert(format!("error {:?} in pallet {}", error, index))264 }265 e => ExError::Revert(format!("substrate error: {:?}", e)),266 }267}268269pub trait WithRecorder<T: Config> {270 fn recorder(&self) -> &SubstrateRecorder<T>;271 fn into_recorder(self) -> SubstrateRecorder<T>;272}273274275pub fn call<T, C, E, H>(handle: &mut H, mut e: E) -> Option<PrecompileResult>276where277 T: Config,278 C: evm_coder::Call + PreDispatch,279 E: evm_coder::Callable<C> + WithRecorder<T>,280 H: PrecompileHandle,281 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,282{283 let result = call_internal(284 handle.context().caller,285 &mut e,286 handle.context().apparent_value,287 handle.input(),288 );289 e.into_recorder().evm_to_precompile_output(handle, result)290}291292fn call_internal<T, C, E>(293 caller: H160,294 e: &mut E,295 value: Value,296 input: &[u8],297) -> execution::Result<Option<AbiWriter>>298where299 T: Config,300 C: evm_coder::Call + PreDispatch,301 E: Contract + evm_coder::Callable<C> + WithRecorder<T>,302 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,303{304 let (selector, mut reader) = AbiReader::new_call(input)?;305 let call = C::parse(selector, &mut reader)?;306 if call.is_none() {307 let selector = u32::from_be_bytes(selector);308 return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());309 }310 let call = call.unwrap();311312 let dispatch_info = call.dispatch_info();313 e.recorder()314 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;315316 match execution::ResultWithPostInfo::from(e.call(Msg {317 call,318 caller,319 value,320 })) {321 Ok(v) => {322 let unspent = v.post_info.calc_unspent(&dispatch_info);323 e.recorder()324 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));325 Ok(Some(v.data))326 }327 Err(v) => {328 let unspent = v.post_info.calc_unspent(&dispatch_info);329 e.recorder()330 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));331 Err(v.data)332 }333 }334}335336#[cfg(test)]337#[allow(dead_code)]338mod tests {339 use core::marker::PhantomData;340341 use evm_coder::ERC165Call;342 use frame_support::weights::Weight;343344 use crate::execution::PreDispatch;345346 #[derive(PreDispatch)]347 enum ExampleCall<T: super::Config> {348 ERC165Call(ERC165Call, PhantomData<fn() -> T>),349 OtherCall(ERC165Call),350351 #[weight(Weight::from_ref_time(a + b))]352 Example {353 a: u64,354 b: u64,355 },356 }357}