 |
Bitcoin Core
22.99.0
P2P Digital Currency
|
Go to the documentation of this file.
27 #include <validation.h>
38 "outbound-full-relay (default automatic connections)",
39 "block-relay-only (does not relay transactions or addresses)",
40 "inbound (initiated by the peer)",
41 "manual (added via addnode RPC or -addnode/-connect configuration options)",
42 "addr-fetch (short-lived automatic connection for soliciting addresses)",
43 "feeler (short-lived automatic connection for testing addresses)"
49 "\nReturns the number of connections to other nodes.\n",
71 "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
72 "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
73 "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n",
96 "\nReturns data about each connected network node as a json array of objects.\n",
106 {
RPCResult::Type::STR,
"addrbind",
true,
"(ip:port) Bind address of the connection to the peer"},
109 {
RPCResult::Type::NUM,
"mapped_as",
true,
"The AS in the BGP route to the peer used for diversifying\n"
110 "peer selection (only available if the asmap config flag is set)"},
131 {
RPCResult::Type::BOOL,
"bip152_hb_to",
"Whether we selected peer as (compact blocks) high-bandwidth peer"},
132 {
RPCResult::Type::BOOL,
"bip152_hb_from",
"Whether peer selected us as (compact blocks) high-bandwidth peer"},
134 {
RPCResult::Type::NUM,
"synced_headers",
true,
"The last header we have in common with this peer"},
135 {
RPCResult::Type::NUM,
"synced_blocks",
true,
"The last block we have in common with this peer"},
140 {
RPCResult::Type::BOOL,
"addr_relay_enabled",
true,
"Whether we participate in address relay with this peer"},
141 {
RPCResult::Type::NUM,
"addr_processed",
true,
"The total number of addresses processed, excluding those dropped due to rate limiting"},
142 {
RPCResult::Type::NUM,
"addr_rate_limited",
true,
"The total number of addresses dropped due to rate limiting"},
143 {
RPCResult::Type::ARR,
"permissions",
"Any special permissions that have been granted to this peer",
147 {
RPCResult::Type::NUM,
"minfeefilter",
"The minimum fee rate for transactions this peer accepts"},
151 "When a message type is not listed in this json object, the bytes sent are 0.\n"
152 "Only known message types can appear as keys in the object."}
157 "When a message type is not listed in this json object, the bytes received are 0.\n"
158 "Only known message types can appear as keys in the object and all bytes received\n"
162 "Please note this output is unlikely to be stable in upcoming releases as we iterate to\n"
163 "best capture connection behaviors."},
177 std::vector<CNodeStats> vstats;
186 obj.
pushKV(
"id", stats.nodeid);
187 obj.
pushKV(
"addr", stats.m_addr_name);
188 if (stats.addrBind.IsValid()) {
189 obj.
pushKV(
"addrbind", stats.addrBind.ToString());
191 if (!(stats.addrLocal.empty())) {
192 obj.
pushKV(
"addrlocal", stats.addrLocal);
195 if (stats.m_mapped_as != 0) {
196 obj.
pushKV(
"mapped_as", uint64_t(stats.m_mapped_as));
200 obj.
pushKV(
"relaytxes", stats.fRelayTxes);
205 obj.
pushKV(
"bytessent", stats.nSendBytes);
206 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
208 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
209 if (stats.m_last_ping_time > 0us) {
212 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
218 obj.
pushKV(
"version", stats.nVersion);
222 obj.
pushKV(
"subver", stats.cleanSubVer);
223 obj.
pushKV(
"inbound", stats.fInbound);
224 obj.
pushKV(
"bip152_hb_to", stats.m_bip152_highbandwidth_to);
225 obj.
pushKV(
"bip152_hb_from", stats.m_bip152_highbandwidth_from);
234 obj.
pushKV(
"inflight", heights);
243 obj.
pushKV(
"permissions", permissions);
247 for (
const auto& i : stats.mapSendBytesPerMsgCmd) {
249 sendPerMsgCmd.
pushKV(i.first, i.second);
251 obj.
pushKV(
"bytessent_per_msg", sendPerMsgCmd);
254 for (
const auto& i : stats.mapRecvBytesPerMsgCmd) {
256 recvPerMsgCmd.
pushKV(i.first, i.second);
258 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgCmd);
272 "\nAttempts to add or remove a node from the addnode list.\n"
273 "Or try a connection to a node once.\n"
274 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n"
275 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n" +
277 " and are counted separately from the -maxconnections limit.\n",
289 std::string strCommand;
290 if (!request.params[1].isNull())
291 strCommand = request.params[1].
get_str();
292 if (strCommand !=
"onetry" && strCommand !=
"add" && strCommand !=
"remove") {
293 throw std::runtime_error(
300 std::string strNode = request.params[0].get_str();
302 if (strCommand ==
"onetry")
309 if (strCommand ==
"add")
311 if (!connman.
AddNode(strNode)) {
315 else if(strCommand ==
"remove")
330 "\nOpen an outbound connection to a specified node. This RPC is for testing only.\n",
342 HelpExampleCli(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
343 +
HelpExampleRpc(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
348 throw std::runtime_error(
"addconnection is for regression testing (-regtest mode) only.");
351 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});
352 const std::string address = request.params[0].get_str();
353 const std::string conn_type_in{
TrimString(request.params[1].get_str())};
355 if (conn_type_in ==
"outbound-full-relay") {
357 }
else if (conn_type_in ==
"block-relay-only") {
359 }
else if (conn_type_in ==
"addr-fetch") {
361 }
else if (conn_type_in ==
"feeler") {
370 const bool success = connman.
AddConnection(address, conn_type);
376 info.
pushKV(
"address", address);
377 info.
pushKV(
"connection_type", conn_type_in);
387 "\nImmediately disconnects from the specified peer node.\n"
388 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
389 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
407 const UniValue &address_arg = request.params[0];
408 const UniValue &id_arg = request.params[1];
433 "\nReturns information about the given added node, or all added nodes\n"
434 "(note that onetry addnodes are not listed here)\n",
467 if (!request.params[0].isNull()) {
470 if (info.strAddedNode == request.params[0].get_str()) {
471 vInfo.assign(1, info);
485 obj.
pushKV(
"addednode", info.strAddedNode);
486 obj.
pushKV(
"connected", info.fConnected);
488 if (info.fConnected) {
490 address.
pushKV(
"address", info.resolvedAddress.ToString());
491 address.
pushKV(
"connected", info.fInbound ?
"inbound" :
"outbound");
494 obj.
pushKV(
"addresses", addresses);
506 "\nReturns information about network traffic, including bytes in, bytes out,\n"
507 "and current time.\n",
547 obj.
pushKV(
"uploadtarget", outboundLimit);
556 for (
int n = 0; n <
NET_MAX; ++n) {
575 "Returns an object containing various state info regarding P2P networking.\n",
584 {
RPCResult::Type::ARR,
"localservicesnames",
"the services we offer to the network, in human-readable form",
601 {
RPCResult::Type::STR,
"proxy",
"(\"host:port\") the proxy that is used for this network, or empty if none"},
637 obj.
pushKV(
"localrelay", !
node.peerman->IgnoresIncomingTxs());
641 obj.
pushKV(
"networkactive",
node.connman->GetNetworkActive());
652 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
655 rec.
pushKV(
"address", item.first.ToString());
656 rec.
pushKV(
"port", item.second.nPort);
657 rec.
pushKV(
"score", item.second.nScore);
661 obj.
pushKV(
"localaddresses", localAddresses);
671 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
675 {
"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)"},
686 std::string strCommand;
687 if (!request.params[1].isNull())
688 strCommand = request.params[1].
get_str();
689 if (strCommand !=
"add" && strCommand !=
"remove") {
699 bool isSubnet =
false;
701 if (request.params[0].get_str().find(
'/') != std::string::npos)
706 LookupHost(request.params[0].get_str(), resolved,
false);
715 if (strCommand ==
"add")
717 if (isSubnet ?
node.banman->IsBanned(subNet) :
node.banman->IsBanned(netAddr)) {
722 if (!request.params[2].isNull())
723 banTime = request.params[2].get_int64();
726 if (request.params[3].isTrue())
732 node.connman->DisconnectNode(subNet);
737 node.connman->DisconnectNode(netAddr);
741 else if(strCommand ==
"remove")
743 if (!( isSubnet ?
node.banman->Unban(subNet) :
node.banman->Unban(netAddr) )) {
755 "\nList all manually banned IPs/Subnets.\n",
780 node.banman->GetBanned(banMap);
781 const int64_t current_time{
GetTime()};
784 for (
const auto& entry : banMap)
786 const CBanEntry& banEntry = entry.second;
788 rec.
pushKV(
"address", entry.first.ToString());
797 return bannedAddresses;
805 "\nClear all banned IPs.\n",
819 node.banman->ClearBanned();
829 "\nDisable/enable all p2p network activity.\n",
850 "\nReturn known addresses, which can potentially be used to find new nodes in the network.\n",
871 +
HelpExampleCli(
"-named getnodeaddresses",
"network=onion count=12")
880 const int count{request.params[0].isNull() ? 1 : request.params[0].get_int()};
883 const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{
ParseNetwork(request.params[1].get_str())}};
892 for (
const CAddress& addr : vAddr) {
894 obj.
pushKV(
"time", (
int)addr.nTime);
895 obj.
pushKV(
"services", (uint64_t)addr.nServices);
896 obj.
pushKV(
"address", addr.ToStringIP());
897 obj.
pushKV(
"port", addr.GetPort());
909 "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
918 {
RPCResult::Type::BOOL,
"success",
"whether the peer address was successfully added to the address manager"},
932 const std::string& addr_string{request.params[0].get_str()};
933 const uint16_t port{
static_cast<uint16_t
>(request.params[1].get_int())};
934 const bool tried{request.params[2].isTrue()};
940 if (
LookupHost(addr_string, net_addr,
false)) {
945 if (
node.addrman->Add({address}, address)) {
949 node.addrman->Good(address);
954 obj.
pushKV(
"success", success);
967 {
"network", &
ping, },
984 for (
const auto& c : commands) {
985 t.appendCommand(c.name, &c);
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
bool DisconnectNode(const std::string &node)
virtual void SendPings()=0
Send ping message to all peers.
static RPCHelpMan getnettotals()
std::vector< int > vHeightInFlight
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.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
enum Network ParseNetwork(const std::string &net_in)
static RPCHelpMan getaddednodeinfo()
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
Mutex g_maplocalhost_mutex
const std::vector< std::string > NET_PERMISSIONS_DOC
std::chrono::seconds GetMaxOutboundTimeframe() const
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
const std::string NET_MESSAGE_COMMAND_OTHER
static RPCHelpMan setnetworkactive()
const UniValue NullUniValue
PeerManager & EnsurePeerman(const NodeContext &node)
uint64_t m_addr_rate_limited
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
static RPCHelpMan getconnectioncount()
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
NodeContext struct containing references to chain state and connection state.
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
static RPCHelpMan setban()
static RPCHelpMan clearbanned()
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
ServiceFlags
nServices flags
std::string TrimString(const std::string &str, const std::string &pattern=" \f\n\r\t\v")
bool m_addr_relay_enabled
static UniValue GetNetworksInfo()
bool pushKV(const std::string &key, const UniValue &val)
std::string ToStringIPPort() const
UniValue ValueFromAmount(const CAmount amount)
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
void GetNodeStats(std::vector< CNodeStats > &vstats) const
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
NodeContext & EnsureAnyNodeContext(const std::any &context)
const std::string & get_str() const
const std::vector< std::string > CONNECTION_TYPE_DOC
std::string ToString() const
int64_t get_int64() const
const std::string CURRENCY_UNIT
bool LookupSubNet(const std::string &subnet_str, CSubNet &subnet_out)
Parse and resolve a specified subnet string into the appropriate internal representation.
bool IsReachable(enum Network net)
static RPCHelpMan addconnection()
@ RPC_DATABASE_ERROR
Database error.
static const std::string REGTEST
@ STR_HEX
Special string with only hex chars.
std::string NetworkIDString() const
Return the network string.
uint64_t GetTotalBytesRecv() const
CConnman & EnsureConnman(const NodeContext &node)
@ NUM_TIME
Special numeric to denote unix epoch time.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
uint64_t m_addr_processed
uint64_t GetMaxOutboundTarget() const
bool RemoveAddedNode(const std::string &node)
void RegisterNetRPCCommands(CRPCTable &t)
Register P2P networking RPC commands.
static RPCHelpMan addpeeraddress()
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
static RPCHelpMan disconnectnode()
CFeeRate incrementalRelayFee
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
int64_t GetAdjustedTime()
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
A CService with information about it as peer.
void SetNetworkActive(bool active)
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
UniValue JSONRPCError(int code, const std::string &message)
bool randomize_credentials
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
@ RPC_CLIENT_NODE_ALREADY_ADDED
Node is already added.
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
@ RPC_CLIENT_NODE_CAPACITY_REACHED
Max number of outbound or block-relay connections already open.
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
bool push_back(const UniValue &val)
const CChainParams & Params()
Return the currently selected parameters.
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
@ RPC_CLIENT_NODE_NOT_ADDED
Node has not been added before.
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
bool AddNode(const std::string &node)
std::chrono::microseconds m_ping_wait
static RPCHelpMan listbanned()
static RPCHelpMan getpeerinfo()
@ OBJ_DYN
Special dictionary with keys that are not literals.
bool GetNetworkActive() const
@ RPC_CLIENT_NODE_NOT_CONNECTED
Node to disconnect not found in connected nodes.
std::map< CSubNet, CBanEntry > banmap_t
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
std::string GetNetworkName(enum Network net)
static path absolute(const path &p)
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
uint64_t GetTotalBytesSent() const
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
ConnectionType
Different types of connections to a peer.
static RPCHelpMan getnetworkinfo()
size_t GetNodeCount(ConnectionDirection) const
int64_t GetTimeMillis()
Returns the system time (not mockable)
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.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
static RPCHelpMan getnodeaddresses()
@ RPC_CLIENT_INVALID_IP_OR_SUBNET
Invalid IP/Subnet.
static RPCHelpMan addnode()
static const int PROTOCOL_VERSION
network protocol versioning
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...