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 Jul 20, 2023
1 parent 3c75079 commit 6fad7d4
Show file tree
Hide file tree
Showing 8 changed files with 179 additions and 113 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 @@ -499,7 +501,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 @@ -510,13 +513,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)?;

let priority = match (
transaction_data.gas_price,
transaction_data.max_fee_per_gas,
Expand Down Expand Up @@ -875,7 +884,8 @@ impl<T: Config> Pallet<T> {
_ => (None, None),
};

let _ = CheckEvmTransaction::<InvalidTransactionWrapper>::new(
let mut v = CheckEvmTransaction::<InvalidTransactionWrapper>::new(
who,
CheckEvmTransactionConfig {
evm_config: T::config(),
block_gas_limit: T::BlockGasLimit::get(),
Expand All @@ -886,13 +896,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::InvalidEvmTransactionError>> = ();
}

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::InvalidEvmTransactionError>> = ();
}

pub(crate) struct MockHandle {
Expand Down
26 changes: 21 additions & 5 deletions frame/evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +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,
InvalidEvmTransactionError, IsPrecompileResult, LinearCostPrecompile, Log, Precompile,
PrecompileFailure, PrecompileHandle, PrecompileOutput, PrecompileResult, PrecompileSet,
Vicinity,
Account, CallInfo, CheckEvmTransaction, CreateInfo, ExecutionInfoV2 as ExecutionInfo,
FeeCalculator, InvalidEvmTransactionError, IsPrecompileResult, LinearCostPrecompile, Log,
Precompile, PrecompileFailure, PrecompileHandle, PrecompileOutput, PrecompileResult,
PrecompileSet, Vicinity,
};

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

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

#[pallet::call]
Expand Down Expand Up @@ -565,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 @@ -1047,3 +1053,13 @@ impl<T> OnCreate<T> for Tuple {
)*)
}
}

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

impl<T: Config, E: From<InvalidEvmTransactionError>> OnCheckEvmTransaction<T, E> for () {
fn on_check_evm_transaction(_v: &mut CheckEvmTransaction<E>, _origin: &H160) -> Result<(), E> {
Ok(())
}
}
4 changes: 3 additions & 1 deletion frame/evm/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ use sp_std::{boxed::Box, prelude::*, str::FromStr};

use crate::{
EnsureAddressNever, EnsureAddressRoot, FeeCalculator, IdentityAddressMapping,
IsPrecompileResult, Precompile, PrecompileHandle, PrecompileResult, PrecompileSet,
InvalidEvmTransactionError, IsPrecompileResult, Precompile, PrecompileHandle, PrecompileResult,
PrecompileSet,
};

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<InvalidEvmTransactionError>> = ();
}

/// 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 @@ -371,8 +370,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 @@ -384,7 +385,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 @@ -394,11 +395,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 6fad7d4

Please sign in to comment.