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::ARR,
"permissions",
"Any special permissions that have been granted to this peer",
148 {
RPCResult::Type::NUM,
"minfeefilter",
"The minimum fee rate for transactions this peer accepts"},
152 "When a message type is not listed in this json object, the bytes sent are 0.\n"
153 "Only known message types can appear as keys in the object."}
158 "When a message type is not listed in this json object, the bytes received are 0.\n"
159 "Only known message types can appear as keys in the object and all bytes received\n"
175 std::vector<CNodeStats> vstats;
176 node.
connman->GetNodeStats(vstats);
184 obj.
pushKV(
"id", stats.nodeid);
185 obj.
pushKV(
"addr", stats.addrName);
186 if (stats.addrBind.IsValid()) {
187 obj.
pushKV(
"addrbind", stats.addrBind.ToString());
189 if (!(stats.addrLocal.empty())) {
190 obj.
pushKV(
"addrlocal", stats.addrLocal);
192 obj.
pushKV(
"network", stats.m_network);
193 if (stats.m_mapped_as != 0) {
194 obj.
pushKV(
"mapped_as", uint64_t(stats.m_mapped_as));
198 obj.
pushKV(
"relaytxes", stats.fRelayTxes);
199 obj.
pushKV(
"lastsend", stats.nLastSend);
200 obj.
pushKV(
"lastrecv", stats.nLastRecv);
201 obj.
pushKV(
"last_transaction", stats.nLastTXTime);
202 obj.
pushKV(
"last_block", stats.nLastBlockTime);
203 obj.
pushKV(
"bytessent", stats.nSendBytes);
204 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
205 obj.
pushKV(
"conntime", stats.nTimeConnected);
206 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
207 if (stats.m_ping_usec > 0) {
208 obj.
pushKV(
"pingtime", ((
double)stats.m_ping_usec) / 1e6);
210 if (stats.m_min_ping_usec < std::numeric_limits<int64_t>::max()) {
211 obj.
pushKV(
"minping", ((
double)stats.m_min_ping_usec) / 1e6);
213 if (stats.m_ping_wait_usec > 0) {
214 obj.
pushKV(
"pingwait", ((
double)stats.m_ping_wait_usec) / 1e6);
216 obj.
pushKV(
"version", stats.nVersion);
220 obj.
pushKV(
"subver", stats.cleanSubVer);
221 obj.
pushKV(
"inbound", stats.fInbound);
224 obj.
pushKV(
"addnode", stats.m_manual_connection);
226 obj.
pushKV(
"startingheight", stats.nStartingHeight);
238 obj.
pushKV(
"inflight", heights);
242 obj.
pushKV(
"whitelisted", stats.m_legacyWhitelisted);
248 obj.
pushKV(
"permissions", permissions);
252 for (
const auto& i : stats.mapSendBytesPerMsgCmd) {
254 sendPerMsgCmd.
pushKV(i.first, i.second);
256 obj.
pushKV(
"bytessent_per_msg", sendPerMsgCmd);
259 for (
const auto& i : stats.mapRecvBytesPerMsgCmd) {
261 recvPerMsgCmd.
pushKV(i.first, i.second);
263 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgCmd);
264 obj.
pushKV(
"connection_type", stats.m_conn_type_string);
277 "\nAttempts to add or remove a node from the addnode list.\n"
278 "Or try a connection to a node once.\n"
279 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n"
280 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n",
292 std::string strCommand;
293 if (!request.params[1].isNull())
294 strCommand = request.params[1].
get_str();
295 if (request.fHelp || request.params.size() != 2 ||
296 (strCommand !=
"onetry" && strCommand !=
"add" && strCommand !=
"remove"))
297 throw std::runtime_error(
304 std::string strNode = request.params[0].get_str();
306 if (strCommand ==
"onetry")
313 if (strCommand ==
"add")
315 if(!node.
connman->AddNode(strNode))
318 else if(strCommand ==
"remove")
320 if(!node.
connman->RemoveAddedNode(strNode))
332 "\nImmediately disconnects from the specified peer node.\n"
333 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
334 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
336 {
"address",
RPCArg::Type::STR,
"fallback to nodeid",
"The IP address/port of the node"},
337 {
"nodeid",
RPCArg::Type::NUM,
"fallback to address",
"The node ID (see getpeerinfo for node IDs)"},
353 const UniValue &address_arg = request.params[0];
354 const UniValue &id_arg = request.params[1];
362 success = node.
connman->DisconnectNode(nodeid);
379 "\nReturns information about the given added node, or all added nodes\n"
380 "(note that onetry addnodes are not listed here)\n",
382 {
"node",
RPCArg::Type::STR,
"all nodes",
"If provided, return information about this specific node, otherwise all nodes are returned."},
412 std::vector<AddedNodeInfo> vInfo = node.
connman->GetAddedNodeInfo();
414 if (!request.params[0].isNull()) {
417 if (info.strAddedNode == request.params[0].get_str()) {
418 vInfo.assign(1, info);
432 obj.
pushKV(
"addednode", info.strAddedNode);
433 obj.
pushKV(
"connected", info.fConnected);
435 if (info.fConnected) {
437 address.
pushKV(
"address", info.resolvedAddress.ToString());
438 address.
pushKV(
"connected", info.fInbound ?
"inbound" :
"outbound");
441 obj.
pushKV(
"addresses", addresses);
453 "\nReturns information about network traffic, including bytes in, bytes out,\n"
454 "and current time.\n",
484 obj.
pushKV(
"totalbytesrecv", node.
connman->GetTotalBytesRecv());
485 obj.
pushKV(
"totalbytessent", node.
connman->GetTotalBytesSent());
489 outboundLimit.
pushKV(
"timeframe", node.
connman->GetMaxOutboundTimeframe());
490 outboundLimit.
pushKV(
"target", node.
connman->GetMaxOutboundTarget());
491 outboundLimit.
pushKV(
"target_reached", node.
connman->OutboundTargetReached(
false));
492 outboundLimit.
pushKV(
"serve_historical_blocks", !node.
connman->OutboundTargetReached(
true));
493 outboundLimit.
pushKV(
"bytes_left_in_cycle", node.
connman->GetOutboundTargetBytesLeft());
494 outboundLimit.
pushKV(
"time_left_in_cycle", node.
connman->GetMaxOutboundTimeLeftInCycle());
495 obj.
pushKV(
"uploadtarget", outboundLimit);
504 for (
int n = 0; n <
NET_MAX; ++n) {
523 "Returns an object containing various state info regarding P2P networking.\n",
532 {
RPCResult::Type::ARR,
"localservicesnames",
"the services we offer to the network, in human-readable form",
549 {
RPCResult::Type::STR,
"proxy",
"(\"host:port\") the proxy that is used for this network, or empty if none"},
587 obj.
pushKV(
"networkactive", node.
connman->GetNetworkActive());
598 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
601 rec.
pushKV(
"address", item.first.ToString());
602 rec.
pushKV(
"port", item.second.nPort);
603 rec.
pushKV(
"score", item.second.nScore);
607 obj.
pushKV(
"localaddresses", localAddresses);
617 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
621 {
"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)"},
632 std::string strCommand;
633 if (!request.params[1].isNull())
634 strCommand = request.params[1].
get_str();
635 if (request.fHelp || !help.
IsValidNumArgs(request.params.size()) || (strCommand !=
"add" && strCommand !=
"remove")) {
636 throw std::runtime_error(help.
ToString());
645 bool isSubnet =
false;
647 if (request.params[0].get_str().find(
'/') != std::string::npos)
652 LookupHost(request.params[0].get_str(), resolved,
false);
661 if (strCommand ==
"add")
663 if (isSubnet ? node.
banman->IsBanned(subNet) : node.
banman->IsBanned(netAddr)) {
668 if (!request.params[2].isNull())
669 banTime = request.params[2].get_int64();
671 bool absolute =
false;
672 if (request.params[3].isTrue())
676 node.
banman->Ban(subNet, banTime, absolute);
678 node.
connman->DisconnectNode(subNet);
681 node.
banman->Ban(netAddr, banTime, absolute);
683 node.
connman->DisconnectNode(netAddr);
687 else if(strCommand ==
"remove")
689 if (!( isSubnet ? node.
banman->Unban(subNet) : node.
banman->Unban(netAddr) )) {
701 "\nList all manually banned IPs/Subnets.\n",
724 node.
banman->GetBanned(banMap);
727 for (
const auto& entry : banMap)
729 const CBanEntry& banEntry = entry.second;
731 rec.
pushKV(
"address", entry.first.ToString());
738 return bannedAddresses;
746 "\nClear all banned IPs.\n",
760 node.
banman->ClearBanned();
770 "\nDisable/enable all p2p network activity.\n",
783 node.
connman->SetNetworkActive(request.params[0].get_bool());
785 return node.
connman->GetNetworkActive();
793 "\nReturn known addresses which can potentially be used to find new nodes in the network\n",
795 {
"count",
RPCArg::Type::NUM,
"1",
"The maximum number of addresses to return. Specify 0 to return all known addresses."},
821 if (!request.params[0].isNull()) {
822 count = request.params[0].get_int();
828 std::vector<CAddress> vAddr = node.
connman->GetAddresses(count, 0);
831 for (
const CAddress& addr : vAddr) {
833 obj.
pushKV(
"time", (
int)addr.nTime);
834 obj.
pushKV(
"services", (uint64_t)addr.nServices);
835 obj.
pushKV(
"address", addr.ToStringIP());
836 obj.
pushKV(
"port", addr.GetPort());
847 "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
855 {
RPCResult::Type::BOOL,
"success",
"whether the peer address was successfully added to the address manager"},
871 std::string addr_string = request.params[0].get_str();
872 uint16_t port = request.params[1].get_int();
875 if (!
LookupHost(addr_string, net_addr,
false)) {
876 obj.
pushKV(
"success",
false);
883 if (!node.
connman->AddNewAddresses({address}, address)) {
884 obj.
pushKV(
"success",
false);
888 obj.
pushKV(
"success",
true);
901 {
"network",
"ping", &
ping, {} },
903 {
"network",
"addnode", &
addnode, {
"node",
"command"} },
904 {
"network",
"disconnectnode", &
disconnectnode, {
"address",
"nodeid"} },
908 {
"network",
"setban", &
setban, {
"subnet",
"command",
"bantime",
"absolute"} },
913 {
"hidden",
"addpeeraddress", &
addpeeraddress, {
"address",
"port"} },
916 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.
const std::vector< std::string > NET_PERMISSIONS_DOC
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.