LCOV - code coverage report
Current view: top level - src/rpc - net.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 810 858 94.4 %
Date: 2026-06-25 07:23:43 Functions: 44 45 97.8 %

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

Generated by: LCOV version 1.16