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

chore: add OpEthApiBuilder and OpEthApiInner #13009

Merged
merged 15 commits into from
Dec 2, 2024
4 changes: 4 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion crates/optimism/bin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ fn main() {
}
let use_legacy_engine = rollup_args.legacy;
let sequencer_http_arg = rollup_args.sequencer_http.clone();
let storage_proof_only = rollup_args.storage_proof_only.clone();
match use_legacy_engine {
false => {
let engine_tree_config = TreeConfig::default()
Expand All @@ -36,7 +37,7 @@ fn main() {
let handle = builder
.with_types_and_provider::<OpNode, BlockchainProvider2<_>>()
.with_components(OpNode::components(rollup_args))
.with_add_ons(OpAddOns::new(sequencer_http_arg))
.with_add_ons(OpAddOns::new(sequencer_http_arg, storage_proof_only))
.launch_with_fn(|builder| {
let launcher = EngineNodeLauncher::new(
builder.task_executor().clone(),
Expand Down
7 changes: 7 additions & 0 deletions crates/optimism/node/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

//! clap [Args](clap::Args) for optimism rollup configuration

use alloy_primitives::Address;
use reth_node_builder::engine_tree_config::{
DEFAULT_MEMORY_BLOCK_BUFFER_TARGET, DEFAULT_PERSISTENCE_THRESHOLD,
};
Expand Down Expand Up @@ -56,6 +57,11 @@ pub struct RollupArgs {
/// Configure the target number of blocks to keep in memory.
#[arg(long = "engine.memory-block-buffer-target", conflicts_with = "legacy", default_value_t = DEFAULT_MEMORY_BLOCK_BUFFER_TARGET)]
pub memory_block_buffer_target: u64,

/// List of addresses that _ONLY_ return storage proofs _WITHOUT_ an account proof when called
/// with `eth_getProof`.
#[arg(long = "rpc.storage-proof-addresses", value_delimiter = ',', num_args(1..))]
pub storage_proof_only: Vec<Address>,
}

impl Default for RollupArgs {
Expand All @@ -70,6 +76,7 @@ impl Default for RollupArgs {
legacy: false,
persistence_threshold: DEFAULT_PERSISTENCE_THRESHOLD,
memory_block_buffer_target: DEFAULT_MEMORY_BLOCK_BUFFER_TARGET,
storage_proof_only: vec![],
}
}
}
Expand Down
15 changes: 10 additions & 5 deletions crates/optimism/node/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::{
OpEngineTypes,
};
use alloy_consensus::Header;
use alloy_primitives::Address;
use reth_basic_payload_builder::{BasicPayloadJobGenerator, BasicPayloadJobGeneratorConfig};
use reth_chainspec::{EthChainSpec, EthereumHardforks, Hardforks};
use reth_db::transaction::{DbTx, DbTxMut};
Expand Down Expand Up @@ -183,7 +184,7 @@ where
}

fn add_ons(&self) -> Self::AddOns {
OpAddOns::new(self.args.sequencer_http.clone())
OpAddOns::new(self.args.sequencer_http.clone(), self.args.storage_proof_only.clone())
}
}

Expand All @@ -204,14 +205,18 @@ pub struct OpAddOns<N: FullNodeComponents>(pub RpcAddOns<N, OpEthApi<N>, OpEngin

impl<N: FullNodeComponents<Types: NodeTypes<Primitives = OpPrimitives>>> Default for OpAddOns<N> {
fn default() -> Self {
Self::new(None)
Self::new(None, vec![])
}
}

impl<N: FullNodeComponents<Types: NodeTypes<Primitives = OpPrimitives>>> OpAddOns<N> {
/// Create a new instance with the given `sequencer_http` URL.
pub fn new(sequencer_http: Option<String>) -> Self {
Self(RpcAddOns::new(move |ctx| OpEthApi::new(ctx, sequencer_http), Default::default()))
/// Create a new instance with the given `sequencer_http` URL and list of storage proof-only
/// addresses.
pub fn new(sequencer_http: Option<String>, storage_proof_addresses: Vec<Address>) -> Self {
Self(RpcAddOns::new(
move |ctx| OpEthApi::new(ctx, sequencer_http, storage_proof_addresses),
Default::default(),
))
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/optimism/node/tests/it/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn test_basic_setup() {
.with_database(db)
.with_types::<OpNode>()
.with_components(OpNode::components(Default::default()))
.with_add_ons(OpAddOns::new(None))
.with_add_ons(OpAddOns::new(None, vec![]))
.on_component_initialized(move |ctx| {
let _provider = ctx.provider();
Ok(())
Expand Down
4 changes: 4 additions & 0 deletions crates/optimism/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ workspace = true
[dependencies]
# reth
reth-evm.workspace = true
reth-errors.workspace = true
reth-primitives.workspace = true
reth-provider.workspace = true
reth-rpc-eth-api.workspace = true
Expand All @@ -23,10 +24,12 @@ reth-tasks = { workspace = true, features = ["rayon"] }
reth-transaction-pool.workspace = true
reth-rpc.workspace = true
reth-rpc-api.workspace = true
reth-rpc-types-compat.workspace = true
reth-node-api.workspace = true
reth-network-api.workspace = true
reth-node-builder.workspace = true
reth-chainspec.workspace = true
reth-trie-common.workspace = true

# op-reth
reth-optimism-chainspec.workspace = true
Expand All @@ -41,6 +44,7 @@ alloy-eips.workspace = true
alloy-primitives.workspace = true
alloy-rpc-types-eth.workspace = true
alloy-rpc-types-debug.workspace = true
alloy-serde.workspace = true
alloy-consensus.workspace = true
op-alloy-network.workspace = true
op-alloy-rpc-types.workspace = true
Expand Down
103 changes: 96 additions & 7 deletions crates/optimism/rpc/src/eth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,38 @@ use reth_optimism_primitives::OpPrimitives;
use std::{fmt, sync::Arc};

use alloy_consensus::Header;
use alloy_primitives::U256;
use alloy_eips::BlockId;
use alloy_primitives::{Address, B256, U256};
use alloy_rpc_types_eth::EIP1186AccountProofResponse;
use alloy_serde::JsonStorageKey;
use derive_more::Deref;
use op_alloy_network::Optimism;
use reth_chainspec::{EthChainSpec, EthereumHardforks};
use reth_errors::RethError;
use reth_evm::ConfigureEvm;
use reth_network_api::NetworkInfo;
use reth_node_builder::EthApiBuilderCtx;
use reth_provider::{
BlockNumReader, BlockReader, BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider,
EvmEnvProvider, StageCheckpointReader, StateProviderFactory,
BlockIdReader, BlockNumReader, BlockReader, BlockReaderIdExt, CanonStateSubscriptions,
ChainSpecProvider, EvmEnvProvider, StageCheckpointReader, StateProviderFactory,
};
use reth_rpc::eth::{core::EthApiInner, DevSigner};
use reth_rpc_eth_api::{
helpers::{
AddDevSigners, EthApiSpec, EthFees, EthSigner, EthState, LoadBlock, LoadFee, LoadState,
SpawnBlocking, Trace,
},
EthApiTypes, RpcNodeCore, RpcNodeCoreExt,
EthApiTypes, FromEthApiError, RpcNodeCore, RpcNodeCoreExt,
};
use reth_rpc_eth_types::{EthStateCache, FeeHistoryCache, GasPriceOracle};
use reth_rpc_eth_types::{EthApiError, EthStateCache, FeeHistoryCache, GasPriceOracle};
use reth_rpc_types_compat::proof::from_primitive_account_proof;
use reth_tasks::{
pool::{BlockingTaskGuard, BlockingTaskPool},
TaskSpawner,
};
use reth_transaction_pool::TransactionPool;
use reth_trie_common::AccountProof;
use std::future::Future;

use crate::{OpEthApiError, SequencerClient};

Expand Down Expand Up @@ -67,6 +74,9 @@ pub struct OpEthApi<N: RpcNodeCore> {
/// Sequencer client, configured to forward submitted transactions to sequencer of given OP
/// network.
sequencer_client: Option<SequencerClient>,
/// List of addresses that _ONLY_ return storage proofs _WITHOUT_ an account proof when called
/// with `eth_getProof`.
storage_proof_only: Vec<Address>,
joshieDo marked this conversation as resolved.
Show resolved Hide resolved
}

impl<N> OpEthApi<N>
Expand All @@ -80,7 +90,11 @@ where
>,
{
/// Creates a new instance for given context.
pub fn new(ctx: &EthApiBuilderCtx<N>, sequencer_http: Option<String>) -> Self {
pub fn new(
ctx: &EthApiBuilderCtx<N>,
sequencer_http: Option<String>,
storage_proof_only: Vec<Address>,
) -> Self {
joshieDo marked this conversation as resolved.
Show resolved Hide resolved
let blocking_task_pool =
BlockingTaskPool::build().expect("failed to build blocking task pool");

Expand All @@ -100,7 +114,11 @@ where
ctx.config.proof_permits,
);

Self { inner: Arc::new(inner), sequencer_client: sequencer_http.map(SequencerClient::new) }
Self {
inner: Arc::new(inner),
sequencer_client: sequencer_http.map(SequencerClient::new),
storage_proof_only,
}
}
}

Expand Down Expand Up @@ -243,6 +261,77 @@ where
fn max_proof_window(&self) -> u64 {
self.inner.eth_proof_window()
}

fn get_proof(
&self,
address: Address,
keys: Vec<JsonStorageKey>,
block_id: Option<BlockId>,
) -> Result<
impl Future<Output = Result<EIP1186AccountProofResponse, Self::Error>> + Send,
Self::Error,
>
where
Self: EthApiSpec,
{
Ok(async move {
let _permit = self
.acquire_owned()
.await
.map_err(RethError::other)
.map_err(EthApiError::Internal)?;

let chain_info = self.chain_info().map_err(Self::Error::from_eth_err)?;
let block_id = block_id.unwrap_or_default();

// Check whether the distance to the block exceeds the maximum configured window.
let block_number = self
.provider()
.block_number_for_id(block_id)
.map_err(Self::Error::from_eth_err)?
.ok_or(EthApiError::HeaderNotFound(block_id))?;

if self.storage_proof_only.contains(&address) {
self.spawn_blocking_io(move |this| {
let b256_keys: Vec<B256> = keys.iter().map(|k| k.as_b256()).collect();
let state = this.state_at_block_id(block_number.into())?;

let proofs = state
.storage_multiproof(address, &b256_keys, Default::default())
.map_err(EthApiError::from_eth_err)?;

let account_proof = AccountProof {
address,
storage_root: proofs.root,
storage_proofs: b256_keys
.into_iter()
.map(|k| proofs.storage_proof(k))
.collect::<Result<_, _>>()
.map_err(RethError::other)
.map_err(Self::Error::from_eth_err)?,
..Default::default()
};
Ok(from_primitive_account_proof(account_proof, keys))
})
.await
} else {
let max_window = self.max_proof_window();
if chain_info.best_number.saturating_sub(block_number) > max_window {
return Err(EthApiError::ExceedsMaxProofWindow.into())
}

self.spawn_blocking_io(move |this| {
let state = this.state_at_block_id(block_id)?;
let storage_keys = keys.iter().map(|key| key.as_b256()).collect::<Vec<_>>();
let proof = state
.proof(Default::default(), address, &storage_keys)
.map_err(Self::Error::from_eth_err)?;
Ok(from_primitive_account_proof(proof, keys))
})
.await
}
})
}
}

impl<N> EthFees for OpEthApi<N>
Expand Down
Loading