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