26 #include <validation.h>
33 "outbound-full-relay (default automatic connections)",
34 "block-relay-only (does not relay transactions or addresses)",
35 "inbound (initiated by the peer)",
36 "manual (added via addnode RPC or -addnode/-connect configuration options)",
37 "addr-fetch (short-lived automatic connection for soliciting addresses)",
38 "feeler (short-lived automatic connection for testing addresses)"
44 "\nReturns the number of connections to other nodes.\n",
67 "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
68 "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
69 "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n",
94 "\nReturns data about each connected network node as a json array of objects.\n",
107 {
RPCResult::Type::NUM,
"mapped_as",
"The AS in the BGP route to the peer used for diversifying\n"
108 "peer selection (only available if the asmap config flag is set)"},
129 {
RPCResult::Type::BOOL,
"addnode",
"Whether connection was due to addnode/-connect or if it was an automatic/inbound connection\n"
130 "(DEPRECATED, returned only if the config option -deprecatedrpc=getpeerinfo_addnode is passed)"},
132 "Please note this output is unlikely to be stable in upcoming releases as we iterate to\n"
133 "best capture connection behaviors."},
135 {
RPCResult::Type::NUM,
"banscore",
"The ban score (DEPRECATED, returned only if config option -deprecatedrpc=banscore is passed)"},
142 {
RPCResult::Type::BOOL,
"whitelisted",
true,
"Whether the peer is whitelisted with default permissions\n"
143 "(DEPRECATED, returned only if config option -deprecatedrpc=whitelisted is passed)"},
144 {
RPCResult::Type::NUM,
"minfeefilter",
"The minimum fee rate for transactions this peer accepts"},
148 "When a message type is not listed in this json object, the bytes sent are 0.\n"
149 "Only known message types can appear as keys in the object."}
154 "When a message type is not listed in this json object, the bytes received are 0.\n"
155 "Only known message types can appear as keys in the object and all bytes received\n"
171 std::vector<CNodeStats> vstats;
172 node.
connman->GetNodeStats(vstats);
180 obj.
pushKV(
"id", stats.nodeid);
181 obj.
pushKV(
"addr", stats.addrName);
182 if (stats.addrBind.IsValid()) {
183 obj.
pushKV(
"addrbind", stats.addrBind.ToString());
185 if (!(stats.addrLocal.empty())) {
186 obj.
pushKV(
"addrlocal", stats.addrLocal);
188 obj.
pushKV(
"network", stats.m_network);
189 if (stats.m_mapped_as != 0) {
190 obj.
pushKV(
"mapped_as", uint64_t(stats.m_mapped_as));
194 obj.
pushKV(
"relaytxes", stats.fRelayTxes);
195 obj.
pushKV(
"lastsend", stats.nLastSend);
196 obj.
pushKV(
"lastrecv", stats.nLastRecv);
197 obj.
pushKV(
"last_transaction", stats.nLastTXTime);
198 obj.
pushKV(
"last_block", stats.nLastBlockTime);
199 obj.
pushKV(
"bytessent", stats.nSendBytes);
200 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
201 obj.
pushKV(
"conntime", stats.nTimeConnected);
202 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
203 if (stats.m_ping_usec > 0) {
204 obj.
pushKV(
"pingtime", ((
double)stats.m_ping_usec) / 1e6);
206 if (stats.m_min_ping_usec < std::numeric_limits<int64_t>::max()) {
207 obj.
pushKV(
"minping", ((
double)stats.m_min_ping_usec) / 1e6);
209 if (stats.m_ping_wait_usec > 0) {
210 obj.
pushKV(
"pingwait", ((
double)stats.m_ping_wait_usec) / 1e6);
212 obj.
pushKV(
"version", stats.nVersion);
216 obj.
pushKV(
"subver", stats.cleanSubVer);
217 obj.
pushKV(
"inbound", stats.fInbound);
220 obj.
pushKV(
"addnode", stats.m_manual_connection);
222 obj.
pushKV(
"startingheight", stats.nStartingHeight);
234 obj.
pushKV(
"inflight", heights);
238 obj.
pushKV(
"whitelisted", stats.m_legacyWhitelisted);
244 obj.
pushKV(
"permissions", permissions);
248 for (
const auto& i : stats.mapSendBytesPerMsgCmd) {
250 sendPerMsgCmd.
pushKV(i.first, i.second);
252 obj.
pushKV(
"bytessent_per_msg", sendPerMsgCmd);
255 for (
const auto& i : stats.mapRecvBytesPerMsgCmd) {
257 recvPerMsgCmd.
pushKV(i.first, i.second);
259 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgCmd);
260 obj.
pushKV(
"connection_type", stats.m_conn_type_string);
273 "\nAttempts to add or remove a node from the addnode list.\n"
274 "Or try a connection to a node once.\n"
275 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n"
276 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n",
288 std::string strCommand;
289 if (!request.params[1].isNull())
290 strCommand = request.params[1].
get_str();
291 if (request.fHelp || request.params.size() != 2 ||
292 (strCommand !=
"onetry" && strCommand !=
"add" && strCommand !=
"remove"))
293 throw std::runtime_error(
300 std::string strNode = request.params[0].get_str();
302 if (strCommand ==
"onetry")
309 if (strCommand ==
"add")
311 if(!node.
connman->AddNode(strNode))
314 else if(strCommand ==
"remove")
316 if(!node.
connman->RemoveAddedNode(strNode))
328 "\nImmediately disconnects from the specified peer node.\n"
329 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
330 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
332 {
"address",
RPCArg::Type::STR,
"fallback to nodeid",
"The IP address/port of the node"},
333 {
"nodeid",
RPCArg::Type::NUM,
"fallback to address",
"The node ID (see getpeerinfo for node IDs)"},
349 const UniValue &address_arg = request.params[0];
350 const UniValue &id_arg = request.params[1];
358 success = node.
connman->DisconnectNode(nodeid);
375 "\nReturns information about the given added node, or all added nodes\n"
376 "(note that onetry addnodes are not listed here)\n",
378 {
"node",
RPCArg::Type::STR,
"all nodes",
"If provided, return information about this specific node, otherwise all nodes are returned."},
408 std::vector<AddedNodeInfo> vInfo = node.
connman->GetAddedNodeInfo();
410 if (!request.params[0].isNull()) {
413 if (info.strAddedNode == request.params[0].get_str()) {
414 vInfo.assign(1, info);
428 obj.
pushKV(
"addednode", info.strAddedNode);
429 obj.
pushKV(
"connected", info.fConnected);
431 if (info.fConnected) {
433 address.
pushKV(
"address", info.resolvedAddress.ToString());
434 address.
pushKV(
"connected", info.fInbound ?
"inbound" :
"outbound");
437 obj.
pushKV(
"addresses", addresses);
449 "\nReturns information about network traffic, including bytes in, bytes out,\n"
450 "and current time.\n",
480 obj.
pushKV(
"totalbytesrecv", node.
connman->GetTotalBytesRecv());
481 obj.
pushKV(
"totalbytessent", node.
connman->GetTotalBytesSent());
485 outboundLimit.
pushKV(
"timeframe", node.
connman->GetMaxOutboundTimeframe());
486 outboundLimit.
pushKV(
"target", node.
connman->GetMaxOutboundTarget());
487 outboundLimit.
pushKV(
"target_reached", node.
connman->OutboundTargetReached(
false));
488 outboundLimit.
pushKV(
"serve_historical_blocks", !node.
connman->OutboundTargetReached(
true));
489 outboundLimit.
pushKV(
"bytes_left_in_cycle", node.
connman->GetOutboundTargetBytesLeft());
490 outboundLimit.
pushKV(
"time_left_in_cycle", node.
connman->GetMaxOutboundTimeLeftInCycle());
491 obj.
pushKV(
"uploadtarget", outboundLimit);
500 for (
int n = 0; n <
NET_MAX; ++n) {
519 "Returns an object containing various state info regarding P2P networking.\n",
528 {
RPCResult::Type::ARR,
"localservicesnames",
"the services we offer to the network, in human-readable form",
545 {
RPCResult::Type::STR,
"proxy",
"(\"host:port\") the proxy that is used for this network, or empty if none"},
583 obj.
pushKV(
"networkactive", node.
connman->GetNetworkActive());
594 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
597 rec.
pushKV(
"address", item.first.ToString());
598 rec.
pushKV(
"port", item.second.nPort);
599 rec.
pushKV(
"score", item.second.nScore);
603 obj.
pushKV(
"localaddresses", localAddresses);
613 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
617 {
"bantime",
RPCArg::Type::NUM,
"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)"},
628 std::string strCommand;
629 if (!request.params[1].isNull())
630 strCommand = request.params[1].
get_str();
631 if (request.fHelp || !help.
IsValidNumArgs(request.params.size()) || (strCommand !=
"add" && strCommand !=
"remove")) {
632 throw std::runtime_error(help.
ToString());
641 bool isSubnet =
false;
643 if (request.params[0].get_str().find(
'/') != std::string::npos)
648 LookupHost(request.params[0].get_str(), resolved,
false);
657 if (strCommand ==
"add")
659 if (isSubnet ? node.
banman->IsBanned(subNet) : node.
banman->IsBanned(netAddr)) {
664 if (!request.params[2].isNull())
665 banTime = request.params[2].get_int64();
667 bool absolute =
false;
668 if (request.params[3].isTrue())
672 node.
banman->Ban(subNet, banTime, absolute);
674 node.
connman->DisconnectNode(subNet);
677 node.
banman->Ban(netAddr, banTime, absolute);
679 node.
connman->DisconnectNode(netAddr);
683 else if(strCommand ==
"remove")
685 if (!( isSubnet ? node.
banman->Unban(subNet) : node.
banman->Unban(netAddr) )) {
697 "\nList all manually banned IPs/Subnets.\n",
720 node.
banman->GetBanned(banMap);
723 for (
const auto& entry : banMap)
725 const CBanEntry& banEntry = entry.second;
727 rec.
pushKV(
"address", entry.first.ToString());
734 return bannedAddresses;
742 "\nClear all banned IPs.\n",
756 node.
banman->ClearBanned();
766 "\nDisable/enable all p2p network activity.\n",
779 node.
connman->SetNetworkActive(request.params[0].get_bool());
781 return node.
connman->GetNetworkActive();
789 "\nReturn known addresses which can potentially be used to find new nodes in the network\n",
791 {
"count",
RPCArg::Type::NUM,
"1",
"The maximum number of addresses to return. Specify 0 to return all known addresses."},
817 if (!request.params[0].isNull()) {
818 count = request.params[0].get_int();
824 std::vector<CAddress> vAddr = node.
connman->GetAddresses(count, 0);
827 for (
const CAddress& addr : vAddr) {
829 obj.
pushKV(
"time", (
int)addr.nTime);
830 obj.
pushKV(
"services", (uint64_t)addr.nServices);
831 obj.
pushKV(
"address", addr.ToStringIP());
832 obj.
pushKV(
"port", addr.GetPort());
843 "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
851 {
RPCResult::Type::BOOL,
"success",
"whether the peer address was successfully added to the address manager"},
867 std::string addr_string = request.params[0].get_str();
868 uint16_t port = request.params[1].get_int();
871 if (!
LookupHost(addr_string, net_addr,
false)) {
872 obj.
pushKV(
"success",
false);
879 if (!node.
connman->AddNewAddresses({address}, address)) {
880 obj.
pushKV(
"success",
false);
884 obj.
pushKV(
"success",
true);
897 {
"network",
"ping", &
ping, {} },
899 {
"network",
"addnode", &
addnode, {
"node",
"command"} },
900 {
"network",
"disconnectnode", &
disconnectnode, {
"address",
"nodeid"} },
904 {
"network",
"setban", &
setban, {
"subnet",
"command",
"bantime",
"absolute"} },
909 {
"hidden",
"addpeeraddress", &
addpeeraddress, {
"address",
"port"} },
912 for (
const auto& c : commands) {
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
const std::string & get_str() const
bool IsReachable(enum Network net)
Node has not been added before.
ServiceFlags
nServices flags
static RPCHelpMan clearbanned()
A set of addresses that represent the hash of a string or FQDN.
We open manual connections to addresses that users explicitly inputted via the addnode RPC...
Dummy value to indicate the number of NET_* constants.
const std::string NET_MESSAGE_COMMAND_OTHER
int64_t GetTimeMillis()
Returns the system time (not mockable)
std::unique_ptr< BanMan > banman
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
void RegisterNetRPCCommands(CRPCTable &t)
Register P2P networking RPC commands.
std::string ToStringIPPort() const
UniValue ValueFromAmount(const CAmount &amount)
static UniValue GetNetworksInfo()
static RPCHelpMan addpeeraddress()
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are: ...
static RPCHelpMan getnettotals()
Invalid, missing or duplicate parameter.
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret)
Parse and resolve a specified subnet string into the appropriate internal representation.
static RPCHelpMan getpeerinfo()
std::string ToString(const T &t)
Locale-independent version of std::to_string.
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
int64_t get_int64() const
UniValue JSONRPCError(int code, const std::string &message)
bool push_back(const UniValue &val)
static RPCHelpMan getnodeaddresses()
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
std::unique_ptr< CConnman > connman
bool randomize_credentials
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
static RPCHelpMan disconnectnode()
A CService with information about it as peer.
const std::string CURRENCY_UNIT
static RPCHelpMan setban()
static RPCHelpMan addnode()
RecursiveMutex cs_mapLocalHost
bool pushKV(const std::string &key, const UniValue &val)
bool IsDeprecatedRPCEnabled(const std::string &method)
Special numeric to denote unix epoch time.
static RPCHelpMan setnetworkactive()
CFeeRate incrementalRelayFee
NodeContext & EnsureNodeContext(const util::Ref &context)
const std::vector< std::string > CONNECTION_TYPE_DOC
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Resolve a host string to its corresponding network addresses.
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
std::atomic< bool > fPingQueued
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
static const int PROTOCOL_VERSION
network protocol versioning
int64_t GetAdjustedTime()
static RPCHelpMan getnetworkinfo()
Node to disconnect not found in connected nodes.
const UniValue NullUniValue
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
static RPCHelpMan getaddednodeinfo()
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
static RPCHelpMan getconnectioncount()
std::map< CSubNet, CBanEntry > banmap_t
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
std::string ToString() const
No valid connection manager instance found.
static RPCHelpMan listbanned()
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
std::string GetNetworkName(enum Network net)
Information about a peer.
std::vector< int > vHeightInFlight
Special dictionary with keys that are not literals.
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
Addresses from these networks are not publicly routable on the global Internet.