Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: OnCheckEvmTransaction callback #1106

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 27 additions & 15 deletions frame/ethereum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ use fp_evm::{
};
pub use fp_rpc::TransactionStatus;
use fp_storage::{EthereumStorageSchema, PALLET_ETHEREUM_SCHEMA};
use pallet_evm::{BlockHashMapping, FeeCalculator, GasWeightMapping, Runner};
use pallet_evm::{
BlockHashMapping, FeeCalculator, GasWeightMapping, OnCheckEvmTransaction, Runner,
};

#[derive(Clone, Eq, PartialEq, RuntimeDebug)]
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]
Expand Down Expand Up @@ -494,7 +496,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::new(
who.clone(),
CheckEvmTransactionConfig {
evm_config: T::config(),
block_gas_limit: T::BlockGasLimit::get(),
Expand All @@ -505,12 +508,16 @@ impl<T: Config> Pallet<T> {
transaction_data.clone().into(),
weight_limit,
proof_size_base_cost,
)
.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)?;
);

T::OnCheckEvmTransaction::on_check_evm_transaction(&mut v, &origin)
.map_err(|e| InvalidTransactionWrapper::from(e).0)?;

v.validate_in_pool()
.and_then(|v| v.with_chain_id())
.and_then(|v| v.with_base_fee())
.and_then(|v| v.with_balance())
.map_err(|e| InvalidTransactionWrapper::from(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 @@ -862,7 +869,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::new(
who,
CheckEvmTransactionConfig {
evm_config: T::config(),
block_gas_limit: T::BlockGasLimit::get(),
Expand All @@ -873,12 +881,16 @@ impl<T: Config> Pallet<T> {
transaction_data.into(),
weight_limit,
proof_size_base_cost,
)
.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))?;
);

T::OnCheckEvmTransaction::on_check_evm_transaction(&mut v, &origin)
.map_err(|e| TransactionValidityError::Invalid(InvalidTransactionWrapper::from(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(InvalidTransactionWrapper::from(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 @@ -177,6 +177,7 @@ impl pallet_evm::Config for Test {
type SuicideQuickClearLimit = SuicideQuickClearLimit;
type Timestamp = Timestamp;
type WeightInfo = ();
type OnCheckEvmTransaction = ();
}

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 @@ -157,6 +157,7 @@ impl pallet_evm::Config for Test {
type GasLimitPovSizeRatio = ();
type Timestamp = Timestamp;
type WeightInfo = ();
type OnCheckEvmTransaction = ();
}

pub(crate) struct MockHandle {
Expand Down
35 changes: 31 additions & 4 deletions frame/evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,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 @@ -182,6 +183,9 @@ pub mod pallet {
fn config() -> &'static EvmConfig {
&SHANGHAI_CONFIG
}

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

#[pallet::call]
Expand Down Expand Up @@ -581,7 +585,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 @@ -1089,3 +1093,26 @@ impl<T> OnCreate<T> for Tuple {
)*)
}
}

/// Implements additional EVM transaction validation logic
pub trait OnCheckEvmTransaction<T: Config> {
/// Validate EVM transaction.
///
/// This method should be called before frontier's built-in validations.
///
/// - `v`: Transaction data to validate. Method can modify transaction data before frontier's built-in validations.
fn on_check_evm_transaction(
fairax marked this conversation as resolved.
Show resolved Hide resolved
v: &mut CheckEvmTransaction,
origin: &H160,
) -> Result<(), TransactionValidationError>;
}

/// Implementation for () does not specify any additional validations.
impl<T: Config> OnCheckEvmTransaction<T> for () {
fn on_check_evm_transaction(
_v: &mut CheckEvmTransaction,
_origin: &H160,
) -> Result<(), TransactionValidationError> {
Ok(())
}
}
1 change: 1 addition & 0 deletions frame/evm/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ impl crate::Config for Test {
type SuicideQuickClearLimit = SuicideQuickClearLimit;
type Timestamp = Timestamp;
type WeightInfo = ();
type OnCheckEvmTransaction = ();
}

/// Example PrecompileSet with only Identity precompile.
Expand Down
38 changes: 25 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::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,22 @@ 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::on_check_evm_transaction(&mut v, &source).map_err(|error| {
RunnerError {
error: error.into(),
weight,
}
})?;

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

Expand Down
1 change: 1 addition & 0 deletions precompiles/tests-external/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ impl pallet_evm::Config for Runtime {
type Runner = pallet_evm::runner::stack::Runner<Self>;
type OnChargeTransaction = ();
type OnCreate = ();
type OnCheckEvmTransaction = ();
type FindAuthor = ();
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type SuicideQuickClearLimit = SuicideQuickClearLimit;
Expand Down
Loading
Loading