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-307: feat: Add event support to Steel #405

Closed
wants to merge 3 commits into from
Closed
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ risc0-binfmt = { git = "https://github.com/risc0/risc0", branch = "main", defaul
alloy-consensus = { version = "0.9" }
alloy-rlp = { version = "0.3.8" }
alloy-primitives = { version = "0.8.16" }
alloy-rpc-types = { version = "0.9" }
alloy-sol-types = { version = "0.8.16" }

# OP Steel
Expand Down
1 change: 1 addition & 0 deletions crates/steel/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ alloy = { workspace = true, optional = true, features = ["full"] }
alloy-consensus = { workspace = true }
alloy-primitives = { workspace = true, features = ["rlp", "serde"] }
alloy-rlp = { workspace = true }
alloy-rpc-types = { workspace = true }
alloy-sol-types = { workspace = true }
alloy-trie = { workspace = true, features = ["serde"] }
anyhow = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion crates/steel/docs/steel-commitments.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Steel uses [revm] to generate an EVM execution environment, `EvmEnv` within the
// Create an EVM environment from that provider
let mut env = EthEvmEnv::builder()
.provider(provider.clone())
.block_number(20842508)
.BLOCK_NUMBER(20842508)
.build()
.await?;
```
Expand Down
42 changes: 31 additions & 11 deletions crates/steel/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub struct BlockInput<H> {
storage_tries: Vec<MerkleTrie>,
contracts: Vec<Bytes>,
ancestors: Vec<H>,
receipts_trie: MerkleTrie,
}

/// Implement [BlockHeaderCommit] for the unit type.
Expand Down Expand Up @@ -72,11 +73,19 @@ impl<H: EvmBlockHeader> BlockInput<H> {
previous_header = ancestor;
}

let receipts_root = self.receipts_trie.hash_slow();
assert_eq!(
header.receipts_root(),
&receipts_root,
"Receipts root mismatch"
);

let db = StateDb::new(
self.state_trie,
self.storage_tries,
self.contracts,
block_hashes,
self.receipts_trie,
);
let commit = Commitment::new(
CommitmentVersion::Block as u16,
Expand All @@ -91,31 +100,31 @@ impl<H: EvmBlockHeader> BlockInput<H> {

#[cfg(feature = "host")]
pub mod host {
use std::fmt::Display;

use super::BlockInput;
use crate::{
host::db::{AlloyDb, ProofDb, ProviderDb},
EvmBlockHeader,
EvmBlockHeader, MerkleTrie,
};
use alloy::{
network::{Ethereum, Network},
providers::Provider,
transports::Transport,
};
use alloy::{network::Network, providers::Provider, transports::Transport};
use alloy_primitives::Sealed;
use anyhow::{anyhow, ensure};
use log::debug;

impl<H: EvmBlockHeader> BlockInput<H> {
impl<H> BlockInput<H> {
/// Creates the `BlockInput` containing the necessary EVM state that can be verified against
/// the block hash.
pub(crate) async fn from_proof_db<T, N, P>(
mut db: ProofDb<AlloyDb<T, N, P>>,
pub(crate) async fn from_proof_db<T, P>(
mut db: ProofDb<AlloyDb<T, Ethereum, P>>,
header: Sealed<H>,
) -> anyhow::Result<Self>
where
T: Transport + Clone,
N: Network,
P: Provider<T, N>,
H: EvmBlockHeader + TryFrom<<N as Network>::HeaderResponse>,
<H as TryFrom<<N as Network>::HeaderResponse>>::Error: Display,
P: Provider<T, Ethereum>,
H: EvmBlockHeader + From<<Ethereum as Network>::HeaderResponse>,
{
assert_eq!(db.inner().block_hash(), header.seal(), "DB block mismatch");

Expand All @@ -137,12 +146,22 @@ pub mod host {
ancestors.push(header);
}

let receipts_trie = db
.receipt_proof()
.await?
.unwrap_or_else(|| MerkleTrie::from_digest(*header.receipts_root()));
ensure!(
header.receipts_root() == &receipts_trie.hash_slow(),
"block receipts does not match header's receiptsRoot"
);

debug!("state size: {}", state_trie.size());
debug!("storage tries: {}", storage_tries.len());
debug!(
"total storage size: {}",
storage_tries.iter().map(|t| t.size()).sum::<usize>()
);
debug!("receipts size: {}", receipts_trie.size());
debug!("contracts: {}", contracts.len());
debug!("ancestor blocks: {}", ancestors.len());

Expand All @@ -152,6 +171,7 @@ pub mod host {
storage_tries,
contracts,
ancestors,
receipts_trie,
};

Ok(input)
Expand Down
4 changes: 4 additions & 0 deletions crates/steel/src/ethereum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ impl EvmBlockHeader for EthBlockHeader {
fn state_root(&self) -> &B256 {
&self.inner().state_root
}
#[inline]
fn receipts_root(&self) -> &B256 {
&self.inner().receipts_root
}

#[inline]
fn fill_block_env(&self, blk_env: &mut BlockEnv) {
Expand Down
123 changes: 123 additions & 0 deletions crates/steel/src/event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// 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.

use crate::{state::WrapStateDb, EvmBlockHeader, GuestEvmEnv};
use alloy_primitives::{Address, Log, Sealed};
use alloy_rpc_types::{Filter, Topic, ValueOrArray};
use alloy_sol_types::SolEvent;
use std::marker::PhantomData;

pub struct Event<S, E> {
filter: Filter,
env: E,
phantom: PhantomData<S>,
}

impl<'a, S: SolEvent, H: EvmBlockHeader> Event<S, &'a GuestEvmEnv<H>> {
pub fn new(env: &'a GuestEvmEnv<H>) -> Self {
Self {
filter: event_filter::<S, H>(env.header()),
env,
phantom: PhantomData,
}
}

pub fn query(self) -> Vec<Log<S>> {
self.try_query().unwrap()
}

pub fn try_query(self) -> anyhow::Result<Vec<Log<S>>> {
let logs = crate::Database::logs(&mut WrapStateDb::new(self.env.db()), &self.filter)?;
logs.iter()
.map(|(_, log)| Ok(S::decode_log(log, false)?))
.collect()
}
}

impl<S, E> Event<S, E> {
/// Sets the address to query with this filter.
///
/// See [`Filter::address`].
pub fn address<A: Into<ValueOrArray<Address>>>(mut self, address: A) -> Self {
self.filter.address = address.into().into();
self
}

/// Sets the 1st indexed topic
pub fn topic1<TO: Into<Topic>>(mut self, topic: TO) -> Self {
self.filter.topics[1] = topic.into();
self
}

/// Sets the 2nd indexed topic
pub fn topic2<TO: Into<Topic>>(mut self, topic: TO) -> Self {
self.filter.topics[2] = topic.into();
self
}

/// Sets the 3rd indexed topic
pub fn topic3<TO: Into<Topic>>(mut self, topic: TO) -> Self {
self.filter.topics[3] = topic.into();
self
}
}

#[cfg(feature = "host")]
mod host {
use super::*;
use crate::host::HostEvmEnv;
use anyhow::{anyhow, Result};
use revm::Database;
use std::fmt::Display;

impl<'a, D, H: EvmBlockHeader, C> Event<(), &'a mut HostEvmEnv<D, H, C>>
where
D: crate::Database + Send + 'static,
<D as Database>::Error: Display + Send + 'static,
{
pub fn preflight<S: SolEvent>(
env: &'a mut HostEvmEnv<D, H, C>,
) -> Event<S, &'a mut HostEvmEnv<D, H, C>> {
Event {
filter: event_filter::<S, H>(env.header()),
env,
phantom: PhantomData,
}
}
}

impl<S: SolEvent, D, H: EvmBlockHeader, C> Event<S, &mut HostEvmEnv<D, H, C>>
where
D: crate::Database + Send + 'static,
<D as Database>::Error: Display + Send + 'static,
{
pub async fn query(self) -> Result<Vec<Log<S>>> {
let logs = self
.env
.spawn_with_db(move |db| crate::Database::logs(db, &self.filter))
.await
.map_err(|err| anyhow!("querying '{}' failed: {}", S::SIGNATURE, err))?;
logs.iter()
.map(|(_, log)| Ok(S::decode_log(log, false)?))
.collect()
}
}
}

fn event_filter<S: SolEvent, H: EvmBlockHeader>(header: &Sealed<H>) -> Filter {
assert!(!S::ANONYMOUS, "Anonymous events not supported");
Filter::new()
.event_signature(S::SIGNATURE_HASH)
.at_block_hash(header.seal())
}
18 changes: 17 additions & 1 deletion crates/steel/src/host/db/alloy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ use alloy::{
providers::Provider,
transports::{Transport, TransportError},
};
use alloy_primitives::{map::B256HashMap, Address, BlockHash, B256, U256};
use alloy_primitives::{map::B256HashMap, Address, BlockHash, Log, B256, U256};
use alloy_rpc_types::Filter;
use revm::{
primitives::{AccountInfo, Bytecode},
Database,
Expand Down Expand Up @@ -171,3 +172,18 @@ impl<T: Transport + Clone, N: Network, P: Provider<T, N>> Database for AlloyDb<T
Ok(block.header().hash())
}
}

impl<T: Transport + Clone, N: Network, P: Provider<T, N>> crate::Database for AlloyDb<T, N, P> {
fn logs(&mut self, filter: &Filter) -> Result<Vec<(u64, Log)>, <Self as Database>::Error> {
assert_eq!(filter.get_block_hash(), Some(self.block_hash));
let rpc_logs = self
.handle
.block_on(self.provider.get_logs(filter))
.map_err(|err| Error::Rpc("eth_getLogs", err))?;

Ok(rpc_logs
.into_iter()
.map(|log| (log.log_index.unwrap(), log.inner))
.collect())
}
}
Loading
Loading