net: add -outboundbind option for outgoing source address #35027

Open
8144225309 wants to merge 3 commits from net-bind-outgoing into master AGit
8144225309 commented 2026-04-07 21:48:46 +00:00 (Migrated from github.com)

Closes #6476

Adds -outboundbind=<addr> to set the source address of outgoing clearnet
connections, one per address family. It is separate from -bind; without it,
outbound follows the OS routing table as before.

  • The command line wins over the config file, as for other options.
  • Clearnet only: Tor and I2P use their own transport, CJDNS is direct but not
    IPv4/IPv6, and a proxy leaves the option inert for that family (with a
    startup warning).
  • The effective address per family is trial-bound at startup, like -bind via
    BindListenPort; a port, the wildcard, or a non-clearnet value is rejected. A
    failed bind at connect time aborts the connection, with no fallback.

Functional and unit tests cover both families, the startup rejections, and the
bind-before-connect path.

Based on vasild's approach in
https://github.com/bitcoin/bitcoin/issues/6476#issuecomment-1666472338.

Closes #6476 Adds `-outboundbind=<addr>` to set the source address of outgoing clearnet connections, one per address family. It is separate from `-bind`; without it, outbound follows the OS routing table as before. - The command line wins over the config file, as for other options. - Clearnet only: Tor and I2P use their own transport, CJDNS is direct but not IPv4/IPv6, and a proxy leaves the option inert for that family (with a startup warning). - The effective address per family is trial-bound at startup, like `-bind` via `BindListenPort`; a port, the wildcard, or a non-clearnet value is rejected. A failed bind at connect time aborts the connection, with no fallback. Functional and unit tests cover both families, the startup rejections, and the bind-before-connect path. Based on vasild's approach in https://github.com/bitcoin/bitcoin/issues/6476#issuecomment-1666472338.
DrahtBot commented 2026-04-07 21:49:10 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK frankomosh
Approach ACK vasild, winterrdog

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36954 (net: make address overlap impossible when relaying addresses by vasild)
  • #36819 ([RFC] enable clang-tidy optin.performance.Padding by fanquake)
  • #36736 (net: unify send pause state by l0rinc)
  • #35936 (net: reject oversized locators before allocating by l0rinc)
  • #17783 (common: Disallow calling IsArgSet() on ALLOW_LIST options by ryanofsky)
  • #17580 (refactor: Add ALLOW_LIST flags and enforce usage in CheckArgFlags by ryanofsky)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35027 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35027.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35027#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [frankomosh](https://github.com/bitcoin/bitcoin/pull/35027#pullrequestreview-4104595148) | | Approach ACK | [vasild](https://github.com/bitcoin/bitcoin/pull/35027#pullrequestreview-4458989700), [winterrdog](https://github.com/bitcoin/bitcoin/pull/35027#pullrequestreview-5187086729) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36954](https://github.com/bitcoin/bitcoin/pull/36954) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36954.svg"></sub> (net: make address overlap impossible when relaying addresses by vasild) * [#36819](https://github.com/bitcoin/bitcoin/pull/36819) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36819.svg"></sub> ([RFC] enable `clang-tidy` `optin.performance.Padding` by fanquake) * [#36736](https://github.com/bitcoin/bitcoin/pull/36736) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36736.svg"></sub> (net: unify send pause state by l0rinc) * [#35936](https://github.com/bitcoin/bitcoin/pull/35936) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35936.svg"></sub> (net: reject oversized locators before allocating by l0rinc) * [#17783](https://github.com/bitcoin/bitcoin/pull/17783) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/17783.svg"></sub> (common: Disallow calling IsArgSet() on ALLOW_LIST options by ryanofsky) * [#17580](https://github.com/bitcoin/bitcoin/pull/17580) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/17580.svg"></sub> (refactor: Add ALLOW_LIST flags and enforce usage in CheckArgFlags by ryanofsky) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
luke-jr commented 2026-04-09 17:12:43 +00:00 (Migrated from github.com)

This might break a scenario where someone wants to listen on one IP, but load balance outgoing connections. A new option might be better?

This might break a scenario where someone wants to listen on one IP, but load balance outgoing connections. A new option might be better?
8144225309 commented 2026-04-09 18:38:53 +00:00 (Migrated from github.com)

The original issue asks for -bind to control outgoing connections, and users who want listen-only can omit -bind. Outbound is capped at 11 (8 full relay + 2 block-only + 1 feeler) so there isn't much to load balance. A separate option could work but users already expect -bind to cover both directions.

The original issue asks for `-bind` to control outgoing connections, and users who want listen-only can omit `-bind`. Outbound is capped at 11 (8 full relay + 2 block-only + 1 feeler) so there isn't much to load balance. A separate option could work but users already expect `-bind` to cover both directions.
frankomosh (Migrated from github.com) reviewed 2026-04-14 09:16:17 +00:00
frankomosh (Migrated from github.com) left a comment

concept ACK.

Left some inline comments

concept ACK. Left some inline comments
frankomosh (Migrated from github.com) commented 2026-04-14 08:54:01 +00:00

IsLocal() also matches 0.0.0.0/8, not just loopback. The PR description says "loopback addresses are skipped", but the actual skip is broader. Worth a comment somewhere, clarifying that?

`IsLocal()` also matches `0.0.0.0/8`, not just loopback. The PR description says "loopback addresses are skipped", but the actual skip is broader. Worth a comment somewhere, clarifying that?
frankomosh (Migrated from github.com) commented 2026-04-14 09:09:33 +00:00

The listen path validates the address early through BindListenPort and surfaces errors at startup. Here we store it without checking if it's actually assigned to a local interface. Would it make sense to do a trial bind() or similar check here so a misconfigured address fails loudly at init rather than silently killing outbound for that family.

