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

feat(rpc): Setup RPC Crate #35

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
68 changes: 63 additions & 5 deletions Cargo.lock

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

21 changes: 17 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ members = [
"crates/net",
"crates/kona-providers",
"crates/rollup",
"crates/rpc",
"crates/ser",
]
default-members = ["bin/hera"]
Expand Down Expand Up @@ -133,13 +134,18 @@ alloy = { version = "0.2", features = [
"consensus",
] }
alloy-rlp = "0.3.4"
alloy-eips = { version = "0.2", default-features = false }

# Tokio
tokio = { version = "1.21", default-features = false }

# SSZ
ssz_rs = "0.9.0"

# rpc
jsonrpsee = { version = "0.24", features = ["jsonrpsee-core", "client-core", "server-core", "macros"] }
jsonrpsee-types = "0.24"

# Reth
reth = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }
reth-chainspec = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }
Expand All @@ -155,6 +161,10 @@ reth-provider = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5"
reth-revm = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }
reth-evm = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }
reth-tracing = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }
reth-rpc-types = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }
reth-rpc-eth-api = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }
reth-rpc-eth-types = { git = "https://github.com/paradigmxyz/reth", version = "1.0.5" }


# Networking
snap = "1.1.1"
Expand All @@ -164,14 +174,17 @@ libp2p-identity = { version = "0.2.9", features = [ "secp256k1" ] }
libp2p = { version = "0.54.0", features = ["macros", "tokio", "tcp", "noise", "gossipsub", "ping", "yamux"] }

# Misc
tracing = "0.1.0"
eyre = "0.6.12"
clap = "4"
url = "2.5.2"
eyre = "0.6.12"
lazy_static = "1.5.0"
futures = "0.3.30"
async-trait = "0.1.81"
tracing = "0.1.0"
thiserror = "1.0"
hashbrown = "0.14.5"
async-trait = "0.1.81"
parking_lot = "0.12.3"
unsigned-varint = "0.8.0"
serde_json = "1.0.94"
reqwest = { version = "0.12", features = ["rustls-tls-native-roots"] }
rand = { version = "0.8.3", features = ["small_rng"], default-features = false }
url = "2.5.2"
46 changes: 46 additions & 0 deletions crates/rpc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
[package]
name = "op-rpc"
description = "Consensus RPC for Rollup Nodes"
version = "0.0.0"
edition.workspace = true
rust-version.workspace = true
authors.workspace = true
license.workspace = true
repository.workspace = true
keywords.workspace = true
categories.workspace = true

[dependencies]
# op-alloy
# op-alloy-rpc-jsonrpsee isn't published yet, so we need to use the git version
op-alloy-rpc-jsonrpsee = { git = "https://github.com/alloy-rs/op-alloy", branch = "main", features = ["client"] }
op-alloy-rpc-types = { git = "https://github.com/alloy-rs/op-alloy", branch = "main" }

# Alloy
alloy-eips.workspace = true

# Misc
tracing.workspace = true
jsonrpsee.workspace = true
async-trait.workspace = true

# `reth` feature flag dependencies
alloy = { workspace = true, optional = true }
reqwest = { workspace = true, optional = true }
thiserror = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
jsonrpsee-types = { workspace = true, optional = true }
reth-rpc-types = { workspace = true, optional = true }
reth-rpc-eth-types = { workspace = true, optional = true }

[features]
default = ["reth"]
reth = [
"dep:alloy",
"dep:reqwest",
"dep:serde_json",
"dep:thiserror",
"dep:jsonrpsee-types",
"dep:reth-rpc-types",
"dep:reth-rpc-eth-types",
]
10 changes: 10 additions & 0 deletions crates/rpc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//! Consensus RPC for Rollup Nodes

#![doc(issue_tracker_base_url = "https://github.com/paradigmxyz/op-rs/issues/")]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#![cfg_attr(not(test), warn(unused_crate_dependencies))]

pub mod rollup;

#[cfg(feature = "reth")]
pub mod sequencer;
48 changes: 48 additions & 0 deletions crates/rpc/src/rollup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//! Contains the RPC Definition

use alloy_eips::BlockNumberOrTag;
use async_trait::async_trait;
use jsonrpsee::core::RpcResult;
use op_alloy_rpc_jsonrpsee::traits::RollupNodeServer;
use op_alloy_rpc_types::{
config::RollupConfig, output::OutputResponse, safe_head::SafeHeadResponse, sync::SyncStatus,
};
use tracing::trace;

/// An implementation of the [`RollupNodeServer`] trait.
#[derive(Debug, Clone)]
pub struct RollupNodeRpc {
/// The version of the node.
version: String,
}

