Skip to content

Commit bd00d3b

Browse files
committed
Merge #19658: [rpc] Allow RPC to fetch all addrman records and add records to addrman
37a480e [net] Add addpeeraddress RPC method (John Newbery) ae8051b [test] Test that getnodeaddresses() can return all known addresses (John Newbery) f26502e [addrman] Specify max addresses and pct when calling GetAddresses() (John Newbery) Pull request description: Currently addrman only allows a maximum of 1000 records or 23% of all records to be returned in a call to `GetAddr()`. Relax this limit and have the client specify the max records they want. For p2p, behaviour is unchanged (but the rate limiting is set inside net_processing, where it belongs). For RPC, `getnodeaddresses` can now return the complete addrman, which is helpful for testing and monitoring. Also add a test-only RPC `addpeeraddress`, which adds an IP address:port to addrman. This is helpful for testing (eg #18991). ACKs for top commit: naumenkogs: utACK 37a480e laanwj: Code review and lightly manually tested ACK 37a480e Tree-SHA512: f86dcd410aaebaf6e9ca18ce6f23556e5e4649c1325577213d873aa09967298e65ab2dc19a72670641ae92211a923afda1fe124a82e9d2c1cad73d478ef27fdc
2 parents ce3bdd0 + 37a480e commit bd00d3b

File tree

10 files changed

+109
-60
lines changed

10 files changed

+109
-60
lines changed

src/addrman.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -479,11 +479,15 @@ int CAddrMan::Check_()
479479
}
480480
#endif
481481

482-
void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr)
482+
void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr, size_t max_addresses, size_t max_pct)
483483
{
484-
unsigned int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.size() / 100;
485-
if (nNodes > ADDRMAN_GETADDR_MAX)
486-
nNodes = ADDRMAN_GETADDR_MAX;
484+
size_t nNodes = vRandom.size();
485+
if (max_pct != 0) {
486+
nNodes = max_pct * nNodes / 100;
487+
}
488+
if (max_addresses != 0) {
489+
nNodes = std::min(nNodes, max_addresses);
490+
}
487491

488492
// gather a list of random nodes, skipping those of low quality
489493
for (unsigned int n = 0; n < vRandom.size(); n++) {

src/addrman.h

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -153,12 +153,6 @@ class CAddrInfo : public CAddress
153153
//! how recent a successful connection should be before we allow an address to be evicted from tried
154154
#define ADDRMAN_REPLACEMENT_HOURS 4
155155

156-
//! the maximum percentage of nodes to return in a getaddr call
157-
#define ADDRMAN_GETADDR_MAX_PCT 23
158-
159-
//! the maximum number of nodes to return in a getaddr call
160-
#define ADDRMAN_GETADDR_MAX 1000
161-
162156
//! Convenience
163157
#define ADDRMAN_TRIED_BUCKET_COUNT (1 << ADDRMAN_TRIED_BUCKET_COUNT_LOG2)
164158
#define ADDRMAN_NEW_BUCKET_COUNT (1 << ADDRMAN_NEW_BUCKET_COUNT_LOG2)
@@ -261,7 +255,7 @@ friend class CAddrManTest;
261255
#endif
262256

263257
//! Select several addresses at once.
264-
void GetAddr_(std::vector<CAddress> &vAddr) EXCLUSIVE_LOCKS_REQUIRED(cs);
258+
void GetAddr_(std::vector<CAddress> &vAddr, size_t max_addresses, size_t max_pct) EXCLUSIVE_LOCKS_REQUIRED(cs);
265259

266260
//! Mark an entry as currently-connected-to.
267261
void Connected_(const CService &addr, int64_t nTime) EXCLUSIVE_LOCKS_REQUIRED(cs);
@@ -638,13 +632,13 @@ friend class CAddrManTest;
638632
}
639633

640634
//! Return a bunch of addresses, selected at random.
641-
std::vector<CAddress> GetAddr()
635+
std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct)
642636
{
643637
Check();
644638
std::vector<CAddress> vAddr;
645639
{
646640
LOCK(cs);
647-
GetAddr_(vAddr);
641+
GetAddr_(vAddr, max_addresses, max_pct);
648642
}
649643
Check();
650644
return vAddr;

src/bench/addrman.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ static void AddrManGetAddr(benchmark::Bench& bench)
9898
FillAddrMan(addrman);
9999

100100
bench.run([&] {
101-
const auto& addresses = addrman.GetAddr();
101+
const auto& addresses = addrman.GetAddr(2500, 23);
102102
assert(addresses.size() > 0);
103103
});
104104
}

