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 sp_std::{cell::RefCell, vec::Vec, rc::Rc};56 use sp_core::{H160};57 use frame_support::{pallet_prelude::*, traits::PalletInfo};58 use frame_system::pallet_prelude::*;5960 61 62 63 64 65 #[pallet::error]66 pub enum Error<T> {67 OutOfGas,68 OutOfFund,69 }7071 #[pallet::config]72 pub trait Config: frame_system::Config {73 type GasWeightMapping: pallet_evm::GasWeightMapping;74 }7576 #[pallet::pallet]77 pub struct Pallet<T>(_);7879 #[pallet::call]80 impl<T: Config> Pallet<T> {81 #[pallet::weight(0)]82 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {83 let _sender = ensure_signed(origin)?;84 Ok(())85 }86 }87}888990pub const G_SLOAD_WORD: u64 = 800;91pub const G_SSTORE_WORD: u64 = 20000;9293pub struct GasCallsBudget<'r, T: Config> {94 recorder: &'r SubstrateRecorder<T>,95 gas_per_call: u64,96}97impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {98 fn consume_custom(&self, calls: u32) -> bool {99 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);100 if overflown {101 return false;102 }103 self.recorder.consume_gas(gas).is_ok()104 }105}106107#[derive(Default)]108pub struct SubstrateRecorder<T: Config> {109 initial_gas: u64,110 gas_limit: RefCell<u64>,111 _phantom: PhantomData<*const T>,112}113114impl<T: Config> SubstrateRecorder<T> {115 pub fn new(gas_limit: u64) -> Self {116 Self {117 initial_gas: gas_limit,118 gas_limit: RefCell::new(gas_limit),119 _phantom: PhantomData,120 }121 }122123 pub fn gas_left(&self) -> u64 {124 *self.gas_limit.borrow()125 }126 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {127 GasCallsBudget {128 recorder: self,129 gas_per_call,130 }131 }132 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {133 GasCallsBudget {134 recorder: self,135 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),136 }137 }138 pub fn consume_sload_sub(&self) -> DispatchResult {139 self.consume_gas_sub(G_SLOAD_WORD)140 }141 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {142 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))143 }144 pub fn consume_sstore_sub(&self) -> DispatchResult {145 self.consume_gas_sub(G_SSTORE_WORD)146 }147 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {148 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);149 let mut gas_limit = self.gas_limit.borrow_mut();150 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);151 *gas_limit -= gas;152 Ok(())153 }154155 pub fn consume_sload(&self) -> Result<()> {156 self.consume_gas(G_SLOAD_WORD)157 }158 pub fn consume_sstore(&self) -> Result<()> {159 self.consume_gas(G_SSTORE_WORD)160 }161 pub fn consume_gas(&self, gas: u64) -> Result<()> {162 if gas == u64::MAX {163 return Err(execution::Error::Error(ExitError::OutOfGas));164 }165 let mut gas_limit = self.gas_limit.borrow_mut();166 if gas > *gas_limit {167 return Err(execution::Error::Error(ExitError::OutOfGas));168 }169 *gas_limit -= gas;170 Ok(())171 }172 pub fn return_gas(&self, gas: u64) {173 let mut gas_limit = self.gas_limit.borrow_mut();174 *gas_limit += gas;175 }176177 pub fn evm_to_precompile_output(178 self,179 result: evm_coder::execution::Result<Option<AbiWriter>>,180 ) -> Option<PrecompileResult> {181 use evm_coder::execution::Error;182 Some(match result {183 Ok(Some(v)) => Ok(PrecompileOutput {184 exit_status: ExitSucceed::Returned,185 cost: self.initial_gas - self.gas_left(),186 187 logs: sp_std::vec![],188 output: v.finish(),189 }),190 Ok(None) => return None,191 Err(Error::Revert(e)) => {192 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));193 (&e as &str).abi_write(&mut writer);194195 Err(PrecompileFailure::Revert {196 exit_status: ExitRevert::Reverted,197 cost: self.initial_gas - self.gas_left(),198 output: writer.finish(),199 })200 }201 Err(Error::Fatal(f)) => Err(f.into()),202 Err(Error::Error(e)) => Err(e.into()),203 })204 }205}206207pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {208 use evm_coder::execution::Error as ExError;209 match err {210 DispatchError::Module(ModuleError { index, error, .. })211 if index212 == T::PalletInfo::index::<Pallet<T>>()213 .expect("evm-coder-substrate is a pallet, which should be added to runtime")214 as u8 =>215 {216 let mut read = &error as &[u8];217 match Error::<T>::decode(&mut read) {218 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),219 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),220 _ => unreachable!("this pallet only defines two possible errors"),221 }222 }223 DispatchError::Module(ModuleError {224 message: Some(msg), ..225 }) => ExError::Revert(msg.into()),226 DispatchError::Module(ModuleError { index, error, .. }) => {227 ExError::Revert(format!("error {:?} in pallet {}", error, index))228 }229 e => ExError::Revert(format!("substrate error: {:?}", e)),230 }231}232233pub trait WithRecorder<T: Config> {234 fn recorder(&self) -> &SubstrateRecorder<T>;235 fn into_recorder(self) -> SubstrateRecorder<T>;236}237238239pub fn call<240 T: Config,241 C: evm_coder::Call + evm_coder::Weighted,242 E: evm_coder::Callable<C> + WithRecorder<T>,243>(244 caller: H160,245 mut e: E,246 value: value,247 input: &[u8],248) -> Option<PrecompileResult> {249 let result = call_internal(caller, &mut e, value, input);250 e.into_recorder().evm_to_precompile_output(result)251}252253fn call_internal<254 T: Config,255 C: evm_coder::Call + evm_coder::Weighted,256 E: evm_coder::Callable<C> + WithRecorder<T>,257>(258 caller: H160,259 e: &mut E,260 value: value,261 input: &[u8],262) -> evm_coder::execution::Result<Option<AbiWriter>> {263 let (selector, mut reader) = AbiReader::new_call(input)?;264 let call = C::parse(selector, &mut reader)?;265 if call.is_none() {266 return Ok(None);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}