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

refactor(l1): pass context to all RpcHandlers #1039

Merged
merged 3 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
6 changes: 3 additions & 3 deletions crates/networking/rpc/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub enum AuthenticationError {
}

pub fn authenticate(
secret: Bytes,
secret: &Bytes,
auth_header: Option<TypedHeader<Authorization<Bearer>>>,
) -> Result<(), RpcErr> {
match auth_header {
Expand All @@ -39,8 +39,8 @@ struct Claims {
}

/// Authenticates bearer jwt to check that authrpc calls are sent by the consensus layer
pub fn validate_jwt_authentication(token: &str, secret: Bytes) -> Result<(), AuthenticationError> {
let decoding_key = DecodingKey::from_secret(&secret);
pub fn validate_jwt_authentication(token: &str, secret: &Bytes) -> Result<(), AuthenticationError> {
let decoding_key = DecodingKey::from_secret(secret);
let mut validation = Validation::new(Algorithm::HS256);
validation.validate_exp = false;
validation.set_required_spec_claims(&["iat"]);
Expand Down
11 changes: 6 additions & 5 deletions crates/networking/rpc/engine/exchange_transition_config.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use ethereum_rust_core::{serde_utils, H256};
use ethereum_rust_storage::Store;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::{info, warn};

use crate::{utils::RpcErr, RpcHandler};
use crate::{utils::RpcErr, RpcApiContext, RpcHandler};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -45,11 +44,11 @@ impl RpcHandler for ExchangeTransitionConfigV1Req {
Ok(ExchangeTransitionConfigV1Req { payload })
}

fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
info!("Received new engine request: {self}");
let payload = &self.payload;

let chain_config = storage.get_chain_config()?;
let chain_config = context.storage.get_chain_config()?;
let terminal_total_difficulty = chain_config.terminal_total_difficulty;

if terminal_total_difficulty.unwrap_or_default() != payload.terminal_total_difficulty {
Expand All @@ -59,7 +58,9 @@ impl RpcHandler for ExchangeTransitionConfigV1Req {
);
};

let block = storage.get_block_header(payload.terminal_block_number)?;
let block = context
.storage
.get_block_header(payload.terminal_block_number)?;
let terminal_block_hash = block.map_or(H256::zero(), |block| block.compute_block_hash());

serde_json::to_value(ExchangeTransitionConfigPayload {
Expand Down
12 changes: 6 additions & 6 deletions crates/networking/rpc/engine/fork_choice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use ethereum_rust_blockchain::{
latest_canonical_block_hash,
payload::{create_payload, BuildPayloadArgs},
};
use ethereum_rust_storage::Store;
use serde_json::Value;
use tracing::{info, warn};

Expand All @@ -14,7 +13,7 @@ use crate::{
payload::PayloadStatus,
},
utils::RpcRequest,
RpcErr, RpcHandler,
RpcApiContext, RpcErr, RpcHandler,
};

#[derive(Debug)]
Expand Down Expand Up @@ -58,7 +57,8 @@ impl RpcHandler for ForkChoiceUpdatedV3 {
})
}

fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
let storage = &context.storage;
info!(
"New fork choice request with head: {}, safe: {}, finalized: {}.",
self.fork_choice_state.head_block_hash,
Expand All @@ -68,7 +68,7 @@ impl RpcHandler for ForkChoiceUpdatedV3 {
let fork_choice_error_to_response = |error| {
let response = match error {
InvalidForkChoice::NewHeadAlreadyCanonical => ForkChoiceResponse::from(
PayloadStatus::valid_with_hash(latest_canonical_block_hash(&storage).unwrap()),
PayloadStatus::valid_with_hash(latest_canonical_block_hash(storage).unwrap()),
),
InvalidForkChoice::Syncing => ForkChoiceResponse::from(PayloadStatus::syncing()),
reason => {
Expand All @@ -83,7 +83,7 @@ impl RpcHandler for ForkChoiceUpdatedV3 {
};

let head_block = match apply_fork_choice(
&storage,
storage,
self.fork_choice_state.head_block_hash,
self.fork_choice_state.safe_block_hash,
self.fork_choice_state.finalized_block_hash,
Expand Down Expand Up @@ -125,7 +125,7 @@ impl RpcHandler for ForkChoiceUpdatedV3 {
};
let payload_id = args.id();
response.set_id(payload_id);
let payload = match create_payload(&args, &storage) {
let payload = match create_payload(&args, storage) {
Ok(payload) => payload,
Err(ChainError::EvmError(error)) => return Err(error.into()),
// Parent block is guaranteed to be present at this point,
Expand Down
4 changes: 2 additions & 2 deletions crates/networking/rpc/engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ pub mod exchange_transition_config;
pub mod fork_choice;
pub mod payload;

use crate::{utils::RpcRequest, RpcErr, RpcHandler, Store};
use crate::{utils::RpcRequest, RpcApiContext, RpcErr, RpcHandler};
use serde_json::{json, Value};

pub type ExchangeCapabilitiesRequest = Vec<String>;
Expand Down Expand Up @@ -30,7 +30,7 @@ impl RpcHandler for ExchangeCapabilitiesRequest {
})
}

fn handle(&self, _storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, _context: RpcApiContext) -> Result<Value, RpcErr> {
Ok(json!(*self))
}
}
13 changes: 7 additions & 6 deletions crates/networking/rpc/engine/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ use ethereum_rust_blockchain::error::ChainError;
use ethereum_rust_blockchain::payload::build_payload;
use ethereum_rust_core::types::Fork;
use ethereum_rust_core::{H256, U256};
use ethereum_rust_storage::Store;
use serde_json::Value;
use tracing::{error, info, warn};

use crate::types::payload::ExecutionPayloadResponse;
use crate::utils::RpcRequest;
use crate::RpcApiContext;
use crate::{
types::payload::{ExecutionPayloadV3, PayloadStatus},
RpcErr, RpcHandler,
Expand Down Expand Up @@ -56,7 +56,8 @@ impl RpcHandler for NewPayloadV3Request {
})
}

fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
let storage = &context.storage;
let block_hash = self.payload.block_hash;
info!("Received new payload with block hash: {block_hash:#x}");

Expand Down Expand Up @@ -114,7 +115,7 @@ impl RpcHandler for NewPayloadV3Request {

// Execute and store the block
info!("Executing payload with block hash: {block_hash:#x}");
let payload_status = match add_block(&block, &storage) {
let payload_status = match add_block(&block, storage) {
Err(ChainError::ParentNotFound) => Ok(PayloadStatus::syncing()),
// Under the current implementation this is not possible: we always calculate the state
// transition of any new payload as long as the parent is present. If we received the
Expand Down Expand Up @@ -185,15 +186,15 @@ impl RpcHandler for GetPayloadV3Request {
Ok(GetPayloadV3Request { payload_id })
}

fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
info!("Requested payload with id: {:#018x}", self.payload_id);
let Some(mut payload) = storage.get_payload(self.payload_id)? else {
let Some(mut payload) = context.storage.get_payload(self.payload_id)? else {
return Err(RpcErr::UnknownPayload(format!(
"Payload with id {:#018x} not found",
self.payload_id
)));
};
let (blobs_bundle, block_value) = build_payload(&mut payload, &storage)
let (blobs_bundle, block_value) = build_payload(&mut payload, &context.storage)
.map_err(|err| RpcErr::Internal(err.to_string()))?;
serde_json::to_value(ExecutionPayloadResponse {
execution_payload: ExecutionPayloadV3::from_block(payload),
Expand Down
36 changes: 21 additions & 15 deletions crates/networking/rpc/eth/account.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use ethereum_rust_storage::Store;
use serde_json::Value;
use tracing::info;

use crate::types::account_proof::{AccountProof, StorageProof};
use crate::types::block_identifier::BlockIdentifierOrHash;
use crate::RpcApiContext;
use crate::{utils::RpcErr, RpcHandler};
use ethereum_rust_core::{Address, BigEndianHash, H256, U256};

Expand Down Expand Up @@ -47,19 +47,21 @@ impl RpcHandler for GetBalanceRequest {
block: BlockIdentifierOrHash::parse(params[1].clone(), 1)?,
})
}
fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
info!(
"Requested balance of account {} at block {}",
self.address, self.block
);

let Some(block_number) = self.block.resolve_block_number(&storage)? else {
let Some(block_number) = self.block.resolve_block_number(&context.storage)? else {
return Err(RpcErr::Internal(
"Could not resolve block number".to_owned(),
)); // Should we return Null here?
};

let account = storage.get_account_info(block_number, self.address)?;
let account = context
.storage
.get_account_info(block_number, self.address)?;
let balance = account.map(|acc| acc.balance).unwrap_or_default();

serde_json::to_value(format!("{:#x}", balance))
Expand All @@ -80,19 +82,20 @@ impl RpcHandler for GetCodeRequest {
block: BlockIdentifierOrHash::parse(params[1].clone(), 1)?,
})
}
fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
info!(
"Requested code of account {} at block {}",
self.address, self.block
);

let Some(block_number) = self.block.resolve_block_number(&storage)? else {
let Some(block_number) = self.block.resolve_block_number(&context.storage)? else {
return Err(RpcErr::Internal(
"Could not resolve block number".to_owned(),
)); // Should we return Null here?
};

let code = storage
let code = context
.storage
.get_code_by_account_address(block_number, self.address)?
.unwrap_or_default();

Expand All @@ -115,19 +118,20 @@ impl RpcHandler for GetStorageAtRequest {
block: BlockIdentifierOrHash::parse(params[2].clone(), 2)?,
})
}
fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
info!(
"Requested storage sot {} of account {} at block {}",
self.storage_slot, self.address, self.block
);

let Some(block_number) = self.block.resolve_block_number(&storage)? else {
let Some(block_number) = self.block.resolve_block_number(&context.storage)? else {
return Err(RpcErr::Internal(
"Could not resolve block number".to_owned(),
)); // Should we return Null here?
};

let storage_value = storage
let storage_value = context
.storage
.get_storage_at(block_number, self.address, self.storage_slot)?
.unwrap_or_default();
let storage_value = H256::from_uint(&storage_value);
Expand All @@ -149,19 +153,20 @@ impl RpcHandler for GetTransactionCountRequest {
block: BlockIdentifierOrHash::parse(params[1].clone(), 1)?,
})
}
fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
info!(
"Requested nonce of account {} at block {}",
self.address, self.block
);

let Some(block_number) = self.block.resolve_block_number(&storage)? else {
let Some(block_number) = self.block.resolve_block_number(&context.storage)? else {
return Err(RpcErr::Internal(
"Could not resolve block number".to_owned(),
)); // Should we return Null here?
};

let nonce = storage
let nonce = context
.storage
.get_nonce_by_account_address(block_number, self.address)?
.unwrap_or_default();

Expand All @@ -187,12 +192,13 @@ impl RpcHandler for GetProofRequest {
})
}

fn handle(&self, storage: Store) -> Result<Value, RpcErr> {
fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
let storage = &context.storage;
info!(
"Requested proof for account {} at block {} with storage keys: {:?}",
self.address, self.block, self.storage_keys
);
let Some(block_number) = self.block.resolve_block_number(&storage)? else {
let Some(block_number) = self.block.resolve_block_number(storage)? else {
return Ok(Value::Null);
};
// Create account proof
Expand Down
Loading
Loading