Skip to content

Commit

Permalink
remove transaction forwarder trait
Browse files Browse the repository at this point in the history
 ref fields by name

add set_sequencer_client
  • Loading branch information
nkysg committed Aug 26, 2024
1 parent ec31b24 commit 6083862
Show file tree
Hide file tree
Showing 17 changed files with 92 additions and 152 deletions.
5 changes: 4 additions & 1 deletion Cargo.lock

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

1 change: 1 addition & 0 deletions bin/reth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ reth-engine-util.workspace = true
reth-prune.workspace = true
reth-stages-api.workspace = true
reth-optimism-cli = { workspace = true, optional = true }
reth-optimism-rpc.workspace = true

# crypto
alloy-rlp.workspace = true
Expand Down
18 changes: 8 additions & 10 deletions bin/reth/src/optimism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@
use clap::Parser;
use reth::cli::Cli;
use reth_node_builder::EngineNodeLauncher;
use reth_node_optimism::{
args::RollupArgs, node::OptimismAddOns, rpc::SequencerClient, OptimismNode,
};
use reth_node_optimism::{args::RollupArgs, node::OptimismAddOns, OptimismNode};
use reth_optimism_rpc::eth::rpc::SequencerClient;
use reth_provider::providers::BlockchainProvider2;
use std::sync::Arc;

