Skip to main content

reth_node_builder/launch/
engine.rs

1//! Engine node related functionality.
2
3use crate::{
4    common::{Attached, LaunchContextWith, WithConfigs},
5    hooks::NodeHooks,
6    rpc::{EngineShutdown, EngineValidatorAddOn, EngineValidatorBuilder, RethRpcAddOns, RpcHandle},
7    setup::build_networked_pipeline,
8    sync::{BackfillClientFor, BackfillContext, BackfillSyncBuilder, PipelineBackfill},
9    AddOns, AddOnsContext, FullNode, LaunchContext, LaunchNode, Node, NodeAdapter,
10    NodeBuilderWithComponents, NodeComponents, NodeComponentsBuilder, NodeHandle, NodeTypesAdapter,
11    RethFullAdapter,
12};
13use alloy_consensus::BlockHeader;
14use futures::{stream::FusedStream, stream_select, FutureExt, StreamExt};
15use reth_chainspec::{EthChainSpec, EthereumHardforks};
16use reth_db::{database_metrics::DatabaseMetrics, Database};
17use reth_engine_tree::{
18    chain::{ChainEvent, FromOrchestrator},
19    engine::{EngineApiKind, EngineApiRequest, EngineRequestHandler},
20    launch::EngineOrchestratorBuilder,
21    tree::TreeConfig,
22};
23use reth_engine_util::EngineMessageStreamExt;
24use reth_exex::ExExManagerHandle;
25use reth_network::{types::BlockRangeUpdate, NetworkSyncUpdater, SyncState};
26use reth_network_api::BlockDownloaderProvider;
27use reth_node_api::{
28    BuiltPayload, ConsensusEngineHandle, FullNodeTypes, NodeTypes, NodeTypesWithDBAdapter,
29};
30use reth_node_core::{
31    args::PruneConfigKind,
32    dirs::{ChainPath, DataDirPath},
33    exit::NodeExitFuture,
34    primitives::Head,
35};
36use reth_node_events::node;
37use reth_provider::{
38    providers::{BlockchainProvider, NodeTypesForProvider},
39    BlockNumReader, StorageSettingsCache,
40};
41use reth_storage_overlay::OverlayManager;
42use reth_tasks::TaskExecutor;
43use reth_tokio_util::EventSender;
44use reth_tracing::tracing::{debug, error, info};
45use std::{future::Future, pin::Pin, sync::Arc};
46use tokio::sync::{mpsc::unbounded_channel, oneshot};
47use tokio_stream::wrappers::UnboundedReceiverStream;
48
49/// The engine node launcher.
50///
51/// `B` builds the engine's backfill, the staged pipeline unless set with
52/// [`Self::with_backfill`].
53#[derive(Debug)]
54pub struct EngineNodeLauncher<B = PipelineBackfill> {
55    /// The task executor for the node.
56    pub ctx: LaunchContext,
57
58    /// Temporary configuration for engine tree.
59    /// After engine is stabilized, this should be configured through node builder.
60    pub engine_tree_config: TreeConfig,
61
62    // Builds the backfill the engine runs while far behind the chain.
63    backfill: B,
64}
65
66impl EngineNodeLauncher {
67    /// Create a new instance of the ethereum node launcher.
68    pub const fn new(
69        task_executor: TaskExecutor,
70        data_dir: ChainPath<DataDirPath>,
71        engine_tree_config: TreeConfig,
72    ) -> Self {
73        Self {
74            ctx: LaunchContext::new(task_executor, data_dir),
75            engine_tree_config,
76            backfill: PipelineBackfill,
77        }
78    }
79}
80
81impl<B> EngineNodeLauncher<B> {
82    async fn launch_node<N, DB, T, CB, AO>(
83        self,
84        target: NodeBuilderWithComponents<T, CB, AO>,
85    ) -> eyre::Result<NodeHandle<NodeAdapter<T, CB::Components>, AO>>
86    where
87        N: Node<RethFullAdapter<DB, N>> + NodeTypesForProvider,
88        DB: Database + DatabaseMetrics + Clone + Unpin + 'static,
89        T: FullNodeTypes<
90            Types = N,
91            Provider = BlockchainProvider<NodeTypesWithDBAdapter<N, DB>>,
92            DB = DB,
93        >,
94        CB: NodeComponentsBuilder<T>,
95        AO: RethRpcAddOns<NodeAdapter<T, CB::Components>>
96            + EngineValidatorAddOn<NodeAdapter<T, CB::Components>>,
97        B: BackfillSyncBuilder<NodeTypesWithDBAdapter<N, DB>, BackfillClientFor<T, CB::Components>>,
98    {
99        let Self { ctx, engine_tree_config, mut backfill } = self;
100        let NodeBuilderWithComponents {
101            adapter: NodeTypesAdapter { database },
102            rocksdb_provider,
103            components_builder,
104            add_ons: AddOns { hooks, exexs: installed_exex, add_ons },
105            config,
106        } = target;
107        let NodeHooks { on_component_initialized, on_node_started, .. } = hooks;
108
109        // Create the overlay manager that will be shared across the provider and engine.
110        let overlay_manager = OverlayManager::<N::Primitives>::new(
111            ctx.task_executor.state_trie_overlay_worker_pool(),
112        );
113        let disabled_stages = N::disabled_stages();
114
115        // setup the launch context
116        let ctx = ctx
117            .with_configured_globals(engine_tree_config.reserved_cpu_cores())
118            // load the toml config
119            .with_loaded_toml_config(config)?
120            // add resolved peers
121            .with_resolved_peers()?
122            // attach the database
123            .attach(database.clone())
124            // ensure certain settings take effect
125            .with_adjusted_configs()
126            // Create the provider factory with the shared overlay manager, letting the backfill
127            // finish writes an earlier run left half-committed before the consistency check
128            .with_provider_factory_and_recovery::<_, <CB::Components as NodeComponents<T>>::Evm>(
129                overlay_manager.clone(),
130                rocksdb_provider,
131                disabled_stages,
132                |factory| backfill.recover(factory),
133            )
134            .await?
135            .inspect(|_| {
136                info!(target: "reth::cli", "Database opened");
137            })
138            .with_prometheus_server().await?
139            .inspect(|this| {
140                debug!(target: "reth::cli", chain=%this.chain_id(), genesis=?this.genesis_hash(), "Initializing genesis");
141            })
142            .with_genesis()?
143            .inspect(|this: &LaunchContextWith<Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, _>>| {
144                info!(target: "reth::cli", "\n{}", this.chain_spec().display_hardforks());
145                let settings = this.provider_factory().cached_storage_settings();
146                let pruning_mode =
147                    PruneConfigKind::from_config(&this.prune_config(), this.chain_spec().as_ref()).as_str();
148                info!(target: "reth::cli", ?settings, ?pruning_mode, "Loaded storage settings");
149            })
150            .with_metrics_task()
151            // passing FullNodeTypes as type parameter here so that we can build
152            // later the components.
153            .with_blockchain_db::<T, _>(move |provider_factory| {
154                Ok(BlockchainProvider::new(provider_factory)?)
155            })?
156            .with_components(components_builder, on_component_initialized).await?;
157
158        // spawn exexs if any
159        let maybe_exex_manager_handle = ctx.launch_exex(installed_exex).await?;
160
161        // create pipeline
162        let network_handle = ctx.components().network().clone();
163        let network_client = network_handle.fetch_client().await?;
164        let (consensus_engine_tx, consensus_engine_rx) = unbounded_channel();
165
166        let node_config = ctx.node_config();
167
168        // We always assume that node is syncing after a restart
169        network_handle.update_sync_state(SyncState::Syncing);
170
171        let max_block = ctx.max_block(network_client.clone()).await?;
172
173        let static_file_producer = ctx.static_file_producer();
174        let static_file_producer_events = static_file_producer.lock().events();
175        info!(target: "reth::cli", "StaticFileProducer initialized");
176
177        let consensus = Arc::new(ctx.components().consensus().clone());
178
179        let pipeline = build_networked_pipeline(
180            &ctx.toml_config().stages,
181            network_client.clone(),
182            consensus.clone(),
183            ctx.provider_factory().clone(),
184            ctx.task_executor(),
185            ctx.sync_metrics_tx(),
186            ctx.prune_config(),
187            max_block,
188            static_file_producer,
189            ctx.components().evm_config().clone(),
190            maybe_exex_manager_handle.clone().unwrap_or_else(ExExManagerHandle::empty),
191            ctx.era_import_source(),
192            disabled_stages,
193        )?;
194
195        // The new engine writes directly to static files. This ensures that they're up to the tip.
196        pipeline.move_to_static_files()?;
197
198        let pipeline_events = pipeline.events();
199
200        let mut pruner_builder = ctx.pruner_builder();
201        if let Some(exex_manager_handle) = &maybe_exex_manager_handle {
202            pruner_builder =
203                pruner_builder.finished_exex_height(exex_manager_handle.finished_height());
204        }
205        let pruner = pruner_builder.build_with_provider_factory(ctx.provider_factory().clone());
206        let pruner_events = pruner.events();
207        info!(target: "reth::cli", prune_config=?ctx.prune_config(), "Pruner initialized");
208
209        let event_sender = EventSender::default();
210
211        let beacon_engine_handle = ConsensusEngineHandle::new(consensus_engine_tx.clone());
212
213        // extract the jwt secret from the args if possible
214        let jwt_secret = ctx.auth_jwt_secret()?;
215
216        let add_ons_ctx = AddOnsContext {
217            node: ctx.node_adapter().clone(),
218            config: ctx.node_config(),
219            beacon_engine_handle: beacon_engine_handle.clone(),
220            jwt_secret,
221            engine_events: event_sender.clone(),
222            sender_recovery_cache: ctx.sender_recovery_cache().cloned(),
223        };
224        let validator_builder = add_ons.engine_validator_builder();
225
226        // Build the engine validator with all required components
227        let engine_validator = validator_builder
228            .clone()
229            .build_tree_validator(&add_ons_ctx, engine_tree_config.clone(), overlay_manager.clone())
230            .await?;
231
232        // Create the consensus engine stream with optional reorg
233        let reorg_overlay_manager = overlay_manager.clone();
234        let consensus_engine_stream = UnboundedReceiverStream::from(consensus_engine_rx)
235            .maybe_skip_fcu(node_config.debug.skip_fcu)
236            .maybe_skip_new_payload(node_config.debug.skip_new_payload)
237            .maybe_reorg(
238                ctx.blockchain_db().clone(),
239                ctx.components().evm_config().clone(),
240                || async {
241                    validator_builder
242                        .build_tree_validator(
243                            &add_ons_ctx,
244                            engine_tree_config.clone(),
245                            reorg_overlay_manager.clone(),
246                        )
247                        .await
248                },
249                node_config.debug.reorg_frequency,
250                node_config.debug.reorg_depth,
251            )
252            .await?
253            // Store messages _after_ skipping so that `replay-engine` command
254            // would replay only the messages that were observed by the engine
255            // during this run.
256            .maybe_store_messages(node_config.debug.engine_api_store.clone());
257
258        let engine_kind = if ctx.chain_spec().is_optimism() {
259            EngineApiKind::OpStack
260        } else {
261            EngineApiKind::Ethereum
262        };
263
264        let (backfill_client, backfill_factory) =
265            (network_client.clone(), ctx.provider_factory().clone());
266        let mut orchestrator = EngineOrchestratorBuilder {
267            engine_kind,
268            consensus,
269            client: network_client,
270            incoming_requests: Box::pin(consensus_engine_stream),
271            pipeline,
272            pipeline_task_spawner: ctx.task_executor().clone(),
273            provider: ctx.provider_factory().clone(),
274            blockchain_db: ctx.blockchain_db().clone(),
275            pruner,
276            payload_builder: ctx.components().payload_builder_handle().clone(),
277            payload_validator: engine_validator,
278            overlay_manager,
279            tree_config: engine_tree_config,
280            sync_metrics_tx: ctx.sync_metrics_tx(),
281            evm_config: ctx.components().evm_config().clone(),
282            runtime: ctx.task_executor().clone(),
283        }
284        .build_with_backfill(|pipeline, runtime| {
285            backfill.build(BackfillContext::new(
286                pipeline,
287                backfill_client,
288                backfill_factory,
289                runtime,
290            ))
291        })?;
292
293        info!(target: "reth::cli", "Consensus engine initialized");
294
295        #[expect(clippy::needless_continue)]
296        let events = stream_select!(
297            event_sender.new_listener().map(Into::into),
298            pipeline_events.map(Into::into),
299            ctx.consensus_layer_events(),
300            pruner_events.map(Into::into),
301            static_file_producer_events.map(Into::into),
302        );
303
304        ctx.task_executor().spawn_critical_task(
305            "events task",
306            node::handle_events(
307                Some(Box::new(ctx.components().network().clone())),
308                Some(ctx.head().number),
309                events,
310            ),
311        );
312
313        let RpcHandle {
314            rpc_server_handles,
315            rpc_registry,
316            engine_events,
317            beacon_engine_handle,
318            engine_shutdown: _,
319        } = add_ons.launch_add_ons(add_ons_ctx).await?;
320
321        // Create engine shutdown handle
322        let (engine_shutdown, shutdown_rx) = EngineShutdown::new();
323
324        // Run consensus engine to completion
325        let initial_target = ctx.initial_backfill_target(disabled_stages)?;
326        let mut built_payloads = ctx
327            .components()
328            .payload_builder_handle()
329            .subscribe()
330            .await
331            .map_err(|e| eyre::eyre!("Failed to subscribe to payload builder events: {:?}", e))?
332            .into_built_payload_stream()
333            .fuse();
334
335        let chainspec = ctx.chain_spec();
336        let provider = ctx.blockchain_db().clone();
337        let (exit, rx) = oneshot::channel();
338        let terminate_after_backfill = ctx.terminate_after_initial_backfill();
339        let startup_sync_state_idle = ctx.node_config().debug.startup_sync_state_idle;
340
341        info!(target: "reth::cli", "Starting consensus engine");
342        let consensus_engine = move |mut on_graceful_shutdown| async move {
343            if let Some(initial_target) = initial_target {
344                debug!(target: "reth::cli", %initial_target,  "start backfill sync");
345                // network_handle's sync state is already initialized at Syncing
346                orchestrator.start_backfill_sync(initial_target);
347            } else if startup_sync_state_idle {
348                network_handle.update_sync_state(SyncState::Idle);
349            }
350
351            let mut res = Ok(());
352            let mut shutdown_rx = shutdown_rx.fuse();
353
354            // advance the chain and await payloads built locally to add into the engine api
355            // tree handler to prevent re-execution if that block is received as payload from
356            // the CL
357            loop {
358                tokio::select! {
359                    event = orchestrator.next() => {
360                        let Some(event) = event else { break };
361                        debug!(target: "reth::cli", "Event: {event}");
362                        match event {
363                            ChainEvent::BackfillSyncFinished => {
364                                if terminate_after_backfill {
365                                    debug!(target: "reth::cli", "Terminating after initial backfill");
366                                    break
367                                }
368                                if startup_sync_state_idle {
369                                    network_handle.update_sync_state(SyncState::Idle);
370                                }
371                            }
372                            ChainEvent::BackfillSyncStarted => {
373                                network_handle.update_sync_state(SyncState::Syncing);
374                            }
375                            ChainEvent::FatalError => {
376                                error!(target: "reth::cli", "Fatal error in consensus engine");
377                                res = Err(eyre::eyre!("Fatal error in consensus engine"));
378                                break
379                            }
380                            ChainEvent::Handler(ev) => {
381                                if let Some(head) = ev.canonical_header() {
382                                    // Once we're progressing via live sync, we can consider the node is not syncing anymore
383                                    network_handle.update_sync_state(SyncState::Idle);
384                                    let head_block = Head {
385                                        number: head.number(),
386                                        hash: head.hash(),
387                                        difficulty: head.difficulty(),
388                                        timestamp: head.timestamp(),
389                                        total_difficulty: chainspec.final_paris_total_difficulty()
390                                            .filter(|_| chainspec.is_paris_active_at_block(head.number()))
391                                            .unwrap_or_default(),
392                                    };
393                                    network_handle.update_status(head_block);
394
395                                    let updated = BlockRangeUpdate {
396                                        earliest: provider.earliest_block_number().unwrap_or_default(),
397                                        latest: head.number(),
398                                        latest_hash: head.hash(),
399                                    };
400                                    network_handle.update_block_range(updated);
401                                }
402                                event_sender.notify(ev);
403                            }
404                        }
405                    }
406                    Some(payload) = built_payloads.next(), if !built_payloads.is_terminated() => {
407                        if let Some(executed_block) = payload.executed_block() {
408                            debug!(target: "reth::cli", block=?executed_block.recovered_block.num_hash(),  "inserting built payload");
409                            orchestrator.handler_mut().handler_mut().on_event(EngineApiRequest::InsertExecutedBlock(executed_block).into());
410                        }
411                    }
412                    shutdown_req = &mut shutdown_rx => {
413                        if let Ok(req) = shutdown_req {
414                            debug!(target: "reth::cli", "received engine shutdown request");
415                            orchestrator.handler_mut().handler_mut().on_event(
416                                FromOrchestrator::Terminate { tx: req.done_tx }.into()
417                            );
418                        }
419                    }
420                    _guard = &mut on_graceful_shutdown => {
421                        // Shutdown signal received.
422                        // Send Terminate so the engine OS thread can exit cleanly before we
423                        // drop the orchestrator.
424                        debug!(target: "reth::cli", "shutdown signal received, terminating engine");
425                        let (done_tx, done_rx) = oneshot::channel();
426                        orchestrator.handler_mut().handler_mut().on_event(
427                            FromOrchestrator::Terminate { tx: done_tx }.into()
428                        );
429                        let _ = done_rx.await;
430                        break;
431                    }
432                }
433            }
434
435            let _ = exit.send(res);
436        };
437        ctx.task_executor()
438            .spawn_critical_with_graceful_shutdown_signal("consensus engine", consensus_engine);
439
440        let engine_events_for_ethstats = engine_events.new_listener();
441
442        let full_node = FullNode {
443            evm_config: ctx.components().evm_config().clone(),
444            pool: ctx.components().pool().clone(),
445            network: ctx.components().network().clone(),
446            provider: ctx.node_adapter().provider.clone(),
447            payload_builder_handle: ctx.components().payload_builder_handle().clone(),
448            task_executor: ctx.task_executor().clone(),
449            config: ctx.node_config().clone(),
450            data_dir: ctx.data_dir().clone(),
451            add_ons_handle: RpcHandle {
452                rpc_server_handles,
453                rpc_registry,
454                engine_events,
455                beacon_engine_handle,
456                engine_shutdown,
457            },
458        };
459        // Notify on node started
460        on_node_started.on_event(FullNode::clone(&full_node))?;
461
462        ctx.spawn_ethstats(engine_events_for_ethstats).await?;
463
464        let handle = NodeHandle {
465            node_exit_future: NodeExitFuture::new(async { rx.await? }),
466            node: full_node,
467        };
468
469        Ok(handle)
470    }
471
472    /// Returns this launcher with the engine's backfill built by `backfill`.
473    pub fn with_backfill<B2>(self, backfill: B2) -> EngineNodeLauncher<B2> {
474        let Self { ctx, engine_tree_config, .. } = self;
475        EngineNodeLauncher { ctx, engine_tree_config, backfill }
476    }
477}
478
479impl<N, DB, T, CB, AO, B> LaunchNode<NodeBuilderWithComponents<T, CB, AO>> for EngineNodeLauncher<B>
480where
481    T: FullNodeTypes<
482        Types = N,
483        DB = DB,
484        Provider = BlockchainProvider<NodeTypesWithDBAdapter<N, DB>>,
485    >,
486    N: Node<RethFullAdapter<DB, N>> + NodeTypesForProvider,
487    DB: Database + DatabaseMetrics + Clone + Unpin + 'static,
488    CB: NodeComponentsBuilder<T> + 'static,
489    AO: RethRpcAddOns<NodeAdapter<T, CB::Components>>
490        + EngineValidatorAddOn<NodeAdapter<T, CB::Components>>
491        + 'static,
492    B: BackfillSyncBuilder<NodeTypesWithDBAdapter<N, DB>, BackfillClientFor<T, CB::Components>>
493        + 'static,
494{
495    type Node = NodeHandle<NodeAdapter<T, CB::Components>, AO>;
496    type Future = Pin<Box<dyn Future<Output = eyre::Result<Self::Node>> + Send>>;
497
498    fn launch_node(self, target: NodeBuilderWithComponents<T, CB, AO>) -> Self::Future {
499        Box::pin(self.launch_node(target))
500    }
501}