Bitcoin ABC 0.33.8
P2P Digital Currency
net.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2019 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <rpc/server.h>
6
7#include <addrman.h>
9#include <banman.h>
10#include <chainparams.h>
11#include <clientversion.h>
12#include <config.h>
13#include <net_permissions.h>
14#include <net_processing.h>
15#include <net_types.h> // For banmap_t
16#include <netbase.h>
17#include <node/context.h>
19#include <policy/settings.h>
20#include <rpc/blockchain.h>
21#include <rpc/protocol.h>
22#include <rpc/server_util.h>
23#include <rpc/util.h>
24#include <sync.h>
25#include <timedata.h>
26#include <util/chaintype.h>
27#include <util/strencodings.h>
28#include <util/string.h>
29#include <util/time.h>
30#include <util/translation.h>
31#include <validation.h>
32#include <warnings.h>
33
34#include <optional>
35
36#include <univalue.h>
37
39using util::Join;
41
43 return RPCHelpMan{
44 "getconnectioncount",
45 "Returns the number of connections to other nodes.\n",
46 {},
47 RPCResult{RPCResult::Type::NUM, "", "The connection count"},
48 RPCExamples{HelpExampleCli("getconnectioncount", "") +
49 HelpExampleRpc("getconnectioncount", "")},
50 [&](const RPCHelpMan &self, const Config &config,
51 const JSONRPCRequest &request) -> UniValue {
52 NodeContext &node = EnsureAnyNodeContext(request.context);
53 const CConnman &connman = EnsureConnman(node);
54
56 },
57 };
58}
59
60static RPCHelpMan ping() {
61 return RPCHelpMan{
62 "ping",
63 "Requests that a ping be sent to all other nodes, to measure ping "
64 "time.\n"
65 "Results provided in getpeerinfo, pingtime and pingwait fields are "
66 "decimal seconds.\n"
67 "Ping command is handled in queue with all other commands, so it "
68 "measures processing backlog, not just network ping.\n",
69 {},
71 RPCExamples{HelpExampleCli("ping", "") + HelpExampleRpc("ping", "")},
72 [&](const RPCHelpMan &self, const Config &config,
73 const JSONRPCRequest &request) -> UniValue {
74 NodeContext &node = EnsureAnyNodeContext(request.context);
75 PeerManager &peerman = EnsurePeerman(node);
76
77 // Request that each node send a ping during next message processing
78 // pass
79 peerman.SendPings();
80 return NullUniValue;
81 },
82 };
83}
84
86 return RPCHelpMan{
87 "getpeerinfo",
88 "Returns data about each connected network node as a json array of "
89 "objects.\n",
90 {},
93 "",
94 "",
95 {{
97 "",
98 "",
99 {{
100 {RPCResult::Type::NUM, "id", "Peer index"},
101 {RPCResult::Type::STR, "addr",
102 "(host:port) The IP address and port of the peer"},
103 {RPCResult::Type::STR, "addrbind",
104 "(ip:port) Bind address of the connection to the peer"},
105 {RPCResult::Type::STR, "addrlocal",
106 "(ip:port) Local address as reported by the peer"},
107 {RPCResult::Type::NUM, "addr_processed",
108 "The total number of addresses processed, excluding those "
109 "dropped due to rate limiting"},
110 {RPCResult::Type::NUM, "addr_rate_limited",
111 "The total number of addresses dropped due to rate "
112 "limiting"},
113 {RPCResult::Type::STR, "network",
114 "Network (" +
115 Join(GetNetworkNames(/* append_unroutable */ true),
116 ", ") +
117 ")"},
118 {RPCResult::Type::NUM, "mapped_as",
119 "The AS in the BGP route to the peer used for "
120 "diversifying\n"
121 "peer selection (only available if the asmap config flag "
122 "is set)\n"},
123 {RPCResult::Type::STR_HEX, "services",
124 "The services offered"},
126 "servicesnames",
127 "the services offered, in human-readable form",
128 {{RPCResult::Type::STR, "SERVICE_NAME",
129 "the service name if it is recognised"}}},
130 {RPCResult::Type::BOOL, "relaytxes",
131 "Whether peer has asked us to relay transactions to it"},
132 {RPCResult::Type::NUM_TIME, "lastsend",
133 "The " + UNIX_EPOCH_TIME + " of the last send"},
134 {RPCResult::Type::NUM_TIME, "lastrecv",
135 "The " + UNIX_EPOCH_TIME + " of the last receive"},
136 {RPCResult::Type::NUM_TIME, "last_msg_start",
137 "The " + UNIX_EPOCH_TIME + " of the last message start"},
138 {RPCResult::Type::NUM_TIME, "last_transaction",
139 "The " + UNIX_EPOCH_TIME +
140 " of the last valid transaction received from this "
141 "peer"},
142 {RPCResult::Type::NUM_TIME, "last_block",
143 "The " + UNIX_EPOCH_TIME +
144 " of the last block received from this peer"},
145 {RPCResult::Type::NUM, "bytessent", "The total bytes sent"},
146 {RPCResult::Type::NUM, "bytesrecv",
147 "The total bytes received"},
148 {RPCResult::Type::NUM, "bytes_inflight",
149 "The current in-flight bytes from this peer"},
150 {RPCResult::Type::NUM_TIME, "conntime",
151 "The " + UNIX_EPOCH_TIME + " of the connection"},
152 {RPCResult::Type::NUM, "timeoffset",
153 "The time offset in seconds"},
154 {RPCResult::Type::NUM, "pingtime",
155 "ping time (if available)"},
156 {RPCResult::Type::NUM, "minping",
157 "minimum observed ping time (if any at all)"},
158 {RPCResult::Type::NUM, "pingwait",
159 "ping wait (if non-zero)"},
160 {RPCResult::Type::NUM, "version",
161 "The peer version, such as 70001"},
162 {RPCResult::Type::STR, "subver", "The string version"},
163 {RPCResult::Type::BOOL, "inbound",
164 "Inbound (true) or Outbound (false)"},
165 {RPCResult::Type::BOOL, "bip152_hb_to",
166 "Whether we selected peer as (compact blocks) "
167 "high-bandwidth peer"},
168 {RPCResult::Type::BOOL, "bip152_hb_from",
169 "Whether peer selected us as (compact blocks) "
170 "high-bandwidth peer"},
171 {RPCResult::Type::STR, "connection_type",
172 "Type of connection: \n" +
173 Join(CONNECTION_TYPE_DOC, ",\n") + "."},
174 {RPCResult::Type::NUM, "startingheight",
175 "The starting height (block) of the peer"},
176 {RPCResult::Type::NUM, "presynced_headers",
177 /*optional=*/true,
178 "The current height of header pre-synchronization with "
179 "this peer, or -1 if no low-work sync is in progress"},
180 {RPCResult::Type::NUM, "synced_headers",
181 "The last header we have in common with this peer"},
182 {RPCResult::Type::NUM, "synced_blocks",
183 "The last block we have in common with this peer"},
185 "inflight",
186 "",
187 {
189 "The heights of blocks we're currently asking from "
190 "this peer"},
191 }},
192 {RPCResult::Type::BOOL, "addr_relay_enabled",
193 "Whether we participate in address relay with this peer"},
195 "permissions",
196 "Any special permissions that have been granted to this "
197 "peer",
198 {
199 {RPCResult::Type::STR, "permission_type",
200 Join(NET_PERMISSIONS_DOC, ",\n") + ".\n"},
201 }},
202 {RPCResult::Type::NUM, "minfeefilter",
203 "The minimum fee rate for transactions this peer accepts"},
205 "bytessent_per_msg",
206 "",
207 {{RPCResult::Type::NUM, "msg",
208 "The total bytes sent aggregated by message type\n"
209 "When a message type is not listed in this json object, "
210 "the bytes sent are 0.\n"
211 "Only known message types can appear as keys in the "
212 "object."}}},
214 "bytesrecv_per_msg",
215 "",
216 {{RPCResult::Type::NUM, "msg",
217 "The total bytes received aggregated by message type\n"
218 "When a message type is not listed in this json object, "
219 "the bytes received are 0.\n"
220 "Only known message types can appear as keys in the "
221 "object and all bytes received\n"
222 "of unknown message types are listed under '" +
223 NET_MESSAGE_TYPE_OTHER + "'."}}},
224 }},
225 }},
226 },
227 RPCExamples{HelpExampleCli("getpeerinfo", "") +
228 HelpExampleRpc("getpeerinfo", "")},
229 [&](const RPCHelpMan &self, const Config &config,
230 const JSONRPCRequest &request) -> UniValue {
231 NodeContext &node = EnsureAnyNodeContext(request.context);
232 const CConnman &connman = EnsureConnman(node);
233 const PeerManager &peerman = EnsurePeerman(node);
234
235 std::vector<CNodeStats> vstats;
236 connman.GetNodeStats(vstats);
237
239
240 for (const CNodeStats &stats : vstats) {
242 CNodeStateStats statestats;
243 bool fStateStats =
244 peerman.GetNodeStateStats(stats.nodeid, statestats);
245 obj.pushKV("id", stats.nodeid);
246 obj.pushKV("addr", stats.m_addr_name);
247 if (stats.addrBind.IsValid()) {
248 obj.pushKV("addrbind", stats.addrBind.ToStringAddrPort());
249 }
250 if (!(stats.addrLocal.empty())) {
251 obj.pushKV("addrlocal", stats.addrLocal);
252 }
253 obj.pushKV("network", GetNetworkName(stats.m_network));
254 if (stats.m_mapped_as != 0) {
255 obj.pushKV("mapped_as", uint64_t(stats.m_mapped_as));
256 }
257 ServiceFlags services{fStateStats ? statestats.their_services
259 obj.pushKV("services", strprintf("%016x", services));
260 obj.pushKV("servicesnames", GetServicesNames(services));
261 obj.pushKV("lastsend", count_seconds(stats.m_last_send));
262 obj.pushKV("lastrecv", count_seconds(stats.m_last_recv));
263 obj.pushKV("last_msg_start",
264 count_seconds(stats.m_last_msg_start));
265 obj.pushKV("last_transaction",
266 count_seconds(stats.m_last_tx_time));
267 if (node.avalanche) {
268 obj.pushKV("last_proof",
269 count_seconds(stats.m_last_proof_time));
270 }
271 obj.pushKV("last_block",
272 count_seconds(stats.m_last_block_time));
273 obj.pushKV("bytessent", stats.nSendBytes);
274 obj.pushKV("bytesrecv", stats.nRecvBytes);
275 obj.pushKV("bytes_inflight", stats.nInflightBytes);
276 obj.pushKV("conntime", count_seconds(stats.m_connected));
277 obj.pushKV("timeoffset", stats.nTimeOffset);
278 if (stats.m_last_ping_time > 0us) {
279 obj.pushKV("pingtime",
280 CountSecondsDouble(stats.m_last_ping_time));
281 }
282 if (stats.m_min_ping_time < std::chrono::microseconds::max()) {
283 obj.pushKV("minping",
284 CountSecondsDouble(stats.m_min_ping_time));
285 }
286 if (fStateStats && statestats.m_ping_wait > 0s) {
287 obj.pushKV("pingwait",
288 CountSecondsDouble(statestats.m_ping_wait));
289 }
290 obj.pushKV("version", stats.nVersion);
291 // Use the sanitized form of subver here, to avoid tricksy
292 // remote peers from corrupting or modifying the JSON output by
293 // putting special characters in their ver message.
294 obj.pushKV("subver", stats.cleanSubVer);
295 obj.pushKV("inbound", stats.fInbound);
296 obj.pushKV("bip152_hb_to", stats.m_bip152_highbandwidth_to);
297 obj.pushKV("bip152_hb_from", stats.m_bip152_highbandwidth_from);
298 if (fStateStats) {
299 obj.pushKV("startingheight", statestats.m_starting_height);
300 obj.pushKV("presynced_headers", statestats.presync_height);
301 obj.pushKV("synced_headers", statestats.nSyncHeight);
302 obj.pushKV("synced_blocks", statestats.nCommonHeight);
303 UniValue heights(UniValue::VARR);
304 for (const int height : statestats.vHeightInFlight) {
305 heights.push_back(height);
306 }
307 obj.pushKV("inflight", std::move(heights));
308 obj.pushKV("relaytxes", statestats.m_relay_txs);
309 obj.pushKV("minfeefilter",
310 statestats.m_fee_filter_received);
311 obj.pushKV("addr_relay_enabled",
312 statestats.m_addr_relay_enabled);
313 obj.pushKV("addr_processed", statestats.m_addr_processed);
314 obj.pushKV("addr_rate_limited",
315 statestats.m_addr_rate_limited);
316 }
317 UniValue permissions(UniValue::VARR);
318 for (const auto &permission :
319 NetPermissions::ToStrings(stats.m_permission_flags)) {
320 permissions.push_back(permission);
321 }
322 obj.pushKV("permissions", std::move(permissions));
323
324 UniValue sendPerMsgType(UniValue::VOBJ);
325 for (const auto &i : stats.mapSendBytesPerMsgType) {
326 if (i.second > 0) {
327 sendPerMsgType.pushKV(i.first, i.second);
328 }
329 }
330 obj.pushKV("bytessent_per_msg", std::move(sendPerMsgType));
331
332 UniValue recvPerMsgType(UniValue::VOBJ);
333 for (const auto &i : stats.mapRecvBytesPerMsgType) {
334 if (i.second > 0) {
335 recvPerMsgType.pushKV(i.first, i.second);
336 }
337 }
338 obj.pushKV("bytesrecv_per_msg", std::move(recvPerMsgType));
339 obj.pushKV("connection_type",
340 ConnectionTypeAsString(stats.m_conn_type));
341
342 ret.push_back(std::move(obj));
343 }
344
345 return ret;
346 },
347 };
348}
349
351 return RPCHelpMan{
352 "addnode",
353 "Attempts to add or remove a node from the addnode list.\n"
354 "Or try a connection to a node once.\n"
355 "Nodes added using addnode (or -connect) are protected from "
356 "DoS disconnection and are not required to be\n"
357 "full nodes as other outbound peers are (though such peers "
358 "will not be synced from).\n",
359 {
361 "The address of the peer to connect to"},
363 "'add' to add a node to the list, 'remove' to remove a "
364 "node from the list, 'onetry' to try a connection to the "
365 "node once"},
366 },
369 HelpExampleCli("addnode", "\"192.168.0.6:8333\" \"onetry\"") +
370 HelpExampleRpc("addnode", "\"192.168.0.6:8333\", \"onetry\"")},
371 [&](const RPCHelpMan &self, const Config &config,
372 const JSONRPCRequest &request) -> UniValue {
373 const auto command{self.Arg<std::string>("command")};
374 if (command != "onetry" && command != "add" &&
375 command != "remove") {
376 throw std::runtime_error(self.ToString());
377 }
378
379 NodeContext &node = EnsureAnyNodeContext(request.context);
380 CConnman &connman = EnsureConnman(node);
381
382 const auto node_arg{self.Arg<std::string>("node")};
383 // TODO: apply core#29277 when backporting the "v2transport" arg
384
385 if (command == "onetry") {
386 CAddress addr;
387 connman.OpenNetworkConnection(
388 addr, /*fCountFailure=*/false, /*grantOutbound=*/nullptr,
389 node_arg.c_str(), ConnectionType::MANUAL);
390 return NullUniValue;
391 }
392
393 if ((command == "add") && (!connman.AddNode(node_arg))) {
395 "Error: Node already added");
396 } else if ((command == "remove") &&
397 (!connman.RemoveAddedNode(node_arg))) {
398 throw JSONRPCError(
400 "Error: Node could not be removed. It has not been "
401 "added previously.");
402 }
403
404 return NullUniValue;
405 },
406 };
407}
408
410 return RPCHelpMan{
411 "addconnection",
412 "\nOpen an outbound connection to a specified node. This RPC is for "
413 "testing only.\n",
414 {
416 "The IP address and port to attempt connecting to."},
417 {"connection_type", RPCArg::Type::STR, RPCArg::Optional::NO,
418 "Type of connection to open (\"outbound-full-relay\", "
419 "\"block-relay-only\", \"addr-fetch\", \"feeler\" or "
420 "\"avalanche\")."},
421 },
423 "",
424 "",
425 {
426 {RPCResult::Type::STR, "address",
427 "Address of newly added connection."},
428 {RPCResult::Type::STR, "connection_type",
429 "Type of connection opened."},
430 }},
432 HelpExampleCli("addconnection",
433 "\"192.168.0.6:8333\" \"outbound-full-relay\"") +
434 HelpExampleRpc("addconnection",
435 "\"192.168.0.6:8333\" \"outbound-full-relay\"")},
436 [&](const RPCHelpMan &self, const Config &config,
437 const JSONRPCRequest &request) -> UniValue {
438 if (config.GetChainParams().GetChainType() != ChainType::REGTEST) {
439 throw std::runtime_error("addconnection is for regression "
440 "testing (-regtest mode) only.");
441 }
442
443 NodeContext &node = EnsureAnyNodeContext(request.context);
444
445 const std::string address = request.params[0].get_str();
446 const std::string conn_type_in{
447 TrimString(request.params[1].get_str())};
448 ConnectionType conn_type{};
449 if (conn_type_in == "outbound-full-relay") {
451 } else if (conn_type_in == "block-relay-only") {
452 conn_type = ConnectionType::BLOCK_RELAY;
453 } else if (conn_type_in == "addr-fetch") {
454 conn_type = ConnectionType::ADDR_FETCH;
455 } else if (conn_type_in == "feeler") {
456 conn_type = ConnectionType::FEELER;
457 } else if (conn_type_in == "avalanche") {
458 if (!node.avalanche) {
460 "Error: avalanche outbound requested "
461 "but avalanche is not enabled.");
462 }
464 } else {
466 }
467
468 CConnman &connman = EnsureConnman(node);
469
470 const bool success = connman.AddConnection(address, conn_type);
471 if (!success) {
473 "Error: Already at capacity for specified "
474 "connection type.");
475 }
476
478 info.pushKV("address", address);
479 info.pushKV("connection_type", conn_type_in);
480
481 return info;
482 },
483 };
484}
485
487 return RPCHelpMan{
488 "disconnectnode",
489 "Immediately disconnects from the specified peer node.\n"
490 "\nStrictly one out of 'address' and 'nodeid' can be provided to "
491 "identify the node.\n"
492 "\nTo disconnect by nodeid, either set 'address' to the empty string, "
493 "or call using the named 'nodeid' argument only.\n",
494 {
495 {"address", RPCArg::Type::STR,
496 RPCArg::DefaultHint{"fallback to nodeid"},
497 "The IP address/port of the node"},
498 {"nodeid", RPCArg::Type::NUM,
499 RPCArg::DefaultHint{"fallback to address"},
500 "The node ID (see getpeerinfo for node IDs)"},
501 },
503 RPCExamples{HelpExampleCli("disconnectnode", "\"192.168.0.6:8333\"") +
504 HelpExampleCli("disconnectnode", "\"\" 1") +
505 HelpExampleRpc("disconnectnode", "\"192.168.0.6:8333\"") +
506 HelpExampleRpc("disconnectnode", "\"\", 1")},
507 [&](const RPCHelpMan &self, const Config &config,
508 const JSONRPCRequest &request) -> UniValue {
509 NodeContext &node = EnsureAnyNodeContext(request.context);
510 CConnman &connman = EnsureConnman(node);
511
512 bool success;
513 const UniValue &address_arg = request.params[0];
514 const UniValue &id_arg = request.params[1];
515
516 if (!address_arg.isNull() && id_arg.isNull()) {
517 /* handle disconnect-by-address */
518 success = connman.DisconnectNode(address_arg.get_str());
519 } else if (!id_arg.isNull() && (address_arg.isNull() ||
520 (address_arg.isStr() &&
521 address_arg.get_str().empty()))) {
522 /* handle disconnect-by-id */
523 NodeId nodeid = (NodeId)id_arg.getInt<int64_t>();
524 success = connman.DisconnectNode(nodeid);
525 } else {
526 throw JSONRPCError(
528 "Only one of address and nodeid should be provided.");
529 }
530
531 if (!success) {
533 "Node not found in connected nodes");
534 }
535
536 return NullUniValue;
537 },
538 };
539}
540
542 return RPCHelpMan{
543 "getaddednodeinfo",
544 "Returns information about the given added node, or all added nodes\n"
545 "(note that onetry addnodes are not listed here)\n",
546 {
547 {"node", RPCArg::Type::STR, RPCArg::DefaultHint{"all nodes"},
548 "If provided, return information about this specific node, "
549 "otherwise all nodes are returned."},
550 },
551 RPCResult{
553 "",
554 "",
555 {
557 "",
558 "",
559 {
560 {RPCResult::Type::STR, "addednode",
561 "The node IP address or name (as provided to addnode)"},
562 {RPCResult::Type::BOOL, "connected", "If connected"},
564 "addresses",
565 "Only when connected = true",
566 {
568 "",
569 "",
570 {
571 {RPCResult::Type::STR, "address",
572 "The bitcoin server IP and port we're "
573 "connected to"},
574 {RPCResult::Type::STR, "connected",
575 "connection, inbound or outbound"},
576 }},
577 }},
578 }},
579 }},
580 RPCExamples{HelpExampleCli("getaddednodeinfo", "\"192.168.0.201\"") +
581 HelpExampleRpc("getaddednodeinfo", "\"192.168.0.201\"")},
582 [&](const RPCHelpMan &self, const Config &config,
583 const JSONRPCRequest &request) -> UniValue {
584 NodeContext &node = EnsureAnyNodeContext(request.context);
585 const CConnman &connman = EnsureConnman(node);
586
587 std::vector<AddedNodeInfo> vInfo = connman.GetAddedNodeInfo();
588
589 if (!request.params[0].isNull()) {
590 bool found = false;
591 for (const AddedNodeInfo &info : vInfo) {
592 if (info.strAddedNode == request.params[0].get_str()) {
593 vInfo.assign(1, info);
594 found = true;
595 break;
596 }
597 }
598 if (!found) {
600 "Error: Node has not been added.");
601 }
602 }
603
605
606 for (const AddedNodeInfo &info : vInfo) {
608 obj.pushKV("addednode", info.strAddedNode);
609 obj.pushKV("connected", info.fConnected);
610 UniValue addresses(UniValue::VARR);
611 if (info.fConnected) {
612 UniValue address(UniValue::VOBJ);
613 address.pushKV("address",
614 info.resolvedAddress.ToStringAddrPort());
615 address.pushKV("connected",
616 info.fInbound ? "inbound" : "outbound");
617 addresses.push_back(std::move(address));
618 }
619 obj.pushKV("addresses", std::move(addresses));
620 ret.push_back(std::move(obj));
621 }
622
623 return ret;
624 },
625 };
626}
627
629 return RPCHelpMan{
630 "getnettotals",
631 "Returns information about network traffic, including bytes in, "
632 "bytes out,\n"
633 "and current time.\n",
634 {},
635 RPCResult{
637 "",
638 "",
639 {
640 {RPCResult::Type::NUM, "totalbytesrecv",
641 "Total bytes received"},
642 {RPCResult::Type::NUM, "totalbytessent", "Total bytes sent"},
643 {RPCResult::Type::NUM_TIME, "timemillis",
644 "Current " + UNIX_EPOCH_TIME + " in milliseconds"},
646 "uploadtarget",
647 "",
648 {
649 {RPCResult::Type::NUM, "timeframe",
650 "Length of the measuring timeframe in seconds"},
651 {RPCResult::Type::NUM, "target", "Target in bytes"},
652 {RPCResult::Type::BOOL, "target_reached",
653 "True if target is reached"},
654 {RPCResult::Type::BOOL, "serve_historical_blocks",
655 "True if serving historical blocks"},
656 {RPCResult::Type::NUM, "bytes_left_in_cycle",
657 "Bytes left in current time cycle"},
658 {RPCResult::Type::NUM, "time_left_in_cycle",
659 "Seconds left in current time cycle"},
660 }},
661 }},
662 RPCExamples{HelpExampleCli("getnettotals", "") +
663 HelpExampleRpc("getnettotals", "")},
664 [&](const RPCHelpMan &self, const Config &config,
665 const JSONRPCRequest &request) -> UniValue {
666 NodeContext &node = EnsureAnyNodeContext(request.context);
667 const CConnman &connman = EnsureConnman(node);
668
670 obj.pushKV("totalbytesrecv", connman.GetTotalBytesRecv());
671 obj.pushKV("totalbytessent", connman.GetTotalBytesSent());
672 obj.pushKV("timemillis", GetTimeMillis());
673
674 UniValue outboundLimit(UniValue::VOBJ);
675 outboundLimit.pushKV(
676 "timeframe", count_seconds(connman.GetMaxOutboundTimeframe()));
677 outboundLimit.pushKV("target", connman.GetMaxOutboundTarget());
678 outboundLimit.pushKV("target_reached",
679 connman.OutboundTargetReached(false));
680 outboundLimit.pushKV("serve_historical_blocks",
681 !connman.OutboundTargetReached(true));
682 outboundLimit.pushKV("bytes_left_in_cycle",
684 outboundLimit.pushKV(
685 "time_left_in_cycle",
687 obj.pushKV("uploadtarget", std::move(outboundLimit));
688 return obj;
689 },
690 };
691}
692
694 UniValue networks(UniValue::VARR);
695 for (int n = 0; n < NET_MAX; ++n) {
696 enum Network network = static_cast<enum Network>(n);
697 if (network == NET_UNROUTABLE || network == NET_CJDNS ||
698 network == NET_INTERNAL) {
699 continue;
700 }
701 Proxy proxy;
703 GetProxy(network, proxy);
704 obj.pushKV("name", GetNetworkName(network));
705 obj.pushKV("limited", !IsReachable(network));
706 obj.pushKV("reachable", IsReachable(network));
707 obj.pushKV("proxy", proxy.IsValid() ? proxy.ToString() : std::string());
708 obj.pushKV("proxy_randomize_credentials",
710 networks.push_back(std::move(obj));
711 }
712 return networks;
713}
714
716 const auto &ticker = Currency::get().ticker;
717 return RPCHelpMan{
718 "getnetworkinfo",
719 "Returns an object containing various state info regarding P2P "
720 "networking.\n",
721 {},
722 RPCResult{
724 "",
725 "",
726 {
727 {RPCResult::Type::NUM, "version", "the server version"},
728 {RPCResult::Type::STR, "subversion",
729 "the server subversion string"},
730 {RPCResult::Type::NUM, "protocolversion",
731 "the protocol version"},
732 {RPCResult::Type::STR_HEX, "localservices",
733 "the services we offer to the network"},
735 "localservicesnames",
736 "the services we offer to the network, in human-readable form",
737 {
738 {RPCResult::Type::STR, "SERVICE_NAME", "the service name"},
739 }},
740 {RPCResult::Type::BOOL, "localrelay",
741 "true if transaction relay is requested from peers"},
742 {RPCResult::Type::NUM, "timeoffset", "the time offset"},
743 {RPCResult::Type::NUM, "connections",
744 "the total number of connections"},
745 {RPCResult::Type::NUM, "connections_in",
746 "the number of inbound connections"},
747 {RPCResult::Type::NUM, "connections_out",
748 "the number of outbound connections"},
749 {RPCResult::Type::BOOL, "networkactive",
750 "whether p2p networking is enabled"},
752 "networks",
753 "information per network",
754 {
756 "",
757 "",
758 {
759 {RPCResult::Type::STR, "name",
760 "network (" + Join(GetNetworkNames(), ", ") + ")"},
761 {RPCResult::Type::BOOL, "limited",
762 "is the network limited using -onlynet?"},
763 {RPCResult::Type::BOOL, "reachable",
764 "is the network reachable?"},
765 {RPCResult::Type::STR, "proxy",
766 "(\"host:port\") the proxy that is used for this "
767 "network, or empty if none"},
768 {RPCResult::Type::BOOL, "proxy_randomize_credentials",
769 "Whether randomized credentials are used"},
770 }},
771 }},
772 {RPCResult::Type::NUM, "relayfee",
773 "minimum relay fee for transactions in " + ticker + "/kB"},
775 "localaddresses",
776 "list of local addresses",
777 {
779 "",
780 "",
781 {
782 {RPCResult::Type::STR, "address", "network address"},
783 {RPCResult::Type::NUM, "port", "network port"},
784 {RPCResult::Type::NUM, "score", "relative score"},
785 }},
786 }},
787 {RPCResult::Type::STR, "warnings",
788 "any network and blockchain warnings"},
789 }},
790 RPCExamples{HelpExampleCli("getnetworkinfo", "") +
791 HelpExampleRpc("getnetworkinfo", "")},
792 [&](const RPCHelpMan &self, const Config &config,
793 const JSONRPCRequest &request) -> UniValue {
794 LOCK(cs_main);
796 obj.pushKV("version", CLIENT_VERSION);
797 obj.pushKV("subversion", userAgent(config));
798 obj.pushKV("protocolversion", PROTOCOL_VERSION);
799 NodeContext &node = EnsureAnyNodeContext(request.context);
800 if (node.connman) {
801 ServiceFlags services = node.connman->GetLocalServices();
802 obj.pushKV("localservices", strprintf("%016x", services));
803 obj.pushKV("localservicesnames", GetServicesNames(services));
804 }
805 if (node.peerman) {
806 obj.pushKV("localrelay", !node.peerman->IgnoresIncomingTxs());
807 }
808 obj.pushKV("timeoffset", GetTimeOffset());
809 if (node.connman) {
810 obj.pushKV("networkactive", node.connman->GetNetworkActive());
811 obj.pushKV("connections", node.connman->GetNodeCount(
813 obj.pushKV("connections_in",
814 node.connman->GetNodeCount(ConnectionDirection::In));
815 obj.pushKV("connections_out", node.connman->GetNodeCount(
817 }
818 obj.pushKV("networks", GetNetworksInfo());
819 if (node.mempool) {
820 // This field can be deprecated, to be replaced by the
821 // getmempoolinfo fields
822 obj.pushKV("relayfee",
823 node.mempool->m_min_relay_feerate.GetFeePerK());
824 }
825 UniValue localAddresses(UniValue::VARR);
826 {
828 for (const std::pair<const CNetAddr, LocalServiceInfo> &item :
829 mapLocalHost) {
831 rec.pushKV("address", item.first.ToStringAddr());
832 rec.pushKV("port", item.second.nPort);
833 rec.pushKV("score", item.second.nScore);
834 localAddresses.push_back(std::move(rec));
835 }
836 }
837 obj.pushKV("localaddresses", std::move(localAddresses));
838 obj.pushKV("warnings", GetWarnings(false).original);
839 return obj;
840 },
841 };
842}
843
845 return RPCHelpMan{
846 "setban",
847 "Attempts to add or remove an IP/Subnet from the banned list.\n",
848 {
850 "The IP/Subnet (see getpeerinfo for nodes IP) with an optional "
851 "netmask (default is /32 = single IP)"},
853 "'add' to add an IP/Subnet to the list, 'remove' to remove an "
854 "IP/Subnet from the list"},
855 {"bantime", RPCArg::Type::NUM, RPCArg::Default{0},
856 "time in seconds how long (or until when if [absolute] is set) "
857 "the IP is banned (0 or empty means using the default time of 24h "
858 "which can also be overwritten by the -bantime startup argument)"},
859 {"absolute", RPCArg::Type::BOOL, RPCArg::Default{false},
860 "If set, the bantime must be an absolute timestamp expressed in " +
862 },
865 HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400") +
866 HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"") +
867 HelpExampleRpc("setban", "\"192.168.0.6\", \"add\", 86400")},
868 [&](const RPCHelpMan &help, const Config &config,
869 const JSONRPCRequest &request) -> UniValue {
870 std::string strCommand;
871 if (!request.params[1].isNull()) {
872 strCommand = request.params[1].get_str();
873 }
874
875 if (strCommand != "add" && strCommand != "remove") {
876 throw std::runtime_error(help.ToString());
877 }
878
879 NodeContext &node = EnsureAnyNodeContext(request.context);
880 if (!node.banman) {
882 "Error: Ban database not loaded");
883 }
884
885 CSubNet subNet;
886 CNetAddr netAddr;
887 bool isSubnet = false;
888
889 if (request.params[0].get_str().find('/') != std::string::npos) {
890 isSubnet = true;
891 }
892
893 if (!isSubnet) {
894 const std::optional<CNetAddr> addr{
895 LookupHost(request.params[0].get_str(), false)};
896 if (addr.has_value()) {
897 netAddr = addr.value();
898 }
899 } else {
900 LookupSubNet(request.params[0].get_str(), subNet);
901 }
902
903 if (!(isSubnet ? subNet.IsValid() : netAddr.IsValid())) {
905 "Error: Invalid IP/Subnet");
906 }
907
908 if (strCommand == "add") {
909 if (isSubnet ? node.banman->IsBanned(subNet)
910 : node.banman->IsBanned(netAddr)) {
912 "Error: IP/Subnet already banned");
913 }
914
915 // Use standard bantime if not specified.
916 int64_t banTime = 0;
917 if (!request.params[2].isNull()) {
918 banTime = request.params[2].getInt<int64_t>();
919 }
920
921 bool absolute = false;
922 if (request.params[3].isTrue()) {
923 absolute = true;
924 }
925
926 if (isSubnet) {
927 node.banman->Ban(subNet, banTime, absolute);
928 if (node.connman) {
929 node.connman->DisconnectNode(subNet);
930 }
931 } else {
932 node.banman->Ban(netAddr, banTime, absolute);
933 if (node.connman) {
934 node.connman->DisconnectNode(netAddr);
935 }
936 }
937 } else if (strCommand == "remove") {
938 if (!(isSubnet ? node.banman->Unban(subNet)
939 : node.banman->Unban(netAddr))) {
940 throw JSONRPCError(
942 "Error: Unban failed. Requested address/subnet "
943 "was not previously manually banned.");
944 }
945 }
946 return NullUniValue;
947 },
948 };
949}
950
952 return RPCHelpMan{
953 "listbanned",
954 "List all manually banned IPs/Subnets.\n",
955 {},
957 "",
958 "",
959 {
961 "",
962 "",
963 {
964 {RPCResult::Type::STR, "address", ""},
965 {RPCResult::Type::NUM_TIME, "banned_until", ""},
966 {RPCResult::Type::NUM_TIME, "ban_created", ""},
967 {RPCResult::Type::STR, "ban_reason", ""},
968 }},
969 }},
970 RPCExamples{HelpExampleCli("listbanned", "") +
971 HelpExampleRpc("listbanned", "")},
972 [&](const RPCHelpMan &self, const Config &config,
973 const JSONRPCRequest &request) -> UniValue {
974 NodeContext &node = EnsureAnyNodeContext(request.context);
975 if (!node.banman) {
977 "Error: Ban database not loaded");
978 }
979
980 banmap_t banMap;
981 node.banman->GetBanned(banMap);
982
983 UniValue bannedAddresses(UniValue::VARR);
984 for (const auto &entry : banMap) {
985 const CBanEntry &banEntry = entry.second;
987 rec.pushKV("address", entry.first.ToString());
988 rec.pushKV("banned_until", banEntry.nBanUntil);
989 rec.pushKV("ban_created", banEntry.nCreateTime);
990
991 bannedAddresses.push_back(std::move(rec));
992 }
993
994 return bannedAddresses;
995 },
996 };
997}
998
1000 return RPCHelpMan{
1001 "clearbanned",
1002 "Clear all banned IPs.\n",
1003 {},
1005 RPCExamples{HelpExampleCli("clearbanned", "") +
1006 HelpExampleRpc("clearbanned", "")},
1007 [&](const RPCHelpMan &self, const Config &config,
1008 const JSONRPCRequest &request) -> UniValue {
1009 NodeContext &node = EnsureAnyNodeContext(request.context);
1010 if (!node.banman) {
1011 throw JSONRPCError(
1013 "Error: Peer-to-peer functionality missing or disabled");
1014 }
1015
1016 node.banman->ClearBanned();
1017
1018 return NullUniValue;
1019 },
1020 };
1021}
1022
1024 return RPCHelpMan{
1025 "setnetworkactive",
1026 "Disable/enable all p2p network activity.\n",
1027 {
1029 "true to enable networking, false to disable"},
1030 },
1031 RPCResult{RPCResult::Type::BOOL, "", "The value that was passed in"},
1032 RPCExamples{""},
1033 [&](const RPCHelpMan &self, const Config &config,
1034 const JSONRPCRequest &request) -> UniValue {
1035 NodeContext &node = EnsureAnyNodeContext(request.context);
1036 CConnman &connman = EnsureConnman(node);
1037
1038 connman.SetNetworkActive(request.params[0].get_bool());
1039
1040 return connman.GetNetworkActive();
1041 },
1042 };
1043}
1044
1046 return RPCHelpMan{
1047 "getnodeaddresses",
1048 "Return known addresses, which can potentially be used to find new "
1049 "nodes in the network.\n",
1050 {
1051 {"count", RPCArg::Type::NUM, RPCArg::Default{1},
1052 "The maximum number of addresses to return. Specify 0 to return "
1053 "all known addresses."},
1054 {"network", RPCArg::Type::STR, RPCArg::DefaultHint{"all networks"},
1055 "Return only addresses of the specified network. Can be one of: " +
1056 Join(GetNetworkNames(), ", ") + "."},
1057 },
1059 "",
1060 "",
1061 {
1063 "",
1064 "",
1065 {
1067 "The " + UNIX_EPOCH_TIME +
1068 " when the node was last seen"},
1069 {RPCResult::Type::NUM, "services",
1070 "The services offered by the node"},
1071 {RPCResult::Type::STR, "address",
1072 "The address of the node"},
1073 {RPCResult::Type::NUM, "port",
1074 "The port number of the node"},
1075 {RPCResult::Type::STR, "network",
1076 "The network (" + Join(GetNetworkNames(), ", ") +
1077 ") the node connected through"},
1078 }},
1079 }},
1080 RPCExamples{HelpExampleCli("getnodeaddresses", "8") +
1081 HelpExampleCli("getnodeaddresses", "4 \"i2p\"") +
1082 HelpExampleCli("-named getnodeaddresses",
1083 "network=onion count=12") +
1084 HelpExampleRpc("getnodeaddresses", "8") +
1085 HelpExampleRpc("getnodeaddresses", "4, \"i2p\"")},
1086 [&](const RPCHelpMan &self, const Config &config,
1087 const JSONRPCRequest &request) -> UniValue {
1088 NodeContext &node = EnsureAnyNodeContext(request.context);
1089 const CConnman &connman = EnsureConnman(node);
1090
1091 const int count{request.params[0].isNull()
1092 ? 1
1093 : request.params[0].getInt<int>()};
1094 if (count < 0) {
1096 "Address count out of range");
1097 }
1098
1099 const std::optional<Network> network{
1100 request.params[1].isNull()
1101 ? std::nullopt
1102 : std::optional<Network>{
1103 ParseNetwork(request.params[1].get_str())}};
1104 if (network == NET_UNROUTABLE) {
1106 strprintf("Network not recognized: %s",
1107 request.params[1].get_str()));
1108 }
1109 // returns a shuffled list of CAddress
1110 const std::vector<CAddress> vAddr{
1111 connman.GetAddresses(count, /* max_pct */ 0, network)};
1113
1114 for (const CAddress &addr : vAddr) {
1116 obj.pushKV(
1117 "time",
1118 int64_t{TicksSinceEpoch<std::chrono::seconds>(addr.nTime)});
1119 obj.pushKV("services", uint64_t(addr.nServices));
1120 obj.pushKV("address", addr.ToStringAddr());
1121 obj.pushKV("port", addr.GetPort());
1122 obj.pushKV("network", GetNetworkName(addr.GetNetClass()));
1123 ret.push_back(std::move(obj));
1124 }
1125 return ret;
1126 },
1127 };
1128}
1129
1131 return RPCHelpMan{
1132 "addpeeraddress",
1133 "Add the address of a potential peer to the address manager. This "
1134 "RPC is for testing only.\n",
1135 {
1137 "The IP address of the peer"},
1139 "The port of the peer"},
1140 {"tried", RPCArg::Type::BOOL, RPCArg::Default{false},
1141 "If true, attempt to add the peer to the tried addresses table"},
1142 },
1143 RPCResult{
1145 "",
1146 "",
1147 {
1148 {RPCResult::Type::BOOL, "success",
1149 "whether the peer address was successfully added to the "
1150 "address manager"},
1151 },
1152 },
1154 HelpExampleCli("addpeeraddress", "\"1.2.3.4\" 8333 true") +
1155 HelpExampleRpc("addpeeraddress", "\"1.2.3.4\", 8333, true")},
1156 [&](const RPCHelpMan &self, const Config &config,
1157 const JSONRPCRequest &request) -> UniValue {
1158 NodeContext &node = EnsureAnyNodeContext(request.context);
1159 if (!node.addrman) {
1160 throw JSONRPCError(
1162 "Error: Address manager functionality missing or disabled");
1163 }
1164
1165 const std::string &addr_string{request.params[0].get_str()};
1166 const uint16_t port{
1167 static_cast<uint16_t>(request.params[1].getInt<int>())};
1168 const bool tried{request.params[2].isTrue()};
1169
1171 std::optional<CNetAddr> net_addr{LookupHost(addr_string, false)};
1172 bool success{false};
1173
1174 if (net_addr.has_value()) {
1175 CAddress address{{net_addr.value(), port},
1177 address.nTime = Now<NodeSeconds>();
1178 // The source address is set equal to the address. This is
1179 // equivalent to the peer announcing itself.
1180 if (node.addrman->Add({address}, address)) {
1181 success = true;
1182 if (tried) {
1183 // Attempt to move the address to the tried addresses
1184 // table.
1185 node.addrman->Good(address);
1186 }
1187 }
1188 }
1189
1190 obj.pushKV("success", success);
1191 return obj;
1192 },
1193 };
1194}
1195
1197 return RPCHelpMan{
1198 "sendmsgtopeer",
1199 "Send a p2p message to a peer specified by id.\n"
1200 "The message type and body must be provided, the message header will "
1201 "be generated.\n"
1202 "This RPC is for testing only.",
1203 {
1205 "The peer to send the message to."},
1207 strprintf("The message type (maximum length %i)",
1210 "The serialized message body to send, in hex, without a message "
1211 "header"},
1212 },
1213 RPCResult{RPCResult::Type::OBJ, "", "", std::vector<RPCResult>{}},
1214 RPCExamples{HelpExampleCli("sendmsgtopeer", "0 \"addr\" \"ffffff\"") +
1215 HelpExampleRpc("sendmsgtopeer", "0 \"addr\" \"ffffff\"")},
1216 [&](const RPCHelpMan &self, const Config &config,
1217 const JSONRPCRequest &request) -> UniValue {
1218 const NodeId peer_id{request.params[0].getInt<int64_t>()};
1219 const std::string &msg_type{request.params[1].get_str()};
1220 if (msg_type.size() > CMessageHeader::MESSAGE_TYPE_SIZE) {
1221 throw JSONRPCError(
1223 strprintf("Error: msg_type too long, max length is %i",
1225 }
1226 auto msg{TryParseHex<uint8_t>(request.params[2].get_str())};
1227 if (!msg.has_value()) {
1229 "Error parsing input for msg");
1230 }
1231
1232 NodeContext &node = EnsureAnyNodeContext(request.context);
1233 CConnman &connman = EnsureConnman(node);
1234
1235 CSerializedNetMsg msg_ser;
1236 msg_ser.data = msg.value();
1237 msg_ser.m_type = msg_type;
1238
1239 bool success = connman.ForNode(peer_id, [&](CNode *node) {
1240 connman.PushMessage(node, std::move(msg_ser));
1241 return true;
1242 });
1243
1244 if (!success) {
1246 "Error: Could not send message to peer");
1247 }
1248
1250 return ret;
1251 },
1252 };
1253}
1254
1256 // clang-format off
1257 static const CRPCCommand commands[] = {
1258 // category actor (function)
1259 // ------------------ ----------------------
1260 { "network", getconnectioncount, },
1261 { "network", ping, },
1262 { "network", getpeerinfo, },
1263 { "network", addnode, },
1264 { "network", disconnectnode, },
1265 { "network", getaddednodeinfo, },
1266 { "network", getnettotals, },
1267 { "network", getnetworkinfo, },
1268 { "network", setban, },
1269 { "network", listbanned, },
1270 { "network", clearbanned, },
1271 { "network", setnetworkactive, },
1272 { "network", getnodeaddresses, },
1273 { "hidden", addconnection, },
1274 { "hidden", addpeeraddress, },
1275 { "hidden", sendmsgtopeer },
1276 };
1277 // clang-format on
1278 for (const auto &c : commands) {
1279 t.appendCommand(c.name, &c);
1280 }
1281}
A CService with information about it as peer.
Definition: protocol.h:442
Definition: addrdb.h:32
int64_t nCreateTime
Definition: addrdb.h:36
int64_t nBanUntil
Definition: addrdb.h:37
Definition: net.h:841
bool AddConnection(const std::string &address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
Definition: net.cpp:1175
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time in second left in the current max outbound cycle in case of no limit,...
Definition: net.cpp:2993
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:3009
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3204
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2865
bool GetNetworkActive() const
Definition: net.h:933
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:3032
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2989
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2920
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:2222
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2984
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2877
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2895
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2132
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3043
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2788
void SetNetworkActive(bool active)
Definition: net.cpp:2473
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2853
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3158
uint64_t GetTotalBytesSent() const
Definition: net.cpp:3047
static constexpr size_t MESSAGE_TYPE_SIZE
Definition: protocol.h:37
Network address.
Definition: netaddress.h:114
bool IsValid() const
Definition: netaddress.cpp:477
Information about a peer.
Definition: net.h:395
RPC command dispatcher.
Definition: server.h:194
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:330
bool IsValid() const
Definition: config.h:19
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
virtual void SendPings()=0
Send ping message to all peers.
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
Definition: netbase.h:67
std::string ToString() const
Definition: netbase.h:96
bool m_randomize_credentials
Definition: netbase.h:80
bool IsValid() const
Definition: netbase.h:82
auto Arg(size_t i) const
Helper to get a required or default-valued request argument.
Definition: util.h:416
std::string ToString() const
Definition: util.cpp:758
void push_back(UniValue val)
Definition: univalue.cpp:96
const std::string & get_str() const
@ VOBJ
Definition: univalue.h:31
@ VARR
Definition: univalue.h:32
bool isNull() const
Definition: univalue.h:104
bool isStr() const
Definition: univalue.h:108
Int getInt() const
Definition: univalue.h:157
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:115
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ AVALANCHE_OUTBOUND
Special case of connection to a full relay outbound with avalanche service enabled.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
int64_t NodeId
Definition: eviction.h:16
static path absolute(const path &p)
Definition: fs.h:101
Definition: messages.h:12
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:105
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:80
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:115
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:130
std::string userAgent(const Config &config)
Definition: net.cpp:3256
bool IsReachable(enum Network net)
Definition: net.cpp:328
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:141
const std::vector< std::string > NET_PERMISSIONS_DOC
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
Network
A network type.
Definition: netaddress.h:37
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:55
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:62
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:40
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:59
std::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:198
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:122
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret, DNSLookupFn dns_lookup_function)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:878
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:100
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
Definition: netbase.cpp:809
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:145
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
@ NODE_NETWORK
Definition: protocol.h:342
static const int PROTOCOL_VERSION
network protocol versioning
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
void RegisterNetRPCCommands(CRPCTable &t)
Register P2P networking RPC commands.
Definition: net.cpp:1255
static RPCHelpMan getnetworkinfo()
Definition: net.cpp:715
static RPCHelpMan addconnection()
Definition: net.cpp:409
static RPCHelpMan getaddednodeinfo()
Definition: net.cpp:541
static RPCHelpMan clearbanned()
Definition: net.cpp:999
static RPCHelpMan getnettotals()
Definition: net.cpp:628
static RPCHelpMan addnode()
Definition: net.cpp:350
static RPCHelpMan getnodeaddresses()
Definition: net.cpp:1045
static RPCHelpMan setban()
Definition: net.cpp:844
static UniValue GetNetworksInfo()
Definition: net.cpp:693
static RPCHelpMan ping()
Definition: net.cpp:60
static RPCHelpMan getconnectioncount()
Definition: net.cpp:42
static RPCHelpMan disconnectnode()
Definition: net.cpp:486
static RPCHelpMan listbanned()
Definition: net.cpp:951
static RPCHelpMan setnetworkactive()
Definition: net.cpp:1023
static RPCHelpMan addpeeraddress()
Definition: net.cpp:1130
static RPCHelpMan getpeerinfo()
Definition: net.cpp:85
static RPCHelpMan sendmsgtopeer()
Definition: net.cpp:1196
@ RPC_CLIENT_NODE_NOT_CONNECTED
Node to disconnect not found in connected nodes.
Definition: protocol.h:77
@ RPC_CLIENT_INVALID_IP_OR_SUBNET
Invalid IP/Subnet.
Definition: protocol.h:79
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
@ RPC_CLIENT_NODE_ALREADY_ADDED
Node is already added.
Definition: protocol.h:73
@ RPC_INVALID_PARAMS
Definition: protocol.h:30
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
@ RPC_DATABASE_ERROR
Database error.
Definition: protocol.h:48
@ RPC_CLIENT_NODE_NOT_ADDED
Node has not been added before.
Definition: protocol.h:75
@ RPC_CLIENT_NODE_CAPACITY_REACHED
Max number of outbound or block-relay connections already open.
Definition: protocol.h:83
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
Definition: protocol.h:81
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:163
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1429
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:180
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:35
static RPCHelpMan help()
Definition: server.cpp:185
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:21
PeerManager & EnsurePeerman(const NodeContext &node)
Definition: server_util.cpp:72
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:63
std::chrono::microseconds m_ping_wait
Amount m_fee_filter_received
std::vector< int > vHeightInFlight
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
int64_t presync_height
ServiceFlags their_services
POD that contains various stats about a node.
Definition: net.h:217
std::vector< uint8_t > data
Definition: net.h:137
std::string m_type
Definition: net.h:138
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:155
@ STR_HEX
Special type that is a STR with only hex chars.
std::string DefaultHint
Hint for default value.
Definition: util.h:212
@ NO
Required arg.
@ NUM_TIME
Special numeric to denote unix epoch time.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
#define LOCK(cs)
Definition: sync.h:306
static int count
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:76
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:85
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
Definition: time.h:104
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
Definition: timedata.cpp:30
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
const UniValue NullUniValue
Definition: univalue.cpp:16
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:43