Skip to content

Commit 0d22482

Browse files
committed
Merge #20002: net, rpc, cli: expose peer network in getpeerinfo; simplify/improve -netinfo
6272604 refactor: enable -netinfo to add future networks (i2p, cjdns) (Jon Atack) 82fd402 refactor: promote some -netinfo localvars to class members (Jon Atack) 5133fab cli: simplify -netinfo using getpeerinfo network field (Jon Atack) 4938a10 rpc, test: expose CNodeStats network in RPC getpeerinfo (Jon Atack) 6df7882 net: add peer network to CNodeStats (Jon Atack) Pull request description: This PR: - builds on #19991 and #19998 - exposes peer networks via a new getpeerinfo `network` field ("ipv4", "ipv6", or "onion"), and adds functional tests - updates -netinfo to use getpeerinfo `network` rather than detecting the peer networks client-side - refactors -netinfo to easily add future networks ACKs for top commit: laanwj: ACK 6272604 Tree-SHA512: 28883487585135ceaaf84ce09131f2336e3193407f2e3df0960e3f4ac340f500ab94ffecb9d06a4c49bc05e3cca4f914ea4379860bea0bd5df2f834f74616015
2 parents 711ddce + 6272604 commit 0d22482

File tree

5 files changed

+97
-106
lines changed

5 files changed

+97
-106
lines changed

src/bitcoin-cli.cpp

Lines changed: 56 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@ static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
3939
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
4040
static const bool DEFAULT_NAMED=false;
4141
static const int CONTINUE_EXECUTION=-1;
42-
static const std::string ONION{".onion"};
43-
static const size_t ONION_LEN{ONION.size()};
4442

