Avoid redundant redeclaration of GetWarnings(const string&)
[bitcoinplatinum.git] / src / rpc / net.cpp
blob090d9e448e86e837adcfbb4993ac8a5f40660873
1 // Copyright (c) 2009-2016 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.
5 #include "rpc/server.h"
7 #include "chainparams.h"
8 #include "clientversion.h"
9 #include "validation.h"
10 #include "net.h"
11 #include "net_processing.h"
12 #include "netbase.h"
13 #include "policy/policy.h"
14 #include "protocol.h"
15 #include "sync.h"
16 #include "timedata.h"
17 #include "ui_interface.h"
18 #include "util.h"
19 #include "utilstrencodings.h"
20 #include "version.h"
21 #include "warnings.h"
23 #include <univalue.h>
25 UniValue getconnectioncount(const JSONRPCRequest& request)
27 if (request.fHelp || request.params.size() != 0)
28 throw std::runtime_error(
29 "getconnectioncount\n"
30 "\nReturns the number of connections to other nodes.\n"
31 "\nResult:\n"
32 "n (numeric) The connection count\n"
33 "\nExamples:\n"
34 + HelpExampleCli("getconnectioncount", "")
35 + HelpExampleRpc("getconnectioncount", "")
38 if(!g_connman)
39 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
41 return (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL);
44 UniValue ping(const JSONRPCRequest& request)
46 if (request.fHelp || request.params.size() != 0)
47 throw std::runtime_error(
48 "ping\n"
49 "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
50 "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
51 "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n"
52 "\nExamples:\n"
53 + HelpExampleCli("ping", "")
54 + HelpExampleRpc("ping", "")
57 if(!g_connman)
58 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
60 // Request that each node send a ping during next message processing pass
61 g_connman->ForEachNode([](CNode* pnode) {
62 pnode->fPingQueued = true;
63 });
64 return NullUniValue;
67 UniValue getpeerinfo(const JSONRPCRequest& request)
69 if (request.fHelp || request.params.size() != 0)
70 throw std::runtime_error(
71 "getpeerinfo\n"
72 "\nReturns data about each connected network node as a json array of objects.\n"
73 "\nResult:\n"
74 "[\n"
75 " {\n"
76 " \"id\": n, (numeric) Peer index\n"
77 " \"addr\":\"host:port\", (string) The IP address and port of the peer\n"
78 " \"addrbind\":\"ip:port\", (string) Bind address of the connection to the peer\n"
79 " \"addrlocal\":\"ip:port\", (string) Local address as reported by the peer\n"
80 " \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n"
81 " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n"
82 " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n"
83 " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n"
84 " \"bytessent\": n, (numeric) The total bytes sent\n"
85 " \"bytesrecv\": n, (numeric) The total bytes received\n"
86 " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n"
87 " \"timeoffset\": ttt, (numeric) The time offset in seconds\n"
88 " \"pingtime\": n, (numeric) ping time (if available)\n"
89 " \"minping\": n, (numeric) minimum observed ping time (if any at all)\n"
90 " \"pingwait\": n, (numeric) ping wait (if non-zero)\n"
91 " \"version\": v, (numeric) The peer version, such as 7001\n"
92 " \"subver\": \"/Satoshi:0.8.5/\", (string) The string version\n"
93 " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n"
94 " \"addnode\": true|false, (boolean) Whether connection was due to addnode and is using an addnode slot\n"
95 " \"startingheight\": n, (numeric) The starting height (block) of the peer\n"
96 " \"banscore\": n, (numeric) The ban score\n"
97 " \"synced_headers\": n, (numeric) The last header we have in common with this peer\n"
98 " \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n"
99 " \"inflight\": [\n"
100 " n, (numeric) The heights of blocks we're currently asking from this peer\n"
101 " ...\n"
102 " ],\n"
103 " \"whitelisted\": true|false, (boolean) Whether the peer is whitelisted\n"
104 " \"bytessent_per_msg\": {\n"
105 " \"addr\": n, (numeric) The total bytes sent aggregated by message type\n"
106 " ...\n"
107 " },\n"
108 " \"bytesrecv_per_msg\": {\n"
109 " \"addr\": n, (numeric) The total bytes received aggregated by message type\n"
110 " ...\n"
111 " }\n"
112 " }\n"
113 " ,...\n"
114 "]\n"
115 "\nExamples:\n"
116 + HelpExampleCli("getpeerinfo", "")
117 + HelpExampleRpc("getpeerinfo", "")
120 if(!g_connman)
121 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
123 std::vector<CNodeStats> vstats;
124 g_connman->GetNodeStats(vstats);
126 UniValue ret(UniValue::VARR);
128 for (const CNodeStats& stats : vstats) {
129 UniValue obj(UniValue::VOBJ);
130 CNodeStateStats statestats;
131 bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
132 obj.push_back(Pair("id", stats.nodeid));
133 obj.push_back(Pair("addr", stats.addrName));
134 if (!(stats.addrLocal.empty()))
135 obj.push_back(Pair("addrlocal", stats.addrLocal));
136 if (stats.addrBind.IsValid())
137 obj.push_back(Pair("addrbind", stats.addrBind.ToString()));
138 obj.push_back(Pair("services", strprintf("%016x", stats.nServices)));
139 obj.push_back(Pair("relaytxes", stats.fRelayTxes));
140 obj.push_back(Pair("lastsend", stats.nLastSend));
141 obj.push_back(Pair("lastrecv", stats.nLastRecv));
142 obj.push_back(Pair("bytessent", stats.nSendBytes));
143 obj.push_back(Pair("bytesrecv", stats.nRecvBytes));
144 obj.push_back(Pair("conntime", stats.nTimeConnected));
145 obj.push_back(Pair("timeoffset", stats.nTimeOffset));
146 if (stats.dPingTime > 0.0)
147 obj.push_back(Pair("pingtime", stats.dPingTime));
148 if (stats.dMinPing < std::numeric_limits<int64_t>::max()/1e6)
149 obj.push_back(Pair("minping", stats.dMinPing));
150 if (stats.dPingWait > 0.0)
151 obj.push_back(Pair("pingwait", stats.dPingWait));
152 obj.push_back(Pair("version", stats.nVersion));
153 // Use the sanitized form of subver here, to avoid tricksy remote peers from
154 // corrupting or modifying the JSON output by putting special characters in
155 // their ver message.
156 obj.push_back(Pair("subver", stats.cleanSubVer));
157 obj.push_back(Pair("inbound", stats.fInbound));
158 obj.push_back(Pair("addnode", stats.fAddnode));
159 obj.push_back(Pair("startingheight", stats.nStartingHeight));
160 if (fStateStats) {
161 obj.push_back(Pair("banscore", statestats.nMisbehavior));
162 obj.push_back(Pair("synced_headers", statestats.nSyncHeight));
163 obj.push_back(Pair("synced_blocks", statestats.nCommonHeight));
164 UniValue heights(UniValue::VARR);
165 for (int height : statestats.vHeightInFlight) {
166 heights.push_back(height);
168 obj.push_back(Pair("inflight", heights));
170 obj.push_back(Pair("whitelisted", stats.fWhitelisted));
172 UniValue sendPerMsgCmd(UniValue::VOBJ);
173 for (const mapMsgCmdSize::value_type &i : stats.mapSendBytesPerMsgCmd) {
174 if (i.second > 0)
175 sendPerMsgCmd.push_back(Pair(i.first, i.second));
177 obj.push_back(Pair("bytessent_per_msg", sendPerMsgCmd));
179 UniValue recvPerMsgCmd(UniValue::VOBJ);
180 for (const mapMsgCmdSize::value_type &i : stats.mapRecvBytesPerMsgCmd) {
181 if (i.second > 0)
182 recvPerMsgCmd.push_back(Pair(i.first, i.second));
184 obj.push_back(Pair("bytesrecv_per_msg", recvPerMsgCmd));
186 ret.push_back(obj);
189 return ret;
192 UniValue addnode(const JSONRPCRequest& request)
194 std::string strCommand;
195 if (request.params.size() == 2)
196 strCommand = request.params[1].get_str();
197 if (request.fHelp || request.params.size() != 2 ||
198 (strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
199 throw std::runtime_error(
200 "addnode \"node\" \"add|remove|onetry\"\n"
201 "\nAttempts to add or remove a node from the addnode list.\n"
202 "Or try a connection to a node once.\n"
203 "\nArguments:\n"
204 "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
205 "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"
206 "\nExamples:\n"
207 + HelpExampleCli("addnode", "\"192.168.0.6:8333\" \"onetry\"")
208 + HelpExampleRpc("addnode", "\"192.168.0.6:8333\", \"onetry\"")
211 if(!g_connman)
212 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
214 std::string strNode = request.params[0].get_str();
216 if (strCommand == "onetry")
218 CAddress addr;
219 g_connman->OpenNetworkConnection(addr, false, NULL, strNode.c_str());
220 return NullUniValue;
223 if (strCommand == "add")
225 if(!g_connman->AddNode(strNode))
226 throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
228 else if(strCommand == "remove")
230 if(!g_connman->RemoveAddedNode(strNode))
231 throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
234 return NullUniValue;
237 UniValue disconnectnode(const JSONRPCRequest& request)
239 if (request.fHelp || request.params.size() == 0 || request.params.size() >= 3)
240 throw std::runtime_error(
241 "disconnectnode \"[address]\" [nodeid]\n"
242 "\nImmediately disconnects from the specified peer node.\n"
243 "\nStrictly one out of 'address' and 'nodeid' can be provided to identify the node.\n"
244 "\nTo disconnect by nodeid, either set 'address' to the empty string, or call using the named 'nodeid' argument only.\n"
245 "\nArguments:\n"
246 "1. \"address\" (string, optional) The IP address/port of the node\n"
247 "2. \"nodeid\" (number, optional) The node ID (see getpeerinfo for node IDs)\n"
248 "\nExamples:\n"
249 + HelpExampleCli("disconnectnode", "\"192.168.0.6:8333\"")
250 + HelpExampleCli("disconnectnode", "\"\" 1")
251 + HelpExampleRpc("disconnectnode", "\"192.168.0.6:8333\"")
252 + HelpExampleRpc("disconnectnode", "\"\", 1")
255 if(!g_connman)
256 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
258 bool success;
259 const UniValue &address_arg = request.params[0];
260 const UniValue &id_arg = request.params.size() < 2 ? NullUniValue : request.params[1];
262 if (!address_arg.isNull() && id_arg.isNull()) {
263 /* handle disconnect-by-address */
264 success = g_connman->DisconnectNode(address_arg.get_str());
265 } else if (!id_arg.isNull() && (address_arg.isNull() || (address_arg.isStr() && address_arg.get_str().empty()))) {
266 /* handle disconnect-by-id */
267 NodeId nodeid = (NodeId) id_arg.get_int64();
268 success = g_connman->DisconnectNode(nodeid);
269 } else {
270 throw JSONRPCError(RPC_INVALID_PARAMS, "Only one of address and nodeid should be provided.");
273 if (!success) {
274 throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes");
277 return NullUniValue;
280 UniValue getaddednodeinfo(const JSONRPCRequest& request)
282 if (request.fHelp || request.params.size() > 1)
283 throw std::runtime_error(
284 "getaddednodeinfo ( \"node\" )\n"
285 "\nReturns information about the given added node, or all added nodes\n"
286 "(note that onetry addnodes are not listed here)\n"
287 "\nArguments:\n"
288 "1. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n"
289 "\nResult:\n"
290 "[\n"
291 " {\n"
292 " \"addednode\" : \"192.168.0.201\", (string) The node IP address or name (as provided to addnode)\n"
293 " \"connected\" : true|false, (boolean) If connected\n"
294 " \"addresses\" : [ (list of objects) Only when connected = true\n"
295 " {\n"
296 " \"address\" : \"192.168.0.201:8333\", (string) The bitcoin server IP and port we're connected to\n"
297 " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n"
298 " }\n"
299 " ]\n"
300 " }\n"
301 " ,...\n"
302 "]\n"
303 "\nExamples:\n"
304 + HelpExampleCli("getaddednodeinfo", "\"192.168.0.201\"")
305 + HelpExampleRpc("getaddednodeinfo", "\"192.168.0.201\"")
308 if(!g_connman)
309 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
311 std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo();
313 if (request.params.size() == 1) {
314 bool found = false;
315 for (const AddedNodeInfo& info : vInfo) {
316 if (info.strAddedNode == request.params[0].get_str()) {
317 vInfo.assign(1, info);
318 found = true;
319 break;
322 if (!found) {
323 throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
327 UniValue ret(UniValue::VARR);
329 for (const AddedNodeInfo& info : vInfo) {
330 UniValue obj(UniValue::VOBJ);
331 obj.push_back(Pair("addednode", info.strAddedNode));
332 obj.push_back(Pair("connected", info.fConnected));
333 UniValue addresses(UniValue::VARR);
334 if (info.fConnected) {
335 UniValue address(UniValue::VOBJ);
336 address.push_back(Pair("address", info.resolvedAddress.ToString()));
337 address.push_back(Pair("connected", info.fInbound ? "inbound" : "outbound"));
338 addresses.push_back(address);
340 obj.push_back(Pair("addresses", addresses));
341 ret.push_back(obj);
344 return ret;
347 UniValue getnettotals(const JSONRPCRequest& request)
349 if (request.fHelp || request.params.size() > 0)
350 throw std::runtime_error(
351 "getnettotals\n"
352 "\nReturns information about network traffic, including bytes in, bytes out,\n"
353 "and current time.\n"
354 "\nResult:\n"
355 "{\n"
356 " \"totalbytesrecv\": n, (numeric) Total bytes received\n"
357 " \"totalbytessent\": n, (numeric) Total bytes sent\n"
358 " \"timemillis\": t, (numeric) Current UNIX time in milliseconds\n"
359 " \"uploadtarget\":\n"
360 " {\n"
361 " \"timeframe\": n, (numeric) Length of the measuring timeframe in seconds\n"
362 " \"target\": n, (numeric) Target in bytes\n"
363 " \"target_reached\": true|false, (boolean) True if target is reached\n"
364 " \"serve_historical_blocks\": true|false, (boolean) True if serving historical blocks\n"
365 " \"bytes_left_in_cycle\": t, (numeric) Bytes left in current time cycle\n"
366 " \"time_left_in_cycle\": t (numeric) Seconds left in current time cycle\n"
367 " }\n"
368 "}\n"
369 "\nExamples:\n"
370 + HelpExampleCli("getnettotals", "")
371 + HelpExampleRpc("getnettotals", "")
373 if(!g_connman)
374 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
376 UniValue obj(UniValue::VOBJ);
377 obj.push_back(Pair("totalbytesrecv", g_connman->GetTotalBytesRecv()));
378 obj.push_back(Pair("totalbytessent", g_connman->GetTotalBytesSent()));
379 obj.push_back(Pair("timemillis", GetTimeMillis()));
381 UniValue outboundLimit(UniValue::VOBJ);
382 outboundLimit.push_back(Pair("timeframe", g_connman->GetMaxOutboundTimeframe()));
383 outboundLimit.push_back(Pair("target", g_connman->GetMaxOutboundTarget()));
384 outboundLimit.push_back(Pair("target_reached", g_connman->OutboundTargetReached(false)));
385 outboundLimit.push_back(Pair("serve_historical_blocks", !g_connman->OutboundTargetReached(true)));
386 outboundLimit.push_back(Pair("bytes_left_in_cycle", g_connman->GetOutboundTargetBytesLeft()));
387 outboundLimit.push_back(Pair("time_left_in_cycle", g_connman->GetMaxOutboundTimeLeftInCycle()));
388 obj.push_back(Pair("uploadtarget", outboundLimit));
389 return obj;
392 static UniValue GetNetworksInfo()
394 UniValue networks(UniValue::VARR);
395 for(int n=0; n<NET_MAX; ++n)
397 enum Network network = static_cast<enum Network>(n);
398 if(network == NET_UNROUTABLE || network == NET_INTERNAL)
399 continue;
400 proxyType proxy;
401 UniValue obj(UniValue::VOBJ);
402 GetProxy(network, proxy);
403 obj.push_back(Pair("name", GetNetworkName(network)));
404 obj.push_back(Pair("limited", IsLimited(network)));
405 obj.push_back(Pair("reachable", IsReachable(network)));
406 obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string()));
407 obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials));
408 networks.push_back(obj);
410 return networks;
413 UniValue getnetworkinfo(const JSONRPCRequest& request)
415 if (request.fHelp || request.params.size() != 0)
416 throw std::runtime_error(
417 "getnetworkinfo\n"
418 "Returns an object containing various state info regarding P2P networking.\n"
419 "\nResult:\n"
420 "{\n"
421 " \"version\": xxxxx, (numeric) the server version\n"
422 " \"subversion\": \"/Satoshi:x.x.x/\", (string) the server subversion string\n"
423 " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
424 " \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n"
425 " \"localrelay\": true|false, (bool) true if transaction relay is requested from peers\n"
426 " \"timeoffset\": xxxxx, (numeric) the time offset\n"
427 " \"connections\": xxxxx, (numeric) the number of connections\n"
428 " \"networkactive\": true|false, (bool) whether p2p networking is enabled\n"
429 " \"networks\": [ (array) information per network\n"
430 " {\n"
431 " \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n"
432 " \"limited\": true|false, (boolean) is the network limited using -onlynet?\n"
433 " \"reachable\": true|false, (boolean) is the network reachable?\n"
434 " \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n"
435 " \"proxy_randomize_credentials\": true|false, (string) Whether randomized credentials are used\n"
436 " }\n"
437 " ,...\n"
438 " ],\n"
439 " \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for transactions in " + CURRENCY_UNIT + "/kB\n"
440 " \"incrementalfee\": x.xxxxxxxx, (numeric) minimum fee increment for mempool limiting or BIP 125 replacement in " + CURRENCY_UNIT + "/kB\n"
441 " \"localaddresses\": [ (array) list of local addresses\n"
442 " {\n"
443 " \"address\": \"xxxx\", (string) network address\n"
444 " \"port\": xxx, (numeric) network port\n"
445 " \"score\": xxx (numeric) relative score\n"
446 " }\n"
447 " ,...\n"
448 " ]\n"
449 " \"warnings\": \"...\" (string) any network warnings\n"
450 "}\n"
451 "\nExamples:\n"
452 + HelpExampleCli("getnetworkinfo", "")
453 + HelpExampleRpc("getnetworkinfo", "")
456 LOCK(cs_main);
457 UniValue obj(UniValue::VOBJ);
458 obj.push_back(Pair("version", CLIENT_VERSION));
459 obj.push_back(Pair("subversion", strSubVersion));
460 obj.push_back(Pair("protocolversion",PROTOCOL_VERSION));
461 if(g_connman)
462 obj.push_back(Pair("localservices", strprintf("%016x", g_connman->GetLocalServices())));
463 obj.push_back(Pair("localrelay", fRelayTxes));
464 obj.push_back(Pair("timeoffset", GetTimeOffset()));
465 if (g_connman) {
466 obj.push_back(Pair("networkactive", g_connman->GetNetworkActive()));
467 obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)));
469 obj.push_back(Pair("networks", GetNetworksInfo()));
470 obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
471 obj.push_back(Pair("incrementalfee", ValueFromAmount(::incrementalRelayFee.GetFeePerK())));
472 UniValue localAddresses(UniValue::VARR);
474 LOCK(cs_mapLocalHost);
475 for (const std::pair<CNetAddr, LocalServiceInfo> &item : mapLocalHost)
477 UniValue rec(UniValue::VOBJ);
478 rec.push_back(Pair("address", item.first.ToString()));
479 rec.push_back(Pair("port", item.second.nPort));
480 rec.push_back(Pair("score", item.second.nScore));
481 localAddresses.push_back(rec);
484 obj.push_back(Pair("localaddresses", localAddresses));
485 obj.push_back(Pair("warnings", GetWarnings("statusbar")));
486 return obj;
489 UniValue setban(const JSONRPCRequest& request)
491 std::string strCommand;
492 if (request.params.size() >= 2)
493 strCommand = request.params[1].get_str();
494 if (request.fHelp || request.params.size() < 2 ||
495 (strCommand != "add" && strCommand != "remove"))
496 throw std::runtime_error(
497 "setban \"subnet\" \"add|remove\" (bantime) (absolute)\n"
498 "\nAttempts to add or remove an IP/Subnet from the banned list.\n"
499 "\nArguments:\n"
500 "1. \"subnet\" (string, required) The IP/Subnet (see getpeerinfo for nodes IP) with an optional netmask (default is /32 = single IP)\n"
501 "2. \"command\" (string, required) 'add' to add an IP/Subnet to the list, 'remove' to remove an IP/Subnet from the list\n"
502 "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"
503 "4. \"absolute\" (boolean, optional) If set, the bantime must be an absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
504 "\nExamples:\n"
505 + HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
506 + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
507 + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\", 86400")
509 if(!g_connman)
510 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
512 CSubNet subNet;
513 CNetAddr netAddr;
514 bool isSubnet = false;
516 if (request.params[0].get_str().find("/") != std::string::npos)
517 isSubnet = true;
519 if (!isSubnet) {
520 CNetAddr resolved;
521 LookupHost(request.params[0].get_str().c_str(), resolved, false);
522 netAddr = resolved;
524 else
525 LookupSubNet(request.params[0].get_str().c_str(), subNet);
527 if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) )
528 throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Invalid IP/Subnet");
530 if (strCommand == "add")
532 if (isSubnet ? g_connman->IsBanned(subNet) : g_connman->IsBanned(netAddr))
533 throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
535 int64_t banTime = 0; //use standard bantime if not specified
536 if (request.params.size() >= 3 && !request.params[2].isNull())
537 banTime = request.params[2].get_int64();
539 bool absolute = false;
540 if (request.params.size() == 4 && request.params[3].isTrue())
541 absolute = true;
543 isSubnet ? g_connman->Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : g_connman->Ban(netAddr, BanReasonManuallyAdded, banTime, absolute);
545 else if(strCommand == "remove")
547 if (!( isSubnet ? g_connman->Unban(subNet) : g_connman->Unban(netAddr) ))
548 throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Unban failed. Requested address/subnet was not previously banned.");
550 return NullUniValue;
553 UniValue listbanned(const JSONRPCRequest& request)
555 if (request.fHelp || request.params.size() != 0)
556 throw std::runtime_error(
557 "listbanned\n"
558 "\nList all banned IPs/Subnets.\n"
559 "\nExamples:\n"
560 + HelpExampleCli("listbanned", "")
561 + HelpExampleRpc("listbanned", "")
564 if(!g_connman)
565 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
567 banmap_t banMap;
568 g_connman->GetBanned(banMap);
570 UniValue bannedAddresses(UniValue::VARR);
571 for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++)
573 CBanEntry banEntry = (*it).second;
574 UniValue rec(UniValue::VOBJ);
575 rec.push_back(Pair("address", (*it).first.ToString()));
576 rec.push_back(Pair("banned_until", banEntry.nBanUntil));
577 rec.push_back(Pair("ban_created", banEntry.nCreateTime));
578 rec.push_back(Pair("ban_reason", banEntry.banReasonToString()));
580 bannedAddresses.push_back(rec);
583 return bannedAddresses;
586 UniValue clearbanned(const JSONRPCRequest& request)
588 if (request.fHelp || request.params.size() != 0)
589 throw std::runtime_error(
590 "clearbanned\n"
591 "\nClear all banned IPs.\n"
592 "\nExamples:\n"
593 + HelpExampleCli("clearbanned", "")
594 + HelpExampleRpc("clearbanned", "")
596 if(!g_connman)
597 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
599 g_connman->ClearBanned();
601 return NullUniValue;
604 UniValue setnetworkactive(const JSONRPCRequest& request)
606 if (request.fHelp || request.params.size() != 1) {
607 throw std::runtime_error(
608 "setnetworkactive true|false\n"
609 "\nDisable/enable all p2p network activity.\n"
610 "\nArguments:\n"
611 "1. \"state\" (boolean, required) true to enable networking, false to disable\n"
615 if (!g_connman) {
616 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
619 g_connman->SetNetworkActive(request.params[0].get_bool());
621 return g_connman->GetNetworkActive();
624 static const CRPCCommand commands[] =
625 { // category name actor (function) okSafeMode
626 // --------------------- ------------------------ ----------------------- ----------
627 { "network", "getconnectioncount", &getconnectioncount, true, {} },
628 { "network", "ping", &ping, true, {} },
629 { "network", "getpeerinfo", &getpeerinfo, true, {} },
630 { "network", "addnode", &addnode, true, {"node","command"} },
631 { "network", "disconnectnode", &disconnectnode, true, {"address", "nodeid"} },
632 { "network", "getaddednodeinfo", &getaddednodeinfo, true, {"node"} },
633 { "network", "getnettotals", &getnettotals, true, {} },
634 { "network", "getnetworkinfo", &getnetworkinfo, true, {} },
635 { "network", "setban", &setban, true, {"subnet", "command", "bantime", "absolute"} },
636 { "network", "listbanned", &listbanned, true, {} },
637 { "network", "clearbanned", &clearbanned, true, {} },
638 { "network", "setnetworkactive", &setnetworkactive, true, {"state"} },
641 void RegisterNetRPCCommands(CRPCTable &t)
643 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
644 t.appendCommand(commands[vcidx].name, &commands[vcidx]);