reth_cli_commands/p2p/
mod.rs

1//! P2P Debugging tool
2
3use std::{path::PathBuf, sync::Arc};
4
5use alloy_eips::BlockHashOrNumber;
6use backon::{ConstantBuilder, Retryable};
7use clap::{Parser, Subcommand};
8use reth_chainspec::{EthChainSpec, EthereumHardforks, Hardforks};
9use reth_cli::chainspec::ChainSpecParser;
10use reth_cli_util::{get_secret_key, hash_or_num_value_parser};
11use reth_config::Config;
12use reth_network::{BlockDownloaderProvider, NetworkConfigBuilder, NetworkPrimitives};
13use reth_network_p2p::bodies::client::BodiesClient;
14use reth_node_core::{
15    args::{DatabaseArgs, DatadirArgs, NetworkArgs},
16    utils::get_single_header,
17};
18
19mod rlpx;
20
21/// `reth p2p` command
22#[derive(Debug, Parser)]
23pub struct Command<C: ChainSpecParser> {
24    /// The path to the configuration file to use.
25    #[arg(long, value_name = "FILE", verbatim_doc_comment)]
26    config: Option<PathBuf>,
27
28    /// The chain this node is running.
29    ///
30    /// Possible values are either a built-in chain or the path to a chain specification file.
31    #[arg(
32        long,
33        value_name = "CHAIN_OR_PATH",
34        long_help = C::help_message(),
35        default_value = C::SUPPORTED_CHAINS[0],
36        value_parser = C::parser()
37    )]
38    chain: Arc<C::ChainSpec>,
39
40    /// The number of retries per request
41    #[arg(long, default_value = "5")]
42    retries: usize,
43
44    #[command(flatten)]
45    network: NetworkArgs,
46
47    #[command(flatten)]
48    datadir: DatadirArgs,
49
50    #[command(flatten)]
51    db: DatabaseArgs,
52
53    #[command(subcommand)]
54    command: Subcommands,
55}
56
57/// `reth p2p` subcommands
58#[derive(Subcommand, Debug)]
59pub enum Subcommands {
60    /// Download block header
61    Header {
62        /// The header number or hash
63        #[arg(value_parser = hash_or_num_value_parser)]
64        id: BlockHashOrNumber,
65    },
66    /// Download block body
67    Body {
68        /// The block number or hash
69        #[arg(value_parser = hash_or_num_value_parser)]
70        id: BlockHashOrNumber,
71    },
72    // RLPx utilities
73    Rlpx(rlpx::Command),
74}
75
76impl<C: ChainSpecParser<ChainSpec: EthChainSpec + Hardforks + EthereumHardforks>> Command<C> {
77    /// Execute `p2p` command
78    pub async fn execute<N: NetworkPrimitives>(self) -> eyre::Result<()> {
79        let data_dir = self.datadir.clone().resolve_datadir(self.chain.chain());
80        let config_path = self.config.clone().unwrap_or_else(|| data_dir.config());
81
82        // Load configuration
83        let mut config = Config::from_path(&config_path).unwrap_or_default();
84
85        config.peers.trusted_nodes.extend(self.network.trusted_peers.clone());
86
87        if config.peers.trusted_nodes.is_empty() && self.network.trusted_only {
88            eyre::bail!("No trusted nodes. Set trusted peer with `--trusted-peer <enode record>` or set `--trusted-only` to `false`")
89        }
90
91        config.peers.trusted_nodes_only = self.network.trusted_only;
92
93        let default_secret_key_path = data_dir.p2p_secret();
94        let secret_key_path =
95            self.network.p2p_secret_key.clone().unwrap_or(default_secret_key_path);
96        let p2p_secret_key = get_secret_key(&secret_key_path)?;
97        let rlpx_socket = (self.network.addr, self.network.port).into();
98        let boot_nodes = self.chain.bootnodes().unwrap_or_default();
99
100        let net = NetworkConfigBuilder::<N>::new(p2p_secret_key)
101            .peer_config(config.peers_config_with_basic_nodes_from_file(None))
102            .external_ip_resolver(self.network.nat)
103            .disable_discv4_discovery_if(self.chain.chain().is_optimism())
104            .boot_nodes(boot_nodes.clone())
105            .apply(|builder| {
106                self.network.discovery.apply_to_builder(builder, rlpx_socket, boot_nodes)
107            })
108            .build_with_noop_provider(self.chain)
109            .manager()
110            .await?;
111        let network = net.handle().clone();
112        tokio::task::spawn(net);
113
114        let fetch_client = network.fetch_client().await?;
115        let retries = self.retries.max(1);
116        let backoff = ConstantBuilder::default().with_max_times(retries);
117
118        match self.command {
119            Subcommands::Header { id } => {
120                let header = (move || get_single_header(fetch_client.clone(), id))
121                    .retry(backoff)
122                    .notify(|err, _| println!("Error requesting header: {err}. Retrying..."))
123                    .await?;
124                println!("Successfully downloaded header: {header:?}");
125            }
126            Subcommands::Body { id } => {
127                let hash = match id {
128                    BlockHashOrNumber::Hash(hash) => hash,
129                    BlockHashOrNumber::Number(number) => {
130                        println!("Block number provided. Downloading header first...");
131                        let client = fetch_client.clone();
132                        let header = (move || {
133                            get_single_header(client.clone(), BlockHashOrNumber::Number(number))
134                        })
135                        .retry(backoff)
136                        .notify(|err, _| println!("Error requesting header: {err}. Retrying..."))
137                        .await?;
138                        header.hash()
139                    }
140                };
141                let (_, result) = (move || {
142                    let client = fetch_client.clone();
143                    client.get_block_bodies(vec![hash])
144                })
145                .retry(backoff)
146                .notify(|err, _| println!("Error requesting block: {err}. Retrying..."))
147                .await?
148                .split();
149                if result.len() != 1 {
150                    eyre::bail!(
151                        "Invalid number of headers received. Expected: 1. Received: {}",
152                        result.len()
153                    )
154                }
155                let body = result.into_iter().next().unwrap();
156                println!("Successfully downloaded body: {body:?}")
157            }
158            Subcommands::Rlpx(command) => {
159                command.execute().await?;
160            }
161        }
162
163        Ok(())
164    }
165}