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,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 result: evm_coder::execution::Result<Option<AbiWriter>>,175 ) -> Option<PrecompileResult> {176 use evm_coder::execution::Error;177 Some(match result {178 Ok(Some(v)) => Ok(PrecompileOutput {179 exit_status: ExitSucceed::Returned,180 cost: self.initial_gas - self.gas_left(),181 182 logs: sp_std::vec![],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 cost: self.initial_gas - self.gas_left(),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) -> evm_coder::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>(239 caller: H160,240 mut e: E,241 value: value,242 input: &[u8],243) -> Option<PrecompileResult> {244 let result = call_internal(caller, &mut e, value, input);245 e.into_recorder().evm_to_precompile_output(result)246}247248fn call_internal<249 T: Config,250 C: evm_coder::Call + evm_coder::Weighted,251 E: evm_coder::Callable<C> + WithRecorder<T>,252>(253 caller: H160,254 e: &mut E,255 value: value,256 input: &[u8],257) -> evm_coder::execution::Result<Option<AbiWriter>> {258 let (selector, mut reader) = AbiReader::new_call(input)?;259 let call = C::parse(selector, &mut reader)?;260 if call.is_none() {261 return Ok(None);262 }263 let call = call.unwrap();264265 let dispatch_info = call.weight();266 e.recorder()267 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;268269 match e.call(Msg {270 call,271 caller,272 value,273 }) {274 Ok(v) => {275 let unspent = v.post_info.calc_unspent(&dispatch_info);276 e.recorder()277 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));278 Ok(Some(v.data))279 }280 Err(v) => {281 let unspent = v.post_info.calc_unspent(&dispatch_info);282 e.recorder()283 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));284 Err(v.data)285 }286 }287}