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

WEB3-276: feat: Add Account query functionality to Steel #414

Open
wants to merge 2 commits into
base: main
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
160 changes: 160 additions & 0 deletions crates/steel/src/account.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// Copyright 2025 RISC Zero, Inc.
//
// 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.

//! Types related to account queries.
pub use revm::primitives::{AccountInfo, Bytecode};
Copy link
Contributor Author

Choose a reason for hiding this comment

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

A Steel account query returns the corresponding revm::primitives::AccountInfo. This is a bit closer to the actual (revm) EVM execution, but it does not return the storage root (which is also inaccessible from inside the EVM) and the code is returned as revm::primitives::Bytecode instead of just Bytes. Alternatively, it may be preferable to define and return our own new type:

pub struct AccountInfo {
    pub nonce: u64,
    pub balance: U256,
    pub storage_root: B256,
    pub code_hash: B256,
    pub code: Option<Byte>,
}

Copy link
Contributor Author

@Wollac Wollac Jan 31, 2025

Choose a reason for hiding this comment

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

OK, I did a little research on this: The problem is the storage_root. Unfortunately, this is not accessible in EVM, so there is no easy way to get it from RPC or the revm DB. The only way is to call an eth_getProof just to get this value. This is possible, but would require a bit more code.
So do we think the storage_root is necessary? Otherwise the existing alternative would be sufficient and easier.

Copy link
Contributor

@nategraf nategraf Feb 1, 2025

Choose a reason for hiding this comment

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

Let's move on without the storage root then. If there becomes a use case for this, we can revisit, possibly adding a helper function of some sort to specifically get the storage root.


use crate::{state::WrapStateDb, EvmBlockHeader, GuestEvmEnv};
use alloy_primitives::Address;
use anyhow::Result;
use revm::Database as RevmDatabase;

/// Represents an EVM account query.
///
/// ### Usage
/// - **Preflight calls on the Host:** To prepare the account query on the host environment and
/// build the necessary proof, use [Account::preflight].
/// - **Calls in the Guest:** To initialize the account query in the guest, use [Account::new].
///
/// ### Examples
/// ```rust,no_run
/// # use risc0_steel::{Account, ethereum::EthEvmEnv};
/// # use alloy_primitives::address;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> anyhow::Result<()> {
/// let account_address = address!("F977814e90dA44bFA03b6295A0616a897441aceC");
///
/// // Host:
/// let url = "https://ethereum-rpc.publicnode.com".parse()?;
/// let mut env = EthEvmEnv::builder().rpc(url).build().await?;
/// let account = Account::preflight(account_address, &mut env);
/// let info = account.bytecode(true).info().await?;
///
/// let evm_input = env.into_input().await?;
///
/// // Guest:
/// let env = evm_input.into_env();
/// let account = Account::new(account_address, &env);
/// let info = account.bytecode(true).info();
///
/// # Ok(())
/// # }
/// ```
pub struct Account<E> {
address: Address,
env: E,
code: bool,
}

impl<E> Account<E> {
/// Sets whether to fetch the bytecode for this account.
///
/// If set to `true`, the bytecode will be fetched when calling [Account::info].
pub fn bytecode(mut self, code: bool) -> Self {
self.code = code;
self
}
}

impl<'a, H: EvmBlockHeader> Account<&'a GuestEvmEnv<H>> {
/// Constructor for querying an Ethereum account in the guest.
pub fn new(address: Address, env: &'a GuestEvmEnv<H>) -> Self {
Self {
address,
env,
code: false,
}
}

/// Attempts to get the [AccountInfo] for the corresponding account and returns an error if the
/// query fails.
///
/// In general, it's recommended to use [Account::info] unless explicit error handling is
/// required.
pub fn try_info(self) -> Result<AccountInfo> {
let mut db = WrapStateDb::new(self.env.db());
let mut info = db.basic(self.address)?.unwrap_or_default();
if self.code && info.code.is_none() {
let code = db.code_by_hash(info.code_hash)?;
info.code = Some(code);
}

Ok(info)
}

/// Gets the [AccountInfo] for the corresponding account and panics on failure.
///
/// A convenience wrapper for [Account::try_info], panicking if the query fails. Useful when
/// success is expected.
pub fn info(self) -> AccountInfo {
self.try_info().unwrap()
}
}

