Skip to main content

reth_engine_tree/
engine.rs

1//! An engine API handler for the chain.
2
3use crate::{
4    backfill::BackfillAction,
5    chain::{ChainHandler, FromOrchestrator, HandlerEvent},
6    download::{BlockDownloader, DownloadAction, DownloadOutcome},
7};
8use alloy_eips::BlockNumHash;
9use alloy_primitives::{map::B256Set, B256};
10use futures::{Stream, StreamExt};
11use reth_concurrency::sync::channel::Sender;
12use reth_engine_primitives::{BeaconEngineMessage, ConsensusEngineEvent};
13use reth_ethereum_primitives::EthPrimitives;
14use reth_network_p2p::full_block::{SealedBlockWithAccessList, StartNumberMismatch};
15use reth_payload_primitives::{BuiltPayloadExecutedBlock, PayloadTypes};
16use reth_primitives_traits::{Block, NodePrimitives};
17use std::{
18    fmt::Display,
19    task::{ready, Context, Poll},
20};
21use tokio::sync::mpsc::UnboundedReceiver;
22
23/// A [`ChainHandler`] that advances the chain based on incoming requests (CL engine API).
24///
25/// This is a general purpose request handler with network access.
26/// This type listens for incoming messages and processes them via the configured request handler.
27///
28/// ## Overview
29///
30/// This type is an orchestrator for incoming messages and responsible for delegating requests
31/// received from the CL to the handler.
32///
33/// It is responsible for handling the following:
34/// - Delegating incoming requests to the [`EngineRequestHandler`].
35/// - Advancing the [`EngineRequestHandler`] by polling it and emitting events.
36/// - Downloading blocks on demand from the network if requested by the [`EngineApiRequestHandler`].
37///
38/// The core logic is part of the [`EngineRequestHandler`], which is responsible for processing the
39/// incoming requests.
40#[derive(Debug)]
41pub struct EngineHandler<T, S, D> {
42    /// Processes requests.
43    ///
44    /// This type is responsible for processing incoming requests.
45    handler: T,
46    /// Receiver for incoming requests (from the engine API endpoint) that need to be processed.
47    incoming_requests: S,
48    /// A downloader to download blocks on demand.
49    downloader: D,
50}
51
52impl<T, S, D> EngineHandler<T, S, D> {
53    /// Creates a new [`EngineHandler`] with the given handler and downloader and incoming stream of
54    /// requests.
55    pub const fn new(handler: T, downloader: D, incoming_requests: S) -> Self
56    where
57        T: EngineRequestHandler,
58    {
59        Self { handler, incoming_requests, downloader }
60    }
61
62    /// Returns a mutable reference to the request handler.
63    pub const fn handler_mut(&mut self) -> &mut T {
64        &mut self.handler
65    }
66}
67
68impl<T, S, D> ChainHandler for EngineHandler<T, S, D>
69where
70    T: EngineRequestHandler<Block = D::Block>,
71    S: Stream + Send + Sync + Unpin + 'static,
72    <S as Stream>::Item: Into<T::Request>,
73    D: BlockDownloader,
74{
75    type Event = T::Event;
76
77    fn on_event(&mut self, event: FromOrchestrator) {
78        // delegate event to the handler
79        self.handler.on_event(event.into());
80    }
81
82    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<HandlerEvent<Self::Event>> {
83        loop {
84            // drain the handler first
85            while let Poll::Ready(ev) = self.handler.poll(cx) {
86                match ev {
87                    RequestHandlerEvent::HandlerEvent(ev) => {
88                        return match ev {
89                            HandlerEvent::BackfillAction(target) => {
90                                // bubble up backfill sync request
91                                // Only a new run, not a target update, makes downloads stale.
92                                if matches!(target, BackfillAction::Start(_)) {
93                                    self.downloader.on_action(DownloadAction::Clear);
94                                }
95                                Poll::Ready(HandlerEvent::BackfillAction(target))
96                            }
97                            HandlerEvent::Event(ev) => {
98                                // bubble up the event
99                                Poll::Ready(HandlerEvent::Event(ev))
100                            }
101                            HandlerEvent::FatalError => Poll::Ready(HandlerEvent::FatalError),
102                        }
103                    }
104                    RequestHandlerEvent::Download(req) => {
105                        // delegate download request to the downloader
106                        self.downloader.on_action(DownloadAction::Download(req));
107                    }
108                }
109            }
110
111            // pop the next incoming request
112            if let Poll::Ready(Some(req)) = self.incoming_requests.poll_next_unpin(cx) {
113                // and delegate the request to the handler
114                self.handler.on_event(FromEngine::Request(req.into()));
115                // skip downloading in this iteration to allow the handler to process the request
116                continue
117            }
118
119            // advance the downloader
120            if let Poll::Ready(outcome) = self.downloader.poll(cx) {
121                match outcome {
122                    // delegate the downloaded blocks to the handler
123                    DownloadOutcome::Blocks(blocks) => {
124                        self.handler.on_event(FromEngine::DownloadedBlocks(blocks))
125                    }
126                    DownloadOutcome::StartNumberMismatch(mismatch) => {
127                        self.handler.on_event(FromEngine::StartNumberMismatch(mismatch))
128                    }
129                    DownloadOutcome::NewDownloadStarted { .. } => {}
130                }
131                continue
132            }
133
134            return Poll::Pending
135        }
136    }
137}
138
139/// A type that processes incoming requests (e.g. requests from the consensus layer, engine API,
140/// such as newPayload).
141///
142/// ## Control flow
143///
144/// Requests and certain updates, such as a change in backfill sync status, are delegated to this
145/// type via [`EngineRequestHandler::on_event`]. This type is responsible for processing the
146/// incoming requests and advancing the chain and emit events when it is polled.
147pub trait EngineRequestHandler: Send + Sync {
148    /// Event type this handler can emit
149    type Event: Send;
150    /// The request type this handler can process.
151    type Request;
152    /// Type of the block sent in [`FromEngine::DownloadedBlocks`] variant.
153    type Block: Block;
154
155    /// Informs the handler about an event from the [`EngineHandler`].
156    fn on_event(&mut self, event: FromEngine<Self::Request, Self::Block>);
157
158    /// Advances the handler.
159    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<RequestHandlerEvent<Self::Event>>;
160}
161
162/// An [`EngineRequestHandler`] that processes engine API requests by delegating to an execution
163/// task.
164///
165/// This type is responsible for advancing the chain during live sync (following the tip of the
166/// chain).
167///
168/// It advances the chain based on received engine API requests by delegating them to the tree
169/// executor.
170///
171/// There are two types of requests that can be processed:
172///
173/// - `on_new_payload`: Executes the payload and inserts it into the tree. These are allowed to be
174///   processed concurrently.
175/// - `on_forkchoice_updated`: Updates the fork choice based on the new head. These require write
176///   access to the database and are skipped if the handler can't acquire exclusive access to the
177///   database.
178///
179/// In case required blocks are missing, the handler will request them from the network, by emitting
180/// a download request upstream.
181#[derive(Debug)]
182pub struct EngineApiRequestHandler<Request, N: NodePrimitives> {
183    /// channel to send messages to the tree to execute the payload.
184    to_tree: Sender<FromEngine<Request, N::Block>>,
185    /// channel to receive messages from the tree.
186    from_tree: UnboundedReceiver<EngineApiEvent<N>>,
187}
188
189impl<Request, N: NodePrimitives> EngineApiRequestHandler<Request, N> {
190    /// Creates a new `EngineApiRequestHandler`.
191    pub const fn new(
192        to_tree: Sender<FromEngine<Request, N::Block>>,
193        from_tree: UnboundedReceiver<EngineApiEvent<N>>,
194    ) -> Self {
195        Self { to_tree, from_tree }
196    }
197}
198
199impl<Request, N: NodePrimitives> EngineRequestHandler for EngineApiRequestHandler<Request, N>
200where
201    Request: Send,
202{
203    type Event = ConsensusEngineEvent<N>;
204    type Request = Request;
205    type Block = N::Block;
206
207    fn on_event(&mut self, event: FromEngine<Self::Request, Self::Block>) {
208        // delegate to the tree
209        let _ = self.to_tree.send(event);
210    }
211
212    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<RequestHandlerEvent<Self::Event>> {
213        let Some(ev) = ready!(self.from_tree.poll_recv(cx)) else {
214            return Poll::Ready(RequestHandlerEvent::HandlerEvent(HandlerEvent::FatalError))
215        };
216
217        let ev = match ev {
218            EngineApiEvent::BeaconConsensus(ev) => {
219                RequestHandlerEvent::HandlerEvent(HandlerEvent::Event(ev))
220            }
221            EngineApiEvent::BackfillAction(action) => {
222                RequestHandlerEvent::HandlerEvent(HandlerEvent::BackfillAction(action))
223            }
224            EngineApiEvent::Download(action) => RequestHandlerEvent::Download(action),
225        };
226        Poll::Ready(ev)
227    }
228}
229
230/// The type for specifying the kind of engine api.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
232pub enum EngineApiKind {
233    /// The chain contains Ethereum configuration.
234    #[default]
235    Ethereum,
236    /// The chain contains Optimism configuration.
237    OpStack,
238}
239
240impl EngineApiKind {
241    /// Returns true if this is the ethereum variant
242    pub const fn is_ethereum(&self) -> bool {
243        matches!(self, Self::Ethereum)
244    }
245
246    /// Returns true if this is the opstack variant
247    pub const fn is_opstack(&self) -> bool {
248        matches!(self, Self::OpStack)
249    }
250}
251
252/// The request variants that the engine API handler can receive.
253#[derive(Debug)]
254pub enum EngineApiRequest<T: PayloadTypes, N: NodePrimitives> {
255    /// A request received from the consensus engine.
256    Beacon(BeaconEngineMessage<T>),
257    /// Request to insert an already executed block, e.g. via payload building.
258    InsertExecutedBlock(BuiltPayloadExecutedBlock<N>),
259}
260
261impl<T: PayloadTypes, N: NodePrimitives> Display for EngineApiRequest<T, N> {
262    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263        match self {
264            Self::Beacon(msg) => msg.fmt(f),
265            Self::InsertExecutedBlock(payload) => {
266                write!(f, "InsertExecutedBlock({:?})", payload.recovered_block.num_hash())
267            }
268        }
269    }
270}
271
272impl<T: PayloadTypes, N: NodePrimitives> From<BeaconEngineMessage<T>> for EngineApiRequest<T, N> {
273    fn from(msg: BeaconEngineMessage<T>) -> Self {
274        Self::Beacon(msg)
275    }
276}
277
278impl<T: PayloadTypes, N: NodePrimitives> From<EngineApiRequest<T, N>>
279    for FromEngine<EngineApiRequest<T, N>, N::Block>
280{
281    fn from(req: EngineApiRequest<T, N>) -> Self {
282        Self::Request(req)
283    }
284}
285
286/// Events emitted by the engine API handler.
287#[derive(Debug)]
288pub enum EngineApiEvent<N: NodePrimitives = EthPrimitives> {
289    /// Event from the consensus engine.
290    // TODO(mattsse): find a more appropriate name for this variant, consider phasing it out.
291    BeaconConsensus(ConsensusEngineEvent<N>),
292    /// Backfill action is needed.
293    BackfillAction(BackfillAction),
294    /// Block download is needed.
295    Download(DownloadRequest),
296}
297
298impl<N: NodePrimitives> EngineApiEvent<N> {
299    /// Returns `true` if the event is a backfill action.
300    pub const fn is_backfill_action(&self) -> bool {
301        matches!(self, Self::BackfillAction(_))
302    }
303}
304
305impl<N: NodePrimitives> From<ConsensusEngineEvent<N>> for EngineApiEvent<N> {
306    fn from(event: ConsensusEngineEvent<N>) -> Self {
307        Self::BeaconConsensus(event)
308    }
309}
310
311/// Events received from the engine.
312#[derive(Debug)]
313pub enum FromEngine<Req, B: Block> {
314    /// Event from the top level orchestrator.
315    Event(FromOrchestrator),
316    /// Request from the engine.
317    Request(Req),
318    /// Downloaded blocks from the network.
319    DownloadedBlocks(Vec<SealedBlockWithAccessList<B>>),
320    /// A range download ended because its start header is not at the requested block number.
321    StartNumberMismatch(StartNumberMismatch<B::Header>),
322}
323
324impl<Req: Display, B: Block> Display for FromEngine<Req, B> {
325    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326        match self {
327            Self::Event(ev) => write!(f, "Event({ev:?})"),
328            Self::Request(req) => write!(f, "Request({req})"),
329            Self::DownloadedBlocks(blocks) => {
330                write!(f, "DownloadedBlocks({} blocks)", blocks.len())
331            }
332            Self::StartNumberMismatch(mismatch) => {
333                write!(f, "StartNumberMismatch({:?})", mismatch.header.num_hash())
334            }
335        }
336    }
337}
338
339impl<Req, B: Block> From<FromOrchestrator> for FromEngine<Req, B> {
340    fn from(event: FromOrchestrator) -> Self {
341        Self::Event(event)
342    }
343}
344
345/// Requests produced by a [`EngineRequestHandler`].
346#[derive(Debug)]
347pub enum RequestHandlerEvent<T> {
348    /// An event emitted by the handler.
349    HandlerEvent(HandlerEvent<T>),
350    /// Request to download blocks.
351    Download(DownloadRequest),
352}
353
354/// A request to download blocks from the network.
355#[derive(Debug)]
356pub enum DownloadRequest {
357    /// Download the given set of blocks.
358    BlockSet {
359        /// The hashes of the blocks to download.
360        hashes: B256Set,
361        /// Whether to also attempt to download the blocks' access lists.
362        access_lists: bool,
363    },
364    /// Download the given range of blocks.
365    BlockRange {
366        /// The highest block of the range. If the header at `start.hash` has another number, the
367        /// download ends with [`DownloadOutcome::StartNumberMismatch`].
368        start: BlockNumHash,
369        /// The number of blocks to download.
370        count: u64,
371        /// Whether to also attempt to download the blocks' access lists.
372        access_lists: bool,
373    },
374}
375
376impl DownloadRequest {
377    /// Returns a [`DownloadRequest`] for a single block.
378    pub fn single_block(hash: B256) -> Self {
379        Self::block_set(B256Set::from_iter([hash]))
380    }
381
382    /// Returns a [`DownloadRequest`] for the given set of blocks.
383    pub const fn block_set(hashes: B256Set) -> Self {
384        Self::BlockSet { hashes, access_lists: false }
385    }
386
387    /// Returns a [`DownloadRequest`] for `count` blocks, from `start` down.
388    pub const fn block_range(start: BlockNumHash, count: u64) -> Self {
389        Self::BlockRange { start, count, access_lists: false }
390    }
391
392    /// Configures whether the download should also attempt to fetch the blocks' access lists.
393    ///
394    /// Access list downloads are best-effort: blocks are returned without access list data if no
395    /// peer can serve them.
396    pub const fn with_access_lists(mut self, access_lists: bool) -> Self {
397        match &mut self {
398            Self::BlockSet { access_lists: al, .. } | Self::BlockRange { access_lists: al, .. } => {
399                *al = access_lists
400            }
401        }
402        self
403    }
404}