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::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 }207}208209pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> execution::Error {210 use execution::Error as ExError;211 match err {212 DispatchError::Module(ModuleError { index, error, .. })213 if index214 == T::PalletInfo::index::<Pallet<T>>()215 .expect("evm-coder-substrate is a pallet, which should be added to runtime")216 as u8 =>217 {218 let mut read = &error as &[u8];219 match Error::<T>::decode(&mut read) {220 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),221 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),222 _ => unreachable!("this pallet only defines two possible errors"),223 }224 }225 DispatchError::Module(ModuleError {226 message: Some(msg), ..227 }) => ExError::Revert(msg.into()),228 DispatchError::Module(ModuleError { index, error, .. }) => {229 ExError::Revert(format!("error {:?} in pallet {}", error, index))230 }231 e => ExError::Revert(format!("substrate error: {:?}", e)),232 }233}234235pub trait WithRecorder<T: Config> {236 fn recorder(&self) -> &SubstrateRecorder<T>;237 fn into_recorder(self) -> SubstrateRecorder<T>;238}239240241pub fn call<T, C, E, H>(handle: &mut H, mut e: E) -> Option<PrecompileResult>242where243 T: Config,244 C: evm_coder::Call + PreDispatch,245 E: evm_coder::Callable<C> + WithRecorder<T>,246 H: PrecompileHandle,247 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,248{249 let result = call_internal(250 handle.context().caller,251 &mut e,252 handle.context().apparent_value,253 handle.input(),254 );255 e.into_recorder().evm_to_precompile_output(handle, result)256}257258fn call_internal<T, C, E>(259 caller: H160,260 e: &mut E,261 value: Value,262 input: &[u8],263) -> execution::Result<Option<AbiWriter>>264where265 T: Config,266 C: evm_coder::Call + PreDispatch,267 E: Contract + evm_coder::Callable<C> + WithRecorder<T>,268 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,269{270 let (selector, mut reader) = AbiReader::new_call(input)?;271 let call = C::parse(selector, &mut reader)?;272 if call.is_none() {273 let selector = u32::from_be_bytes(selector);274 return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());275 }276 let call = call.unwrap();277278 let dispatch_info = call.dispatch_info();279 e.recorder()280 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;281282 match execution::ResultWithPostInfo::from(e.call(Msg {283 call,284 caller,285 value,286 })) {287 Ok(v) => {288 let unspent = v.post_info.calc_unspent(&dispatch_info);289 e.recorder()290 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));291 Ok(Some(v.data))292 }293 Err(v) => {294 let unspent = v.post_info.calc_unspent(&dispatch_info);295 e.recorder()296 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));297 Err(v.data)298 }299 }300}301302#[cfg(test)]303#[allow(dead_code)]304mod tests {305 use core::marker::PhantomData;306307 use evm_coder::ERC165Call;308 use frame_support::weights::Weight;309310 use crate::execution::PreDispatch;311312 #[derive(PreDispatch)]313 enum ExampleCall<T: super::Config> {314 ERC165Call(ERC165Call, PhantomData<fn() -> T>),315 OtherCall(ERC165Call),316317 #[weight(Weight::from_ref_time(a + b))]318 Example {319 a: u64,320 b: u64,321 },322 }323}