1use 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#[derive(Debug)]
41pub struct EngineHandler<T, S, D> {
42 handler: T,
46 incoming_requests: S,
48 downloader: D,
50}
51
52impl<T, S, D> EngineHandler<T, S, D> {
53 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 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 self.handler.on_event(event.into());
80 }
81
82 fn poll(&mut self, cx: &mut Context<'_>) -> Poll<HandlerEvent<Self::Event>> {
83 loop {
84 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 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 Poll::Ready(HandlerEvent::Event(ev))
100 }
101 HandlerEvent::FatalError => Poll::Ready(HandlerEvent::FatalError),
102 }
103 }
104 RequestHandlerEvent::Download(req) => {
105 self.downloader.on_action(DownloadAction::Download(req));
107 }
108 }
109 }
110
111 if let Poll::Ready(Some(req)) = self.incoming_requests.poll_next_unpin(cx) {
113 self.handler.on_event(FromEngine::Request(req.into()));
115 continue
117 }
118
119 if let Poll::Ready(outcome) = self.downloader.poll(cx) {
121 match outcome {
122 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
139pub trait EngineRequestHandler: Send + Sync {
148 type Event: Send;
150 type Request;
152 type Block: Block;
154
155 fn on_event(&mut self, event: FromEngine<Self::Request, Self::Block>);
157
158 fn poll(&mut self, cx: &mut Context<'_>) -> Poll<RequestHandlerEvent<Self::Event>>;
160}
161
162#[derive(Debug)]
182pub struct EngineApiRequestHandler<Request, N: NodePrimitives> {
183 to_tree: Sender<FromEngine<Request, N::Block>>,
185 from_tree: UnboundedReceiver<EngineApiEvent<N>>,
187}
188
189impl<Request, N: NodePrimitives> EngineApiRequestHandler<Request, N> {
190 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
232pub enum EngineApiKind {
233 #[default]
235 Ethereum,
236 OpStack,
238}
239
240impl EngineApiKind {
241 pub const fn is_ethereum(&self) -> bool {
243 matches!(self, Self::Ethereum)
244 }
245
246 pub const fn is_opstack(&self) -> bool {
248 matches!(self, Self::OpStack)
249 }
250}
251
252#[derive(Debug)]
254pub enum EngineApiRequest<T: PayloadTypes, N: NodePrimitives> {
255 Beacon(BeaconEngineMessage<T>),
257 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#[derive(Debug)]
288pub enum EngineApiEvent<N: NodePrimitives = EthPrimitives> {
289 BeaconConsensus(ConsensusEngineEvent<N>),
292 BackfillAction(BackfillAction),
294 Download(DownloadRequest),
296}
297
298impl<N: NodePrimitives> EngineApiEvent<N> {
299 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#[derive(Debug)]
313pub enum FromEngine<Req, B: Block> {
314 Event(FromOrchestrator),
316 Request(Req),
318 DownloadedBlocks(Vec<SealedBlockWithAccessList<B>>),
320 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#[derive(Debug)]
347pub enum RequestHandlerEvent<T> {
348 HandlerEvent(HandlerEvent<T>),
350 Download(DownloadRequest),
352}
353
354#[derive(Debug)]
356pub enum DownloadRequest {
357 BlockSet {
359 hashes: B256Set,
361 access_lists: bool,
363 },
364 BlockRange {
366 start: BlockNumHash,
369 count: u64,
371 access_lists: bool,
373 },
374}
375
376impl DownloadRequest {
377 pub fn single_block(hash: B256) -> Self {
379 Self::block_set(B256Set::from_iter([hash]))
380 }
381
382 pub const fn block_set(hashes: B256Set) -> Self {
384 Self::BlockSet { hashes, access_lists: false }
385 }
386
387 pub const fn block_range(start: BlockNumHash, count: u64) -> Self {
389 Self::BlockRange { start, count, access_lists: false }
390 }
391
392 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}