27#include <validation.h>
36 "outbound-full-relay (default automatic connections)",
37 "block-relay-only (does not relay transactions or addresses)",
38 "inbound (initiated by the peer)",
39 "manual (added via addnode RPC or -addnode/-connect configuration options)",
40 "addr-fetch (short-lived automatic connection for soliciting addresses)",
41 "feeler (short-lived automatic connection for testing addresses)"
63 "\nReturns the number of connections to other nodes.\n",
85 "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
86 "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
87 "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n",
109 "\nReturns data about each connected network node as a json array of objects.\n",
119 {
RPCResult::Type::STR,
"addrbind",
true,
"(ip:port) Bind address of the connection to the peer"},
122 {
RPCResult::Type::NUM,
"mapped_as",
true,
"The AS in the BGP route to the peer used for diversifying\n"
123 "peer selection (only available if the asmap config flag is set)"},
144 {
RPCResult::Type::BOOL,
"bip152_hb_to",
"Whether we selected peer as (compact blocks) high-bandwidth peer"},
145 {
RPCResult::Type::BOOL,
"bip152_hb_from",
"Whether peer selected us as (compact blocks) high-bandwidth peer"},
153 {
RPCResult::Type::BOOL,
"addr_relay_enabled",
"Whether we participate in address relay with this peer"},
154 {
RPCResult::Type::NUM,
"addr_processed",
"The total number of addresses processed, excluding those dropped due to rate limiting"},
155 {
RPCResult::Type::NUM,
"addr_rate_limited",
"The total number of addresses dropped due to rate limiting"},
156 {
RPCResult::Type::ARR,
"permissions",
"Any special permissions that have been granted to this peer",
160 {
RPCResult::Type::NUM,
"minfeefilter",
"The minimum fee rate for transactions this peer accepts"},
164 "When a message type is not listed in this json object, the bytes sent are 0.\n"
165 "Only known message types can appear as keys in the object."}
170 "When a message type is not listed in this json object, the bytes received are 0.\n"
171 "Only known message types can appear as keys in the object and all bytes received\n"
175 "Please note this output is unlikely to be stable in upcoming releases as we iterate to\n"
176 "best capture connection behaviors."},
190 std::vector<CNodeStats> vstats;
199 obj.
pushKV(
"id", stats.nodeid);
200 obj.
pushKV(
"addr", stats.m_addr_name);
201 if (stats.addrBind.IsValid()) {
202 obj.
pushKV(
"addrbind", stats.addrBind.ToString());
204 if (!(stats.addrLocal.empty())) {
205 obj.
pushKV(
"addrlocal", stats.addrLocal);
208 if (stats.m_mapped_as != 0) {
209 obj.
pushKV(
"mapped_as", uint64_t(stats.m_mapped_as));
213 obj.
pushKV(
"relaytxes", stats.fRelayTxes);
214 obj.
pushKV(
"lastsend", stats.nLastSend);
215 obj.
pushKV(
"lastrecv", stats.nLastRecv);
216 obj.
pushKV(
"last_transaction", stats.nLastTXTime);
217 obj.
pushKV(
"last_block", stats.nLastBlockTime);
218 obj.
pushKV(
"bytessent", stats.nSendBytes);
219 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
220 obj.
pushKV(
"conntime", stats.nTimeConnected);
221 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
222 if (stats.m_last_ping_time > 0us) {
225 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
231 obj.
pushKV(
"version", stats.nVersion);
235 obj.
pushKV(
"subver", stats.cleanSubVer);
236 obj.
pushKV(
"inbound", stats.fInbound);
237 obj.
pushKV(
"bip152_hb_to", stats.m_bip152_highbandwidth_to);
238 obj.
pushKV(
"bip152_hb_from", stats.m_bip152_highbandwidth_from);
247 obj.
pushKV(
"inflight", heights);
256 obj.
pushKV(
"permissions", permissions);
260 for (
const auto& i : stats.mapSendBytesPerMsgCmd) {
262 sendPerMsgCmd.
pushKV(i.first, i.second);
264 obj.
pushKV(
"bytessent_per_msg", sendPerMsgCmd);
267 for (
const auto& i : stats.mapRecvBytesPerMsgCmd) {
269 recvPerMsgCmd.
pushKV(i.first, i.second);
271 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgCmd);
285 "\nAttempts to add or remove a node from the addnode list.\n"
286 "Or try a connection to a node once.\n"
287 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n"
288 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n" +
290 " and are counted separately from the -maxconnections limit.\n",
302 std::string strCommand;
303 if (!request.params[1].isNull())
304 strCommand = request.params[1].
get_str();
305 if (strCommand !=
"onetry" && strCommand !=
"add" && strCommand !=
"remove") {
306 throw std::runtime_error(
313 std::string strNode = request.params[0].get_str();
315 if (strCommand ==
"onetry")
322 if (strCommand ==
"add")
324 if (!connman.
AddNode(strNode)) {
328 else if(strCommand ==
"remove")
343 "\nOpen an outbound connection to a specified node. This RPC is for testing only.\n",
355 HelpExampleCli(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
356 +
HelpExampleRpc(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
361 throw std::runtime_error(
"addconnection is for regression testing (-regtest mode) only.");
364 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});
365 const std::string address = request.params[0].get_str();
366 const std::string conn_type_in{
TrimString(request.params[1].get_str())};
368 if (conn_type_in ==
"outbound-full-relay") {
370 }
else if (conn_type_in ==
"block-relay-only") {
372 }
else if (conn_type_in ==
"addr-fetch") {
381 const bool success = connman.
AddConnection(address, conn_type);
387 info.
pushKV(
"address", address);
388 info.
pushKV(
"connection_type", conn_type_in);
398 "\nImmediately disconnects from the specified peer node.\n"
399 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
400 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
418 const UniValue &address_arg = request.params[0];
419 const UniValue &id_arg = request.params[1];
444 "\nReturns information about the given added node, or all added nodes\n"
445 "(note that onetry addnodes are not listed here)\n",
478 if (!request.params[0].isNull()) {
481 if (info.strAddedNode == request.params[0].get_str()) {
482 vInfo.assign(1, info);
496 obj.
pushKV(
"addednode", info.strAddedNode);
497 obj.
pushKV(
"connected", info.fConnected);
499 if (info.fConnected) {
501 address.
pushKV(
"address", info.resolvedAddress.ToString());
502 address.
pushKV(
"connected", info.fInbound ?
"inbound" :
"outbound");
505 obj.
pushKV(
"addresses", addresses);
517 "\nReturns information about network traffic, including bytes in, bytes out,\n"
518 "and current time.\n",
558 obj.
pushKV(
"uploadtarget", outboundLimit);
567 for (
int n = 0; n <
NET_MAX; ++n) {
586 "Returns an object containing various state info regarding P2P networking.\n",
595 {
RPCResult::Type::ARR,
"localservicesnames",
"the services we offer to the network, in human-readable form",
612 {
RPCResult::Type::STR,
"proxy",
"(\"host:port\") the proxy that is used for this network, or empty if none"},
648 obj.
pushKV(
"localrelay", !
node.peerman->IgnoresIncomingTxs());
652 obj.
pushKV(
"networkactive",
node.connman->GetNetworkActive());
663 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
666 rec.
pushKV(
"address", item.first.ToString());
667 rec.
pushKV(
"port", item.second.nPort);
668 rec.
pushKV(
"score", item.second.nScore);
672 obj.
pushKV(
"localaddresses", localAddresses);
682 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
686 {
"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)"},
697 std::string strCommand;
698 if (!request.params[1].isNull())
699 strCommand = request.params[1].
get_str();
700 if (strCommand !=
"add" && strCommand !=
"remove") {
701 throw std::runtime_error(
help.ToString());
710 bool isSubnet =
false;
712 if (request.params[0].get_str().find(
'/') != std::string::npos)
717 LookupHost(request.params[0].get_str(), resolved,
false);
726 if (strCommand ==
"add")
728 if (isSubnet ?
node.banman->IsBanned(subNet) :
node.banman->IsBanned(netAddr)) {
733 if (!request.params[2].isNull())
734 banTime = request.params[2].get_int64();
736 bool absolute =
false;
737 if (request.params[3].isTrue())
741 node.banman->Ban(subNet, banTime, absolute);
743 node.connman->DisconnectNode(subNet);
746 node.banman->Ban(netAddr, banTime, absolute);
748 node.connman->DisconnectNode(netAddr);
752 else if(strCommand ==
"remove")
754 if (!( isSubnet ?
node.banman->Unban(subNet) :
node.banman->Unban(netAddr) )) {
766 "\nList all manually banned IPs/Subnets.\n",
791 node.banman->GetBanned(banMap);
792 const int64_t current_time{
GetTime()};
795 for (
const auto& entry : banMap)
797 const CBanEntry& banEntry = entry.second;
799 rec.
pushKV(
"address", entry.first.ToString());
808 return bannedAddresses;
816 "\nClear all banned IPs.\n",
830 node.banman->ClearBanned();
840 "\nDisable/enable all p2p network activity.\n",
861 "\nReturn known addresses, which can potentially be used to find new nodes in the network.\n",
882 +
HelpExampleCli(
"-named getnodeaddresses",
"network=onion count=12")
891 const int count{request.params[0].isNull() ? 1 : request.params[0].get_int()};
894 const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{
ParseNetwork(request.params[1].get_str())}};
903 for (
const CAddress& addr : vAddr) {
905 obj.
pushKV(
"time", (
int)addr.nTime);
906 obj.
pushKV(
"services", (uint64_t)addr.nServices);
907 obj.
pushKV(
"address", addr.ToStringIP());
908 obj.
pushKV(
"port", addr.GetPort());
920 "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
929 {
RPCResult::Type::BOOL,
"success",
"whether the peer address was successfully added to the address manager"},
943 const std::string& addr_string{request.params[0].get_str()};
944 const uint16_t port{
static_cast<uint16_t
>(request.params[1].get_int())};
945 const bool tried{request.params[2].isTrue()};
951 if (
LookupHost(addr_string, net_addr,
false)) {
956 if (
node.addrman->Add({address}, address)) {
960 node.addrman->Good(address);
965 obj.
pushKV(
"success", success);
978 {
"network", &
ping, },
995 for (
const auto& c : commands) {
NodeContext & EnsureAnyNodeContext(const std::any &context)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
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.
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
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
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
size_t GetNodeCount(ConnectionDirection) const
void GetNodeStats(std::vector< CNodeStats > &vstats) const
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)
uint64_t GetTotalBytesSent() const
bool RemoveAddedNode(const std::string &node)
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
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.
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 const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
UniValue ValueFromAmount(const CAmount amount)
const std::string CURRENCY_UNIT
RecursiveMutex cs_mapLocalHost
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
const std::string NET_MESSAGE_COMMAND_OTHER
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
bool IsReachable(enum Network net)
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
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.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
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)
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)
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::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
CFeeRate incrementalRelayFee
ServiceFlags
nServices flags
UniValue JSONRPCError(int code, const std::string &message)
const std::vector< std::string > CONNECTION_TYPE_DOC
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()
PeerManager & EnsurePeerman(const NodeContext &node)
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()
CConnman & EnsureConnman(const NodeContext &node)
@ 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.
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
std::vector< int > vHeightInFlight
bool m_addr_relay_enabled
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
NodeContext struct containing references to chain state and connection state.
@ 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.
int64_t GetTimeMillis()
Returns the system time (not mockable)
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
int64_t GetAdjustedTime()
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
const UniValue NullUniValue
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
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.