Skip to main content

reth_node_builder/launch/
invalid_block_hook.rs

1//! Invalid block hook helpers for the node builder.
2
3use crate::AddOnsContext;
4use alloy_consensus::TxEnvelope;
5use alloy_rpc_types::{Block, Header, Receipt, Transaction, TransactionRequest};
6use eyre::OptionExt;
7use reth_chainspec::EthChainSpec;
8use reth_engine_primitives::InvalidBlockHook;
9use reth_node_api::{FullNodeComponents, NodeTypes};
10use reth_node_core::{
11    args::InvalidBlockHookType,
12    dirs::{ChainPath, DataDirPath},
13    node_config::NodeConfig,
14};
15use reth_primitives_traits::NodePrimitives;
16use reth_provider::ChainSpecProvider;
17use reth_rpc_api::EthApiClient;
18
19/// Extension trait for [`AddOnsContext`] to create invalid block hooks.
20pub trait InvalidBlockHookExt {
21    /// Node primitives type.
22    type Primitives: NodePrimitives;
23
24    /// Creates an invalid block hook based on the node configuration.
25    fn create_invalid_block_hook(
26        &self,
27        data_dir: &ChainPath<DataDirPath>,
28    ) -> impl std::future::Future<Output = eyre::Result<Box<dyn InvalidBlockHook<Self::Primitives>>>>
29           + Send;
30}
31
32impl<N> InvalidBlockHookExt for AddOnsContext<'_, N>
33where
34    N: FullNodeComponents,
35{
36    type Primitives = <N::Types as NodeTypes>::Primitives;
37
38    async fn create_invalid_block_hook(
39        &self,
40        data_dir: &ChainPath<DataDirPath>,
41    ) -> eyre::Result<Box<dyn InvalidBlockHook<Self::Primitives>>> {
42        create_invalid_block_hook(
43            self.config,
44            data_dir,
45            self.node.provider().clone(),
46            self.node.evm_config().clone(),
47            self.node.provider().chain_spec().chain().id(),
48        )
49        .await
50    }
51}
52
53/// Creates an invalid block hook based on the node configuration.
54///
55/// This function constructs the appropriate [`InvalidBlockHook`] based on the debug
56/// configuration in the node config. It supports:
57/// - Witness hooks for capturing block witness data
58/// - Healthy node verification via RPC
59///
60/// # Arguments
61/// * `config` - The node configuration containing debug settings
62/// * `data_dir` - The data directory for storing hook outputs
63/// * `provider` - The blockchain database provider
64/// * `evm_config` - The EVM configuration
65/// * `chain_id` - The chain ID for verification
66pub async fn create_invalid_block_hook<N, P, E>(
67    config: &NodeConfig<P::ChainSpec>,
68    data_dir: &ChainPath<DataDirPath>,
69    provider: P,
70    evm_config: E,
71    chain_id: u64,
72) -> eyre::Result<Box<dyn InvalidBlockHook<N>>>
73where
74    N: NodePrimitives,
75    P: reth_provider::StateProviderFactory + reth_provider::ChainSpecProvider + Clone + 'static,
76    E: reth_evm::ConfigureEvm<Primitives = N> + 'static,
77{
78    use reth_engine_primitives::{InvalidBlockHooks, NoopInvalidBlockHook};
79    use reth_invalid_block_hooks::InvalidBlockWitnessHook;
80
81    let Some(ref hook) = config.debug.invalid_block_hook else {
82        return Ok(Box::new(NoopInvalidBlockHook::default()))
83    };
84
85    let healthy_node_rpc_client = get_healthy_node_client(config, chain_id).await?;
86
87    let output_directory = data_dir.invalid_block_hooks();
88    let hooks = hook
89        .iter()
90        .copied()
91        .map(|hook| {
92            let output_directory = output_directory.join(hook.to_string());
93            std::fs::create_dir_all(&output_directory)?;
94
95            Ok(match hook {
96                InvalidBlockHookType::Witness => Box::new(InvalidBlockWitnessHook::new(
97                    provider.clone(),
98                    evm_config.clone(),
99                    output_directory,
100                    healthy_node_rpc_client.clone(),
101                )),
102                InvalidBlockHookType::PreState | InvalidBlockHookType::Opcode => {
103                    eyre::bail!("invalid block hook {hook:?} is not implemented yet");
104                }
105            } as Box<dyn InvalidBlockHook<_>>)
106        })
107        .collect::<Result<_, _>>()?;
108
109    Ok(Box::new(InvalidBlockHooks(hooks)))
110}
111
112/// Returns an RPC client for the healthy node, if configured in the node config.
113async fn get_healthy_node_client<C>(
114    config: &NodeConfig<C>,
115    chain_id: u64,
116) -> eyre::Result<Option<jsonrpsee::http_client::HttpClient>>
117where
118    C: EthChainSpec,
119{
120    let Some(url) = config.debug.healthy_node_rpc_url.as_ref() else {
121        return Ok(None);
122    };
123
124    let client = jsonrpsee::http_client::HttpClientBuilder::default().build(url)?;
125
126    // Verify that the healthy node is running the same chain as the current node.
127    let healthy_chain_id = EthApiClient::<
128        TransactionRequest,
129        Transaction,
130        Block,
131        Receipt,
132        Header,
133        TxEnvelope,
134    >::chain_id(&client)
135    .await?
136    .ok_or_eyre("healthy node rpc client didn't return a chain id")?;
137
138    if healthy_chain_id.to::<u64>() != chain_id {
139        eyre::bail!("Invalid chain ID. Expected {}, got {}", chain_id, healthy_chain_id);
140    }
141
142    Ok(Some(client))
143}