Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 1 addition & 1 deletion substrate/frame/revive/src/call_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub struct CallSetup<T: Config> {
value: BalanceOf<T>,
data: Vec<u8>,
transient_storage_size: u32,
exec_config: ExecConfig,
exec_config: ExecConfig<T>,
}

impl<T> Default for CallSetup<T>
Expand Down
86 changes: 67 additions & 19 deletions substrate/frame/revive/src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ pub struct Stack<'a, T: Config, E> {
/// Transient storage used to store data, which is kept for the duration of a transaction.
transient_storage: TransientStorage<T>,
/// Global behavior determined by the creater of this stack.
exec_config: &'a ExecConfig,
exec_config: &'a ExecConfig<T>,
/// No executable is held by the struct but influences its behaviour.
_phantom: PhantomData<E>,
}
Expand Down Expand Up @@ -579,7 +579,7 @@ struct Frame<T: Config> {

/// This structure is used to represent the arguments in a delegate call frame in order to
/// distinguish who delegated the call and where it was delegated to.
struct DelegateInfo<T: Config> {
pub struct DelegateInfo<T: Config> {
/// The caller of the contract.
pub caller: Origin<T>,
/// The address of the contract the call was delegated to.
Expand Down Expand Up @@ -794,7 +794,7 @@ where
storage_meter: &mut storage::meter::Meter<T>,
value: U256,
input_data: Vec<u8>,
exec_config: &ExecConfig,
exec_config: &ExecConfig<T>,
) -> ExecResult {
let dest = T::AddressMapper::to_account_id(&dest);
if let Some((mut stack, executable)) = Stack::<'_, T, E>::new(
Expand All @@ -804,6 +804,7 @@ where
storage_meter,
value,
exec_config,
&input_data,
)? {
stack.run(executable, input_data).map(|_| stack.first_frame.last_frame_output)
} else {
Expand All @@ -819,14 +820,21 @@ where
);
});

let result = Self::transfer_from_origin(
&origin,
&origin,
&dest,
value,
storage_meter,
exec_config,
);
let result = if let Some(mock_answer) =
exec_config.mock_handler.as_ref().and_then(|handler| {
handler.mock_call(T::AddressMapper::to_address(&dest), &input_data, value)
}) {
Ok(mock_answer)
} else {
Self::transfer_from_origin(
&origin,
&origin,
&dest,
value,
storage_meter,
exec_config,
)
};

