28 #include <validation.h>
39 "outbound-full-relay (default automatic connections)",
40 "block-relay-only (does not relay transactions or addresses)",
41 "inbound (initiated by the peer)",
42 "manual (added via addnode RPC or -addnode/-connect configuration options)",
43 "addr-fetch (short-lived automatic connection for soliciting addresses)",
44 "feeler (short-lived automatic connection for testing addresses)"
50 "\nReturns the number of connections to other nodes.\n",
72 "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
73 "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
74 "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n",
97 "Returns data about each connected network peer as a json array of objects.",
107 {
RPCResult::Type::STR,
"addrbind",
true,
"(ip:port) Bind address of the connection to the peer"},
110 {
RPCResult::Type::NUM,
"mapped_as",
true,
"The AS in the BGP route to the peer used for diversifying\n"
111 "peer selection (only available if the asmap config flag is set)"},
127 {
RPCResult::Type::NUM,
"minping",
true,
"The minimum observed ping time in milliseconds (ms), if any"},
128 {
RPCResult::Type::NUM,
"pingwait",
true,
"The duration in milliseconds (ms) of an outstanding ping (if non-zero)"},
132 {
RPCResult::Type::BOOL,
"bip152_hb_to",
"Whether we selected peer as (compact blocks) high-bandwidth peer"},
133 {
RPCResult::Type::BOOL,
"bip152_hb_from",
"Whether peer selected us as (compact blocks) high-bandwidth peer"},
135 {
RPCResult::Type::NUM,
"presynced_headers",
"The current height of header pre-synchronization with this peer, or -1 if no low-work sync is in progress"},
142 {
RPCResult::Type::BOOL,
"addr_relay_enabled",
"Whether we participate in address relay with this peer"},
143 {
RPCResult::Type::NUM,
"addr_processed",
"The total number of addresses processed, excluding those dropped due to rate limiting"},
144 {
RPCResult::Type::NUM,
"addr_rate_limited",
"The total number of addresses dropped due to rate limiting"},
145 {
RPCResult::Type::ARR,
"permissions",
"Any special permissions that have been granted to this peer",
149 {
RPCResult::Type::NUM,
"minfeefilter",
"The minimum fee rate for transactions this peer accepts"},
153 "When a message type is not listed in this json object, the bytes sent are 0.\n"
154 "Only known message types can appear as keys in the object."}
159 "When a message type is not listed in this json object, the bytes received are 0.\n"
160 "Only known message types can appear as keys in the object and all bytes received\n"
164 "Please note this output is unlikely to be stable in upcoming releases as we iterate to\n"
165 "best capture connection behaviors."},
179 std::vector<CNodeStats> vstats;
196 obj.
pushKV(
"id", stats.nodeid);
197 obj.
pushKV(
"addr", stats.m_addr_name);
198 if (stats.addrBind.IsValid()) {
199 obj.
pushKV(
"addrbind", stats.addrBind.ToString());
201 if (!(stats.addrLocal.empty())) {
202 obj.
pushKV(
"addrlocal", stats.addrLocal);
205 if (stats.m_mapped_as != 0) {
206 obj.
pushKV(
"mapped_as", uint64_t(stats.m_mapped_as));
216 obj.
pushKV(
"bytessent", stats.nSendBytes);
217 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
219 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
220 if (stats.m_last_ping_time > 0us) {
221 obj.
pushKV(
"pingtime", Ticks<SecondsDouble>(stats.m_last_ping_time));
223 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
224 obj.
pushKV(
"minping", Ticks<SecondsDouble>(stats.m_min_ping_time));
229 obj.
pushKV(
"version", stats.nVersion);
233 obj.
pushKV(
"subver", stats.cleanSubVer);
234 obj.
pushKV(
"inbound", stats.fInbound);
235 obj.
pushKV(
"bip152_hb_to", stats.m_bip152_highbandwidth_to);
236 obj.
pushKV(
"bip152_hb_from", stats.m_bip152_highbandwidth_from);
245 obj.
pushKV(
"inflight", heights);
253 obj.
pushKV(
"permissions", permissions);
257 for (
const auto& i : stats.mapSendBytesPerMsgType) {
259 sendPerMsgType.
pushKV(i.first, i.second);
261 obj.
pushKV(
"bytessent_per_msg", sendPerMsgType);
264 for (
const auto& i : stats.mapRecvBytesPerMsgType) {
266 recvPerMsgType.
pushKV(i.first, i.second);
268 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgType);
282 "\nAttempts to add or remove a node from the addnode list.\n"
283 "Or try a connection to a node once.\n"
284 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n"
285 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n" +
287 " and are counted separately from the -maxconnections limit.\n",
299 std::string strCommand;
300 if (!request.params[1].isNull())
301 strCommand = request.params[1].
get_str();
302 if (strCommand !=
"onetry" && strCommand !=
"add" && strCommand !=
"remove") {
303 throw std::runtime_error(
310 std::string strNode = request.params[0].get_str();
312 if (strCommand ==
"onetry")
319 if (strCommand ==
"add")
321 if (!connman.
AddNode(strNode)) {
325 else if(strCommand ==
"remove")
340 "\nOpen an outbound connection to a specified node. This RPC is for testing only.\n",
352 HelpExampleCli(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
353 +
HelpExampleRpc(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
358 throw std::runtime_error(
"addconnection is for regression testing (-regtest mode) only.");
361 const std::string address = request.params[0].get_str();
362 const std::string conn_type_in{
TrimString(request.params[1].get_str())};
364 if (conn_type_in ==
"outbound-full-relay") {
366 }
else if (conn_type_in ==
"block-relay-only") {
368 }
else if (conn_type_in ==
"addr-fetch") {
370 }
else if (conn_type_in ==
"feeler") {
379 const bool success = connman.
AddConnection(address, conn_type);
385 info.
pushKV(
"address", address);
386 info.
pushKV(
"connection_type", conn_type_in);
396 "\nImmediately disconnects from the specified peer node.\n"
397 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
398 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
416 const UniValue &address_arg = request.params[0];
417 const UniValue &id_arg = request.params[1];
442 "\nReturns information about the given added node, or all added nodes\n"
443 "(note that onetry addnodes are not listed here)\n",
476 if (!request.params[0].isNull()) {
479 if (info.strAddedNode == request.params[0].get_str()) {
480 vInfo.assign(1, info);
494 obj.
pushKV(
"addednode", info.strAddedNode);
495 obj.
pushKV(
"connected", info.fConnected);
497 if (info.fConnected) {
499 address.
pushKV(
"address", info.resolvedAddress.ToString());
500 address.
pushKV(
"connected", info.fInbound ?
"inbound" :
"outbound");
503 obj.
pushKV(
"addresses", addresses);
515 "\nReturns information about network traffic, including bytes in, bytes out,\n"
516 "and current time.\n",
556 obj.
pushKV(
"uploadtarget", outboundLimit);
565 for (
int n = 0; n <
NET_MAX; ++n) {
584 "Returns an object containing various state info regarding P2P networking.\n",
593 {
RPCResult::Type::ARR,
"localservicesnames",
"the services we offer to the network, in human-readable form",
610 {
RPCResult::Type::STR,
"proxy",
"(\"host:port\") the proxy that is used for this network, or empty if none"},
646 obj.
pushKV(
"localrelay", !
node.peerman->IgnoresIncomingTxs());
650 obj.
pushKV(
"networkactive",
node.connman->GetNetworkActive());
664 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
667 rec.
pushKV(
"address", item.first.ToString());
668 rec.
pushKV(
"port", item.second.nPort);
669 rec.
pushKV(
"score", item.second.nScore);
673 obj.
pushKV(
"localaddresses", localAddresses);
683 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
687 {
"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)"},
698 std::string strCommand;
699 if (!request.params[1].isNull())
700 strCommand = request.params[1].
get_str();
701 if (strCommand !=
"add" && strCommand !=
"remove") {
711 bool isSubnet =
false;
713 if (request.params[0].get_str().find(
'/') != std::string::npos)
718 LookupHost(request.params[0].get_str(), resolved,
false);
727 if (strCommand ==
"add")
729 if (isSubnet ?
node.banman->IsBanned(subNet) :
node.banman->IsBanned(netAddr)) {
734 if (!request.params[2].isNull())
735 banTime = request.params[2].getInt<int64_t>();
737 const bool absolute{request.params[3].isNull() ? false : request.params[3].get_bool()};
746 node.connman->DisconnectNode(subNet);
751 node.connman->DisconnectNode(netAddr);
755 else if(strCommand ==
"remove")
757 if (!( isSubnet ?
node.banman->Unban(subNet) :
node.banman->Unban(netAddr) )) {
769 "\nList all manually banned IPs/Subnets.\n",
794 node.banman->GetBanned(banMap);
795 const int64_t current_time{
GetTime()};
798 for (
const auto& entry : banMap)
800 const CBanEntry& banEntry = entry.second;
802 rec.
pushKV(
"address", entry.first.ToString());
811 return bannedAddresses;
819 "\nClear all banned IPs.\n",
833 node.banman->ClearBanned();
843 "\nDisable/enable all p2p network activity.\n",
864 "Return known addresses, after filtering for quality and recency.\n"
865 "These can potentially be used to find new peers in the network.\n"
866 "The total number of addresses known to the node may be higher.",
887 +
HelpExampleCli(
"-named getnodeaddresses",
"network=onion count=12")
896 const int count{request.params[0].isNull() ? 1 : request.params[0].getInt<
int>()};
899 const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{
ParseNetwork(request.params[1].get_str())}};
908 for (
const CAddress& addr : vAddr) {
910 obj.
pushKV(
"time", int64_t{TicksSinceEpoch<std::chrono::seconds>(addr.nTime)});
911 obj.
pushKV(
"services", (uint64_t)addr.nServices);
912 obj.
pushKV(
"address", addr.ToStringIP());
913 obj.
pushKV(
"port", addr.GetPort());
925 "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
934 {
RPCResult::Type::BOOL,
"success",
"whether the peer address was successfully added to the address manager"},
948 const std::string& addr_string{request.params[0].get_str()};
949 const auto port{request.params[1].getInt<uint16_t>()};
950 const bool tried{request.params[2].isNull() ? false : request.params[2].get_bool()};
956 if (
LookupHost(addr_string, net_addr,
false)) {
959 address.nTime = Now<NodeSeconds>();
962 if (
node.addrman->Add({address}, address)) {
966 node.addrman->Good(address);
971 obj.
pushKV(
"success", success);
996 for (
const auto& c : commands) {
997 t.appendCommand(c.name, &c);
const CChainParams & Params()
Return the currently selected parameters.
A CService with information about it as peer.
static const std::string REGTEST
std::string NetworkIDString() const
Return the network string.
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
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
std::chrono::seconds GetMaxOutboundTimeframe() const
bool DisconnectNode(const std::string &node)
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)
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
A combination of a network address (CNetAddr) and a (TCP) port.
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.
bool randomize_credentials
std::string ToString() const
void push_back(UniValue val)
const std::string & get_str() const
void pushKV(std::string key, UniValue val)
static const 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 requested via the addnode RPC or the -a...
@ 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.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
UniValue ValueFromAmount(const CAmount amount)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
const std::string CURRENCY_UNIT
static path absolute(const path &p)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
const std::string NET_MESSAGE_TYPE_OTHER
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
GlobalMutex g_maplocalhost_mutex
bool IsReachable(enum Network net)
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
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::string GetNetworkName(enum Network net)
enum Network ParseNetwork(const std::string &net_in)
bool LookupSubNet(const std::string &subnet_str, CSubNet &subnet_out)
Parse and resolve a specified subnet string into the appropriate internal representation.
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.
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)
const std::vector< std::string > CONNECTION_TYPE_DOC
void RegisterNetRPCCommands(CRPCTable &t)
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.
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)
CConnman & EnsureConnman(const NodeContext &node)
PeerManager & EnsurePeerman(const NodeContext &node)
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
std::string ToString(const T &t)
Locale-independent version of std::to_string.
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
std::chrono::microseconds m_ping_wait
std::vector< int > vHeightInFlight
CAmount m_fee_filter_received
bool m_addr_relay_enabled
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
ServiceFlags their_services
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)
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
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.