Skip to main content

reth_node_builder/launch/
debug.rs

1use super::LaunchNode;
2use crate::{rpc::RethRpcAddOns, EngineNodeLauncher, Node, NodeHandle};
3use alloy_consensus::transaction::Either;
4use alloy_provider::network::AnyNetwork;
5use jsonrpsee::core::{DeserializeOwned, Serialize};
6use reth_chainspec::EthChainSpec;
7use reth_consensus_debug_client::{
8    BlockProvider, DebugConsensusClient, EtherscanBlockProvider, RpcBlockProvider,
9};
10use reth_engine_local::LocalMiner;
11use reth_node_api::{
12    BlockTy, FullNodeComponents, FullNodeTypes, HeaderTy, PayloadAttrTy, PayloadAttributesBuilder,
13    PayloadTypes,
14};
15use std::{
16    future::{Future, IntoFuture},
17    pin::Pin,
18    sync::Arc,
19};
20use tracing::info;
21
22/// [`Node`] extension with support for debugging utilities.
23///
24/// This trait provides additional necessary conversion from RPC block type to the node's
25/// primitive block type, e.g. `alloy_rpc_types_eth::Block` to the node's internal block
26/// representation.
27///
28/// This is used in conjunction with the [`DebugNodeLauncher`] to enable debugging features such as:
29///
30/// - **Etherscan Integration**: Use Etherscan as a consensus client to follow the chain and submit
31///   blocks to the local engine.
32/// - **RPC Consensus Client**: Connect to an external RPC endpoint to fetch blocks and submit them
33///   to the local engine to follow the chain.
34///
35/// See [`DebugNodeLauncher`] for the launcher that enables these features.
36///
37/// # Implementation
38///
39/// To implement this trait, you need to:
40/// 1. Define the RPC block type (typically `alloy_rpc_types_eth::Block`)
41/// 2. Implement the conversion from RPC format to your primitive block type
42///
43/// # Example
44///
45/// ```ignore
46/// impl<N: FullNodeComponents<Types = Self>> DebugNode<N> for MyNode {
47///     type RpcBlock = alloy_rpc_types_eth::Block;
48///
49///     fn rpc_to_primitive_block(rpc_block: Self::RpcBlock) -> BlockTy<Self> {
50///         // Convert from RPC format to primitive format by converting the transactions
51///         rpc_block.into_consensus().convert_transactions()
52///     }
53/// }
54/// ```
55pub trait DebugNode<N: FullNodeComponents>: Node<N> {
56    /// RPC block type. Used by [`DebugConsensusClient`] to fetch blocks and submit them to the
57    /// engine. This is intended to match the block format returned by the external RPC endpoint.
58    type RpcBlock: Serialize + DeserializeOwned + 'static;
59
60    /// Converts an RPC block to a primitive block.
61    ///
62    /// This method handles the conversion between the RPC block format and the internal primitive
63    /// block format used by the node's consensus engine.
64    ///
65    /// # Example
66    ///
67    /// For Ethereum nodes, this typically converts from `alloy_rpc_types_eth::Block`
68    /// to the node's internal block representation.
69    fn rpc_to_primitive_block(rpc_block: Self::RpcBlock) -> BlockTy<Self>;
70
71    /// Creates a payload attributes builder for local mining in dev mode.
72    ///
73    ///  It will be used by the `LocalMiner` when dev mode is enabled.
74    ///
75    /// The builder is responsible for creating the payload attributes that define how blocks should
76    /// be constructed during local mining.
77    fn local_payload_attributes_builder(
78        chain_spec: &Self::ChainSpec,
79    ) -> impl PayloadAttributesBuilder<<Self::Payload as PayloadTypes>::PayloadAttributes, HeaderTy<Self>>;
80}
81
82/// Node launcher with support for launching various debugging utilities.
83///
84/// This launcher wraps an existing launcher and adds debugging capabilities when
85/// certain debug flags are enabled. It provides two main debugging features:
86///
87/// ## RPC Consensus Client
88///
89/// When `--debug.rpc-consensus-ws <URL>` is provided, the launcher will:
90/// - Connect to an external RPC endpoint (`WebSocket` or HTTP)
91/// - Fetch blocks from that endpoint (using subscriptions for `WebSocket`, polling for HTTP)
92/// - Submit them to the local engine for execution
93/// - Useful for testing engine behavior with real network data
94///
95/// ## Etherscan Consensus Client
96///
97/// When `--debug.etherscan [URL]` is provided, the launcher will:
98/// - Use Etherscan API as a consensus client
99/// - Fetch recent blocks from Etherscan
100/// - Submit them to the local engine
101/// - Requires `ETHERSCAN_API_KEY` environment variable
102/// - Falls back to default Etherscan URL for the chain if URL not provided
103#[derive(Debug, Clone)]
104pub struct DebugNodeLauncher<L = EngineNodeLauncher> {
105    inner: L,
106}
107
108impl<L> DebugNodeLauncher<L> {
109    /// Creates a new instance of the [`DebugNodeLauncher`].
110    pub const fn new(inner: L) -> Self {
111        Self { inner }
112    }
113}
114
115/// Type alias for the default debug block provider. We use etherscan provider to satisfy the
116/// bounds.
117pub type DefaultDebugBlockProvider<N> = EtherscanBlockProvider<
118    <<N as FullNodeTypes>::Types as DebugNode<N>>::RpcBlock,
119    BlockTy<<N as FullNodeTypes>::Types>,
120>;
121
122/// Future for the [`DebugNodeLauncher`].
123#[expect(missing_debug_implementations, clippy::type_complexity)]
124pub struct DebugNodeLauncherFuture<L, Target, N, B = DefaultDebugBlockProvider<N>>
125where
126    N: FullNodeComponents<Types: DebugNode<N>>,
127{
128    inner: L,
129    target: Target,
130    local_payload_attributes_builder:
131        Option<Box<dyn PayloadAttributesBuilder<PayloadAttrTy<N::Types>, HeaderTy<N::Types>>>>,
132    map_attributes:
133        Option<Box<dyn Fn(PayloadAttrTy<N::Types>) -> PayloadAttrTy<N::Types> + Send + Sync>>,
134    debug_block_provider: Option<B>,
135}
136
137impl<L, Target, N, AddOns, B> DebugNodeLauncherFuture<L, Target, N, B>
138where
139    N: FullNodeComponents<Types: DebugNode<N>>,
140    AddOns: RethRpcAddOns<N>,
141    L: LaunchNode<Target, Node = NodeHandle<N, AddOns>>,
142    B: BlockProvider<Block = BlockTy<N::Types>> + Clone,
143{
144    /// Sets a custom payload attributes builder for local mining in dev mode.
145    pub fn with_payload_attributes_builder(
146        self,
147        builder: impl PayloadAttributesBuilder<PayloadAttrTy<N::Types>, HeaderTy<N::Types>>,
148    ) -> Self {
149        Self {
150            inner: self.inner,
151            target: self.target,
152            local_payload_attributes_builder: Some(Box::new(builder)),
153            map_attributes: None,
154            debug_block_provider: self.debug_block_provider,
155        }
156    }
157
158    /// Sets a function to map payload attributes before building.
159    pub fn map_debug_payload_attributes(
160        self,
161        f: impl Fn(PayloadAttrTy<N::Types>) -> PayloadAttrTy<N::Types> + Send + Sync + 'static,
162    ) -> Self {
163        Self {
164            inner: self.inner,
165            target: self.target,
166            local_payload_attributes_builder: None,
167            map_attributes: Some(Box::new(f)),
168            debug_block_provider: self.debug_block_provider,
169        }
170    }
171
172    /// Sets a custom block provider for the debug consensus client.
173    ///
174    /// When set, this provider will be used instead of creating an `EtherscanBlockProvider`
175    /// or `RpcBlockProvider` from CLI arguments.
176    pub fn with_debug_block_provider<B2>(
177        self,
178        provider: B2,
179    ) -> DebugNodeLauncherFuture<L, Target, N, B2>
180    where
181        B2: BlockProvider<Block = BlockTy<N::Types>> + Clone,
182    {
183        DebugNodeLauncherFuture {
184            inner: self.inner,
185            target: self.target,
186            local_payload_attributes_builder: self.local_payload_attributes_builder,
187            map_attributes: self.map_attributes,
188            debug_block_provider: Some(provider),
189        }
190    }
191
192    async fn launch_node(self) -> eyre::Result<NodeHandle<N, AddOns>> {
193        let Self {
194            inner,
195            target,
196            local_payload_attributes_builder,
197            map_attributes,
198            debug_block_provider,
199        } = self;
200
201        let handle = inner.launch_node(target).await?;
202
203        let config = &handle.node.config;
204
205        if let Some(provider) = debug_block_provider {
206            info!(target: "reth::cli", "Using custom debug block provider");
207
208            let rpc_consensus_client = DebugConsensusClient::new(
209                handle.node.add_ons_handle.beacon_engine_handle.clone(),
210                Arc::new(provider),
211            );
212
213            handle
214                .node
215                .task_executor
216                .spawn_critical_task("custom debug block provider consensus client", async move {
217                    rpc_consensus_client.run().await
218                });
219        } else if let Some(url) = config.debug.rpc_consensus_url.clone() {
220            info!(target: "reth::cli", "Using RPC consensus client: {}", url);
221
222            let block_provider =
223                RpcBlockProvider::<AnyNetwork, _>::new(url.as_str(), |block_response| {
224                    let json = serde_json::to_value(block_response)
225                        .expect("Block serialization cannot fail");
226                    let rpc_block =
227                        serde_json::from_value(json).expect("Block deserialization cannot fail");
228                    N::Types::rpc_to_primitive_block(rpc_block)
229                })
230                .await?;
231
232            let rpc_consensus_client = DebugConsensusClient::new(
233                handle.node.add_ons_handle.beacon_engine_handle.clone(),
234                Arc::new(block_provider),
235            );
236
237            handle.node.task_executor.spawn_critical_task("rpc-ws consensus client", async move {
238                rpc_consensus_client.run().await
239            });
240        } else if let Some(maybe_custom_etherscan_url) = config.debug.etherscan.clone() {
241            info!(target: "reth::cli", "Using etherscan as consensus client");
242
243            let chain = config.chain.chain();
244            let etherscan_url = maybe_custom_etherscan_url.map(Ok).unwrap_or_else(|| {
245                chain
246                    .etherscan_urls()
247                    .map(|urls| urls.0.to_string())
248                    .ok_or_else(|| eyre::eyre!("failed to get etherscan url for chain: {chain}"))
249            })?;
250
251            let block_provider = EtherscanBlockProvider::new(
252                etherscan_url,
253                chain.etherscan_api_key().ok_or_else(|| {
254                    eyre::eyre!(
255                        "etherscan api key not found for rpc consensus client for chain: {chain}"
256                    )
257                })?,
258                chain.id(),
259                N::Types::rpc_to_primitive_block,
260            );
261            let rpc_consensus_client = DebugConsensusClient::new(
262                handle.node.add_ons_handle.beacon_engine_handle.clone(),
263                Arc::new(block_provider),
264            );
265            handle
266                .node
267                .task_executor
268                .spawn_critical_task("etherscan consensus client", async move {
269                    rpc_consensus_client.run().await
270                });
271        }
272
273        if config.dev.dev {
274            info!(target: "reth::cli", "Using local payload attributes builder for dev mode");
275
276            let blockchain_db = handle.node.provider.clone();
277            let chain_spec = config.chain.clone();
278            let beacon_engine_handle = handle.node.add_ons_handle.beacon_engine_handle.clone();
279            let pool = handle.node.pool.clone();
280            let payload_builder_handle = handle.node.payload_builder_handle.clone();
281
282            let builder = if let Some(builder) = local_payload_attributes_builder {
283                Either::Left(builder)
284            } else {
285                let local = N::Types::local_payload_attributes_builder(&chain_spec);
286                let builder = if let Some(f) = map_attributes {
287                    Either::Left(move |parent| f(local.build(&parent)))
288                } else {
289                    Either::Right(local)
290                };
291                Either::Right(builder)
292            };
293
294            let dev_mining_mode = handle.node.config.dev_mining_mode(pool);
295            handle.node.task_executor.spawn_critical_task("local engine", async move {
296                LocalMiner::new(
297                    blockchain_db,
298                    builder,
299                    beacon_engine_handle,
300                    dev_mining_mode,
301                    payload_builder_handle,
302                )
303                .run()
304                .await
305            });
306        }
307
308        Ok(handle)
309    }
310}
311
312impl<L, Target, N, AddOns, B> IntoFuture for DebugNodeLauncherFuture<L, Target, N, B>
313where
314    Target: Send + 'static,
315    N: FullNodeComponents<Types: DebugNode<N>>,
316    AddOns: RethRpcAddOns<N> + 'static,
317    L: LaunchNode<Target, Node = NodeHandle<N, AddOns>> + 'static,
318    B: BlockProvider<Block = BlockTy<N::Types>> + Clone + 'static,
319{
320    type Output = eyre::Result<NodeHandle<N, AddOns>>;
321    type IntoFuture = Pin<Box<dyn Future<Output = eyre::Result<NodeHandle<N, AddOns>>> + Send>>;
322
323    fn into_future(self) -> Self::IntoFuture {
324        Box::pin(self.launch_node())
325    }
326}
327
328impl<L, Target, N, AddOns> LaunchNode<Target> for DebugNodeLauncher<L>
329where
330    Target: Send + 'static,
331    N: FullNodeComponents<Types: DebugNode<N>>,
332    AddOns: RethRpcAddOns<N> + 'static,
333    L: LaunchNode<Target, Node = NodeHandle<N, AddOns>> + 'static,
334    DefaultDebugBlockProvider<N>: BlockProvider<Block = BlockTy<N::Types>> + Clone,
335{
336    type Node = NodeHandle<N, AddOns>;
337    type Future = DebugNodeLauncherFuture<L, Target, N>;
338
339    fn launch_node(self, target: Target) -> Self::Future {
340        DebugNodeLauncherFuture {
341            inner: self.inner,
342            target,
343            local_payload_attributes_builder: None,
344            map_attributes: None,
345            debug_block_provider: None,
346        }
347    }
348}