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;27use sp_std::vec::Vec;2829use codec::Decode;30use frame_support::pallet_prelude::DispatchError;31use frame_support::traits::PalletInfo;32use frame_support::{ensure, sp_runtime::ModuleError};33use up_data_structs::budget;34use pallet_evm::{35 ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,36 PrecompileResult, runner::stack::MaybeMirroredLog,37};38use sp_core::H160;39use pallet_ethereum::EthereumTransactionSender;40414243use evm_coder::{44 ToLog,45 abi::{AbiReader, AbiWrite, AbiWriter},46 execution::{self, Result},47 types::{Msg, value},48};4950pub use pallet::*;5152#[frame_support::pallet]53pub mod pallet {54 use super::*;5556 use frame_system::ensure_signed;57 pub use frame_support::dispatch::DispatchResult;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 EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;74 type GasWeightMapping: pallet_evm::GasWeightMapping;75 }7677 #[pallet::pallet]78 pub struct Pallet<T>(_);7980 #[pallet::call]81 impl<T: Config> Pallet<T> {82 #[pallet::weight(0)]83 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {84 let _sender = ensure_signed(origin)?;85 Ok(())86 }87 }88}899091pub const G_SLOAD_WORD: u64 = 800;92pub const G_SSTORE_WORD: u64 = 20000;9394pub struct GasCallsBudget<'r, T: Config> {95 recorder: &'r SubstrateRecorder<T>,96 gas_per_call: u64,97}98impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {99 fn consume_custom(&self, calls: u32) -> bool {100 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);101 if overflown {102 return false;103 }104 self.recorder.consume_gas(gas).is_ok()105 }106}107108#[derive(Default)]109pub struct SubstrateRecorder<T: Config> {110 contract: H160,111 logs: RefCell<Vec<MaybeMirroredLog>>,112 initial_gas: u64,113 gas_limit: RefCell<u64>,114 _phantom: PhantomData<*const T>,115}116117impl<T: Config> SubstrateRecorder<T> {118 pub fn new(contract: H160, gas_limit: u64) -> Self {119 Self {120 contract,121 logs: RefCell::new(Vec::new()),122 initial_gas: gas_limit,123 gas_limit: RefCell::new(gas_limit),124 _phantom: PhantomData,125 }126 }127128 pub fn is_empty(&self) -> bool {129 self.logs.borrow().is_empty()130 }131 132 pub fn log_direct(&self, log: impl ToLog) {133 self.logs134 .borrow_mut()135 .push(MaybeMirroredLog::direct(log.to_log(self.contract)))136 }137 138 pub fn log_mirrored(&self, log: impl ToLog) {139 self.logs140 .borrow_mut()141 .push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))142 }143 pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {144 self.logs.into_inner()145 }146147 pub fn gas_left(&self) -> u64 {148 *self.gas_limit.borrow()149 }150 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {151 GasCallsBudget {152 recorder: self,153 gas_per_call,154 }155 }156 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {157 GasCallsBudget {158 recorder: self,159 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),160 }161 }162 pub fn consume_sload_sub(&self) -> DispatchResult {163 self.consume_gas_sub(G_SLOAD_WORD)164 }165 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {166 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))167 }168 pub fn consume_sstore_sub(&self) -> DispatchResult {169 self.consume_gas_sub(G_SSTORE_WORD)170 }171 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {172 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);173 let mut gas_limit = self.gas_limit.borrow_mut();174 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);175 *gas_limit -= gas;176 Ok(())177 }178179 pub fn consume_sload(&self) -> Result<()> {180 self.consume_gas(G_SLOAD_WORD)181 }182 pub fn consume_sstore(&self) -> Result<()> {183 self.consume_gas(G_SSTORE_WORD)184 }185 pub fn consume_gas(&self, gas: u64) -> Result<()> {186 if gas == u64::MAX {187 return Err(execution::Error::Error(ExitError::OutOfGas));188 }189 let mut gas_limit = self.gas_limit.borrow_mut();190 if gas > *gas_limit {191 return Err(execution::Error::Error(ExitError::OutOfGas));192 }193 *gas_limit -= gas;194 Ok(())195 }196 pub fn return_gas(&self, gas: u64) {197 let mut gas_limit = self.gas_limit.borrow_mut();198 *gas_limit += gas;199 }200201 pub fn evm_to_precompile_output(202 self,203 result: evm_coder::execution::Result<Option<AbiWriter>>,204 ) -> Option<PrecompileResult> {205 use evm_coder::execution::Error;206 Some(match result {207 Ok(Some(v)) => Ok(PrecompileOutput {208 exit_status: ExitSucceed::Returned,209 cost: self.initial_gas - self.gas_left(),210 211 logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),212 output: v.finish(),213 }),214 Ok(None) => return None,215 Err(Error::Revert(e)) => {216 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));217 (&e as &str).abi_write(&mut writer);218219 Err(PrecompileFailure::Revert {220 exit_status: ExitRevert::Reverted,221 cost: self.initial_gas - self.gas_left(),222 output: writer.finish(),223 })224 }225 Err(Error::Fatal(f)) => Err(f.into()),226 Err(Error::Error(e)) => Err(e.into()),227 })228 }229230 pub fn submit_logs(self) {231 let logs = self.retrieve_logs();232 if logs.is_empty() {233 return;234 }235 T::EthereumTransactionSender::submit_logs_transaction(Default::default(), logs)236 }237}238239pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {240 use evm_coder::execution::Error as ExError;241 match err {242 DispatchError::Module(ModuleError { index, error, .. })243 if index244 == T::PalletInfo::index::<Pallet<T>>()245 .expect("evm-coder-substrate is a pallet, which should be added to runtime")246 as u8 =>247 {248 let mut read = &error as &[u8];249 match Error::<T>::decode(&mut read) {250 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),251 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),252 _ => unreachable!("this pallet only defines two possible errors"),253 }254 }255 DispatchError::Module(ModuleError {256 message: Some(msg), ..257 }) => ExError::Revert(msg.into()),258 DispatchError::Module(ModuleError { index, error, .. }) => {259 ExError::Revert(format!("error {:?} in pallet {}", error, index))260 }261 e => ExError::Revert(format!("substrate error: {:?}", e)),262 }263}264265pub trait WithRecorder<T: Config> {266 fn recorder(&self) -> &SubstrateRecorder<T>;267 fn into_recorder(self) -> SubstrateRecorder<T>;268}269270271pub fn call<272 T: Config,273 C: evm_coder::Call + evm_coder::Weighted,274 E: evm_coder::Callable<C> + WithRecorder<T>,275>(276 caller: H160,277 mut e: E,278 value: value,279 input: &[u8],280) -> Option<PrecompileResult> {281 let result = call_internal(caller, &mut e, value, input);282 e.into_recorder().evm_to_precompile_output(result)283}284285fn call_internal<286 T: Config,287 C: evm_coder::Call + evm_coder::Weighted,288 E: evm_coder::Callable<C> + WithRecorder<T>,289>(290 caller: H160,291 e: &mut E,292 value: value,293 input: &[u8],294) -> evm_coder::execution::Result<Option<AbiWriter>> {295 let (selector, mut reader) = AbiReader::new_call(input)?;296 let call = C::parse(selector, &mut reader)?;297 if call.is_none() {298 return Ok(None);299 }300 let call = call.unwrap();301302 let dispatch_info = call.weight();303 e.recorder()304 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;305306 match e.call(Msg {307 call,308 caller,309 value,310 }) {311 Ok(v) => {312 let unspent = v.post_info.calc_unspent(&dispatch_info);313 e.recorder()314 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));315 Ok(Some(v.data))316 }317 Err(v) => {318 let unspent = v.post_info.calc_unspent(&dispatch_info);319 e.recorder()320 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));321 Err(v.data)322 }323 }324}