#[cfg(feature = "host")]
mod host {
use super::*;
use crate::host::HostEvmEnv;
use anyhow::Context;
use std::error::Error as StdError;

impl<'a, D, H, C> Account<&'a mut HostEvmEnv<D, H, C>>
where
D: RevmDatabase + Send + 'static,
<D as RevmDatabase>::Error: StdError + Send + Sync + 'static,
{
/// Constructor for preflighting queries to an Ethereum account on the host.
///
/// Initializes the environment for querying account information, fetching necessary data
/// via the [Provider], and generating a storage proof for any accessed elements using
/// [EvmEnv::into_input].
///
/// [EvmEnv::into_input]: crate::EvmEnv::into_input
/// [EvmEnv]: crate::EvmEnv
/// [Provider]: alloy::providers::Provider
pub fn preflight(address: Address, env: &'a mut HostEvmEnv<D, H, C>) -> Self {
Self {
address,
env,
code: false,
}
}

/// Gets the [AccountInfo] for the corresponding account using an [EvmEnv] constructed with
/// [Account::preflight].
///
/// [EvmEnv]: crate::EvmEnv
pub async fn info(self) -> Result<AccountInfo> {
log::info!("Executing preflight querying account {}", &self.address);

let mut info = self
.env
.spawn_with_db(move |db| db.basic(self.address))
.await
.context("failed to get basic account information")?
.unwrap_or_default();
if self.code && info.code.is_none() {
let code = self
.env
.spawn_with_db(move |db| db.code_by_hash(info.code_hash))
.await
.context("failed to get account code by its hash")?;
info.code = Some(code);
}

Ok(info)
}
}
}
4 changes: 2 additions & 2 deletions crates/steel/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ use revm::{
///
/// ### Usage
/// - **Preflight calls on the Host:** To prepare calls on the host environment and build the
/// necessary proof, use [Contract::preflight][Contract]. The environment can be initialized using the
/// [EthEvmEnv::builder] or [EvmEnv::builder].
/// necessary proof, use [Contract::preflight][Contract]. The environment can be initialized using
/// the [EthEvmEnv::builder] or [EvmEnv::builder].
/// - **Calls in the Guest:** To initialize the contract in the guest environment, use
/// [Contract::new]. The environment should be constructed using [EvmInput::into_env].
///
Expand Down
3 changes: 2 additions & 1 deletion crates/steel/src/host/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,8 @@ pub struct History {
}

impl<P> EvmEnvBuilder<P, EthBlockHeader, Url> {
/// Sets the block hash for the commitment block, which can be different from the execution block.
/// Sets the block hash for the commitment block, which can be different from the execution
/// block.
///
/// This allows for historical state execution while maintaining security through a more recent
/// commitment. The commitment block must be more recent than the execution block.
Expand Down
2 changes: 1 addition & 1 deletion crates/steel/src/host/db/alloy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl<T: Transport + Clone, N: Network, P: Provider<T, N>> Database for AlloyDb<T
let nonce = nonce.map_err(|err| Error::Rpc("eth_getTransactionCount", err))?;
let balance = balance.map_err(|err| Error::Rpc("eth_getBalance", err))?;
let code = code.map_err(|err| Error::Rpc("eth_getCode", err))?;
let bytecode = Bytecode::new_raw(code.0.into());
let bytecode = Bytecode::new_raw(code);

// if the account is empty return None
// in the EVM, emptiness is treated as equivalent to nonexistence
Expand Down
31 changes: 31 additions & 0 deletions crates/steel/src/host/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,37 @@ pub struct HostCommit<C> {
config_id: B256,
}

impl<D, H, C> HostEvmEnv<D, H, C>
where
D: Send + 'static,
{
/// Runs the provided closure that requires mutable access to the database on a thread where
/// blocking is acceptable.
///
/// It panics if the closure panics.
/// This function is necessary because mutable references to the database cannot be passed
/// directly to `tokio::task::spawn_blocking`. Instead, the database is temporarily taken out of
/// the `HostEvmEnv`, moved into the blocking task, and then restored after the task completes.
#[allow(dead_code)]
pub(crate) async fn spawn_with_db<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut ProofDb<D>) -> R + Send + 'static,
R: Send + 'static,
{
// as mutable references are not possible, the DB must be moved in and out of the task
let mut db = self.db.take().unwrap();

let (result, db) = tokio::task::spawn_blocking(move || (f(&mut db), db))
.await
.expect("DB execution panicked");

// restore the DB, so that we never return an env without a DB
self.db = Some(db);

result
}
}

impl<D, H: EvmBlockHeader, C> HostEvmEnv<D, H, C> {
/// Sets the chain ID and specification ID from the given chain spec.
///
Expand Down
2 changes: 2 additions & 0 deletions crates/steel/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use alloy_sol_types::SolValue;
use config::ChainSpec;
use revm::primitives::{BlockEnv, CfgEnvWithHandlerCfg, SpecId};

pub mod account;
pub mod beacon;
mod block;
pub mod config;
Expand All @@ -47,6 +48,7 @@ mod state;
#[cfg(feature = "unstable-verifier")]
mod verifier;

pub use account::Account;
pub use beacon::BeaconInput;
pub use block::BlockInput;
pub use contract::{CallBuilder, Contract};
Expand Down
36 changes: 1 addition & 35 deletions crates/steel/src/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,7 @@ impl<'a, H: EvmBlockHeader> SteelVerifier<&'a GuestEvmEnv<H>> {
#[cfg(feature = "host")]
mod host {
use super::*;
use crate::{
history::beacon_roots,
host::{db::ProofDb, HostEvmEnv},
};
use crate::{history::beacon_roots, host::HostEvmEnv};
use anyhow::Context;
use revm::Database;

Expand Down Expand Up @@ -111,37 +108,6 @@ mod host {
}
}
}

impl<D, H, C> HostEvmEnv<D, H, C>
where
D: Database + Send + 'static,
{
/// Runs the provided closure that requires mutable access to the database on a thread where
/// blocking is acceptable.
///
/// It panics if the closure panics.
/// This function is necessary because mutable references to the database cannot be passed
/// directly to `tokio::task::spawn_blocking`. Instead, the database is temporarily taken
/// out of the `HostEvmEnv`, moved into the blocking task, and then restored after
/// the task completes.
async fn spawn_with_db<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut ProofDb<D>) -> R + Send + 'static,
R: Send + 'static,
{
// as mutable references are not possible, the DB must be moved in and out of the task
let mut db = self.db.take().unwrap();

let (result, db) = tokio::task::spawn_blocking(|| (f(&mut db), db))
.await
.expect("DB execution panicked");

// restore the DB, so that we never return an env without a DB
self.db = Some(db);

result
}
}
}

