Skip to content
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
5 changes: 5 additions & 0 deletions crates/engine/primitives/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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<dyn core::error::Error + Send + Sync>),
Expand Down
94 changes: 70 additions & 24 deletions crates/engine/primitives/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand All @@ -24,9 +24,12 @@ use tokio::sync::{mpsc::UnboundedSender, oneshot};
#[deprecated(note = "Use ConsensusEngineHandle instead")]
pub type BeaconConsensusEngineHandle<Payload> = ConsensusEngineHandle<Payload>;

/// The result of a forkchoice update, or the error to return to the consensus client.
pub type OnForkChoiceUpdatedResult = Result<ForkchoiceUpdated, BeaconForkChoiceUpdateError>;

/// 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 {
Expand All @@ -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<futures::future::Ready<ForkChoiceUpdateResult>, PendingPayloadId>,
fut: Either<futures::future::Ready<OnForkChoiceUpdatedResult>, PendingPayloadId>,
}

// === impl OnForkChoiceUpdated ===
Expand Down Expand Up @@ -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()
))),
}
}

Expand All @@ -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()
))),
}
}

Expand All @@ -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<Result<PayloadId, PayloadBuilderError>>,
Expand All @@ -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::Output> {
self.get_mut().fut.poll_unpin(cx)
Expand All @@ -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<Self::Output> {
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),
}))
}
}

Expand Down Expand Up @@ -380,12 +385,11 @@ where
state: ForkchoiceState,
payload_attrs: Option<Payload::PayloadAttributes>,
) -> Result<ForkchoiceUpdated, BeaconForkChoiceUpdateError> {
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
Expand All @@ -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<Result<PayloadId, PayloadBuilderError>>,
) -> 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)
));
}
}
9 changes: 7 additions & 2 deletions crates/engine/tree/src/tree/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions crates/payload/builder/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,10 @@ pub enum PayloadServiceCommand<T: PayloadTypes> {
///
/// 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<BuildNewPayload<T::PayloadAttributes>>,
Span,
Expand Down
3 changes: 3 additions & 0 deletions crates/payload/builder/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions crates/payload/primitives/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ pub enum PayloadBuilderError {
/// Any other payload building errors.
#[error(transparent)]
Other(Box<dyn core::error::Error + Send + Sync>),
/// 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<dyn core::error::Error + Send + Sync>),
}

impl PayloadBuilderError {
Expand All @@ -49,6 +58,14 @@ impl PayloadBuilderError {
{
Self::Other(Box::new(error))
}

/// Create a new error that rejects the payload attributes.
pub fn invalid_attributes<E>(error: E) -> Self
where
E: core::error::Error + Send + Sync + 'static,
{
Self::InvalidAttributes(Box::new(error))
}
}

impl From<ProviderError> for PayloadBuilderError {
Expand Down
50 changes: 50 additions & 0 deletions crates/rpc/rpc-engine-api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,18 @@ impl From<EngineApiError> 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,
Expand All @@ -241,6 +252,7 @@ impl From<EngineApiError> 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,
Expand Down Expand Up @@ -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}"}}"#)
);
}
}
}