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(sidecar): minimal module refactor + add missing docs #362

Merged
merged 2 commits into from
Nov 7, 2024
Merged
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
2 changes: 1 addition & 1 deletion bolt-sidecar/bin/sidecar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use clap::Parser;
use eyre::{bail, Result};
use tracing::info;

use bolt_sidecar::{telemetry::init_telemetry_stack, Opts, SidecarDriver};
use bolt_sidecar::{config::Opts, telemetry::init_telemetry_stack, SidecarDriver};

const BOLT: &str = r#"
██████╗ ██████╗ ██╗ ████████╗
Expand Down
12 changes: 10 additions & 2 deletions bolt-sidecar/src/api/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ use super::spec::{
STATUS_PATH,
};
use crate::{
builder::payload_fetcher::PayloadFetcher,
client::constraints_client::ConstraintsClient,
builder::PayloadFetcher,
client::ConstraintsClient,
primitives::{GetPayloadResponse, SignedBuilderBid},
telemetry::ApiMetrics,
};
Expand All @@ -39,6 +39,7 @@ const GET_HEADER_WITH_PROOFS_TIMEOUT: Duration = Duration::from_millis(500);

/// A proxy server for the builder API.
/// Forwards all requests to the target after interception.
#[derive(Debug)]
pub struct BuilderProxyServer<T, P> {
proxy_target: T,
/// INVARIANT: This will be `Some` IFF we have signed a local header for the latest slot.
Expand All @@ -47,7 +48,9 @@ pub struct BuilderProxyServer<T, P> {
payload_fetcher: P,
}

/// Parameters for the get_header request.
#[derive(Debug, Deserialize)]
#[allow(missing_docs)]
pub struct GetHeaderParams {
pub slot: u64,
pub parent_hash: Hash32,
Expand All @@ -60,6 +63,7 @@ where
T: ConstraintsApi,
P: PayloadFetcher + Send + Sync,
{
/// Create a new builder proxy server.
pub fn new(proxy_target: T, payload_fetcher: P) -> Self {
Self { proxy_target, local_payload: Mutex::new(None), payload_fetcher }
}
Expand Down Expand Up @@ -164,6 +168,8 @@ where
Ok(Json(versioned_bid))
}

/// Gets the payload. If we have a locally built payload, we return it.
/// Otherwise, we forward the request to the constraints client.
pub async fn get_payload(
State(server): State<Arc<BuilderProxyServer<T, P>>>,
req: Request<Body>,
Expand Down Expand Up @@ -259,7 +265,9 @@ async fn index() -> Html<&'static str> {
Html("Hello")
}

/// Errors that can occur when checking the integrity of a locally built payload.
#[derive(Error, Debug, Clone)]
#[allow(missing_docs)]
pub enum LocalPayloadIntegrityError {
#[error(
"Locally built payload does not match signed header.
Expand Down
22 changes: 13 additions & 9 deletions bolt-sidecar/src/api/commitments/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,18 @@ use serde_json::Value;
use tracing::{debug, error, info, instrument};

use crate::{
commitments::headers::auth_from_headers,
api::commitments::headers::auth_from_headers,
common::CARGO_PKG_VERSION,
primitives::{commitment::SignatureError, InclusionRequest},
};

use super::{
jsonrpc::{JsonPayload, JsonResponse},
server::CommitmentsApiInner,
spec::{CommitmentsApi, CommitmentError, RejectionError, GET_VERSION_METHOD, REQUEST_INCLUSION_METHOD},
spec::{
CommitmentError, CommitmentsApi, RejectionError, GET_VERSION_METHOD,
REQUEST_INCLUSION_METHOD,
},
};

/// Handler function for the root JSON-RPC path.
Expand All @@ -32,10 +35,6 @@ pub async fn rpc_entrypoint(
) -> Result<Json<JsonResponse>, CommitmentError> {
debug!("Received new request");

let (signer, signature) = auth_from_headers(&headers).inspect_err(|e| {
error!("Failed to extract signature from headers: {:?}", e);
})?;

match payload.method.as_str() {
GET_VERSION_METHOD => {
let version_string = format!("bolt-sidecar-v{CARGO_PKG_VERSION}");
Expand All @@ -47,6 +46,11 @@ pub async fn rpc_entrypoint(
}

REQUEST_INCLUSION_METHOD => {
// Validate the authentication header and extract the signer and signature
let (signer, signature) = auth_from_headers(&headers).inspect_err(|e| {
error!("Failed to extract signature from headers: {:?}", e);
})?;

let Some(request_json) = payload.params.first().cloned() else {
return Err(RejectionError::ValidationFailed("Bad params".to_string()).into());
};
Expand All @@ -66,8 +70,8 @@ pub async fn rpc_entrypoint(

if recovered_signer != signer {
error!(
?recovered_signer,
?signer,
%recovered_signer,
%signer,
"Recovered signer does not match the provided signer"
);

Expand All @@ -83,7 +87,7 @@ pub async fn rpc_entrypoint(
// Create the JSON-RPC response
let response = JsonResponse {
id: payload.id,
result: serde_json::to_value(inclusion_commitment).unwrap(),
result: serde_json::to_value(inclusion_commitment).expect("infallible"),
..Default::default()
};

Expand Down
6 changes: 3 additions & 3 deletions bolt-sidecar/src/api/commitments/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use tower_http::timeout::TimeoutLayer;
use tracing::{error, info};

use crate::{
commitments::handlers,
api::commitments::handlers,
primitives::{
commitment::{InclusionCommitment, SignedCommitment},
CommitmentRequest, InclusionRequest,
Expand All @@ -31,7 +31,7 @@ use crate::{
use super::{
middleware::track_server_metrics,
spec,
spec::{CommitmentsApi, CommitmentError},
spec::{CommitmentError, CommitmentsApi},
};

/// Event type emitted by the commitments API.
Expand Down Expand Up @@ -169,7 +169,7 @@ fn make_router(state: Arc<CommitmentsApiInner>) -> Router {

#[cfg(test)]
mod test {
use crate::commitments::{jsonrpc::JsonResponse, spec::SIGNATURE_HEADER};
use crate::api::commitments::{jsonrpc::JsonResponse, spec::SIGNATURE_HEADER};
use alloy::signers::{k256::SecretKey, local::PrivateKeySigner};
use serde_json::json;

Expand Down
6 changes: 5 additions & 1 deletion bolt-sidecar/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ use ethereum_consensus::{

use crate::{
common::BlsSecretKeyWrapper,
config::{ChainConfig, Opts},
primitives::{
BuilderBid, GetPayloadResponse, PayloadAndBid, PayloadAndBlobs, SignedBuilderBid,
},
ChainConfig, Opts,
};

/// Basic block template handler that can keep track of
/// the local commitments according to protocol validity rules.
///
/// The built template can be used as a fallback block in case of no valid
/// response from all relays.
pub mod template;
pub use template::BlockTemplate;

Expand All @@ -30,6 +33,7 @@ use payload_builder::FallbackPayloadBuilder;

/// Interface for fetching payloads from the beacon node.
pub mod payload_fetcher;
pub use payload_fetcher::{LocalPayloadFetcher, PayloadFetcher};

/// Compatibility types and utilities between Alloy, Reth,
/// Ethereum-consensus and other crates.
Expand Down
6 changes: 5 additions & 1 deletion bolt-sidecar/src/builder/payload_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ use super::{
compat::{to_alloy_execution_payload, to_reth_withdrawal},
BuilderError,
};
use crate::{BeaconClient, Opts, RpcClient};

use crate::{
client::{BeaconClient, RpcClient},
config::Opts,
};

/// Extra-data payload field used for locally built blocks, decoded in UTF-8.
///
Expand Down
4 changes: 2 additions & 2 deletions bolt-sidecar/src/builder/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use ethereum_consensus::{
use tree_hash::TreeHash;
use tree_hash_derive::TreeHash;

use crate::ChainConfig;
use crate::config::ChainConfig;

/// Sign a SSZ object with a BLS secret key, using the Application Builder domain
/// for signing arbitrary builder-api messages in the out-of-protocol specifications.
Expand Down Expand Up @@ -116,7 +116,7 @@ pub fn compute_builder_domain(

#[cfg(test)]
mod tests {
use crate::{builder::signature::compute_builder_domain, ChainConfig};
use crate::{builder::signature::compute_builder_domain, config::ChainConfig};

#[test]
fn test_compute_builder_domain() {
Expand Down
3 changes: 0 additions & 3 deletions bolt-sidecar/src/builder/template.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
//! Package `template` contains the functionality for building local block templates that can
//! be used as a fallback. It's also used to keep any intermediary state that is needed to simulate
//! new commitment requests.
use std::collections::HashMap;

use alloy::primitives::{Address, U256};
Expand Down
1 change: 1 addition & 0 deletions bolt-sidecar/src/chain_io/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// Wrapper over the BoltManager contract
pub mod manager;
pub use manager::BoltManager;

/// Utilities and functions used in the Bolt contracts
pub mod utils;
4 changes: 0 additions & 4 deletions bolt-sidecar/src/client/constraints_client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
//! Module for interacting with the Constraints client API via its Builder API interface.
//! The Bolt sidecar's main purpose is to sit between the beacon node and Constraints client,
//! so most requests are simply proxied to its API.

use std::collections::HashSet;

use axum::http::StatusCode;
Expand Down
12 changes: 8 additions & 4 deletions bolt-sidecar/src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
/// Module for interacting with the Constraints client API via its Builder API interface.
/// The Bolt sidecar's main purpose is to sit between the beacon node and Constraints client,
/// so most requests are simply proxied to its API.
pub mod constraints_client;
pub mod pubsub;
pub use constraints_client::ConstraintsClient;

/// Module defining an RpcClient wrapper around the [`alloy::rpc::client::RpcClient`].
/// It provides a simple interface to interact with the Execution layer JSON-RPC API.
pub mod rpc;
pub use rpc::RpcClient;

// Re-export the beacon_api_client
pub use beacon_api_client::mainnet::Client as BeaconClient;

#[cfg(test)]
mod test_util;
42 changes: 0 additions & 42 deletions bolt-sidecar/src/client/pubsub.rs

This file was deleted.

4 changes: 1 addition & 3 deletions bolt-sidecar/src/client/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
//! This module contains the `RpcClient` struct, which is a wrapper around the `alloy_rpc_client`.
//! It provides a simple interface to interact with the Execution layer JSON-RPC API.

use std::ops::{Deref, DerefMut};

use alloy::{
Expand Down Expand Up @@ -114,6 +111,7 @@ impl RpcClient {
}

/// Send a raw transaction to the network.
#[allow(unused)]
pub async fn send_raw_transaction(&self, raw: Bytes) -> TransportResult<B256> {
self.0.request("eth_sendRawTransaction", [raw]).await
}
Expand Down
Loading
Loading