diff --git a/crates/engine/primitives/src/error.rs b/crates/engine/primitives/src/error.rs index 0062d47c751..692d7e225e0 100644 --- a/crates/engine/primitives/src/error.rs +++ b/crates/engine/primitives/src/error.rs @@ -2,6 +2,7 @@ use alloc::boxed::Box; use alloy_rpc_types_engine::ForkchoiceUpdateError; use reth_errors::{BlockExecutionError, BlockValidationError, ConsensusError, ProviderError}; use reth_execution_errors::InternalBlockExecutionError; +use reth_payload_primitives::PayloadBuilderError; /// Represents all error cases when handling a new payload. /// @@ -57,6 +58,10 @@ pub enum BeaconForkChoiceUpdateError { /// Thrown when the engine task is unavailable/stopped. #[error("beacon consensus engine task stopped")] EngineUnavailable, + /// Thrown when the forkchoice update was applied, but the payload job for the provided payload + /// attributes could not be started. + #[error("failed to start payload job: {0}")] + PayloadJob(#[source] PayloadBuilderError), /// An internal error occurred, not necessarily related to the update. #[error(transparent)] Internal(Box), diff --git a/crates/engine/primitives/src/message.rs b/crates/engine/primitives/src/message.rs index 951f3196421..239fd9e06ad 100644 --- a/crates/engine/primitives/src/message.rs +++ b/crates/engine/primitives/src/message.rs @@ -4,8 +4,8 @@ use crate::{ use alloy_eips::eip4895::Withdrawal; use alloy_primitives::{Bytes, B256}; use alloy_rpc_types_engine::{ - ExecutionData, ForkChoiceUpdateResult, ForkchoiceState, ForkchoiceUpdateError, - ForkchoiceUpdated, PayloadId, PayloadStatus, PayloadStatusEnum, + ExecutionData, ForkchoiceState, ForkchoiceUpdateError, ForkchoiceUpdated, PayloadId, + PayloadStatus, PayloadStatusEnum, }; use core::{ fmt::{self, Display}, @@ -24,9 +24,12 @@ use tokio::sync::{mpsc::UnboundedSender, oneshot}; #[deprecated(note = "Use ConsensusEngineHandle instead")] pub type BeaconConsensusEngineHandle = ConsensusEngineHandle; +/// The result of a forkchoice update, or the error to return to the consensus client. +pub type OnForkChoiceUpdatedResult = Result; + /// Represents the outcome of forkchoice update. /// -/// This is a future that resolves to [`ForkChoiceUpdateResult`] +/// This is a future that resolves to [`OnForkChoiceUpdatedResult`] #[must_use = "futures do nothing unless you `.await` or poll them"] #[derive(Debug)] pub struct OnForkChoiceUpdated { @@ -36,7 +39,7 @@ pub struct OnForkChoiceUpdated { /// depending on the payload attributes, even if the forkchoice update itself is valid. forkchoice_status: ForkchoiceStatus, /// Returns the result of the forkchoice update. - fut: Either, PendingPayloadId>, + fut: Either, PendingPayloadId>, } // === impl OnForkChoiceUpdated === @@ -79,7 +82,9 @@ impl OnForkChoiceUpdated { pub fn invalid_state() -> Self { Self { forkchoice_status: ForkchoiceStatus::Invalid, - fut: Either::Left(futures::future::ready(Err(ForkchoiceUpdateError::InvalidState))), + fut: Either::Left(futures::future::ready(Err( + ForkchoiceUpdateError::InvalidState.into() + ))), } } @@ -88,7 +93,9 @@ impl OnForkChoiceUpdated { pub fn too_deep_reorg() -> Self { Self { forkchoice_status: ForkchoiceStatus::Invalid, - fut: Either::Left(futures::future::ready(Err(ForkchoiceUpdateError::TooDeepReorg))), + fut: Either::Left(futures::future::ready(Err( + ForkchoiceUpdateError::TooDeepReorg.into() + ))), } } @@ -99,12 +106,14 @@ impl OnForkChoiceUpdated { // This is valid because this is only reachable if the state and payload is valid forkchoice_status: ForkchoiceStatus::Valid, fut: Either::Left(futures::future::ready(Err( - ForkchoiceUpdateError::UpdatedInvalidPayloadAttributes, + ForkchoiceUpdateError::UpdatedInvalidPayloadAttributes.into(), ))), } } - /// If the forkchoice update was successful and no payload attributes were provided, this method + /// Creates a new instance of `OnForkChoiceUpdated` that resolves to the id of the payload job + /// started for the payload attributes, or to [`BeaconForkChoiceUpdateError::PayloadJob`] if the + /// job cannot be started. pub const fn updated_with_pending_payload_id( payload_status: PayloadStatus, pending_payload_id: oneshot::Receiver>, @@ -120,7 +129,7 @@ impl OnForkChoiceUpdated { } impl Future for OnForkChoiceUpdated { - type Output = ForkChoiceUpdateResult; + type Output = OnForkChoiceUpdatedResult; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { self.get_mut().fut.poll_unpin(cx) @@ -136,21 +145,17 @@ struct PendingPayloadId { } impl Future for PendingPayloadId { - type Output = ForkChoiceUpdateResult; + type Output = OnForkChoiceUpdatedResult; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.get_mut(); - let res = ready!(this.pending_payload_id.poll_unpin(cx)); - match res { - Ok(Ok(payload_id)) => Poll::Ready(Ok(ForkchoiceUpdated { - payload_status: this.payload_status.take().expect("Polled after completion"), - payload_id: Some(payload_id), - })), - Err(_) | Ok(Err(_)) => { - // failed to initiate a payload build job - Poll::Ready(Err(ForkchoiceUpdateError::UpdatedInvalidPayloadAttributes)) - } - } + let payload_id = ready!(this.pending_payload_id.poll_unpin(cx)) + .unwrap_or_else(|err| Err(err.into())) + .map_err(BeaconForkChoiceUpdateError::PayloadJob)?; + Poll::Ready(Ok(ForkchoiceUpdated { + payload_status: this.payload_status.take().expect("Polled after completion"), + payload_id: Some(payload_id), + })) } } @@ -380,12 +385,11 @@ where state: ForkchoiceState, payload_attrs: Option, ) -> Result { - Ok(self - .send_fork_choice_updated(state, payload_attrs) + self.send_fork_choice_updated(state, payload_attrs) .map_err(|_| BeaconForkChoiceUpdateError::EngineUnavailable) .await? .map_err(BeaconForkChoiceUpdateError::internal)? - .await?) + .await } /// Sends a forkchoice update message to the beacon consensus engine and returns the receiver to @@ -404,3 +408,45 @@ where rx } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Resolves the forkchoice update for a payload job that answers with `result`, or whose sender + /// is dropped if `result` is `None`. + fn on_payload_job( + result: Option>, + ) -> OnForkChoiceUpdatedResult { + let (tx, rx) = oneshot::channel(); + match result { + Some(result) => tx.send(result).unwrap(), + None => drop(tx), + } + OnForkChoiceUpdated::updated_with_pending_payload_id( + PayloadStatus::from_status(PayloadStatusEnum::Valid), + rx, + ) + .now_or_never() + .expect("payload job result is ready") + } + + #[test] + fn payload_job_start_errors_are_returned() { + let id = PayloadId::new([1; 8]); + assert_eq!(on_payload_job(Some(Ok(id))).unwrap().payload_id, Some(id)); + + let err = on_payload_job(Some(Err(PayloadBuilderError::MissingParentHeader(B256::ZERO)))) + .unwrap_err(); + assert!(matches!( + err, + BeaconForkChoiceUpdateError::PayloadJob(PayloadBuilderError::MissingParentHeader(_)) + )); + + let err = on_payload_job(None).unwrap_err(); + assert!(matches!( + err, + BeaconForkChoiceUpdateError::PayloadJob(PayloadBuilderError::ChannelClosed) + )); + } +} diff --git a/crates/engine/tree/src/tree/tests.rs b/crates/engine/tree/src/tree/tests.rs index e4b88ebc1aa..a8753130b2f 100644 --- a/crates/engine/tree/src/tree/tests.rs +++ b/crates/engine/tree/src/tree/tests.rs @@ -23,7 +23,9 @@ use alloy_rpc_types_engine::{ use assert_matches::assert_matches; use reth_chain_state::test_utils::TestBlockBuilder; use reth_chainspec::{ChainSpec, HOLESKY, MAINNET}; -use reth_engine_primitives::{EngineApiValidator, ForkchoiceStatus, NoopInvalidBlockHook}; +use reth_engine_primitives::{ + BeaconForkChoiceUpdateError, EngineApiValidator, ForkchoiceStatus, NoopInvalidBlockHook, +}; use reth_ethereum_consensus::EthBeaconConsensus; use reth_ethereum_engine_primitives::{EthEngineTypes, EthPayloadAttributes}; use reth_ethereum_primitives::{Block, EthPrimitives}; @@ -1812,7 +1814,10 @@ async fn test_fcu_with_canonical_ancestor_below_finalized_is_rejected() { .await .unwrap_err(); - assert_matches!(err, ForkchoiceUpdateError::TooDeepReorg); + assert_matches!( + err, + BeaconForkChoiceUpdateError::ForkchoiceUpdateError(ForkchoiceUpdateError::TooDeepReorg) + ); } // no payload build is started and the canonical head remains untouched diff --git a/crates/payload/builder/src/service.rs b/crates/payload/builder/src/service.rs index b9e2abac366..b7669c8734f 100644 --- a/crates/payload/builder/src/service.rs +++ b/crates/payload/builder/src/service.rs @@ -538,6 +538,10 @@ pub enum PayloadServiceCommand { /// /// Carries the caller's [`Span`] so the service can parent payload-building work under the /// originating Engine API trace. + /// + /// The sender receives the id of the started payload job. Answering with + /// [`PayloadBuilderError::InvalidAttributes`] rejects the payload attributes; any other error, + /// or dropping the sender, is reported to the CL as an internal error. BuildNewPayload( Box>, Span, diff --git a/crates/payload/builder/src/traits.rs b/crates/payload/builder/src/traits.rs index 89ae6ecbfa5..39a17ff6fef 100644 --- a/crates/payload/builder/src/traits.rs +++ b/crates/payload/builder/src/traits.rs @@ -112,6 +112,9 @@ pub trait PayloadJobGenerator { /// /// This is called when the CL requests a new payload job via a fork choice update. /// + /// Return [`PayloadBuilderError::InvalidAttributes`] to reject the payload attributes; any + /// other error is reported to the CL as an internal error. + /// /// # Note /// /// This is expected to initially build a new (empty) payload without transactions, so it can be diff --git a/crates/payload/primitives/src/error.rs b/crates/payload/primitives/src/error.rs index 9976bdea97d..a4ec2b78100 100644 --- a/crates/payload/primitives/src/error.rs +++ b/crates/payload/primitives/src/error.rs @@ -31,6 +31,15 @@ pub enum PayloadBuilderError { /// Any other payload building errors. #[error(transparent)] Other(Box), + /// The payload attributes are invalid on top of the parent block, e.g. a transaction they + /// include is invalid. + /// + /// Returned from `PayloadJobGenerator::new_payload_job`, this is the only variant that rejects + /// the attributes; returned later from a running job, it is an internal error like any other. + /// Failures of this node, such as a failed state read during execution, must use another + /// variant. + #[error("invalid payload attributes: {0}")] + InvalidAttributes(Box), } impl PayloadBuilderError { @@ -49,6 +58,14 @@ impl PayloadBuilderError { { Self::Other(Box::new(error)) } + + /// Create a new error that rejects the payload attributes. + pub fn invalid_attributes(error: E) -> Self + where + E: core::error::Error + Send + Sync + 'static, + { + Self::InvalidAttributes(Box::new(error)) + } } impl From for PayloadBuilderError { diff --git a/crates/rpc/rpc-engine-api/src/error.rs b/crates/rpc/rpc-engine-api/src/error.rs index 7c7dbb3b1ea..de243ba1455 100644 --- a/crates/rpc/rpc-engine-api/src/error.rs +++ b/crates/rpc/rpc-engine-api/src/error.rs @@ -214,7 +214,18 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { ); } }, + // Only attributes that the payload builder rejects are invalid payload attributes. + // Any other failure to start the payload job is a failure of this node and must + // not be reported as invalid attributes, which the consensus client would discard. + BeaconForkChoiceUpdateError::PayloadJob( + PayloadBuilderError::InvalidAttributes(_), + ) => jsonrpsee_types::error::ErrorObject::owned( + INVALID_PAYLOAD_ATTRIBUTES_ERROR, + INVALID_PAYLOAD_ATTRIBUTES_ERROR_MSG, + Some(ErrorData::new(error)), + ), BeaconForkChoiceUpdateError::EngineUnavailable | + BeaconForkChoiceUpdateError::PayloadJob(_) | BeaconForkChoiceUpdateError::Internal(_) => { jsonrpsee_types::error::ErrorObject::owned( INTERNAL_ERROR_CODE, @@ -241,6 +252,7 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { mod tests { use super::*; use alloy_rpc_types_engine::ForkchoiceUpdateError; + use reth_payload_primitives::InvalidPayloadAttributesError; #[track_caller] fn ensure_engine_rpc_error( code: i32, @@ -363,4 +375,42 @@ mod tests { ), ); } + + fn payload_job_error(err: PayloadBuilderError) -> jsonrpsee_types::error::ErrorObject<'static> { + EngineApiError::ForkChoiceUpdate(BeaconForkChoiceUpdateError::PayloadJob(err)).into() + } + + #[test] + fn payload_job_rejecting_the_attributes_is_invalid_payload_attributes() { + let err = payload_job_error(PayloadBuilderError::invalid_attributes( + InvalidPayloadAttributesError::InvalidTimestamp, + )); + + assert_eq!(err.code(), INVALID_PAYLOAD_ATTRIBUTES_ERROR); + assert_eq!(err.message(), INVALID_PAYLOAD_ATTRIBUTES_ERROR_MSG); + assert_eq!( + err.data().unwrap().get(), + r#"{"err":"failed to start payload job: invalid payload attributes: invalid timestamp"}"# + ); + } + + #[test] + fn payload_job_failing_on_this_node_is_an_internal_error() { + let node_local = [ + PayloadBuilderError::MissingParentHeader(B256::ZERO), + PayloadBuilderError::ChannelClosed, + PayloadBuilderError::other(std::io::Error::other("other")), + ]; + + for payload_job in node_local { + let message = payload_job.to_string(); + let err = payload_job_error(payload_job); + assert_eq!(err.code(), INTERNAL_ERROR_CODE, "{message}"); + assert_eq!(err.message(), SERVER_ERROR_MSG, "{message}"); + assert_eq!( + err.data().unwrap().get(), + format!(r#"{{"err":"failed to start payload job: {message}"}}"#) + ); + } + } }