Skip to content

Commit 7130048

Browse files
committed
Merge bitcoin/bitcoin#26261: p2p: cleanup LookupIntern, Lookup and LookupHost
5c832c3 p2p, refactor: return `std::optional<CNetAddr>` in `LookupHost` (brunoerg) 34bcdfc p2p, refactor: return vector/optional<CService> in `Lookup` (brunoerg) 7799eb1 p2p, refactor: return `std::vector<CNetAddr>` in `LookupHost` (brunoerg) 5c1774a p2p, refactor: return `std::vector<CNetAddr>` in `LookupIntern` (brunoerg) Pull request description: Continuation of #26078. To improve readability instead of returning a bool and passing stuff by reference, this PR changes: - `LookupHost` to return `std::vector<CNetAddr>` - `LookupHost` to return `std::optional<CNetAddr>` - `Lookup` to return `std::vector<CService>` - `Lookup` to return `std::optional<CService>`. - `LookupIntern` to return `std::vector<CNetAddr>` As discussed in #26078, it would be better to avoid using `optional` in some cases, but for specific `Lookup` and `LookupHost` functions it's necessary to use `optional` to verify if they were able to catch some data from their overloaded function. ACKs for top commit: achow101: ACK 5c832c3 stickies-v: re-ACK 5c832c3 - just addressing two nits, no other changes theStack: re-ACK 5c832c3 Tree-SHA512: ea346fdc54463999646269bd600cd4a1590ef958001d2f0fc2be608ca51e1b4365efccca76dd4972b023e12fcc6e67d226608b0df7beb901bdeadd19948df840
2 parents 05ec664 + 5c832c3 commit 7130048

16 files changed

+171
-225
lines changed

src/bench/addrman.cpp

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -72,20 +72,6 @@ static void FillAddrMan(AddrMan& addrman)
7272
AddAddressesToAddrMan(addrman);
7373
}
7474

75-
static CNetAddr ResolveIP(const std::string& ip)
76-
{
77-
CNetAddr addr;
78-
LookupHost(ip, addr, false);
79-
return addr;
80-
}
81-
82-
static CService ResolveService(const std::string& ip, uint16_t port = 0)
83-
{
84-
CService serv;
85-
Lookup(ip, serv, port, false);
86-
return serv;
87-
}
88-
8975
/* Benchmarks */
9076

9177
static void AddrManAdd(benchmark::Bench& bench)
@@ -118,8 +104,8 @@ static void AddrManSelectFromAlmostEmpty(benchmark::Bench& bench)
118104
AddrMan addrman{EMPTY_NETGROUPMAN, /*deterministic=*/false, ADDRMAN_CONSISTENCY_CHECK_RATIO};
119105

120106
// Add one address to the new table
121-
CService addr = ResolveService("250.3.1.1", 8333);
122-
addrman.Add({CAddress(addr, NODE_NONE)}, ResolveService("250.3.1.1", 8333));
107+
CService addr = Lookup("250.3.1.1", 8333, false).value();
108+
addrman.Add({CAddress(addr, NODE_NONE)}, addr);
123109

