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