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