124110
bench.run([&] {
125111
(void)addrman.Select();
@@ -135,7 +121,7 @@ static void AddrManSelectByNetwork(benchmark::Bench& bench)
135121
i2p_service.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.i2p");
136122
CAddress i2p_address(i2p_service, NODE_NONE);
137123
i2p_address.nTime = Now<NodeSeconds>();
138-
CNetAddr source = ResolveIP("252.2.2.2");
124+
const CNetAddr source{LookupHost("252.2.2.2", false).value()};
139125
addrman.Add({i2p_address}, source);
140126

141127
FillAddrMan(addrman);

src/httpserver.cpp

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -170,12 +170,8 @@ static bool ClientAllowed(const CNetAddr& netaddr)
170170
static bool InitHTTPAllowList()
171171
{
172172
rpc_allow_subnets.clear();
173-
CNetAddr localv4;
174-
CNetAddr localv6;
175-
LookupHost("127.0.0.1", localv4, false);
176-
LookupHost("::1", localv6, false);
177-
rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
178-
rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
173+
rpc_allow_subnets.push_back(CSubNet{LookupHost("127.0.0.1", false).value(), 8}); // always allow IPv4 local subnet
174+
rpc_allow_subnets.push_back(CSubNet{LookupHost("::1", false).value()}); // always allow IPv6 localhost
179175
for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
180176
CSubNet subnet;
181177
LookupSubNet(strAllow, subnet);
@@ -338,8 +334,8 @@ static bool HTTPBindAddresses(struct evhttp* http)
338334
LogPrintf("Binding RPC on address %s port %i\n", i->first, i->second);
339335
evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
340336
if (bind_handle) {
341-
CNetAddr addr;
342-
if (i->first.empty() || (LookupHost(i->first, addr, false) && addr.IsBindAny())) {
337+
const std::optional<CNetAddr> addr{LookupHost(i->first, false)};
338+
if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
343339
LogPrintf("WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
344340
}
345341
boundSockets.push_back(bind_handle);

src/init.cpp

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1359,12 +1359,12 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
13591359
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
13601360
std::string proxyArg = args.GetArg("-proxy", "");
13611361
if (proxyArg != "" && proxyArg != "0") {
1362-
CService proxyAddr;
1363-
if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
1362+
const std::optional<CService> proxyAddr{Lookup(proxyArg, 9050, fNameLookup)};
1363+
if (!proxyAddr.has_value()) {
13641364
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
13651365
}
13661366

1367-
Proxy addrProxy = Proxy(proxyAddr, proxyRandomize);
1367+
Proxy addrProxy = Proxy(proxyAddr.value(), proxyRandomize);
13681368
if (!addrProxy.IsValid())
13691369
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
13701370

@@ -1390,11 +1390,11 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
13901390
"reaching the Tor network is explicitly forbidden: -onion=0"));
13911391
}
13921392
} else {
1393-
CService addr;
1394-
if (!Lookup(onionArg, addr, 9050, fNameLookup) || !addr.IsValid()) {
1393+
const std::optional<CService> addr{Lookup(onionArg, 9050, fNameLookup)};
1394+
if (!addr.has_value() || !addr->IsValid()) {
13951395
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
13961396
}
1397-
onion_proxy = Proxy{addr, proxyRandomize};
1397+
onion_proxy = Proxy{addr.value(), proxyRandomize};
13981398
}
13991399
}
14001400

@@ -1414,9 +1414,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14141414
}
14151415

14161416
for (const std::string& strAddr : args.GetArgs("-externalip")) {
1417-
CService addrLocal;
1418-
if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1419-
AddLocal(addrLocal, LOCAL_MANUAL);
1417+
const std::optional<CService> addrLocal{Lookup(strAddr, GetListenPort(), fNameLookup)};
1418+
if (addrLocal.has_value() && addrLocal->IsValid())
1419+
AddLocal(addrLocal.value(), LOCAL_MANUAL);
14201420
else
14211421
return InitError(ResolveErrMsg("externalip", strAddr));
14221422
}
@@ -1754,22 +1754,24 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
17541754
};
17551755

