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 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, runner::stack::MaybeMirroredLog,36};37use ethereum::TransactionV2;38use sp_core::{H160, H256};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_support::{pallet_prelude::*, traits::PalletInfo};59 use frame_system::pallet_prelude::*;6061 62 63 64 65 66 #[pallet::error]67 pub enum Error<T> {68 OutOfGas,69 OutOfFund,70 }7172 #[pallet::config]73 pub trait Config: frame_system::Config {74 type EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;75 type GasWeightMapping: pallet_evm::GasWeightMapping;76 }7778 #[pallet::pallet]79 pub struct Pallet<T>(_);8081 #[pallet::call]82 impl<T: Config> Pallet<T> {83 #[pallet::weight(0)]84 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {85 let _sender = ensure_signed(origin)?;86 Ok(())87 }88 }89}909192pub const G_SLOAD_WORD: u64 = 800;93pub const G_SSTORE_WORD: u64 = 20000;9495pub fn generate_transaction() -> TransactionV2 {96 use ethereum::{TransactionV0, TransactionAction, TransactionSignature};97 TransactionV2::Legacy(TransactionV0 {98 nonce: 0.into(),99 gas_price: 0.into(),100 gas_limit: 0.into(),101 action: TransactionAction::Call(H160([0; 20])),102 value: 0.into(),103 104 input: Vec::from([0, 0, 0, 0]),105 106 signature: TransactionSignature::new(27, H256([0x88; 32]), H256([0x88; 32])).unwrap(),107 })108}109110pub struct GasCallsBudget<'r, T: Config> {111 recorder: &'r SubstrateRecorder<T>,112 gas_per_call: u64,113}114impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {115 fn consume_custom(&self, calls: u32) -> bool {116 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);117 if overflown {118 return false;119 }120 self.recorder.consume_gas(gas).is_ok()121 }122}123124#[derive(Default)]125pub struct SubstrateRecorder<T: Config> {126 contract: H160,127 logs: RefCell<Vec<MaybeMirroredLog>>,128 initial_gas: u64,129 gas_limit: RefCell<u64>,130 _phantom: PhantomData<*const T>,131}132133impl<T: Config> SubstrateRecorder<T> {134 pub fn new(contract: H160, gas_limit: u64) -> Self {135 Self {136 contract,137 logs: RefCell::new(Vec::new()),138 initial_gas: gas_limit,139 gas_limit: RefCell::new(gas_limit),140 _phantom: PhantomData,141 }142 }143144 pub fn is_empty(&self) -> bool {145 self.logs.borrow().is_empty()146 }147 148 pub fn log_direct(&self, log: impl ToLog) {149 self.logs150 .borrow_mut()151 .push(MaybeMirroredLog::direct(log.to_log(self.contract)))152 }153 154 pub fn log_mirrored(&self, log: impl ToLog) {155 self.logs156 .borrow_mut()157 .push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))158 }159 pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {160 self.logs.into_inner()161 }162163 pub fn gas_left(&self) -> u64 {164 *self.gas_limit.borrow()165 }166 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {167 GasCallsBudget {168 recorder: self,169 gas_per_call,170 }171 }172 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {173 GasCallsBudget {174 recorder: self,175 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),176 }177 }178 pub fn consume_sload_sub(&self) -> DispatchResult {179 self.consume_gas_sub(G_SLOAD_WORD)180 }181 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {182 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))183 }184 pub fn consume_sstore_sub(&self) -> DispatchResult {185 self.consume_gas_sub(G_SSTORE_WORD)186 }187 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {188 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);189 let mut gas_limit = self.gas_limit.borrow_mut();190 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);191 *gas_limit -= gas;192 Ok(())193 }194195 pub fn consume_sload(&self) -> Result<()> {196 self.consume_gas(G_SLOAD_WORD)197 }198 pub fn consume_sstore(&self) -> Result<()> {199 self.consume_gas(G_SSTORE_WORD)200 }201 pub fn consume_gas(&self, gas: u64) -> Result<()> {202 if gas == u64::MAX {203 return Err(execution::Error::Error(ExitError::OutOfGas));204 }205 let mut gas_limit = self.gas_limit.borrow_mut();206 if gas > *gas_limit {207 return Err(execution::Error::Error(ExitError::OutOfGas));208 }209 *gas_limit -= gas;210 Ok(())211 }212 pub fn return_gas(&self, gas: u64) {213 let mut gas_limit = self.gas_limit.borrow_mut();214 *gas_limit += gas;215 }216217 pub fn evm_to_precompile_output(218 self,219 result: evm_coder::execution::Result<Option<AbiWriter>>,220 ) -> Option<PrecompileResult> {221 use evm_coder::execution::Error;222 Some(match result {223 Ok(Some(v)) => Ok(PrecompileOutput {224 exit_status: ExitSucceed::Returned,225 cost: self.initial_gas - self.gas_left(),226 227 logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),228 output: v.finish(),229 }),230 Ok(None) => return None,231 Err(Error::Revert(e)) => {232 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));233 (&e as &str).abi_write(&mut writer);234235 Err(PrecompileFailure::Revert {236 exit_status: ExitRevert::Reverted,237 cost: self.initial_gas - self.gas_left(),238 output: writer.finish(),239 })240 }241 Err(Error::Fatal(f)) => Err(f.into()),242 Err(Error::Error(e)) => Err(e.into()),243 })244 }245246 pub fn submit_logs(self) {247 let logs = self.retrieve_logs();248 if logs.is_empty() {249 return;250 }251 T::EthereumTransactionSender::submit_logs_transaction(252 Default::default(),253 generate_transaction(),254 logs,255 )256 }257}258259pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {260 use evm_coder::execution::Error as ExError;261 match err {262 DispatchError::Module(ModuleError { index, error, .. })263 if index264 == T::PalletInfo::index::<Pallet<T>>()265 .expect("evm-coder-substrate is a pallet, which should be added to runtime")266 as u8 =>267 {268 match error {269 v if v == Error::<T>::OutOfGas.as_u8() => ExError::Error(ExitError::OutOfGas),270 v if v == Error::<T>::OutOfFund.as_u8() => ExError::Error(ExitError::OutOfFund),271 _ => unreachable!("this pallet only defines two possible errors"),272 }273 }274 DispatchError::Module(ModuleError {275 message: Some(msg), ..276 }) => ExError::Revert(msg.into()),277 DispatchError::Module(ModuleError { index, error, .. }) => {278 ExError::Revert(format!("error {} in pallet {}", error, index))279 }280 e => ExError::Revert(format!("substrate error: {:?}", e)),281 }282}283284pub trait WithRecorder<T: Config> {285 fn recorder(&self) -> &SubstrateRecorder<T>;286 fn into_recorder(self) -> SubstrateRecorder<T>;287}288289290pub fn call<291 T: Config,292 C: evm_coder::Call + evm_coder::Weighted,293 E: evm_coder::Callable<C> + WithRecorder<T>,294>(295 caller: H160,296 mut e: E,297 value: value,298 input: &[u8],299) -> Option<PrecompileResult> {300 let result = call_internal(caller, &mut e, value, input);301 e.into_recorder().evm_to_precompile_output(result)302}303304fn call_internal<305 T: Config,306 C: evm_coder::Call + evm_coder::Weighted,307 E: evm_coder::Callable<C> + WithRecorder<T>,308>(309 caller: H160,310 e: &mut E,311 value: value,312 input: &[u8],313) -> evm_coder::execution::Result<Option<AbiWriter>> {314 let (selector, mut reader) = AbiReader::new_call(input)?;315 let call = C::parse(selector, &mut reader)?;316 if call.is_none() {317 return Ok(None);318 }319 let call = call.unwrap();320321 let dispatch_info = call.weight();322 e.recorder()323 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;324325 match e.call(Msg {326 call,327 caller,328 value,329 }) {330 Ok(v) => {331 let unspent = v.post_info.calc_unspent(&dispatch_info);332 e.recorder()333 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));334 Ok(Some(v.data))335 }336 Err(v) => {337 let unspent = v.post_info.calc_unspent(&dispatch_info);338 e.recorder()339 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));340 Err(v.data)341 }342 }343}