// We use jemalloc for performance reasons
#[cfg(all(feature = "jemalloc", unix))]
Expand Down Expand Up @@ -38,9 +36,9 @@ fn main() {
.extend_rpc_modules(move |ctx| {
// register sequencer tx forwarder
if let Some(sequencer_http) = sequencer_http_arg {
ctx.registry.set_eth_raw_transaction_forwarder(Arc::new(
SequencerClient::new(sequencer_http),
));
ctx.registry
.eth_api()
.set_sequencer_client(SequencerClient::new(sequencer_http));
}

Ok(())
Expand All @@ -62,9 +60,9 @@ fn main() {
.extend_rpc_modules(move |ctx| {
// register sequencer tx forwarder
if let Some(sequencer_http) = sequencer_http_arg {
ctx.registry.set_eth_raw_transaction_forwarder(Arc::new(
SequencerClient::new(sequencer_http),
));
ctx.registry
.eth_api()
.set_sequencer_client(SequencerClient::new(sequencer_http));
}

Ok(())
Expand Down
2 changes: 0 additions & 2 deletions crates/optimism/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ pub use node::OptimismNode;

pub mod txpool;

pub mod rpc;

pub use reth_optimism_payload_builder::{
OptimismBuiltPayload, OptimismPayloadBuilder, OptimismPayloadBuilderAttributes,
};
Expand Down
4 changes: 3 additions & 1 deletion crates/optimism/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,15 @@ revm.workspace = true
# async
parking_lot.workspace = true
tokio.workspace = true
reqwest = { workspace = true, features = ["rustls-tls-native-roots"] }

# rpc
jsonrpsee-types.workspace = true
serde_json.workspace = true

# misc
thiserror.workspace = true
derive_more.workspace = true
tracing.workspace = true

[features]
optimism = [
Expand Down
22 changes: 17 additions & 5 deletions crates/optimism/rpc/src/eth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ pub mod transaction;
mod block;
mod call;
mod pending_block;
pub mod rpc;

use std::{fmt, sync::Arc};

use crate::eth::rpc::SequencerClient;
use alloy_primitives::U256;
use derive_more::Deref;
use op_alloy_network::Optimism;
use reth_chainspec::ChainSpec;
use reth_evm::ConfigureEvm;
Expand Down Expand Up @@ -56,10 +57,9 @@ pub type EthApiNodeBackend<N> = EthApiInner<
///
/// This type implements the [`FullEthApi`](reth_rpc_eth_api::helpers::FullEthApi) by implemented
/// all the `Eth` helper traits and prerequisite traits.
#[derive(Clone, Deref)]
pub struct OpEthApi<N: FullNodeComponents> {
#[deref]
inner: Arc<EthApiNodeBackend<N>>,
sequencer_client: parking_lot::RwLock<Option<SequencerClient>>,
}

impl<N: FullNodeComponents> OpEthApi<N> {
Expand All @@ -81,11 +81,23 @@ impl<N: FullNodeComponents> OpEthApi<N> {
ctx.new_fee_history_cache(),
ctx.evm_config.clone(),
ctx.executor.clone(),
None,
ctx.config.proof_permits,
);

Self { inner: Arc::new(inner) }
Self { inner: Arc::new(inner), sequencer_client: parking_lot::RwLock::new(None) }
}
}

impl<N> Clone for OpEthApi<N>
where
N: FullNodeComponents,
Self: Send + Sync,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
sequencer_client: parking_lot::RwLock::new(self.sequencer_client.read().clone()),
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use std::sync::{atomic::AtomicUsize, Arc};

use jsonrpsee_types::error::{ErrorObject, INTERNAL_ERROR_CODE};
use reqwest::Client;
use reth_rpc_eth_api::RawTransactionForwarder;
use reth_rpc_eth_types::error::{EthApiError, EthResult};
use reth_rpc_eth_types::error::EthApiError;
use reth_rpc_types::ToRpcError;

/// Error type when interacting with the Sequencer
Expand Down Expand Up @@ -104,14 +103,6 @@ impl SequencerClient {
}
}

#[async_trait::async_trait]
impl RawTransactionForwarder for SequencerClient {
async fn forward_raw_transaction(&self, tx: &[u8]) -> EthResult<()> {
Self::forward_raw_transaction(self, tx).await?;
Ok(())
}
}

#[derive(Debug, Default)]
struct SequencerClientInner {
/// The endpoint of the sequencer
Expand Down
54 changes: 46 additions & 8 deletions crates/optimism/rpc/src/eth/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
//! Loads and formats OP transaction RPC response.
use std::sync::Arc;
use alloy_primitives::{Bytes, B256};

use reth_evm_optimism::RethL1BlockInfo;
use reth_node_api::FullNodeComponents;
use reth_primitives::TransactionSigned;
use reth_provider::{BlockReaderIdExt, TransactionsProvider};
use reth_rpc_eth_api::{
helpers::{EthApiSpec, EthSigner, EthTransactions, LoadTransaction, SpawnBlocking},
EthApiTypes, RawTransactionForwarder,
EthApiTypes, FromEthApiError,
};
use reth_rpc_eth_types::EthStateCache;
use reth_rpc_eth_types::{utils::recover_raw_transaction, EthStateCache};
use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool};
use revm::L1BlockInfo;

use crate::{OpEthApi, OpEthApiError};
use crate::{eth::rpc::SequencerClient, OpEthApi, OpEthApiError};

impl<N> EthTransactions for OpEthApi<N>
where
Expand All @@ -24,13 +25,35 @@ where
self.inner.provider()
}

fn raw_tx_forwarder(&self) -> Option<Arc<dyn RawTransactionForwarder>> {
self.inner.raw_tx_forwarder()
}

fn signers(&self) -> &parking_lot::RwLock<Vec<Box<dyn EthSigner>>> {
self.inner.signers()
}

/// Decodes and recovers the transaction and submits it to the pool.
///
/// Returns the hash of the transaction.
async fn send_raw_transaction(&self, tx: Bytes) -> Result<B256, Self::Error> {
let recovered = recover_raw_transaction(tx.clone())?;
let pool_transaction = <Self::Pool as TransactionPool>::Transaction::from_pooled(recovered);

// On optimism, transactions are forwarded directly to the sequencer to be included in
// blocks that it builds.
if let Some(client) = self.raw_tx_forwarder().as_ref() {
tracing::debug!( target: "rpc::eth", "forwarding raw transaction to");
let _ = client.forward_raw_transaction(&tx).await.inspect_err(|err| {
tracing::debug!(target: "rpc::eth", %err, hash=% *pool_transaction.hash(), "failed to forward raw transaction");
});
}

// submit the transaction to the pool with a `Local` origin
let hash = self
.pool()
.add_transaction(TransactionOrigin::Local, pool_transaction)
.await
.map_err(Self::Error::from_eth_err)?;

Ok(hash)
}
}

impl<N> LoadTransaction for OpEthApi<N>
Expand Down Expand Up @@ -113,3 +136,18 @@ where
Ok(OptimismTxMeta::new(Some(l1_block_info), l1_fee, l1_data_gas))
}
}

impl<N> OpEthApi<N>
where
N: FullNodeComponents,
{
/// Sets a `SequencerClient` for `eth_sendRawTransaction` to forward transactions to.
pub fn set_sequencer_client(&self, sequencer_client: SequencerClient) {
*self.sequencer_client.write() = Some(sequencer_client);
}

/// Returns the `SequencerClient` if one is set.
pub fn raw_tx_forwarder(&self) -> Option<SequencerClient> {
self.sequencer_client.read().clone()
}
}
21 changes: 2 additions & 19 deletions crates/rpc/rpc-builder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@
use std::{
collections::HashMap,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};

Expand Down Expand Up @@ -165,10 +164,8 @@ use reth_rpc::{
};
use reth_rpc_api::servers::*;
use reth_rpc_eth_api::{
helpers::{
Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt, UpdateRawTxForwarder,
},
EthApiServer, FullEthApiServer, RawTransactionForwarder,
helpers::{Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt},
EthApiServer, FullEthApiServer,
};
use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider};
use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret};
Expand Down Expand Up @@ -741,20 +738,6 @@ impl<Provider, Pool, Network, Tasks, Events, EthApi>
}
}