The listen path validates the address early through `BindListenPort` and surfaces errors at startup. Here we store it without checking if it's actually assigned to a local interface. Would it make sense to do a trial `bind()` or similar check here so a misconfigured address fails loudly at init rather than silently killing outbound for that family.
frankomosh (Migrated from github.com) reviewed 2026-04-14 13:14:01 +00:00
frankomosh (Migrated from github.com) commented 2026-04-14 13:13:19 +00:00

I believe it would it be great to add a unit test that calls ConnectDirectly with a bind address, even if just to verify the syscall is attempted. Right now the unit test covers Init-time storage but this Bind() path has no automated coverage.

I believe it would it be great to add a unit test that calls `ConnectDirectly` with a bind address, even if just to verify the syscall is attempted. Right now the unit test covers Init-time storage but this `Bind()` path has no automated coverage.
frankomosh (Migrated from github.com) commented 2026-04-14 13:01:59 +00:00

The test verifies that the first IPv4 address is stored, but doesn't check that m_outbound_bind_v6 stays empty. If the else if condition were weakened, an IPv4 address could leak into the IPv6 slot undetected. You can avoid this by including BOOST_CHECK(!connman->GetOutboundBindV6()); around here.

The test verifies that the first IPv4 address is stored, but doesn't check that `m_outbound_bind_v6` stays empty. If the `else if` condition were weakened, an IPv4 address could leak into the IPv6 slot undetected. You can avoid this by including `BOOST_CHECK(!connman->GetOutboundBindV6());` around here.
gmaxwell commented 2026-04-25 02:38:04 +00:00 (Migrated from github.com)

The original issue asks for -bind to control outgoing connections, and users who want listen-only can omit -bind.

Just because someone asked that way doesn't mean it's the best solution. I believe that as proposed here -bind=mypublicinterface would suddenly make my node unable to connect to stuff on my local lan (or, in VM on bridge interfaces)-- pretty surprising.

I don't see any particular harm in making a separate obind to control output interfaces-- otherwise the OS's routing table makes binding decisions.

> The original issue asks for -bind to control outgoing connections, and users who want listen-only can omit -bind. Just because someone asked that way doesn't mean it's the best solution. I believe that as proposed here -bind=mypublicinterface would suddenly make my node unable to connect to stuff on my local lan (or, in VM on bridge interfaces)-- pretty surprising. I don't see any particular harm in making a separate obind to control output interfaces-- otherwise the OS's routing table makes binding decisions.
8144225309 commented 2026-04-25 15:29:04 +00:00 (Migrated from github.com)

On the LAN/bridge case, that's a real regression for multi-homed setups (VM bridges especially). A separate outbound-only option avoids it without forcing existing -bind users to revisit their configs.

I'd lean towards -bindoutgoing for clarity and alphabetic proximity to -bind in docs/tab-completion. That said, -outboundbind (or -obind) is arguably the better fit given the existing -whitebind/-rpcbind convention. Any preference?

On the LAN/bridge case, that's a real regression for multi-homed setups (VM bridges especially). A separate outbound-only option avoids it without forcing existing `-bind` users to revisit their configs. I'd lean towards `-bindoutgoing` for clarity and alphabetic proximity to `-bind` in docs/tab-completion. That said, `-outboundbind` (or `-obind`) is arguably the better fit given the existing `-whitebind`/`-rpcbind` convention. Any preference?
8144225309 commented 2026-05-23 05:11:19 +00:00 (Migrated from github.com)

Force-pushed a redesign based on the feedback above:

  • Added -outboundbind=<addr> as a separate option instead of extending -bind
  • Kept -bind semantics unchanged, so existing setups (including LAN/bridge peers) are unaffected
  • One non-local address per family, first wins; proxied (Tor, I2P, SOCKS5) and CJDNS excluded; loopback skipped
  • Named for consistency with -whitebind/-rpcbind; happy to rename if preferred
Force-pushed a redesign based on the feedback above: - Added `-outboundbind=<addr>` as a separate option instead of extending `-bind` - Kept `-bind` semantics unchanged, so existing setups (including LAN/bridge peers) are unaffected - One non-local address per family, first wins; proxied (Tor, I2P, SOCKS5) and CJDNS excluded; loopback skipped - Named for consistency with `-whitebind`/`-rpcbind`; happy to rename if preferred
DrahtBot commented 2026-05-24 09:05:08 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/26346661562/job/77584098255
LLM reason (✨ experimental): C++ build failed due to clang++ errors in src/netbase.cpp (use of undeclared identifier bind_addr, causing further CService constructor/type errors).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `test ancestor commits`: https://github.com/bitcoin/bitcoin/actions/runs/26346661562/job/77584098255</sub> <sub>LLM reason (✨ experimental): C++ build failed due to `clang++` errors in `src/netbase.cpp` (use of undeclared identifier `bind_addr`, causing further `CService` constructor/type errors).</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
vasild (Migrated from github.com) reviewed 2026-05-26 09:10:20 +00:00
vasild (Migrated from github.com) left a comment

Concept ACK

I agree that it is better to not change the semantic of the existent -bind and introduce a new option instead with a default value "leave it to the OS" which is the same as of before this PR.

Concept ACK I agree that it is better to not change the semantic of the existent `-bind` and introduce a new option instead with a default value "leave it to the OS" which is the same as of before this PR.
8144225309 commented 2026-06-04 23:33:29 +00:00 (Migrated from github.com)

Rebased after conflict with #35410: the outbound bind selection in ConnectNode now sits inside the new private-broadcast guard. Also fixed an include-order nit and clarified wording in a net.h comment and the test commit message.