#[async_trait]
impl RollupNodeServer for RollupNodeRpc {
async fn op_output_at_block(
&self,
block_number: BlockNumberOrTag,
) -> RpcResult<OutputResponse> {
trace!("op_output_at_block: {:?}", block_number);
unimplemented!()
}

async fn op_safe_head_at_l1_block(
&self,
block_number: BlockNumberOrTag,
) -> RpcResult<SafeHeadResponse> {
trace!("op_safe_head_at_l1_block: {:?}", block_number);
unimplemented!()
}

async fn op_sync_status(&self) -> RpcResult<SyncStatus> {
unimplemented!()
}

async fn op_rollup_config(&self) -> RpcResult<RollupConfig> {
unimplemented!()
}

async fn op_version(&self) -> RpcResult<String> {
Ok(self.version.clone())
}
}
Comment on lines +12 to +48
Copy link
Member

Choose a reason for hiding this comment

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

usually rpc extensions contain have a reth Provider, where various on disk information can be fetched. I'm assuming this rpc will be used either in the standalone binary or in the exex. For the standalone binary, I am guessing that the L1 RPC will be used for this, making the reth Provider traits the wrong abstraction. So maybe an enum would have to implement fetching each type of data:

enum ProviderType<RP, AP> {
    Local(RP), // reth provider
    Network(AP) // alloy provider
}

lmk if my understanding is off. There are probably other ways to implement this as well

Just to confirm: the op_output_at_block and op_safe_head_at_l1_block seem like the only two things that would need to fetch information from the L1 node?

114 changes: 114 additions & 0 deletions crates/rpc/src/sequencer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
//! Optimism reth RPC Extension used to forward raw transactions to the sequencer.
refcell marked this conversation as resolved.
Show resolved Hide resolved

use std::sync::{atomic::AtomicUsize, Arc};

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

/// Error type when interacting with the Sequencer
#[derive(Debug, thiserror::Error)]
pub enum SequencerRpcError {
/// Wrapper around an [`reqwest::Error`].
#[error(transparent)]
HttpError(#[from] reqwest::Error),
/// Thrown when serializing transaction to forward to sequencer
#[error("invalid sequencer transaction")]
InvalidSequencerTransaction,
}

impl ToRpcError for SequencerRpcError {
fn to_rpc_error(&self) -> ErrorObject<'static> {
ErrorObject::owned(INTERNAL_ERROR_CODE, self.to_string(), None::<String>)
}
}

impl From<SequencerRpcError> for EthApiError {
fn from(err: SequencerRpcError) -> Self {
Self::other(err)
}
}

/// A client to interact with a Sequencer
#[derive(Debug, Clone)]
pub struct SequencerClient {
inner: Arc<SequencerClientInner>,
}

impl SequencerClient {
/// Creates a new [`SequencerClient`].
pub fn new(sequencer_endpoint: impl Into<String>) -> Self {
let client = Client::builder().use_rustls_tls().build().unwrap();
Self::with_client(sequencer_endpoint, client)
}

/// Creates a new [`SequencerClient`].
pub fn with_client(sequencer_endpoint: impl Into<String>, http_client: Client) -> Self {
let inner = SequencerClientInner {
sequencer_endpoint: sequencer_endpoint.into(),
http_client,
id: AtomicUsize::new(0),
};
Self { inner: Arc::new(inner) }
}

/// Returns the network of the client
pub fn endpoint(&self) -> &str {
&self.inner.sequencer_endpoint
}

/// Returns the client
pub fn http_client(&self) -> &Client {
&self.inner.http_client
}

/// Returns the next id for the request
fn next_request_id(&self) -> usize {
self.inner.id.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
}

/// Forwards a transaction to the sequencer endpoint.
pub async fn forward_raw_transaction(&self, tx: &[u8]) -> Result<(), SequencerRpcError> {
let body = serde_json::to_string(&serde_json::json!({
"jsonrpc": "2.0",
"method": "eth_sendRawTransaction",
"params": [format!("0x{}", alloy::primitives::hex::encode(tx))],
"id": self.next_request_id()
}))
.map_err(|_| {
tracing::warn!(
target = "rpc::eth",
"Failed to serialize transaction for forwarding to sequencer"
);
SequencerRpcError::InvalidSequencerTransaction
})?;

self.http_client()
.post(self.endpoint())
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(body)
.send()
.await
.inspect_err(|err| {
tracing::warn!(
target = "rpc::eth",
%err,
"Failed to forward transaction to sequencer",
);
})
.map_err(SequencerRpcError::HttpError)?;

Ok(())
}
}

#[derive(Debug, Default)]
struct SequencerClientInner {
/// The endpoint of the sequencer
sequencer_endpoint: String,
/// The HTTP client
http_client: Client,
/// Keeps track of unique request ids
id: AtomicUsize,
}