impl<Provider, Pool, Network, Tasks, Events, EthApi>
RpcRegistryInner<Provider, Pool, Network, Tasks, Events, EthApi>
where
EthApi: UpdateRawTxForwarder,
{
/// Sets a forwarder for `eth_sendRawTransaction`
///
/// Note: this might be removed in the future in favor of a more generic approach.
pub fn set_eth_raw_transaction_forwarder(&self, forwarder: Arc<dyn RawTransactionForwarder>) {
// in case the eth api has been created before the forwarder was set: <https://github.com/paradigmxyz/reth/issues/8661>
self.eth.api.set_eth_raw_transaction_forwarder(forwarder.clone());
}
}

impl<Provider, Pool, Network, Tasks, Events, EthApi>
RpcRegistryInner<Provider, Pool, Network, Tasks, Events, EthApi>
where
Expand Down
9 changes: 2 additions & 7 deletions crates/rpc/rpc-eth-api/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,21 @@ use tracing::trace;

use crate::{
helpers::{
transaction::UpdateRawTxForwarder, EthApiSpec, EthBlocks, EthCall, EthFees, EthState,
EthTransactions, FullEthApi, LoadState,
EthApiSpec, EthBlocks, EthCall, EthFees, EthState, EthTransactions, FullEthApi, LoadState,
},
RpcBlock, RpcTransaction,
};

/// Helper trait, unifies functionality that must be supported to implement all RPC methods for
/// server.
pub trait FullEthApiServer:
EthApiServer<RpcTransaction<Self::NetworkTypes>, RpcBlock<Self::NetworkTypes>>
+ FullEthApi
+ UpdateRawTxForwarder
+ Clone
EthApiServer<RpcTransaction<Self::NetworkTypes>, RpcBlock<Self::NetworkTypes>> + FullEthApi + Clone
{
}

impl<T> FullEthApiServer for T where
T: EthApiServer<RpcTransaction<T::NetworkTypes>, RpcBlock<T::NetworkTypes>>
+ FullEthApi
+ UpdateRawTxForwarder
+ Clone
{
}
Expand Down
2 changes: 1 addition & 1 deletion crates/rpc/rpc-eth-api/src/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub use signer::{AddDevSigners, EthSigner};
pub use spec::EthApiSpec;
pub use state::{EthState, LoadState};
pub use trace::Trace;
pub use transaction::{EthTransactions, LoadTransaction, UpdateRawTxForwarder};
pub use transaction::{EthTransactions, LoadTransaction};

use crate::EthApiTypes;

Expand Down
Loading

0 comments on commit 6083862

Please sign in to comment.