28 #include <validation.h>
41 "Returns the number of connections to other nodes.\n",
59 "Requests that a ping be sent to all other nodes, to measure ping "
61 "Results provided in getpeerinfo, pingtime and pingwait fields are "
63 "Ping command is handled in queue with all other commands, so it "
64 "measures processing backlog, not just network ping.\n",
84 "Returns data about each connected network node as a json array of "
98 "(host:port) The IP address and port of the peer"},
100 "(ip:port) Bind address of the connection to the peer"},
102 "(ip:port) Local address as reported by the peer"},
104 "The total number of addresses processed, excluding those "
105 "dropped due to rate limiting"},
107 "The total number of addresses dropped due to rate "
115 "The AS in the BGP route to the peer used for "
117 "peer selection (only available if the asmap config flag "
120 "The services offered"},
123 "the services offered, in human-readable form",
125 "the service name if it is recognised"}}},
127 "Whether peer has asked us to relay transactions to it"},
134 " of the last valid transaction received from this "
138 " of the last block received from this peer"},
141 "The total bytes received"},
145 "The time offset in seconds"},
147 "ping time (if available)"},
149 "minimum observed ping time (if any at all)"},
151 "ping wait (if non-zero)"},
153 "The peer version, such as 70001"},
156 "Inbound (true) or Outbound (false)"},
158 "Whether we selected peer as (compact blocks) "
159 "high-bandwidth peer"},
161 "Whether peer selected us as (compact blocks) "
162 "high-bandwidth peer"},
164 "Type of connection: \n" +
167 "The starting height (block) of the peer"},
170 "The current height of header pre-synchronization with "
171 "this peer, or -1 if no low-work sync is in progress"},
173 "The last header we have in common with this peer"},
175 "The last block we have in common with this peer"},
181 "The heights of blocks we're currently asking from "
185 "Whether we participate in address relay with this peer"},
187 "The minimum fee rate for transactions this peer accepts"},
192 "The total bytes sent aggregated by message type\n"
193 "When a message type is not listed in this json object, "
194 "the bytes sent are 0.\n"
195 "Only known message types can appear as keys in the "
201 "The total bytes received aggregated by message type\n"
202 "When a message type is not listed in this json object, "
203 "the bytes received are 0.\n"
204 "Only known message types can appear as keys in the "
205 "object and all bytes received\n"
206 "of unknown message types are listed under '" +
209 "Avalanche availability score of this node (if any)"},
221 std::vector<CNodeStats> vstats;
231 obj.
pushKV(
"id", stats.nodeid);
232 obj.
pushKV(
"addr", stats.m_addr_name);
233 if (stats.addrBind.IsValid()) {
234 obj.
pushKV(
"addrbind", stats.addrBind.ToString());
236 if (!(stats.addrLocal.empty())) {
237 obj.
pushKV(
"addrlocal", stats.addrLocal);
240 if (stats.m_mapped_as != 0) {
241 obj.
pushKV(
"mapped_as", uint64_t(stats.m_mapped_as));
249 obj.
pushKV(
"last_transaction",
257 obj.
pushKV(
"bytessent", stats.nSendBytes);
258 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
260 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
261 if (stats.m_last_ping_time > 0us) {
265 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
273 obj.
pushKV(
"version", stats.nVersion);
277 obj.
pushKV(
"subver", stats.cleanSubVer);
278 obj.
pushKV(
"inbound", stats.fInbound);
279 obj.
pushKV(
"bip152_hb_to", stats.m_bip152_highbandwidth_to);
280 obj.
pushKV(
"bip152_hb_from", stats.m_bip152_highbandwidth_from);
290 obj.
pushKV(
"inflight", heights);
292 obj.
pushKV(
"minfeefilter",
294 obj.
pushKV(
"addr_relay_enabled",
297 obj.
pushKV(
"addr_rate_limited",
301 for (
const auto &permission :
305 obj.
pushKV(
"permissions", permissions);
308 for (
const auto &i : stats.mapSendBytesPerMsgCmd) {
310 sendPerMsgCmd.
pushKV(i.first, i.second);
313 obj.
pushKV(
"bytessent_per_msg", sendPerMsgCmd);
316 for (
const auto &i : stats.mapRecvBytesPerMsgCmd) {
318 recvPerMsgCmd.
pushKV(i.first, i.second);
321 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgCmd);
322 obj.
pushKV(
"connection_type",
325 if (stats.m_availabilityScore) {
326 obj.
pushKV(
"availability_score",
327 *stats.m_availabilityScore);
341 "Attempts to add or remove a node from the addnode list.\n"
342 "Or try a connection to a node once.\n"
343 "Nodes added using addnode (or -connect) are protected from "
344 "DoS disconnection and are not required to be\n"
345 "full nodes as other outbound peers are (though such peers "
346 "will not be synced from).\n",
349 "The node (see getpeerinfo for nodes)"},
351 "'add' to add a node to the list, 'remove' to remove a "
352 "node from the list, 'onetry' to try a connection to the "
361 std::string strCommand;
362 if (!request.params[1].isNull()) {
363 strCommand = request.params[1].
get_str();
366 if (strCommand !=
"onetry" && strCommand !=
"add" &&
367 strCommand !=
"remove") {
368 throw std::runtime_error(
self.
ToString());
374 std::string strNode = request.params[0].get_str();
376 if (strCommand ==
"onetry") {
384 if ((strCommand ==
"add") && (!connman.
AddNode(strNode))) {
386 "Error: Node already added");
387 }
else if ((strCommand ==
"remove") &&
391 "Error: Node could not be removed. It has not been "
392 "added previously.");
403 "\nOpen an outbound connection to a specified node. This RPC is for "
407 "The IP address and port to attempt connecting to."},
409 "Type of connection to open (\"outbound-full-relay\", "
410 "\"block-relay-only\", \"addr-fetch\", \"feeler\" or "
418 "Address of newly added connection."},
420 "Type of connection opened."},
424 "\"192.168.0.6:8333\" \"outbound-full-relay\"") +
426 "\"192.168.0.6:8333\" \"outbound-full-relay\"")},
429 if (config.GetChainParams().NetworkIDString() !=
431 throw std::runtime_error(
"addconnection is for regression "
432 "testing (-regtest mode) only.");
438 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});
439 const std::string address = request.params[0].get_str();
440 const std::string conn_type_in{
443 if (conn_type_in ==
"outbound-full-relay") {
445 }
else if (conn_type_in ==
"block-relay-only") {
447 }
else if (conn_type_in ==
"addr-fetch") {
449 }
else if (conn_type_in ==
"feeler") {
451 }
else if (conn_type_in ==
"avalanche") {
454 "Error: avalanche outbound requested "
455 "but avalanche is not enabled.");
464 const bool success = connman.
AddConnection(address, conn_type);
467 "Error: Already at capacity for specified "
472 info.
pushKV(
"address", address);
473 info.
pushKV(
"connection_type", conn_type_in);
483 "Immediately disconnects from the specified peer node.\n"
484 "\nStrictly one out of 'address' and 'nodeid' can be provided to "
485 "identify the node.\n"
486 "\nTo disconnect by nodeid, either set 'address' to the empty string, "
487 "or call using the named 'nodeid' argument only.\n",
491 "The IP address/port of the node"},
494 "The node ID (see getpeerinfo for node IDs)"},
507 const UniValue &address_arg = request.params[0];
508 const UniValue &id_arg = request.params[1];
514 (address_arg.
isStr() &&
515 address_arg.
get_str().empty()))) {
522 "Only one of address and nodeid should be provided.");
527 "Node not found in connected nodes");
538 "Returns information about the given added node, or all added nodes\n"
539 "(note that onetry addnodes are not listed here)\n",
542 "If provided, return information about this specific node, "
543 "otherwise all nodes are returned."},
555 "The node IP address or name (as provided to addnode)"},
559 "Only when connected = true",
566 "The bitcoin server IP and port we're "
569 "connection, inbound or outbound"},
583 if (!request.params[0].isNull()) {
586 if (info.strAddedNode == request.params[0].get_str()) {
587 vInfo.assign(1, info);
594 "Error: Node has not been added.");
602 obj.
pushKV(
"addednode", info.strAddedNode);
603 obj.
pushKV(
"connected", info.fConnected);
605 if (info.fConnected) {
607 address.
pushKV(
"address", info.resolvedAddress.ToString());
608 address.
pushKV(
"connected",
609 info.fInbound ?
"inbound" :
"outbound");
612 obj.
pushKV(
"addresses", addresses);
624 "Returns information about network traffic, including bytes in, "
626 "and current time.\n",
634 "Total bytes received"},
643 "Length of the measuring timeframe in seconds"},
646 "True if target is reached"},
648 "True if serving historical blocks"},
650 "Bytes left in current time cycle"},
652 "Seconds left in current time cycle"},
671 outboundLimit.
pushKV(
"target_reached",
673 outboundLimit.
pushKV(
"serve_historical_blocks",
675 outboundLimit.
pushKV(
"bytes_left_in_cycle",
678 "time_left_in_cycle",
680 obj.
pushKV(
"uploadtarget", outboundLimit);
688 for (
int n = 0; n <
NET_MAX; ++n) {
712 "Returns an object containing various state info regarding P2P "
722 "the server subversion string"},
724 "the protocol version"},
726 "the services we offer to the network"},
728 "localservicesnames",
729 "the services we offer to the network, in human-readable form",
734 "true if transaction relay is requested from peers"},
737 "the total number of connections"},
739 "the number of inbound connections"},
741 "the number of outbound connections"},
743 "whether p2p networking is enabled"},
746 "information per network",
755 "is the network limited using -onlynet?"},
757 "is the network reachable?"},
759 "(\"host:port\") the proxy that is used for this "
760 "network, or empty if none"},
762 "Whether randomized credentials are used"},
766 "minimum relay fee for transactions in " + ticker +
"/kB"},
769 "list of local addresses",
781 "any network and blockchain warnings"},
799 obj.
pushKV(
"localrelay", !
node.peerman->IgnoresIncomingTxs());
803 obj.
pushKV(
"networkactive",
node.connman->GetNetworkActive());
804 obj.
pushKV(
"connections",
int(
node.connman->GetNodeCount(
806 obj.
pushKV(
"connections_in",
int(
node.connman->GetNodeCount(
808 obj.
pushKV(
"connections_out",
int(
node.connman->GetNodeCount(
816 node.mempool->m_min_relay_feerate.GetFeePerK());
821 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item :
824 rec.
pushKV(
"address", item.first.ToString());
825 rec.
pushKV(
"port", item.second.nPort);
826 rec.
pushKV(
"score", item.second.nScore);
830 obj.
pushKV(
"localaddresses", localAddresses);
840 "Attempts to add or remove an IP/Subnet from the banned list.\n",
843 "The IP/Subnet (see getpeerinfo for nodes IP) with an optional "
844 "netmask (default is /32 = single IP)"},
846 "'add' to add an IP/Subnet to the list, 'remove' to remove an "
847 "IP/Subnet from the list"},
849 "time in seconds how long (or until when if [absolute] is set) "
850 "the IP is banned (0 or empty means using the default time of 24h "
851 "which can also be overwritten by the -bantime startup argument)"},
853 "If set, the bantime must be an absolute timestamp expressed in " +
863 std::string strCommand;
864 if (!request.params[1].isNull()) {
865 strCommand = request.params[1].
get_str();
868 if (strCommand !=
"add" && strCommand !=
"remove") {
875 "Error: Ban database not loaded");
880 bool isSubnet =
false;
882 if (request.params[0].get_str().find(
'/') != std::string::npos) {
888 LookupHost(request.params[0].get_str(), resolved,
false);
896 "Error: Invalid IP/Subnet");
899 if (strCommand ==
"add") {
900 if (isSubnet ?
node.banman->IsBanned(subNet)
901 :
node.banman->IsBanned(netAddr)) {
903 "Error: IP/Subnet already banned");
908 if (!request.params[2].isNull()) {
909 banTime = request.params[2].get_int64();
913 if (request.params[3].isTrue()) {
920 node.connman->DisconnectNode(subNet);
925 node.connman->DisconnectNode(netAddr);
928 }
else if (strCommand ==
"remove") {
929 if (!(isSubnet ?
node.banman->Unban(subNet)
930 :
node.banman->Unban(netAddr))) {
933 "Error: Unban failed. Requested address/subnet "
934 "was not previously manually banned.");
945 "List all manually banned IPs/Subnets.\n",
968 "Error: Ban database not loaded");
972 node.banman->GetBanned(banMap);
975 for (
const auto &entry : banMap) {
976 const CBanEntry &banEntry = entry.second;
978 rec.
pushKV(
"address", entry.first.ToString());
985 return bannedAddresses;
993 "Clear all banned IPs.\n",
1004 "Error: Peer-to-peer functionality missing or disabled");
1007 node.banman->ClearBanned();
1017 "Disable/enable all p2p network activity.\n",
1020 "true to enable networking, false to disable"},
1039 "Return known addresses, which can potentially be used to find new "
1040 "nodes in the network.\n",
1043 "The maximum number of addresses to return. Specify 0 to return "
1044 "all known addresses."},
1046 "Return only addresses of the specified network. Can be one of: " +
1059 " when the node was last seen"},
1061 "The services offered by the node"},
1063 "The address of the node"},
1065 "The port number of the node"},
1068 ") the node connected through"},
1074 "network=onion count=12") +
1083 request.params[0].isNull() ? 1 : request.params[0].get_int()};
1086 "Address count out of range");
1089 const std::optional<Network> network{
1090 request.params[1].isNull()
1092 : std::optional<Network>{
1097 request.params[1].get_str()));
1100 const std::vector<CAddress> vAddr{
1104 for (
const CAddress &addr : vAddr) {
1108 int64_t{TicksSinceEpoch<std::chrono::seconds>(addr.nTime)});
1109 obj.
pushKV(
"services", uint64_t(addr.nServices));
1110 obj.
pushKV(
"address", addr.ToStringIP());
1111 obj.
pushKV(
"port", addr.GetPort());
1123 "Add the address of a potential peer to the address manager. This "
1124 "RPC is for testing only.\n",
1127 "The IP address of the peer"},
1129 "The port of the peer"},
1131 "If true, attempt to add the peer to the tried addresses table"},
1139 "whether the peer address was successfully added to the "
1149 if (!
node.addrman) {
1152 "Error: Address manager functionality missing or disabled");
1155 const std::string &addr_string{request.params[0].get_str()};
1156 const uint16_t port{
1157 static_cast<uint16_t
>(request.params[1].get_int())};
1158 const bool tried{request.params[2].isTrue()};
1162 bool success{
false};
1164 if (
LookupHost(addr_string, net_addr,
false)) {
1169 if (
node.addrman->Add({address}, address)) {
1174 node.addrman->Good(address);
1179 obj.
pushKV(
"success", success);
1191 {
"network",
ping, },
1207 for (
const auto &c : commands) {
bool isAvalancheEnabled(const ArgsManager &argsman)
std::unique_ptr< avalanche::Processor > g_avalanche
Global avalanche instance.
A CService with information about it as peer.
static const std::string REGTEST
size_t GetNodeCount(NumConnections num) const
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time in second left in the current max outbound cycle in case of no limit,...
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
bool GetNetworkActive() const
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
std::chrono::seconds GetMaxOutboundTimeframe() const
bool DisconnectNode(const std::string &node)
uint64_t GetMaxOutboundTarget() const
void GetNodeStats(std::vector< CNodeStats > &vstats) const
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
uint64_t GetTotalBytesRecv() const
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
void SetNetworkActive(bool active)
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
uint64_t GetTotalBytesSent() const
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
std::string ToStringIPPort() const
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
virtual void SendPings()=0
Send ping message to all peers.
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
std::string ToString() const
const std::string & get_str() const
int64_t get_int64() const
bool push_back(const UniValue &val)
bool pushKV(const std::string &key, const UniValue &val)
bool randomize_credentials
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static path absolute(const path &p)
const std::string NET_MESSAGE_COMMAND_OTHER
GlobalMutex g_maplocalhost_mutex
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
std::string userAgent(const Config &config)
bool IsReachable(enum Network net)
const std::vector< std::string > CONNECTION_TYPE_DOC
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ AVALANCHE_OUTBOUND
Special case of connection to a full relay outbound with avalanche service enabled.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
std::map< CSubNet, CBanEntry > banmap_t
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
std::string GetNetworkName(enum Network net)
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret, DNSLookupFn dns_lookup_function)
Parse and resolve a specified subnet string into the appropriate internal representation.
enum Network ParseNetwork(const std::string &net_in)
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
ServiceFlags
nServices flags.
UniValue JSONRPCError(int code, const std::string &message)
void RegisterNetRPCCommands(CRPCTable &t)
Register P2P networking RPC commands.
static RPCHelpMan getnetworkinfo()
static RPCHelpMan addconnection()
static RPCHelpMan getaddednodeinfo()
static RPCHelpMan clearbanned()
static RPCHelpMan getnettotals()
static RPCHelpMan addnode()
static RPCHelpMan getnodeaddresses()
static RPCHelpMan setban()
static UniValue GetNetworksInfo()
static RPCHelpMan getconnectioncount()
static RPCHelpMan disconnectnode()
static RPCHelpMan listbanned()
static RPCHelpMan setnetworkactive()
static RPCHelpMan addpeeraddress()
static RPCHelpMan getpeerinfo()
@ RPC_CLIENT_NODE_NOT_CONNECTED
Node to disconnect not found in connected nodes.
@ RPC_CLIENT_INVALID_IP_OR_SUBNET
Invalid IP/Subnet.
@ RPC_CLIENT_NODE_ALREADY_ADDED
Node is already added.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_DATABASE_ERROR
Database error.
@ RPC_CLIENT_NODE_NOT_ADDED
Node has not been added before.
@ RPC_CLIENT_NODE_CAPACITY_REACHED
Max number of outbound or block-relay connections already open.
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
ArgsManager & EnsureArgsman(const NodeContext &node)
NodeContext & EnsureAnyNodeContext(const std::any &context)
CConnman & EnsureConnman(const NodeContext &node)
PeerManager & EnsurePeerman(const NodeContext &node)
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
std::string TrimString(const std::string &str, const std::string &pattern=" \f\n\r\t\v")
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::chrono::microseconds m_ping_wait
Amount m_fee_filter_received
std::vector< int > vHeightInFlight
bool m_addr_relay_enabled
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
ServiceFlags their_services
POD that contains various stats about a node.
static const Currency & get()
@ NUM_TIME
Special numeric to denote unix epoch time.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
int64_t GetTimeMillis()
Returns the system time (not mockable)
constexpr int64_t count_seconds(std::chrono::seconds t)
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
NodeSeconds AdjustedTime()
const UniValue NullUniValue
static const int PROTOCOL_VERSION
network protocol versioning
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.