You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net.cpp 30KB

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