Skip to main content

reth_e2e_test_utils/
setup_builder.rs

1//! Builder for configuring and launching test node setups.
2//!
3//! This module provides a flexible builder API for setting up test nodes with custom
4//! configurations through closures that modify `NodeConfig` and `TreeConfig`.
5
6use crate::{
7    eth_payload_attributes,
8    node::{NodeRestart, NodeTestContext, Relaunch},
9    test_chain_spec,
10    wallet::Wallet,
11    Adapter, NodeBuilderHelper, NodeHelperType, TmpDB, TmpNodeAdapter,
12};
13use alloy_primitives::B256;
14use alloy_rpc_types_engine::{ForkchoiceState, PayloadAttributes};
15use alloy_rpc_types_eth::BlockNumberOrTag;
16use eyre::{ensure, eyre, WrapErr};
17use futures_util::future::{BoxFuture, TryJoinAll};
18use reth_chainspec::{ChainSpec, EthChainSpec, EthereumHardfork};
19use reth_db::{init_db, mdbx::DatabaseArguments, test_utils::TempDatabase};
20use reth_node_api::{PayloadAttrTy, TreeConfig};
21use reth_node_builder::{
22    sync::{BackfillClientFor, BackfillSyncBuilder, PipelineBackfill},
23    ComponentsFor, DebugNode, DebugNodeLauncher, EngineNodeLauncher, Node, NodeBuilder,
24    NodeBuilderWithComponents, NodeConfig, NodeHandle, NodeTypesWithDBAdapter,
25};
26use reth_node_core::{
27    args::{DatadirArgs, DiscoveryArgs, NetworkArgs, PruningArgs, RpcServerArgs, StorageArgs},
28    dirs::{ChainPath, DataDirPath, MaybePlatformPath},
29};
30use reth_primitives_traits::AlloyBlockHeader;
31use reth_provider::{
32    providers::BlockchainProvider, BlockReaderIdExt, DatabaseProviderFactory, MetadataProvider,
33};
34use reth_rpc_server_types::RpcModuleSelection;
35use reth_tasks::Runtime;
36use std::{
37    path::{Path, PathBuf},
38    sync::{Arc, Mutex},
39    time::Duration,
40};
41use tracing::{span, Instrument, Level};
42
43/// Builder for configuring and launching test node setups.
44///
45/// By default, the nodes:
46/// - are [`Default`] instances of `N`, see [`Self::with_node`],
47/// - run on a shared [`Runtime::test`] runtime, unless they are
48///   [restartable](Self::with_restartable_nodes),
49/// - build payloads with [`eth_payload_attributes`] for the hardforks active in the chain spec,
50///   unless created with [`Self::new_with_attributes_generator`],
51/// - have discovery disabled, use unused ports and serve all RPC modules except `testing` over
52///   HTTP,
53/// - report an idle sync state from startup, so they gossip transactions before their first block,
54/// - do not persist their peers, so a restarted node only connects to the peers a test connects it
55///   to,
56/// - are connected to each other.
57///
58/// Once launched, each node receives a forkchoice update that makes genesis the head, safe and
59/// finalized block, unless [dev mining](Self::with_dev_mining) is enabled or
60/// [`Self::with_initial_forkchoice`] disables the update.
61///
62/// Configuration and tree configuration modifiers are applied in the order they are added. Like
63/// for a node launched from the command line, the tree configuration of a node is derived from its
64/// final node configuration, see [`NodeConfig::tree_config`], so the engine arguments and
65/// `--debug.skip-state-root` set by node configuration modifiers take effect. Tree configuration
66/// modifiers are applied last and take precedence over them.
67///
68/// Use [`E2ETestSetupExt::test_setup_for`] to set up nodes on the [`test_chain_spec`] at a
69/// hardfork, or [`E2ETestSetupExt::test_setup`] for any other chain spec:
70///
71/// ```ignore
72/// let (mut node, wallet) = EthereumNode::test_setup_for(EthereumHardfork::Cancun)
73///     .with_tree_config_modifier(|config| config.with_persistence_threshold(0))
74///     .build_single()
75///     .await?;
76/// ```
77pub struct E2ETestSetupBuilder<N: NodeBuilderHelper> {
78    num_nodes: usize,
79    chain_spec: Arc<N::ChainSpec>,
80    runtime: Option<Runtime>,
81    attributes_generator: AttributesGenerator<N>,
82    connect_nodes: bool,
83    tree_config_modifiers: Vec<TreeConfigModifier>,
84    node_config_modifiers: Vec<NodeConfigModifier<N::ChainSpec>>,
85    storage_v2: bool,
86    dev_launcher: Option<NodeLauncher<N>>,
87    backfill_launcher: Option<NodeLauncher<N>>,
88    dev_payload_attributes: Option<PayloadAttributesMapper<N>>,
89    node_factory: NodeFactory<N>,
90    node_builder_modifiers: Vec<NodeBuilderModifier<N>>,
91    restartable: bool,
92    initial_forkchoice: bool,
93}
94
95impl<N: NodeBuilderHelper> E2ETestSetupBuilder<N> {
96    /// Creates a new builder for `num_nodes` nodes of the given chain.
97    ///
98    /// The nodes build payloads with [`eth_payload_attributes`] for the chain spec, which requires
99    /// the payload attributes of the node to be convertible from Ethereum's. Use
100    /// [`Self::new_with_attributes_generator`] for other nodes.
101    pub fn new(num_nodes: usize, chain_spec: Arc<N::ChainSpec>) -> Self
102    where
103        PayloadAttrTy<N>: From<PayloadAttributes>,
104    {
105        let attributes_chain_spec = chain_spec.clone();
106        Self::new_with_attributes_generator(num_nodes, chain_spec, move |timestamp| {
107            eth_payload_attributes(&attributes_chain_spec, timestamp).into()
108        })
109    }
110
111    /// Creates a new builder for `num_nodes` nodes of the given chain, whose payloads are built
112    /// with the attributes returned by `attributes_generator`, see
113    /// [`Self::with_attributes_generator`].
114    ///
115    /// Unlike [`Self::new`], this does not require the payload attributes of the node to be
116    /// convertible from Ethereum's.
117    pub fn new_with_attributes_generator<G>(
118        num_nodes: usize,
119        chain_spec: Arc<N::ChainSpec>,
120        attributes_generator: G,
121    ) -> Self
122    where
123        G: Fn(u64) -> PayloadAttrTy<N> + Send + Sync + 'static,
124    {
125        Self {
126            num_nodes,
127            chain_spec,
128            runtime: None,
129            attributes_generator: Arc::new(attributes_generator),
130            connect_nodes: true,
131            tree_config_modifiers: Vec::new(),
132            node_config_modifiers: Vec::new(),
133            storage_v2: StorageArgs::default().v2,
134            dev_launcher: None,
135            backfill_launcher: None,
136            dev_payload_attributes: None,
137            node_factory: Arc::new(|_| N::default()),
138            node_builder_modifiers: Vec::new(),
139            restartable: false,
140            initial_forkchoice: true,
141        }
142    }
143
144    /// Sets the number of nodes to launch.
145    pub const fn with_num_nodes(mut self, num_nodes: usize) -> Self {
146        self.num_nodes = num_nodes;
147        self
148    }
149
150    /// Launches the nodes on the given runtime instead of a new [`Runtime::test`].
151    ///
152    /// This lets multiple setups, or other components of a test, share the same tokio handle and
153    /// rayon pools. Note that the tasks of the nodes are only shut down once all handles to the
154    /// runtime are dropped, not when the nodes are dropped. Restartable nodes, see
155    /// [`Self::with_restartable_nodes`], can not share a runtime.
156    pub fn with_runtime(mut self, runtime: Runtime) -> Self {
157        self.runtime = Some(runtime);
158        self
159    }
160
161    /// Sets the generator for the payload attributes of the payloads built by the test nodes.
162    ///
163    /// The generator is called with the timestamp of the next payload. It replaces the generator
164    /// of the constructor, which is [`eth_payload_attributes`] for the chain spec of the setup for
165    /// [`Self::new`].
166    pub fn with_attributes_generator<G>(mut self, generator: G) -> Self
167    where
168        G: Fn(u64) -> PayloadAttrTy<N> + Send + Sync + 'static,
169    {
170        self.attributes_generator = Arc::new(generator);
171        self
172    }
173
174    /// Sets whether nodes should be interconnected (default: true).
175    pub const fn with_connect_nodes(mut self, connect_nodes: bool) -> Self {
176        self.connect_nodes = connect_nodes;
177        self
178    }
179
180    /// Adds a modifier for the tree configuration.
181    ///
182    /// The closure receives the current tree config and returns a modified version. The base
183    /// config is derived from the node configuration after all node configuration modifiers ran,
184    /// see [`NodeConfig::tree_config`]. Unless a node configuration modifier changes
185    /// `engine.cross_block_cache_size`, it uses a small cross block cache of 1 MiB.
186    pub fn with_tree_config_modifier<G>(mut self, modifier: G) -> Self
187    where
188        G: Fn(TreeConfig) -> TreeConfig + Send + Sync + 'static,
189    {
190        self.tree_config_modifiers.push(Box::new(modifier));
191        self
192    }
193
194    /// Adds a modifier for the node configuration.
195    ///
196    /// The closure receives the current node config and returns a modified version. Its engine
197    /// arguments and `debug.skip_state_root` configure the engine tree, unless a
198    /// [tree configuration modifier](Self::with_tree_config_modifier) overrides them.
199    pub fn with_node_config_modifier<G>(mut self, modifier: G) -> Self
200    where
201        G: Fn(NodeConfig<N::ChainSpec>) -> NodeConfig<N::ChainSpec> + Send + Sync + 'static,
202    {
203        self.node_config_modifiers.push(Box::new(modifier));
204        self
205    }
206
207    /// Adds a modifier for the RPC server arguments.
208    ///
209    /// The closure receives the current arguments, which serve all modules except `testing` over
210    /// HTTP on an unused port.
211    pub fn with_rpc_modifier<G>(self, modifier: G) -> Self
212    where
213        G: Fn(RpcServerArgs) -> RpcServerArgs + Send + Sync + 'static,
214    {
215        self.with_node_config_modifier(move |mut config| {
216            config.rpc = modifier(config.rpc);
217            config
218        })
219    }
220
221    /// Sets the pruning arguments for the test nodes.
222    pub fn with_pruning(self, pruning: PruningArgs) -> Self {
223        self.with_node_config_modifier(move |config| config.with_pruning(pruning.clone()))
224    }
225
226    /// Sets whether nodes use the v2 storage layout (`--storage.v2`), which routes tx hashes,
227    /// history indices, etc. to `RocksDB` and changesets/senders to static files.
228    ///
229    /// Defaults to the node's `--storage.v2` default. Node config modifiers run afterwards and can
230    /// still override it.
231    pub const fn with_storage_v2(mut self, storage_v2: bool) -> Self {
232        self.storage_v2 = storage_v2;
233        self
234    }
235
236    /// Sets whether the nodes run in dev mode (`--dev`).
237    ///
238    /// Unlike [dev mining](Self::with_dev_mining), this only sets the dev flag and does not start a
239    /// local miner.
240    pub fn with_dev_mode(self, dev: bool) -> Self {
241        self.with_node_config_modifier(move |config| config.set_dev(dev))
242    }
243
244    /// Launches the node in dev mode with a local miner that builds a block every `block_time`, or
245    /// as soon as a transaction is pending if `None`.
246    ///
247    /// Dev mining is limited to a single node, since every node would mine its own chain. The local
248    /// miner drives forkchoice and payload building, so the node does not receive the initial
249    /// forkchoice update to genesis, and the block producing helpers of [`NodeTestContext`], e.g.
250    /// [`NodeTestContext::advance_block`] and [`NodeTestContext::update_forkchoice`], must not be
251    /// used. Use [`Self::map_dev_payload_attributes`] to customize the payload attributes of the
252    /// mined blocks.
253    pub fn with_dev_mining(mut self, block_time: Option<Duration>) -> Self
254    where
255        N: DebugNode<Adapter<N>>,
256    {
257        self.dev_launcher =
258            Some(Arc::new(|args, database| Box::pin(launch_dev_node::<N>(args, database))));
259        self.with_node_config_modifier(move |mut config| {
260            config.dev.dev = true;
261            config.dev.block_time = block_time;
262            config
263        })
264    }
265
266    /// Maps the payload attributes of the blocks built by the local miner of
267    /// [dev mining](Self::with_dev_mining) nodes, e.g. to set the fee recipient.
268    ///
269    /// Mappers are applied in the order they are added. Has no effect unless dev mining is
270    /// enabled.
271    pub fn map_dev_payload_attributes<G>(mut self, map: G) -> Self
272    where
273        G: Fn(PayloadAttrTy<N>) -> PayloadAttrTy<N> + Send + Sync + 'static,
274    {
275        self.dev_payload_attributes = Some(match self.dev_payload_attributes.take() {
276            Some(prev) => Arc::new(move |attributes| map(prev(attributes))),
277            None => Arc::new(map),
278        });
279        self
280    }
281
282    /// Launches each node with the engine's backfill built by the [`BackfillSyncBuilder`] that
283    /// `backfill` returns for the node's final configuration, instead of the staged pipeline.
284    ///
285    /// Like a node launched from the command line, the backfill follows the node's flags, e.g.
286    /// `with_backfill(EthereumBackfill::new)` snap syncs once a node configuration modifier sets
287    /// `--snap.v2`. A restarted node builds its backfill again from its configuration.
288    ///
289    /// Cannot be combined with [dev mining](Self::with_dev_mining): the harness launches dev mining
290    /// nodes with the staged pipeline.
291    pub fn with_backfill<F, B>(mut self, backfill: F) -> Self
292    where
293        F: Fn(&NodeConfig<N::ChainSpec>) -> B + Send + Sync + 'static,
294        B: BackfillSyncBuilder<NodeTypesWithDBAdapter<N, TmpDB>, BackfillClient<N>> + 'static,
295    {
296        self.backfill_launcher = Some(Arc::new(move |args, database| {
297            let backfill = backfill(&args.node_config);
298            Box::pin(launch_test_node(args, database, backfill))
299        }));
300        self
301    }
302
303    /// Sets the factory of the node instances, which is called with the index of each node when it
304    /// is launched.
305    ///
306    /// Defaults to [`Default::default`]. Use this to configure the node type, or to keep a handle
307    /// of the node instance, e.g. one that reads state of the node once it is launched.
308    pub fn with_node<F>(mut self, node: F) -> Self
309    where
310        F: Fn(usize) -> N + Send + Sync + 'static,
311    {
312        self.node_factory = Arc::new(node);
313        self
314    }
315
316    /// Adds a modifier for the node builder of each test node.
317    ///
318    /// The closure receives the [`TestNodeBuilder`] after the node types, components and add-ons
319    /// are configured, and returns it to be launched. It can e.g. install an `ExEx` with
320    /// [`install_exex`](NodeBuilderWithComponents::install_exex), extend the RPC modules with
321    /// [`extend_rpc_modules`](NodeBuilderWithComponents::extend_rpc_modules), set the
322    /// `on_component_initialized`, `on_node_started` and `on_rpc_started` hooks, or modify the
323    /// add-ons with [`map_add_ons`](NodeBuilderWithComponents::map_add_ons).
324    ///
325    /// Modifiers are applied to every node in the order they are added. The node builder keeps a
326    /// single hook of each kind, so a modifier that sets e.g. the `extend_rpc_modules` hook
327    /// replaces the one set by an earlier modifier. The datadir and tree configuration of the node
328    /// are derived before the modifiers run, so change the node configuration with
329    /// [`Self::with_node_config_modifier`] instead of `builder.config`.
330    pub fn with_node_builder_modifier<G>(mut self, modifier: G) -> Self
331    where
332        G: Fn(TestNodeBuilder<N>) -> TestNodeBuilder<N> + Send + Sync + 'static,
333    {
334        self.node_builder_modifiers.push(Arc::new(modifier));
335        self
336    }
337
338    /// Makes the nodes restartable, so they can be stopped and launched again on the same datadir
339    /// with [`NodeTestContext::stop`] and [`NodeTestContext::restart`].
340    ///
341    /// Each restartable node runs on a [`Runtime::test`] runtime of its own instead of the shared
342    /// one, so stopping it shuts down only its tasks. This costs a few threads per node, which is
343    /// why nodes are not restartable by default. Conflicts with [`Self::with_runtime`].
344    pub const fn with_restartable_nodes(mut self) -> Self {
345        self.restartable = true;
346        self
347    }
348
349    /// Sets whether startup makes genesis the head, safe and finalized block (default: true).
350    ///
351    /// Disable to test a node with no finalized block. Dev mining always skips this update.
352    pub const fn with_initial_forkchoice(mut self, enabled: bool) -> Self {
353        self.initial_forkchoice = enabled;
354        self
355    }
356
357    /// Builds and launches the test nodes.
358    pub async fn build(self) -> eyre::Result<(Vec<NodeHelperType<N>>, Wallet)> {
359        ensure!(
360            self.dev_launcher.is_none() || self.num_nodes == 1,
361            "dev mining requires a single node setup, got {} nodes",
362            self.num_nodes
363        );
364        ensure!(
365            !self.restartable || self.runtime.is_none(),
366            "restartable nodes run on a runtime of their own and can not use the runtime set with \
367             `with_runtime`"
368        );
369        ensure!(
370            self.dev_launcher.is_none() || self.backfill_launcher.is_none(),
371            "dev mining nodes backfill with the staged pipeline and can not use the backfill set \
372             with `with_backfill`"
373        );
374        // The pipeline would silently replace the snap sync the flag opts into.
375        ensure!(
376            self.backfill_launcher.is_some() || !self.node_and_tree_config().0.network.snap_v2,
377            "nodes with `--snap.v2` need a backfill set with `with_backfill`, e.g. \
378             `EthereumBackfill::new`"
379        );
380        let dev_mining = self.dev_launcher.is_some();
381        let launch = self.dev_launcher.as_ref().or(self.backfill_launcher.as_ref()).cloned();
382        let launch = launch.unwrap_or_else(|| {
383            Arc::new(|args, database| Box::pin(launch_test_node(args, database, PipelineBackfill)))
384        });
385        // Restartable nodes create their own runtime when they are launched.
386        let runtime =
387            (!self.restartable).then(|| self.runtime.clone().unwrap_or_else(Runtime::test));
388
389        let mut nodes = (0..self.num_nodes)
390            .map(async |idx| {
391                let (node_config, tree_config) = self.node_and_tree_config();
392                // The local miner of dev nodes drives forkchoice, unless a modifier disabled dev
393                // mode.
394                let mines = dev_mining && node_config.dev.dev;
395                let args = LaunchArgs {
396                    idx,
397                    node_factory: self.node_factory.clone(),
398                    node_builder_modifiers: self.node_builder_modifiers.clone(),
399                    node_config,
400                    runtime: runtime.clone(),
401                    tree_config,
402                    datadir: reth_db::test_utils::tempdir_path(),
403                    attributes_generator: self.attributes_generator.clone(),
404                    dev_payload_attributes: self.dev_payload_attributes.clone(),
405                };
406                let node = launch_node(launch.clone(), args, self.restartable, mines)
407                    .instrument(span!(Level::INFO, "node", idx))
408                    .await?;
409
410                if !mines && self.initial_forkchoice {
411                    let genesis = node.block_hash(self.chain_spec.genesis_header().number());
412                    node.update_forkchoice(genesis, genesis).await?;
413                }
414
415                eyre::Ok(node)
416            })
417            .collect::<TryJoinAll<_>>()
418            .await?;
419
420        if self.connect_nodes {
421            for idx in 1..self.num_nodes {
422                let (prev, current) = nodes.split_at_mut(idx);
423                prev[idx - 1].connect(&mut current[0]).await;
424            }
425
426            // Connect the last node with the first if there are more than two.
427            if self.num_nodes > 2 {
428                let (first, rest) = nodes.split_at_mut(1);
429                rest.last_mut().unwrap().connect(&mut first[0]).await;
430            }
431        }
432
433        Ok((nodes, Wallet::default().with_chain_id(self.chain_spec.chain().into())))
434    }
435
436    /// Builds and launches a single test node.
437    ///
438    /// Returns an error if the builder was not configured with exactly one node.
439    pub async fn build_single(self) -> eyre::Result<(NodeHelperType<N>, Wallet)> {
440        ensure!(self.num_nodes == 1, "expected a single node setup, got {} nodes", self.num_nodes);
441        let (mut nodes, wallet) = self.build().await?;
442        Ok((nodes.pop().expect("one node was launched"), wallet))
443    }
444
445    /// Returns the configuration of a test node and the tree configuration derived from it.
446    ///
447    /// The node configuration modifiers run first, the tree configuration modifiers are applied to
448    /// the tree configuration of the resulting node configuration.
449    fn node_and_tree_config(&self) -> (NodeConfig<N::ChainSpec>, TreeConfig) {
450        let node_config = self.node_config_modifiers.iter().fold(
451            test_node_config(self.chain_spec.clone())
452                .with_storage(StorageArgs { v2: self.storage_v2 }),
453            |config, modifier| modifier(config),
454        );
455        let tree_config = self
456            .tree_config_modifiers
457            .iter()
458            .fold(node_config.tree_config(), |config, modifier| modifier(config));
459        (node_config, tree_config)
460    }
461}
462
463impl<N: NodeBuilderHelper> std::fmt::Debug for E2ETestSetupBuilder<N> {
464    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
465        f.debug_struct("E2ETestSetupBuilder")
466            .field("num_nodes", &self.num_nodes)
467            .field("runtime", &self.runtime)
468            .field("connect_nodes", &self.connect_nodes)
469            .field("tree_config_modifiers", &self.tree_config_modifiers.len())
470            .field("node_config_modifiers", &self.node_config_modifiers.len())
471            .field("storage_v2", &self.storage_v2)
472            .field("dev_mining", &self.dev_launcher.is_some())
473            .field("custom_backfill", &self.backfill_launcher.is_some())
474            .field("node_builder_modifiers", &self.node_builder_modifiers.len())
475            .field("restartable", &self.restartable)
476            .finish_non_exhaustive()
477    }
478}
479
480/// Extension trait to create an [`E2ETestSetupBuilder`] from a node type.
481pub trait E2ETestSetupExt: NodeBuilderHelper {
482    /// Returns an [`E2ETestSetupBuilder`] for `num_nodes` nodes of this type, see
483    /// [`E2ETestSetupBuilder::new`].
484    fn test_setup(num_nodes: usize, chain_spec: Arc<Self::ChainSpec>) -> E2ETestSetupBuilder<Self>
485    where
486        PayloadAttrTy<Self>: From<PayloadAttributes>,
487    {
488        E2ETestSetupBuilder::new(num_nodes, chain_spec)
489    }
490
491    /// Returns an [`E2ETestSetupBuilder`] for a single node of this type on the
492    /// [`test_chain_spec`] with every hardfork up to and including `fork` active at genesis, see
493    /// [`E2ETestSetupBuilder::new`].
494    ///
495    /// Use [`E2ETestSetupBuilder::with_num_nodes`] to launch more nodes.
496    fn test_setup_for(fork: EthereumHardfork) -> E2ETestSetupBuilder<Self>
497    where
498        Self::ChainSpec: From<ChainSpec>,
499        PayloadAttrTy<Self>: From<PayloadAttributes>,
500    {
501        let chain_spec = Arc::unwrap_or_clone(test_chain_spec(fork));
502        E2ETestSetupBuilder::new(1, Arc::new(chain_spec.into()))
503    }
504}
505
506impl<N: NodeBuilderHelper> E2ETestSetupExt for N {}
507
508/// Closure that modifies the tree configuration of the test nodes.
509type TreeConfigModifier = Box<dyn Fn(TreeConfig) -> TreeConfig + Send + Sync>;
510
511/// Closure that modifies the node configuration of each test node.
512type NodeConfigModifier<C> = Box<dyn Fn(NodeConfig<C>) -> NodeConfig<C> + Send + Sync>;
513
514/// Closure that generates the payload attributes for a given timestamp.
515pub(crate) type AttributesGenerator<N> = Arc<dyn Fn(u64) -> PayloadAttrTy<N> + Send + Sync>;
516
517/// Closure that maps payload attributes.
518type PayloadAttributesMapper<N> = Arc<dyn Fn(PayloadAttrTy<N>) -> PayloadAttrTy<N> + Send + Sync>;
519
520/// Builder of a test node with the node types, components and add-ons of `N`, which is ready to
521/// be launched.
522///
523/// This is what [`E2ETestSetupBuilder::with_node_builder_modifier`] receives.
524pub type TestNodeBuilder<N> = NodeBuilderWithComponents<
525    TmpNodeAdapter<N>,
526    <N as Node<TmpNodeAdapter<N>>>::ComponentsBuilder,
527    <N as Node<TmpNodeAdapter<N>>>::AddOns,
528>;
529
530/// Closure that returns the node instance of the test node with the given index.
531type NodeFactory<N> = Arc<dyn Fn(usize) -> N + Send + Sync>;
532
533/// Closure that modifies the node builder of each test node.
534type NodeBuilderModifier<N> = Arc<dyn Fn(TestNodeBuilder<N>) -> TestNodeBuilder<N> + Send + Sync>;
535
536/// Closure that launches a single test node on the given database in its datadir.
537type NodeLauncher<N> = Arc<
538    dyn Fn(LaunchArgs<N>, TmpDB) -> BoxFuture<'static, eyre::Result<NodeHelperType<N>>>
539        + Send
540        + Sync,
541>;
542
543/// Client the network of a test node hands its backfill.
544type BackfillClient<N> = BackfillClientFor<TmpNodeAdapter<N>, ComponentsFor<TmpNodeAdapter<N>>>;
545
546/// Arguments for launching a single test node.
547pub(crate) struct LaunchArgs<N: NodeBuilderHelper> {
548    /// The index of the node in the setup.
549    pub(crate) idx: usize,
550    /// Factory of the node instance, called with the index of the node.
551    pub(crate) node_factory: NodeFactory<N>,
552    /// Modifiers for the node builder, applied in order.
553    pub(crate) node_builder_modifiers: Vec<NodeBuilderModifier<N>>,
554    /// The node configuration.
555    pub(crate) node_config: NodeConfig<N::ChainSpec>,
556    /// The runtime to launch the node on, or `None` to launch it on a new [`Runtime::test`]
557    /// runtime of its own.
558    pub(crate) runtime: Option<Runtime>,
559    /// The engine tree configuration.
560    pub(crate) tree_config: TreeConfig,
561    /// The datadir of the node.
562    pub(crate) datadir: PathBuf,
563    /// Generator for the payload attributes of the payloads built by the test context.
564    pub(crate) attributes_generator: AttributesGenerator<N>,
565    /// Mapper for the payload attributes of the local miner in dev mode.
566    pub(crate) dev_payload_attributes: Option<PayloadAttributesMapper<N>>,
567}
568
569// Derived `Clone` would require the chain spec to be `Clone`.
570impl<N: NodeBuilderHelper> Clone for LaunchArgs<N> {
571    fn clone(&self) -> Self {
572        Self {
573            idx: self.idx,
574            node_factory: self.node_factory.clone(),
575            node_builder_modifiers: self.node_builder_modifiers.clone(),
576            node_config: self.node_config.clone(),
577            runtime: self.runtime.clone(),
578            tree_config: self.tree_config.clone(),
579            datadir: self.datadir.clone(),
580            attributes_generator: self.attributes_generator.clone(),
581            dev_payload_attributes: self.dev_payload_attributes.clone(),
582        }
583    }
584}
585
586/// Returns the base configuration of a test node.
587///
588/// Discovery is disabled, all ports are unused, all RPC modules except `testing` are served over
589/// HTTP, the node reports an idle sync state from startup, does not persist its peers and the
590/// engine uses a cross block cache of 1 MiB.
591pub(crate) fn test_node_config<C>(chain_spec: Arc<C>) -> NodeConfig<C> {
592    let mut config = NodeConfig::new(chain_spec)
593        .with_network(NetworkArgs {
594            discovery: DiscoveryArgs { disable_discovery: true, ..DiscoveryArgs::default() },
595            ..NetworkArgs::default()
596        })
597        .with_unused_ports()
598        .with_rpc(
599            RpcServerArgs::default()
600                .with_unused_ports()
601                .with_http()
602                .with_http_api(RpcModuleSelection::All),
603        );
604    // Nodes otherwise report that they are syncing until their first canonical block, which
605    // e.g. stops transaction gossip.
606    config.debug.startup_sync_state_idle = true;
607    // A stopped node would otherwise save its peers and dial them on its own once it is started
608    // again, racing the test that connects it.
609    config.network.no_persist_peers = true;
610    // The cross block cache is allocated up front, and the default of 4 GiB is far more than tests
611    // need. The size is in MiB.
612    config.engine.cross_block_cache_size = 1;
613    // Most tests never validate a blob, so only load the KZG trusted setup when needed.
614    config.debug.lazy_kzg_settings = true;
615    config
616}
617
618/// Launches a test node with the engine launcher and the engine's backfill built by `backfill`.
619pub(crate) async fn launch_test_node<N, B>(
620    args: LaunchArgs<N>,
621    database: TmpDB,
622    backfill: B,
623) -> eyre::Result<NodeHelperType<N>>
624where
625    N: NodeBuilderHelper,
626    B: BackfillSyncBuilder<NodeTypesWithDBAdapter<N, TmpDB>, BackfillClient<N>> + 'static,
627{
628    let LaunchArgs {
629        idx,
630        node_factory,
631        node_builder_modifiers,
632        node_config,
633        runtime,
634        tree_config,
635        datadir,
636        attributes_generator,
637        ..
638    } = args;
639    let (builder, datadir) = test_node_builder(
640        node_factory(idx),
641        node_config,
642        datadir,
643        database,
644        &node_builder_modifiers,
645    );
646    let runtime = runtime.unwrap_or_else(Runtime::test);
647    let NodeHandle { node, node_exit_future } = builder
648        .launch_with(EngineNodeLauncher::new(runtime, datadir, tree_config).with_backfill(backfill))
649        .await?;
650
651    let mut node =
652        NodeTestContext::new(node, move |timestamp| attributes_generator(timestamp)).await?;
653    node.exit_future = Mutex::new(Some(node_exit_future));
654    Ok(node)
655}
656
657/// Launches a test node with the debug launcher, which runs a local miner in dev mode.
658async fn launch_dev_node<N>(args: LaunchArgs<N>, database: TmpDB) -> eyre::Result<NodeHelperType<N>>
659where
660    N: NodeBuilderHelper + DebugNode<Adapter<N>>,
661{
662    let LaunchArgs {
663        idx,
664        node_factory,
665        node_builder_modifiers,
666        node_config,
667        runtime,
668        tree_config,
669        datadir,
670        attributes_generator,
671        dev_payload_attributes,
672    } = args;
673    let (builder, datadir) = test_node_builder(
674        node_factory(idx),
675        node_config,
676        datadir,
677        database,
678        &node_builder_modifiers,
679    );
680    let runtime = runtime.unwrap_or_else(Runtime::test);
681    let launch = builder.launch_with(DebugNodeLauncher::new(EngineNodeLauncher::new(
682        runtime,
683        datadir,
684        tree_config,
685    )));
686    let launch = match dev_payload_attributes {
687        Some(map) => launch.map_debug_payload_attributes(move |attributes| map(attributes)),
688        None => launch,
689    };
690    let NodeHandle { node, node_exit_future } = launch.await?;
691
692    let mut node =
693        NodeTestContext::new(node, move |timestamp| attributes_generator(timestamp)).await?;
694    node.exit_future = Mutex::new(Some(node_exit_future));
695    Ok(node)
696}
697
698/// Returns the builder of the test node `node` with the database in `datadir` and the node
699/// builder modifiers applied, and the resolved datadir of the node.
700fn test_node_builder<N: NodeBuilderHelper>(
701    node: N,
702    node_config: NodeConfig<N::ChainSpec>,
703    datadir: PathBuf,
704    database: TmpDB,
705    node_builder_modifiers: &[NodeBuilderModifier<N>],
706) -> (TestNodeBuilder<N>, ChainPath<DataDirPath>) {
707    let datadir_args =
708        DatadirArgs { datadir: MaybePlatformPath::from(datadir), ..node_config.datadir.clone() };
709    let node_config = node_config.with_datadir_args(datadir_args);
710    let datadir = node_config.datadir();
711    let builder = NodeBuilder::new(node_config)
712        .with_database(database)
713        .with_types_and_provider::<N, BlockchainProvider<_>>()
714        .with_components(node.components_builder())
715        .with_add_ons(node.add_ons());
716    let builder =
717        node_builder_modifiers.iter().fold(builder, |builder, modifier| modifier(builder));
718    (builder, datadir)
719}
720
721/// Launches a test node with `launch` on the database in the datadir of `args`, which is created
722/// if it does not exist yet.
723///
724/// A `restartable` node keeps what [`NodeTestContext::stop`] needs to stop it and launch it again
725/// with the same arguments. Unless the node `mines` in dev mode, the relaunched node receives a
726/// forkchoice update that restates the forkchoice state it loaded from disk.
727fn launch_node<N: NodeBuilderHelper>(
728    launch: NodeLauncher<N>,
729    args: LaunchArgs<N>,
730    restartable: bool,
731    mines: bool,
732) -> BoxFuture<'static, eyre::Result<NodeHelperType<N>>> {
733    Box::pin(async move {
734        let database = open_test_database(&args.datadir)?;
735        let relaunch_args = restartable.then(|| args.clone());
736        let mut node = launch(args, database.clone()).await?;
737        if let Some(args) = relaunch_args {
738            let relaunch: Relaunch<_> =
739                Arc::new(move || relaunch_node(launch.clone(), args.clone(), mines));
740            node.restart = Some(NodeRestart { database, relaunch });
741        }
742        Ok(node)
743    })
744}
745
746/// Launches a stopped restartable node again, see [`launch_node`].
747fn relaunch_node<N: NodeBuilderHelper>(
748    launch: NodeLauncher<N>,
749    args: LaunchArgs<N>,
750    mines: bool,
751) -> BoxFuture<'static, eyre::Result<NodeHelperType<N>>> {
752    let span = span!(Level::INFO, "node", idx = args.idx);
753    Box::pin(
754        async move {
755            let node = launch_node(launch, args, true, mines).await?;
756            if !mines {
757                restate_forkchoice(&node).await?;
758            }
759            Ok(node)
760        }
761        .instrument(span),
762    )
763}
764
765/// Sends a forkchoice update to a restarted node that restates the head, safe and finalized block
766/// it loaded from disk.
767///
768/// Unfinished snap attempts wait for the test to reconnect peers and supply a target.
769/// Returns an error if the engine does not report the update valid.
770async fn restate_forkchoice<N: NodeBuilderHelper>(node: &NodeHelperType<N>) -> eyre::Result<()> {
771    let provider = &node.inner.provider;
772    // During snap sync the latest stored header has no executable state yet. Let the test send
773    // the consensus target after reconnecting peers instead of requiring a VALID response here.
774    if provider
775        .database_provider_ro()?
776        .snap_attempt()?
777        .is_some_and(|attempt| !attempt.is_verified())
778    {
779        return Ok(())
780    }
781    let hash = |tag| -> eyre::Result<Option<B256>> {
782        Ok(provider.sealed_header_by_number_or_tag(tag)?.map(|header| header.hash()))
783    };
784    let head = hash(BlockNumberOrTag::Latest)?
785        .ok_or_else(|| eyre!("the restarted node has no latest block"))?;
786    // A zero hash leaves the safe or finalized block unset if the node did not persist one.
787    let state = ForkchoiceState {
788        head_block_hash: head,
789        safe_block_hash: hash(BlockNumberOrTag::Safe)?.unwrap_or_default(),
790        finalized_block_hash: hash(BlockNumberOrTag::Finalized)?.unwrap_or_default(),
791    };
792    let updated =
793        node.inner.add_ons_handle.beacon_engine_handle.fork_choice_updated(state, None).await?;
794    ensure!(
795        updated.is_valid(),
796        "forkchoice update to the head {head} the restarted node loaded from disk is not valid: {}",
797        updated.payload_status.status
798    );
799    Ok(())
800}
801
802/// Opens the database in `datadir` like [`create_test_rw_db_with_datadir`], creating it if it does
803/// not exist yet.
804///
805/// The datadir is removed when the returned database is dropped.
806///
807/// [`create_test_rw_db_with_datadir`]: reth_db::test_utils::create_test_rw_db_with_datadir
808pub(crate) fn open_test_database(datadir: &Path) -> eyre::Result<TmpDB> {
809    let path = datadir.join("db");
810    let database = init_db(&path, DatabaseArguments::test())
811        .wrap_err_with(|| format!("failed to open the database at {}", path.display()))?;
812    Ok(Arc::new(TempDatabase::new(database, datadir.to_path_buf())))
813}
814
815#[cfg(test)]
816mod tests {
817    use super::*;
818    use reth_node_ethereum::EthereumNode;
819
820    #[test]
821    fn tree_config_uses_small_cross_block_cache() {
822        let (_, tree_config) =
823            EthereumNode::test_setup_for(EthereumHardfork::Cancun).node_and_tree_config();
824        assert_eq!(tree_config.cross_block_cache_size(), 1024 * 1024);
825    }
826
827    #[test]
828    fn tree_config_follows_node_config() {
829        let (_, tree_config) = EthereumNode::test_setup_for(EthereumHardfork::Cancun)
830            .with_node_config_modifier(|mut config| {
831                config.engine.cross_block_cache_size = 2;
832                config.engine.persistence_threshold = 0;
833                config.debug.skip_state_root = true;
834                config
835            })
836            .node_and_tree_config();
837        assert_eq!(tree_config.cross_block_cache_size(), 2 * 1024 * 1024);
838        assert_eq!(tree_config.persistence_threshold(), 0);
839        assert!(tree_config.skip_state_root());
840    }
841
842    #[test]
843    fn tree_config_modifiers_override_node_config() {
844        // Tree config modifiers apply last, even if they are added before node config modifiers.
845        let (_, tree_config) = EthereumNode::test_setup_for(EthereumHardfork::Cancun)
846            .with_tree_config_modifier(|config| config.with_state_root_fallback(false))
847            .with_node_config_modifier(|mut config| {
848                config.engine.state_root_fallback = true;
849                config
850            })
851            .node_and_tree_config();
852        assert!(!tree_config.state_root_fallback());
853    }
854
855    /// Nodes whose payload attributes are not convertible from Ethereum's can be set up with an
856    /// explicit attributes generator.
857    #[expect(dead_code)]
858    async fn build_with_attributes_generator<N: NodeBuilderHelper>(
859        chain_spec: Arc<N::ChainSpec>,
860        attributes_generator: fn(u64) -> PayloadAttrTy<N>,
861    ) -> eyre::Result<(Vec<NodeHelperType<N>>, Wallet)> {
862        E2ETestSetupBuilder::new_with_attributes_generator(1, chain_spec, attributes_generator)
863            .build()
864            .await
865    }
866
867    /// The node builder modifier can use the hooks of the node builder for any node.
868    #[expect(dead_code)]
869    fn node_builder_modifier_can_use_builder_hooks<N: NodeBuilderHelper>(
870        setup: E2ETestSetupBuilder<N>,
871    ) -> E2ETestSetupBuilder<N> {
872        setup.with_node_builder_modifier(|builder| {
873            builder
874                .on_component_initialized(|_| Ok(()))
875                .on_node_started(|_| Ok(()))
876                .on_rpc_started(|_, _| Ok(()))
877                .extend_rpc_modules(|_| Ok(()))
878                .map_add_ons(|add_ons| add_ons)
879                .install_exex("exex", |_| async { Ok(async { Ok(()) }) })
880        })
881    }
882}