Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

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