10#include <chainparams.h>
31#include <validation.h>
45 "Returns the number of connections to other nodes.\n",
63 "Requests that a ping be sent to all other nodes, to measure ping "
65 "Results provided in getpeerinfo, pingtime and pingwait fields are "
67 "Ping command is handled in queue with all other commands, so it "
68 "measures processing backlog, not just network ping.\n",
88 "Returns data about each connected network node as a json array of "
102 "(host:port) The IP address and port of the peer"},
104 "(ip:port) Bind address of the connection to the peer"},
106 "(ip:port) Local address as reported by the peer"},
108 "The total number of addresses processed, excluding those "
109 "dropped due to rate limiting"},
111 "The total number of addresses dropped due to rate "
119 "The AS in the BGP route to the peer used for "
121 "peer selection (only available if the asmap config flag "
124 "The services offered"},
127 "the services offered, in human-readable form",
129 "the service name if it is recognised"}}},
131 "Whether peer has asked us to relay transactions to it"},
140 " of the last valid transaction received from this "
144 " of the last block received from this peer"},
147 "The total bytes received"},
149 "The current in-flight bytes from this peer"},
153 "The time offset in seconds"},
155 "ping time (if available)"},
157 "minimum observed ping time (if any at all)"},
159 "ping wait (if non-zero)"},
161 "The peer version, such as 70001"},
164 "Inbound (true) or Outbound (false)"},
166 "Whether we selected peer as (compact blocks) "
167 "high-bandwidth peer"},
169 "Whether peer selected us as (compact blocks) "
170 "high-bandwidth peer"},
172 "Type of connection: \n" +
175 "The starting height (block) of the peer"},
178 "The current height of header pre-synchronization with "
179 "this peer, or -1 if no low-work sync is in progress"},
181 "The last header we have in common with this peer"},
183 "The last block we have in common with this peer"},
189 "The heights of blocks we're currently asking from "
193 "Whether we participate in address relay with this peer"},
196 "Any special permissions that have been granted to this "
203 "The minimum fee rate for transactions this peer accepts"},
208 "The total bytes sent aggregated by message type\n"
209 "When a message type is not listed in this json object, "
210 "the bytes sent are 0.\n"
211 "Only known message types can appear as keys in the "
217 "The total bytes received aggregated by message type\n"
218 "When a message type is not listed in this json object, "
219 "the bytes received are 0.\n"
220 "Only known message types can appear as keys in the "
221 "object and all bytes received\n"
222 "of unknown message types are listed under '" +
235 std::vector<CNodeStats> vstats;
245 obj.
pushKV(
"id", stats.nodeid);
246 obj.
pushKV(
"addr", stats.m_addr_name);
247 if (stats.addrBind.IsValid()) {
248 obj.
pushKV(
"addrbind", stats.addrBind.ToStringAddrPort());
250 if (!(stats.addrLocal.empty())) {
251 obj.
pushKV(
"addrlocal", stats.addrLocal);
254 if (stats.m_mapped_as != 0) {
255 obj.
pushKV(
"mapped_as", uint64_t(stats.m_mapped_as));
263 obj.
pushKV(
"last_msg_start",
265 obj.
pushKV(
"last_transaction",
267 if (
node.avalanche) {
273 obj.
pushKV(
"bytessent", stats.nSendBytes);
274 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
275 obj.
pushKV(
"bytes_inflight", stats.nInflightBytes);
277 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
278 if (stats.m_last_ping_time > 0us) {
282 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
290 obj.
pushKV(
"version", stats.nVersion);
294 obj.
pushKV(
"subver", stats.cleanSubVer);
295 obj.
pushKV(
"inbound", stats.fInbound);
296 obj.
pushKV(
"bip152_hb_to", stats.m_bip152_highbandwidth_to);
297 obj.
pushKV(
"bip152_hb_from", stats.m_bip152_highbandwidth_from);
307 obj.
pushKV(
"inflight", std::move(heights));
309 obj.
pushKV(
"minfeefilter",
311 obj.
pushKV(
"addr_relay_enabled",
314 obj.
pushKV(
"addr_rate_limited",
318 for (
const auto &permission :
322 obj.
pushKV(
"permissions", std::move(permissions));
325 for (
const auto &i : stats.mapSendBytesPerMsgType) {
327 sendPerMsgType.
pushKV(i.first, i.second);
330 obj.
pushKV(
"bytessent_per_msg", std::move(sendPerMsgType));
333 for (
const auto &i : stats.mapRecvBytesPerMsgType) {
335 recvPerMsgType.
pushKV(i.first, i.second);
338 obj.
pushKV(
"bytesrecv_per_msg", std::move(recvPerMsgType));
339 obj.
pushKV(
"connection_type",
353 "Attempts to add or remove a node from the addnode list.\n"
354 "Or try a connection to a node once.\n"
355 "Nodes added using addnode (or -connect) are protected from "
356 "DoS disconnection and are not required to be\n"
357 "full nodes as other outbound peers are (though such peers "
358 "will not be synced from).\n",
361 "The address of the peer to connect to"},
363 "'add' to add a node to the list, 'remove' to remove a "
364 "node from the list, 'onetry' to try a connection to the "
373 const auto command{self.
Arg<std::string>(
"command")};
374 if (command !=
"onetry" && command !=
"add" &&
375 command !=
"remove") {
376 throw std::runtime_error(self.
ToString());
382 const auto node_arg{self.
Arg<std::string>(
"node")};
385 if (command ==
"onetry") {
388 addr,
false,
nullptr,
393 if ((command ==
"add") && (!connman.
AddNode(node_arg))) {
395 "Error: Node already added");
396 }
else if ((command ==
"remove") &&
400 "Error: Node could not be removed. It has not been "
401 "added previously.");
412 "\nOpen an outbound connection to a specified node. This RPC is for "
416 "The IP address and port to attempt connecting to."},
418 "Type of connection to open (\"outbound-full-relay\", "
419 "\"block-relay-only\", \"addr-fetch\", \"feeler\" or "
427 "Address of newly added connection."},
429 "Type of connection opened."},
433 "\"192.168.0.6:8333\" \"outbound-full-relay\"") +
435 "\"192.168.0.6:8333\" \"outbound-full-relay\"")},
439 throw std::runtime_error(
"addconnection is for regression "
440 "testing (-regtest mode) only.");
445 const std::string address = request.params[0].get_str();
446 const std::string conn_type_in{
449 if (conn_type_in ==
"outbound-full-relay") {
451 }
else if (conn_type_in ==
"block-relay-only") {
453 }
else if (conn_type_in ==
"addr-fetch") {
455 }
else if (conn_type_in ==
"feeler") {
457 }
else if (conn_type_in ==
"avalanche") {
458 if (!
node.avalanche) {
460 "Error: avalanche outbound requested "
461 "but avalanche is not enabled.");
470 const bool success = connman.
AddConnection(address, conn_type);
473 "Error: Already at capacity for specified "
478 info.
pushKV(
"address", address);
479 info.
pushKV(
"connection_type", conn_type_in);
489 "Immediately disconnects from the specified peer node.\n"
490 "\nStrictly one out of 'address' and 'nodeid' can be provided to "
491 "identify the node.\n"
492 "\nTo disconnect by nodeid, either set 'address' to the empty string, "
493 "or call using the named 'nodeid' argument only.\n",
497 "The IP address/port of the node"},
500 "The node ID (see getpeerinfo for node IDs)"},
513 const UniValue &address_arg = request.params[0];
514 const UniValue &id_arg = request.params[1];
520 (address_arg.
isStr() &&
521 address_arg.
get_str().empty()))) {
528 "Only one of address and nodeid should be provided.");
533 "Node not found in connected nodes");
544 "Returns information about the given added node, or all added nodes\n"
545 "(note that onetry addnodes are not listed here)\n",
548 "If provided, return information about this specific node, "
549 "otherwise all nodes are returned."},
561 "The node IP address or name (as provided to addnode)"},
565 "Only when connected = true",
572 "The bitcoin server IP and port we're "
575 "connection, inbound or outbound"},
589 if (!request.params[0].isNull()) {
592 if (info.strAddedNode == request.params[0].get_str()) {
593 vInfo.assign(1, info);
600 "Error: Node has not been added.");
608 obj.
pushKV(
"addednode", info.strAddedNode);
609 obj.
pushKV(
"connected", info.fConnected);
611 if (info.fConnected) {
614 info.resolvedAddress.ToStringAddrPort());
615 address.
pushKV(
"connected",
616 info.fInbound ?
"inbound" :
"outbound");
619 obj.
pushKV(
"addresses", std::move(addresses));
631 "Returns information about network traffic, including bytes in, "
633 "and current time.\n",
641 "Total bytes received"},
650 "Length of the measuring timeframe in seconds"},
653 "True if target is reached"},
655 "True if serving historical blocks"},
657 "Bytes left in current time cycle"},
659 "Seconds left in current time cycle"},
678 outboundLimit.
pushKV(
"target_reached",
680 outboundLimit.
pushKV(
"serve_historical_blocks",
682 outboundLimit.
pushKV(
"bytes_left_in_cycle",
685 "time_left_in_cycle",
687 obj.
pushKV(
"uploadtarget", std::move(outboundLimit));
695 for (
int n = 0; n <
NET_MAX; ++n) {
708 obj.
pushKV(
"proxy_randomize_credentials",
719 "Returns an object containing various state info regarding P2P "
729 "the server subversion string"},
731 "the protocol version"},
733 "the services we offer to the network"},
735 "localservicesnames",
736 "the services we offer to the network, in human-readable form",
741 "true if transaction relay is requested from peers"},
744 "the total number of connections"},
746 "the number of inbound connections"},
748 "the number of outbound connections"},
750 "whether p2p networking is enabled"},
753 "information per network",
762 "is the network limited using -onlynet?"},
764 "is the network reachable?"},
766 "(\"host:port\") the proxy that is used for this "
767 "network, or empty if none"},
769 "Whether randomized credentials are used"},
773 "minimum relay fee for transactions in " + ticker +
"/kB"},
776 "list of local addresses",
788 "any network and blockchain warnings"},
806 obj.
pushKV(
"localrelay", !
node.peerman->IgnoresIncomingTxs());
810 obj.
pushKV(
"networkactive",
node.connman->GetNetworkActive());
811 obj.
pushKV(
"connections",
node.connman->GetNodeCount(
813 obj.
pushKV(
"connections_in",
815 obj.
pushKV(
"connections_out",
node.connman->GetNodeCount(
823 node.mempool->m_min_relay_feerate.GetFeePerK());
828 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item :
831 rec.
pushKV(
"address", item.first.ToStringAddr());
832 rec.
pushKV(
"port", item.second.nPort);
833 rec.
pushKV(
"score", item.second.nScore);
834 localAddresses.
push_back(std::move(rec));
837 obj.
pushKV(
"localaddresses", std::move(localAddresses));
847 "Attempts to add or remove an IP/Subnet from the banned list.\n",
850 "The IP/Subnet (see getpeerinfo for nodes IP) with an optional "
851 "netmask (default is /32 = single IP)"},
853 "'add' to add an IP/Subnet to the list, 'remove' to remove an "
854 "IP/Subnet from the list"},
856 "time in seconds how long (or until when if [absolute] is set) "
857 "the IP is banned (0 or empty means using the default time of 24h "
858 "which can also be overwritten by the -bantime startup argument)"},
860 "If set, the bantime must be an absolute timestamp expressed in " +
870 std::string strCommand;
871 if (!request.params[1].isNull()) {
872 strCommand = request.params[1].
get_str();
875 if (strCommand !=
"add" && strCommand !=
"remove") {
882 "Error: Ban database not loaded");
887 bool isSubnet =
false;
889 if (request.params[0].get_str().find(
'/') != std::string::npos) {
894 const std::optional<CNetAddr> addr{
895 LookupHost(request.params[0].get_str(),
false)};
896 if (addr.has_value()) {
897 netAddr = addr.value();
905 "Error: Invalid IP/Subnet");
908 if (strCommand ==
"add") {
909 if (isSubnet ?
node.banman->IsBanned(subNet)
910 :
node.banman->IsBanned(netAddr)) {
912 "Error: IP/Subnet already banned");
917 if (!request.params[2].isNull()) {
918 banTime = request.params[2].getInt<int64_t>();
922 if (request.params[3].isTrue()) {
929 node.connman->DisconnectNode(subNet);
934 node.connman->DisconnectNode(netAddr);
937 }
else if (strCommand ==
"remove") {
938 if (!(isSubnet ?
node.banman->Unban(subNet)
939 :
node.banman->Unban(netAddr))) {
942 "Error: Unban failed. Requested address/subnet "
943 "was not previously manually banned.");
954 "List all manually banned IPs/Subnets.\n",
977 "Error: Ban database not loaded");
981 node.banman->GetBanned(banMap);
984 for (
const auto &entry : banMap) {
985 const CBanEntry &banEntry = entry.second;
987 rec.
pushKV(
"address", entry.first.ToString());
991 bannedAddresses.
push_back(std::move(rec));
994 return bannedAddresses;
1002 "Clear all banned IPs.\n",
1013 "Error: Peer-to-peer functionality missing or disabled");
1016 node.banman->ClearBanned();
1026 "Disable/enable all p2p network activity.\n",
1029 "true to enable networking, false to disable"},
1048 "Return known addresses, which can potentially be used to find new "
1049 "nodes in the network.\n",
1052 "The maximum number of addresses to return. Specify 0 to return "
1053 "all known addresses."},
1055 "Return only addresses of the specified network. Can be one of: " +
1068 " when the node was last seen"},
1070 "The services offered by the node"},
1072 "The address of the node"},
1074 "The port number of the node"},
1077 ") the node connected through"},
1083 "network=onion count=12") +
1091 const int count{request.params[0].isNull()
1093 : request.params[0].getInt<
int>()};
1096 "Address count out of range");
1099 const std::optional<Network> network{
1100 request.params[1].isNull()
1102 : std::optional<Network>{
1107 request.params[1].get_str()));
1110 const std::vector<CAddress> vAddr{
1114 for (
const CAddress &addr : vAddr) {
1118 int64_t{TicksSinceEpoch<std::chrono::seconds>(addr.nTime)});
1119 obj.
pushKV(
"services", uint64_t(addr.nServices));
1120 obj.
pushKV(
"address", addr.ToStringAddr());
1121 obj.
pushKV(
"port", addr.GetPort());
1133 "Add the address of a potential peer to the address manager. This "
1134 "RPC is for testing only.\n",
1137 "The IP address of the peer"},
1139 "The port of the peer"},
1141 "If true, attempt to add the peer to the tried addresses table"},
1149 "whether the peer address was successfully added to the "
1159 if (!
node.addrman) {
1162 "Error: Address manager functionality missing or disabled");
1165 const std::string &addr_string{request.params[0].get_str()};
1166 const uint16_t port{
1167 static_cast<uint16_t
>(request.params[1].getInt<
int>())};
1168 const bool tried{request.params[2].isTrue()};
1171 std::optional<CNetAddr> net_addr{
LookupHost(addr_string,
false)};
1172 bool success{
false};
1174 if (net_addr.has_value()) {
1175 CAddress address{{net_addr.value(), port},
1177 address.nTime = Now<NodeSeconds>();
1180 if (
node.addrman->Add({address}, address)) {
1185 node.addrman->Good(address);
1190 obj.
pushKV(
"success", success);
1199 "Send a p2p message to a peer specified by id.\n"
1200 "The message type and body must be provided, the message header will "
1202 "This RPC is for testing only.",
1205 "The peer to send the message to."},
1207 strprintf(
"The message type (maximum length %i)",
1210 "The serialized message body to send, in hex, without a message "
1218 const NodeId peer_id{request.params[0].
getInt<int64_t>()};
1219 const std::string &msg_type{request.params[1].get_str()};
1223 strprintf(
"Error: msg_type too long, max length is %i",
1226 auto msg{TryParseHex<uint8_t>(request.params[2].get_str())};
1227 if (!
msg.has_value()) {
1229 "Error parsing input for msg");
1237 msg_ser.
m_type = msg_type;
1246 "Error: Could not send message to peer");
1261 {
"network",
ping, },
1278 for (
const auto &c : commands) {
A CService with information about it as peer.
bool AddConnection(const std::string &address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
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 ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
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)
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
uint64_t GetMaxOutboundTarget() const
size_t GetNodeCount(ConnectionDirection) 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)
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
uint64_t GetTotalBytesSent() const
Information about a peer.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
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
bool m_randomize_credentials
auto Arg(size_t i) const
Helper to get a required or default-valued request argument.
std::string ToString() const
void push_back(UniValue val)
const std::string & get_str() const
void pushKV(std::string key, UniValue val)
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
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.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static path absolute(const path &p)
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(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
const std::string NET_MESSAGE_TYPE_OTHER
GlobalMutex g_maplocalhost_mutex
std::string userAgent(const Config &config)
bool IsReachable(enum Network net)
const std::vector< std::string > CONNECTION_TYPE_DOC
const std::vector< std::string > NET_PERMISSIONS_DOC
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::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
std::string GetNetworkName(enum Network net)
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)
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
ServiceFlags
nServices flags.
static const int PROTOCOL_VERSION
network protocol versioning
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()
static RPCHelpMan sendmsgtopeer()
@ RPC_CLIENT_NODE_NOT_CONNECTED
Node to disconnect not found in connected nodes.
@ RPC_CLIENT_INVALID_IP_OR_SUBNET
Invalid IP/Subnet.
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
@ 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.
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.
NodeContext & EnsureAnyNodeContext(const std::any &context)
PeerManager & EnsurePeerman(const NodeContext &node)
CConnman & EnsureConnman(const NodeContext &node)
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.
std::vector< uint8_t > data
static const Currency & get()
@ STR_HEX
Special type that is a STR with only hex chars.
std::string DefaultHint
Hint for default value.
@ 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:
const UniValue NullUniValue
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.