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::{self, Result},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::weight(0)]77 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {78 let _sender = ensure_signed(origin)?;79 Ok(())80 }81 }82}838485pub const G_SLOAD_WORD: u64 = 800;86pub const G_SSTORE_WORD: u64 = 20000;8788pub struct GasCallsBudget<'r, T: Config> {89 recorder: &'r SubstrateRecorder<T>,90 gas_per_call: u64,91}92impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {93 fn consume_custom(&self, calls: u32) -> bool {94 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);95 if overflown {96 return false;97 }98 self.recorder.consume_gas(gas).is_ok()99 }100}101102#[derive(Default)]103pub struct SubstrateRecorder<T: Config> {104 initial_gas: u64,105 gas_limit: RefCell<u64>,106 _phantom: PhantomData<*const T>,107}108109impl<T: Config> SubstrateRecorder<T> {110 pub fn new(gas_limit: u64) -> Self {111 Self {112 initial_gas: gas_limit,113 gas_limit: RefCell::new(gas_limit),114 _phantom: PhantomData,115 }116 }117118 pub fn gas_left(&self) -> u64 {119 *self.gas_limit.borrow()120 }121 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {122 GasCallsBudget {123 recorder: self,124 gas_per_call,125 }126 }127 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {128 GasCallsBudget {129 recorder: self,130 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),131 }132 }133 pub fn consume_sload_sub(&self) -> DispatchResult {134 self.consume_gas_sub(G_SLOAD_WORD)135 }136 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {137 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))138 }139 pub fn consume_sstore_sub(&self) -> DispatchResult {140 self.consume_gas_sub(G_SSTORE_WORD)141 }142 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {143 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);144 let mut gas_limit = self.gas_limit.borrow_mut();145 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);146 *gas_limit -= gas;147 Ok(())148 }149150 pub fn consume_sload(&self) -> Result<()> {151 self.consume_gas(G_SLOAD_WORD)152 }153 pub fn consume_sstore(&self) -> Result<()> {154 self.consume_gas(G_SSTORE_WORD)155 }156 pub fn consume_gas(&self, gas: u64) -> Result<()> {157 if gas == u64::MAX {158 return Err(execution::Error::Error(ExitError::OutOfGas));159 }160 let mut gas_limit = self.gas_limit.borrow_mut();161 if gas > *gas_limit {162 return Err(execution::Error::Error(ExitError::OutOfGas));163 }164 *gas_limit -= gas;165 Ok(())166 }167 pub fn return_gas(&self, gas: u64) {168 let mut gas_limit = self.gas_limit.borrow_mut();169 *gas_limit += gas;170 }171172 pub fn evm_to_precompile_output(173 self,174 handle: &mut impl PrecompileHandle,175 result: evm_coder::execution::Result<Option<AbiWriter>>,176 ) -> Option<PrecompileResult> {177 use evm_coder::execution::Error;178 179 let _ = handle.record_cost(self.initial_gas - self.gas_left());180 Some(match result {181 Ok(Some(v)) => Ok(PrecompileOutput {182 exit_status: ExitSucceed::Returned,183 output: v.finish(),184 }),185 Ok(None) => return None,186 Err(Error::Revert(e)) => {187 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));188 (&e as &str).abi_write(&mut writer);189190 Err(PrecompileFailure::Revert {191 exit_status: ExitRevert::Reverted,192 output: writer.finish(),193 })194 }195 Err(Error::Fatal(f)) => Err(f.into()),196 Err(Error::Error(e)) => Err(e.into()),197 })198 }199}200201pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {202 use evm_coder::execution::Error as ExError;203 match err {204 DispatchError::Module(ModuleError { index, error, .. })205 if index206 == T::PalletInfo::index::<Pallet<T>>()207 .expect("evm-coder-substrate is a pallet, which should be added to runtime")208 as u8 =>209 {210 let mut read = &error as &[u8];211 match Error::<T>::decode(&mut read) {212 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),213 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),214 _ => unreachable!("this pallet only defines two possible errors"),215 }216 }217 DispatchError::Module(ModuleError {218 message: Some(msg), ..219 }) => ExError::Revert(msg.into()),220 DispatchError::Module(ModuleError { index, error, .. }) => {221 ExError::Revert(format!("error {:?} in pallet {}", error, index))222 }223 e => ExError::Revert(format!("substrate error: {:?}", e)),224 }225}226227pub trait WithRecorder<T: Config> {228 fn recorder(&self) -> &SubstrateRecorder<T>;229 fn into_recorder(self) -> SubstrateRecorder<T>;230}231232233pub fn call<234 T: Config,235 C: evm_coder::Call + evm_coder::Weighted,236 E: evm_coder::Callable<C> + WithRecorder<T>,237 H: PrecompileHandle,238>(239 handle: &mut H,240 mut e: E,241) -> Option<PrecompileResult> {242 let result = call_internal(243 handle.context().caller,244 &mut e,245 handle.context().apparent_value,246 handle.input(),247 );248 e.into_recorder().evm_to_precompile_output(handle, result)249}250251fn call_internal<252 T: Config,253 C: evm_coder::Call + evm_coder::Weighted,254 E: evm_coder::Callable<C> + WithRecorder<T>,255>(256 caller: H160,257 e: &mut E,258 value: value,259 input: &[u8],260) -> evm_coder::execution::Result<Option<AbiWriter>> {261 let (selector, mut reader) = AbiReader::new_call(input)?;262 let call = C::parse(selector, &mut reader)?;263 if call.is_none() {264 let selector = u32::from_be_bytes(selector);265 return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());266 }267 let call = call.unwrap();268269 let dispatch_info = call.weight();270 e.recorder()271 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;272273 match e.call(Msg {274 call,275 caller,276 value,277 }) {278 Ok(v) => {279 let unspent = v.post_info.calc_unspent(&dispatch_info);280 e.recorder()281 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));282 Ok(Some(v.data))283 }284 Err(v) => {285 let unspent = v.post_info.calc_unspent(&dispatch_info);286 e.recorder()287 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));288 Err(v.data)289 }290 }291}