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