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