Skip to main content

reth_engine_tree/
launch.rs

1//! Engine orchestrator launch helper.
2//!
3//! Provides [`EngineOrchestratorBuilder`] which wires
4//! together all engine components and builds a
5//! [`ChainOrchestrator`] ready to be polled as a `Stream`, with the staged pipeline or a
6//! caller-supplied [`BackfillSync`] as backfill.
7
8use crate::{
9    backfill::{BackfillSync, PipelineSync},
10    chain::ChainOrchestrator,
11    download::BasicBlockDownloader,
12    engine::{EngineApiKind, EngineApiRequest, EngineApiRequestHandler, EngineHandler},
13    persistence::PersistenceHandle,
14    tree::{EngineApiTreeHandler, EngineValidator, TreeConfig, WaitForCaches},
15};
16use futures::Stream;
17use reth_chain_state::CanonicalInMemoryStateWriter;
18use reth_consensus::FullConsensus;
19use reth_engine_primitives::BeaconEngineMessage;
20use reth_evm::ConfigureEvm;
21use reth_network_p2p::{BlockAccessListsClient, BlockClient};
22use reth_payload_builder::PayloadBuilderHandle;
23use reth_primitives_traits::NodePrimitives;
24use reth_provider::{
25    providers::{BlockchainProvider, ProviderNodeTypes},
26    ProviderFactory,
27};
28use reth_prune::PrunerWithFactory;
29use reth_stages_api::{MetricEventsSender, Pipeline};
30use reth_storage_overlay::OverlayManager;
31use reth_tasks::Runtime;
32use std::{convert::Infallible, sync::Arc};
33
34/// The [`ChainOrchestrator`] built by [`EngineOrchestratorBuilder`].
35pub type EngineOrchestrator<T, N, Client, S, B> = ChainOrchestrator<
36    EngineHandler<
37        EngineApiRequestHandler<EngineApiRequest<T, N>, N>,
38        S,
39        BasicBlockDownloader<Client, <N as NodePrimitives>::Block>,
40    >,
41    B,
42>;
43
44// An [`EngineOrchestrator`], or the error its backfill failed to build with.
45type EngineOrchestratorResult<T, N, Client, S, B, E> =
46    Result<EngineOrchestrator<T, N, Client, S, B>, E>;
47
48/// Components needed to build the engine [`ChainOrchestrator`] that drives the chain forward.
49///
50/// [`build`](Self::build) spawns and wires together the following components:
51///
52/// - **[`BasicBlockDownloader`]** — downloads blocks on demand from the network during live sync.
53/// - **[`PersistenceHandle`]** — spawns the persistence service on a background thread for writing
54///   blocks and performing pruning outside the critical consensus path.
55/// - **[`EngineApiTreeHandler`]** — spawns the tree handler that processes engine API requests
56///   (`newPayload`, `forkchoiceUpdated`) and maintains the in-memory chain state.
57/// - **[`EngineApiRequestHandler`]** + **[`EngineHandler`]** — glue that routes incoming CL
58///   messages to the tree handler and manages download requests.
59/// - **[`PipelineSync`]** — wraps the staged sync [`Pipeline`] for backfill sync when the node
60///   needs to catch up over large block ranges.
61///
62/// The returned orchestrator implements [`Stream`] and yields
63/// [`ChainEvent`]s.
64///
65/// [`ChainEvent`]: crate::chain::ChainEvent
66#[derive(Debug)]
67pub struct EngineOrchestratorBuilder<N, Client, S, V, C>
68where
69    N: ProviderNodeTypes,
70{
71    /// The engine API flavor to run.
72    pub engine_kind: EngineApiKind,
73    /// Consensus used to validate downloaded and incoming blocks.
74    pub consensus: Arc<dyn FullConsensus<N::Primitives>>,
75    /// Network client used to download blocks during live sync.
76    pub client: Client,
77    /// Incoming consensus layer messages.
78    pub incoming_requests: S,
79    /// Staged sync pipeline used for backfill.
80    pub pipeline: Pipeline<N>,
81    /// Runtime the pipeline runs on.
82    pub pipeline_task_spawner: Runtime,
83    /// Provider factory handed to the persistence service.
84    pub provider: ProviderFactory<N>,
85    /// Blockchain provider backing the engine tree.
86    pub blockchain_db: BlockchainProvider<N>,
87    /// Writer of the canonical in-memory state that `blockchain_db` reads. The engine tree
88    /// changes that state through it.
89    pub canonical_in_memory_state_writer: CanonicalInMemoryStateWriter<N::Primitives>,
90    /// Pruner run by the persistence service.
91    pub pruner: PrunerWithFactory<ProviderFactory<N>>,
92    /// Handle to the payload builder service.
93    pub payload_builder: PayloadBuilderHandle<N::Payload>,
94    /// Validator for incoming payloads.
95    pub payload_validator: V,
96    /// Overlay manager for state on top of the database.
97    pub overlay_manager: OverlayManager<N::Primitives>,
98    /// Engine tree configuration.
99    pub tree_config: TreeConfig,
100    /// Sender for sync metric events.
101    pub sync_metrics_tx: MetricEventsSender,
102    /// EVM configuration used to execute payloads.
103    pub evm_config: C,
104    /// Runtime used to spawn engine tree tasks.
105    pub runtime: Runtime,
106}
107
108impl<N, Client, S, V, C> EngineOrchestratorBuilder<N, Client, S, V, C>
109where
110    N: ProviderNodeTypes,
111    Client: BlockClient<Block = <N::Primitives as NodePrimitives>::Block>
112        + BlockAccessListsClient
113        + 'static,
114    S: Stream<Item = BeaconEngineMessage<N::Payload>> + Send + Sync + Unpin + 'static,
115    V: EngineValidator<N::Payload> + WaitForCaches,
116    C: ConfigureEvm<Primitives = N::Primitives> + 'static,
117{
118    /// Spawns the engine services and returns the [`ChainOrchestrator`] driving them.
119    pub fn build(
120        self,
121    ) -> EngineOrchestrator<N::Payload, N::Primitives, Client, S, PipelineSync<N>> {
122        let Ok(orchestrator) = self.build_with_backfill(|pipeline, runtime| {
123            Ok::<_, Infallible>(PipelineSync::new(pipeline, runtime))
124        });
125        orchestrator
126    }
127
128    /// Like [`Self::build`], backfilling through the [`BackfillSync`] `backfill` makes from the
129    /// staged [`Pipeline`] and its runtime, instead of [`PipelineSync`].
130    ///
131    /// The backfill is built before any engine service is spawned, so its error aborts the build.
132    pub fn build_with_backfill<B: BackfillSync + Unpin, E>(
133        self,
134        backfill: impl FnOnce(Pipeline<N>, Runtime) -> Result<B, E>,
135    ) -> EngineOrchestratorResult<N::Payload, N::Primitives, Client, S, B, E> {
136        let Self {
137            engine_kind,
138            consensus,
139            client,
140            incoming_requests,
141            pipeline,
142            pipeline_task_spawner,
143            provider,
144            blockchain_db,
145            canonical_in_memory_state_writer,
146            pruner,
147            payload_builder,
148            payload_validator,
149            overlay_manager,
150            tree_config,
151            sync_metrics_tx,
152            evm_config,
153            runtime,
154        } = self;
155
156        let backfill_sync = backfill(pipeline, pipeline_task_spawner)?;
157        let downloader = BasicBlockDownloader::new(client, consensus.clone());
158
159        let persistence_handle =
160            PersistenceHandle::<N::Primitives>::spawn_service(provider, pruner, sync_metrics_tx);
161
162        let (to_tree_tx, from_tree) = EngineApiTreeHandler::spawn_new(
163            blockchain_db,
164            consensus,
165            payload_validator,
166            persistence_handle,
167            payload_builder,
168            canonical_in_memory_state_writer,
169            overlay_manager,
170            tree_config,
171            engine_kind,
172            evm_config,
173            runtime,
174        );
175
176        let engine_handler = EngineApiRequestHandler::new(to_tree_tx, from_tree);
177        let handler = EngineHandler::new(engine_handler, downloader, incoming_requests);
178
179        Ok(ChainOrchestrator::new(handler, backfill_sync))
180    }
181}