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

Access StorageData for eth_getBalance #43

Closed
Closed
Show file tree
Hide file tree
Changes from 2 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
4 changes: 3 additions & 1 deletion rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@ frontier-rpc-core = { path = "core" }
frontier-rpc-primitives = { path = "primitives" }
sp-runtime = { path = "../vendor/substrate/primitives/runtime" }
sp-api = { path = "../vendor/substrate/primitives/api" }
sp-io = { path = "../vendor/substrate/primitives/io" }
sp-consensus = { path = "../vendor/substrate/primitives/consensus/common" }
sp-transaction-pool = { path = "../vendor/substrate/primitives/transaction-pool" }
sp-storage = { path = "../vendor/substrate/primitives/storage" }
sc-service = { path = "../vendor/substrate/client/service" }
sc-client-api = { path = "../vendor/substrate/client/api" }
sp-blockchain = { path = "../vendor/substrate/primitives/blockchain" }
ethereum = { version = "0.2", features = ["codec"] }
codec = { package = "parity-scale-codec", version = "1.0.0" }
rlp = "0.4"
pallet-ethereum = "0.1"
futures = { version = "0.3.1", features = ["compat"] }
sha3 = "0.8"
sha3 = "0.8"
1 change: 1 addition & 0 deletions rpc/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ sp_api::decl_runtime_apis! {
pub trait EthereumRuntimeApi {
fn chain_id() -> u64;
fn account_basic(address: H160) -> pallet_evm::Account;
fn account_decode(bytes: Vec<u8>) -> pallet_evm::Account;
fn transaction_status(hash: H256) -> Option<TransactionStatus>;
fn gas_price() -> U256;
fn account_code_at(address: H160) -> Vec<u8>;
Expand Down
61 changes: 53 additions & 8 deletions rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ use futures::future::TryFutureExt;
use sp_runtime::traits::{Block as BlockT, Header as _, UniqueSaturatedInto};
use sp_runtime::transaction_validity::TransactionSource;
use sp_api::{ProvideRuntimeApi, BlockId};
use sp_io::hashing::{twox_128, blake2_128};
use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend};
use sp_storage::StorageKey;
use sp_consensus::SelectChain;
use sp_transaction_pool::TransactionPool;
use sc_client_api::backend::{StorageProvider, Backend, StateBackend};
Expand All @@ -34,7 +37,6 @@ use frontier_rpc_core::types::{
SyncStatus, Transaction, Work, Rich, Block, BlockTransactions
};
use frontier_rpc_primitives::{EthereumRuntimeApi, ConvertTransaction, TransactionStatus};

pub use frontier_rpc_core::EthApiServer;

fn internal_err(message: &str) -> Error {
Expand Down Expand Up @@ -131,8 +133,13 @@ fn transaction_build(
}
}

fn storage_prefix_build(module: &[u8], storage: &[u8]) -> Vec<u8> {
[twox_128(module), twox_128(storage)].concat().to_vec()
}

impl<B, C, SC, P, CT, BE> EthApiT for EthApi<B, C, SC, P, CT, BE> where
C: ProvideRuntimeApi<B> + StorageProvider<B,BE>,
C: ProvideRuntimeApi<B> + StorageProvider<B,BE> +
HeaderBackend<B> + HeaderMetadata<B, Error=BlockChainError>,
C::Api: EthereumRuntimeApi<B>,
BE: Backend<B> + 'static,
BE::State: StateBackend<BlakeTwo256>,
Expand Down Expand Up @@ -206,15 +213,53 @@ impl<B, C, SC, P, CT, BE> EthApiT for EthApi<B, C, SC, P, CT, BE> where
}

fn balance(&self, address: H160, number: Option<BlockNumber>) -> Result<U256> {
let header = self.select_chain.best_chain()
.map_err(|_| internal_err("fetch header failed"))?;

let number_param: u32;

if let Some(number) = number {
if number != BlockNumber::Latest {
unimplemented!("fetch nonce for past blocks is not yet supported");
if let Some(block_number) = number.to_min_block_num() {
number_param = block_number.unique_saturated_into();
} else if number == BlockNumber::Latest {
number_param = header.number().clone().unique_saturated_into() as u32;
} else {
unimplemented!("only latest or block number are supported");
}
} else {
number_param = header.number().clone().unique_saturated_into() as u32;
}

let mut block_hash = None;
if let Ok(result) = self.client.header(BlockId::Number(number_param.into())) {
if let Some(header) = result {
block_hash = Some(header.hash());
}
}

if let Some(block_hash) = block_hash {
// StorageProvider prefix
let mut prefix = storage_prefix_build(b"EVM", b"Accounts");
// StorageMap blake2_128_concat key
let mut storage_key = blake2_128(address.as_bytes()).to_vec();
storage_key.extend_from_slice(address.as_bytes());
// Module and Storage prefix + StorageMap concat
prefix.extend(storage_key.clone());

let key = StorageKey(prefix);

if let Ok(Some(data)) = self.client.storage(
&BlockId::Hash(block_hash),
&key) {
return Ok(
self.client
.runtime_api()
.account_decode(&BlockId::Hash(header.hash()), data.0)
Copy link
Member

Choose a reason for hiding this comment

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

If we are reading the raw account data, what's the reason still calling into runtime?

Copy link
Contributor Author

@tgmichel tgmichel Jun 18, 2020

Choose a reason for hiding this comment

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

Not adding the pallet-evm as a dependency for accessing the EvmAccount (as it's a dependency for the Runtime anyways).

If we are OK adding that dep, then it would make no sense of course.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Also as a side note, Decode::decode cannot infer the data type, in this case pallet-evm::Account needs to be declared as the result type.

Copy link
Member

Choose a reason for hiding this comment

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

The round trip call to runtime API is the main consumption of performance. If we still call in runtime I'm not sure how this PR brings improvements, TBH.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Indeed. As in the RPC module we already have the frontier-rpc-primitives dep, we could do a public re-export of the pallet-evm::Account from there, and avoid calling the Runtime doing that. Let me update the PR with that.

.map_err(|_| internal_err("fetch runtime chain id failed"))?
.balance.into()
);
}
}
let header = self
.select_chain
.best_chain()
.map_err(|_| internal_err("fetch header failed"))?;
Ok(
self.client
.runtime_api()
Expand Down
5 changes: 5 additions & 0 deletions template/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,11 @@ impl_runtime_apis! {
evm::Module::<Runtime>::accounts(address)
}

fn account_decode(bytes: Vec<u8>) -> EVMAccount {
let account: EVMAccount = Decode::decode(&mut &bytes[..]).unwrap();
account
}

fn transaction_status(hash: H256) -> Option<ethereum::TransactionStatus> {
ethereum::Module::<Runtime>::transaction_status(hash)
}
Expand Down