mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 16:05:36 +00:00
net: add -outboundbind option for outgoing source address #35027
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35027
Loading…
Reference in a new issue
No description provided.
Delete branch "net-bind-outgoing"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Closes #6476
Adds
-outboundbind=<addr>to set the source address of outgoing clearnetconnections, one per address family. It is separate from
-bind; without it,outbound follows the OS routing table as before.
IPv4/IPv6, and a proxy leaves the option inert for that family (with a
startup warning).
-bindviaBindListenPort; a port, the wildcard, or a non-clearnet value is rejected. Afailed 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.
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.
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:
clang-tidyoptin.performance.Paddingby fanquake)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.
This might break a scenario where someone wants to listen on one IP, but load balance outgoing connections. A new option might be better?
The original issue asks for
-bindto 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-bindto cover both directions.concept ACK.
Left some inline comments
IsLocal()also matches0.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?The listen path validates the address early through
BindListenPortand 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 trialbind()or similar check here so a misconfigured address fails loudly at init rather than silently killing outbound for that family.I believe it would it be great to add a unit test that calls
ConnectDirectlywith a bind address, even if just to verify the syscall is attempted. Right now the unit test covers Init-time storage but thisBind()path has no automated coverage.The test verifies that the first IPv4 address is stored, but doesn't check that
m_outbound_bind_v6stays empty. If theelse ifcondition were weakened, an IPv4 address could leak into the IPv6 slot undetected. You can avoid this by includingBOOST_CHECK(!connman->GetOutboundBindV6());around here.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.
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
-bindusers to revisit their configs.I'd lean towards
-bindoutgoingfor clarity and alphabetic proximity to-bindin docs/tab-completion. That said,-outboundbind(or-obind) is arguably the better fit given the existing-whitebind/-rpcbindconvention. Any preference?Force-pushed a redesign based on the feedback above:
-outboundbind=<addr>as a separate option instead of extending-bind-bindsemantics unchanged, so existing setups (including LAN/bridge peers) are unaffected-whitebind/-rpcbind; happy to rename if preferred🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/26346661562/job/77584098255LLM reason (✨ experimental): C++ build failed due to
clang++errors insrc/netbase.cpp(use of undeclared identifierbind_addr, causing furtherCServiceconstructor/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.
Concept ACK
I agree that it is better to not change the semantic of the existent
-bindand introduce a new option instead with a default value "leave it to the OS" which is the same as of before this PR.Rebased after conflict with #35410: the outbound bind selection in
ConnectNodenow sits inside the new private-broadcast guard. Also fixed an include-order nit and clarified wording in anet.hcomment and the test commit message.Approach ACK fa19b8c43489ffcc7693317af3c754992078e536
The number at the end should be the PR that contains the change:
Better use "address" as "host" could be mistaken for a hostname.
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 twostd::optional<CNetAddr>members, then just copy them fromconnOptionsinto theCConnmanmembers.Usually the notion is that the last one wins. E.g.
-outboundbind=1.2.3.4 -outboundbind=5.6.7.8--5.6.7.8should be used. This helps override earlier settings which might be out of one's control.I didn't test, but I guess this will allow ports to be included, e.g.
-outboundbind=1.2.4.5:5678which better not be allowed to avoid confusion.LookupHost()can be used to parse just an address.In new code use
snake_case.and also
s/CService/CNetAddr/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.
Or even, why treat such addresses specially? It might be desirable to use
-outboundbind=0.0.0.0to remove the effect of a preceding-outboundbind=....Here and everywhere the trailing
\nin the message is not needed anymore and is frowned upon. Drop it.If you want to have
struct, that is fine. Just to mention that C++ can do without it:The port here is irrelevant. These should all be
CNetAddr.Instead of hardcoding the string address again
"203.0.113.1"better useaddr1.ToStringAddr()(here and elsewhere).This is not testing the new feature. Better drop it.
Recently the CI was extended to provide
1.1.1.5and1111:1111::5on the VMs it creates to facilitate such tests. Seeci/test/02_run_container.pyandtest/functional/feature_bind_port_discover.pyandtest/functional/feature_bind_port_externalip.pyfor example tests. It would be better if we keep the instructions consistent among tests.(and below as well)
🐙 This pull request conflicts with the target branch and needs rebase.
@8144225309 this needs a rebase and there have been unaddressed review comments for two months now. Are you still working on this?
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.
Rebased and addressed the review comments:
-outboundbindtakes a bare address (LookupHost, a port is rejected), stored as oneCNetAddrper family; the command line wins over the config file0.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-nooutboundbindclears an earlier settingPer-commit details in the commit messages.
Removed entirely. Addresses are used as given, then validated: parse, wildcard, and family checks, plus a trial
bind()at init.Done.
IsAddrBindable()does a trialbind()at init, so a misconfigured address fails startup. It has its own unit test.Done. A unit test checks that
ConnectDirectly()binds to the given source before connecting (recording mock socket viaCreateSock), doesn't bind without one, and aborts on a failed bind.Done. The help now says to give a bare address without a port (
LookupHost()rejects a value with a port).Done, switched to
LookupHost()so a port is rejected at startup.Done, and replaced the vector with one
std::optional<CNetAddr>per family.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.
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-nooutboundbindto 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.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?
That block checked a
CNetAddrproperty 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), inoutbound_bind_address_selection.Done. The test binds
1.1.1.5/1111:1111::5as the outgoing sources to a loopback destination (so the observed source differs from it), and self-skips when they're absent.Done (the test was rewritten).
Rebased and fixed a few issues found while re-reviewing:
approach ACK
though, i might be TOO late for the name search party. i'd
-exitbindin mind (inspired by TOR exit relays). will provide more review🟠 Minor · Broadcast and multicast outbound bind addresses do not pin the source address
On Linux, a misconfigured broadcast or multicast
-outboundbindvalue 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
-outboundbindwithout a startup warningWith 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 reportsi 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 clearerthere is also the
-proxyinteraction worth mentioning. when-proxyis configured for an address family,-outboundbindhas no effect on that family, and a warning is logged at startup.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
patch
what do you think ?
what happens when
-outboundbindis combined with-onlynet? for instance,-onlynet=ipv4with an IPv6-outboundbind. users who pin their source address usually restrict networks toothe 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
InitWarningfor the same reason i.e. the option is set but inert for that transportcould we add a similar warning when
-outboundbindis set for a family excluded by-onlynet.. with a functional test covering the warning, if necessary ?a design question on
ConnectDirectlyit adds a
bool* bind_failedout-param. the developer notes prefer returning values over output parameters:ConnectThroughProxystill uses the same pattern (proxyConnectionFailed), and the otherConnectDirectlycallers (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
SockRestoreis duplicated across 2 test cases i.e. here and inis_addr_bindable. a shared fixture defines it once, so futureCreateSockmocks reuse it instead of copy-pasting, and it still restores on a throwingBOOST_REQUIREpatch
small suggestion: could the PR description mention that
feature_bind_outgoing.pyneeds1.1.1.5and1111:1111::5assigned 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.pylocally without touching a real interface, you can use a dummy device:for linux
for freeBSD & netBSD
-nooutboundbindis documented in both the help text and commit message but it is not testedcould we add a functional test with
outboundbind=<addr>in the config file and-nooutboundbindon the command line, asserting that the outgoing source is no longer the address in the configuration file ?patch