LCOV - code coverage report
Current view: top level - src/rpc - net.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 358 784 45.7 %
Date: 2023-09-26 12:08:55 Functions: 24 43 55.8 %

          Line data    Source code
       1             : // Copyright (c) 2009-2022 The Bitcoin Core developers
       2             : // Distributed under the MIT software license, see the accompanying
       3             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4             : 
       5             : #include <rpc/server.h>
       6             : 
       7             : #include <addrman.h>
       8             : #include <banman.h>
       9             : #include <chainparams.h>
      10             : #include <clientversion.h>
      11             : #include <core_io.h>
      12             : #include <net_permissions.h>
      13             : #include <net_processing.h>
      14             : #include <net_types.h> // For banmap_t
      15             : #include <netbase.h>
      16             : #include <node/context.h>
      17           2 : #include <policy/settings.h>
      18           2 : #include <rpc/blockchain.h>
      19             : #include <rpc/protocol.h>
      20             : #include <rpc/server_util.h>
      21             : #include <rpc/util.h>
      22             : #include <sync.h>
      23             : #include <timedata.h>
      24             : #include <util/chaintype.h>
      25             : #include <util/strencodings.h>
      26             : #include <util/string.h>
      27           2 : #include <util/time.h>
      28             : #include <util/translation.h>
      29             : #include <validation.h>
      30             : #include <version.h>
      31             : #include <warnings.h>
      32             : 
      33             : #include <optional>
      34             : 
      35             : #include <univalue.h>
      36             : 
      37             : using node::NodeContext;
      38             : 
      39           2 : const std::vector<std::string> CONNECTION_TYPE_DOC{
      40           2 :         "outbound-full-relay (default automatic connections)",
      41           2 :         "block-relay-only (does not relay transactions or addresses)",
      42           2 :         "inbound (initiated by the peer)",
      43           2 :         "manual (added via addnode RPC or -addnode/-connect configuration options)",
      44           2 :         "addr-fetch (short-lived automatic connection for soliciting addresses)",
      45           2 :         "feeler (short-lived automatic connection for testing addresses)"
      46             : };
      47             : 
      48           2 : static RPCHelpMan getconnectioncount()
      49             : {
      50           4 :     return RPCHelpMan{"getconnectioncount",
      51           2 :                 "\nReturns the number of connections to other nodes.\n",
      52           2 :                 {},
      53           2 :                 RPCResult{
      54           2 :                     RPCResult::Type::NUM, "", "The connection count"
      55             :                 },
      56           2 :                 RPCExamples{
      57           2 :                     HelpExampleCli("getconnectioncount", "")
      58           2 :             + HelpExampleRpc("getconnectioncount", "")
      59             :                 },
      60           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
      61             : {
      62           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
      63           0 :     const CConnman& connman = EnsureConnman(node);
      64             : 
      65           0 :     return connman.GetNodeCount(ConnectionDirection::Both);
      66             : },
      67             :     };
      68           0 : }
      69             : 
      70           2 : static RPCHelpMan ping()
      71             : {
      72           4 :     return RPCHelpMan{"ping",
      73           2 :                 "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
      74           2 :                 "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
      75             :                 "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n",
      76           2 :                 {},
      77           2 :                 RPCResult{RPCResult::Type::NONE, "", ""},
      78           2 :                 RPCExamples{
      79           2 :                     HelpExampleCli("ping", "")
      80           2 :             + HelpExampleRpc("ping", "")
      81             :                 },
      82           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
      83           2 : {
      84           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
      85           0 :     PeerManager& peerman = EnsurePeerman(node);
      86             : 
      87             :     // Request that each node send a ping during next message processing pass
      88           0 :     peerman.SendPings();
      89           0 :     return UniValue::VNULL;
      90           0 : },
      91             :     };
      92           0 : }
      93             : 
      94           2 : static RPCHelpMan getpeerinfo()
      95             : {
      96           2 :     return RPCHelpMan{
      97           2 :         "getpeerinfo",
      98           2 :         "Returns data about each connected network peer as a json array of objects.",
      99           2 :         {},
     100           2 :         RPCResult{
     101           2 :             RPCResult::Type::ARR, "", "",
     102           4 :             {
     103           4 :                 {RPCResult::Type::OBJ, "", "",
     104           2 :                 {
     105          78 :                     {
     106           2 :                     {RPCResult::Type::NUM, "id", "Peer index"},
     107           2 :                     {RPCResult::Type::STR, "addr", "(host:port) The IP address and port of the peer"},
     108           2 :                     {RPCResult::Type::STR, "addrbind", /*optional=*/true, "(ip:port) Bind address of the connection to the peer"},
     109           2 :                     {RPCResult::Type::STR, "addrlocal", /*optional=*/true, "(ip:port) Local address as reported by the peer"},
     110           2 :                     {RPCResult::Type::STR, "network", "Network (" + Join(GetNetworkNames(/*append_unroutable=*/true), ", ") + ")"},
     111           2 :                     {RPCResult::Type::NUM, "mapped_as", /*optional=*/true, "The AS in the BGP route to the peer used for diversifying\n"
     112             :                                                         "peer selection (only available if the asmap config flag is set)"},
     113           2 :                     {RPCResult::Type::STR_HEX, "services", "The services offered"},
     114           4 :                     {RPCResult::Type::ARR, "servicesnames", "the services offered, in human-readable form",
     115           4 :                     {
     116           2 :                         {RPCResult::Type::STR, "SERVICE_NAME", "the service name if it is recognised"}
     117             :                     }},
     118           2 :                     {RPCResult::Type::BOOL, "relaytxes", "Whether we relay transactions to this peer"},
     119           2 :                     {RPCResult::Type::NUM_TIME, "lastsend", "The " + UNIX_EPOCH_TIME + " of the last send"},
     120           2 :                     {RPCResult::Type::NUM_TIME, "lastrecv", "The " + UNIX_EPOCH_TIME + " of the last receive"},
     121           2 :                     {RPCResult::Type::NUM_TIME, "last_transaction", "The " + UNIX_EPOCH_TIME + " of the last valid transaction received from this peer"},
     122           2 :                     {RPCResult::Type::NUM_TIME, "last_block", "The " + UNIX_EPOCH_TIME + " of the last block received from this peer"},
     123           2 :                     {RPCResult::Type::NUM, "bytessent", "The total bytes sent"},
     124           2 :                     {RPCResult::Type::NUM, "bytesrecv", "The total bytes received"},
     125           2 :                     {RPCResult::Type::NUM_TIME, "conntime", "The " + UNIX_EPOCH_TIME + " of the connection"},
     126           2 :                     {RPCResult::Type::NUM, "timeoffset", "The time offset in seconds"},
     127           2 :                     {RPCResult::Type::NUM, "pingtime", /*optional=*/true, "The last ping time in milliseconds (ms), if any"},
     128           2 :                     {RPCResult::Type::NUM, "minping", /*optional=*/true, "The minimum observed ping time in milliseconds (ms), if any"},
     129           2 :                     {RPCResult::Type::NUM, "pingwait", /*optional=*/true, "The duration in milliseconds (ms) of an outstanding ping (if non-zero)"},
     130           2 :                     {RPCResult::Type::NUM, "version", "The peer version, such as 70001"},
     131           2 :                     {RPCResult::Type::STR, "subver", "The string version"},
     132           2 :                     {RPCResult::Type::BOOL, "inbound", "Inbound (true) or Outbound (false)"},
     133           2 :                     {RPCResult::Type::BOOL, "bip152_hb_to", "Whether we selected peer as (compact blocks) high-bandwidth peer"},
     134           2 :                     {RPCResult::Type::BOOL, "bip152_hb_from", "Whether peer selected us as (compact blocks) high-bandwidth peer"},
     135           2 :                     {RPCResult::Type::NUM, "startingheight", "The starting height (block) of the peer"},
     136           2 :                     {RPCResult::Type::NUM, "presynced_headers", "The current height of header pre-synchronization with this peer, or -1 if no low-work sync is in progress"},
     137           2 :                     {RPCResult::Type::NUM, "synced_headers", "The last header we have in common with this peer"},
     138           2 :                     {RPCResult::Type::NUM, "synced_blocks", "The last block we have in common with this peer"},
     139           4 :                     {RPCResult::Type::ARR, "inflight", "",
     140           4 :                     {
     141           2 :                         {RPCResult::Type::NUM, "n", "The heights of blocks we're currently asking from this peer"},
     142             :                     }},
     143           2 :                     {RPCResult::Type::BOOL, "addr_relay_enabled", "Whether we participate in address relay with this peer"},
     144           2 :                     {RPCResult::Type::NUM, "addr_processed", "The total number of addresses processed, excluding those dropped due to rate limiting"},
     145           2 :                     {RPCResult::Type::NUM, "addr_rate_limited", "The total number of addresses dropped due to rate limiting"},
     146           4 :                     {RPCResult::Type::ARR, "permissions", "Any special permissions that have been granted to this peer",
     147           4 :                     {
     148           2 :                         {RPCResult::Type::STR, "permission_type", Join(NET_PERMISSIONS_DOC, ",\n") + ".\n"},
     149             :                     }},
     150           2 :                     {RPCResult::Type::NUM, "minfeefilter", "The minimum fee rate for transactions this peer accepts"},
     151           4 :                     {RPCResult::Type::OBJ_DYN, "bytessent_per_msg", "",
     152           4 :                     {
     153           2 :                         {RPCResult::Type::NUM, "msg", "The total bytes sent aggregated by message type\n"
     154             :                                                       "When a message type is not listed in this json object, the bytes sent are 0.\n"
     155             :                                                       "Only known message types can appear as keys in the object."}
     156             :                     }},
     157           4 :                     {RPCResult::Type::OBJ_DYN, "bytesrecv_per_msg", "",
     158           4 :                     {
     159           4 :                         {RPCResult::Type::NUM, "msg", "The total bytes received aggregated by message type\n"
     160             :                                                       "When a message type is not listed in this json object, the bytes received are 0.\n"
     161             :                                                       "Only known message types can appear as keys in the object and all bytes received\n"
     162           2 :                                                       "of unknown message types are listed under '"+NET_MESSAGE_TYPE_OTHER+"'."}
     163             :                     }},
     164           2 :                     {RPCResult::Type::STR, "connection_type", "Type of connection: \n" + Join(CONNECTION_TYPE_DOC, ",\n") + ".\n"
     165             :                                                               "Please note this output is unlikely to be stable in upcoming releases as we iterate to\n"
     166             :                                                               "best capture connection behaviors."},
     167             :                 }},
     168             :             }},
     169             :         },
     170           2 :         RPCExamples{
     171           2 :             HelpExampleCli("getpeerinfo", "")
     172           2 :             + HelpExampleRpc("getpeerinfo", "")
     173             :         },
     174           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     175             : {
     176           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     177           0 :     const CConnman& connman = EnsureConnman(node);
     178           0 :     const PeerManager& peerman = EnsurePeerman(node);
     179             : 
     180           0 :     std::vector<CNodeStats> vstats;
     181           0 :     connman.GetNodeStats(vstats);
     182             : 
     183           0 :     UniValue ret(UniValue::VARR);
     184             : 
     185           0 :     for (const CNodeStats& stats : vstats) {
     186           0 :         UniValue obj(UniValue::VOBJ);
     187           0 :         CNodeStateStats statestats;
     188           0 :         bool fStateStats = peerman.GetNodeStateStats(stats.nodeid, statestats);
     189             :         // GetNodeStateStats() requires the existence of a CNodeState and a Peer object
     190             :         // to succeed for this peer. These are created at connection initialisation and
     191             :         // exist for the duration of the connection - except if there is a race where the
     192             :         // peer got disconnected in between the GetNodeStats() and the GetNodeStateStats()
     193             :         // calls. In this case, the peer doesn't need to be reported here.
     194           0 :         if (!fStateStats) {
     195           0 :             continue;
     196             :         }
     197           0 :         obj.pushKV("id", stats.nodeid);
     198           0 :         obj.pushKV("addr", stats.m_addr_name);
     199           0 :         if (stats.addrBind.IsValid()) {
     200           0 :             obj.pushKV("addrbind", stats.addrBind.ToStringAddrPort());
     201           0 :         }
     202           0 :         if (!(stats.addrLocal.empty())) {
     203           0 :             obj.pushKV("addrlocal", stats.addrLocal);
     204           0 :         }
     205           0 :         obj.pushKV("network", GetNetworkName(stats.m_network));
     206           0 :         if (stats.m_mapped_as != 0) {
     207           0 :             obj.pushKV("mapped_as", uint64_t(stats.m_mapped_as));
     208           0 :         }
     209           0 :         ServiceFlags services{statestats.their_services};
     210           0 :         obj.pushKV("services", strprintf("%016x", services));
     211           0 :         obj.pushKV("servicesnames", GetServicesNames(services));
     212           0 :         obj.pushKV("relaytxes", statestats.m_relay_txs);
     213           0 :         obj.pushKV("lastsend", count_seconds(stats.m_last_send));
     214           0 :         obj.pushKV("lastrecv", count_seconds(stats.m_last_recv));
     215           0 :         obj.pushKV("last_transaction", count_seconds(stats.m_last_tx_time));
     216           0 :         obj.pushKV("last_block", count_seconds(stats.m_last_block_time));
     217           0 :         obj.pushKV("bytessent", stats.nSendBytes);
     218           0 :         obj.pushKV("bytesrecv", stats.nRecvBytes);
     219           0 :         obj.pushKV("conntime", count_seconds(stats.m_connected));
     220           0 :         obj.pushKV("timeoffset", stats.nTimeOffset);
     221           0 :         if (stats.m_last_ping_time > 0us) {
     222           0 :             obj.pushKV("pingtime", Ticks<SecondsDouble>(stats.m_last_ping_time));
     223           0 :         }
     224           0 :         if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
     225           0 :             obj.pushKV("minping", Ticks<SecondsDouble>(stats.m_min_ping_time));
     226           0 :         }
     227           0 :         if (statestats.m_ping_wait > 0s) {
     228           0 :             obj.pushKV("pingwait", Ticks<SecondsDouble>(statestats.m_ping_wait));
     229           0 :         }
     230           0 :         obj.pushKV("version", stats.nVersion);
     231             :         // Use the sanitized form of subver here, to avoid tricksy remote peers from
     232             :         // corrupting or modifying the JSON output by putting special characters in
     233             :         // their ver message.
     234           0 :         obj.pushKV("subver", stats.cleanSubVer);
     235           0 :         obj.pushKV("inbound", stats.fInbound);
     236           0 :         obj.pushKV("bip152_hb_to", stats.m_bip152_highbandwidth_to);
     237           0 :         obj.pushKV("bip152_hb_from", stats.m_bip152_highbandwidth_from);
     238           0 :         obj.pushKV("startingheight", statestats.m_starting_height);
     239           0 :         obj.pushKV("presynced_headers", statestats.presync_height);
     240           0 :         obj.pushKV("synced_headers", statestats.nSyncHeight);
     241           0 :         obj.pushKV("synced_blocks", statestats.nCommonHeight);
     242           0 :         UniValue heights(UniValue::VARR);
     243           0 :         for (const int height : statestats.vHeightInFlight) {
     244           0 :             heights.push_back(height);
     245             :         }
     246           0 :         obj.pushKV("inflight", heights);
     247           0 :         obj.pushKV("addr_relay_enabled", statestats.m_addr_relay_enabled);
     248           0 :         obj.pushKV("addr_processed", statestats.m_addr_processed);
     249           0 :         obj.pushKV("addr_rate_limited", statestats.m_addr_rate_limited);
     250           0 :         UniValue permissions(UniValue::VARR);
     251           0 :         for (const auto& permission : NetPermissions::ToStrings(stats.m_permission_flags)) {
     252           0 :             permissions.push_back(permission);
     253             :         }
     254           0 :         obj.pushKV("permissions", permissions);
     255           0 :         obj.pushKV("minfeefilter", ValueFromAmount(statestats.m_fee_filter_received));
     256             : 
     257           0 :         UniValue sendPerMsgType(UniValue::VOBJ);
     258           0 :         for (const auto& i : stats.mapSendBytesPerMsgType) {
     259           0 :             if (i.second > 0)
     260           0 :                 sendPerMsgType.pushKV(i.first, i.second);
     261             :         }
     262           0 :         obj.pushKV("bytessent_per_msg", sendPerMsgType);
     263             : 
     264           0 :         UniValue recvPerMsgType(UniValue::VOBJ);
     265           0 :         for (const auto& i : stats.mapRecvBytesPerMsgType) {
     266           0 :             if (i.second > 0)
     267           0 :                 recvPerMsgType.pushKV(i.first, i.second);
     268             :         }
     269           0 :         obj.pushKV("bytesrecv_per_msg", recvPerMsgType);
     270           0 :         obj.pushKV("connection_type", ConnectionTypeAsString(stats.m_conn_type));
     271             : 
     272           0 :         ret.push_back(obj);
     273           0 :     }
     274             : 
     275           0 :     return ret;
     276           0 : },
     277             :     };
     278           0 : }
     279             : 
     280           2 : static RPCHelpMan addnode()
     281             : {
     282           4 :     return RPCHelpMan{"addnode",
     283             :                 "\nAttempts to add or remove a node from the addnode list.\n"
     284             :                 "Or try a connection to a node once.\n"
     285             :                 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n"
     286           2 :                 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n" +
     287           4 :                 strprintf("Addnode connections are limited to %u at a time", MAX_ADDNODE_CONNECTIONS) +
     288             :                 " and are counted separately from the -maxconnections limit.\n",
     289           6 :                 {
     290           2 :                     {"node", RPCArg::Type::STR, RPCArg::Optional::NO, "The address of the peer to connect to"},
     291           2 :                     {"command", RPCArg::Type::STR, RPCArg::Optional::NO, "'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once"},
     292             :                 },
     293           2 :                 RPCResult{RPCResult::Type::NONE, "", ""},
     294           2 :                 RPCExamples{
     295           2 :                     HelpExampleCli("addnode", "\"192.168.0.6:8333\" \"onetry\"")
     296           2 :             + HelpExampleRpc("addnode", "\"192.168.0.6:8333\", \"onetry\"")
     297             :                 },
     298           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     299             : {
     300           0 :     const std::string command{request.params[1].get_str()};
     301           0 :     if (command != "onetry" && command != "add" && command != "remove") {
     302           0 :         throw std::runtime_error(
     303           0 :             self.ToString());
     304             :     }
     305             : 
     306           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     307           0 :     CConnman& connman = EnsureConnman(node);
     308             : 
     309           0 :     const std::string node_arg{request.params[0].get_str()};
     310             : 
     311           0 :     if (command == "onetry")
     312             :     {
     313           0 :         CAddress addr;
     314           0 :         connman.OpenNetworkConnection(addr, /*fCountFailure=*/false, /*grantOutbound=*/nullptr, node_arg.c_str(), ConnectionType::MANUAL);
     315           0 :         return UniValue::VNULL;
     316           0 :     }
     317             : 
     318           0 :     if (command == "add")
     319             :     {
     320           0 :         if (!connman.AddNode(node_arg)) {
     321           0 :             throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
     322             :         }
     323           0 :     }
     324           0 :     else if (command == "remove")
     325             :     {
     326           0 :         if (!connman.RemoveAddedNode(node_arg)) {
     327           0 :             throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node could not be removed. It has not been added previously.");
     328             :         }
     329           0 :     }
     330             : 
     331           0 :     return UniValue::VNULL;
     332           0 : },
     333             :     };
     334           0 : }
     335             : 
     336           2 : static RPCHelpMan addconnection()
     337             : {
     338           4 :     return RPCHelpMan{"addconnection",
     339           2 :         "\nOpen an outbound connection to a specified node. This RPC is for testing only.\n",
     340           6 :         {
     341           2 :             {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP address and port to attempt connecting to."},
     342           2 :             {"connection_type", RPCArg::Type::STR, RPCArg::Optional::NO, "Type of connection to open (\"outbound-full-relay\", \"block-relay-only\", \"addr-fetch\" or \"feeler\")."},
     343             :         },
     344           2 :         RPCResult{
     345           2 :             RPCResult::Type::OBJ, "", "",
     346           6 :             {
     347           2 :                 { RPCResult::Type::STR, "address", "Address of newly added connection." },
     348           2 :                 { RPCResult::Type::STR, "connection_type", "Type of connection opened." },
     349             :             }},
     350           2 :         RPCExamples{
     351           2 :             HelpExampleCli("addconnection", "\"192.168.0.6:8333\" \"outbound-full-relay\"")
     352           2 :             + HelpExampleRpc("addconnection", "\"192.168.0.6:8333\" \"outbound-full-relay\"")
     353             :         },
     354           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     355             : {
     356           0 :     if (Params().GetChainType() != ChainType::REGTEST) {
     357           0 :         throw std::runtime_error("addconnection is for regression testing (-regtest mode) only.");
     358             :     }
     359             : 
     360           0 :     const std::string address = request.params[0].get_str();
     361           0 :     const std::string conn_type_in{TrimString(request.params[1].get_str())};
     362           0 :     ConnectionType conn_type{};
     363           0 :     if (conn_type_in == "outbound-full-relay") {
     364           0 :         conn_type = ConnectionType::OUTBOUND_FULL_RELAY;
     365           0 :     } else if (conn_type_in == "block-relay-only") {
     366           0 :         conn_type = ConnectionType::BLOCK_RELAY;
     367           0 :     } else if (conn_type_in == "addr-fetch") {
     368           0 :         conn_type = ConnectionType::ADDR_FETCH;
     369           0 :     } else if (conn_type_in == "feeler") {
     370           0 :         conn_type = ConnectionType::FEELER;
     371           0 :     } else {
     372           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, self.ToString());
     373             :     }
     374             : 
     375           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     376           0 :     CConnman& connman = EnsureConnman(node);
     377             : 
     378           0 :     const bool success = connman.AddConnection(address, conn_type);
     379           0 :     if (!success) {
     380           0 :         throw JSONRPCError(RPC_CLIENT_NODE_CAPACITY_REACHED, "Error: Already at capacity for specified connection type.");
     381             :     }
     382             : 
     383           0 :     UniValue info(UniValue::VOBJ);
     384           0 :     info.pushKV("address", address);
     385           0 :     info.pushKV("connection_type", conn_type_in);
     386             : 
     387           0 :     return info;
     388           0 : },
     389             :     };
     390           0 : }
     391             : 
     392           2 : static RPCHelpMan disconnectnode()
     393             : {
     394           4 :     return RPCHelpMan{"disconnectnode",
     395           2 :                 "\nImmediately disconnects from the specified peer node.\n"
     396             :                 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
     397             :                 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
     398           6 :                 {
     399           2 :                     {"address", RPCArg::Type::STR, RPCArg::DefaultHint{"fallback to nodeid"}, "The IP address/port of the node"},
     400           2 :                     {"nodeid", RPCArg::Type::NUM, RPCArg::DefaultHint{"fallback to address"}, "The node ID (see getpeerinfo for node IDs)"},
     401             :                 },
     402           2 :                 RPCResult{RPCResult::Type::NONE, "", ""},
     403           2 :                 RPCExamples{
     404           2 :                     HelpExampleCli("disconnectnode", "\"192.168.0.6:8333\"")
     405           2 :             + HelpExampleCli("disconnectnode", "\"\" 1")
     406           2 :             + HelpExampleRpc("disconnectnode", "\"192.168.0.6:8333\"")
     407           2 :             + HelpExampleRpc("disconnectnode", "\"\", 1")
     408             :                 },
     409           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     410             : {
     411           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     412           0 :     CConnman& connman = EnsureConnman(node);
     413             : 
     414             :     bool success;
     415           0 :     const UniValue &address_arg = request.params[0];
     416           0 :     const UniValue &id_arg = request.params[1];
     417             : 
     418           0 :     if (!address_arg.isNull() && id_arg.isNull()) {
     419             :         /* handle disconnect-by-address */
     420           0 :         success = connman.DisconnectNode(address_arg.get_str());
     421           0 :     } else if (!id_arg.isNull() && (address_arg.isNull() || (address_arg.isStr() && address_arg.get_str().empty()))) {
     422             :         /* handle disconnect-by-id */
     423           0 :         NodeId nodeid = (NodeId) id_arg.getInt<int64_t>();
     424           0 :         success = connman.DisconnectNode(nodeid);
     425           0 :     } else {
     426           0 :         throw JSONRPCError(RPC_INVALID_PARAMS, "Only one of address and nodeid should be provided.");
     427             :     }
     428             : 
     429           0 :     if (!success) {
     430           0 :         throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes");
     431             :     }
     432             : 
     433           0 :     return UniValue::VNULL;
     434           0 : },
     435             :     };
     436           0 : }
     437             : 
     438           2 : static RPCHelpMan getaddednodeinfo()
     439             : {
     440           4 :     return RPCHelpMan{"getaddednodeinfo",
     441           2 :                 "\nReturns information about the given added node, or all added nodes\n"
     442             :                 "(note that onetry addnodes are not listed here)\n",
     443           4 :                 {
     444           2 :                     {"node", RPCArg::Type::STR, RPCArg::DefaultHint{"all nodes"}, "If provided, return information about this specific node, otherwise all nodes are returned."},
     445             :                 },
     446           2 :                 RPCResult{
     447           2 :                     RPCResult::Type::ARR, "", "",
     448           4 :                     {
     449           4 :                         {RPCResult::Type::OBJ, "", "",
     450           8 :                         {
     451           2 :                             {RPCResult::Type::STR, "addednode", "The node IP address or name (as provided to addnode)"},
     452           2 :                             {RPCResult::Type::BOOL, "connected", "If connected"},
     453           4 :                             {RPCResult::Type::ARR, "addresses", "Only when connected = true",
     454           4 :                             {
     455           4 :                                 {RPCResult::Type::OBJ, "", "",
     456           6 :                                 {
     457           2 :                                     {RPCResult::Type::STR, "address", "The bitcoin server IP and port we're connected to"},
     458           2 :                                     {RPCResult::Type::STR, "connected", "connection, inbound or outbound"},
     459             :                                 }},
     460             :                             }},
     461             :                         }},
     462             :                     }
     463             :                 },
     464           2 :                 RPCExamples{
     465           2 :                     HelpExampleCli("getaddednodeinfo", "\"192.168.0.201\"")
     466           2 :             + HelpExampleRpc("getaddednodeinfo", "\"192.168.0.201\"")
     467             :                 },
     468           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     469             : {
     470           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     471           0 :     const CConnman& connman = EnsureConnman(node);
     472             : 
     473           0 :     std::vector<AddedNodeInfo> vInfo = connman.GetAddedNodeInfo();
     474             : 
     475           0 :     if (!request.params[0].isNull()) {
     476           0 :         bool found = false;
     477           0 :         for (const AddedNodeInfo& info : vInfo) {
     478           0 :             if (info.strAddedNode == request.params[0].get_str()) {
     479           0 :                 vInfo.assign(1, info);
     480           0 :                 found = true;
     481           0 :                 break;
     482             :             }
     483             :         }
     484           0 :         if (!found) {
     485           0 :             throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
     486             :         }
     487           0 :     }
     488             : 
     489           0 :     UniValue ret(UniValue::VARR);
     490             : 
     491           0 :     for (const AddedNodeInfo& info : vInfo) {
     492           0 :         UniValue obj(UniValue::VOBJ);
     493           0 :         obj.pushKV("addednode", info.strAddedNode);
     494           0 :         obj.pushKV("connected", info.fConnected);
     495           0 :         UniValue addresses(UniValue::VARR);
     496           0 :         if (info.fConnected) {
     497           0 :             UniValue address(UniValue::VOBJ);
     498           0 :             address.pushKV("address", info.resolvedAddress.ToStringAddrPort());
     499           0 :             address.pushKV("connected", info.fInbound ? "inbound" : "outbound");
     500           0 :             addresses.push_back(address);
     501           0 :         }
     502           0 :         obj.pushKV("addresses", addresses);
     503           0 :         ret.push_back(obj);
     504           0 :     }
     505             : 
     506           0 :     return ret;
     507           0 : },
     508             :     };
     509           0 : }
     510             : 
     511           2 : static RPCHelpMan getnettotals()
     512             : {
     513           4 :     return RPCHelpMan{"getnettotals",
     514           2 :         "Returns information about network traffic, including bytes in, bytes out,\n"
     515             :         "and current system time.",
     516           2 :         {},
     517           2 :                 RPCResult{
     518           2 :                    RPCResult::Type::OBJ, "", "",
     519          10 :                    {
     520           2 :                        {RPCResult::Type::NUM, "totalbytesrecv", "Total bytes received"},
     521           2 :                        {RPCResult::Type::NUM, "totalbytessent", "Total bytes sent"},
     522           2 :                        {RPCResult::Type::NUM_TIME, "timemillis", "Current system " + UNIX_EPOCH_TIME + " in milliseconds"},
     523           4 :                        {RPCResult::Type::OBJ, "uploadtarget", "",
     524          14 :                        {
     525           2 :                            {RPCResult::Type::NUM, "timeframe", "Length of the measuring timeframe in seconds"},
     526           2 :                            {RPCResult::Type::NUM, "target", "Target in bytes"},
     527           2 :                            {RPCResult::Type::BOOL, "target_reached", "True if target is reached"},
     528           2 :                            {RPCResult::Type::BOOL, "serve_historical_blocks", "True if serving historical blocks"},
     529           2 :                            {RPCResult::Type::NUM, "bytes_left_in_cycle", "Bytes left in current time cycle"},
     530           2 :                            {RPCResult::Type::NUM, "time_left_in_cycle", "Seconds left in current time cycle"},
     531             :                         }},
     532             :                     }
     533             :                 },
     534           2 :                 RPCExamples{
     535           2 :                     HelpExampleCli("getnettotals", "")
     536           2 :             + HelpExampleRpc("getnettotals", "")
     537             :                 },
     538           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     539             : {
     540           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     541           0 :     const CConnman& connman = EnsureConnman(node);
     542             : 
     543           0 :     UniValue obj(UniValue::VOBJ);
     544           0 :     obj.pushKV("totalbytesrecv", connman.GetTotalBytesRecv());
     545           0 :     obj.pushKV("totalbytessent", connman.GetTotalBytesSent());
     546           0 :     obj.pushKV("timemillis", TicksSinceEpoch<std::chrono::milliseconds>(SystemClock::now()));
     547             : 
     548           0 :     UniValue outboundLimit(UniValue::VOBJ);
     549           0 :     outboundLimit.pushKV("timeframe", count_seconds(connman.GetMaxOutboundTimeframe()));
     550           0 :     outboundLimit.pushKV("target", connman.GetMaxOutboundTarget());
     551           0 :     outboundLimit.pushKV("target_reached", connman.OutboundTargetReached(false));
     552           0 :     outboundLimit.pushKV("serve_historical_blocks", !connman.OutboundTargetReached(true));
     553           0 :     outboundLimit.pushKV("bytes_left_in_cycle", connman.GetOutboundTargetBytesLeft());
     554           0 :     outboundLimit.pushKV("time_left_in_cycle", count_seconds(connman.GetMaxOutboundTimeLeftInCycle()));
     555           0 :     obj.pushKV("uploadtarget", outboundLimit);
     556           0 :     return obj;
     557           0 : },
     558             :     };
     559           0 : }
     560             : 
     561           0 : static UniValue GetNetworksInfo()
     562             : {
     563           0 :     UniValue networks(UniValue::VARR);
     564           0 :     for (int n = 0; n < NET_MAX; ++n) {
     565           0 :         enum Network network = static_cast<enum Network>(n);
     566           0 :         if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
     567           0 :         Proxy proxy;
     568           0 :         UniValue obj(UniValue::VOBJ);
     569           0 :         GetProxy(network, proxy);
     570           0 :         obj.pushKV("name", GetNetworkName(network));
     571           0 :         obj.pushKV("limited", !IsReachable(network));
     572           0 :         obj.pushKV("reachable", IsReachable(network));
     573           0 :         obj.pushKV("proxy", proxy.IsValid() ? proxy.proxy.ToStringAddrPort() : std::string());
     574           0 :         obj.pushKV("proxy_randomize_credentials", proxy.randomize_credentials);
     575           0 :         networks.push_back(obj);
     576           0 :     }
     577           0 :     return networks;
     578           0 : }
     579             : 
     580           2 : static RPCHelpMan getnetworkinfo()
     581             : {
     582           4 :     return RPCHelpMan{"getnetworkinfo",
     583           2 :                 "Returns an object containing various state info regarding P2P networking.\n",
     584           2 :                 {},
     585           2 :                 RPCResult{
     586           2 :                     RPCResult::Type::OBJ, "", "",
     587          34 :                     {
     588           2 :                         {RPCResult::Type::NUM, "version", "the server version"},
     589           2 :                         {RPCResult::Type::STR, "subversion", "the server subversion string"},
     590           2 :                         {RPCResult::Type::NUM, "protocolversion", "the protocol version"},
     591           2 :                         {RPCResult::Type::STR_HEX, "localservices", "the services we offer to the network"},
     592           4 :                         {RPCResult::Type::ARR, "localservicesnames", "the services we offer to the network, in human-readable form",
     593           4 :                         {
     594           2 :                             {RPCResult::Type::STR, "SERVICE_NAME", "the service name"},
     595             :                         }},
     596           2 :                         {RPCResult::Type::BOOL, "localrelay", "true if transaction relay is requested from peers"},
     597           2 :                         {RPCResult::Type::NUM, "timeoffset", "the time offset"},
     598           2 :                         {RPCResult::Type::NUM, "connections", "the total number of connections"},
     599           2 :                         {RPCResult::Type::NUM, "connections_in", "the number of inbound connections"},
     600           2 :                         {RPCResult::Type::NUM, "connections_out", "the number of outbound connections"},
     601           2 :                         {RPCResult::Type::BOOL, "networkactive", "whether p2p networking is enabled"},
     602           4 :                         {RPCResult::Type::ARR, "networks", "information per network",
     603           4 :                         {
     604           4 :                             {RPCResult::Type::OBJ, "", "",
     605          12 :                             {
     606           2 :                                 {RPCResult::Type::STR, "name", "network (" + Join(GetNetworkNames(), ", ") + ")"},
     607           2 :                                 {RPCResult::Type::BOOL, "limited", "is the network limited using -onlynet?"},
     608           2 :                                 {RPCResult::Type::BOOL, "reachable", "is the network reachable?"},
     609           2 :                                 {RPCResult::Type::STR, "proxy", "(\"host:port\") the proxy that is used for this network, or empty if none"},
     610           2 :                                 {RPCResult::Type::BOOL, "proxy_randomize_credentials", "Whether randomized credentials are used"},
     611             :                             }},
     612             :                         }},
     613           2 :                         {RPCResult::Type::NUM, "relayfee", "minimum relay fee rate for transactions in " + CURRENCY_UNIT + "/kvB"},
     614           2 :                         {RPCResult::Type::NUM, "incrementalfee", "minimum fee rate increment for mempool limiting or replacement in " + CURRENCY_UNIT + "/kvB"},
     615           4 :                         {RPCResult::Type::ARR, "localaddresses", "list of local addresses",
     616           4 :                         {
     617           4 :                             {RPCResult::Type::OBJ, "", "",
     618           8 :                             {
     619           2 :                                 {RPCResult::Type::STR, "address", "network address"},
     620           2 :                                 {RPCResult::Type::NUM, "port", "network port"},
     621           2 :                                 {RPCResult::Type::NUM, "score", "relative score"},
     622             :                             }},
     623             :                         }},
     624           2 :                         {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"},
     625             :                     }
     626             :                 },
     627           2 :                 RPCExamples{
     628           2 :                     HelpExampleCli("getnetworkinfo", "")
     629           2 :             + HelpExampleRpc("getnetworkinfo", "")
     630             :                 },
     631           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     632             : {
     633           0 :     LOCK(cs_main);
     634           0 :     UniValue obj(UniValue::VOBJ);
     635           0 :     obj.pushKV("version",       CLIENT_VERSION);
     636           0 :     obj.pushKV("subversion",    strSubVersion);
     637           0 :     obj.pushKV("protocolversion",PROTOCOL_VERSION);
     638           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     639           0 :     if (node.connman) {
     640           0 :         ServiceFlags services = node.connman->GetLocalServices();
     641           0 :         obj.pushKV("localservices", strprintf("%016x", services));
     642           0 :         obj.pushKV("localservicesnames", GetServicesNames(services));
     643           0 :     }
     644           0 :     if (node.peerman) {
     645           0 :         obj.pushKV("localrelay", !node.peerman->IgnoresIncomingTxs());
     646           0 :     }
     647           0 :     obj.pushKV("timeoffset",    GetTimeOffset());
     648           0 :     if (node.connman) {
     649           0 :         obj.pushKV("networkactive", node.connman->GetNetworkActive());
     650           0 :         obj.pushKV("connections", node.connman->GetNodeCount(ConnectionDirection::Both));
     651           0 :         obj.pushKV("connections_in", node.connman->GetNodeCount(ConnectionDirection::In));
     652           0 :         obj.pushKV("connections_out", node.connman->GetNodeCount(ConnectionDirection::Out));
     653           0 :     }
     654           0 :     obj.pushKV("networks",      GetNetworksInfo());
     655           0 :     if (node.mempool) {
     656             :         // Those fields can be deprecated, to be replaced by the getmempoolinfo fields
     657           0 :         obj.pushKV("relayfee", ValueFromAmount(node.mempool->m_min_relay_feerate.GetFeePerK()));
     658           0 :         obj.pushKV("incrementalfee", ValueFromAmount(node.mempool->m_incremental_relay_feerate.GetFeePerK()));
     659           0 :     }
     660           0 :     UniValue localAddresses(UniValue::VARR);
     661             :     {
     662           0 :         LOCK(g_maplocalhost_mutex);
     663           0 :         for (const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
     664             :         {
     665           0 :             UniValue rec(UniValue::VOBJ);
     666           0 :             rec.pushKV("address", item.first.ToStringAddr());
     667           0 :             rec.pushKV("port", item.second.nPort);
     668           0 :             rec.pushKV("score", item.second.nScore);
     669           0 :             localAddresses.push_back(rec);
     670           0 :         }
     671           0 :     }
     672           0 :     obj.pushKV("localaddresses", localAddresses);
     673           0 :     obj.pushKV("warnings",       GetWarnings(false).original);
     674           0 :     return obj;
     675           0 : },
     676             :     };
     677           0 : }
     678             : 
     679           2 : static RPCHelpMan setban()
     680             : {
     681           4 :     return RPCHelpMan{"setban",
     682           2 :                 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
     683          10 :                 {
     684           2 :                     {"subnet", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP/Subnet (see getpeerinfo for nodes IP) with an optional netmask (default is /32 = single IP)"},
     685           2 :                     {"command", RPCArg::Type::STR, RPCArg::Optional::NO, "'add' to add an IP/Subnet to the list, 'remove' to remove an IP/Subnet from the list"},
     686           2 :                     {"bantime", RPCArg::Type::NUM, RPCArg::Default{0}, "time in seconds how long (or until when if [absolute] is set) the IP is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)"},
     687           2 :                     {"absolute", RPCArg::Type::BOOL, RPCArg::Default{false}, "If set, the bantime must be an absolute timestamp expressed in " + UNIX_EPOCH_TIME},
     688             :                 },
     689           2 :                 RPCResult{RPCResult::Type::NONE, "", ""},
     690           2 :                 RPCExamples{
     691           2 :                     HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
     692           2 :                             + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
     693           2 :                             + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\", 86400")
     694             :                 },
     695           2 :         [&](const RPCHelpMan& help, const JSONRPCRequest& request) -> UniValue
     696             : {
     697           0 :     std::string strCommand;
     698           0 :     if (!request.params[1].isNull())
     699           0 :         strCommand = request.params[1].get_str();
     700           0 :     if (strCommand != "add" && strCommand != "remove") {
     701           0 :         throw std::runtime_error(help.ToString());
     702             :     }
     703           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     704           0 :     BanMan& banman = EnsureBanman(node);
     705             : 
     706           0 :     CSubNet subNet;
     707           0 :     CNetAddr netAddr;
     708           0 :     bool isSubnet = false;
     709             : 
     710           0 :     if (request.params[0].get_str().find('/') != std::string::npos)
     711           0 :         isSubnet = true;
     712             : 
     713           0 :     if (!isSubnet) {
     714           0 :         const std::optional<CNetAddr> addr{LookupHost(request.params[0].get_str(), false)};
     715           0 :         if (addr.has_value()) {
     716           0 :             netAddr = addr.value();
     717           0 :         }
     718           0 :     }
     719             :     else
     720           0 :         LookupSubNet(request.params[0].get_str(), subNet);
     721             : 
     722           0 :     if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) )
     723           0 :         throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Invalid IP/Subnet");
     724             : 
     725           0 :     if (strCommand == "add")
     726             :     {
     727           0 :         if (isSubnet ? banman.IsBanned(subNet) : banman.IsBanned(netAddr)) {
     728           0 :             throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
     729             :         }
     730             : 
     731           0 :         int64_t banTime = 0; //use standard bantime if not specified
     732           0 :         if (!request.params[2].isNull())
     733           0 :             banTime = request.params[2].getInt<int64_t>();
     734             : 
     735           0 :         const bool absolute{request.params[3].isNull() ? false : request.params[3].get_bool()};
     736             : 
     737           0 :         if (absolute && banTime < GetTime()) {
     738           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Error: Absolute timestamp is in the past");
     739             :         }
     740             : 
     741           0 :         if (isSubnet) {
     742           0 :             banman.Ban(subNet, banTime, absolute);
     743           0 :             if (node.connman) {
     744           0 :                 node.connman->DisconnectNode(subNet);
     745           0 :             }
     746           0 :         } else {
     747           0 :             banman.Ban(netAddr, banTime, absolute);
     748           0 :             if (node.connman) {
     749           0 :                 node.connman->DisconnectNode(netAddr);
     750           0 :             }
     751             :         }
     752           0 :     }
     753           0 :     else if(strCommand == "remove")
     754             :     {
     755           0 :         if (!( isSubnet ? banman.Unban(subNet) : banman.Unban(netAddr) )) {
     756           0 :             throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Unban failed. Requested address/subnet was not previously manually banned.");
     757             :         }
     758           0 :     }
     759           0 :     return UniValue::VNULL;
     760           0 : },
     761             :     };
     762           0 : }
     763             : 
     764           2 : static RPCHelpMan listbanned()
     765             : {
     766           4 :     return RPCHelpMan{"listbanned",
     767           2 :                 "\nList all manually banned IPs/Subnets.\n",
     768           2 :                 {},
     769           4 :         RPCResult{RPCResult::Type::ARR, "", "",
     770           4 :             {
     771           4 :                 {RPCResult::Type::OBJ, "", "",
     772          12 :                     {
     773           2 :                         {RPCResult::Type::STR, "address", "The IP/Subnet of the banned node"},
     774           2 :                         {RPCResult::Type::NUM_TIME, "ban_created", "The " + UNIX_EPOCH_TIME + " the ban was created"},
     775           2 :                         {RPCResult::Type::NUM_TIME, "banned_until", "The " + UNIX_EPOCH_TIME + " the ban expires"},
     776           2 :                         {RPCResult::Type::NUM_TIME, "ban_duration", "The ban duration, in seconds"},
     777           2 :                         {RPCResult::Type::NUM_TIME, "time_remaining", "The time remaining until the ban expires, in seconds"},
     778             :                     }},
     779             :             }},
     780           2 :                 RPCExamples{
     781           2 :                     HelpExampleCli("listbanned", "")
     782           2 :                             + HelpExampleRpc("listbanned", "")
     783             :                 },
     784           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     785             : {
     786           0 :     BanMan& banman = EnsureAnyBanman(request.context);
     787             : 
     788           0 :     banmap_t banMap;
     789           0 :     banman.GetBanned(banMap);
     790           0 :     const int64_t current_time{GetTime()};
     791             : 
     792           0 :     UniValue bannedAddresses(UniValue::VARR);
     793           0 :     for (const auto& entry : banMap)
     794             :     {
     795           0 :         const CBanEntry& banEntry = entry.second;
     796           0 :         UniValue rec(UniValue::VOBJ);
     797           0 :         rec.pushKV("address", entry.first.ToString());
     798           0 :         rec.pushKV("ban_created", banEntry.nCreateTime);
     799           0 :         rec.pushKV("banned_until", banEntry.nBanUntil);
     800           0 :         rec.pushKV("ban_duration", (banEntry.nBanUntil - banEntry.nCreateTime));
     801           0 :         rec.pushKV("time_remaining", (banEntry.nBanUntil - current_time));
     802             : 
     803           0 :         bannedAddresses.push_back(rec);
     804           0 :     }
     805             : 
     806           0 :     return bannedAddresses;
     807           0 : },
     808             :     };
     809           0 : }
     810             : 
     811           2 : static RPCHelpMan clearbanned()
     812             : {
     813           4 :     return RPCHelpMan{"clearbanned",
     814           2 :                 "\nClear all banned IPs.\n",
     815           2 :                 {},
     816           2 :                 RPCResult{RPCResult::Type::NONE, "", ""},
     817           2 :                 RPCExamples{
     818           2 :                     HelpExampleCli("clearbanned", "")
     819           2 :                             + HelpExampleRpc("clearbanned", "")
     820             :                 },
     821           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     822             : {
     823           0 :     BanMan& banman = EnsureAnyBanman(request.context);
     824             : 
     825           0 :     banman.ClearBanned();
     826             : 
     827           0 :     return UniValue::VNULL;
     828           0 : },
     829             :     };
     830           0 : }
     831             : 
     832           2 : static RPCHelpMan setnetworkactive()
     833             : {
     834           4 :     return RPCHelpMan{"setnetworkactive",
     835           2 :                 "\nDisable/enable all p2p network activity.\n",
     836           4 :                 {
     837           2 :                     {"state", RPCArg::Type::BOOL, RPCArg::Optional::NO, "true to enable networking, false to disable"},
     838             :                 },
     839           2 :                 RPCResult{RPCResult::Type::BOOL, "", "The value that was passed in"},
     840           2 :                 RPCExamples{""},
     841           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     842             : {
     843           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     844           0 :     CConnman& connman = EnsureConnman(node);
     845             : 
     846           0 :     connman.SetNetworkActive(request.params[0].get_bool());
     847             : 
     848           0 :     return connman.GetNetworkActive();
     849             : },
     850             :     };
     851           0 : }
     852             : 
     853           2 : static RPCHelpMan getnodeaddresses()
     854             : {
     855           4 :     return RPCHelpMan{"getnodeaddresses",
     856           2 :                 "Return known addresses, after filtering for quality and recency.\n"
     857             :                 "These can potentially be used to find new peers in the network.\n"
     858             :                 "The total number of addresses known to the node may be higher.",
     859           6 :                 {
     860           2 :                     {"count", RPCArg::Type::NUM, RPCArg::Default{1}, "The maximum number of addresses to return. Specify 0 to return all known addresses."},
     861           2 :                     {"network", RPCArg::Type::STR, RPCArg::DefaultHint{"all networks"}, "Return only addresses of the specified network. Can be one of: " + Join(GetNetworkNames(), ", ") + "."},
     862             :                 },
     863           2 :                 RPCResult{
     864           2 :                     RPCResult::Type::ARR, "", "",
     865           4 :                     {
     866           4 :                         {RPCResult::Type::OBJ, "", "",
     867          12 :                         {
     868           2 :                             {RPCResult::Type::NUM_TIME, "time", "The " + UNIX_EPOCH_TIME + " when the node was last seen"},
     869           2 :                             {RPCResult::Type::NUM, "services", "The services offered by the node"},
     870           2 :                             {RPCResult::Type::STR, "address", "The address of the node"},
     871           2 :                             {RPCResult::Type::NUM, "port", "The port number of the node"},
     872           2 :                             {RPCResult::Type::STR, "network", "The network (" + Join(GetNetworkNames(), ", ") + ") the node connected through"},
     873             :                         }},
     874             :                     }
     875             :                 },
     876           2 :                 RPCExamples{
     877           2 :                     HelpExampleCli("getnodeaddresses", "8")
     878           2 :                     + HelpExampleCli("getnodeaddresses", "4 \"i2p\"")
     879           2 :                     + HelpExampleCli("-named getnodeaddresses", "network=onion count=12")
     880           2 :                     + HelpExampleRpc("getnodeaddresses", "8")
     881           2 :                     + HelpExampleRpc("getnodeaddresses", "4, \"i2p\"")
     882             :                 },
     883           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     884             : {
     885           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     886           0 :     const CConnman& connman = EnsureConnman(node);
     887             : 
     888           0 :     const int count{request.params[0].isNull() ? 1 : request.params[0].getInt<int>()};
     889           0 :     if (count < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Address count out of range");
     890             : 
     891           0 :     const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{ParseNetwork(request.params[1].get_str())}};
     892           0 :     if (network == NET_UNROUTABLE) {
     893           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Network not recognized: %s", request.params[1].get_str()));
     894             :     }
     895             : 
     896             :     // returns a shuffled list of CAddress
     897           0 :     const std::vector<CAddress> vAddr{connman.GetAddresses(count, /*max_pct=*/0, network)};
     898           0 :     UniValue ret(UniValue::VARR);
     899             : 
     900           0 :     for (const CAddress& addr : vAddr) {
     901           0 :         UniValue obj(UniValue::VOBJ);
     902           0 :         obj.pushKV("time", int64_t{TicksSinceEpoch<std::chrono::seconds>(addr.nTime)});
     903           0 :         obj.pushKV("services", (uint64_t)addr.nServices);
     904           0 :         obj.pushKV("address", addr.ToStringAddr());
     905           0 :         obj.pushKV("port", addr.GetPort());
     906           0 :         obj.pushKV("network", GetNetworkName(addr.GetNetClass()));
     907           0 :         ret.push_back(obj);
     908           0 :     }
     909           0 :     return ret;
     910           0 : },
     911             :     };
     912           0 : }
     913             : 
     914           2 : static RPCHelpMan addpeeraddress()
     915             : {
     916           4 :     return RPCHelpMan{"addpeeraddress",
     917           2 :         "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
     918           8 :         {
     919           2 :             {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP address of the peer"},
     920           2 :             {"port", RPCArg::Type::NUM, RPCArg::Optional::NO, "The port of the peer"},
     921           2 :             {"tried", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, attempt to add the peer to the tried addresses table"},
     922             :         },
     923           2 :         RPCResult{
     924           2 :             RPCResult::Type::OBJ, "", "",
     925           4 :             {
     926           2 :                 {RPCResult::Type::BOOL, "success", "whether the peer address was successfully added to the address manager"},
     927             :             },
     928             :         },
     929           2 :         RPCExamples{
     930           2 :             HelpExampleCli("addpeeraddress", "\"1.2.3.4\" 8333 true")
     931           2 :     + HelpExampleRpc("addpeeraddress", "\"1.2.3.4\", 8333, true")
     932             :         },
     933           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     934             : {
     935           0 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     936           0 :     if (!node.addrman) {
     937           0 :         throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Address manager functionality missing or disabled");
     938             :     }
     939             : 
     940           0 :     const std::string& addr_string{request.params[0].get_str()};
     941           0 :     const auto port{request.params[1].getInt<uint16_t>()};
     942           0 :     const bool tried{request.params[2].isNull() ? false : request.params[2].get_bool()};
     943             : 
     944           0 :     UniValue obj(UniValue::VOBJ);
     945           0 :     std::optional<CNetAddr> net_addr{LookupHost(addr_string, false)};
     946           0 :     bool success{false};
     947             : 
     948           0 :     if (net_addr.has_value()) {
     949           0 :         CService service{net_addr.value(), port};
     950           0 :         CAddress address{MaybeFlipIPv6toCJDNS(service), ServiceFlags{NODE_NETWORK | NODE_WITNESS}};
     951           0 :         address.nTime = Now<NodeSeconds>();
     952             :         // The source address is set equal to the address. This is equivalent to the peer
     953             :         // announcing itself.
     954           0 :         if (node.addrman->Add({address}, address)) {
     955           0 :             success = true;
     956           0 :             if (tried) {
     957             :                 // Attempt to move the address to the tried addresses table.
     958           0 :                 node.addrman->Good(address);
     959           0 :             }
     960           0 :         }
     961           0 :     }
     962             : 
     963           0 :     obj.pushKV("success", success);
     964           0 :     return obj;
     965           0 : },
     966             :     };
     967           0 : }
     968             : 
     969           2 : static RPCHelpMan sendmsgtopeer()
     970             : {
     971           2 :     return RPCHelpMan{
     972           2 :         "sendmsgtopeer",
     973           2 :         "Send a p2p message to a peer specified by id.\n"
     974             :         "The message type and body must be provided, the message header will be generated.\n"
     975             :         "This RPC is for testing only.",
     976           8 :         {
     977           2 :             {"peer_id", RPCArg::Type::NUM, RPCArg::Optional::NO, "The peer to send the message to."},
     978           2 :             {"msg_type", RPCArg::Type::STR, RPCArg::Optional::NO, strprintf("The message type (maximum length %i)", CMessageHeader::COMMAND_SIZE)},
     979           2 :             {"msg", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The serialized message body to send, in hex, without a message header"},
     980             :         },
     981           2 :         RPCResult{RPCResult::Type::OBJ, "", "", std::vector<RPCResult>{}},
     982           2 :         RPCExamples{
     983           2 :             HelpExampleCli("sendmsgtopeer", "0 \"addr\" \"ffffff\"") + HelpExampleRpc("sendmsgtopeer", "0 \"addr\" \"ffffff\"")},
     984           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
     985           0 :             const NodeId peer_id{request.params[0].getInt<int64_t>()};
     986           0 :             const std::string& msg_type{request.params[1].get_str()};
     987           0 :             if (msg_type.size() > CMessageHeader::COMMAND_SIZE) {
     988           0 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Error: msg_type too long, max length is %i", CMessageHeader::COMMAND_SIZE));
     989             :             }
     990           0 :             auto msg{TryParseHex<unsigned char>(request.params[2].get_str())};
     991           0 :             if (!msg.has_value()) {
     992           0 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, "Error parsing input for msg");
     993             :             }
     994             : 
     995           0 :             NodeContext& node = EnsureAnyNodeContext(request.context);
     996           0 :             CConnman& connman = EnsureConnman(node);
     997             : 
     998           0 :             CSerializedNetMsg msg_ser;
     999           0 :             msg_ser.data = msg.value();
    1000           0 :             msg_ser.m_type = msg_type;
    1001             : 
    1002           0 :             bool success = connman.ForNode(peer_id, [&](CNode* node) {
    1003           0 :                 connman.PushMessage(node, std::move(msg_ser));
    1004           0 :                 return true;
    1005             :             });
    1006             : 
    1007           0 :             if (!success) {
    1008           0 :                 throw JSONRPCError(RPC_MISC_ERROR, "Error: Could not send message to peer");
    1009             :             }
    1010             : 
    1011           0 :             UniValue ret{UniValue::VOBJ};
    1012           0 :             return ret;
    1013           0 :         },
    1014             :     };
    1015           0 : }
    1016             : 
    1017           2 : static RPCHelpMan getaddrmaninfo()
    1018             : {
    1019           4 :     return RPCHelpMan{"getaddrmaninfo",
    1020           2 :                       "\nProvides information about the node's address manager by returning the number of "
    1021             :                       "addresses in the `new` and `tried` tables and their sum for all networks.\n"
    1022             :                       "This RPC is for testing only.\n",
    1023           2 :                       {},
    1024           2 :                       RPCResult{
    1025           2 :                               RPCResult::Type::OBJ_DYN, "", "json object with network type as keys",
    1026           4 :                               {
    1027           4 :                                       {RPCResult::Type::OBJ, "network", "the network (" + Join(GetNetworkNames(), ", ") + ")",
    1028           8 :                                        {
    1029           2 :                                                {RPCResult::Type::NUM, "new", "number of addresses in the new table, which represent potential peers the node has discovered but hasn't yet successfully connected to."},
    1030           2 :                                                {RPCResult::Type::NUM, "tried", "number of addresses in the tried table, which represent peers the node has successfully connected to in the past."},
    1031           2 :                                                {RPCResult::Type::NUM, "total", "total number of addresses in both new/tried tables"},
    1032             :                                        }},
    1033             :                               }
    1034             :                       },
    1035           2 :                       RPCExamples{
    1036           2 :                               HelpExampleCli("getaddrmaninfo", "")
    1037           2 :                               + HelpExampleRpc("getaddrmaninfo", "")
    1038             :                       },
    1039           2 :                       [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1040             :                       {
    1041           0 :                           NodeContext& node = EnsureAnyNodeContext(request.context);
    1042           0 :                           if (!node.addrman) {
    1043           0 :                               throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Address manager functionality missing or disabled");
    1044             :                           }
    1045             : 
    1046           0 :                           UniValue ret(UniValue::VOBJ);
    1047           0 :                           for (int n = 0; n < NET_MAX; ++n) {
    1048           0 :                               enum Network network = static_cast<enum Network>(n);
    1049           0 :                               if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
    1050           0 :                               UniValue obj(UniValue::VOBJ);
    1051           0 :                               obj.pushKV("new", node.addrman->Size(network, true));
    1052           0 :                               obj.pushKV("tried", node.addrman->Size(network, false));
    1053           0 :                               obj.pushKV("total", node.addrman->Size(network));
    1054           0 :                               ret.pushKV(GetNetworkName(network), obj);
    1055           0 :                           }
    1056           0 :                           UniValue obj(UniValue::VOBJ);
    1057           0 :                           obj.pushKV("new", node.addrman->Size(std::nullopt, true));
    1058           0 :                           obj.pushKV("tried", node.addrman->Size(std::nullopt, false));
    1059           0 :                           obj.pushKV("total", node.addrman->Size());
    1060           0 :                           ret.pushKV("all_networks", obj);
    1061           0 :                           return ret;
    1062           0 :                       },
    1063             :     };
    1064           0 : }
    1065             : 
    1066           1 : void RegisterNetRPCCommands(CRPCTable& t)
    1067             : {
    1068          18 :     static const CRPCCommand commands[]{
    1069           1 :         {"network", &getconnectioncount},
    1070           1 :         {"network", &ping},
    1071           1 :         {"network", &getpeerinfo},
    1072           1 :         {"network", &addnode},
    1073           1 :         {"network", &disconnectnode},
    1074           1 :         {"network", &getaddednodeinfo},
    1075           1 :         {"network", &getnettotals},
    1076           1 :         {"network", &getnetworkinfo},
    1077           1 :         {"network", &setban},
    1078           1 :         {"network", &listbanned},
    1079           1 :         {"network", &clearbanned},
    1080           1 :         {"network", &setnetworkactive},
    1081           1 :         {"network", &getnodeaddresses},
    1082           1 :         {"hidden", &addconnection},
    1083           1 :         {"hidden", &addpeeraddress},
    1084           1 :         {"hidden", &sendmsgtopeer},
    1085           1 :         {"hidden", &getaddrmaninfo},
    1086             :     };
    1087          18 :     for (const auto& c : commands) {
    1088          17 :         t.appendCommand(c.name, &c);
    1089             :     }
    1090           1 : }

Generated by: LCOV version 1.14