fc_rpc/
net.rs

1// This file is part of Frontier.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use std::sync::Arc;
20
21use jsonrpsee::core::RpcResult;
22// Substrate
23use sc_network::{service::traits::NetworkService, NetworkPeers};
24use sp_api::ProvideRuntimeApi;
25use sp_blockchain::HeaderBackend;
26use sp_runtime::traits::Block as BlockT;
27// Frontier
28use fc_rpc_core::{types::PeerCount, NetApiServer};
29use fp_rpc::EthereumRuntimeRPCApi;
30
31use crate::internal_err;
32
33/// Net API implementation.
34pub struct Net<B: BlockT, C> {
35	client: Arc<C>,
36	network: Arc<dyn NetworkService>,
37	peer_count_as_hex: bool,
38	_phantom_data: std::marker::PhantomData<B>,
39}
40impl<B: BlockT, C> Net<B, C> {
41	pub fn new(client: Arc<C>, network: Arc<dyn NetworkService>, peer_count_as_hex: bool) -> Self {
42		Self {
43			client,
44			network,
45			peer_count_as_hex,
46			_phantom_data: Default::default(),
47		}
48	}
49}
50
51impl<B, C> NetApiServer for Net<B, C>
52where
53	B: BlockT,
54	C: ProvideRuntimeApi<B>,
55	C::Api: EthereumRuntimeRPCApi<B>,
56	C: HeaderBackend<B> + 'static,
57{
58	fn version(&self) -> RpcResult<String> {
59		let hash = self.client.info().best_hash;
60		Ok(self
61			.client
62			.runtime_api()
63			.chain_id(hash)
64			.map_err(|_| internal_err("fetch runtime chain id failed"))?
65			.to_string())
66	}
67
68	fn peer_count(&self) -> RpcResult<PeerCount> {
69		let peer_count = self.network.sync_num_connected();
70		Ok(match self.peer_count_as_hex {
71			true => PeerCount::String(format!("0x{peer_count:x}")),
72			false => PeerCount::U32(peer_count as u32),
73		})
74	}
75
76	fn is_listening(&self) -> RpcResult<bool> {
77		Ok(true)
78	}
79}