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",
122 {
RPCResult::Type::NUM,
"mapped_as",
"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::ARR,
"permissions",
"Any special permissions that have been granted to this peer",
157 {
RPCResult::Type::NUM,
"minfeefilter",
"The minimum fee rate for transactions this peer accepts"},
161 "When a message type is not listed in this json object, the bytes sent are 0.\n" 162 "Only known message types can appear as keys in the object."}
167 "When a message type is not listed in this json object, the bytes received are 0.\n" 168 "Only known message types can appear as keys in the object and all bytes received\n" 172 "Please note this output is unlikely to be stable in upcoming releases as we iterate to\n" 173 "best capture connection behaviors."},
187 std::vector<CNodeStats> vstats;
196 obj.
pushKV(
"id", stats.nodeid);
197 obj.
pushKV(
"addr", stats.addrName);
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));
210 obj.
pushKV(
"relaytxes", stats.fRelayTxes);
211 obj.
pushKV(
"lastsend", stats.nLastSend);
212 obj.
pushKV(
"lastrecv", stats.nLastRecv);
213 obj.
pushKV(
"last_transaction", stats.nLastTXTime);
214 obj.
pushKV(
"last_block", stats.nLastBlockTime);
215 obj.
pushKV(
"bytessent", stats.nSendBytes);
216 obj.
pushKV(
"bytesrecv", stats.nRecvBytes);
217 obj.
pushKV(
"conntime", stats.nTimeConnected);
218 obj.
pushKV(
"timeoffset", stats.nTimeOffset);
219 if (stats.m_last_ping_time > 0us) {
222 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
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);
244 obj.
pushKV(
"inflight", heights);
252 obj.
pushKV(
"permissions", permissions);
256 for (
const auto& i : stats.mapSendBytesPerMsgCmd) {
258 sendPerMsgCmd.
pushKV(i.first, i.second);
260 obj.
pushKV(
"bytessent_per_msg", sendPerMsgCmd);
263 for (
const auto& i : stats.mapRecvBytesPerMsgCmd) {
265 recvPerMsgCmd.
pushKV(i.first, i.second);
267 obj.
pushKV(
"bytesrecv_per_msg", recvPerMsgCmd);
281 "\nAttempts to add or remove a node from the addnode list.\n" 282 "Or try a connection to a node once.\n" 283 "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n" 284 "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n" +
286 " and are counted separately from the -maxconnections limit.\n",
298 std::string strCommand;
299 if (!request.params[1].isNull())
300 strCommand = request.params[1].
get_str();
301 if (strCommand !=
"onetry" && strCommand !=
"add" && strCommand !=
"remove") {
302 throw std::runtime_error(
309 std::string strNode = request.params[0].get_str();
311 if (strCommand ==
"onetry")
318 if (strCommand ==
"add")
320 if (!connman.
AddNode(strNode)) {
324 else if(strCommand ==
"remove")
339 "\nOpen an outbound connection to a specified node. This RPC is for testing only.\n",
351 HelpExampleCli(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
352 +
HelpExampleRpc(
"addconnection",
"\"192.168.0.6:8333\" \"outbound-full-relay\"")
357 throw std::runtime_error(
"addconnection is for regression testing (-regtest mode) only.");
360 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});
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") {
377 const bool success = connman.
AddConnection(address, conn_type);
383 info.
pushKV(
"address", address);
384 info.
pushKV(
"connection_type", conn_type_in);
394 "\nImmediately disconnects from the specified peer node.\n" 395 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n" 396 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n",
414 const UniValue &address_arg = request.params[0];
415 const UniValue &id_arg = request.params[1];
440 "\nReturns information about the given added node, or all added nodes\n" 441 "(note that onetry addnodes are not listed here)\n",
474 if (!request.params[0].isNull()) {
477 if (info.strAddedNode == request.params[0].get_str()) {
478 vInfo.assign(1, info);
492 obj.
pushKV(
"addednode", info.strAddedNode);
493 obj.
pushKV(
"connected", info.fConnected);
495 if (info.fConnected) {
497 address.
pushKV(
"address", info.resolvedAddress.ToString());
498 address.
pushKV(
"connected", info.fInbound ?
"inbound" :
"outbound");
501 obj.
pushKV(
"addresses", addresses);
513 "\nReturns information about network traffic, including bytes in, bytes out,\n" 514 "and current time.\n",
554 obj.
pushKV(
"uploadtarget", outboundLimit);
563 for (
int n = 0; n <
NET_MAX; ++n) {
582 "Returns an object containing various state info regarding P2P networking.\n",
591 {
RPCResult::Type::ARR,
"localservicesnames",
"the services we offer to the network, in human-readable form",
608 {
RPCResult::Type::STR,
"proxy",
"(\"host:port\") the proxy that is used for this network, or empty if none"},
644 obj.
pushKV(
"localrelay", !
node.peerman->IgnoresIncomingTxs());
648 obj.
pushKV(
"networkactive",
node.connman->GetNetworkActive());
659 for (
const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
662 rec.
pushKV(
"address", item.first.ToString());
663 rec.
pushKV(
"port", item.second.nPort);
664 rec.
pushKV(
"score", item.second.nScore);
668 obj.
pushKV(
"localaddresses", localAddresses);
678 "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
682 {
"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)"},
693 std::string strCommand;
694 if (!request.params[1].isNull())
695 strCommand = request.params[1].
get_str();
696 if (strCommand !=
"add" && strCommand !=
"remove") {
706 bool isSubnet =
false;
708 if (request.params[0].get_str().find(
'/') != std::string::npos)
713 LookupHost(request.params[0].get_str(), resolved,
false);
722 if (strCommand ==
"add")
724 if (isSubnet ?
node.banman->IsBanned(subNet) :
node.banman->IsBanned(netAddr)) {
729 if (!request.params[2].isNull())
730 banTime = request.params[2].get_int64();
732 bool absolute =
false;
733 if (request.params[3].isTrue())
737 node.banman->Ban(subNet, banTime, absolute);
739 node.connman->DisconnectNode(subNet);
742 node.banman->Ban(netAddr, banTime, absolute);
744 node.connman->DisconnectNode(netAddr);
748 else if(strCommand ==
"remove")
750 if (!( isSubnet ?
node.banman->Unban(subNet) :
node.banman->Unban(netAddr) )) {
762 "\nList all manually banned IPs/Subnets.\n",
787 node.banman->GetBanned(banMap);
788 const int64_t current_time{
GetTime()};
791 for (
const auto& entry : banMap)
793 const CBanEntry& banEntry = entry.second;
795 rec.
pushKV(
"address", entry.first.ToString());
804 return bannedAddresses;
812 "\nClear all banned IPs.\n",
826 node.banman->ClearBanned();
836 "\nDisable/enable all p2p network activity.\n",
857 "\nReturn known addresses, which can potentially be used to find new nodes in the network.\n",
878 +
HelpExampleCli(
"-named getnodeaddresses",
"network=onion count=12")
887 const int count{request.params[0].isNull() ? 1 : request.params[0].get_int()};
890 const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{
ParseNetwork(request.params[1].get_str())}};
899 for (
const CAddress& addr : vAddr) {
901 obj.
pushKV(
"time", (
int)addr.nTime);
902 obj.
pushKV(
"services", (uint64_t)addr.nServices);
903 obj.
pushKV(
"address", addr.ToStringIP());
904 obj.
pushKV(
"port", addr.GetPort());
916 "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
924 {
RPCResult::Type::BOOL,
"success",
"whether the peer address was successfully added to the address manager"},
938 const std::string& addr_string{request.params[0].get_str()};
939 const uint16_t port{
static_cast<uint16_t
>(request.params[1].get_int())};
945 if (
LookupHost(addr_string, net_addr,
false)) {
950 if (
node.addrman->Add(address, address)) success =
true;
953 obj.
pushKV(
"success", success);
966 {
"network", &
ping, },
983 for (
const auto& c : commands) {
std::string NetworkIDString() const
Return the network string.
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
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 ...
Node has not been added before.
const std::vector< std::string > NET_PERMISSIONS_DOC
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret, DNSLookupFn dns_lookup_function)
Parse and resolve a specified subnet string into the appropriate internal representation.
ServiceFlags
nServices flags
static RPCHelpMan clearbanned()
A set of addresses that represent the hash of a string or FQDN.
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
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
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
static const std::string REGTEST
int64_t GetTimeMillis()
Returns the system time (not mockable)
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
uint64_t GetTotalBytesRecv() const
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
void RegisterNetRPCCommands(CRPCTable &t)
Register P2P networking RPC commands.
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 get_int64() const
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are: ...
static RPCHelpMan getnettotals()
PeerManager & EnsurePeerman(const NodeContext &node)
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
Invalid, missing or duplicate parameter.
std::string TrimString(const std::string &str, const std::string &pattern=" \\\)
RecursiveMutex cs_mapLocalHost
bool DisconnectNode(const std::string &node)
static RPCHelpMan getpeerinfo()
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
UniValue JSONRPCError(int code, const std::string &message)
bool push_back(const UniValue &val)
static RPCHelpMan getnodeaddresses()
Special string with only hex chars.
uint64_t m_addr_processed
NodeContext struct containing references to chain state and connection state.
bool AddNode(const std::string &node)
bool randomize_credentials
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
static RPCHelpMan disconnectnode()
A CService with information about it as peer.
const std::string CURRENCY_UNIT
static RPCHelpMan setban()
static RPCHelpMan addnode()
bool pushKV(const std::string &key, const UniValue &val)
void SetNetworkActive(bool active)
bool GetNetworkActive() const
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Special numeric to denote unix epoch time.
static RPCHelpMan setnetworkactive()
CFeeRate incrementalRelayFee
const std::string NET_MESSAGE_COMMAND_OTHER
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)
Helper to count the seconds of a duration.
CConnman & EnsureConnman(const NodeContext &node)
std::chrono::microseconds m_ping_wait
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
enum Network ParseNetwork(const std::string &net_in)
const std::vector< std::string > CONNECTION_TYPE_DOC
bool RemoveAddedNode(const std::string &node)
size_t GetNodeCount(ConnectionDirection) const
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.
ConnectionType
Different types of connections to a peer.
const CChainParams & Params()
Return the currently selected parameters.
static const int PROTOCOL_VERSION
network protocol versioning
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
int64_t GetAdjustedTime()
std::string ToStringIPPort() const
static RPCHelpMan getnetworkinfo()
Node to disconnect not found in connected nodes.
std::chrono::seconds GetMaxOutboundTimeframe() const
UniValue ValueFromAmount(const CAmount amount)
const UniValue NullUniValue
These are the default connections that we use to connect with the network.
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true...
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
static RPCHelpMan getaddednodeinfo()
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
static RPCHelpMan getconnectioncount()
std::map< CSubNet, CBanEntry > banmap_t
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
NodeContext & EnsureAnyNodeContext(const std::any &context)
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
No valid connection manager instance found.
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
static RPCHelpMan listbanned()
std::string GetNetworkName(enum Network net)
uint64_t GetMaxOutboundTarget() const
std::vector< int > vHeightInFlight
Special dictionary with keys that are not literals.
We use block-relay-only connections to help prevent against partition attacks.
AddrFetch connections are short lived connections used to solicit addresses from peers.
int64_t GetTime()
Return system time (or mocked time, if set)
uint64_t GetTotalBytesSent() const
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
static RPCHelpMan addconnection()
Addresses from these networks are not publicly routable on the global Internet.