1234567891011121314151617#![cfg_attr(not(feature = "std"), no_std)]1819#[cfg(not(feature = "std"))]20extern crate alloc;21#[cfg(not(feature = "std"))]22use alloc::format;23use frame_support::dispatch::Weight;2425use core::marker::PhantomData;26use sp_std::cell::RefCell;2728use codec::Decode;29use frame_support::pallet_prelude::DispatchError;30use frame_support::traits::PalletInfo;31use frame_support::{ensure, sp_runtime::ModuleError};32use up_data_structs::budget;33use pallet_evm::{34 ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,35 PrecompileResult, PrecompileHandle,36};37use sp_core::H160;38394041use evm_coder::{42 abi::{AbiReader, AbiWrite, AbiWriter},43 execution,44 types::{Msg, Value},45};4647pub use pallet::*;4849#[frame_support::pallet]50pub mod pallet {51 use super::*;5253 use frame_system::ensure_signed;54 pub use frame_support::dispatch::DispatchResult;55 use frame_system::pallet_prelude::*;5657 58 59 60 61 62 #[pallet::error]63 pub enum Error<T> {64 OutOfGas,65 OutOfFund,66 }6768 #[pallet::config]69 pub trait Config: frame_system::Config + pallet_evm::Config {}7071 #[pallet::pallet]72 pub struct Pallet<T>(_);7374 #[pallet::call]75 impl<T: Config> Pallet<T> {76 #[pallet::call_index(0)]77 #[pallet::weight(0)]78 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {79 let _sender = ensure_signed(origin)?;80 Ok(())81 }82 }83}848586pub const G_SLOAD_WORD: u64 = 800;87pub const G_SSTORE_WORD: u64 = 20000;8889pub struct GasCallsBudget<'r, T: Config> {90 recorder: &'r SubstrateRecorder<T>,91 gas_per_call: u64,92}93impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {94 fn consume_custom(&self, calls: u32) -> bool {95 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);96 if overflown {97 return false;98 }99 self.recorder.consume_gas(gas).is_ok()100 }101}102103#[derive(Default)]104pub struct SubstrateRecorder<T: Config> {105 initial_gas: u64,106 gas_limit: RefCell<u64>,107 _phantom: PhantomData<*const T>,108}109110impl<T: Config> SubstrateRecorder<T> {111 pub fn new(gas_limit: u64) -> Self {112 Self {113 initial_gas: gas_limit,114 gas_limit: RefCell::new(gas_limit),115 _phantom: PhantomData,116 }117 }118119 pub fn gas_left(&self) -> u64 {120 *self.gas_limit.borrow()121 }122 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {123 GasCallsBudget {124 recorder: self,125 gas_per_call,126 }127 }128 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {129 GasCallsBudget {130 recorder: self,131 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),132 }133 }134 pub fn consume_sload_sub(&self) -> DispatchResult {135 self.consume_gas_sub(G_SLOAD_WORD)136 }137 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {138 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))139 }140 pub fn consume_sstore_sub(&self) -> DispatchResult {141 self.consume_gas_sub(G_SSTORE_WORD)142 }143 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {144 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);145 let mut gas_limit = self.gas_limit.borrow_mut();146 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);147 *gas_limit -= gas;148 Ok(())149 }150151 pub fn consume_sload(&self) -> execution::Result<()> {152 self.consume_gas(G_SLOAD_WORD)153 }154 pub fn consume_sstore(&self) -> execution::Result<()> {155 self.consume_gas(G_SSTORE_WORD)156 }157 pub fn consume_gas(&self, gas: u64) -> execution::Result<()> {158 if gas == u64::MAX {159 return Err(execution::Error::Error(ExitError::OutOfGas));160 }161 let mut gas_limit = self.gas_limit.borrow_mut();162 if gas > *gas_limit {163 return Err(execution::Error::Error(ExitError::OutOfGas));164 }165 *gas_limit -= gas;166 Ok(())167 }168 pub fn return_gas(&self, gas: u64) {169 let mut gas_limit = self.gas_limit.borrow_mut();170 *gas_limit += gas;171 }172173 pub fn evm_to_precompile_output(174 self,175 handle: &mut impl PrecompileHandle,176 result: execution::Result<Option<AbiWriter>>,177 ) -> Option<PrecompileResult> {178 use evm_coder::execution::Error;179 180 let _ = handle.record_cost(self.initial_gas - self.gas_left());181 Some(match result {182 Ok(Some(v)) => Ok(PrecompileOutput {183 exit_status: ExitSucceed::Returned,184 output: v.finish(),185 }),186 Ok(None) => return None,187 Err(Error::Revert(e)) => {188 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));189 (&e as &str).abi_write(&mut writer);190191 Err(PrecompileFailure::Revert {192 exit_status: ExitRevert::Reverted,193 output: writer.finish(),194 })195 }196 Err(Error::Fatal(f)) => Err(f.into()),197 Err(Error::Error(e)) => Err(e.into()),198 })199 }200}201202pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> execution::Error {203 use evm_coder::execution::Error as ExError;204 match err {205 DispatchError::Module(ModuleError { index, error, .. })206 if index207 == T::PalletInfo::index::<Pallet<T>>()208 .expect("evm-coder-substrate is a pallet, which should be added to runtime")209 as u8 =>210 {211 let mut read = &error as &[u8];212 match Error::<T>::decode(&mut read) {213 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),214 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),215 _ => unreachable!("this pallet only defines two possible errors"),216 }217 }218 DispatchError::Module(ModuleError {219 message: Some(msg), ..220 }) => ExError::Revert(msg.into()),221 DispatchError::Module(ModuleError { index, error, .. }) => {222 ExError::Revert(format!("error {:?} in pallet {}", error, index))223 }224 e => ExError::Revert(format!("substrate error: {:?}", e)),225 }226}227228pub trait WithRecorder<T: Config> {229 fn recorder(&self) -> &SubstrateRecorder<T>;230 fn into_recorder(self) -> SubstrateRecorder<T>;231}232233234pub fn call<235 T: Config,236 C: evm_coder::Call + evm_coder::Weighted,237 E: evm_coder::Callable<C> + WithRecorder<T>,238 H: PrecompileHandle,239>(240 handle: &mut H,241 mut e: E,242) -> Option<PrecompileResult> {243 let result = call_internal(244 handle.context().caller,245 &mut e,246 handle.context().apparent_value,247 handle.input(),248 );249 e.into_recorder().evm_to_precompile_output(handle, result)250}251252fn call_internal<253 T: Config,254 C: evm_coder::Call + evm_coder::Weighted,255 E: evm_coder::Callable<C> + WithRecorder<T>,256>(257 caller: H160,258 e: &mut E,259 value: Value,260 input: &[u8],261) -> execution::Result<Option<AbiWriter>> {262 let (selector, mut reader) = AbiReader::new_call(input)?;263 let call = C::parse(selector, &mut reader)?;264 if call.is_none() {265 let selector = u32::from_be_bytes(selector);266 return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());267 }268 let call = call.unwrap();269270 let dispatch_info = call.weight();271 e.recorder()272 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;273274 match e.call(Msg {275 call,276 caller,277 value,278 }) {279 Ok(v) => {280 let unspent = v.post_info.calc_unspent(&dispatch_info);281 e.recorder()282 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));283 Ok(Some(v.data))284 }285 Err(v) => {286 let unspent = v.post_info.calc_unspent(&dispatch_info);287 e.recorder()288 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));289 Err(v.data)290 }291 }292}