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

[MOON-2092] Implement call state override for eth_call #163

Open
wants to merge 11 commits into
base: moonbeam-polkadot-v0.9.37
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 24 additions & 1 deletion client/rpc-core/src/types/call_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@

use crate::types::Bytes;
use ethereum::AccessListItem;
use ethereum_types::{H160, U256};
use ethereum_types::{H160, H256, U256};
use serde::Deserialize;
use std::collections::BTreeMap;

/// Call request
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)]
Expand Down Expand Up @@ -49,4 +50,26 @@ pub struct CallRequest {
/// EIP-2718 type
#[serde(rename = "type")]
pub transaction_type: Option<U256>,
/// Call state override
nbaztec marked this conversation as resolved.
Show resolved Hide resolved
#[serde(rename = "stateOverride")]
pub state_override: Option<CallStateOverride>,
}

// State override
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
pub struct CallStateOverride {
/// Fake balance to set for the account before executing the call.
pub balance: Option<U256>,
/// Fake nonce to set for the account before executing the call.
pub nonce: Option<U256>,
/// Fake EVM bytecode to inject into the account before executing the call.
pub code: Option<Bytes>,
/// Fake key-value mapping to override all slots in the account storage before
/// executing the call.
pub state: Option<BTreeMap<H256, H256>>,
/// Fake key-value mapping to override individual slots in the account storage before
/// executing the call.
pub state_diff: Option<BTreeMap<H256, H256>>,
}
2 changes: 1 addition & 1 deletion client/rpc-core/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub use self::{
block::{Block, BlockTransactions, Header, Rich, RichBlock, RichHeader},
block_number::BlockNumber,
bytes::Bytes,
call_request::CallRequest,
call_request::{CallRequest, CallStateOverride},
fee::{FeeHistory, FeeHistoryCache, FeeHistoryCacheItem, FeeHistoryCacheLimit},
filter::{
Filter, FilterAddress, FilterChanges, FilterPool, FilterPoolItem, FilterType,
Expand Down
2 changes: 2 additions & 0 deletions client/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,14 @@ sp-core = { workspace = true }
sp-io = { workspace = true }
sp-runtime = { workspace = true }
sp-storage = { workspace = true }
sp-state-machine = { workspace = true }
# Frontier
fc-db = { workspace = true }
fc-rpc-core = { workspace = true }
fp-ethereum = { workspace = true, features = ["std"] }
fp-rpc = { workspace = true, features = ["std"] }
fp-storage = { workspace = true, features = ["std"] }
fp-evm = { workspace = true }

[dev-dependencies]
tempfile = "3.3.0"
Expand Down
124 changes: 102 additions & 22 deletions client/rpc/src/eth/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ use jsonrpsee::core::RpcResult as Result;
use sc_client_api::backend::{Backend, StateBackend, StorageProvider};
use sc_network_common::ExHashT;
use sc_transaction_pool::ChainApi;
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_api::{ApiExt, CallApiAt, ProvideRuntimeApi};
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_blockchain::HeaderBackend;
use sp_io::hashing::{blake2_128, twox_128};
use sp_runtime::{
generic::BlockId,
traits::{BlakeTwo256, Block as BlockT},
Expand All @@ -36,6 +37,7 @@ use sp_runtime::{
// Frontier
use fc_rpc_core::types::*;
use fp_rpc::EthereumRuntimeRPCApi;
use fp_storage::{EVM_ACCOUNT_CODES, PALLET_EVM};

use crate::{
eth::{pending_runtime_api, Eth},
Expand Down Expand Up @@ -67,7 +69,7 @@ impl<B, C, P, CT, BE, H: ExHashT, A: ChainApi, EGA> Eth<B, C, P, CT, BE, H, A, E
where
B: BlockT<Hash = H256> + Send + Sync + 'static,
C: ProvideRuntimeApi<B> + StorageProvider<B, BE>,
C: HeaderBackend<B> + Send + Sync + 'static,
C: HeaderBackend<B> + CallApiAt<B> + Send + Sync + 'static,
C::Api: BlockBuilderApi<B> + EthereumRuntimeRPCApi<B>,
BE: Backend<B> + 'static,
BE::State: StateBackend<BlakeTwo256>,
Expand All @@ -86,6 +88,7 @@ where
data,
nonce,
access_list,
state_override,
..
} = request;

Expand Down Expand Up @@ -161,6 +164,8 @@ where
},
};

log::info!("VER {api_version}");

let data = data.map(|d| d.0).unwrap_or_default();
match to {
Some(to) => {
Expand Down Expand Up @@ -205,29 +210,104 @@ where
Ok(Bytes(info.value))
} else if api_version == 4 {
// Post-london + access list support
let access_list = access_list.unwrap_or_default();
let info = api
.call(
&id,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
false,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
let encoded_params = sp_api::Encode::encode(&(
&from.unwrap_or_default(),
&to,
&data,
&value.unwrap_or_default(),
&gas_limit,
&max_fee_per_gas,
&max_priority_fee_per_gas,
&nonce,
&false,
&Some(
access_list
.unwrap_or_default()
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect::<Vec<(sp_core::H160, Vec<H256>)>>(),
),
));

// set custom storage override
let mut overlayed_changes = sp_api::OverlayedChanges::default();
if let Some(state_override) = state_override {
let address = from.unwrap_or_default();
if let Some(runtime_state_override) = self.runtime_state_override.as_ref() {
let hash =
self.client.expect_block_hash_from_id(&id).map_err(|err| {
internal_err(format!("failed retrieving block hash: {:?}", err))
})?;

runtime_state_override.set_overlayed_changes(
self.client.as_ref(),
&mut overlayed_changes,
hash,
api_version,
address,
state_override.balance,
state_override.nonce,
);
}

if let Some(code) = &state_override.code {
let mut key = [twox_128(PALLET_EVM), twox_128(EVM_ACCOUNT_CODES)]
.concat()
.to_vec();
key.extend(blake2_128(address.as_bytes()));
key.extend(address.as_bytes());
overlayed_changes.set_storage(key, Some(code.clone().into_vec()));
}

// Prioritize `state_diff` over `state`
if let Some(state_diff) = &state_override.state_diff {
for (k, v) in state_diff {
overlayed_changes.set_storage(
k.as_bytes().to_owned(),
Some(v.as_bytes().to_owned()),
);
}
} else if let Some(state) = &state_override.state {
for (k, v) in state {
overlayed_changes.set_storage(
k.as_bytes().to_owned(),
Some(v.as_bytes().to_owned()),
);
}
}
}

let storage_transaction_cache = std::cell::RefCell::<
sp_api::StorageTransactionCache<B, C::StateBackend>,
>::default();
let params = sp_api::CallApiAtParams {
at: &id,
function: "EthereumRuntimeRPCApi_call",
arguments: encoded_params,
overlayed_changes: &std::cell::RefCell::new(overlayed_changes),
storage_transaction_cache: &storage_transaction_cache,
context: sp_api::ExecutionContext::OffchainCall(None),
recorder: &None,
};
let info = self
.client
.call_api_at(params)
.and_then(|r| {
std::result::Result::map_err(
<std::result::Result<
fp_evm::CallInfo,
sp_runtime::DispatchError,
> as sp_api::Decode>::decode(&mut &r[..]),
|error| sp_api::ApiError::FailedToDecodeReturnValue {
function: "EthereumRuntimeRPCApi_call",
error,
},
)
})
.map_err(|err| internal_err(format!("runtime error: {:?}", err)))?
.map_err(|err| internal_err(format!("execution fatal: {:?}", err)))?;

log::info!("2 {:?}", info);
error_on_execution_failure(&info.exit_reason, &info.value)?;
Ok(Bytes(info.value))
} else {
Expand Down
17 changes: 13 additions & 4 deletions client/rpc/src/eth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use sc_network::NetworkService;
use sc_network_common::ExHashT;
use sc_transaction_pool::{ChainApi, Pool};
use sc_transaction_pool_api::{InPoolTransaction, TransactionPool};
use sp_api::{Core, HeaderT, ProvideRuntimeApi};
use sp_api::{CallApiAt, Core, HeaderT, ProvideRuntimeApi};
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_blockchain::HeaderBackend;
use sp_core::hashing::keccak_256;
Expand All @@ -49,7 +49,10 @@ use sp_runtime::{
};
// Frontier
use fc_rpc_core::{types::*, EthApiServer};
use fp_rpc::{ConvertTransactionRuntimeApi, EthereumRuntimeRPCApi, TransactionStatus};
use fp_rpc::{
ConvertTransactionRuntimeApi, EthereumRuntimeRPCApi, EthereumRuntimeStorageOverride,
TransactionStatus,
};

use crate::{internal_err, overrides::OverrideHandle, public_key, signer::EthSigner};

Expand All @@ -76,6 +79,7 @@ pub struct Eth<B: BlockT, C, P, CT, BE, H: ExHashT, A: ChainApi, EGA = ()> {
/// When using eth_call/eth_estimateGas, the maximum allowed gas limit will be
/// block.gas_limit * execute_gas_limit_multiplier
execute_gas_limit_multiplier: u64,
runtime_state_override: Option<Arc<dyn EthereumRuntimeStorageOverride<B, C>>>,
_marker: PhantomData<(B, BE, EGA)>,
}

Expand All @@ -94,6 +98,7 @@ impl<B: BlockT, C, P, CT, BE, H: ExHashT, A: ChainApi> Eth<B, C, P, CT, BE, H, A
fee_history_cache: FeeHistoryCache,
fee_history_cache_limit: FeeHistoryCacheLimit,
execute_gas_limit_multiplier: u64,
runtime_state_override: Option<Arc<dyn EthereumRuntimeStorageOverride<B, C>>>,
) -> Self {
Self {
client,
Expand All @@ -109,6 +114,7 @@ impl<B: BlockT, C, P, CT, BE, H: ExHashT, A: ChainApi> Eth<B, C, P, CT, BE, H, A
fee_history_cache,
fee_history_cache_limit,
execute_gas_limit_multiplier,
runtime_state_override,
_marker: PhantomData,
}
}
Expand All @@ -132,6 +138,7 @@ impl<B: BlockT, C, P, CT, BE, H: ExHashT, A: ChainApi, EGA> Eth<B, C, P, CT, BE,
fee_history_cache,
fee_history_cache_limit,
execute_gas_limit_multiplier,
runtime_state_override,
_marker: _,
} = self;

Expand All @@ -149,6 +156,7 @@ impl<B: BlockT, C, P, CT, BE, H: ExHashT, A: ChainApi, EGA> Eth<B, C, P, CT, BE,
fee_history_cache,
fee_history_cache_limit,
execute_gas_limit_multiplier,
runtime_state_override,
_marker: PhantomData,
}
}
Expand All @@ -159,7 +167,7 @@ impl<B, C, P, CT, BE, H: ExHashT, A, EGA> EthApiServer for Eth<B, C, P, CT, BE,
where
B: BlockT<Hash = H256> + Send + Sync + 'static,
C: ProvideRuntimeApi<B> + StorageProvider<B, BE>,
C: HeaderBackend<B> + Send + Sync + 'static,
C: HeaderBackend<B> + CallApiAt<B> + Send + Sync + 'static,
C::Api: BlockBuilderApi<B> + ConvertTransactionRuntimeApi<B> + EthereumRuntimeRPCApi<B>,
P: TransactionPool<Block = B> + Send + Sync + 'static,
CT: fp_rpc::ConvertTransaction<<B as BlockT>::Extrinsic> + Send + Sync + 'static,
Expand Down Expand Up @@ -290,6 +298,7 @@ where
// ########################################################################

fn call(&self, request: CallRequest, number: Option<BlockNumber>) -> Result<Bytes> {
log::info!("CALL");
self.call(request, number)
}

Expand Down Expand Up @@ -508,7 +517,7 @@ fn pending_runtime_api<'a, B: BlockT, C, BE, A: ChainApi>(
where
B: BlockT<Hash = H256> + Send + Sync + 'static,
C: ProvideRuntimeApi<B> + StorageProvider<B, BE>,
C: HeaderBackend<B> + Send + Sync + 'static,
C: HeaderBackend<B> + sp_api::CallApiAt<B> + Send + Sync + 'static,
C::Api: BlockBuilderApi<B> + EthereumRuntimeRPCApi<B>,
BE: Backend<B> + 'static,
BE::State: StateBackend<BlakeTwo256>,
Expand Down
2 changes: 1 addition & 1 deletion client/rpc/src/eth/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl<B, C, P, CT, BE, H: ExHashT, A: ChainApi, EGA> Eth<B, C, P, CT, BE, H, A, E
where
B: BlockT<Hash = H256> + Send + Sync + 'static,
C: ProvideRuntimeApi<B> + StorageProvider<B, BE>,
C: HeaderBackend<B> + Send + Sync + 'static,
C: HeaderBackend<B> + sp_api::CallApiAt<B> + Send + Sync + 'static,
C::Api: BlockBuilderApi<B> + EthereumRuntimeRPCApi<B>,
BE: Backend<B> + 'static,
BE::State: StateBackend<BlakeTwo256>,
Expand Down
2 changes: 1 addition & 1 deletion client/rpc/src/eth/submit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl<B, C, P, CT, BE, H: ExHashT, A: ChainApi, EGA> Eth<B, C, P, CT, BE, H, A, E
where
B: BlockT<Hash = H256> + Send + Sync + 'static,
C: ProvideRuntimeApi<B> + StorageProvider<B, BE>,
C: HeaderBackend<B> + Send + Sync + 'static,
C: HeaderBackend<B> + sp_api::CallApiAt<B> + Send + Sync + 'static,
C::Api: BlockBuilderApi<B> + ConvertTransactionRuntimeApi<B> + EthereumRuntimeRPCApi<B>,
BE: Backend<B> + 'static,
BE::State: StateBackend<BlakeTwo256>,
Expand Down
Loading