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_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 fn generate_transaction() -> TransactionV2 {95 use ethereum::{TransactionV0, TransactionAction, TransactionSignature};96 TransactionV2::Legacy(TransactionV0 {97 nonce: 0.into(),98 gas_price: 0.into(),99 gas_limit: 0.into(),100 action: TransactionAction::Call(H160([0; 20])),101 value: 0.into(),102 103 input: Vec::from([0, 0, 0, 0]),104 105 signature: TransactionSignature::new(27, H256([0x88; 32]), H256([0x88; 32])).unwrap(),106 })107}108109pub struct GasCallsBudget<'r, T: Config> {110 recorder: &'r SubstrateRecorder<T>,111 gas_per_call: u64,112}113impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {114 fn consume_custom(&self, calls: u32) -> bool {115 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);116 if overflown {117 return false;118 }119 self.recorder.consume_gas(gas).is_ok()120 }121}122123#[derive(Default)]124pub struct SubstrateRecorder<T: Config> {125 contract: H160,126 logs: RefCell<Vec<MaybeMirroredLog>>,127 initial_gas: u64,128 gas_limit: RefCell<u64>,129 _phantom: PhantomData<*const T>,130}131132impl<T: Config> SubstrateRecorder<T> {133 pub fn new(contract: H160, gas_limit: u64) -> Self {134 Self {135 contract,136 logs: RefCell::new(Vec::new()),137 initial_gas: gas_limit,138 gas_limit: RefCell::new(gas_limit),139 _phantom: PhantomData,140 }141 }142143 pub fn is_empty(&self) -> bool {144 self.logs.borrow().is_empty()145 }146 147 pub fn log_direct(&self, log: impl ToLog) {148 self.logs149 .borrow_mut()150 .push(MaybeMirroredLog::direct(log.to_log(self.contract)))151 }152 153 pub fn log_mirrored(&self, log: impl ToLog) {154 self.logs155 .borrow_mut()156 .push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))157 }158 pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {159 self.logs.into_inner()160 }161162 pub fn gas_left(&self) -> u64 {163 *self.gas_limit.borrow()164 }165 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {166 GasCallsBudget {167 recorder: self,168 gas_per_call,169 }170 }171 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {172 GasCallsBudget {173 recorder: self,174 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),175 }176 }177 pub fn consume_sload_sub(&self) -> DispatchResult {178 self.consume_gas_sub(G_SLOAD_WORD)179 }180 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {181 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))182 }183 pub fn consume_sstore_sub(&self) -> DispatchResult {184 self.consume_gas_sub(G_SSTORE_WORD)185 }186 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {187 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);188 let mut gas_limit = self.gas_limit.borrow_mut();189 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);190 *gas_limit -= gas;191 Ok(())192 }193194 pub fn consume_sload(&self) -> Result<()> {195 self.consume_gas(G_SLOAD_WORD)196 }197 pub fn consume_sstore(&self) -> Result<()> {198 self.consume_gas(G_SSTORE_WORD)199 }200 pub fn consume_gas(&self, gas: u64) -> Result<()> {201 if gas == u64::MAX {202 return Err(execution::Error::Error(ExitError::OutOfGas));203 }204 let mut gas_limit = self.gas_limit.borrow_mut();205 if gas > *gas_limit {206 return Err(execution::Error::Error(ExitError::OutOfGas));207 }208 *gas_limit -= gas;209 Ok(())210 }211 pub fn return_gas(&self, gas: u64) {212 let mut gas_limit = self.gas_limit.borrow_mut();213 *gas_limit += gas;214 }215216 pub fn evm_to_precompile_output(217 self,218 result: evm_coder::execution::Result<Option<AbiWriter>>,219 ) -> Option<PrecompileResult> {220 use evm_coder::execution::Error;221 Some(match result {222 Ok(Some(v)) => Ok(PrecompileOutput {223 exit_status: ExitSucceed::Returned,224 cost: self.initial_gas - self.gas_left(),225 226 logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),227 output: v.finish(),228 }),229 Ok(None) => return None,230 Err(Error::Revert(e)) => {231 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));232 (&e as &str).abi_write(&mut writer);233234 Err(PrecompileFailure::Revert {235 exit_status: ExitRevert::Reverted,236 cost: self.initial_gas - self.gas_left(),237 output: writer.finish(),238 })239 }240 Err(Error::Fatal(f)) => Err(f.into()),241 Err(Error::Error(e)) => Err(e.into()),242 })243 }244245 pub fn submit_logs(self) {246 let logs = self.retrieve_logs();247 if logs.is_empty() {248 return;249 }250 T::EthereumTransactionSender::submit_logs_transaction(251 Default::default(),252 generate_transaction(),253 logs,254 )255 }256}257258pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {259 use evm_coder::execution::Error as ExError;260 match err {261 DispatchError::Module(ModuleError { index, error, .. })262 if index263 == T::PalletInfo::index::<Pallet<T>>()264 .expect("evm-coder-substrate is a pallet, which should be added to runtime")265 as u8 =>266 {267 match error {268 v if v == Error::<T>::OutOfGas.as_u8() => ExError::Error(ExitError::OutOfGas),269 v if v == Error::<T>::OutOfFund.as_u8() => ExError::Error(ExitError::OutOfFund),270 _ => unreachable!("this pallet only defines two possible errors"),271 }272 }273 DispatchError::Module(ModuleError {274 message: Some(msg), ..275 }) => ExError::Revert(msg.into()),276 DispatchError::Module(ModuleError { index, error, .. }) => {277 ExError::Revert(format!("error {} in pallet {}", error, index))278 }279 e => ExError::Revert(format!("substrate error: {:?}", e)),280 }281}282283pub trait WithRecorder<T: Config> {284 fn recorder(&self) -> &SubstrateRecorder<T>;285 fn into_recorder(self) -> SubstrateRecorder<T>;286}287288289pub fn call<290 T: Config,291 C: evm_coder::Call + evm_coder::Weighted,292 E: evm_coder::Callable<C> + WithRecorder<T>,293>(294 caller: H160,295 mut e: E,296 value: value,297 input: &[u8],298) -> Option<PrecompileResult> {299 let result = call_internal(caller, &mut e, value, input);300 e.into_recorder().evm_to_precompile_output(result)301}302303fn call_internal<304 T: Config,305 C: evm_coder::Call + evm_coder::Weighted,306 E: evm_coder::Callable<C> + WithRecorder<T>,307>(308 caller: H160,309 e: &mut E,310 value: value,311 input: &[u8],312) -> evm_coder::execution::Result<Option<AbiWriter>> {313 let (selector, mut reader) = AbiReader::new_call(input)?;314 let call = C::parse(selector, &mut reader)?;315 if call.is_none() {316 return Ok(None);317 }318 let call = call.unwrap();319320 let dispatch_info = call.weight();321 e.recorder()322 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;323324 match e.call(Msg {325 call,326 caller,327 value,328 }) {329 Ok(v) => {330 let unspent = v.post_info.calc_unspent(&dispatch_info);331 e.recorder()332 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));333 Ok(Some(v.data))334 }335 Err(v) => {336 let unspent = v.post_info.calc_unspent(&dispatch_info);337 e.recorder()338 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));339 Err(v.data)340 }341 }342}