17561756
for (const std::string& bind_arg : args.GetArgs("-bind")) {
1757-
CService bind_addr;
1757+
std::optional<CService> bind_addr;
17581758
const size_t index = bind_arg.rfind('=');
17591759
if (index == std::string::npos) {
1760-
if (Lookup(bind_arg, bind_addr, default_bind_port, /*fAllowLookup=*/false)) {
1761-
connOptions.vBinds.push_back(bind_addr);
1762-
if (IsBadPort(bind_addr.GetPort())) {
1763-
InitWarning(BadPortWarning("-bind", bind_addr.GetPort()));
1760+
bind_addr = Lookup(bind_arg, default_bind_port, /*fAllowLookup=*/false);
1761+
if (bind_addr.has_value()) {
1762+
connOptions.vBinds.push_back(bind_addr.value());
1763+
if (IsBadPort(bind_addr.value().GetPort())) {
1764+
InitWarning(BadPortWarning("-bind", bind_addr.value().GetPort()));
17641765
}
17651766
continue;
17661767
}
17671768
} else {
17681769
const std::string network_type = bind_arg.substr(index + 1);
17691770
if (network_type == "onion") {
17701771
const std::string truncated_bind_arg = bind_arg.substr(0, index);
1771-
if (Lookup(truncated_bind_arg, bind_addr, BaseParams().OnionServiceTargetPort(), false)) {
1772-
connOptions.onion_binds.push_back(bind_addr);
1772+
bind_addr = Lookup(truncated_bind_arg, BaseParams().OnionServiceTargetPort(), false);
1773+
if (bind_addr.has_value()) {
1774+
connOptions.onion_binds.push_back(bind_addr.value());
17731775
continue;
17741776
}
17751777
}
@@ -1847,11 +1849,11 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
18471849

18481850
const std::string& i2psam_arg = args.GetArg("-i2psam", "");
18491851
if (!i2psam_arg.empty()) {
1850-
CService addr;
1851-
if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
1852+
const std::optional<CService> addr{Lookup(i2psam_arg, 7656, fNameLookup)};
1853+
if (!addr.has_value() || !addr->IsValid()) {
18521854
return InitError(strprintf(_("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
18531855
}
1854-
SetProxy(NET_I2P, Proxy{addr});
1856+
SetProxy(NET_I2P, Proxy{addr.value()});
18551857
} else {
18561858
if (args.IsArgSet("-onlynet") && IsReachable(NET_I2P)) {
18571859
return InitError(

src/mapport.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,10 @@ static bool ProcessUpnp()
175175
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
176176
} else {
177177
if (externalIPAddress[0]) {
178-
CNetAddr resolved;
179-
if (LookupHost(externalIPAddress, resolved, false)) {
180-
LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToStringAddr());
181-
AddLocal(resolved, LOCAL_MAPPED);
178+
std::optional<CNetAddr> resolved{LookupHost(externalIPAddress, false)};
179+
if (resolved.has_value()) {
180+
LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved->ToStringAddr());
181+
AddLocal(resolved.value(), LOCAL_MAPPED);
182182
}
183183
} else {
184184
LogPrintf("UPnP: GetExternalIPAddress failed.\n");

src/net.cpp

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -130,14 +130,10 @@ uint16_t GetListenPort()
130130
{
131131
// If -bind= is provided with ":port" part, use that (first one if multiple are provided).
132132
for (const std::string& bind_arg : gArgs.GetArgs("-bind")) {
133-
CService bind_addr;
134133
constexpr uint16_t dummy_port = 0;
135134

136-
if (Lookup(bind_arg, bind_addr, dummy_port, /*fAllowLookup=*/false)) {
137-
if (bind_addr.GetPort() != dummy_port) {
138-
return bind_addr.GetPort();
139-
}
140-
}
135+
const std::optional<CService> bind_addr{Lookup(bind_arg, dummy_port, /*fAllowLookup=*/false)};
136+
if (bind_addr.has_value() && bind_addr->GetPort() != dummy_port) return bind_addr->GetPort();
141137
}
142138

143139
// Otherwise, if -whitebind= without NetPermissionFlags::NoBan is provided, use that
@@ -461,9 +457,9 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
461457
const uint16_t default_port{pszDest != nullptr ? Params().GetDefaultPort(pszDest) :
462458
Params().GetDefaultPort()};
463459
if (pszDest) {
464-
std::vector<CService> resolved;
465-
if (Lookup(pszDest, resolved, default_port, fNameLookup && !HaveNameProxy(), 256) && !resolved.empty()) {
466-
const CService rnd{resolved[GetRand(resolved.size())]};
460+
const std::vector<CService> resolved{Lookup(pszDest, default_port, fNameLookup && !HaveNameProxy(), 256)};
461+
if (!resolved.empty()) {
462+
const CService& rnd{resolved[GetRand(resolved.size())]};
467463
addrConnect = CAddress{MaybeFlipIPv6toCJDNS(rnd), NODE_NONE};
468464
if (!addrConnect.IsValid()) {
469465
LogPrint(BCLog::NET, "Resolver returned invalid address %s for %s\n", addrConnect.ToStringAddrPort(), pszDest);
@@ -1487,7 +1483,6 @@ void CConnman::ThreadDNSAddressSeed()
14871483
if (HaveNameProxy()) {
14881484
AddAddrFetch(seed);
14891485
} else {
1490-
std::vector<CNetAddr> vIPs;
14911486
std::vector<CAddress> vAdd;
14921487
ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE);
14931488
std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
@@ -1496,8 +1491,9 @@ void CConnman::ThreadDNSAddressSeed()
14961491
continue;
14971492
}
14981493
unsigned int nMaxIPs = 256; // Limits number of IPs learned from a DNS seed
1499-
if (LookupHost(host, vIPs, nMaxIPs, true)) {
1500-
for (const CNetAddr& ip : vIPs) {
1494+
const auto addresses{LookupHost(host, nMaxIPs, true)};
1495+
if (!addresses.empty()) {
1496+
for (const CNetAddr& ip : addresses) {
15011497
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
15021498
addr.nTime = rng.rand_uniform_delay(Now<NodeSeconds>() - 3 * 24h, -4 * 24h); // use a random age between 3 and 7 days old
15031499
vAdd.push_back(addr);
@@ -2201,14 +2197,11 @@ void Discover()
22012197
char pszHostName[256] = "";
22022198
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
22032199
{
2204-
std::vector<CNetAddr> vaddr;
2205-
if (LookupHost(pszHostName, vaddr, 0, true))
2200+
const std::vector<CNetAddr> addresses{LookupHost(pszHostName, 0, true)};
2201+
for (const CNetAddr& addr : addresses)
22062202
{
2207-
for (const CNetAddr &addr : vaddr)
2208-
{
2209-
if (AddLocal(addr, LOCAL_IF))
2210-
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToStringAddr());
2211-
}
2203+
if (AddLocal(addr, LOCAL_IF))
2204+
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToStringAddr());
22122205
}
22132206
}
22142207
#elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)

src/net_permissions.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,18 +88,18 @@ bool NetWhitebindPermissions::TryParse(const std::string& str, NetWhitebindPermi
8888
if (!TryParsePermissionFlags(str, flags, offset, error)) return false;
8989

9090
const std::string strBind = str.substr(offset);
91-
CService addrBind;
92-
if (!Lookup(strBind, addrBind, 0, false)) {
91+
const std::optional<CService> addrBind{Lookup(strBind, 0, false)};
92+
if (!addrBind.has_value()) {
9393
error = ResolveErrMsg("whitebind", strBind);
9494
return false;
9595
}
96-
if (addrBind.GetPort() == 0) {
96+
if (addrBind.value().GetPort() == 0) {
9797
error = strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind);
9898
return false;
9999
}
100100

101101
output.m_flags = flags;
102-
output.m_service = addrBind;
102+
output.m_service = addrBind.value();
103103
error = Untranslated("");
104104
return true;
105105
}

0 commit comments

Comments
 (0)