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)"},
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",
true,
"The current height of header pre-synchronization with this peer, or -1 if no low-work sync is in progress"},
136 {
RPCResult::Type::NUM,
"synced_headers",
true,
"The last header we have in common with this peer"},
137 {
RPCResult::Type::NUM,
"synced_blocks",
true,
"The last block we have in common with this peer"},
142 {
RPCResult::Type::BOOL,
"addr_relay_enabled",
true,
"Whether we participate in address relay with this peer"},
143 {
RPCResult::Type::NUM,
"addr_processed",
true,
"The total number of addresses processed, excluding those dropped due to rate limiting"},
144 {
RPCResult::Type::NUM,
"addr_rate_limited",
true,
"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",
true,
"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));
215 obj.
pushKV(
"bytessent", stats.nSendBytes);
216 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
218 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
219 if (stats.m_last_ping_time > 0us) {
220 obj.
pushKV(
"pingtime", Ticks<SecondsDouble>(stats.m_last_ping_time));
222 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
223 obj.
pushKV(
"minping", Ticks<SecondsDouble>(stats.m_min_ping_time));
228 obj.
pushKV(
"version", stats.nVersion);
232 obj.
pushKV(
"subver", stats.cleanSubVer);
233 obj.
pushKV(
"inbound", stats.fInbound);
234 obj.
pushKV(
"bip152_hb_to", stats.m_bip152_highbandwidth_to);
235 obj.
pushKV(
"bip152_hb_from", stats.m_bip152_highbandwidth_from);
245 obj.
pushKV(
"inflight", heights);
256 obj.
pushKV(
"permissions", permissions);
259 for (
const auto& i : stats.mapSendBytesPerMsgType) {
261 sendPerMsgType.
pushKV(i.first, i.second);
263 obj.
pushKV(
"bytessent_per_msg", sendPerMsgType);
266 for (
const auto& i : stats.mapRecvBytesPerMsgType) {
268 recvPerMsgType.
pushKV(i.first, i.second);
270 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgType);
284 "\nAttempts to add or remove a node from the addnode list.\n" 285 "Or try a connection to a node once.\n" 286 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n" 287 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n" +
289 " and are counted separately from the -maxconnections limit.\n",
301 std::string strCommand;
302 if (!request.params[1].isNull())
303 strCommand = request.params[1].
get_str();
304 if (strCommand !=
"onetry" && strCommand !=
"add" && strCommand !=
"remove") {
305 throw std::runtime_error(
312 std::string strNode = request.params[0].get_str();
314 if (strCommand ==
"onetry")
321 if (strCommand ==
"add")
323 if (!connman.
AddNode(strNode)) {
327 else if(strCommand ==
"remove")
342 "\nOpen an outbound connection to a specified node. This RPC is for testing only.\n",
354 HelpExampleCli(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
355 +
HelpExampleRpc(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
360 throw std::runtime_error(
"addconnection is for regression testing (-regtest mode) only.");
363 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});
364 const std::string address = request.params[0].get_str();
365 const std::string conn_type_in{
TrimString(request.params[1].get_str())};
367 if (conn_type_in ==
"outbound-full-relay") {
369 }
else if (conn_type_in ==
"block-relay-only") {
371 }
else if (conn_type_in ==
"addr-fetch") {
373 }
else if (conn_type_in ==
"feeler") {
382 const bool success = connman.
AddConnection(address, conn_type);
388 info.
pushKV(
"address", address);
389 info.
pushKV(
"connection_type", conn_type_in);
399 "\nImmediately disconnects from the specified peer node.\n" 400 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n" 401 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
419 const UniValue &address_arg = request.params[0];
420 const UniValue &id_arg = request.params[1];
445 "\nReturns information about the given added node, or all added nodes\n" 446 "(note that onetry addnodes are not listed here)\n",
479 if (!request.params[0].isNull()) {
482 if (info.strAddedNode == request.params[0].get_str()) {
483 vInfo.assign(1, info);
497 obj.
pushKV(
"addednode", info.strAddedNode);
498 obj.
pushKV(
"connected", info.fConnected);
500 if (info.fConnected) {
502 address.
pushKV(
"address", info.resolvedAddress.ToString());
503 address.
pushKV(
"connected", info.fInbound ?
"inbound" :
"outbound");
506 obj.
pushKV(
"addresses", addresses);
518 "\nReturns information about network traffic, including bytes in, bytes out,\n" 519 "and current time.\n",
559 obj.
pushKV(
"uploadtarget", outboundLimit);
568 for (
int n = 0; n <
NET_MAX; ++n) {
587 "Returns an object containing various state info regarding P2P networking.\n",
596 {
RPCResult::Type::ARR,
"localservicesnames",
"the services we offer to the network, in human-readable form",
613 {
RPCResult::Type::STR,
"proxy",
"(\"host:port\") the proxy that is used for this network, or empty if none"},
649 obj.
pushKV(
"localrelay", !
node.peerman->IgnoresIncomingTxs());
653 obj.
pushKV(
"networkactive",
node.connman->GetNetworkActive());
667 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
670 rec.
pushKV(
"address", item.first.ToString());
671 rec.
pushKV(
"port", item.second.nPort);
672 rec.
pushKV(
"score", item.second.nScore);
676 obj.
pushKV(
"localaddresses", localAddresses);
686 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
690 {
"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)"},
701 std::string strCommand;
702 if (!request.params[1].isNull())
703 strCommand = request.params[1].
get_str();
704 if (strCommand !=
"add" && strCommand !=
"remove") {
714 bool isSubnet =
false;
716 if (request.params[0].get_str().find(
'/') != std::string::npos)
721 LookupHost(request.params[0].get_str(), resolved,
false);
730 if (strCommand ==
"add")
732 if (isSubnet ?
node.banman->IsBanned(subNet) :
node.banman->IsBanned(netAddr)) {
737 if (!request.params[2].isNull())
738 banTime = request.params[2].getInt<int64_t>();
741 if (request.params[3].isTrue())
747 node.connman->DisconnectNode(subNet);
752 node.connman->DisconnectNode(netAddr);
756 else if(strCommand ==
"remove")
758 if (!( isSubnet ?
node.banman->Unban(subNet) :
node.banman->Unban(netAddr) )) {
770 "\nList all manually banned IPs/Subnets.\n",
795 node.banman->GetBanned(banMap);
796 const int64_t current_time{
GetTime()};
799 for (
const auto& entry : banMap)
801 const CBanEntry& banEntry = entry.second;
803 rec.
pushKV(
"address", entry.first.ToString());
812 return bannedAddresses;
820 "\nClear all banned IPs.\n",
834 node.banman->ClearBanned();
844 "\nDisable/enable all p2p network activity.\n",
865 "Return known addresses, after filtering for quality and recency.\n" 866 "These can potentially be used to find new peers in the network.\n" 867 "The total number of addresses known to the node may be higher.",
888 +
HelpExampleCli(
"-named getnodeaddresses",
"network=onion count=12")
897 const int count{request.params[0].isNull() ? 1 : request.params[0].getInt<
int>()};
900 const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{
ParseNetwork(request.params[1].get_str())}};
909 for (
const CAddress& addr : vAddr) {
911 obj.
pushKV(
"time", int64_t{TicksSinceEpoch<std::chrono::seconds>(addr.nTime)});
912 obj.
pushKV(
"services", (uint64_t)addr.nServices);
913 obj.
pushKV(
"address", addr.ToStringIP());
914 obj.
pushKV(
"port", addr.GetPort());
926 "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
935 {
RPCResult::Type::BOOL,
"success",
"whether the peer address was successfully added to the address manager"},
949 const std::string& addr_string{request.params[0].get_str()};
950 const auto port{request.params[1].getInt<uint16_t>()};
951 const bool tried{request.params[2].isTrue()};
957 if (
LookupHost(addr_string, net_addr,
false)) {
960 address.nTime = Now<NodeSeconds>();
963 if (
node.addrman->Add({address}, address)) {
967 node.addrman->Good(address);
972 obj.
pushKV(
"success", success);
997 for (
const auto& c : commands) {
998 t.appendCommand(c.name, &c);
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
std::string NetworkIDString() const
Return the network string.
void push_back(UniValue val)
AddrFetch connections are short lived connections used to solicit addresses from peers.
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.
Max number of outbound or block-relay connections already open.
Dummy value to indicate the number of NET_* constants.
uint64_t m_addr_rate_limited
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...
Feeler connections are short-lived connections made to check that a node is alive.
bool randomize_credentials
static const std::string REGTEST
int64_t GetTimeMillis()
Returns the system time (not mockable)
const std::string NET_MESSAGE_TYPE_OTHER
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
uint64_t GetTotalBytesRecv() const
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
void RegisterNetRPCCommands(CRPCTable &t)
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.
static UniValue GetNetworksInfo()
static RPCHelpMan addpeeraddress()
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
const std::string & get_str() const
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are: ...
static RPCHelpMan getnettotals()
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
These are the default connections that we use to connect with the network.
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 GetNodeStats(std::vector< CNodeStats > &vstats) const
std::string ToString() const
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Invalid, missing or duplicate parameter.
bool DisconnectNode(const std::string &node)
static RPCHelpMan getpeerinfo()
std::string ToString(const T &t)
Locale-independent version of std::to_string.
NodeContext struct containing references to chain state and connection state.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
CAmount m_fee_filter_received
UniValue JSONRPCError(int code, const std::string &message)
static RPCHelpMan getnodeaddresses()
Special string with only hex chars.
uint64_t m_addr_processed
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
A combination of a network address (CNetAddr) and a (TCP) port.
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
static RPCHelpMan disconnectnode()
bool AddConnection(const std::string &address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
A CService with information about it as peer.
const std::string CURRENCY_UNIT
static RPCHelpMan setban()
static RPCHelpMan addnode()
void SetNetworkActive(bool active)
bool GetNetworkActive() const
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Special numeric to denote unix epoch time.
static RPCHelpMan setnetworkactive()
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
constexpr int64_t count_seconds(std::chrono::seconds t)
std::chrono::microseconds m_ping_wait
enum Network ParseNetwork(const std::string &net_in)
const std::vector< std::string > CONNECTION_TYPE_DOC
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
ServiceFlags their_services
size_t GetNodeCount(ConnectionDirection) const
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...
bool IsReachable(enum Network net)
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
virtual void SendPings()=0
Send ping message to all peers.
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
const CChainParams & Params()
Return the currently selected parameters.
void pushKV(std::string key, UniValue val)
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
static const int PROTOCOL_VERSION
network protocol versioning
GlobalMutex g_maplocalhost_mutex
std::string ToStringIPPort() const
static RPCHelpMan getnetworkinfo()
Node to disconnect not found in connected nodes.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
std::chrono::seconds GetMaxOutboundTimeframe() const
UniValue ValueFromAmount(const CAmount amount)
static RPCHelpMan getaddednodeinfo()
bool LookupSubNet(const std::string &subnet_str, CSubNet &subnet_out)
Parse and resolve a specified subnet string into the appropriate internal representation.
ConnectionType
Different types of connections to a peer.
PeerManager & EnsurePeerman(const NodeContext &node)
static RPCHelpMan getconnectioncount()
std::map< CSubNet, CBanEntry > banmap_t
No valid connection manager instance found.
static RPCHelpMan listbanned()
std::string GetNetworkName(enum Network net)
std::vector< int > vHeightInFlight
Special dictionary with keys that are not literals.
int64_t GetTime()
DEPRECATED, see GetTime.
std::string TrimString(std::string_view str, std::string_view pattern=" \\\)
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
static path absolute(const path &p)
bool m_addr_relay_enabled
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...
NodeContext & EnsureAnyNodeContext(const std::any &context)
We use block-relay-only connections to help prevent against partition attacks.
CConnman & EnsureConnman(const NodeContext &node)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
static RPCHelpMan addconnection()
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Addresses from these networks are not publicly routable on the global Internet.