src/net.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2521,14 +2521,14 @@ void CConnman::MarkAddressGood(const CAddress& addr)
25212521
addrman.Good(addr);
25222522
}
25232523

2524-
void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
2524+
bool CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
25252525
{
2526-
addrman.Add(vAddr, addrFrom, nTimePenalty);
2526+
return addrman.Add(vAddr, addrFrom, nTimePenalty);
25272527
}
25282528

2529-
std::vector<CAddress> CConnman::GetAddresses()
2529+
std::vector<CAddress> CConnman::GetAddresses(size_t max_addresses, size_t max_pct)
25302530
{
2531-
std::vector<CAddress> addresses = addrman.GetAddr();
2531+
std::vector<CAddress> addresses = addrman.GetAddr(max_addresses, max_pct);
25322532
if (m_banman) {
25332533
addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
25342534
[this](const CAddress& addr){return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr);}),
@@ -2537,12 +2537,12 @@ std::vector<CAddress> CConnman::GetAddresses()
25372537
return addresses;
25382538
}
25392539

2540-
std::vector<CAddress> CConnman::GetAddresses(Network requestor_network)
2540+
std::vector<CAddress> CConnman::GetAddresses(Network requestor_network, size_t max_addresses, size_t max_pct)
25412541
{
25422542
const auto current_time = GetTime<std::chrono::microseconds>();
25432543
if (m_addr_response_caches.find(requestor_network) == m_addr_response_caches.end() ||
25442544
m_addr_response_caches[requestor_network].m_update_addr_response < current_time) {
2545-
m_addr_response_caches[requestor_network].m_addrs_response_cache = GetAddresses();
2545+
m_addr_response_caches[requestor_network].m_addrs_response_cache = GetAddresses(max_addresses, max_pct);
25462546
m_addr_response_caches[requestor_network].m_update_addr_response = current_time + std::chrono::hours(21) + GetRandMillis(std::chrono::hours(6));
25472547
}
25482548
return m_addr_response_caches[requestor_network].m_addrs_response_cache;

src/net.h

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,8 @@ static const bool DEFAULT_WHITELISTFORCERELAY = false;
5151
static const int TIMEOUT_INTERVAL = 20 * 60;
5252
/** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
5353
static const int FEELER_INTERVAL = 120;
54-
/** The maximum number of new addresses to accumulate before announcing. */
55-
static const unsigned int MAX_ADDR_TO_SEND = 1000;
56-
// TODO: remove ADDRMAN_GETADDR_MAX and let the caller specify this limit with MAX_ADDR_TO_SEND.
57-
static_assert(MAX_ADDR_TO_SEND == ADDRMAN_GETADDR_MAX,
58-
"Max allowed ADDR message size should be equal to the max number of records returned from AddrMan.");
54+
/** The maximum number of addresses from our addrman to return in response to a getaddr message. */
55+
static constexpr size_t MAX_ADDR_TO_SEND = 1000;
5956
/** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
6057
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
6158
/** Maximum length of the user agent string in `version` message */
@@ -264,15 +261,15 @@ class CConnman
264261
// Addrman functions
265262
void SetServices(const CService &addr, ServiceFlags nServices);
266263
void MarkAddressGood(const CAddress& addr);
267-
void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
268-
std::vector<CAddress> GetAddresses();
264+
bool AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
265+
std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct);
269266
/**
270267
* Cache is used to minimize topology leaks, so it should
271268
* be used for all non-trusted calls, for example, p2p.
272269
* A non-malicious call (from RPC or a peer with addr permission) should
273270
* call the function without a parameter to avoid using the cache.
274271
*/
275-
std::vector<CAddress> GetAddresses(Network requestor_network);
272+
std::vector<CAddress> GetAddresses(Network requestor_network, size_t max_addresses, size_t max_pct);
276273