Rebased after conflict with #35410: the outbound bind selection in `ConnectNode` now sits inside the new private-broadcast guard. Also fixed an include-order nit and clarified wording in a `net.h` comment and the test commit message.
vasild (Migrated from github.com) reviewed 2026-06-10 13:58:21 +00:00
vasild (Migrated from github.com) left a comment

Approach ACK fa19b8c43489ffcc7693317af3c754992078e536

Approach ACK fa19b8c43489ffcc7693317af3c754992078e536
vasild (Migrated from github.com) commented 2026-06-10 13:43:31 +00:00

The number at the end should be the PR that contains the change:

  Existing `-bind` semantics are unchanged. (#35027)
The number at the end should be the PR that contains the change: ```suggestion Existing `-bind` semantics are unchanged. (#35027) ```
vasild (Migrated from github.com) commented 2026-06-09 13:24:48 +00:00
    argsman.AddArg("-outboundbind=<addr>", "Bind outgoing connections to the given local address (one per address family). The address must be on a local interface; outgoing connections will use it as their source IP. Use [address] notation for IPv6.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);

Better use "address" as "host" could be mistaken for a hostname.

```suggestion argsman.AddArg("-outboundbind=<addr>", "Bind outgoing connections to the given local address (one per address family). The address must be on a local interface; outgoing connections will use it as their source IP. Use [address] notation for IPv6.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); ``` Better use "address" as "host" could be mistaken for a hostname.
vasild (Migrated from github.com) commented 2026-06-10 09:52:05 +00:00

Here we collect all addresses supplied to -outboundbind= but we will only use one IPv4 and one IPv6 of them. I think it would be better to replace this vector with two std::optional<CNetAddr> members, then just copy them from connOptions into the CConnman members.

Here we collect all addresses supplied to `-outboundbind=` but we will only use one IPv4 and one IPv6 of them. I think it would be better to replace this vector with two `std::optional<CNetAddr>` members, then just copy them from `connOptions` into the `CConnman` members.
vasild (Migrated from github.com) commented 2026-06-10 09:54:48 +00:00

Usually the notion is that the last one wins. E.g. -outboundbind=1.2.3.4 -outboundbind=5.6.7.8 -- 5.6.7.8 should be used. This helps override earlier settings which might be out of one's control.

Usually the notion is that the last one wins. E.g. `-outboundbind=1.2.3.4 -outboundbind=5.6.7.8` -- `5.6.7.8` should be used. This helps override earlier settings which might be out of one's control.
Lines 2184-2194
vasild (Migrated from github.com) commented 2026-06-09 13:30:15 +00:00

I didn't test, but I guess this will allow ports to be included, e.g. -outboundbind=1.2.4.5:5678 which better not be allowed to avoid confusion. LookupHost() can be used to parse just an address.

I didn't test, but I guess this will allow ports to be included, e.g. `-outboundbind=1.2.4.5:5678` which better not be allowed to avoid confusion. `LookupHost()` can be used to parse just an address.
vasild (Migrated from github.com) commented 2026-06-09 13:42:09 +00:00

In new code use snake_case.

        std::vector<CService> outbound_binds;

and also s/CService/CNetAddr/

In new code use `snake_case`. ```suggestion std::vector<CService> outbound_binds; ``` and also `s/CService/CNetAddr/`
vasild (Migrated from github.com) commented 2026-06-09 13:49:38 +00:00

What's the reason to silently swallow such addresses? It would be more obvious if we return an error for those at startup, like we do for invalid values.

What's the reason to silently swallow such addresses? It would be more obvious if we return an error for those at startup, like we do for invalid values.
vasild (Migrated from github.com) commented 2026-06-09 13:51:38 +00:00

Or even, why treat such addresses specially? It might be desirable to use -outboundbind=0.0.0.0 to remove the effect of a preceding -outboundbind=....

Or even, why treat such addresses specially? It might be desirable to use `-outboundbind=0.0.0.0` to remove the effect of a preceding `-outboundbind=...`.
vasild (Migrated from github.com) commented 2026-06-10 10:01:07 +00:00

Here and everywhere the trailing \n in the message is not needed anymore and is frowned upon. Drop it.

Here and everywhere the trailing `\n` in the message is not needed anymore and is frowned upon. Drop it.
Lines 1009-1011
vasild (Migrated from github.com) commented 2026-06-09 13:35:03 +00:00

If you want to have struct, that is fine. Just to mention that C++ can do without it:

    sockaddr_storage sa;
    socklen_t len = sizeof(sa);
    if (!service.GetSockAddr(reinterpret_cast<sockaddr*>(&sa), &len)) {
If you want to have `struct`, that is fine. Just to mention that C++ can do without it: ```suggestion sockaddr_storage sa; socklen_t len = sizeof(sa); if (!service.GetSockAddr(reinterpret_cast<sockaddr*>(&sa), &len)) { ```
vasild (Migrated from github.com) commented 2026-06-10 13:24:37 +00:00

The port here is irrelevant. These should all be CNetAddr.

The port here is irrelevant. These should all be `CNetAddr`.
vasild (Migrated from github.com) commented 2026-06-10 13:26:25 +00:00

Instead of hardcoding the string address again "203.0.113.1" better use addr1.ToStringAddr() (here and elsewhere).

Instead of hardcoding the string address again `"203.0.113.1"` better use `addr1.ToStringAddr()` (here and elsewhere).
Lines 1637-1645
vasild (Migrated from github.com) commented 2026-06-10 13:27:42 +00:00

This is not testing the new feature. Better drop it.

This is not testing the new feature. Better drop it.
vasild (Migrated from github.com) commented 2026-06-10 13:42:27 +00:00

Recently the CI was extended to provide 1.1.1.5 and 1111:1111::5 on the VMs it creates to facilitate such tests. See ci/test/02_run_container.py and test/functional/feature_bind_port_discover.py and test/functional/feature_bind_port_externalip.py for example tests. It would be better if we keep the instructions consistent among tests.

Recently the CI was extended to provide `1.1.1.5` and `1111:1111::5` on the VMs it creates to facilitate such tests. See `ci/test/02_run_container.py` and `test/functional/feature_bind_port_discover.py` and `test/functional/feature_bind_port_externalip.py` for example tests. It would be better if we keep the instructions consistent among tests.
vasild (Migrated from github.com) commented 2026-06-10 13:56:02 +00:00
        self.log.info(f"Checking that node 0 sees inbound from {ADDR2}")

(and below as well)

```suggestion self.log.info(f"Checking that node 0 sees inbound from {ADDR2}") ``` (and below as well)
DrahtBot commented 2026-07-14 23:49:02 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
sedited commented 2026-08-10 20:23:27 +00:00 (Migrated from github.com)

@8144225309 this needs a rebase and there have been unaddressed review comments for two months now. Are you still working on this?

@8144225309 this needs a rebase and there have been unaddressed review comments for two months now. Are you still working on this?
8144225309 commented 2026-08-11 23:49:43 +00:00 (Migrated from github.com)

Yes, rebasing now and addressing the review comments (LookupHost/CNetAddr storage, last-one-wins, CI-runnable functional test). Testing tonight; will push and update here once it's green.

Yes, rebasing now and addressing the review comments (LookupHost/CNetAddr storage, last-one-wins, CI-runnable functional test). Testing tonight; will push and update here once it's green.
8144225309 commented 2026-08-17 04:08:32 +00:00 (Migrated from github.com)

Rebased and addressed the review comments:

  • -outboundbind takes a bare address (LookupHost, a port is rejected), stored as one CNetAddr per family; the command line wins over the config file
  • the local-address special-casing is gone. 0.0.0.0/:: and Tor/I2P addresses are rejected at startup, each with its own error; the effective address per family is trial-bound at init, so a command-line value can override an unbindable config one, and -nooutboundbind clears an earlier setting
  • clearnet only: Tor and I2P use their own transport, CJDNS is direct but not IPv4/IPv6, and a proxy for a family leaves the option inert (a startup warning)
  • a connect-time bind failure aborts the connection, with no fallback to the default source
  • tests: functional (both families with a loopback destination so source differs from destination; command-line-over-config override; rejection of unassigned/port/wildcard/Tor) and unit (per-family selection and nothing for Tor/I2P/CJDNS, trial bind, bind-before-connect, and fail-closed)

Per-commit details in the commit messages.

Rebased and addressed the review comments: - `-outboundbind` takes a bare address (`LookupHost`, a port is rejected), stored as one `CNetAddr` per family; the command line wins over the config file - the local-address special-casing is gone. `0.0.0.0`/`::` and Tor/I2P addresses are rejected at startup, each with its own error; the effective address per family is trial-bound at init, so a command-line value can override an unbindable config one, and `-nooutboundbind` clears an earlier setting - clearnet only: Tor and I2P use their own transport, CJDNS is direct but not IPv4/IPv6, and a proxy for a family leaves the option inert (a startup warning) - a connect-time bind failure aborts the connection, with no fallback to the default source - tests: functional (both families with a loopback destination so source differs from destination; command-line-over-config override; rejection of unassigned/port/wildcard/Tor) and unit (per-family selection and nothing for Tor/I2P/CJDNS, trial bind, bind-before-connect, and fail-closed) Per-commit details in the commit messages.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:18:16 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:18:16 +00:00

Removed entirely. Addresses are used as given, then validated: parse, wildcard, and family checks, plus a trial bind() at init.

Removed entirely. Addresses are used as given, then validated: parse, wildcard, and family checks, plus a trial `bind()` at init.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:18:23 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:18:23 +00:00

Done. IsAddrBindable() does a trial bind() at init, so a misconfigured address fails startup. It has its own unit test.

Done. `IsAddrBindable()` does a trial `bind()` at init, so a misconfigured address fails startup. It has its own unit test.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:18:36 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:18:36 +00:00

Done. A unit test checks that ConnectDirectly() binds to the given source before connecting (recording mock socket via CreateSock), doesn't bind without one, and aborts on a failed bind.

Done. A unit test checks that `ConnectDirectly()` binds to the given source before connecting (recording mock socket via `CreateSock`), doesn't bind without one, and aborts on a failed bind.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:18:43 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:18:43 +00:00

Done. The help now says to give a bare address without a port (LookupHost() rejects a value with a port).

Done. The help now says to give a bare address without a port (`LookupHost()` rejects a value with a port).
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:18:49 +00:00
Lines 2242-2281
8144225309 (Migrated from github.com) commented 2026-08-17 04:18:49 +00:00

Done, switched to LookupHost() so a port is rejected at startup.

Done, switched to `LookupHost()` so a port is rejected at startup.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:19:03 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:19:03 +00:00

Done, and replaced the vector with one std::optional<CNetAddr> per family.

Done, and replaced the vector with one `std::optional<CNetAddr>` per family.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:19:09 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:19:09 +00:00

No longer. A value that doesn't resolve, includes a port, is the wildcard, or isn't IPv4/IPv6 (a Tor or I2P address) is rejected at startup with its own error, and the effective address is then trial-bound. Nothing is dropped silently.

No longer. A value that doesn't resolve, includes a port, is the wildcard, or isn't IPv4/IPv6 (a Tor or I2P address) is rejected at startup with its own error, and the effective address is then trial-bound. Nothing is dropped silently.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:19:16 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:19:16 +00:00

Removed the special-casing. 0.0.0.0/:: pins nothing, so it's rejected at startup with its own error ("is not a usable source address"). Use -nooutboundbind to clear an earlier setting. Loopback is allowed; it fails at connect time for non-local destinations like any unroutable source, and is fine for nodes that only reach local peers.

Removed the special-casing. `0.0.0.0`/`::` pins nothing, so it's rejected at startup with its own error ("is not a usable source address"). Use `-nooutboundbind` to clear an earlier setting. Loopback is allowed; it fails at connect time for non-local destinations like any unroutable source, and is fine for nodes that only reach local peers.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:19:31 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:19:31 +00:00

first-wins matches the config-file convention ("the first one is generally chosen", doc/bitcoin-conf.md; reverse_precedence in common/settings.cpp). Last-wins over GetArgs() would also invert command-line-over-config: an unbindable config address would then win over a valid command-line one and fail startup. Fully conventional resolution (last on the command line, first in the config) needs a per-source accessor ArgsManager doesn't have. Ok as-is, or want that added here?

first-wins matches the config-file convention ("the first one is generally chosen", doc/bitcoin-conf.md; reverse_precedence in common/settings.cpp). Last-wins over GetArgs() would also invert command-line-over-config: an unbindable config address would then win over a valid command-line one and fail startup. Fully conventional resolution (last on the command line, first in the config) needs a per-source accessor ArgsManager doesn't have. Ok as-is, or want that added here?
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:19:58 +00:00
Lines 1637-1645
8144225309 (Migrated from github.com) commented 2026-08-17 04:19:58 +00:00

That block checked a CNetAddr property rather than the option, so I replaced it with a direct test of the feature: SelectOutboundBind() selects no source for a CJDNS target (and likewise Tor and I2P), in outbound_bind_address_selection.

That block checked a `CNetAddr` property rather than the option, so I replaced it with a direct test of the feature: `SelectOutboundBind()` selects no source for a CJDNS target (and likewise Tor and I2P), in `outbound_bind_address_selection`.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:20:04 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:20:04 +00:00

Done. The test binds 1.1.1.5/1111:1111::5 as the outgoing sources to a loopback destination (so the observed source differs from it), and self-skips when they're absent.

Done. The test binds `1.1.1.5`/`1111:1111::5` as the outgoing sources to a loopback destination (so the observed source differs from it), and self-skips when they're absent.
8144225309 (Migrated from github.com) reviewed 2026-08-17 04:20:18 +00:00
8144225309 (Migrated from github.com) commented 2026-08-17 04:20:18 +00:00

Done (the test was rewritten).

Done (the test was rewritten).
8144225309 commented 2026-08-19 06:01:43 +00:00 (Migrated from github.com)

Rebased and fixed a few issues found while re-reviewing:

  • reject an fc00::/8 source as CJDNS when -cjdnsreachable is set, matching how the connect path classifies it
  • reject only the wildcard per value; other unusable values are left to the trial bind of the effective address, so a command line value can override a stale config one
  • don't count a failed local source bind as an addrman attempt against the peer, as proxy failures already don't
  • set IP_BIND_ADDRESS_NO_PORT on the source bind where available
  • name the destination in the connect-time bind failure log
  • tests: cover the new rejections and the per-family proxy warning, make the bind mock length-exact, tighten the skip condition
Rebased and fixed a few issues found while re-reviewing: - reject an fc00::/8 source as CJDNS when -cjdnsreachable is set, matching how the connect path classifies it - reject only the wildcard per value; other unusable values are left to the trial bind of the effective address, so a command line value can override a stale config one - don't count a failed local source bind as an addrman attempt against the peer, as proxy failures already don't - set IP_BIND_ADDRESS_NO_PORT on the source bind where available - name the destination in the connect-time bind failure log - tests: cover the new rejections and the per-family proxy warning, make the bind mock length-exact, tighten the skip condition
winterrdog (Migrated from github.com) reviewed 2026-09-12 16:16:23 +00:00
winterrdog (Migrated from github.com) left a comment

approach ACK

though, i might be TOO late for the name search party. i'd -exitbind in mind (inspired by TOR exit relays). will provide more review

approach ACK though, i might be TOO late for the name search party. i'd `-exitbind` in mind (inspired by TOR exit relays). will provide more review
First-time contributor

🟠 Minor · Broadcast and multicast outbound bind addresses do not pin the source address

On Linux, a misconfigured broadcast or multicast -outboundbind value can pass startup validation, after which direct connections use the OS-selected source address instead of failing closed.

Location: src/init.cpp:2214 (head).

🔵 Suggestion · Name-proxy connections can bypass -outboundbind without a startup warning

With an IPv4 bind and an IPv6-only proxy, or vice versa, hostname-based connections and DNS-seed fetches use the name proxy without a warning that the bind does not apply.

Location: src/init.cpp:2245 (head).

🔵 Suggestion · Assert bind-before-connect in the recording socket test

BindRecordingSock (net_tests.cpp:1756) overrides only Bind(), so ZeroSock::Connect() goes unobserved. The successful cases never assert that Bind happens before Connect, even though the test comment claims they do. Low impact: the functional test covers the end-to-end source.

Location: src/test/net_tests.cpp:1754 (head).

Review coverage was incomplete.


Reviewed: 5baa78a79cb0 · Full review report · Previous reports

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:6f232c871bca65facadc248ad7ecd634f87b0b5f6936bc30593af890589888f1:0cfbbc826fdd30e42f35c9a5b7d389c0902089c94f2400654bb32123e69823f6 --> <!-- ralph-base:6ed5aad06111177c39f9b9f07a52634476380ae1 --> <!-- ralph-head:5baa78a79cb0c2144b680360d3bb46d223546df3 --> <!-- ralph-case:a77741f07de01b9445134959f3c6a24f7541fe61d65850e8c454b3a2e27e76c5 --> **🟠 Minor · Broadcast and multicast outbound bind addresses do not pin the source address** On Linux, a misconfigured broadcast or multicast `-outboundbind` value can pass startup validation, after which direct connections use the OS-selected source address instead of failing closed. Location: [`src/init.cpp:2214`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5baa78a79cb0c2144b680360d3bb46d223546df3/src/init.cpp#L2214>) (head). **🔵 Suggestion · Name-proxy connections can bypass `-outboundbind` without a startup warning** With an IPv4 bind and an IPv6-only proxy, or vice versa, hostname-based connections and DNS-seed fetches use the name proxy without a warning that the bind does not apply. Location: [`src/init.cpp:2245`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5baa78a79cb0c2144b680360d3bb46d223546df3/src/init.cpp#L2245>) (head). **🔵 Suggestion · Assert bind-before-connect in the recording socket test** BindRecordingSock (net_tests.cpp:1756) overrides only Bind(), so ZeroSock::Connect() goes unobserved. The successful cases never assert that Bind happens before Connect, even though the test comment claims they do. Low impact: the functional test covers the end-to-end source. Location: [`src/test/net_tests.cpp:1754`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5baa78a79cb0c2144b680360d3bb46d223546df3/src/test/net_tests.cpp#L1754>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`5baa78a79cb0`](<https://git.fish.foo/bitcoin/bitcoin/commit/5baa78a79cb0c2144b680360d3bb46d223546df3>) · [Full review report](<https://review.fish.foo/traces/35027-5baa78a79cb0c2144b680360d3bb46d223546df3-1720-3.html>) · [Previous reports](<https://review.fish.foo/traces/35027/>)
winterrdog (Migrated from github.com) reviewed 2026-11-16 22:00:12 +00:00
winterrdog (Migrated from github.com) commented 2026-11-11 17:55:56 +00:00

i have a few thoughts on making the release note clearer.

"one per address family" might be a little broad. saying that one IPv4 and one IPv6 address can be configured independently makes it clearer what the option actually supports. similarly, "local source address" makes the distinction from the destination a bit clearer

there is also the -proxy interaction worth mentioning. when -proxy is configured for an address family, -outboundbind has no effect on that family, and a warning is logged at startup.

- A new `-outboundbind=<addr>` option binds outgoing clearnet connections to
  the given local source address. One IPv4 and one IPv6 address can be
  configured independently. The address must be assigned to a local
  interface. Connections over Tor, I2P and CJDNS are not affected. If
  `-proxy` is configured for an address family, `-outboundbind` has no
  effect on that family, and a warning is logged at startup. Existing
  `-bind` semantics are unchanged. (#35027)

what do you think ?

i have a few thoughts on making the release note clearer. `"one per address family"` might be a little broad. saying that one IPv4 and one IPv6 address can be configured independently makes it clearer what the option actually supports. similarly, "local _source_ address" makes the distinction from the destination a bit clearer there is also the `-proxy` interaction worth mentioning. when `-proxy` is configured for an address family, `-outboundbind` has no effect on that family, and a warning is logged at startup. ```suggestion - A new `-outboundbind=<addr>` option binds outgoing clearnet connections to the given local source address. One IPv4 and one IPv6 address can be configured independently. The address must be assigned to a local interface. Connections over Tor, I2P and CJDNS are not affected. If `-proxy` is configured for an address family, `-outboundbind` has no effect on that family, and a warning is logged at startup. Existing `-bind` semantics are unchanged. (#35027) ``` --- what do you think ?
Lines 2230-2240
winterrdog (Migrated from github.com) commented 2026-11-16 21:56:04 +00:00

i think we could avoid invalid clearnet source addresses completely 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

patch
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[in] dest The service to which to connect.
  * @param[in] manual_connection Whether or not the connection was manually requested (e.g. through the addnode RPC)
- * @param[in] bind_addr If set, bind to this local address before connecting. On
+ * @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[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 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).

what do you think ?

i think we could avoid invalid clearnet source addresses completely 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 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[in] dest The service to which to connect. * @param[in] manual_connection Whether or not the connection was manually requested (e.g. through the addnode RPC) - * @param[in] bind_addr If set, bind to this local address before connecting. On + * @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[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 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 ?
Lines 2244-2245
winterrdog (Migrated from github.com) commented 2026-11-11 18:11:55 +00:00

what happens when -outboundbind is combined with -onlynet? for instance, -onlynet=ipv4 with an IPv6 -outboundbind. users who pin their source address usually restrict networks too

the PR does not check reachable networks, so the address is trial-bound at startup but never used for automatic connections, and a user can never know about that. the proxy case already gets an InitWarning for the same reason i.e. the option is set but inert for that transport


could we add a similar warning when -outboundbind is set for a family excluded by -onlynet.. with a functional test covering the warning, if necessary ?

what happens when `-outboundbind` is combined with `-onlynet`? for instance, `-onlynet=ipv4` with an IPv6 `-outboundbind`. users who pin their source address _usually_ restrict networks too the PR does not check reachable networks, so the address is trial-bound at startup but never used for automatic connections, and a user can never know about that. the proxy case already gets an `InitWarning` for the same reason i.e. the option is set but inert for that transport --- could we add a similar warning when `-outboundbind` is set for a family excluded by `-onlynet`.. with a functional test covering the warning, if necessary ?
Lines 322-329
winterrdog (Migrated from github.com) commented 2026-11-11 21:30:00 +00:00

a design question on ConnectDirectly

it adds a bool* bind_failed out-param. the developer notes prefer returning values over output parameters:

  • Prefer returning values directly to using in-out or output parameters. Use
    std::optional where helpful for returning values.
  • Rationale: Less error-prone (no need for assumptions about what the output
    is initialized to on failure), easier to read, and often the same or better
    performance.

ConnectThroughProxy still uses the same pattern (proxyConnectionFailed), and the other ConnectDirectly callers (bitcoin-cli, torcontrol, and the proxy path) do not use outbound bind.


is adding another out-param here fine, given the existing pattern, or would returning the failure reason alongside the socket be preferable ?

not a blocker, just curious where you (& others) would draw the line

#### a design question on `ConnectDirectly` it adds a `bool* bind_failed` out-param. the developer notes [prefer returning values](https://raw.githubusercontent.com/bitcoin/bitcoin/refs/heads/master/doc/developer-notes.md#:~:text=%2D%20Prefer%20returning%20values,or%20better%0A%20%20performance.) over output parameters: > - Prefer returning values directly to using in-out or output parameters. Use > `std::optional` where helpful for returning values. > - *Rationale*: Less error-prone (no need for assumptions about what the output > is initialized to on failure), easier to read, and often the same or better > performance. `ConnectThroughProxy` still uses the same pattern (`proxyConnectionFailed`), and the other `ConnectDirectly` callers (`bitcoin-cli`, `torcontrol`, and the proxy path) do not use outbound bind. --- is adding another out-param here fine, given the existing pattern, or would returning the failure reason alongside the socket be preferable ? not a blocker, just curious where you (& others) would draw the line
Lines 1806-1811
winterrdog (Migrated from github.com) commented 2026-11-15 17:34:46 +00:00

SockRestore is duplicated across 2 test cases i.e. here and in is_addr_bindable. a shared fixture defines it once, so future CreateSock mocks reuse it instead of copy-pasting, and it still restores on a throwing BOOST_REQUIRE

patch
diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index 400f19a1f2..41488e4237 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -1749,7 +1749,16 @@ BOOST_AUTO_TEST_CASE(outbound_bind_address_selection)
     BOOST_CHECK(!connman->SelectOutboundBindPublic(cjdns));
 }
 
-BOOST_AUTO_TEST_CASE(outbound_bind_connect)
+namespace {
+// Restore CreateSock on any exit path, including a throwing BOOST_REQUIRE,
+// so a failure does not leak the mock into later tests.
+struct SockFixture : RegTestingSetup {
+    const decltype(CreateSock) orig{CreateSock};
+    ~SockFixture() { CreateSock = orig; }
+};
+} // namespace
+
+BOOST_FIXTURE_TEST_CASE(outbound_bind_connect, SockFixture)
 {
     // ConnectDirectly() must bind() the socket to the given source address
     // before connecting, and must not bind() when no address is given.
@@ -1798,13 +1807,6 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
         bool& m_connect_called;
     };
 
-    // Restore CreateSock on any exit path, including a throwing BOOST_REQUIRE,
-    // so a failure here does not leak the mock into later tests.
-    struct SockRestore {
-        const decltype(CreateSock) orig{CreateSock};
-        ~SockRestore() { CreateSock = orig; }
-    } sock_restore;
-
     std::optional<CService> bound;
     CreateSock = [&bound](int, int, int) { return std::make_unique<BindRecordingSock>(bound); };
 
@@ -1855,14 +1857,10 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
     BOOST_CHECK(bind_failed);
 }
 
-BOOST_AUTO_TEST_CASE(is_addr_bindable)
+BOOST_FIXTURE_TEST_CASE(is_addr_bindable, SockFixture)
 {
     // IsAddrBindable() trial-binds a fresh socket and reports the result.
     const CNetAddr addr{LookupHost("127.0.0.1", /*fAllowLookup=*/false).value()};
-    struct SockRestore {
-        const decltype(CreateSock) orig{CreateSock};
-        ~SockRestore() { CreateSock = orig; }
-    } sock_restore;
     bilingual_str error;
 
     // Bind() succeeds -> bindable, error left empty.
`SockRestore` is duplicated across 2 test cases i.e. here and in `is_addr_bindable`. a shared fixture defines it once, so future `CreateSock` mocks reuse it instead of copy-pasting, and it still restores on a throwing `BOOST_REQUIRE` <details><summary>patch</summary> ```diff diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp index 400f19a1f2..41488e4237 100644 --- a/src/test/net_tests.cpp +++ b/src/test/net_tests.cpp @@ -1749,7 +1749,16 @@ BOOST_AUTO_TEST_CASE(outbound_bind_address_selection) BOOST_CHECK(!connman->SelectOutboundBindPublic(cjdns)); } -BOOST_AUTO_TEST_CASE(outbound_bind_connect) +namespace { +// Restore CreateSock on any exit path, including a throwing BOOST_REQUIRE, +// so a failure does not leak the mock into later tests. +struct SockFixture : RegTestingSetup { + const decltype(CreateSock) orig{CreateSock}; + ~SockFixture() { CreateSock = orig; } +}; +} // namespace + +BOOST_FIXTURE_TEST_CASE(outbound_bind_connect, SockFixture) { // ConnectDirectly() must bind() the socket to the given source address // before connecting, and must not bind() when no address is given. @@ -1798,13 +1807,6 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect) bool& m_connect_called; }; - // Restore CreateSock on any exit path, including a throwing BOOST_REQUIRE, - // so a failure here does not leak the mock into later tests. - struct SockRestore { - const decltype(CreateSock) orig{CreateSock}; - ~SockRestore() { CreateSock = orig; } - } sock_restore; - std::optional<CService> bound; CreateSock = [&bound](int, int, int) { return std::make_unique<BindRecordingSock>(bound); }; @@ -1855,14 +1857,10 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect) BOOST_CHECK(bind_failed); } -BOOST_AUTO_TEST_CASE(is_addr_bindable) +BOOST_FIXTURE_TEST_CASE(is_addr_bindable, SockFixture) { // IsAddrBindable() trial-binds a fresh socket and reports the result. const CNetAddr addr{LookupHost("127.0.0.1", /*fAllowLookup=*/false).value()}; - struct SockRestore { - const decltype(CreateSock) orig{CreateSock}; - ~SockRestore() { CreateSock = orig; } - } sock_restore; bilingual_str error; // Bind() succeeds -> bindable, error left empty. ``` </details>
winterrdog (Migrated from github.com) commented 2026-11-11 21:38:59 +00:00

small suggestion: could the PR description mention that feature_bind_outgoing.py needs 1.1.1.5 and 1111:1111::5 assigned to a non-loopback interface (CI sets them already), and that it skips otherwise ?

the setup commands are in the test file's header, but reviewers running it locally would likely look at the description first 🙂


i think other reviewers might find this helpful when testing locally. for running feature_bind_outgoing.py locally without touching a real interface, you can use a dummy device:

for linux
# create a dummy device and assign test IPs
sudo ip link add btc0 type dummy && sudo ip link set btc0 up
sudo ip addr add 1.1.1.5/32 dev btc0 && sudo ip addr add 1111:1111::5/128 dev btc0

# remove the dummy device/interface afterwards. drops the addresses with it
sudo ip link del btc0
for freeBSD & netBSD
# switched to root first
su -

# create dummy device and assign test IPs
ifconfig lo1 create && ifconfig lo1 up
ifconfig lo1 inet 1.1.1.5/32 alias && ifconfig lo1 inet6 1111:1111::5/128 alias

# ctrl+D to leave root and run the functional test (feature_bind_outgoing.py)

# remove device when done (remember to switch back to root before doing this)
sudo ifconfig lo1 destroy
**small suggestion**: could the PR description mention that `feature_bind_outgoing.py` needs `1.1.1.5` and `1111:1111::5` assigned to a non-loopback interface (CI sets them already), and that it skips otherwise ? the setup commands are in the test file's header, but reviewers running it locally would likely look at the description first 🙂 --- i think other reviewers might find this helpful when testing locally. for running `feature_bind_outgoing.py` locally without touching a real interface, you can use a dummy device: <details><summary>for linux</summary> ```sh # create a dummy device and assign test IPs sudo ip link add btc0 type dummy && sudo ip link set btc0 up sudo ip addr add 1.1.1.5/32 dev btc0 && sudo ip addr add 1111:1111::5/128 dev btc0 # remove the dummy device/interface afterwards. drops the addresses with it sudo ip link del btc0 ``` </details> <details><summary>for freeBSD & netBSD</summary> ```sh # switched to root first su - # create dummy device and assign test IPs ifconfig lo1 create && ifconfig lo1 up ifconfig lo1 inet 1.1.1.5/32 alias && ifconfig lo1 inet6 1111:1111::5/128 alias # ctrl+D to leave root and run the functional test (feature_bind_outgoing.py) # remove device when done (remember to switch back to root before doing this) sudo ifconfig lo1 destroy ``` </details>
winterrdog (Migrated from github.com) commented 2026-11-11 12:24:59 +00:00

-nooutboundbind is documented in both the help text and commit message but it is not tested

could we add a functional test with outboundbind=<addr> in the config file and -nooutboundbind on the command line, asserting that the outgoing source is no longer the address in the configuration file ?

patch
diff --git a/test/functional/feature_bind_outgoing.py b/test/functional/feature_bind_outgoing.py
index f4a8d502aa..fb8b166fc5 100755
--- a/test/functional/feature_bind_outgoing.py
+++ b/test/functional/feature_bind_outgoing.py
@@ -164,6 +164,11 @@ class BindOutgoingTest(BitcoinTestFramework):
         self.restart_node(1, [f'-outboundbind={ADDR4}'])
         self.check_source(f'127.0.0.1:{self.port4}', ADDR4)
 
+        self.log.info('Check that -nooutboundbind discards a config-file -outboundbind')
+        self.restart_node(1, ['-nooutboundbind'])
+        self.check_source(f'127.0.0.1:{self.port4}', '127.0.0.1')
+        self.check_source(f'[::1]:{self.port6}', '::1')
+
         self.log.info('Check that a configured proxy makes -outboundbind inert, '
                       'with a startup warning')
         self.stop_node(1)
`-nooutboundbind` is documented in both the help text and commit message but it is not tested could we add a functional test with `outboundbind=<addr>` in the config file and `-nooutboundbind` on the command line, asserting that the outgoing source is no longer the address in the configuration file ? <details><summary>patch</summary> ```diff diff --git a/test/functional/feature_bind_outgoing.py b/test/functional/feature_bind_outgoing.py index f4a8d502aa..fb8b166fc5 100755 --- a/test/functional/feature_bind_outgoing.py +++ b/test/functional/feature_bind_outgoing.py @@ -164,6 +164,11 @@ class BindOutgoingTest(BitcoinTestFramework): self.restart_node(1, [f'-outboundbind={ADDR4}']) self.check_source(f'127.0.0.1:{self.port4}', ADDR4) + self.log.info('Check that -nooutboundbind discards a config-file -outboundbind') + self.restart_node(1, ['-nooutboundbind']) + self.check_source(f'127.0.0.1:{self.port4}', '127.0.0.1') + self.check_source(f'[::1]:{self.port6}', '::1') + self.log.info('Check that a configured proxy makes -outboundbind inert, ' 'with a startup warning') self.stop_node(1) ``` </details>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35027
No description provided.