if_tracing(|t| match result {
Ok(ref output) => t.exit_child_span(&output, Weight::zero()),
Expand All @@ -852,7 +860,7 @@ where
value: U256,
input_data: Vec<u8>,
salt: Option<&[u8; 32]>,
exec_config: &ExecConfig,
exec_config: &ExecConfig<T>,
) -> Result<(H160, ExecReturnValue), ExecError> {
let deployer = T::AddressMapper::to_address(&origin);
let (mut stack, executable) = Stack::<'_, T, E>::new(
Expand All @@ -867,6 +875,7 @@ where
storage_meter,
value,
exec_config,
&input_data,
)?
.expect(FRAME_ALWAYS_EXISTS_ON_INSTANTIATE);
let address = T::AddressMapper::to_address(&stack.top_frame().account_id);
Expand All @@ -889,7 +898,7 @@ where
gas_meter: &'a mut GasMeter<T>,
storage_meter: &'a mut storage::meter::Meter<T>,
value: BalanceOf<T>,
exec_config: &'a ExecConfig,
exec_config: &'a ExecConfig<T>,
) -> (Self, E) {
let call = Self::new(
FrameArgs::Call {
Expand All @@ -902,6 +911,7 @@ where
storage_meter,
value.into(),
exec_config,
&Default::default(),
)
.unwrap()
.unwrap();
Expand All @@ -918,7 +928,8 @@ where
gas_meter: &'a mut GasMeter<T>,
storage_meter: &'a mut storage::meter::Meter<T>,
value: U256,
exec_config: &'a ExecConfig,
exec_config: &'a ExecConfig<T>,
input_data: &Vec<u8>,
) -> Result<Option<(Self, ExecutableOrPrecompile<T, E, Self>)>, ExecError> {
origin.ensure_mapped()?;
let Some((first_frame, executable)) = Self::new_frame(
Expand All @@ -930,6 +941,8 @@ where
BalanceOf::<T>::max_value(),
false,
true,
input_data,
exec_config,
)?
else {
return Ok(None);
Expand Down Expand Up @@ -964,6 +977,8 @@ where
deposit_limit: BalanceOf<T>,
read_only: bool,
origin_is_caller: bool,
input_data: &[u8],
exec_config: &ExecConfig<T>,
) -> Result<Option<(Frame<T>, ExecutableOrPrecompile<T, E, Self>)>, ExecError> {
let (account_id, contract_info, executable, delegate, entry_point) = match frame_args {
FrameArgs::Call { dest, cached_info, delegated_call } => {
Expand Down Expand Up @@ -991,6 +1006,11 @@ where
(None, Some(_)) => CachedContract::None,
};

let delegated_call = delegated_call.or_else(|| {
exec_config.mock_handler.as_ref().and_then(|mock_handler| {
mock_handler.mock_delegated_caller(address, input_data)
})
});
// in case of delegate the executable is not the one at `address`
let executable = if let Some(delegated_call) = &delegated_call {
if let Some(precompile) =
Expand Down Expand Up @@ -1085,6 +1105,7 @@ where
gas_limit: Weight,
deposit_limit: BalanceOf<T>,
read_only: bool,
input_data: &[u8],
) -> Result<Option<ExecutableOrPrecompile<T, E, Self>>, ExecError> {
if self.frames.len() as u32 == limits::CALL_STACK_DEPTH {
return Err(Error::<T>::MaxCallDepthReached.into());
Expand Down Expand Up @@ -1116,6 +1137,8 @@ where
deposit_limit,
read_only,
false,
input_data,
self.exec_config,
)? {
self.frames.try_push(frame).map_err(|_| Error::<T>::MaxCallDepthReached)?;
Ok(Some(executable))
Expand Down Expand Up @@ -1251,11 +1274,23 @@ where
.map(|exec| exec.code_info().deposit())
.unwrap_or_default();

let mut output = match executable {
ExecutableOrPrecompile::Executable(executable) =>
let mock_answer = self.exec_config.mock_handler.as_ref().and_then(|handler| {
handler.mock_call(
frame
.delegate
.as_ref()
.map(|delegate| delegate.callee)
.unwrap_or(T::AddressMapper::to_address(&frame.account_id)),
&input_data,
frame.value_transferred,
)
});
let mut output = match (executable, mock_answer) {
(ExecutableOrPrecompile::Executable(executable), None) =>
executable.execute(self, entry_point, input_data),
ExecutableOrPrecompile::Precompile { instance, .. } =>
(ExecutableOrPrecompile::Precompile { instance, .. }, None) =>
instance.call(input_data, self),
(_, Some(mock_answer)) => Ok(mock_answer),
}
.and_then(|output| {
if u32::try_from(output.data.len())
Expand Down Expand Up @@ -1467,7 +1502,7 @@ where
to: &T::AccountId,
value: U256,
storage_meter: &mut storage::meter::GenericMeter<T, S>,
exec_config: &ExecConfig,
exec_config: &ExecConfig<T>,
) -> DispatchResult {
fn transfer_with_dust<T: Config>(
from: &AccountIdOf<T>,
Expand Down Expand Up @@ -1579,7 +1614,7 @@ where
to: &T::AccountId,
value: U256,
storage_meter: &mut storage::meter::GenericMeter<T, S>,
exec_config: &ExecConfig,
exec_config: &ExecConfig<T>,
) -> ExecResult {
// If the from address is root there is no account to transfer from, and therefore we can't
// take any `value` other than 0.
Expand Down Expand Up @@ -1692,6 +1727,7 @@ where
gas_limit,
deposit_limit.saturated_into::<BalanceOf<T>>(),
self.is_read_only(),
&input_data,
)? {
self.run(executable, input_data)
} else {
Expand Down Expand Up @@ -1859,6 +1895,7 @@ where
gas_limit,
deposit_limit.saturated_into::<BalanceOf<T>>(),
self.is_read_only(),
&input_data,
)?
};
let executable = executable.expect(FRAME_ALWAYS_EXISTS_ON_INSTANTIATE);
Expand Down Expand Up @@ -1926,6 +1963,7 @@ where
gas_limit,
deposit_limit.saturated_into::<BalanceOf<T>>(),
is_read_only,
&input_data,
)? {
self.run(executable, input_data)
} else {
Expand Down Expand Up @@ -2001,6 +2039,16 @@ where
}

fn caller(&self) -> Origin<T> {
if let Some(Ok(mock_caller)) = self
.exec_config
.mock_handler
.as_ref()
.and_then(|mock_handler| mock_handler.mock_caller(self.frames.len()))
.map(|mock_caller| Origin::<T>::from_runtime_origin(mock_caller))
{
return mock_caller;
}

if let Some(DelegateInfo { caller, .. }) = &self.top_frame().delegate {
caller.clone()
} else {
Expand Down
19 changes: 10 additions & 9 deletions substrate/frame/revive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ mod vm;

pub mod evm;
pub mod migrations;
pub mod mock;
pub mod precompiles;
pub mod test_utils;
pub mod tracing;
Expand All @@ -48,7 +49,7 @@ use crate::{
create_call, fees::InfoT as FeeInfo, runtime::SetWeightLimit, CallTracer,
GenericTransaction, PrestateTracer, Trace, Tracer, TracerType, TYPE_EIP1559,
},
exec::{AccountIdOf, ExecError, Executable, Stack as ExecStack},
exec::{AccountIdOf, ExecError, Stack as ExecStack},
gas::GasMeter,
storage::{meter::Meter as StorageMeter, AccountType, DeletionQueueManager},
tracing::if_tracing,
Expand Down Expand Up @@ -87,7 +88,7 @@ pub use crate::{
address::{
create1, create2, is_eth_derived, AccountId32Mapper, AddressMapper, TestAccountMapper,
},
exec::{Key, MomentOf, Origin as ExecOrigin},
exec::{DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin},
pallet::{genesis, *},
storage::{AccountInfo, ContractInfo},
};
Expand Down Expand Up @@ -1275,7 +1276,7 @@ impl<T: Config> Pallet<T> {
gas_limit: Weight,
storage_deposit_limit: BalanceOf<T>,
data: Vec<u8>,
exec_config: ExecConfig,
exec_config: ExecConfig<T>,
) -> ContractResult<ExecReturnValue, BalanceOf<T>> {
if let Err(contract_result) = Self::ensure_non_contract_if_signed(&origin) {
return contract_result;
Expand Down Expand Up @@ -1334,7 +1335,7 @@ impl<T: Config> Pallet<T> {
code: Code,
data: Vec<u8>,
salt: Option<[u8; 32]>,
exec_config: ExecConfig,
exec_config: ExecConfig<T>,
) -> ContractResult<InstantiateReturnValue, BalanceOf<T>> {
// Enforce EIP-3607 for top-level signed origins: deny signed contract addresses.
if let Err(contract_result) = Self::ensure_non_contract_if_signed(&origin) {
Expand Down Expand Up @@ -1849,11 +1850,11 @@ impl<T: Config> Pallet<T> {
}

/// Uploads new code and returns the Vm binary contract blob and deposit amount collected.
fn try_upload_pvm_code(
pub fn try_upload_pvm_code(
origin: T::AccountId,
code: Vec<u8>,
storage_deposit_limit: BalanceOf<T>,
exec_config: &ExecConfig,
exec_config: &ExecConfig<T>,
) -> Result<(ContractBlob<T>, BalanceOf<T>), DispatchError> {
let mut module = ContractBlob::from_pvm_code(code, origin)?;
let deposit = module.store_code(exec_config, None)?;
Expand Down Expand Up @@ -1881,7 +1882,7 @@ impl<T: Config> Pallet<T> {
}

/// Convert a weight to a gas value.
fn evm_gas_from_weight(weight: Weight) -> U256 {
pub fn evm_gas_from_weight(weight: Weight) -> U256 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is that used from outside the crate?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

T::FeeInfo::weight_to_fee(weight).into()
}

Expand Down Expand Up @@ -1967,7 +1968,7 @@ impl<T: Config> Pallet<T> {
from: &T::AccountId,
to: &T::AccountId,
amount: BalanceOf<T>,
exec_config: &ExecConfig,
exec_config: &ExecConfig<T>,
) -> DispatchResult {
use frame_support::traits::tokens::{Fortitude, Precision, Preservation};
match (exec_config.collect_deposit_from_hold, hold_reason) {
Expand Down Expand Up @@ -2012,7 +2013,7 @@ impl<T: Config> Pallet<T> {
from: &T::AccountId,
to: &T::AccountId,
amount: BalanceOf<T>,
exec_config: &ExecConfig,
exec_config: &ExecConfig<T>,
) -> Result<BalanceOf<T>, DispatchError> {
use frame_support::traits::{
tokens::{Fortitude, Precision, Preservation, Restriction},
Expand Down
55 changes: 55 additions & 0 deletions substrate/frame/revive/src/mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Helper interfaces and functions, that help with controlling the execution of EVM contracts.
//! It is mostly used to help with the implementation of foundry cheatscodes for forge test
//! integration.
use frame_system::pallet_prelude::OriginFor;
use sp_core::{H160, U256};

use crate::{pallet, DelegateInfo, ExecReturnValue};

/// A trait that provides hooks for mocking EVM contract calls and callers.
/// This is useful for testing and simulating contract interactions within foundry forge tests.
pub trait MockHandler<T: pallet::Config> {
/// Mock an EVM contract call.
///
/// Returns `Some(ExecReturnValue)` if the call is mocked, otherwise `None`.
fn mock_call(
&self,
_callee: H160,
_call_data: &[u8],
_value_transferred: U256,
) -> Option<ExecReturnValue> {
None
}

/// Mock the caller of a contract.
///
/// Returns `Some(OriginFor<T>)` if the caller is mocked, otherwise `None`.
fn mock_caller(&self, _frames_len: usize) -> Option<OriginFor<T>> {
None
}

/// Mock a delegated caller for a contract call.
///
/// Returns `Some(DelegateInfo<T>)` if the delegated caller is mocked, otherwise `None`.
fn mock_delegated_caller(&self, _dest: H160, _input_data: &[u8]) -> Option<DelegateInfo<T>> {
None
}
}
Loading