4543
/** Default number of blocks to generate for RPC generatetoaddress. */
4644
static const std::string DEFAULT_NBLOCKS = "1";
@@ -298,30 +296,24 @@ class GetinfoRequestHandler: public BaseRequestHandler
298296
class NetinfoRequestHandler : public BaseRequestHandler
299297
{
300298
private:
301-
bool IsAddrIPv6(const std::string& addr) const
299+
static constexpr int8_t UNKNOWN_NETWORK{-1};
300+
static constexpr size_t m_networks_size{3};
301+
const std::array<std::string, m_networks_size> m_networks{{"ipv4", "ipv6", "onion"}};
302+
std::array<std::array<uint16_t, m_networks_size + 2>, 3> m_counts{{{}}}; //!< Peer counts by (in/out/total, networks/total/block-relay)
303+
int8_t NetworkStringToId(const std::string& str) const
302304
{
303-
return !addr.empty() && addr.front() == '[';
304-
}
305-
bool IsInboundOnion(const std::string& addr_local, int mapped_as) const
306-
{
307-
return mapped_as == 0 && addr_local.find(ONION) != std::string::npos;
308-
}
309-
bool IsOutboundOnion(const std::string& addr, int mapped_as) const
310-
{
311-
const size_t addr_len{addr.size()};
312-
const size_t onion_pos{addr.rfind(ONION)};
313-
return mapped_as == 0 && onion_pos != std::string::npos && addr_len > ONION_LEN &&
314-
(onion_pos == addr_len - ONION_LEN || onion_pos == addr.find_last_of(":") - ONION_LEN);
305+
for (size_t i = 0; i < m_networks_size; ++i) {
306+
if (str == m_networks.at(i)) return i;
307+
}
308+
return UNKNOWN_NETWORK;
315309
}
316310
uint8_t m_details_level{0}; //!< Optional user-supplied arg to set dashboard details level
317311
bool DetailsRequested() const { return m_details_level > 0 && m_details_level < 5; }
318312
bool IsAddressSelected() const { return m_details_level == 2 || m_details_level == 4; }
319313
bool IsVersionSelected() const { return m_details_level == 3 || m_details_level == 4; }
320-
enum struct NetType {
321-
ipv4,
322-
ipv6,
323-
onion,
324-
};
314+
bool m_is_asmap_on{false};
315+
size_t m_max_addr_length{0};
316+
size_t m_max_id_length{2};
325317
struct Peer {
326318
int id;
327319
int mapped_as;
@@ -334,30 +326,24 @@ class NetinfoRequestHandler : public BaseRequestHandler
334326
double min_ping;
335327
double ping;
336328
std::string addr;
329+
std::string network;
337330
std::string sub_version;
338-
NetType net_type;
339331
bool is_block_relay;
340332
bool is_outbound;
341333
bool operator<(const Peer& rhs) const { return std::tie(is_outbound, min_ping) < std::tie(rhs.is_outbound, rhs.min_ping); }
342334
};
343-
std::string NetTypeEnumToString(NetType t)
344-
{
345-
switch (t) {
346-
case NetType::ipv4: return "ipv4";
347-
case NetType::ipv6: return "ipv6";
348-
case NetType::onion: return "onion";
349-
} // no default case, so the compiler can warn about missing cases
350-
assert(false);
351-
}
335+
std::vector<Peer> m_peers;
352336
std::string ChainToString() const
353337
{
354338
if (gArgs.GetChainName() == CBaseChainParams::TESTNET) return " testnet";
355339
if (gArgs.GetChainName() == CBaseChainParams::REGTEST) return " regtest";
356340
return "";
357341
}
342+
const int64_t m_time_now{GetSystemTimeInSeconds()};
343+
358344
public:
359-
const int ID_PEERINFO = 0;
360-
const int ID_NETWORKINFO = 1;
345+
static constexpr int ID_PEERINFO = 0;
346+
static constexpr int ID_NETWORKINFO = 1;
361347

362348
UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
363349
{
@@ -385,104 +371,81 @@ class NetinfoRequestHandler : public BaseRequestHandler
385371
}
386372

387373
// Count peer connection totals, and if DetailsRequested(), store peer data in a vector of structs.
388-
const int64_t time_now{GetSystemTimeInSeconds()};
389-
int ipv4_i{0}, ipv6_i{0}, onion_i{0}, block_relay_i{0}, total_i{0}; // inbound conn counters
390-
int ipv4_o{0}, ipv6_o{0}, onion_o{0}, block_relay_o{0}, total_o{0}; // outbound conn counters
391-
size_t max_peer_id_length{2}, max_addr_length{0};
392-
bool is_asmap_on{false};
393-
std::vector<Peer> peers;
394-
const UniValue& getpeerinfo{batch[ID_PEERINFO]["result"]};
395-
396-
for (const UniValue& peer : getpeerinfo.getValues()) {
397-
const std::string addr{peer["addr"].get_str()};
398-
const std::string addr_local{peer["addrlocal"].isNull() ? "" : peer["addrlocal"].get_str()};
399-
const int mapped_as{peer["mapped_as"].isNull() ? 0 : peer["mapped_as"].get_int()};
374+
for (const UniValue& peer : batch[ID_PEERINFO]["result"].getValues()) {
375+
const std::string network{peer["network"].get_str()};
376+
const int8_t network_id{NetworkStringToId(network)};
377+
if (network_id == UNKNOWN_NETWORK) continue;
378+
const bool is_outbound{!peer["inbound"].get_bool()};
400379
const bool is_block_relay{!peer["relaytxes"].get_bool()};
401-
const bool is_inbound{peer["inbound"].get_bool()};
402-
NetType net_type{NetType::ipv4};
403-
if (is_inbound) {
404-
if (IsAddrIPv6(addr)) {
405-
net_type = NetType::ipv6;
406-
++ipv6_i;
407-
} else if (IsInboundOnion(addr_local, mapped_as)) {
408-
net_type = NetType::onion;
409-
++onion_i;
410-
} else {
411-
++ipv4_i;
412-
}
413-
if (is_block_relay) ++block_relay_i;
414-
} else {
415-
if (IsAddrIPv6(addr)) {
416-
net_type = NetType::ipv6;
417-
++ipv6_o;
418-
} else if (IsOutboundOnion(addr, mapped_as)) {
419-
net_type = NetType::onion;
420-
++onion_o;
421-
} else {
422-
++ipv4_o;
423-
}
424-
if (is_block_relay) ++block_relay_o;
380+
++m_counts.at(is_outbound).at(network_id); // in/out by network
381+
++m_counts.at(is_outbound).at(m_networks_size); // in/out overall
382+
++m_counts.at(2).at(network_id); // total by network
383+
++m_counts.at(2).at(m_networks_size); // total overall
384+
if (is_block_relay) {
385+
++m_counts.at(is_outbound).at(m_networks_size + 1); // in/out block-relay
386+
++m_counts.at(2).at(m_networks_size + 1); // total block-relay
425387
}
426388
if (DetailsRequested()) {
427389
// Push data for this peer to the peers vector.
428390
const int peer_id{peer["id"].get_int()};
391+
const int mapped_as{peer["mapped_as"].isNull() ? 0 : peer["mapped_as"].get_int()};
429392
const int version{peer["version"].get_int()};
430-
const std::string sub_version{peer["subver"].get_str()};
431393
const int64_t conn_time{peer["conntime"].get_int64()};
432394
const int64_t last_blck{peer["last_block"].get_int64()};
433395
const int64_t last_recv{peer["lastrecv"].get_int64()};
434396
const int64_t last_send{peer["lastsend"].get_int64()};
435397
const int64_t last_trxn{peer["last_transaction"].get_int64()};
436398
const double min_ping{peer["minping"].isNull() ? -1 : peer["minping"].get_real()};
437399
const double ping{peer["pingtime"].isNull() ? -1 : peer["pingtime"].get_real()};
438-
peers.push_back({peer_id, mapped_as, version, conn_time, last_blck, last_recv, last_send, last_trxn, min_ping, ping, addr, sub_version, net_type, is_block_relay, !is_inbound});
439-
max_peer_id_length = std::max(ToString(peer_id).length(), max_peer_id_length);
440-
max_addr_length = std::max(addr.length() + 1, max_addr_length);
441-
is_asmap_on |= (mapped_as != 0);
400+
const std::string addr{peer["addr"].get_str()};
401+
const std::string sub_version{peer["subver"].get_str()};
402+
m_peers.push_back({peer_id, mapped_as, version, conn_time, last_blck, last_recv, last_send, last_trxn, min_ping, ping, addr, network, sub_version, is_block_relay, is_outbound});
403+
m_max_id_length = std::max(ToString(peer_id).length(), m_max_id_length);
404+
m_max_addr_length = std::max(addr.length() + 1, m_max_addr_length);
405+
m_is_asmap_on |= (mapped_as != 0);
442406
}
443407
}
444408

445409
// Generate report header.
446410
std::string result{strprintf("%s %s%s - %i%s\n\n", PACKAGE_NAME, FormatFullVersion(), ChainToString(), networkinfo["protocolversion"].get_int(), networkinfo["subversion"].get_str())};
447411

448412
// Report detailed peer connections list sorted by direction and minimum ping time.
449-
if (DetailsRequested() && !peers.empty()) {
450-
std::sort(peers.begin(), peers.end());
413+
if (DetailsRequested() && !m_peers.empty()) {
414+
std::sort(m_peers.begin(), m_peers.end());
451415
result += "Peer connections sorted by direction and min ping\n<-> relay net mping ping send recv txn blk uptime ";
452-
if (is_asmap_on) result += " asmap ";
453-
result += strprintf("%*s %-*s%s\n", max_peer_id_length, "id", IsAddressSelected() ? max_addr_length : 0, IsAddressSelected() ? "address" : "", IsVersionSelected() ? "version" : "");
454-
for (const Peer& peer : peers) {
416+
if (m_is_asmap_on) result += " asmap ";
417+
result += strprintf("%*s %-*s%s\n", m_max_id_length, "id", IsAddressSelected() ? m_max_addr_length : 0, IsAddressSelected() ? "address" : "", IsVersionSelected() ? "version" : "");
418+
for (const Peer& peer : m_peers) {
455419
std::string version{ToString(peer.version) + peer.sub_version};
456420
result += strprintf(
457421
"%3s %5s %5s%6s%7s%5s%5s%5s%5s%7s%*i %*s %-*s%s\n",
458422
peer.is_outbound ? "out" : "in",
459423
peer.is_block_relay ? "block" : "full",
460-
NetTypeEnumToString(peer.net_type),
424+
peer.network,
461425
peer.min_ping == -1 ? "" : ToString(round(1000 * peer.min_ping)),
462426
peer.ping == -1 ? "" : ToString(round(1000 * peer.ping)),
463-
peer.last_send == 0 ? "" : ToString(time_now - peer.last_send),
464-
peer.last_recv == 0 ? "" : ToString(time_now - peer.last_recv),
465-
peer.last_trxn == 0 ? "" : ToString((time_now - peer.last_trxn) / 60),
466-
peer.last_blck == 0 ? "" : ToString((time_now - peer.last_blck) / 60),
467-
peer.conn_time == 0 ? "" : ToString((time_now - peer.conn_time) / 60),
468-
is_asmap_on ? 7 : 0, // variable spacing
469-
is_asmap_on && peer.mapped_as != 0 ? ToString(peer.mapped_as) : "",
470-
max_peer_id_length, // variable spacing
427+
peer.last_send == 0 ? "" : ToString(m_time_now - peer.last_send),
428+
peer.last_recv == 0 ? "" : ToString(m_time_now - peer.last_recv),
429+
peer.last_trxn == 0 ? "" : ToString((m_time_now - peer.last_trxn) / 60),
430+
peer.last_blck == 0 ? "" : ToString((m_time_now - peer.last_blck) / 60),
431+
peer.conn_time == 0 ? "" : ToString((m_time_now - peer.conn_time) / 60),
432+
m_is_asmap_on ? 7 : 0, // variable spacing
433+
m_is_asmap_on && peer.mapped_as != 0 ? ToString(peer.mapped_as) : "",
434+
m_max_id_length, // variable spacing
471435
peer.id,
472-
IsAddressSelected() ? max_addr_length : 0, // variable spacing
436+
IsAddressSelected() ? m_max_addr_length : 0, // variable spacing
473437
IsAddressSelected() ? peer.addr : "",
474438
IsVersionSelected() && version != "0" ? version : "");
475439
}
476440
result += " ms ms sec sec min min min\n\n";
477441
}
478442

479443
// Report peer connection totals by type.
480-
total_i = ipv4_i + ipv6_i + onion_i;
481-
total_o = ipv4_o + ipv6_o + onion_o;
482444
result += " ipv4 ipv6 onion total block-relay\n";
483-
result += strprintf("in %5i %5i %5i %5i %5i\n", ipv4_i, ipv6_i, onion_i, total_i, block_relay_i);
484-
result += strprintf("out %5i %5i %5i %5i %5i\n", ipv4_o, ipv6_o, onion_o, total_o, block_relay_o);
485-
result += strprintf("total %5i %5i %5i %5i %5i\n", ipv4_i + ipv4_o, ipv6_i + ipv6_o, onion_i + onion_o, total_i + total_o, block_relay_i + block_relay_o);
445+
const std::array<std::string, 3> rows{{"in", "out", "total"}};
446+
for (size_t i = 0; i < m_networks_size; ++i) {
447+
result += strprintf("%-5s %5i %5i %5i %5i %5i\n", rows.at(i), m_counts.at(i).at(0), m_counts.at(i).at(1), m_counts.at(i).at(2), m_counts.at(i).at(m_networks_size), m_counts.at(i).at(m_networks_size + 1));
448+
}
486449

487450
// Report local addresses, ports, and scores.
488451
result += "\nLocal addresses";

src/net.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,7 @@ void CNode::copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap)
552552
X(nServices);
553553
X(addr);
554554
X(addrBind);
555+
stats.m_network = GetNetworkName(ConnectedThroughNetwork());
555556
stats.m_mapped_as = addr.GetMappedAS(m_asmap);
556557
if (m_tx_relay != nullptr) {
557558
LOCK(m_tx_relay->cs_filter);

src/net.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -705,6 +705,8 @@ class CNodeStats
705705
CAddress addr;
706706
// Bind address of our side of the connection
707707
CAddress addrBind;
708+
// Name of the network the peer connected through
709+
std::string m_network;
708710
uint32_t m_mapped_as;
709711
std::string m_conn_type_string;
710712
};

src/rpc/net.cpp

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ static RPCHelpMan getpeerinfo()
9494
{RPCResult::Type::STR, "addr", "(host:port) The IP address and port of the peer"},
9595
{RPCResult::Type::STR, "addrbind", "(ip:port) Bind address of the connection to the peer"},
9696
{RPCResult::Type::STR, "addrlocal", "(ip:port) Local address as reported by the peer"},
97+
{RPCResult::Type::STR, "network", "Network (ipv4, ipv6, or onion) the peer connected through"},
9798
{RPCResult::Type::NUM, "mapped_as", "The AS in the BGP route to the peer used for diversifying\n"
9899
"peer selection (only available if the asmap config flag is set)"},
99100
{RPCResult::Type::STR_HEX, "services", "The services offered"},
@@ -167,10 +168,13 @@ static RPCHelpMan getpeerinfo()
167168
bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
168169
obj.pushKV("id", stats.nodeid);
169170
obj.pushKV("addr", stats.addrName);
170-
if (!(stats.addrLocal.empty()))
171-
obj.pushKV("addrlocal", stats.addrLocal);
172-
if (stats.addrBind.IsValid())
171+
if (stats.addrBind.IsValid()) {
173172
obj.pushKV("addrbind", stats.addrBind.ToString());
173+
}
174+
if (!(stats.addrLocal.empty())) {
175+
obj.pushKV("addrlocal", stats.addrLocal);
176+
}
177+
obj.pushKV("network", stats.m_network);
174178
if (stats.m_mapped_as != 0) {
175179
obj.pushKV("mapped_as", uint64_t(stats.m_mapped_as));
176180
}

test/functional/feature_proxy.py

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@
1818
- proxy on IPv6
1919
2020
- Create various proxies (as threads)
21-
- Create bitcoinds that connect to them
22-
- Manipulate the bitcoinds using addnode (onetry) an observe effects
21+
- Create nodes that connect to them
22+
- Manipulate the peer connections using addnode (onetry) and observe effects
23+
- Test the getpeerinfo `network` field for the peer
2324
2425
addnode connect to IPv4
2526
addnode connect to IPv6
@@ -40,6 +41,12 @@
4041
from test_framework.netutil import test_ipv6_local
4142

4243
RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE # Start after p2p and rpc ports
44+
# From GetNetworkName() in netbase.cpp:
45+
NET_UNROUTABLE = ""
46+
NET_IPV4 = "ipv4"
47+
NET_IPV6 = "ipv6"
48+
NET_ONION = "onion"
49+
4350

4451
class ProxyTest(BitcoinTestFramework):
4552
def set_test_params(self):
@@ -90,10 +97,16 @@ def setup_nodes(self):
9097
self.add_nodes(self.num_nodes, extra_args=args)
9198
self.start_nodes()
9299

100+
def network_test(self, node, addr, network):
101+
for peer in node.getpeerinfo():
102+
if peer["addr"] == addr:
103+
assert_equal(peer["network"], network)
104+
93105
def node_test(self, node, proxies, auth, test_onion=True):
94106
rv = []
95-
# Test: outgoing IPv4 connection through node
96-
node.addnode("15.61.23.23:1234", "onetry")
107+
addr = "15.61.23.23:1234"
108+
self.log.debug("Test: outgoing IPv4 connection through node for address {}".format(addr))
109+
node.addnode(addr, "onetry")
97110
cmd = proxies[0].queue.get()
98111
assert isinstance(cmd, Socks5Command)
99112
# Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
@@ -104,10 +117,12 @@ def node_test(self, node, proxies, auth, test_onion=True):
104117
assert_equal(cmd.username, None)
105118
assert_equal(cmd.password, None)
106119
rv.append(cmd)
120+
self.network_test(node, addr, network=NET_IPV4)
107121

108122
if self.have_ipv6:
109-
# Test: outgoing IPv6 connection through node
110-
node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry")
123+
addr = "[1233:3432:2434:2343:3234:2345:6546:4534]:5443"
124+
self.log.debug("Test: outgoing IPv6 connection through node for address {}".format(addr))
125+
node.addnode(addr, "onetry")
111126
cmd = proxies[1].queue.get()
112127
assert isinstance(cmd, Socks5Command)
113128
# Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
@@ -118,10 +133,12 @@ def node_test(self, node, proxies, auth, test_onion=True):
118133
assert_equal(cmd.username, None)
119134
assert_equal(cmd.password, None)
120135
rv.append(cmd)
136+
self.network_test(node, addr, network=NET_IPV6)
121137

122138
if test_onion:
123-
# Test: outgoing onion connection through node
124-
node.addnode("bitcoinostk4e4re.onion:8333", "onetry")
139+
addr = "bitcoinostk4e4re.onion:8333"
140+
self.log.debug("Test: outgoing onion connection through node for address {}".format(addr))
141+
node.addnode(addr, "onetry")
125142
cmd = proxies[2].queue.get()
126143
assert isinstance(cmd, Socks5Command)
127144
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
@@ -131,9 +148,11 @@ def node_test(self, node, proxies, auth, test_onion=True):
131148
assert_equal(cmd.username, None)
132149
assert_equal(cmd.password, None)
133150
rv.append(cmd)
151+
self.network_test(node, addr, network=NET_ONION)
134152

135-
# Test: outgoing DNS name connection through node
136-
node.addnode("node.noumenon:8333", "onetry")
153+
addr = "node.noumenon:8333"
154+
self.log.debug("Test: outgoing DNS name connection through node for address {}".format(addr))
155+
node.addnode(addr, "onetry")
137156
cmd = proxies[3].queue.get()
138157
assert isinstance(cmd, Socks5Command)
139158
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
@@ -143,6 +162,7 @@ def node_test(self, node, proxies, auth, test_onion=True):
143162
assert_equal(cmd.username, None)
144163
assert_equal(cmd.password, None)
145164
rv.append(cmd)
165+
self.network_test(node, addr, network=NET_UNROUTABLE)
146166

147167
return rv
148168

@@ -197,5 +217,6 @@ def networks_dict(d):
197217
assert_equal(n3[net]['proxy_randomize_credentials'], False)
198218
assert_equal(n3['onion']['reachable'], False)
199219

220+
200221
if __name__ == '__main__':
201222
ProxyTest().main()

0 commit comments

Comments
 (0)