reth_rpc/
net.rs

1use alloy_primitives::U64;
2use jsonrpsee::core::RpcResult as Result;
3use reth_network_api::PeersInfo;
4use reth_rpc_api::NetApiServer;
5use reth_rpc_eth_api::helpers::EthApiSpec;
6
7/// `Net` API implementation.
8///
9/// This type provides the functionality for handling `net` related requests.
10pub struct NetApi<Net, Eth> {
11    /// An interface to interact with the network
12    network: Net,
13    /// The implementation of `eth` API
14    eth: Eth,
15}
16
17// === impl NetApi ===
18
19impl<Net, Eth> NetApi<Net, Eth> {
20    /// Returns a new instance with the given network and eth interface implementations
21    pub const fn new(network: Net, eth: Eth) -> Self {
22        Self { network, eth }
23    }
24}
25
26/// Net rpc implementation
27impl<Net, Eth> NetApiServer for NetApi<Net, Eth>
28where
29    Net: PeersInfo + 'static,
30    Eth: EthApiSpec + 'static,
31{
32    /// Handler for `net_version`
33    fn version(&self) -> Result<String> {
34        // Note: net_version is numeric: <https://github.com/paradigmxyz/reth/issues/5569
35        Ok(self.eth.chain_id().to::<u64>().to_string())
36    }
37
38    /// Handler for `net_peerCount`
39    fn peer_count(&self) -> Result<U64> {
40        Ok(U64::from(self.network.num_connected_peers()))
41    }
42
43    /// Handler for `net_listening`
44    fn is_listening(&self) -> Result<bool> {
45        Ok(true)
46    }
47}
48
49impl<Net, Eth> std::fmt::Debug for NetApi<Net, Eth> {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.debug_struct("NetApi").finish_non_exhaustive()
52    }
53}