fn validate_block_number(header: &impl EvmBlockHeader, block_number: U256) -> anyhow::Result<u64> {
Expand Down
40 changes: 37 additions & 3 deletions crates/steel/tests/steel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ use alloy::{
transports::BoxTransport,
uint,
};
use alloy_primitives::{address, b256, bytes, hex, Address, Bytes, U256};
use alloy_primitives::{address, b256, bytes, hex, keccak256, Address, Bytes, U256};
use alloy_sol_types::SolCall;
use common::{CallOptions, ANVIL_CHAIN_SPEC};
use risc0_steel::{ethereum::EthEvmEnv, Contract};
use risc0_steel::{ethereum::EthEvmEnv, Account, Contract};
use sha2::{Digest, Sha256};
use test_log::test;

Expand Down Expand Up @@ -116,7 +116,7 @@ alloy::sol!(
);

/// Returns an Anvil provider with the deployed [SteelTest] contract.
async fn test_provider() -> impl Provider<BoxTransport> {
async fn test_provider() -> impl Provider<BoxTransport> + Clone {
let provider = ProviderBuilder::new()
.with_recommended_fillers()
.on_anvil_with_wallet_and_config(|anvil| anvil.args(["--hardfork", "cancun"]));
Expand All @@ -128,6 +128,40 @@ async fn test_provider() -> impl Provider<BoxTransport> {
provider
}

#[test(tokio::test)]
async fn account_info() {
let provider = test_provider().await;
let mut env = EthEvmEnv::builder()
.provider(provider.clone())
.build()
.await
.unwrap()
.with_chain_spec(&ANVIL_CHAIN_SPEC);
let address = STEEL_TEST_CONTRACT;
let preflight_info = {
let account = Account::preflight(address, &mut env);
account.bytecode(true).info().await.unwrap()
};

let input = env.into_input().await.unwrap();
let env = input.into_env().with_chain_spec(&ANVIL_CHAIN_SPEC);

let info = {
let account = Account::new(address, &env);
account.bytecode(true).info()
};
assert_eq!(info, preflight_info, "mismatch in preflight and execution");

assert_eq!(info.balance, provider.get_balance(address).await.unwrap());
assert_eq!(
info.nonce,
provider.get_transaction_count(address).await.unwrap()
);
let code = info.code.unwrap().bytes();
assert_eq!(code, provider.get_code_at(address).await.unwrap());
assert_eq!(info.code_hash, keccak256(code));
}

#[test(tokio::test)]
async fn ec_recover() {
let result = common::eth_call(
Expand Down
Loading