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