Bitcoin Core  22.99.0
P2P Digital Currency
net.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <rpc/server.h>
6 
7 #include <addrman.h>
8 #include <banman.h>
9 #include <chainparams.h>
10 #include <clientversion.h>
11 #include <core_io.h>
12 #include <net_permissions.h>
13 #include <net_processing.h>
14 #include <net_types.h> // For banmap_t
15 #include <netbase.h>
16 #include <node/context.h>
17 #include <policy/settings.h>
18 #include <rpc/blockchain.h>
19 #include <rpc/protocol.h>
20 #include <rpc/server_util.h>
21 #include <rpc/util.h>
22 #include <sync.h>
23 #include <timedata.h>
24 #include <util/strencodings.h>
25 #include <util/string.h>
26 #include <util/translation.h>
27 #include <validation.h>
28 #include <version.h>
29 #include <warnings.h>
30 
31 #include <optional>
32 
33 #include <univalue.h>
34 
35 using node::NodeContext;
36 
37 const std::vector<std::string> CONNECTION_TYPE_DOC{
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)"
44 };
45 
47 {
48  return RPCHelpMan{"getconnectioncount",
49  "\nReturns the number of connections to other nodes.\n",
50  {},
51  RPCResult{
52  RPCResult::Type::NUM, "", "The connection count"
53  },
55  HelpExampleCli("getconnectioncount", "")
56  + HelpExampleRpc("getconnectioncount", "")
57  },
58  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
59 {
60  NodeContext& node = EnsureAnyNodeContext(request.context);
61  const CConnman& connman = EnsureConnman(node);
62 
63  return (int)connman.GetNodeCount(ConnectionDirection::Both);
64 },
65  };
66 }
67 
68 static RPCHelpMan ping()
69 {
70  return RPCHelpMan{"ping",
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",
74  {},
77  HelpExampleCli("ping", "")
78  + HelpExampleRpc("ping", "")
79  },
80  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
81 {
82  NodeContext& node = EnsureAnyNodeContext(request.context);
83  PeerManager& peerman = EnsurePeerman(node);
84 
85  // Request that each node send a ping during next message processing pass
86  peerman.SendPings();
87  return NullUniValue;
88 },
89  };
90 }
91 
93 {
94  return RPCHelpMan{
95  "getpeerinfo",
96  "\nReturns data about each connected network node as a json array of objects.\n",
97  {},
98  RPCResult{
99  RPCResult::Type::ARR, "", "",
100  {
101  {RPCResult::Type::OBJ, "", "",
102  {
103  {
104  {RPCResult::Type::NUM, "id", "Peer index"},
105  {RPCResult::Type::STR, "addr", "(host:port) The IP address and port of the peer"},
106  {RPCResult::Type::STR, "addrbind", /*optional=*/true, "(ip:port) Bind address of the connection to the peer"},
107  {RPCResult::Type::STR, "addrlocal", /*optional=*/true, "(ip:port) Local address as reported by the peer"},
108  {RPCResult::Type::STR, "network", "Network (" + Join(GetNetworkNames(/* append_unroutable */ true), ", ") + ")"},
109  {RPCResult::Type::NUM, "mapped_as", /*optional=*/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)"},
111  {RPCResult::Type::STR_HEX, "services", "The services offered"},
112  {RPCResult::Type::ARR, "servicesnames", "the services offered, in human-readable form",
113  {
114  {RPCResult::Type::STR, "SERVICE_NAME", "the service name if it is recognised"}
115  }},
116  {RPCResult::Type::BOOL, "relaytxes", "Whether peer has asked us to relay transactions to it"},
117  {RPCResult::Type::NUM_TIME, "lastsend", "The " + UNIX_EPOCH_TIME + " of the last send"},
118  {RPCResult::Type::NUM_TIME, "lastrecv", "The " + UNIX_EPOCH_TIME + " of the last receive"},
119  {RPCResult::Type::NUM_TIME, "last_transaction", "The " + UNIX_EPOCH_TIME + " of the last valid transaction received from this peer"},
120  {RPCResult::Type::NUM_TIME, "last_block", "The " + UNIX_EPOCH_TIME + " of the last block received from this peer"},
121  {RPCResult::Type::NUM, "bytessent", "The total bytes sent"},
122  {RPCResult::Type::NUM, "bytesrecv", "The total bytes received"},
123  {RPCResult::Type::NUM_TIME, "conntime", "The " + UNIX_EPOCH_TIME + " of the connection"},
124  {RPCResult::Type::NUM, "timeoffset", "The time offset in seconds"},
125  {RPCResult::Type::NUM, "pingtime", /*optional=*/true, "ping time (if available)"},
126  {RPCResult::Type::NUM, "minping", /*optional=*/true, "minimum observed ping time (if any at all)"},
127  {RPCResult::Type::NUM, "pingwait", /*optional=*/true, "ping wait (if non-zero)"},
128  {RPCResult::Type::NUM, "version", "The peer version, such as 70001"},
129  {RPCResult::Type::STR, "subver", "The string version"},
130  {RPCResult::Type::BOOL, "inbound", "Inbound (true) or Outbound (false)"},
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"},
133  {RPCResult::Type::NUM, "startingheight", /*optional=*/true, "The starting height (block) of the peer"},
134  {RPCResult::Type::NUM, "synced_headers", /*optional=*/true, "The last header we have in common with this peer"},
135  {RPCResult::Type::NUM, "synced_blocks", /*optional=*/true, "The last block we have in common with this peer"},
136  {RPCResult::Type::ARR, "inflight", /*optional=*/true, "",
137  {
138  {RPCResult::Type::NUM, "n", "The heights of blocks we're currently asking from this peer"},
139  }},
140  {RPCResult::Type::BOOL, "addr_relay_enabled", /*optional=*/true, "Whether we participate in address relay with this peer"},
141  {RPCResult::Type::NUM, "addr_processed", /*optional=*/true, "The total number of addresses processed, excluding those dropped due to rate limiting"},
142  {RPCResult::Type::NUM, "addr_rate_limited", /*optional=*/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",
144  {
145  {RPCResult::Type::STR, "permission_type", Join(NET_PERMISSIONS_DOC, ",\n") + ".\n"},
146  }},
147  {RPCResult::Type::NUM, "minfeefilter", "The minimum fee rate for transactions this peer accepts"},
148  {RPCResult::Type::OBJ_DYN, "bytessent_per_msg", "",
149  {
150  {RPCResult::Type::NUM, "msg", "The total bytes sent aggregated by message type\n"
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."}
153  }},
154  {RPCResult::Type::OBJ_DYN, "bytesrecv_per_msg", "",
155  {
156  {RPCResult::Type::NUM, "msg", "The total bytes received aggregated by message type\n"
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"
159  "of unknown message types are listed under '"+NET_MESSAGE_COMMAND_OTHER+"'."}
160  }},
161  {RPCResult::Type::STR, "connection_type", "Type of connection: \n" + Join(CONNECTION_TYPE_DOC, ",\n") + ".\n"
162  "Please note this output is unlikely to be stable in upcoming releases as we iterate to\n"
163  "best capture connection behaviors."},
164  }},
165  }},
166  },
167  RPCExamples{
168  HelpExampleCli("getpeerinfo", "")
169  + HelpExampleRpc("getpeerinfo", "")
170  },
171  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
172 {
173  NodeContext& node = EnsureAnyNodeContext(request.context);
174  const CConnman& connman = EnsureConnman(node);
175  const PeerManager& peerman = EnsurePeerman(node);
176 
177  std::vector<CNodeStats> vstats;
178  connman.GetNodeStats(vstats);
179 
181 
182  for (const CNodeStats& stats : vstats) {
184  CNodeStateStats statestats;
185  bool fStateStats = peerman.GetNodeStateStats(stats.nodeid, statestats);
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());
190  }
191  if (!(stats.addrLocal.empty())) {
192  obj.pushKV("addrlocal", stats.addrLocal);
193  }
194  obj.pushKV("network", GetNetworkName(stats.m_network));
195  if (stats.m_mapped_as != 0) {
196  obj.pushKV("mapped_as", uint64_t(stats.m_mapped_as));
197  }
198  obj.pushKV("services", strprintf("%016x", stats.nServices));
199  obj.pushKV("servicesnames", GetServicesNames(stats.nServices));
200  obj.pushKV("relaytxes", stats.fRelayTxes);
201  obj.pushKV("lastsend", count_seconds(stats.m_last_send));
202  obj.pushKV("lastrecv", count_seconds(stats.m_last_recv));
203  obj.pushKV("last_transaction", count_seconds(stats.m_last_tx_time));
204  obj.pushKV("last_block", count_seconds(stats.m_last_block_time));
205  obj.pushKV("bytessent", stats.nSendBytes);
206  obj.pushKV("bytesrecv", stats.nRecvBytes);
207  obj.pushKV("conntime", count_seconds(stats.m_connected));
208  obj.pushKV("timeoffset", stats.nTimeOffset);
209  if (stats.m_last_ping_time > 0us) {
210  obj.pushKV("pingtime", CountSecondsDouble(stats.m_last_ping_time));
211  }
212  if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
213  obj.pushKV("minping", CountSecondsDouble(stats.m_min_ping_time));
214  }
215  if (fStateStats && statestats.m_ping_wait > 0s) {
216  obj.pushKV("pingwait", CountSecondsDouble(statestats.m_ping_wait));
217  }
218  obj.pushKV("version", stats.nVersion);
219  // Use the sanitized form of subver here, to avoid tricksy remote peers from
220  // corrupting or modifying the JSON output by putting special characters in
221  // their ver message.
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);
226  if (fStateStats) {
227  obj.pushKV("startingheight", statestats.m_starting_height);
228  obj.pushKV("synced_headers", statestats.nSyncHeight);
229  obj.pushKV("synced_blocks", statestats.nCommonHeight);
230  UniValue heights(UniValue::VARR);
231  for (const int height : statestats.vHeightInFlight) {
232  heights.push_back(height);
233  }
234  obj.pushKV("inflight", heights);
235  obj.pushKV("addr_relay_enabled", statestats.m_addr_relay_enabled);
236  obj.pushKV("addr_processed", statestats.m_addr_processed);
237  obj.pushKV("addr_rate_limited", statestats.m_addr_rate_limited);
238  }
239  UniValue permissions(UniValue::VARR);
240  for (const auto& permission : NetPermissions::ToStrings(stats.m_permissionFlags)) {
241  permissions.push_back(permission);
242  }
243  obj.pushKV("permissions", permissions);
244  obj.pushKV("minfeefilter", ValueFromAmount(stats.minFeeFilter));
245 
246  UniValue sendPerMsgCmd(UniValue::VOBJ);
247  for (const auto& i : stats.mapSendBytesPerMsgCmd) {
248  if (i.second > 0)
249  sendPerMsgCmd.pushKV(i.first, i.second);
250  }
251  obj.pushKV("bytessent_per_msg", sendPerMsgCmd);
252 
253  UniValue recvPerMsgCmd(UniValue::VOBJ);
254  for (const auto& i : stats.mapRecvBytesPerMsgCmd) {
255  if (i.second > 0)
256  recvPerMsgCmd.pushKV(i.first, i.second);
257  }
258  obj.pushKV("bytesrecv_per_msg", recvPerMsgCmd);
259  obj.pushKV("connection_type", ConnectionTypeAsString(stats.m_conn_type));
260 
261  ret.push_back(obj);
262  }
263 
264  return ret;
265 },
266  };
267 }
268 
270 {
271  return RPCHelpMan{"addnode",
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" +
276  strprintf("Addnode connections are limited to %u at a time", MAX_ADDNODE_CONNECTIONS) +
277  " and are counted separately from the -maxconnections limit.\n",
278  {
279  {"node", RPCArg::Type::STR, RPCArg::Optional::NO, "The node (see getpeerinfo for nodes)"},
280  {"command", RPCArg::Type::STR, RPCArg::Optional::NO, "'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once"},
281  },
283  RPCExamples{
284  HelpExampleCli("addnode", "\"192.168.0.6:8333\" \"onetry\"")
285  + HelpExampleRpc("addnode", "\"192.168.0.6:8333\", \"onetry\"")
286  },
287  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
288 {
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(
294  self.ToString());
295  }
296 
297  NodeContext& node = EnsureAnyNodeContext(request.context);
298  CConnman& connman = EnsureConnman(node);
299 
300  std::string strNode = request.params[0].get_str();
301 
302  if (strCommand == "onetry")
303  {
304  CAddress addr;
305  connman.OpenNetworkConnection(addr, false, nullptr, strNode.c_str(), ConnectionType::MANUAL);
306  return NullUniValue;
307  }
308 
309  if (strCommand == "add")
310  {
311  if (!connman.AddNode(strNode)) {
312  throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
313  }
314  }
315  else if(strCommand == "remove")
316  {
317  if (!connman.RemoveAddedNode(strNode)) {
318  throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node could not be removed. It has not been added previously.");
319  }
320  }
321 
322  return NullUniValue;
323 },
324  };
325 }
326 
328 {
329  return RPCHelpMan{"addconnection",
330  "\nOpen an outbound connection to a specified node. This RPC is for testing only.\n",
331  {
332  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP address and port to attempt connecting to."},
333  {"connection_type", RPCArg::Type::STR, RPCArg::Optional::NO, "Type of connection to open (\"outbound-full-relay\", \"block-relay-only\", \"addr-fetch\" or \"feeler\")."},
334  },
335  RPCResult{
336  RPCResult::Type::OBJ, "", "",
337  {
338  { RPCResult::Type::STR, "address", "Address of newly added connection." },
339  { RPCResult::Type::STR, "connection_type", "Type of connection opened." },
340  }},
341  RPCExamples{
342  HelpExampleCli("addconnection", "\"192.168.0.6:8333\" \"outbound-full-relay\"")
343  + HelpExampleRpc("addconnection", "\"192.168.0.6:8333\" \"outbound-full-relay\"")
344  },
345  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
346 {
348  throw std::runtime_error("addconnection is for regression testing (-regtest mode) only.");
349  }
350 
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())};
354  ConnectionType conn_type{};
355  if (conn_type_in == "outbound-full-relay") {
357  } else if (conn_type_in == "block-relay-only") {
358  conn_type = ConnectionType::BLOCK_RELAY;
359  } else if (conn_type_in == "addr-fetch") {
360  conn_type = ConnectionType::ADDR_FETCH;
361  } else if (conn_type_in == "feeler") {
362  conn_type = ConnectionType::FEELER;
363  } else {
365  }
366 
367  NodeContext& node = EnsureAnyNodeContext(request.context);
368  CConnman& connman = EnsureConnman(node);
369 
370  const bool success = connman.AddConnection(address, conn_type);
371  if (!success) {
372  throw JSONRPCError(RPC_CLIENT_NODE_CAPACITY_REACHED, "Error: Already at capacity for specified connection type.");
373  }
374 
375  UniValue info(UniValue::VOBJ);
376  info.pushKV("address", address);
377  info.pushKV("connection_type", conn_type_in);
378 
379  return info;
380 },
381  };
382 }
383 
385 {
386  return RPCHelpMan{"disconnectnode",
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",
390  {
391  {"address", RPCArg::Type::STR, RPCArg::DefaultHint{"fallback to nodeid"}, "The IP address/port of the node"},
392  {"nodeid", RPCArg::Type::NUM, RPCArg::DefaultHint{"fallback to address"}, "The node ID (see getpeerinfo for node IDs)"},
393  },
395  RPCExamples{
396  HelpExampleCli("disconnectnode", "\"192.168.0.6:8333\"")
397  + HelpExampleCli("disconnectnode", "\"\" 1")
398  + HelpExampleRpc("disconnectnode", "\"192.168.0.6:8333\"")
399  + HelpExampleRpc("disconnectnode", "\"\", 1")
400  },
401  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
402 {
403  NodeContext& node = EnsureAnyNodeContext(request.context);
404  CConnman& connman = EnsureConnman(node);
405 
406  bool success;
407  const UniValue &address_arg = request.params[0];
408  const UniValue &id_arg = request.params[1];
409 
410  if (!address_arg.isNull() && id_arg.isNull()) {
411  /* handle disconnect-by-address */
412  success = connman.DisconnectNode(address_arg.get_str());
413  } else if (!id_arg.isNull() && (address_arg.isNull() || (address_arg.isStr() && address_arg.get_str().empty()))) {
414  /* handle disconnect-by-id */
415  NodeId nodeid = (NodeId) id_arg.get_int64();
416  success = connman.DisconnectNode(nodeid);
417  } else {
418  throw JSONRPCError(RPC_INVALID_PARAMS, "Only one of address and nodeid should be provided.");
419  }
420 
421  if (!success) {
422  throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes");
423  }
424 
425  return NullUniValue;
426 },
427  };
428 }
429 
431 {
432  return RPCHelpMan{"getaddednodeinfo",
433  "\nReturns information about the given added node, or all added nodes\n"
434  "(note that onetry addnodes are not listed here)\n",
435  {
436  {"node", RPCArg::Type::STR, RPCArg::DefaultHint{"all nodes"}, "If provided, return information about this specific node, otherwise all nodes are returned."},
437  },
438  RPCResult{
439  RPCResult::Type::ARR, "", "",
440  {
441  {RPCResult::Type::OBJ, "", "",
442  {
443  {RPCResult::Type::STR, "addednode", "The node IP address or name (as provided to addnode)"},
444  {RPCResult::Type::BOOL, "connected", "If connected"},
445  {RPCResult::Type::ARR, "addresses", "Only when connected = true",
446  {
447  {RPCResult::Type::OBJ, "", "",
448  {
449  {RPCResult::Type::STR, "address", "The bitcoin server IP and port we're connected to"},
450  {RPCResult::Type::STR, "connected", "connection, inbound or outbound"},
451  }},
452  }},
453  }},
454  }
455  },
456  RPCExamples{
457  HelpExampleCli("getaddednodeinfo", "\"192.168.0.201\"")
458  + HelpExampleRpc("getaddednodeinfo", "\"192.168.0.201\"")
459  },
460  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
461 {
462  NodeContext& node = EnsureAnyNodeContext(request.context);
463  const CConnman& connman = EnsureConnman(node);
464 
465  std::vector<AddedNodeInfo> vInfo = connman.GetAddedNodeInfo();
466 
467  if (!request.params[0].isNull()) {
468  bool found = false;
469  for (const AddedNodeInfo& info : vInfo) {
470  if (info.strAddedNode == request.params[0].get_str()) {
471  vInfo.assign(1, info);
472  found = true;
473  break;
474  }
475  }
476  if (!found) {
477  throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
478  }
479  }
480 
482 
483  for (const AddedNodeInfo& info : vInfo) {
485  obj.pushKV("addednode", info.strAddedNode);
486  obj.pushKV("connected", info.fConnected);
487  UniValue addresses(UniValue::VARR);
488  if (info.fConnected) {
489  UniValue address(UniValue::VOBJ);
490  address.pushKV("address", info.resolvedAddress.ToString());
491  address.pushKV("connected", info.fInbound ? "inbound" : "outbound");
492  addresses.push_back(address);
493  }
494  obj.pushKV("addresses", addresses);
495  ret.push_back(obj);
496  }
497 
498  return ret;
499 },
500  };
501 }
502 
504 {
505  return RPCHelpMan{"getnettotals",
506  "\nReturns information about network traffic, including bytes in, bytes out,\n"
507  "and current time.\n",
508  {},
509  RPCResult{
510  RPCResult::Type::OBJ, "", "",
511  {
512  {RPCResult::Type::NUM, "totalbytesrecv", "Total bytes received"},
513  {RPCResult::Type::NUM, "totalbytessent", "Total bytes sent"},
514  {RPCResult::Type::NUM_TIME, "timemillis", "Current " + UNIX_EPOCH_TIME + " in milliseconds"},
515  {RPCResult::Type::OBJ, "uploadtarget", "",
516  {
517  {RPCResult::Type::NUM, "timeframe", "Length of the measuring timeframe in seconds"},
518  {RPCResult::Type::NUM, "target", "Target in bytes"},
519  {RPCResult::Type::BOOL, "target_reached", "True if target is reached"},
520  {RPCResult::Type::BOOL, "serve_historical_blocks", "True if serving historical blocks"},
521  {RPCResult::Type::NUM, "bytes_left_in_cycle", "Bytes left in current time cycle"},
522  {RPCResult::Type::NUM, "time_left_in_cycle", "Seconds left in current time cycle"},
523  }},
524  }
525  },
526  RPCExamples{
527  HelpExampleCli("getnettotals", "")
528  + HelpExampleRpc("getnettotals", "")
529  },
530  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
531 {
532  NodeContext& node = EnsureAnyNodeContext(request.context);
533  const CConnman& connman = EnsureConnman(node);
534 
536  obj.pushKV("totalbytesrecv", connman.GetTotalBytesRecv());
537  obj.pushKV("totalbytessent", connman.GetTotalBytesSent());
538  obj.pushKV("timemillis", GetTimeMillis());
539 
540  UniValue outboundLimit(UniValue::VOBJ);
541  outboundLimit.pushKV("timeframe", count_seconds(connman.GetMaxOutboundTimeframe()));
542  outboundLimit.pushKV("target", connman.GetMaxOutboundTarget());
543  outboundLimit.pushKV("target_reached", connman.OutboundTargetReached(false));
544  outboundLimit.pushKV("serve_historical_blocks", !connman.OutboundTargetReached(true));
545  outboundLimit.pushKV("bytes_left_in_cycle", connman.GetOutboundTargetBytesLeft());
546  outboundLimit.pushKV("time_left_in_cycle", count_seconds(connman.GetMaxOutboundTimeLeftInCycle()));
547  obj.pushKV("uploadtarget", outboundLimit);
548  return obj;
549 },
550  };
551 }
552 
554 {
555  UniValue networks(UniValue::VARR);
556  for (int n = 0; n < NET_MAX; ++n) {
557  enum Network network = static_cast<enum Network>(n);
558  if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
559  proxyType proxy;
561  GetProxy(network, proxy);
562  obj.pushKV("name", GetNetworkName(network));
563  obj.pushKV("limited", !IsReachable(network));
564  obj.pushKV("reachable", IsReachable(network));
565  obj.pushKV("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string());
566  obj.pushKV("proxy_randomize_credentials", proxy.randomize_credentials);
567  networks.push_back(obj);
568  }
569  return networks;
570 }
571 
573 {
574  return RPCHelpMan{"getnetworkinfo",
575  "Returns an object containing various state info regarding P2P networking.\n",
576  {},
577  RPCResult{
578  RPCResult::Type::OBJ, "", "",
579  {
580  {RPCResult::Type::NUM, "version", "the server version"},
581  {RPCResult::Type::STR, "subversion", "the server subversion string"},
582  {RPCResult::Type::NUM, "protocolversion", "the protocol version"},
583  {RPCResult::Type::STR_HEX, "localservices", "the services we offer to the network"},
584  {RPCResult::Type::ARR, "localservicesnames", "the services we offer to the network, in human-readable form",
585  {
586  {RPCResult::Type::STR, "SERVICE_NAME", "the service name"},
587  }},
588  {RPCResult::Type::BOOL, "localrelay", "true if transaction relay is requested from peers"},
589  {RPCResult::Type::NUM, "timeoffset", "the time offset"},
590  {RPCResult::Type::NUM, "connections", "the total number of connections"},
591  {RPCResult::Type::NUM, "connections_in", "the number of inbound connections"},
592  {RPCResult::Type::NUM, "connections_out", "the number of outbound connections"},
593  {RPCResult::Type::BOOL, "networkactive", "whether p2p networking is enabled"},
594  {RPCResult::Type::ARR, "networks", "information per network",
595  {
596  {RPCResult::Type::OBJ, "", "",
597  {
598  {RPCResult::Type::STR, "name", "network (" + Join(GetNetworkNames(), ", ") + ")"},
599  {RPCResult::Type::BOOL, "limited", "is the network limited using -onlynet?"},
600  {RPCResult::Type::BOOL, "reachable", "is the network reachable?"},
601  {RPCResult::Type::STR, "proxy", "(\"host:port\") the proxy that is used for this network, or empty if none"},
602  {RPCResult::Type::BOOL, "proxy_randomize_credentials", "Whether randomized credentials are used"},
603  }},
604  }},
605  {RPCResult::Type::NUM, "relayfee", "minimum relay fee rate for transactions in " + CURRENCY_UNIT + "/kvB"},
606  {RPCResult::Type::NUM, "incrementalfee", "minimum fee rate increment for mempool limiting or BIP 125 replacement in " + CURRENCY_UNIT + "/kvB"},
607  {RPCResult::Type::ARR, "localaddresses", "list of local addresses",
608  {
609  {RPCResult::Type::OBJ, "", "",
610  {
611  {RPCResult::Type::STR, "address", "network address"},
612  {RPCResult::Type::NUM, "port", "network port"},
613  {RPCResult::Type::NUM, "score", "relative score"},
614  }},
615  }},
616  {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"},
617  }
618  },
619  RPCExamples{
620  HelpExampleCli("getnetworkinfo", "")
621  + HelpExampleRpc("getnetworkinfo", "")
622  },
623  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
624 {
625  LOCK(cs_main);
627  obj.pushKV("version", CLIENT_VERSION);
628  obj.pushKV("subversion", strSubVersion);
629  obj.pushKV("protocolversion",PROTOCOL_VERSION);
630  NodeContext& node = EnsureAnyNodeContext(request.context);
631  if (node.connman) {
632  ServiceFlags services = node.connman->GetLocalServices();
633  obj.pushKV("localservices", strprintf("%016x", services));
634  obj.pushKV("localservicesnames", GetServicesNames(services));
635  }
636  if (node.peerman) {
637  obj.pushKV("localrelay", !node.peerman->IgnoresIncomingTxs());
638  }
639  obj.pushKV("timeoffset", GetTimeOffset());
640  if (node.connman) {
641  obj.pushKV("networkactive", node.connman->GetNetworkActive());
642  obj.pushKV("connections", (int)node.connman->GetNodeCount(ConnectionDirection::Both));
643  obj.pushKV("connections_in", (int)node.connman->GetNodeCount(ConnectionDirection::In));
644  obj.pushKV("connections_out", (int)node.connman->GetNodeCount(ConnectionDirection::Out));
645  }
646  obj.pushKV("networks", GetNetworksInfo());
647  obj.pushKV("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()));
648  obj.pushKV("incrementalfee", ValueFromAmount(::incrementalRelayFee.GetFeePerK()));
649  UniValue localAddresses(UniValue::VARR);
650  {
652  for (const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
653  {
655  rec.pushKV("address", item.first.ToString());
656  rec.pushKV("port", item.second.nPort);
657  rec.pushKV("score", item.second.nScore);
658  localAddresses.push_back(rec);
659  }
660  }
661  obj.pushKV("localaddresses", localAddresses);
662  obj.pushKV("warnings", GetWarnings(false).original);
663  return obj;
664 },
665  };
666 }
667 
669 {
670  return RPCHelpMan{"setban",
671  "\nAttempts to add or remove an IP/Subnet from the banned list.\n",
672  {
673  {"subnet", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP/Subnet (see getpeerinfo for nodes IP) with an optional netmask (default is /32 = single IP)"},
674  {"command", RPCArg::Type::STR, RPCArg::Optional::NO, "'add' to add an IP/Subnet to the list, 'remove' to remove an IP/Subnet from the list"},
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)"},
676  {"absolute", RPCArg::Type::BOOL, RPCArg::Default{false}, "If set, the bantime must be an absolute timestamp expressed in " + UNIX_EPOCH_TIME},
677  },
679  RPCExamples{
680  HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
681  + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
682  + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\", 86400")
683  },
684  [&](const RPCHelpMan& help, const JSONRPCRequest& request) -> UniValue
685 {
686  std::string strCommand;
687  if (!request.params[1].isNull())
688  strCommand = request.params[1].get_str();
689  if (strCommand != "add" && strCommand != "remove") {
690  throw std::runtime_error(help.ToString());
691  }
692  NodeContext& node = EnsureAnyNodeContext(request.context);
693  if (!node.banman) {
694  throw JSONRPCError(RPC_DATABASE_ERROR, "Error: Ban database not loaded");
695  }
696 
697  CSubNet subNet;
698  CNetAddr netAddr;
699  bool isSubnet = false;
700 
701  if (request.params[0].get_str().find('/') != std::string::npos)
702  isSubnet = true;
703 
704  if (!isSubnet) {
705  CNetAddr resolved;
706  LookupHost(request.params[0].get_str(), resolved, false);
707  netAddr = resolved;
708  }
709  else
710  LookupSubNet(request.params[0].get_str(), subNet);
711 
712  if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) )
713  throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Invalid IP/Subnet");
714 
715  if (strCommand == "add")
716  {
717  if (isSubnet ? node.banman->IsBanned(subNet) : node.banman->IsBanned(netAddr)) {
718  throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
719  }
720 
721  int64_t banTime = 0; //use standard bantime if not specified
722  if (!request.params[2].isNull())
723  banTime = request.params[2].get_int64();
724 
725  bool absolute = false;
726  if (request.params[3].isTrue())
727  absolute = true;
728 
729  if (isSubnet) {
730  node.banman->Ban(subNet, banTime, absolute);
731  if (node.connman) {
732  node.connman->DisconnectNode(subNet);
733  }
734  } else {
735  node.banman->Ban(netAddr, banTime, absolute);
736  if (node.connman) {
737  node.connman->DisconnectNode(netAddr);
738  }
739  }
740  }
741  else if(strCommand == "remove")
742  {
743  if (!( isSubnet ? node.banman->Unban(subNet) : node.banman->Unban(netAddr) )) {
744  throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Unban failed. Requested address/subnet was not previously manually banned.");
745  }
746  }
747  return NullUniValue;
748 },
749  };
750 }
751 
753 {
754  return RPCHelpMan{"listbanned",
755  "\nList all manually banned IPs/Subnets.\n",
756  {},
758  {
759  {RPCResult::Type::OBJ, "", "",
760  {
761  {RPCResult::Type::STR, "address", "The IP/Subnet of the banned node"},
762  {RPCResult::Type::NUM_TIME, "ban_created", "The " + UNIX_EPOCH_TIME + " the ban was created"},
763  {RPCResult::Type::NUM_TIME, "banned_until", "The " + UNIX_EPOCH_TIME + " the ban expires"},
764  {RPCResult::Type::NUM_TIME, "ban_duration", "The ban duration, in seconds"},
765  {RPCResult::Type::NUM_TIME, "time_remaining", "The time remaining until the ban expires, in seconds"},
766  }},
767  }},
768  RPCExamples{
769  HelpExampleCli("listbanned", "")
770  + HelpExampleRpc("listbanned", "")
771  },
772  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
773 {
774  NodeContext& node = EnsureAnyNodeContext(request.context);
775  if(!node.banman) {
776  throw JSONRPCError(RPC_DATABASE_ERROR, "Error: Ban database not loaded");
777  }
778 
779  banmap_t banMap;
780  node.banman->GetBanned(banMap);
781  const int64_t current_time{GetTime()};
782 
783  UniValue bannedAddresses(UniValue::VARR);
784  for (const auto& entry : banMap)
785  {
786  const CBanEntry& banEntry = entry.second;
788  rec.pushKV("address", entry.first.ToString());
789  rec.pushKV("ban_created", banEntry.nCreateTime);
790  rec.pushKV("banned_until", banEntry.nBanUntil);
791  rec.pushKV("ban_duration", (banEntry.nBanUntil - banEntry.nCreateTime));
792  rec.pushKV("time_remaining", (banEntry.nBanUntil - current_time));
793 
794  bannedAddresses.push_back(rec);
795  }
796 
797  return bannedAddresses;
798 },
799  };
800 }
801 
803 {
804  return RPCHelpMan{"clearbanned",
805  "\nClear all banned IPs.\n",
806  {},
808  RPCExamples{
809  HelpExampleCli("clearbanned", "")
810  + HelpExampleRpc("clearbanned", "")
811  },
812  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
813 {
814  NodeContext& node = EnsureAnyNodeContext(request.context);
815  if (!node.banman) {
816  throw JSONRPCError(RPC_DATABASE_ERROR, "Error: Ban database not loaded");
817  }
818 
819  node.banman->ClearBanned();
820 
821  return NullUniValue;
822 },
823  };
824 }
825 
827 {
828  return RPCHelpMan{"setnetworkactive",
829  "\nDisable/enable all p2p network activity.\n",
830  {
831  {"state", RPCArg::Type::BOOL, RPCArg::Optional::NO, "true to enable networking, false to disable"},
832  },
833  RPCResult{RPCResult::Type::BOOL, "", "The value that was passed in"},
834  RPCExamples{""},
835  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
836 {
837  NodeContext& node = EnsureAnyNodeContext(request.context);
838  CConnman& connman = EnsureConnman(node);
839 
840  connman.SetNetworkActive(request.params[0].get_bool());
841 
842  return connman.GetNetworkActive();
843 },
844  };
845 }
846 
848 {
849  return RPCHelpMan{"getnodeaddresses",
850  "\nReturn known addresses, which can potentially be used to find new nodes in the network.\n",
851  {
852  {"count", RPCArg::Type::NUM, RPCArg::Default{1}, "The maximum number of addresses to return. Specify 0 to return all known addresses."},
853  {"network", RPCArg::Type::STR, RPCArg::DefaultHint{"all networks"}, "Return only addresses of the specified network. Can be one of: " + Join(GetNetworkNames(), ", ") + "."},
854  },
855  RPCResult{
856  RPCResult::Type::ARR, "", "",
857  {
858  {RPCResult::Type::OBJ, "", "",
859  {
860  {RPCResult::Type::NUM_TIME, "time", "The " + UNIX_EPOCH_TIME + " when the node was last seen"},
861  {RPCResult::Type::NUM, "services", "The services offered by the node"},
862  {RPCResult::Type::STR, "address", "The address of the node"},
863  {RPCResult::Type::NUM, "port", "The port number of the node"},
864  {RPCResult::Type::STR, "network", "The network (" + Join(GetNetworkNames(), ", ") + ") the node connected through"},
865  }},
866  }
867  },
868  RPCExamples{
869  HelpExampleCli("getnodeaddresses", "8")
870  + HelpExampleCli("getnodeaddresses", "4 \"i2p\"")
871  + HelpExampleCli("-named getnodeaddresses", "network=onion count=12")
872  + HelpExampleRpc("getnodeaddresses", "8")
873  + HelpExampleRpc("getnodeaddresses", "4, \"i2p\"")
874  },
875  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
876 {
877  NodeContext& node = EnsureAnyNodeContext(request.context);
878  const CConnman& connman = EnsureConnman(node);
879 
880  const int count{request.params[0].isNull() ? 1 : request.params[0].get_int()};
881  if (count < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Address count out of range");
882 
883  const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{ParseNetwork(request.params[1].get_str())}};
884  if (network == NET_UNROUTABLE) {
885  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Network not recognized: %s", request.params[1].get_str()));
886  }
887 
888  // returns a shuffled list of CAddress
889  const std::vector<CAddress> vAddr{connman.GetAddresses(count, /* max_pct */ 0, network)};
891 
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());
898  obj.pushKV("network", GetNetworkName(addr.GetNetClass()));
899  ret.push_back(obj);
900  }
901  return ret;
902 },
903  };
904 }
905 
907 {
908  return RPCHelpMan{"addpeeraddress",
909  "\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
910  {
911  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP address of the peer"},
912  {"port", RPCArg::Type::NUM, RPCArg::Optional::NO, "The port of the peer"},
913  {"tried", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, attempt to add the peer to the tried addresses table"},
914  },
915  RPCResult{
916  RPCResult::Type::OBJ, "", "",
917  {
918  {RPCResult::Type::BOOL, "success", "whether the peer address was successfully added to the address manager"},
919  },
920  },
921  RPCExamples{
922  HelpExampleCli("addpeeraddress", "\"1.2.3.4\" 8333 true")
923  + HelpExampleRpc("addpeeraddress", "\"1.2.3.4\", 8333, true")
924  },
925  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
926 {
927  NodeContext& node = EnsureAnyNodeContext(request.context);
928  if (!node.addrman) {
929  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Address manager functionality missing or disabled");
930  }
931 
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()};
935 
937  CNetAddr net_addr;
938  bool success{false};
939 
940  if (LookupHost(addr_string, net_addr, false)) {
941  CAddress address{{net_addr, port}, ServiceFlags{NODE_NETWORK | NODE_WITNESS}};
942  address.nTime = GetAdjustedTime();
943  // The source address is set equal to the address. This is equivalent to the peer
944  // announcing itself.
945  if (node.addrman->Add({address}, address)) {
946  success = true;
947  if (tried) {
948  // Attempt to move the address to the tried addresses table.
949  node.addrman->Good(address);
950  }
951  }
952  }
953 
954  obj.pushKV("success", success);
955  return obj;
956 },
957  };
958 }
959 
961 {
962 // clang-format off
963 static const CRPCCommand commands[] =
964 { // category actor
965  // --------------------- -----------------------
966  { "network", &getconnectioncount, },
967  { "network", &ping, },
968  { "network", &getpeerinfo, },
969  { "network", &addnode, },
970  { "network", &disconnectnode, },
971  { "network", &getaddednodeinfo, },
972  { "network", &getnettotals, },
973  { "network", &getnetworkinfo, },
974  { "network", &setban, },
975  { "network", &listbanned, },
976  { "network", &clearbanned, },
977  { "network", &setnetworkactive, },
978  { "network", &getnodeaddresses, },
979 
980  { "hidden", &addconnection, },
981  { "hidden", &addpeeraddress, },
982 };
983 // clang-format on
984  for (const auto& c : commands) {
985  t.appendCommand(c.name, &c);
986  }
987 }
NodeId
int64_t NodeId
Definition: net.h:88
PeerManager::GetNodeStateStats
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
CConnman::DisconnectNode
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2829
PeerManager::SendPings
virtual void SendPings()=0
Send ping message to all peers.
getnettotals
static RPCHelpMan getnettotals()
Definition: net.cpp:503
CNodeStateStats::vHeightInFlight
std::vector< int > vHeightInFlight
Definition: net_processing.h:31
LookupHost
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.
Definition: netbase.cpp:170
HelpExampleCli
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:156
CNodeStateStats::nCommonHeight
int nCommonHeight
Definition: net_processing.h:28
ToString
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
proxyType::IsValid
bool IsValid() const
Definition: netbase.h:54
NET_UNROUTABLE
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:47
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:19
count
static int count
Definition: tests.c:31
ParseNetwork
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:87
getaddednodeinfo
static RPCHelpMan getaddednodeinfo()
Definition: net.cpp:430
ConnectionDirection::Out
@ Out
NetPermissions::ToStrings
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
Definition: net_permissions.cpp:71
settings.h
RPC_CLIENT_P2P_DISABLED
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
Definition: protocol.h:64
NET_PERMISSIONS_DOC
const std::vector< std::string > NET_PERMISSIONS_DOC
Definition: net_permissions.cpp:11
CConnman::GetMaxOutboundTimeframe
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2899
NET_INTERNAL
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:66
help
static RPCHelpMan help()
Definition: server.cpp:133
GetWarnings
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:31
RPCHelpMan
Definition: util.h:345
sync.h
NET_MESSAGE_COMMAND_OTHER
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:105
timedata.h
setnetworkactive
static RPCHelpMan setnetworkactive()
Definition: net.cpp:826
NullUniValue
const UniValue NullUniValue
Definition: univalue.cpp:13
EnsurePeerman
PeerManager & EnsurePeerman(const NodeContext &node)
Definition: server_util.cpp:89
string.h
CNodeStateStats::m_addr_rate_limited
uint64_t m_addr_rate_limited
Definition: net_processing.h:33
CNetAddr
Network address.
Definition: netaddress.h:118
RPC_INVALID_PARAMETER
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
getconnectioncount
static RPCHelpMan getconnectioncount()
Definition: net.cpp:46
CConnman::OutboundTargetReached
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:2918
NET_MAX
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:69
GetServicesNames
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1029
ConnectionType::OUTBOUND_FULL_RELAY
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
node::NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:40
RPCArg::Optional::NO
@ NO
Required arg.
RPCArg::Type::STR
@ STR
ConnectionDirection::Both
@ Both
CConnman::AddConnection
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1217
minRelayTxFee
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:153
GetTime
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
protocol.h
CNodeStateStats::nSyncHeight
int nSyncHeight
Definition: net_processing.h:27
setban
static RPCHelpMan setban()
Definition: net.cpp:668
RPCResult::Type::NUM
@ NUM
clearbanned
static RPCHelpMan clearbanned()
Definition: net.cpp:802
CountSecondsDouble
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
Definition: time.h:38
clientversion.h
server_util.h
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:271
UniValue::isNull
bool isNull() const
Definition: univalue.h:75
TrimString
std::string TrimString(const std::string &str, const std::string &pattern=" \f\n\r\t\v")
Definition: string.h:18
NODE_NETWORK
@ NODE_NETWORK
Definition: protocol.h:277
chainparams.h
Network
Network
A network type.
Definition: netaddress.h:45
CNodeStateStats::m_addr_relay_enabled
bool m_addr_relay_enabled
Definition: net_processing.h:34
GetNetworksInfo
static UniValue GetNetworksInfo()
Definition: net.cpp:553
context.h
version.h
core_io.h
proxyType
Definition: netbase.h:48
UniValue::pushKV
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
CService::ToStringIPPort
std::string ToStringIPPort() const
Definition: netaddress.cpp:1039
ValueFromAmount
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:21
CConnman::GetMaxOutboundTimeLeftInCycle
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
Definition: net.cpp:2904
UniValue
Definition: univalue.h:17
ConnectionType::MANUAL
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
CConnman::GetNodeStats
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2817
CConnman::OpenNetworkConnection
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2223
RPCArg::Type::NUM
@ NUM
EnsureAnyNodeContext
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:20
UniValue::get_str
const std::string & get_str() const
Definition: univalue_get.cpp:98
strencodings.h
UniValue::isStr
bool isStr() const
Definition: univalue.h:79
net_types.h
ConnectionDirection::In
@ In
CONNECTION_TYPE_DOC
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.cpp:37
banman.h
RPCHelpMan::ToString
std::string ToString() const
Definition: util.cpp:602
UniValue::get_int64
int64_t get_int64() const
Definition: univalue_get.cpp:115
CURRENCY_UNIT
const std::string CURRENCY_UNIT
Definition: feerate.h:14
LookupSubNet
bool LookupSubNet(const std::string &subnet_str, CSubNet &subnet_out)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:679
RPCArg::DefaultHint
std::string DefaultHint
Definition: util.h:155
RPCResult::Type::OBJ
@ OBJ
CRPCCommand
Definition: server.h:89
RPCResult::Type::NONE
@ NONE
IsReachable
bool IsReachable(enum Network net)
Definition: net.cpp:299
addconnection
static RPCHelpMan addconnection()
Definition: net.cpp:327
cs_mapLocalHost
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:115
univalue.h
RPC_DATABASE_ERROR
@ RPC_DATABASE_ERROR
Database error.
Definition: protocol.h:44
CBaseChainParams::REGTEST
static const std::string REGTEST
Definition: chainparamsbase.h:25
RPCResult::Type::STR_HEX
@ STR_HEX
Special string with only hex chars.
AddedNodeInfo
Definition: net.h:90
RPCExamples
Definition: util.h:335
CChainParams::NetworkIDString
std::string NetworkIDString() const
Return the network string.
Definition: chainparams.h:112
CConnman::GetTotalBytesRecv
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2947
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:451
CSubNet
Definition: netaddress.h:475
EnsureConnman
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:81
CBanEntry::nCreateTime
int64_t nCreateTime
Definition: net_types.h:19
RPCResult::Type::STR
@ STR
PeerManager
Definition: net_processing.h:37
RPCResult::Type::NUM_TIME
@ NUM_TIME
Special numeric to denote unix epoch time.
RPCResult::Type::ARR
@ ARR
HelpExampleRpc
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:174
GetNetworkNames
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:121
ConnectionType::FEELER
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
CNodeStateStats::m_addr_processed
uint64_t m_addr_processed
Definition: net_processing.h:32
net_processing.h
CNodeStateStats::m_starting_height
int m_starting_height
Definition: net_processing.h:29
CConnman::GetMaxOutboundTarget
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2893
ping
static RPCHelpMan ping()
Definition: net.cpp:68
CRPCTable
RPC command dispatcher.
Definition: server.h:125
CConnman::RemoveAddedNode
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2789
RegisterNetRPCCommands
void RegisterNetRPCCommands(CRPCTable &t)
Register P2P networking RPC commands.
Definition: net.cpp:960
NODE_WITNESS
@ NODE_WITNESS
Definition: protocol.h:284
addpeeraddress
static RPCHelpMan addpeeraddress()
Definition: net.cpp:906
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
CConnman
Definition: net.h:741
Join
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:44
disconnectnode
static RPCHelpMan disconnectnode()
Definition: net.cpp:384
incrementalRelayFee
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
strSubVersion
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:118
GetAdjustedTime
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
ConnectionTypeAsString
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:534
CAddress
A CService with information about it as peer.
Definition: protocol.h:358
CConnman::SetNetworkActive
void SetNetworkActive(bool active)
Definition: net.cpp:2450
RPCResult::Type::BOOL
@ BOOL
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:138
translation.h
RPCTypeCheck
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:24
MAX_ADDNODE_CONNECTIONS
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:64
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
proxyType::randomize_credentials
bool randomize_credentials
Definition: netbase.h:57
LOCK
#define LOCK(cs)
Definition: sync.h:226
ConnectionType::ADDR_FETCH
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
RPC_CLIENT_NODE_ALREADY_ADDED
@ RPC_CLIENT_NODE_ALREADY_ADDED
Node is already added.
Definition: protocol.h:60
RPCArg::Type::BOOL
@ BOOL
CLIENT_VERSION
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
RPC_CLIENT_NODE_CAPACITY_REACHED
@ RPC_CLIENT_NODE_CAPACITY_REACHED
Max number of outbound or block-relay connections already open.
Definition: protocol.h:65
CBanEntry
Definition: net_types.h:14
CConnman::GetAddedNodeInfo
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
Definition: net.cpp:2140
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
CBanEntry::nBanUntil
int64_t nBanUntil
Definition: net_types.h:20
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:561
count_seconds
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
Definition: time.h:29
RPC_CLIENT_NODE_NOT_ADDED
@ RPC_CLIENT_NODE_NOT_ADDED
Node has not been added before.
Definition: protocol.h:61
CSubNet::IsValid
bool IsValid() const
Definition: netaddress.cpp:1219
GetProxy
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:617
node
Definition: init.h:22
CConnman::AddNode
bool AddNode(const std::string &node)
Definition: net.cpp:2778
CNodeStateStats::m_ping_wait
std::chrono::microseconds m_ping_wait
Definition: net_processing.h:30
addrman.h
listbanned
static RPCHelpMan listbanned()
Definition: net.cpp:752
getpeerinfo
static RPCHelpMan getpeerinfo()
Definition: net.cpp:92
RPCResult::Type::OBJ_DYN
@ OBJ_DYN
Special dictionary with keys that are not literals.
CConnman::GetNetworkActive
bool GetNetworkActive() const
Definition: net.h:814
RPC_CLIENT_NODE_NOT_CONNECTED
@ RPC_CLIENT_NODE_NOT_CONNECTED
Node to disconnect not found in connected nodes.
Definition: protocol.h:62
JSONRPCRequest
Definition: request.h:28
banmap_t
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:41
ConnectionType::BLOCK_RELAY
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
netbase.h
RPCResult
Definition: util.h:231
GetNetworkName
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:105
blockchain.h
RPC_INVALID_PARAMS
@ RPC_INVALID_PARAMS
Definition: protocol.h:32
GetTimeOffset
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
Definition: timedata.cpp:29
UniValue::VARR
@ VARR
Definition: univalue.h:19
CConnman::GetTotalBytesSent
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2952
server.h
CNodeStateStats
Definition: net_processing.h:26
CFeeRate::GetFeePerK
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:57
ConnectionType
ConnectionType
Different types of connections to a peer.
Definition: net.h:121
CNodeStats
Definition: net.h:239
warnings.h
getnetworkinfo
static RPCHelpMan getnetworkinfo()
Definition: net.cpp:572
CConnman::GetNodeCount
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2801
GetTimeMillis
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
CConnman::GetAddresses
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.
Definition: net.cpp:2726
UNIX_EPOCH_TIME
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:21
getnodeaddresses
static RPCHelpMan getnodeaddresses()
Definition: net.cpp:847
proxyType::proxy
CService proxy
Definition: netbase.h:56
ByteUnit::t
@ t
RPC_CLIENT_INVALID_IP_OR_SUBNET
@ RPC_CLIENT_INVALID_IP_OR_SUBNET
Invalid IP/Subnet.
Definition: protocol.h:63
addnode
static RPCHelpMan addnode()
Definition: net.cpp:269
net_permissions.h
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
CConnman::GetOutboundTargetBytesLeft
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:2938