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