subcoin_rpc_bitcoind/
network.rs

1//! Bitcoin Core compatible network RPC methods.
2//!
3//! Implements: getnetworkinfo
4
5use crate::error::Error;
6use crate::types::GetNetworkInfo;
7use bitcoin::Network;
8use jsonrpsee::proc_macros::rpc;
9
10/// Bitcoin Core compatible network RPC API.
11#[rpc(client, server)]
12pub trait NetworkApi {
13    /// Returns an object containing various state info regarding P2P networking.
14    #[method(name = "getnetworkinfo", blocking)]
15    fn get_network_info(&self) -> Result<GetNetworkInfo, Error>;
16}
17
18/// Bitcoin Core compatible network RPC implementation.
19pub struct NetworkRpc {
20    #[allow(dead_code)]
21    network: Network,
22    /// Number of connected peers (can be updated externally).
23    num_peers: std::sync::atomic::AtomicU32,
24}
25
26impl NetworkRpc {
27    /// Creates a new instance of [`NetworkRpc`].
28    pub fn new(network: Network) -> Self {
29        Self {
30            network,
31            num_peers: std::sync::atomic::AtomicU32::new(0),
32        }
33    }
34
35    /// Updates the number of connected peers.
36    pub fn set_num_peers(&self, num: u32) {
37        self.num_peers
38            .store(num, std::sync::atomic::Ordering::Relaxed);
39    }
40}
41
42#[async_trait::async_trait]
43impl NetworkApiServer for NetworkRpc {
44    fn get_network_info(&self) -> Result<GetNetworkInfo, Error> {
45        let num_peers = self.num_peers.load(std::sync::atomic::Ordering::Relaxed);
46
47        // Return a minimal but valid response for electrs compatibility.
48        // electrs checks:
49        // - version >= 21_00_00
50        // - networkactive == true
51        // - relayfee for get_relay_fee()
52        Ok(GetNetworkInfo {
53            // Version 27.0.0 in Bitcoin Core format
54            version: 270000,
55            subversion: "/Subcoin:0.1.0/".to_string(),
56            protocolversion: 70016, // Current Bitcoin protocol version
57            localservices: "0000000000000409".to_string(), // NODE_NETWORK | NODE_WITNESS | NODE_NETWORK_LIMITED
58            localrelay: true,
59            timeoffset: 0,
60            networkactive: true,
61            connections: num_peers,
62            connections_in: 0,
63            connections_out: num_peers,
64            relayfee: 0.00001, // 1 sat/vB in BTC/kvB
65            incrementalfee: 0.00001,
66            localaddresses: vec![],
67            warnings: vec![],
68        })
69    }
70}