277274
// This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
278275
// a peer that is better than all our current peers.

src/net_processing.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ static constexpr unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
143143
static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
144144
/** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */
145145
static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;
146+
/** the maximum percentage of addresses from our addrman to return in response to a getaddr message. */
147+
static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
146148

147149
struct COrphanTx {
148150
// When modifying, adapt the copy of this definition in tests/DoS_tests.
@@ -3521,9 +3523,9 @@ void ProcessMessage(
35213523
pfrom.vAddrToSend.clear();
35223524
std::vector<CAddress> vAddr;
35233525
if (pfrom.HasPermission(PF_ADDR)) {
3524-
vAddr = connman.GetAddresses();
3526+
vAddr = connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
35253527
} else {
3526-
vAddr = connman.GetAddresses(pfrom.addr.GetNetwork());
3528+
vAddr = connman.GetAddresses(pfrom.addr.GetNetwork(), MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
35273529
}
35283530
FastRandomContext insecure_rand;
35293531
for (const CAddress &addr : vAddr) {

src/rpc/client.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
173173
{ "createwallet", 4, "avoid_reuse"},
174174
{ "createwallet", 5, "descriptors"},
175175
{ "getnodeaddresses", 0, "count"},
176+
{ "addpeeraddress", 1, "port"},
176177
{ "stop", 0, "wait" },
177178
};
178179
// clang-format on

src/rpc/net.cpp

Lines changed: 53 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -727,7 +727,7 @@ static UniValue getnodeaddresses(const JSONRPCRequest& request)
727727
RPCHelpMan{"getnodeaddresses",
728728
"\nReturn known addresses which can potentially be used to find new nodes in the network\n",
729729
{
730-
{"count", RPCArg::Type::NUM, /* default */ "1", "How many addresses to return. Limited to the smaller of " + ToString(ADDRMAN_GETADDR_MAX) + " or " + ToString(ADDRMAN_GETADDR_MAX_PCT) + "% of all known addresses."},
730+
{"count", RPCArg::Type::NUM, /* default */ "1", "The maximum number of addresses to return. Specify 0 to return all known addresses."},
731731
},
732732
RPCResult{
733733
RPCResult::Type::ARR, "", "",
@@ -754,18 +754,16 @@ static UniValue getnodeaddresses(const JSONRPCRequest& request)
754754
int count = 1;
755755
if (!request.params[0].isNull()) {
756756
count = request.params[0].get_int();
757-
if (count <= 0) {
757+
if (count < 0) {
758758
throw JSONRPCError(RPC_INVALID_PARAMETER, "Address count out of range");
759759
}
760760
}
761761
// returns a shuffled list of CAddress
762-
std::vector<CAddress> vAddr = node.connman->GetAddresses();
762+
std::vector<CAddress> vAddr = node.connman->GetAddresses(count, /* max_pct */ 0);
763763
UniValue ret(UniValue::VARR);
764764

765-
int address_return_count = std::min<int>(count, vAddr.size());
766-
for (int i = 0; i < address_return_count; ++i) {
765+
for (const CAddress& addr : vAddr) {
767766
UniValue obj(UniValue::VOBJ);
768-
const CAddress& addr = vAddr[i];
769767
obj.pushKV("time", (int)addr.nTime);
770768
obj.pushKV("services", (uint64_t)addr.nServices);
771769
obj.pushKV("address", addr.ToStringIP());
@@ -775,6 +773,54 @@ static UniValue getnodeaddresses(const JSONRPCRequest& request)
775773
return ret;
776774
}
777775

776+
static UniValue addpeeraddress(const JSONRPCRequest& request)
777+
{
778+
RPCHelpMan{"addpeeraddress",
779+
"\nAdd the address of a potential peer to the address manager. This RPC is for testing only.\n",
780+
{
781+
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP address of the peer"},
782+
{"port", RPCArg::Type::NUM, RPCArg::Optional::NO, "The port of the peer"},
783+
},
784+
RPCResult{
785+
RPCResult::Type::OBJ, "", "",
786+
{
787+
{RPCResult::Type::BOOL, "success", "whether the peer address was successfully added to the address manager"},
788+
},
789+
},
790+
RPCExamples{
791+
HelpExampleCli("addpeeraddress", "\"1.2.3.4\" 8333")
792+
+ HelpExampleRpc("addpeeraddress", "\"1.2.3.4\", 8333")
793+
},
794+
}.Check(request);
795+
796+
NodeContext& node = EnsureNodeContext(request.context);
797+
if (!node.connman) {
798+
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
799+
}
800+
801+
UniValue obj(UniValue::VOBJ);
802+
803+
std::string addr_string = request.params[0].get_str();
804+
uint16_t port = request.params[1].get_int();
805+
806+
CNetAddr net_addr;
807+
if (!LookupHost(addr_string, net_addr, false)) {
808+
obj.pushKV("success", false);
809+
return obj;
810+
}
811+
CAddress address = CAddress({net_addr, port}, ServiceFlags(NODE_NETWORK|NODE_WITNESS));
812+
address.nTime = GetAdjustedTime();
813+
// The source address is set equal to the address. This is equivalent to the peer
814+
// announcing itself.
815+
if (!node.connman->AddNewAddresses({address}, address)) {
816+
obj.pushKV("success", false);
817+
return obj;
818+
}
819+
820+
obj.pushKV("success", true);
821+
return obj;
822+
}
823+
778824
void RegisterNetRPCCommands(CRPCTable &t)
779825
{
780826
// clang-format off
@@ -794,6 +840,7 @@ static const CRPCCommand commands[] =
794840
{ "network", "clearbanned", &clearbanned, {} },
795841
{ "network", "setnetworkactive", &setnetworkactive, {"state"} },
796842
{ "network", "getnodeaddresses", &getnodeaddresses, {"count"} },
843+
{ "hidden", "addpeeraddress", &addpeeraddress, {"address", "port"} },
797844
};
798845
// clang-format on
799846

src/test/addrman_tests.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr)
392392
// Test: Sanity check, GetAddr should never return anything if addrman
393393
// is empty.
394394
BOOST_CHECK_EQUAL(addrman.size(), 0U);
395-
std::vector<CAddress> vAddr1 = addrman.GetAddr();
395+
std::vector<CAddress> vAddr1 = addrman.GetAddr(/* max_addresses */ 0, /* max_pct */0);
396396
BOOST_CHECK_EQUAL(vAddr1.size(), 0U);
397397

398398
CAddress addr1 = CAddress(ResolveService("250.250.2.1", 8333), NODE_NONE);
@@ -415,13 +415,15 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr)
415415
BOOST_CHECK(addrman.Add(addr4, source2));
416416
BOOST_CHECK(addrman.Add(addr5, source1));
417417

418-
// GetAddr returns 23% of addresses, 23% of 5 is 1 rounded down.
419-
BOOST_CHECK_EQUAL(addrman.GetAddr().size(), 1U);
418+
BOOST_CHECK_EQUAL(addrman.GetAddr(/* max_addresses */ 0, /* max_pct */ 0).size(), 5U);
419+
// Net processing asks for 23% of addresses. 23% of 5 is 1 rounded down.
420+
BOOST_CHECK_EQUAL(addrman.GetAddr(/* max_addresses */ 2500, /* max_pct */ 23).size(), 1U);
420421

421422
// Test: Ensure GetAddr works with new and tried addresses.
422423
addrman.Good(CAddress(addr1, NODE_NONE));
423424
addrman.Good(CAddress(addr2, NODE_NONE));
424-
BOOST_CHECK_EQUAL(addrman.GetAddr().size(), 1U);
425+
BOOST_CHECK_EQUAL(addrman.GetAddr(/* max_addresses */ 0, /* max_pct */ 0).size(), 5U);
426+
BOOST_CHECK_EQUAL(addrman.GetAddr(/* max_addresses */ 2500, /* max_pct */ 23).size(), 1U);
425427

426428
// Test: Ensure GetAddr still returns 23% when addrman has many addrs.
427429
for (unsigned int i = 1; i < (8 * 256); i++) {
@@ -436,7 +438,7 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr)
436438
if (i % 8 == 0)
437439
addrman.Good(addr);
438440
}
439-
std::vector<CAddress> vAddr = addrman.GetAddr();
441+
std::vector<CAddress> vAddr = addrman.GetAddr(/* max_addresses */ 2500, /* max_pct */ 23);
440442

441443
size_t percent23 = (addrman.size() * 23) / 100;
442444
BOOST_CHECK_EQUAL(vAddr.size(), percent23);

test/functional/rpc_net.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@
2222
from test_framework.mininode import P2PInterface
2323
import test_framework.messages
2424
from test_framework.messages import (
25-
CAddress,
26-
msg_addr,
2725
NODE_NETWORK,
2826
NODE_WITNESS,
2927
)
@@ -154,30 +152,34 @@ def test_service_flags(self):
154152
def _test_getnodeaddresses(self):
155153
self.nodes[0].add_p2p_connection(P2PInterface())
156154

157-
# send some addresses to the node via the p2p message addr
158-
msg = msg_addr()
155+
# Add some addresses to the Address Manager over RPC. Due to the way
156+
# bucket and bucket position are calculated, some of these addresses
157+
# will collide.
159158
imported_addrs = []
160-
for i in range(256):
161-
a = "123.123.123.{}".format(i)
159+
for i in range(10000):
160+
first_octet = i >> 8
161+
second_octet = i % 256
162+
a = "{}.{}.1.1".format(first_octet, second_octet)
162163
imported_addrs.append(a)
163-
addr = CAddress()
164-
addr.time = 100000000
165-
addr.nServices = NODE_NETWORK | NODE_WITNESS
166-
addr.ip = a
167-
addr.port = 8333
168-
msg.addrs.append(addr)
169-
self.nodes[0].p2p.send_and_ping(msg)
170-
171-
# obtain addresses via rpc call and check they were ones sent in before
172-
REQUEST_COUNT = 10
173-
node_addresses = self.nodes[0].getnodeaddresses(REQUEST_COUNT)
174-
assert_equal(len(node_addresses), REQUEST_COUNT)
164+
self.nodes[0].addpeeraddress(a, 8333)
165+
166+
# Obtain addresses via rpc call and check they were ones sent in before.
167+
#
168+
# Maximum possible addresses in addrman is 10000, although actual
169+
# number will usually be less due to bucket and bucket position
170+
# collisions.
171+
node_addresses = self.nodes[0].getnodeaddresses(0)
172+
assert_greater_than(len(node_addresses), 5000)
173+
assert_greater_than(10000, len(node_addresses))
175174
for a in node_addresses:
176-
assert_greater_than(a["time"], 1527811200) # 1st June 2018
175+
assert_greater_than(a["time"], 1527811200) # 1st June 2018
177176
assert_equal(a["services"], NODE_NETWORK | NODE_WITNESS)
178177
assert a["address"] in imported_addrs
179178
assert_equal(a["port"], 8333)
180179

180+
node_addresses = self.nodes[0].getnodeaddresses(1)
181+
assert_equal(len(node_addresses), 1)
182+
181183
assert_raises_rpc_error(-8, "Address count out of range", self.nodes[0].getnodeaddresses, -1)
182184

183185
# addrman's size cannot be known reliably after insertion, as hash collisions may occur

0 commit comments

Comments
 (0)