i think we could avoid invalid clearnet source addresses by introducing a dedicated type that can only represent a specific IPv4 or IPv6 address. once you have one, callers can rely on it being a valid clearnet source without having to keep checking
currently, that guarantee is maintained by convention between init and the connect path. a dedicated type would make it an invariant instead, so an invalid address cannot easily make its way into the connection code. i think that would make the code easier to reason about and protect against future regressions
<details><summary>patch</summary>
diff --git a/src/init.cpp b/src/init.cpp
index 812e456b7d..ce8f11dfe4 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -2208,32 +2208,18 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
// Classify fc00::/8 as CJDNS when -cjdnsreachable is set, the same
// way the connect path does.
const CNetAddr bind_addr{static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{*lookup_addr, /*port=*/0}))};
- // The unspecified (wildcard) address pins nothing, so it is not a
- // usable source address. Any other unusable value is left to the
- // trial bind of the effective address below.
- if (bind_addr.IsBindAny()) {
- return InitError(strprintf(_("-outboundbind address '%s' is not a usable source address"), bind_arg));
- }
- // GetArgs() returns values in descending source precedence (command line
- // before config file), so keep the first per family: the command line
- // wins over the config file, and repeats resolve to the first given.
- if (bind_addr.IsIPv4()) {
- if (!connOptions.outbound_bind_v4) connOptions.outbound_bind_v4 = bind_addr;
- } else if (bind_addr.IsIPv6()) {
- if (!connOptions.outbound_bind_v6) connOptions.outbound_bind_v6 = bind_addr;
- } else if (bind_addr.IsCJDNS()) {
- return InitError(strprintf(_("-outboundbind address '%s' is a CJDNS address (fc00::/8 while -cjdnsreachable is set), which cannot be a clearnet source"), bind_arg));
- } else {
- // LookupHost() also accepts Tor/I2P addresses (via SetSpecial);
- // they cannot be a clearnet source.
- return InitError(strprintf(_("-outboundbind address '%s' is not an IPv4 or IPv6 address"), bind_arg));
+ const auto source{ClearnetSource::Make(bind_addr)};
+ if (!source) {
+ return InitError(strprintf(_("-outboundbind address '%s' must be a specific IPv4 or IPv6 address (not a wildcard, Tor, I2P or CJDNS address)"), bind_arg));
}
+ auto& slot{source->Addr().IsIPv4() ? connOptions.outbound_bind_v4 : connOptions.outbound_bind_v6};
+ if (!slot) slot = source;
}
// Check that the addresses that will be used can be bound to. Only the
// effective address per family is checked, so that a command-line
// -outboundbind can override a config-file one that is no longer assigned
// to this machine.
- for (const std::optional<CNetAddr>& bind_addr : {connOptions.outbound_bind_v4, connOptions.outbound_bind_v6}) {
+ for (const std::optional<ClearnetSource>& bind_addr : {connOptions.outbound_bind_v4, connOptions.outbound_bind_v6}) {
if (!bind_addr.has_value()) continue;
bilingual_str error;
if (!IsAddrBindable(*bind_addr, error)) {
diff --git a/src/net.h b/src/net.h
index f6019bf7e8..4052502235 100644
--- a/src/net.h
+++ b/src/net.h
@@ -1103,8 +1103,8 @@ public:
std::vector<NetWhitebindPermissions> vWhiteBinds;
std::vector<CService> vBinds;
//! Source address for outgoing connections, one per address family.
- std::optional<CNetAddr> outbound_bind_v4;
- std::optional<CNetAddr> outbound_bind_v6;
+ std::optional<ClearnetSource> outbound_bind_v4;
+ std::optional<ClearnetSource> outbound_bind_v6;
std::vector<CService> onion_binds;
/// True if the user did not specify -bind= or -whitebind= and thus
/// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
@@ -1807,8 +1807,8 @@ private:
* the config file). Applied only to outgoing clearnet (IPv4/IPv6)
* connections; Tor, I2P and CJDNS are unaffected.
*/
- std::optional<CNetAddr> m_outbound_bind_v4;
- std::optional<CNetAddr> m_outbound_bind_v6;
+ std::optional<ClearnetSource> m_outbound_bind_v4;
+ std::optional<ClearnetSource> m_outbound_bind_v6;
/**
* Source address to bind for an outgoing connection to `target`: the
@@ -1817,7 +1817,7 @@ private:
* source is bound (the tun device selects it); Tor and I2P use their own
* transports.
*/
- std::optional<CNetAddr> SelectOutboundBind(const CService& target) const
+ std::optional<ClearnetSource> SelectOutboundBind(const CService& target) const
{
if (target.IsIPv4()) return m_outbound_bind_v4;
if (target.IsIPv6()) return m_outbound_bind_v6;
diff --git a/src/netbase.cpp b/src/netbase.cpp
index e7d5589f16..b5ec56ed31 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -648,7 +648,7 @@ static bool ConnectToSocket(const Sock& sock,
return true;
}
-std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<CNetAddr>& bind_addr, bool* bind_failed)
+std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<ClearnetSource>& bind_addr, bool* bind_failed)
{
return ConnectDirectly(dest, manual_connection, std::chrono::milliseconds{nConnectTimeout}, bind_addr, bind_failed);
}
@@ -656,7 +656,7 @@ std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connecti
std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
bool manual_connection,
std::chrono::milliseconds timeout,
- const std::optional<CNetAddr>& bind_addr,
+ const std::optional<ClearnetSource>& bind_addr,
bool* bind_failed)
{
auto sock = CreateSock(dest.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
@@ -667,11 +667,11 @@ std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
// If a bind address is specified, bind to it before connecting.
if (bind_addr) {
- const CService bind_service{*bind_addr, /*port=*/0};
+ const CService bind_service{bind_addr->Addr(), /*port=*/0};
sockaddr_storage bind_sa;
socklen_t bind_len = sizeof(bind_sa);
- if (!bind_service.GetSockAddr(reinterpret_cast<sockaddr*>(&bind_sa), &bind_len)) {
- LogInfo("Cannot get sockaddr for bind address %s", bind_addr->ToStringAddr());
+ // NOTE: ClearnetSource is IPv4/IPv6 by construction, so a sockaddr always exists
+ if (!Assume(bind_service.GetSockAddr(reinterpret_cast<sockaddr*>(&bind_sa), &bind_len))) {
if (bind_failed) *bind_failed = true;
return {};
}
@@ -691,7 +691,7 @@ std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
// source that is no longer bindable is an operator misconfiguration
// worth surfacing. The global log rate limiter bounds repetition.
LogWarning("Failed to bind to %s for outgoing connection to %s: %s",
- bind_addr->ToStringAddr(), dest.ToStringAddrPort(), NetworkErrorString(err));
+ bind_addr->Addr().ToStringAddr(), dest.ToStringAddrPort(), NetworkErrorString(err));
if (bind_failed) *bind_failed = true;
return {};
}
@@ -1018,25 +1018,25 @@ CService GetBindAddress(const Sock& sock)
return addr_bind;
}
-bool IsAddrBindable(const CNetAddr& addr, bilingual_str& error)
+bool IsAddrBindable(const ClearnetSource& source, bilingual_str& error)
{
- const CService service{addr, /*port=*/0};
+ const CService service{source.Addr(), /*port=*/0};
sockaddr_storage sa;
socklen_t len = sizeof(sa);
- if (!service.GetSockAddr(reinterpret_cast<sockaddr*>(&sa), &len)) {
- error = Untranslated(strprintf("Bind address family for %s not supported", addr.ToStringAddr()));
+ // NOTE: ClearnetSource is IPv4/IPv6 by construction, so a sockaddr always exists
+ if (!Assume(service.GetSockAddr(reinterpret_cast<sockaddr*>(&sa), &len))) {
return false;
}
std::unique_ptr<Sock> sock = CreateSock(service.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
if (!sock) {
const int err{WSAGetLastError()};
- error = Untranslated(strprintf("Couldn't open socket for %s (socket returned error %s)", addr.ToStringAddr(), NetworkErrorString(err)));
+ error = Untranslated(strprintf("Couldn't open socket for %s (socket returned error %s)", source.Addr().ToStringAddr(), NetworkErrorString(err)));
return false;
}
if (sock->Bind(reinterpret_cast<sockaddr*>(&sa), len) == SOCKET_ERROR) {
const int err{WSAGetLastError()};
error = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"),
- addr.ToStringAddr(), NetworkErrorString(err));
+ source.Addr().ToStringAddr(), NetworkErrorString(err));
return false;
}
return true;
diff --git a/src/netbase.h b/src/netbase.h
index 748e5e2d92..45fcae1743 100644
--- a/src/netbase.h
+++ b/src/netbase.h
@@ -173,6 +173,26 @@ private:
extern ReachableNets g_reachable_nets;
+/**
+ * A local source address that is guaranteed usable for a clearnet connection:
+ * a specific (non-wildcard) IPv4 or IPv6 address. Tor, CJDNS, I2P and the wildcard
+ * address cannot be represented, so consumers need no checks.
+ */
+class ClearnetSource
+{
+public:
+ static std::optional<ClearnetSource> Make(const CNetAddr& addr)
+ {
+ if (addr.IsBindAny() || (!addr.IsIPv6() && !addr.IsIPv4())) return std::nullopt;
+ return ClearnetSource(addr);
+ }
+ const CNetAddr& Addr() const { return m_addr; }
+
+private:
+ explicit ClearnetSource(const CNetAddr& addr) : m_addr(addr) {}
+ CNetAddr m_addr;
+};
+
/**
* Wrapper for getaddrinfo(3). Do not use directly: call Lookup/LookupHost/LookupNumeric/LookupSubNet.
*/
@@ -303,7 +323,7 @@ extern std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock;
*
* [@param](/bitcoin-bitcoin/contributor/param/)[in] dest The service to which to connect.
* [@param](/bitcoin-bitcoin/contributor/param/)[in] manual_connection Whether or not the connection was manually requested (e.g. through the addnode RPC)
- * [@param](/bitcoin-bitcoin/contributor/param/)[in] bind_addr If set, bind to this local address before connecting. On
+ * [@param](/bitcoin-bitcoin/contributor/param/)[in] bind_addr If set, bind to this local source address before connecting. On
* bind failure the connection is aborted; there is no fallback to a
* default source address.
* [@param](/bitcoin-bitcoin/contributor/param/)[out] bind_failed If not nullptr, set to true when the connection was
@@ -312,13 +332,13 @@ extern std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock;
*
* [@returns](/bitcoin-bitcoin/contributor/returns/) the connected socket if the operation succeeded, empty unique_ptr otherwise
*/
-std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<CNetAddr>& bind_addr = std::nullopt, bool* bind_failed = nullptr);
+std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<ClearnetSource>& bind_addr = std::nullopt, bool* bind_failed = nullptr);
/** Create a socket and try to connect to the specified service, using the provided timeout. */
std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
bool manual_connection,
std::chrono::milliseconds timeout,
- const std::optional<CNetAddr>& bind_addr = std::nullopt,
+ const std::optional<ClearnetSource>& bind_addr = std::nullopt,
bool* bind_failed = nullptr);
/**
@@ -384,10 +404,10 @@ CService MaybeFlipIPv6toCJDNS(const CService& service);
CService GetBindAddress(const Sock& sock);
/**
- * Check whether a local address can be bound to (assigned to a local interface).
+ * Check whether a local source address can be bound to (assigned to a local interface).
* Attempts a real bind() syscall on a fresh socket; the socket is closed before
* return. Returns false with `error` populated on failure.
*/
-bool IsAddrBindable(const CNetAddr& addr, bilingual_str& error);
+bool IsAddrBindable(const ClearnetSource& source, bilingual_str& error);
#endif // BITCOIN_NETBASE_H
diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index 400f19a1f2..92cadac01a 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -1711,30 +1711,30 @@ BOOST_AUTO_TEST_CASE(outbound_bind_address_selection)
const CNetAddr addr6{LookupHost("2001:db8::1", /*fAllowLookup=*/false).value()};
// An address is stored per family; an unset family stays unset.
- options.outbound_bind_v4 = addr4;
+ options.outbound_bind_v4 = ClearnetSource::Make(addr4);
connman->Init(options);
BOOST_REQUIRE(connman->GetOutboundBindV4());
- BOOST_CHECK_EQUAL(connman->GetOutboundBindV4()->ToStringAddr(), addr4.ToStringAddr());
+ BOOST_CHECK_EQUAL(connman->GetOutboundBindV4()->Addr().ToStringAddr(), addr4.ToStringAddr());
BOOST_CHECK(!connman->GetOutboundBindV6());
// With the v6 family unset, an IPv6 target selects nothing.
BOOST_CHECK(!connman->SelectOutboundBindPublic(CService{LookupHost("2001:db8::3", /*fAllowLookup=*/false).value(), /*port=*/8333}));
// Setting the other family leaves the first family's stored address intact.
connman = std::make_unique<ConnmanTestMsg>(seed, seed, *m_node.addrman, *m_node.netgroupman, Params());
- options.outbound_bind_v6 = addr6;
+ options.outbound_bind_v6 = ClearnetSource::Make(addr6);
connman->Init(options);
BOOST_REQUIRE(connman->GetOutboundBindV4());
BOOST_REQUIRE(connman->GetOutboundBindV6());
- BOOST_CHECK_EQUAL(connman->GetOutboundBindV6()->ToStringAddr(), addr6.ToStringAddr());
+ BOOST_CHECK_EQUAL(connman->GetOutboundBindV6()->Addr().ToStringAddr(), addr6.ToStringAddr());
// SelectOutboundBind() picks the configured source by the target's family,
// and binds nothing for a non-clearnet (Tor/I2P/CJDNS) target.
const auto sel4{connman->SelectOutboundBindPublic(CService{LookupHost("198.51.100.1", /*fAllowLookup=*/false).value(), /*port=*/8333})};
BOOST_REQUIRE(sel4);
- BOOST_CHECK_EQUAL(sel4->ToStringAddr(), addr4.ToStringAddr());
+ BOOST_CHECK_EQUAL(sel4->Addr().ToStringAddr(), addr4.ToStringAddr());
const auto sel6{connman->SelectOutboundBindPublic(CService{LookupHost("2001:db8::2", /*fAllowLookup=*/false).value(), /*port=*/8333})};
BOOST_REQUIRE(sel6);
- BOOST_CHECK_EQUAL(sel6->ToStringAddr(), addr6.ToStringAddr());
+ BOOST_CHECK_EQUAL(sel6->Addr().ToStringAddr(), addr6.ToStringAddr());
const CService onion{LookupHost("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", /*fAllowLookup=*/false).value(), /*port=*/8333};
BOOST_CHECK(!connman->SelectOutboundBindPublic(onion));
CNetAddr i2p;
@@ -1809,19 +1809,19 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
CreateSock = [&bound](int, int, int) { return std::make_unique<BindRecordingSock>(bound); };
const CService dest{LookupNumeric("198.51.100.34", 8333)};
- const CNetAddr src{LookupHost("203.0.113.1", /*fAllowLookup=*/false).value()};
+ const auto src{ClearnetSource::Make(LookupHost("203.0.113.1", /*fAllowLookup=*/false).value())};
BOOST_REQUIRE(ConnectDirectly(dest, /*manual_connection=*/false, src));
BOOST_REQUIRE(bound.has_value());
- BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src, /*port=*/0).ToStringAddrPort());
+ BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src->Addr(), /*port=*/0).ToStringAddrPort());
// The same for IPv6.
bound.reset();
const CService dest6{LookupNumeric("2001:db8::1", 8333)};
- const CNetAddr src6{LookupHost("2001:db8::2", /*fAllowLookup=*/false).value()};
+ const auto src6{ClearnetSource::Make(LookupHost("2001:db8::2", /*fAllowLookup=*/false).value())};
BOOST_REQUIRE(ConnectDirectly(dest6, /*manual_connection=*/false, src6));
BOOST_REQUIRE(bound.has_value());
- BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src6, /*port=*/0).ToStringAddrPort());
+ BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src6->Addr(), /*port=*/0).ToStringAddrPort());
// The bind_failed out-param stays false when no bind was requested and on
// a successful bind, so the caller only skips addrman accounting when the
@@ -1843,22 +1843,12 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
BOOST_CHECK(!ConnectDirectly(dest, /*manual_connection=*/false, src, &bind_failed));
BOOST_CHECK(!connect_called);
BOOST_CHECK(bind_failed);
-
- // A non-clearnet source has no sockaddr: ConnectDirectly() aborts before
- // connecting (defensive; SelectOutboundBind() never yields such a source).
- // This local failure also reports bind_failed.
- CNetAddr onion_src;
- BOOST_REQUIRE(onion_src.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
- CreateSock = [](int, int, int) { return std::make_unique<ZeroSock>(); };
- bind_failed = false;
- BOOST_CHECK(!ConnectDirectly(dest, /*manual_connection=*/false, onion_src, &bind_failed));
- BOOST_CHECK(bind_failed);
}
BOOST_AUTO_TEST_CASE(is_addr_bindable)
{
// IsAddrBindable() trial-binds a fresh socket and reports the result.
- const CNetAddr addr{LookupHost("127.0.0.1", /*fAllowLookup=*/false).value()};
+ const auto addr{ClearnetSource::Make(LookupHost("127.0.0.1", /*fAllowLookup=*/false).value()).value()};
struct SockRestore {
const decltype(CreateSock) orig{CreateSock};
~SockRestore() { CreateSock = orig; }
@@ -1891,13 +1881,6 @@ BOOST_AUTO_TEST_CASE(is_addr_bindable)
error = bilingual_str{};
BOOST_CHECK(!IsAddrBindable(addr, error));
BOOST_CHECK(!error.empty());
-
- // A non-clearnet address has no sockaddr -> not bindable, family error.
- CNetAddr onion;
- BOOST_REQUIRE(onion.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
- error = bilingual_str{};
- BOOST_CHECK(!IsAddrBindable(onion, error));
- BOOST_CHECK(!error.empty());
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/util/net.h b/src/test/util/net.h
index 18665b3c04..bf0fc97ac5 100644
--- a/src/test/util/net.h
+++ b/src/test/util/net.h
@@ -89,9 +89,9 @@ struct ConnmanTestMsg : public CConnman {
return InitBinds(options);
}
- std::optional<CNetAddr> GetOutboundBindV4() const { return m_outbound_bind_v4; }
- std::optional<CNetAddr> GetOutboundBindV6() const { return m_outbound_bind_v6; }
- std::optional<CNetAddr> SelectOutboundBindPublic(const CService& target) const { return SelectOutboundBind(target); }
+ std::optional<ClearnetSource> GetOutboundBindV4() const { return m_outbound_bind_v4; }
+ std::optional<ClearnetSource> GetOutboundBindV6() const { return m_outbound_bind_v6; }
+ std::optional<ClearnetSource> SelectOutboundBindPublic(const CService& target) const { return SelectOutboundBind(target); }
void SocketHandlerPublic()
{
diff --git a/test/functional/feature_bind_outgoing.py b/test/functional/feature_bind_outgoing.py
index f4a8d502aa..a8102f6ca0 100755
--- a/test/functional/feature_bind_outgoing.py
+++ b/test/functional/feature_bind_outgoing.py
@@ -107,7 +107,7 @@ class BindOutgoingTest(BitcoinTestFramework):
for wildcard in ('0.0.0.0', '::'):
self.nodes[1].assert_start_raises_init_error(
extra_args=[f'-outboundbind={wildcard}'],
- expected_msg=f"Error: -outboundbind address '{wildcard}' is not a usable source address",
+ expected_msg=f"Error: -outboundbind address '{wildcard}' must be a specific IPv4 or IPv6 address",
match=ErrorMatch.PARTIAL_REGEX,
)
@@ -118,21 +118,6 @@ class BindOutgoingTest(BitcoinTestFramework):
match=ErrorMatch.PARTIAL_REGEX,
)
- self.log.info('Check that a non-clearnet (Tor) address is rejected at startup')
- self.nodes[1].assert_start_raises_init_error(
- extra_args=['-outboundbind=pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion'],
- expected_msg='is not an IPv4 or IPv6 address',
- match=ErrorMatch.PARTIAL_REGEX,
- )
-
- self.log.info('Check that an fc00::/8 address is rejected at startup when it '
- 'is a CJDNS address (-cjdnsreachable)')
- self.nodes[1].assert_start_raises_init_error(
- extra_args=['-cjdnsreachable', '-outboundbind=fc00:db8::1'],
- expected_msg='is a CJDNS address',
- match=ErrorMatch.PARTIAL_REGEX,
- )
-
self.log.info('Check that fc00::/8 stays a plain IPv6 source without -cjdnsreachable')
# Accepted by the parser (proven by reaching the later trial bind, which
# fails because the address is not assigned to this machine).
</details>
what do you think ?