Skip to content

Commit

Permalink
feat: add OnCheckEvmTransaction callback
Browse files Browse the repository at this point in the history
  • Loading branch information
Grigoriy Simonov committed Sep 11, 2023
1 parent 71692bc commit e13a219
Show file tree
Hide file tree
Showing 8 changed files with 178 additions and 111 deletions.
38 changes: 27 additions & 11 deletions frame/ethereum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ use frame_support::{
weights::Weight,
};
use frame_system::{pallet_prelude::OriginFor, CheckWeight, WeightInfo};
use pallet_evm::{BlockHashMapping, FeeCalculator, GasWeightMapping, Runner};
use pallet_evm::{
BlockHashMapping, FeeCalculator, GasWeightMapping, OnCheckEvmTransaction, Runner,
};
use sp_runtime::{
generic::DigestItem,
traits::{DispatchInfoOf, Dispatchable, One, Saturating, UniqueSaturatedInto, Zero},
Expand Down Expand Up @@ -490,7 +492,8 @@ impl<T: Config> Pallet<T> {
let (base_fee, _) = T::FeeCalculator::min_gas_price();
let (who, _) = pallet_evm::Pallet::<T>::account_basic(&origin);

let _ = CheckEvmTransaction::<InvalidTransactionWrapper>::new(
let mut v = CheckEvmTransaction::<InvalidTransactionWrapper>::new(
who.clone(),
CheckEvmTransactionConfig {
evm_config: T::config(),
block_gas_limit: T::BlockGasLimit::get(),
Expand All @@ -501,13 +504,19 @@ impl<T: Config> Pallet<T> {
transaction_data.clone().into(),
weight_limit,
proof_size_base_cost,
);

T::OnCheckEvmTransaction::<InvalidTransactionWrapper>::on_check_evm_transaction(
&mut v, &origin,
)
.validate_in_pool_for(&who)
.and_then(|v| v.with_chain_id())
.and_then(|v| v.with_base_fee())
.and_then(|v| v.with_balance_for(&who))
.map_err(|e| e.0)?;

v.validate_in_pool_for()
.and_then(|v| v.with_chain_id())
.and_then(|v| v.with_base_fee())
.and_then(|v| v.with_balance())
.map_err(|e| e.0)?;

// EIP-3607: https://eips.ethereum.org/EIPS/eip-3607
// Do not allow transactions for which `tx.sender` has any code deployed.
//
Expand Down Expand Up @@ -858,7 +867,8 @@ impl<T: Config> Pallet<T> {
let (base_fee, _) = T::FeeCalculator::min_gas_price();
let (who, _) = pallet_evm::Pallet::<T>::account_basic(&origin);

let _ = CheckEvmTransaction::<InvalidTransactionWrapper>::new(
let mut v = CheckEvmTransaction::<InvalidTransactionWrapper>::new(
who,
CheckEvmTransactionConfig {
evm_config: T::config(),
block_gas_limit: T::BlockGasLimit::get(),
Expand All @@ -869,13 +879,19 @@ impl<T: Config> Pallet<T> {
transaction_data.into(),
weight_limit,
proof_size_base_cost,
);

T::OnCheckEvmTransaction::<InvalidTransactionWrapper>::on_check_evm_transaction(
&mut v, &origin,
)
.validate_in_block_for(&who)
.and_then(|v| v.with_chain_id())
.and_then(|v| v.with_base_fee())
.and_then(|v| v.with_balance_for(&who))
.map_err(|e| TransactionValidityError::Invalid(e.0))?;

v.validate_in_block()
.and_then(|v| v.with_chain_id())
.and_then(|v| v.with_base_fee())
.and_then(|v| v.with_balance())
.map_err(|e| TransactionValidityError::Invalid(e.0))?;

Ok(())
}

Expand Down
1 change: 1 addition & 0 deletions frame/ethereum/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ impl pallet_evm::Config for Test {
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type Timestamp = Timestamp;
type WeightInfo = ();
type OnCheckEvmTransaction<E: From<pallet_evm::TransactionValidationError>> = ();
}

parameter_types! {
Expand Down
1 change: 1 addition & 0 deletions frame/evm/precompile/dispatch/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ impl pallet_evm::Config for Test {
type GasLimitPovSizeRatio = ();
type Timestamp = Timestamp;
type WeightInfo = ();
type OnCheckEvmTransaction<E: From<pallet_evm::TransactionValidationError>> = ();
}

pub(crate) struct MockHandle {
Expand Down
25 changes: 21 additions & 4 deletions frame/evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,10 @@ use sp_std::{cmp::min, collections::btree_map::BTreeMap, vec::Vec};
use fp_account::AccountId20;
use fp_evm::GenesisAccount;
pub use fp_evm::{
Account, CallInfo, CreateInfo, ExecutionInfoV2 as ExecutionInfo, FeeCalculator,
IsPrecompileResult, LinearCostPrecompile, Log, Precompile, PrecompileFailure, PrecompileHandle,
PrecompileOutput, PrecompileResult, PrecompileSet, TransactionValidationError, Vicinity,
Account, CallInfo, CheckEvmTransaction, CreateInfo, ExecutionInfoV2 as ExecutionInfo,
FeeCalculator, IsPrecompileResult, LinearCostPrecompile, Log, Precompile, PrecompileFailure,
PrecompileHandle, PrecompileOutput, PrecompileResult, PrecompileSet,
TransactionValidationError, Vicinity,
};

pub use self::{
Expand Down Expand Up @@ -176,6 +177,12 @@ pub mod pallet {
fn config() -> &'static EvmConfig {
&SHANGHAI_CONFIG
}

// Called when transaction info for validation is created
type OnCheckEvmTransaction<E: From<TransactionValidationError>>: OnCheckEvmTransaction<
Self,
E,
>;
}

#[pallet::call]
Expand Down Expand Up @@ -564,7 +571,7 @@ pub type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;

/// Type alias for negative imbalance during fees
type NegativeImbalanceOf<C, T> =
pub type NegativeImbalanceOf<C, T> =
<C as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;

#[derive(
Expand Down Expand Up @@ -1046,3 +1053,13 @@ impl<T> OnCreate<T> for Tuple {
)*)
}
}

pub trait OnCheckEvmTransaction<T: Config, E: From<TransactionValidationError>> {
fn on_check_evm_transaction(v: &mut CheckEvmTransaction<E>, origin: &H160) -> Result<(), E>;
}

impl<T: Config, E: From<TransactionValidationError>> OnCheckEvmTransaction<T, E> for () {
fn on_check_evm_transaction(_v: &mut CheckEvmTransaction<E>, _origin: &H160) -> Result<(), E> {
Ok(())
}
}
2 changes: 2 additions & 0 deletions frame/evm/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use sp_std::{boxed::Box, prelude::*, str::FromStr};
use crate::{
EnsureAddressNever, EnsureAddressRoot, FeeCalculator, IdentityAddressMapping,
IsPrecompileResult, Precompile, PrecompileHandle, PrecompileResult, PrecompileSet,
TransactionValidationError,
};

type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
Expand Down Expand Up @@ -162,6 +163,7 @@ impl crate::Config for Test {
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type Timestamp = Timestamp;
type WeightInfo = ();
type OnCheckEvmTransaction<E: From<TransactionValidationError>> = ();
}

/// Example PrecompileSet with only Identity precompile.
Expand Down
31 changes: 18 additions & 13 deletions frame/evm/src/runner/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@

//! EVM stack-based runner.

use crate::{
runner::Runner as RunnerT, AccountCodes, AccountCodesMetadata, AccountStorages, AddressMapping,
BalanceOf, BlockHashMapping, Config, Error, Event, FeeCalculator, OnChargeEVMTransaction,
OnCheckEvmTransaction, OnCreate, Pallet, RunnerError,
};
use evm::{
backend::Backend as BackendT,
executor::stack::{Accessed, StackExecutor, StackState as StackStateT, StackSubstateMetadata},
Expand Down Expand Up @@ -47,12 +52,6 @@ use fp_evm::{
ACCOUNT_STORAGE_PROOF_SIZE, IS_EMPTY_CHECK_PROOF_SIZE, WRITE_PROOF_SIZE,
};

use crate::{
runner::Runner as RunnerT, AccountCodes, AccountCodesMetadata, AccountStorages, AddressMapping,
BalanceOf, BlockHashMapping, Config, Error, Event, FeeCalculator, OnChargeEVMTransaction,
OnCreate, Pallet, RunnerError,
};

#[cfg(feature = "forbid-evm-reentrancy")]
environmental::thread_local_impl!(static IN_EVM: environmental::RefCell<bool> = environmental::RefCell::new(false));

Expand Down Expand Up @@ -376,8 +375,10 @@ where
let (base_fee, mut weight) = T::FeeCalculator::min_gas_price();
let (source_account, inner_weight) = Pallet::<T>::account_basic(&source);
weight = weight.saturating_add(inner_weight);
let nonce = nonce.unwrap_or(source_account.nonce);

let _ = fp_evm::CheckEvmTransaction::<Self::Error>::new(
let mut v = fp_evm::CheckEvmTransaction::<Self::Error>::new(
source_account,
fp_evm::CheckEvmTransactionConfig {
evm_config,
block_gas_limit: T::BlockGasLimit::get(),
Expand All @@ -389,7 +390,7 @@ where
chain_id: Some(T::ChainId::get()),
to: target,
input,
nonce: nonce.unwrap_or(source_account.nonce),
nonce,
gas_limit: gas_limit.into(),
gas_price: None,
max_fee_per_gas,
Expand All @@ -399,11 +400,15 @@ where
},
weight_limit,
proof_size_base_cost,
)
.validate_in_block_for(&source_account)
.and_then(|v| v.with_base_fee())
.and_then(|v| v.with_balance_for(&source_account))
.map_err(|error| RunnerError { error, weight })?;
);

T::OnCheckEvmTransaction::<Error<T>>::on_check_evm_transaction(&mut v, &source)
.map_err(|error| RunnerError { error, weight })?;

v.validate_in_block()
.and_then(|v| v.with_base_fee())
.and_then(|v| v.with_balance())
.map_err(|error| RunnerError { error, weight })?;
Ok(())
}

Expand Down
Loading

0 comments on commit e13a219

Please sign in to comment.