BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
net.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2018 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 <chainparams.h>
8 #include <clientversion.h>
9 #include <core_io.h>
10 #include <validation.h>
11 #include <net.h>
12 #include <net_processing.h>
13 #include <netbase.h>
14 #include <policy/policy.h>
15 #include <rpc/protocol.h>
16 #include <sync.h>
17 #include <timedata.h>
18 #include <ui_interface.h>
19 #include <util.h>
20 #include <utilstrencodings.h>
21 #include <version.h>
22 #include <warnings.h>
23 
24 #include <univalue.h>
25 
26 static UniValue getconnectioncount(const JSONRPCRequest& request)
27 {
28  if (request.fHelp || request.params.size() != 0)
29  throw std::runtime_error(
30  "getconnectioncount\n"
31  "\nReturns the number of connections to other nodes.\n"
32  "\nResult:\n"
33  "n (numeric) The connection count\n"
34  "\nExamples:\n"
35  + HelpExampleCli("getconnectioncount", "")
36  + HelpExampleRpc("getconnectioncount", "")
37  );
38 
39  if(!g_connman)
40  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
41 
42  return (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL);
43 }
44 
45 static UniValue ping(const JSONRPCRequest& request)
46 {
47  if (request.fHelp || request.params.size() != 0)
48  throw std::runtime_error(
49  "ping\n"
50  "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
51  "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
52  "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n"
53  "\nExamples:\n"
54  + HelpExampleCli("ping", "")
55  + HelpExampleRpc("ping", "")
56  );
57 
58  if(!g_connman)
59  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
60 
61  // Request that each node send a ping during next message processing pass
62  g_connman->ForEachNode([](CNode* pnode) {
63  pnode->fPingQueued = true;
64  });
65  return NullUniValue;
66 }
67 
68 static UniValue getpeerinfo(const JSONRPCRequest& request)
69 {
70  if (request.fHelp || request.params.size() != 0)
71  throw std::runtime_error(
72  "getpeerinfo\n"
73  "\nReturns data about each connected network node as a json array of objects.\n"
74  "\nResult:\n"
75  "[\n"
76  " {\n"
77  " \"id\": n, (numeric) Peer index\n"
78  " \"addr\":\"host:port\", (string) The IP address and port of the peer\n"
79  " \"addrbind\":\"ip:port\", (string) Bind address of the connection to the peer\n"
80  " \"addrlocal\":\"ip:port\", (string) Local address as reported by the peer\n"
81  " \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n"
82  " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n"
83  " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n"
84  " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n"
85  " \"bytessent\": n, (numeric) The total bytes sent\n"
86  " \"bytesrecv\": n, (numeric) The total bytes received\n"
87  " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n"
88  " \"timeoffset\": ttt, (numeric) The time offset in seconds\n"
89  " \"pingtime\": n, (numeric) ping time (if available)\n"
90  " \"minping\": n, (numeric) minimum observed ping time (if any at all)\n"
91  " \"pingwait\": n, (numeric) ping wait (if non-zero)\n"
92  " \"version\": v, (numeric) The peer version, such as 70001\n"
93  " \"subver\": \"/Satoshi:0.8.5/\", (string) The string version\n"
94  " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n"
95  " \"addnode\": true|false, (boolean) Whether connection was due to addnode/-connect or if it was an automatic/inbound connection\n"
96  " \"startingheight\": n, (numeric) The starting height (block) of the peer\n"
97  " \"banscore\": n, (numeric) The ban score\n"
98  " \"synced_headers\": n, (numeric) The last header we have in common with this peer\n"
99  " \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n"
100  " \"inflight\": [\n"
101  " n, (numeric) The heights of blocks we're currently asking from this peer\n"
102  " ...\n"
103  " ],\n"
104  " \"whitelisted\": true|false, (boolean) Whether the peer is whitelisted\n"
105  " \"minfeefilter\": n, (numeric) The minimum fee rate for transactions this peer accepts\n"
106  " \"bytessent_per_msg\": {\n"
107  " \"addr\": n, (numeric) The total bytes sent aggregated by message type\n"
108  " ...\n"
109  " },\n"
110  " \"bytesrecv_per_msg\": {\n"
111  " \"addr\": n, (numeric) The total bytes received aggregated by message type\n"
112  " ...\n"
113  " }\n"
114  " }\n"
115  " ,...\n"
116  "]\n"
117  "\nExamples:\n"
118  + HelpExampleCli("getpeerinfo", "")
119  + HelpExampleRpc("getpeerinfo", "")
120  );
121 
122  if(!g_connman)
123  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
124 
125  std::vector<CNodeStats> vstats;
126  g_connman->GetNodeStats(vstats);
127 
129 
130  for (const CNodeStats& stats : vstats) {
132  CNodeStateStats statestats;
133  bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
134  obj.pushKV("id", stats.nodeid);
135  obj.pushKV("addr", stats.addrName);
136  if (!(stats.addrLocal.empty()))
137  obj.pushKV("addrlocal", stats.addrLocal);
138  if (stats.addrBind.IsValid())
139  obj.pushKV("addrbind", stats.addrBind.ToString());
140  obj.pushKV("services", strprintf("%016x", stats.nServices));
141  obj.pushKV("relaytxes", stats.fRelayTxes);
142  obj.pushKV("lastsend", stats.nLastSend);
143  obj.pushKV("lastrecv", stats.nLastRecv);
144  obj.pushKV("bytessent", stats.nSendBytes);
145  obj.pushKV("bytesrecv", stats.nRecvBytes);
146  obj.pushKV("conntime", stats.nTimeConnected);
147  obj.pushKV("timeoffset", stats.nTimeOffset);
148  if (stats.dPingTime > 0.0)
149  obj.pushKV("pingtime", stats.dPingTime);
150  if (stats.dMinPing < static_cast<double>(std::numeric_limits<int64_t>::max())/1e6)
151  obj.pushKV("minping", stats.dMinPing);
152  if (stats.dPingWait > 0.0)
153  obj.pushKV("pingwait", stats.dPingWait);
154  obj.pushKV("version", stats.nVersion);
155  // Use the sanitized form of subver here, to avoid tricksy remote peers from
156  // corrupting or modifying the JSON output by putting special characters in
157  // their ver message.
158  obj.pushKV("subver", stats.cleanSubVer);
159  obj.pushKV("inbound", stats.fInbound);
160  obj.pushKV("addnode", stats.m_manual_connection);
161  obj.pushKV("startingheight", stats.nStartingHeight);
162  if (fStateStats) {
163  obj.pushKV("banscore", statestats.nMisbehavior);
164  obj.pushKV("synced_headers", statestats.nSyncHeight);
165  obj.pushKV("synced_blocks", statestats.nCommonHeight);
166  UniValue heights(UniValue::VARR);
167  for (const int height : statestats.vHeightInFlight) {
168  heights.push_back(height);
169  }
170  obj.pushKV("inflight", heights);
171  }
172  obj.pushKV("whitelisted", stats.fWhitelisted);
173  obj.pushKV("minfeefilter", ValueFromAmount(stats.minFeeFilter));
174 
175  UniValue sendPerMsgCmd(UniValue::VOBJ);
176  for (const mapMsgCmdSize::value_type &i : stats.mapSendBytesPerMsgCmd) {
177  if (i.second > 0)
178  sendPerMsgCmd.pushKV(i.first, i.second);
179  }
180  obj.pushKV("bytessent_per_msg", sendPerMsgCmd);
181 
182  UniValue recvPerMsgCmd(UniValue::VOBJ);
183  for (const mapMsgCmdSize::value_type &i : stats.mapRecvBytesPerMsgCmd) {
184  if (i.second > 0)
185  recvPerMsgCmd.pushKV(i.first, i.second);
186  }
187  obj.pushKV("bytesrecv_per_msg", recvPerMsgCmd);
188 
189  ret.push_back(obj);
190  }
191 
192  return ret;
193 }
194 
195 static UniValue addnode(const JSONRPCRequest& request)
196 {
197  std::string strCommand;
198  if (!request.params[1].isNull())
199  strCommand = request.params[1].get_str();
200  if (request.fHelp || request.params.size() != 2 ||
201  (strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
202  throw std::runtime_error(
203  "addnode \"node\" \"add|remove|onetry\"\n"
204  "\nAttempts to add or remove a node from the addnode list.\n"
205  "Or try a connection to a node once.\n"
206  "Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be\n"
207  "full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).\n"
208  "\nArguments:\n"
209  "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
210  "2. \"command\" (string, required) '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\n"
211  "\nExamples:\n"
212  + HelpExampleCli("addnode", "\"192.168.0.6:8335\" \"onetry\"")
213  + HelpExampleRpc("addnode", "\"192.168.0.6:8335\", \"onetry\"")
214  );
215 
216  if(!g_connman)
217  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
218 
219  std::string strNode = request.params[0].get_str();
220 
221  if (strCommand == "onetry")
222  {
223  CAddress addr;
224  g_connman->OpenNetworkConnection(addr, false, nullptr, strNode.c_str(), false, false, true);
225  return NullUniValue;
226  }
227 
228  if (strCommand == "add")
229  {
230  if(!g_connman->AddNode(strNode))
231  throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
232  }
233  else if(strCommand == "remove")
234  {
235  if(!g_connman->RemoveAddedNode(strNode))
236  throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
237  }
238 
239  return NullUniValue;
240 }
241 
242 static UniValue disconnectnode(const JSONRPCRequest& request)
243 {
244  if (request.fHelp || request.params.size() == 0 || request.params.size() >= 3)
245  throw std::runtime_error(
246  "disconnectnode \"[address]\" [nodeid]\n"
247  "\nImmediately disconnects from the specified peer node.\n"
248  "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
249  "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n"
250  "\nArguments:\n"
251  "1. \"address\" (string, optional) The IP address/port of the node\n"
252  "2. \"nodeid\" (number, optional) The node ID (see getpeerinfo for node IDs)\n"
253  "\nExamples:\n"
254  + HelpExampleCli("disconnectnode", "\"192.168.0.6:8335\"")
255  + HelpExampleCli("disconnectnode", "\"\" 1")
256  + HelpExampleRpc("disconnectnode", "\"192.168.0.6:8335\"")
257  + HelpExampleRpc("disconnectnode", "\"\", 1")
258  );
259 
260  if(!g_connman)
261  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
262 
263  bool success;
264  const UniValue &address_arg = request.params[0];
265  const UniValue &id_arg = request.params[1];
266 
267  if (!address_arg.isNull() && id_arg.isNull()) {
268  /* handle disconnect-by-address */
269  success = g_connman->DisconnectNode(address_arg.get_str());
270  } else if (!id_arg.isNull() && (address_arg.isNull() || (address_arg.isStr() && address_arg.get_str().empty()))) {
271  /* handle disconnect-by-id */
272  NodeId nodeid = (NodeId) id_arg.get_int64();
273  success = g_connman->DisconnectNode(nodeid);
274  } else {
275  throw JSONRPCError(RPC_INVALID_PARAMS, "Only one of address and nodeid should be provided.");
276  }
277 
278  if (!success) {
279  throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes");
280  }
281 
282  return NullUniValue;
283 }
284 
285 static UniValue getaddednodeinfo(const JSONRPCRequest& request)
286 {
287  if (request.fHelp || request.params.size() > 1)
288  throw std::runtime_error(
289  "getaddednodeinfo ( \"node\" )\n"
290  "\nReturns information about the given added node, or all added nodes\n"
291  "(note that onetry addnodes are not listed here)\n"
292  "\nArguments:\n"
293  "1. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n"
294  "\nResult:\n"
295  "[\n"
296  " {\n"
297  " \"addednode\" : \"192.168.0.201\", (string) The node IP address or name (as provided to addnode)\n"
298  " \"connected\" : true|false, (boolean) If connected\n"
299  " \"addresses\" : [ (list of objects) Only when connected = true\n"
300  " {\n"
301  " \"address\" : \"192.168.0.201:8335\", (string) The bitcoin server IP and port we're connected to\n"
302  " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n"
303  " }\n"
304  " ]\n"
305  " }\n"
306  " ,...\n"
307  "]\n"
308  "\nExamples:\n"
309  + HelpExampleCli("getaddednodeinfo", "\"192.168.0.201\"")
310  + HelpExampleRpc("getaddednodeinfo", "\"192.168.0.201\"")
311  );
312 
313  if(!g_connman)
314  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
315 
316  std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo();
317 
318  if (!request.params[0].isNull()) {
319  bool found = false;
320  for (const AddedNodeInfo& info : vInfo) {
321  if (info.strAddedNode == request.params[0].get_str()) {
322  vInfo.assign(1, info);
323  found = true;
324  break;
325  }
326  }
327  if (!found) {
328  throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
329  }
330  }
331 
333 
334  for (const AddedNodeInfo& info : vInfo) {
336  obj.pushKV("addednode", info.strAddedNode);
337  obj.pushKV("connected", info.fConnected);
338  UniValue addresses(UniValue::VARR);
339  if (info.fConnected) {
340  UniValue address(UniValue::VOBJ);
341  address.pushKV("address", info.resolvedAddress.ToString());
342  address.pushKV("connected", info.fInbound ? "inbound" : "outbound");
343  addresses.push_back(address);
344  }
345  obj.pushKV("addresses", addresses);
346  ret.push_back(obj);
347  }
348 
349  return ret;
350 }
351 
352 static UniValue getnettotals(const JSONRPCRequest& request)
353 {
354  if (request.fHelp || request.params.size() > 0)
355  throw std::runtime_error(
356  "getnettotals\n"
357  "\nReturns information about network traffic, including bytes in, bytes out,\n"
358  "and current time.\n"
359  "\nResult:\n"
360  "{\n"
361  " \"totalbytesrecv\": n, (numeric) Total bytes received\n"
362  " \"totalbytessent\": n, (numeric) Total bytes sent\n"
363  " \"timemillis\": t, (numeric) Current UNIX time in milliseconds\n"
364  " \"uploadtarget\":\n"
365  " {\n"
366  " \"timeframe\": n, (numeric) Length of the measuring timeframe in seconds\n"
367  " \"target\": n, (numeric) Target in bytes\n"
368  " \"target_reached\": true|false, (boolean) True if target is reached\n"
369  " \"serve_historical_blocks\": true|false, (boolean) True if serving historical blocks\n"
370  " \"bytes_left_in_cycle\": t, (numeric) Bytes left in current time cycle\n"
371  " \"time_left_in_cycle\": t (numeric) Seconds left in current time cycle\n"
372  " }\n"
373  "}\n"
374  "\nExamples:\n"
375  + HelpExampleCli("getnettotals", "")
376  + HelpExampleRpc("getnettotals", "")
377  );
378  if(!g_connman)
379  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
380 
382  obj.pushKV("totalbytesrecv", g_connman->GetTotalBytesRecv());
383  obj.pushKV("totalbytessent", g_connman->GetTotalBytesSent());
384  obj.pushKV("timemillis", GetTimeMillis());
385 
386  UniValue outboundLimit(UniValue::VOBJ);
387  outboundLimit.pushKV("timeframe", g_connman->GetMaxOutboundTimeframe());
388  outboundLimit.pushKV("target", g_connman->GetMaxOutboundTarget());
389  outboundLimit.pushKV("target_reached", g_connman->OutboundTargetReached(false));
390  outboundLimit.pushKV("serve_historical_blocks", !g_connman->OutboundTargetReached(true));
391  outboundLimit.pushKV("bytes_left_in_cycle", g_connman->GetOutboundTargetBytesLeft());
392  outboundLimit.pushKV("time_left_in_cycle", g_connman->GetMaxOutboundTimeLeftInCycle());
393  obj.pushKV("uploadtarget", outboundLimit);
394  return obj;
395 }
396 
397 static UniValue GetNetworksInfo()
398 {
399  UniValue networks(UniValue::VARR);
400  for(int n=0; n<NET_MAX; ++n)
401  {
402  enum Network network = static_cast<enum Network>(n);
403  if(network == NET_UNROUTABLE || network == NET_INTERNAL)
404  continue;
405  proxyType proxy;
407  GetProxy(network, proxy);
408  obj.pushKV("name", GetNetworkName(network));
409  obj.pushKV("limited", IsLimited(network));
410  obj.pushKV("reachable", IsReachable(network));
411  obj.pushKV("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string());
412  obj.pushKV("proxy_randomize_credentials", proxy.randomize_credentials);
413  networks.push_back(obj);
414  }
415  return networks;
416 }
417 
418 static UniValue getnetworkinfo(const JSONRPCRequest& request)
419 {
420  if (request.fHelp || request.params.size() != 0)
421  throw std::runtime_error(
422  "getnetworkinfo\n"
423  "Returns an object containing various state info regarding P2P networking.\n"
424  "\nResult:\n"
425  "{\n"
426  " \"version\": xxxxx, (numeric) the server version\n"
427  " \"subversion\": \"/Satoshi:x.x.x/\", (string) the server subversion string\n"
428  " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
429  " \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n"
430  " \"localrelay\": true|false, (bool) true if transaction relay is requested from peers\n"
431  " \"timeoffset\": xxxxx, (numeric) the time offset\n"
432  " \"connections\": xxxxx, (numeric) the number of connections\n"
433  " \"networkactive\": true|false, (bool) whether p2p networking is enabled\n"
434  " \"networks\": [ (array) information per network\n"
435  " {\n"
436  " \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n"
437  " \"limited\": true|false, (boolean) is the network limited using -onlynet?\n"
438  " \"reachable\": true|false, (boolean) is the network reachable?\n"
439  " \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n"
440  " \"proxy_randomize_credentials\": true|false, (string) Whether randomized credentials are used\n"
441  " }\n"
442  " ,...\n"
443  " ],\n"
444  " \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for transactions in " + CURRENCY_UNIT + "/kB\n"
445  " \"incrementalfee\": x.xxxxxxxx, (numeric) minimum fee increment for mempool limiting or BIP 125 replacement in " + CURRENCY_UNIT + "/kB\n"
446  " \"localaddresses\": [ (array) list of local addresses\n"
447  " {\n"
448  " \"address\": \"xxxx\", (string) network address\n"
449  " \"port\": xxx, (numeric) network port\n"
450  " \"score\": xxx (numeric) relative score\n"
451  " }\n"
452  " ,...\n"
453  " ]\n"
454  " \"warnings\": \"...\" (string) any network and blockchain warnings\n"
455  "}\n"
456  "\nExamples:\n"
457  + HelpExampleCli("getnetworkinfo", "")
458  + HelpExampleRpc("getnetworkinfo", "")
459  );
460 
461  LOCK(cs_main);
463  obj.pushKV("version", CLIENT_VERSION);
464  obj.pushKV("subversion", strSubVersion);
465  obj.pushKV("protocolversion",PROTOCOL_VERSION);
466  if(g_connman)
467  obj.pushKV("localservices", strprintf("%016x", g_connman->GetLocalServices()));
468  obj.pushKV("localrelay", fRelayTxes);
469  obj.pushKV("timeoffset", GetTimeOffset());
470  if (g_connman) {
471  obj.pushKV("networkactive", g_connman->GetNetworkActive());
472  obj.pushKV("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL));
473  }
474  obj.pushKV("networks", GetNetworksInfo());
475  obj.pushKV("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()));
476  obj.pushKV("incrementalfee", ValueFromAmount(::incrementalRelayFee.GetFeePerK()));
477  UniValue localAddresses(UniValue::VARR);
478  {
480  for (const std::pair<const CNetAddr, LocalServiceInfo> &item : mapLocalHost)
481  {
483  rec.pushKV("address", item.first.ToString());
484  rec.pushKV("port", item.second.nPort);
485  rec.pushKV("score", item.second.nScore);
486  localAddresses.push_back(rec);
487  }
488  }
489  obj.pushKV("localaddresses", localAddresses);
490  obj.pushKV("warnings", GetWarnings("statusbar"));
491  return obj;
492 }
493 
494 static UniValue setban(const JSONRPCRequest& request)
495 {
496  std::string strCommand;
497  if (!request.params[1].isNull())
498  strCommand = request.params[1].get_str();
499  if (request.fHelp || request.params.size() < 2 ||
500  (strCommand != "add" && strCommand != "remove"))
501  throw std::runtime_error(
502  "setban \"subnet\" \"add|remove\" (bantime) (absolute)\n"
503  "\nAttempts to add or remove an IP/Subnet from the banned list.\n"
504  "\nArguments:\n"
505  "1. \"subnet\" (string, required) The IP/Subnet (see getpeerinfo for nodes IP) with an optional netmask (default is /32 = single IP)\n"
506  "2. \"command\" (string, required) 'add' to add an IP/Subnet to the list, 'remove' to remove an IP/Subnet from the list\n"
507  "3. \"bantime\" (numeric, optional) 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)\n"
508  "4. \"absolute\" (boolean, optional) If set, the bantime must be an absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
509  "\nExamples:\n"
510  + HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
511  + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
512  + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\", 86400")
513  );
514  if(!g_connman)
515  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
516 
517  CSubNet subNet;
518  CNetAddr netAddr;
519  bool isSubnet = false;
520 
521  if (request.params[0].get_str().find('/') != std::string::npos)
522  isSubnet = true;
523 
524  if (!isSubnet) {
525  CNetAddr resolved;
526  LookupHost(request.params[0].get_str().c_str(), resolved, false);
527  netAddr = resolved;
528  }
529  else
530  LookupSubNet(request.params[0].get_str().c_str(), subNet);
531 
532  if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) )
533  throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Invalid IP/Subnet");
534 
535  if (strCommand == "add")
536  {
537  if (isSubnet ? g_connman->IsBanned(subNet) : g_connman->IsBanned(netAddr))
538  throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
539 
540  int64_t banTime = 0; //use standard bantime if not specified
541  if (!request.params[2].isNull())
542  banTime = request.params[2].get_int64();
543 
544  bool absolute = false;
545  if (request.params[3].isTrue())
546  absolute = true;
547 
548  isSubnet ? g_connman->Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : g_connman->Ban(netAddr, BanReasonManuallyAdded, banTime, absolute);
549  }
550  else if(strCommand == "remove")
551  {
552  if (!( isSubnet ? g_connman->Unban(subNet) : g_connman->Unban(netAddr) ))
553  throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Unban failed. Requested address/subnet was not previously banned.");
554  }
555  return NullUniValue;
556 }
557 
558 static UniValue listbanned(const JSONRPCRequest& request)
559 {
560  if (request.fHelp || request.params.size() != 0)
561  throw std::runtime_error(
562  "listbanned\n"
563  "\nList all banned IPs/Subnets.\n"
564  "\nExamples:\n"
565  + HelpExampleCli("listbanned", "")
566  + HelpExampleRpc("listbanned", "")
567  );
568 
569  if(!g_connman)
570  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
571 
572  banmap_t banMap;
573  g_connman->GetBanned(banMap);
574 
575  UniValue bannedAddresses(UniValue::VARR);
576  for (const auto& entry : banMap)
577  {
578  const CBanEntry& banEntry = entry.second;
580  rec.pushKV("address", entry.first.ToString());
581  rec.pushKV("banned_until", banEntry.nBanUntil);
582  rec.pushKV("ban_created", banEntry.nCreateTime);
583  rec.pushKV("ban_reason", banEntry.banReasonToString());
584 
585  bannedAddresses.push_back(rec);
586  }
587 
588  return bannedAddresses;
589 }
590 
591 static UniValue clearbanned(const JSONRPCRequest& request)
592 {
593  if (request.fHelp || request.params.size() != 0)
594  throw std::runtime_error(
595  "clearbanned\n"
596  "\nClear all banned IPs.\n"
597  "\nExamples:\n"
598  + HelpExampleCli("clearbanned", "")
599  + HelpExampleRpc("clearbanned", "")
600  );
601  if(!g_connman)
602  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
603 
604  g_connman->ClearBanned();
605 
606  return NullUniValue;
607 }
608 
609 static UniValue setnetworkactive(const JSONRPCRequest& request)
610 {
611  if (request.fHelp || request.params.size() != 1) {
612  throw std::runtime_error(
613  "setnetworkactive true|false\n"
614  "\nDisable/enable all p2p network activity.\n"
615  "\nArguments:\n"
616  "1. \"state\" (boolean, required) true to enable networking, false to disable\n"
617  );
618  }
619 
620  if (!g_connman) {
621  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
622  }
623 
624  g_connman->SetNetworkActive(request.params[0].get_bool());
625 
626  return g_connman->GetNetworkActive();
627 }
628 
629 static UniValue getnodeaddresses(const JSONRPCRequest& request)
630 {
631  if (request.fHelp || request.params.size() > 1) {
632  throw std::runtime_error(
633  "getnodeaddresses ( count )\n"
634  "\nReturn known addresses which can potentially be used to find new nodes in the network\n"
635  "\nArguments:\n"
636  "1. \"count\" (numeric, optional) How many addresses to return. Limited to the smaller of " + std::to_string(ADDRMAN_GETADDR_MAX) +
637  " or " + std::to_string(ADDRMAN_GETADDR_MAX_PCT) + "% of all known addresses. (default = 1)\n"
638  "\nResult:\n"
639  "[\n"
640  " {\n"
641  " \"time\": ttt, (numeric) Timestamp in seconds since epoch (Jan 1 1970 GMT) keeping track of when the node was last seen\n"
642  " \"services\": n, (numeric) The services offered\n"
643  " \"address\": \"host\", (string) The address of the node\n"
644  " \"port\": n (numeric) The port of the node\n"
645  " }\n"
646  " ,....\n"
647  "]\n"
648  "\nExamples:\n"
649  + HelpExampleCli("getnodeaddresses", "8")
650  + HelpExampleRpc("getnodeaddresses", "8")
651  );
652  }
653  if (!g_connman) {
654  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
655  }
656 
657  int count = 1;
658  if (!request.params[0].isNull()) {
659  count = request.params[0].get_int();
660  if (count <= 0) {
661  throw JSONRPCError(RPC_INVALID_PARAMETER, "Address count out of range");
662  }
663  }
664  // returns a shuffled list of CAddress
665  std::vector<CAddress> vAddr = g_connman->GetAddresses();
667 
668  int address_return_count = std::min<int>(count, vAddr.size());
669  for (int i = 0; i < address_return_count; ++i) {
671  const CAddress& addr = vAddr[i];
672  obj.pushKV("time", (int)addr.nTime);
673  obj.pushKV("services", (uint64_t)addr.nServices);
674  obj.pushKV("address", addr.ToStringIP());
675  obj.pushKV("port", addr.GetPort());
676  ret.push_back(obj);
677  }
678  return ret;
679 }
680 
681 // clang-format off
682 static const CRPCCommand commands[] =
683 { // category name actor (function) argNames
684  // --------------------- ------------------------ ----------------------- ----------
685  { "network", "getconnectioncount", &getconnectioncount, {} },
686  { "network", "ping", &ping, {} },
687  { "network", "getpeerinfo", &getpeerinfo, {} },
688  { "network", "addnode", &addnode, {"node","command"} },
689  { "network", "disconnectnode", &disconnectnode, {"address", "nodeid"} },
690  { "network", "getaddednodeinfo", &getaddednodeinfo, {"node"} },
691  { "network", "getnettotals", &getnettotals, {} },
692  { "network", "getnetworkinfo", &getnetworkinfo, {} },
693  { "network", "setban", &setban, {"subnet", "command", "bantime", "absolute"} },
694  { "network", "listbanned", &listbanned, {} },
695  { "network", "clearbanned", &clearbanned, {} },
696  { "network", "setnetworkactive", &setnetworkactive, {"state"} },
697  { "network", "getnodeaddresses", &getnodeaddresses, {"count"} },
698 };
699 // clang-format on
700 
702 {
703  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
704  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
705 }
unsigned short GetPort() const
Definition: netaddress.cpp:505
Node has not been added before.
Definition: protocol.h:70
Bitcoin RPC command dispatcher.
Definition: server.h:143
bool get_bool() const
#define strprintf
Definition: tinyformat.h:1066
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
UniValue ret(UniValue::VARR)
Definition: rpcwallet.cpp:1140
void RegisterNetRPCCommands(CRPCTable &t)
Register P2P networking RPC commands.
Definition: net.cpp:701
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:19
const std::string & get_str() const
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:516
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
bool isStr() const
Definition: univalue.h:82
int64_t get_int64() const
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are: ...
Definition: timedata.cpp:29
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:40
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:285
std::string banReasonToString() const
Definition: addrdb.h:64
int64_t nCreateTime
Definition: addrdb.h:31
Invalid, missing or duplicate parameter.
Definition: protocol.h:52
bool IsValid() const
Definition: netaddress.cpp:188
std::string name
Definition: server.h:135
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:77
bool fRelayTxes
Definition: net.cpp:85
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
CCriticalSection cs_main
Definition: validation.cpp:216
bool randomize_credentials
Definition: netbase.h:37
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:241
UniValue params
Definition: server.h:44
std::string ToStringIP() const
Definition: netaddress.cpp:254
#define LOCK(cs)
Definition: sync.h:181
CCriticalSection cs_mapLocalHost
Definition: net.cpp:86
std::map< CNetAddr, LocalServiceInfo > mapLocalHost
Definition: net.cpp:87
A CService with information about it as peer.
Definition: protocol.h:328
Network
Definition: netaddress.h:20
int64_t NodeId
Definition: net.h:88
int get_int() const
Invalid IP/Subnet.
Definition: protocol.h:72
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:511
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:89
bool isNull() const
Definition: univalue.h:78
bool isTrue() const
Definition: univalue.h:79
int64_t nBanUntil
Definition: addrdb.h:32
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:614
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:32
bool fHelp
Definition: server.h:45
bool IsValid() const
Definition: netaddress.cpp:699
#define ADDRMAN_GETADDR_MAX
the maximum number of nodes to return in a getaddr call
Definition: addrman.h:175
std::atomic< bool > fPingQueued
Definition: net.h:742
unsigned int nTime
Definition: protocol.h:360
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
Definition: net.cpp:288
ServiceFlags nServices
Definition: protocol.h:357
CService proxy
Definition: netbase.h:36
bool IsValid() const
Definition: netbase.h:34
#define ARRAYLEN(array)
int64_t GetTimeMillis()
Definition: utiltime.cpp:40
std::string ToStringIPPort() const
Definition: netaddress.cpp:565
Node to disconnect not found in connected nodes.
Definition: protocol.h:71
Node is already added.
Definition: protocol.h:69
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:74
const UniValue NullUniValue
Definition: univalue.cpp:13
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:551
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:51
No valid connection manager instance found.
Definition: protocol.h:73
size_t size() const
Definition: univalue.h:69
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:51
Information about a peer.
Definition: net.h:626
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:118
std::vector< int > vHeightInFlight
Definition: addrdb.h:26
CFeeRate incrementalRelayFee
Definition: policy.cpp:242
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:41
bool IsLimited(enum Network net)
Definition: net.cpp:256
#define ADDRMAN_GETADDR_MAX_PCT
the maximum percentage of nodes to return in a getaddr call
Definition: addrman.h:172