http: Restore requirement of IPv4 bind success #36187

Open
hodlinator wants to merge 6 commits from 2026/09/req_all_binds into master AGit
hodlinator commented 2026-09-07 19:51:07 +00:00 (Migrated from github.com)

Problem

When bitcoind starts and the HTTP IPv4 listen address is occupied by another process, but the IPv6 address is available, the server fails open and generates a cookie file. When bitcoin-cli runs it picks up the cookie file and sends the credentials in plain text to the non-bitcoind process running on the default IPv4 port. An attacker can then use the credentials to commandeer bitcoind over IPv6.

Solution

Safe defaults:

  • When running with default settings, require that the IPv4 bind succeeds.
  • When -rpcbind is specified, require that all HTTP listen socket binds succeed (fail closed-behavior).

Node operators who only have IPv6 are now required to override -rpcbind and -rpcallowip to only specify the working interface and allowed subnet if they were not doing so already.

The problem of bitcoin-cli sending the credentials to what could possibly be the wrong process remains only in non-default setups.

History

40b556d374 from 2015 switched the HTTP server from Boost Asio to LibEvent, and binding switched from an attempt at dual-binding IPv4+v6 and falling back to IPv4-only (rpcserver.cpp / StartRPCThreads()), to binding IPv4 or IPv6 (httpserver.cpp / HTTPBindAddresses()). The current PR restores the prior behavior of IPv4 being mandatory.

#14968 from 2018 was an attempt to change the behavior to require all binds to succeed. But it ran into issues with poor IPv6 support on CI.

Severity

This credential exfiltration attack requires capability to launch processes on the bitcoind host. If we are on the same account we can already read the cookie credentials off disk. So it's only really interesting when an attacker is on a different user account on the same host.

### Problem When bitcoind starts and the HTTP IPv4 listen address is occupied by another process, but the IPv6 address is available, the server fails open and generates a cookie file. When bitcoin-cli runs it picks up the cookie file and sends the credentials in plain text to the non-bitcoind process running on the default IPv4 port. An attacker can then use the credentials to commandeer bitcoind over IPv6. ### Solution *Safe defaults*: * When running with default settings, require that the IPv4 bind succeeds. * When `-rpcbind` is specified, require that all HTTP listen socket binds succeed (fail closed-behavior). Node operators who only have IPv6 are now required to override `-rpcbind` and `-rpcallowip` to only specify the working interface and allowed subnet if they were not doing so already. The problem of bitcoin-cli sending the credentials to what could possibly be the wrong process remains **only in non-default setups**. ### History 40b556d3742a1f65d67e2d4c760d0b13fe8be5b7 from 2015 switched the HTTP server from Boost Asio to LibEvent, and binding switched from an attempt at dual-binding IPv4+v6 and falling back to IPv4-only (rpcserver.cpp / `StartRPCThreads()`), to binding IPv4 *or* IPv6 (httpserver.cpp / `HTTPBindAddresses()`). **The current PR restores the prior behavior of IPv4 being mandatory.** #14968 from 2018 was an attempt to change the behavior to require *all* binds to succeed. But it ran into issues with poor IPv6 support on CI. ### Severity This credential exfiltration attack requires capability to launch processes on the bitcoind host. If we are on the same account we can already read the cookie credentials off disk. So it's only really interesting when an attacker is on a different user account on the same host.
DrahtBot commented 2026-09-07 19:51:15 +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
ACK l0rinc, janb84
Concept ACK sedited
Stale ACK 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:

  • #37019 (http: free idle connection slots for waiting connections at the limit by optout21)
  • #36434 (http: support unix sockets by pinheadmz)
  • #36204 (http: disconnect clients that never finish a request by janb84)
  • #35355 (Use atomics for determining whether trace logging is enabled by ajtowns)
  • #34520 (refactor: Add nodiscard to functions returning bool+mutable ref by maflcko)

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/36187 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36187.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36187#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 | | ---- | --------- | | ACK | [l0rinc](https://github.com/bitcoin/bitcoin/pull/36187#issuecomment-6900419308), [janb84](https://github.com/bitcoin/bitcoin/pull/36187#pullrequestreview-5958340408) | | Concept ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/36187#issuecomment-5604417877) | | Stale ACK | [winterrdog](https://github.com/bitcoin/bitcoin/pull/36187#pullrequestreview-5831818070) | 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: * [#37019](https://github.com/bitcoin/bitcoin/pull/37019) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/37019.svg"></sub> (http: free idle connection slots for waiting connections at the limit by optout21) * [#36434](https://github.com/bitcoin/bitcoin/pull/36434) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36434.svg"></sub> (http: support unix sockets by pinheadmz) * [#36204](https://github.com/bitcoin/bitcoin/pull/36204) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36204.svg"></sub> (http: disconnect clients that never finish a request by janb84) * [#35355](https://github.com/bitcoin/bitcoin/pull/35355) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35355.svg"></sub> (Use atomics for determining whether trace logging is enabled by ajtowns) * [#34520](https://github.com/bitcoin/bitcoin/pull/34520) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34520.svg"></sub> (refactor: Add [[nodiscard]] to functions returning bool+mutable ref by maflcko) 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-->
l0rinc commented 2026-09-07 19:55:37 +00:00 (Migrated from github.com)

Concept ACK, thanks for pushing the fix

Concept ACK, thanks for pushing the fix
hodlinator commented 2026-09-07 20:07:23 +00:00 (Migrated from github.com)

For some reason thought that we weren't enabling the HTTP subsystem by default. Going to re-work the code slightly. Put in draft.

For some reason thought that we weren't enabling the HTTP subsystem by default. Going to re-work the code slightly. Put in draft.
janb84 (Migrated from github.com) reviewed 2026-09-08 10:27:34 +00:00
janb84 (Migrated from github.com) left a comment

Concept ACK 64fd5cef0c938d3d1e7f69d6be2f255b6eafc1e2

Looks good, some suggestion NITS.

NITl Commit message of c309e5fb73 has a typo / grammar issue "and without this change that one would Mac CI would fail with:"

Concept ACK 64fd5cef0c938d3d1e7f69d6be2f255b6eafc1e2 Looks good, some suggestion NITS. NITl Commit message of c309e5fb73 has a typo / grammar issue "and without this change that one would Mac CI would fail with:"
janb84 (Migrated from github.com) commented 2026-09-08 09:48:41 +00:00

NIT: I would keep the style of the 2 lines the same (helps the OCD people)

        endpoints.push_back({.address = "127.0.0.1", .port = http_port});
NIT: I would keep the style of the 2 lines the same (helps the OCD people) ```suggestion endpoints.push_back({.address = "127.0.0.1", .port = http_port}); ```
Lines 1366-1369
janb84 (Migrated from github.com) commented 2026-09-08 10:25:13 +00:00

non blocking, micro nit: Currently even the required entry/bindings failure only logs as a LogWarning. Is that the correct level for something that aborts startup ?

if (required) {
    LogError("Binding required RPC endpoint %s failed: %s", addr->ToStringAddrPort(), result.error());
    required_failure = true;
} else {
    LogWarning("Binding optional RPC endpoint %s failed: %s", addr->ToStringAddrPort(), result.error());
}
non blocking, micro nit: Currently even the required entry/bindings failure only logs as a LogWarning. Is that the correct level for something that aborts startup ? ```suggestion if (required) { LogError("Binding required RPC endpoint %s failed: %s", addr->ToStringAddrPort(), result.error()); required_failure = true; } else { LogWarning("Binding optional RPC endpoint %s failed: %s", addr->ToStringAddrPort(), result.error()); } ```
janb84 (Migrated from github.com) commented 2026-09-08 09:18:26 +00:00

NIT: Leftover assert on started, Line 121 asserts that started is false so started cannot be true at this point.

        assert 'Unable to start HTTP server' in error
NIT: Leftover assert on started, Line 121 asserts that started is false so started cannot be true at this point. ```suggestion assert 'Unable to start HTTP server' in error ```
hodlinator (Migrated from github.com) reviewed 2026-09-08 20:08:30 +00:00
hodlinator (Migrated from github.com) left a comment
Latest push addresses all but 1 comment from https://github.com/bitcoin/bitcoin/pull/36187#pullrequestreview-5139772278
hodlinator (Migrated from github.com) commented 2026-09-08 19:19:21 +00:00

Will do if others agree, holding off for now.

Will do if others agree, holding off for now.
sedited commented 2026-09-09 15:28:53 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
winterrdog (Migrated from github.com) reviewed 2026-09-10 22:40:36 +00:00
winterrdog (Migrated from github.com) left a comment

concept ACK

concept ACK
winterrdog (Migrated from github.com) commented 2026-09-10 22:39:15 +00:00

one of the "others" has arrived 😁


anyway, i agree with @janb84

when i first looked at the code, i thought there might be a subtle
reason for using one over the other, but later on i realised they do
the same thing. so i think sticking to the same pattern makes sense.
whether you use emplace_back() or push_back() is up to you, as long
as there is some symmetry

one of the _"others"_ has arrived 😁 --- anyway, i agree with @janb84 when i first looked at the code, i thought there might be a subtle reason for using one over the other, but later on i realised they do the same thing. so i think sticking to the same pattern makes sense. whether you use `emplace_back()` or `push_back()` is up to you, as long as there is some symmetry
winterrdog (Migrated from github.com) commented 2026-09-10 22:23:25 +00:00

from the PR description:

Node runners who only have IPv6 are now required to override -rpcbind to only specify the working interface if they were not doing so already.

can we make the IPv6-only case a bit more actionable in the error message ?

with the new defaults, an IPv6-only host will fail because the required 127.0.0.1 bind will never succeed, but the user may not know that they need to override -rpcbind to use only their IPv6 address. mayhaps the error could point them towards -rpcbind rather than just reporting that a required endpoint failed

i was thinking of sth like (feel free to put a spin to it):

        LogError("Unable to bind all required endpoints for RPC server. If this host does not support IPv4, specify the IPv6 RPC address with -rpcbind.");
from the PR description: > Node runners who only have IPv6 are now required to override `-rpcbind` to only specify the working interface if they were not doing so already. can we make the IPv6-only case a bit more actionable in the error message ? with the new defaults, an IPv6-only host will fail because the required `127.0.0.1` bind will never succeed, but the user may not know that they need to override `-rpcbind` to use only their IPv6 address. mayhaps the error could point them towards `-rpcbind` rather than just reporting that a required endpoint failed i was thinking of sth like (_feel free to put a spin to it_): ```suggestion LogError("Unable to bind all required endpoints for RPC server. If this host does not support IPv4, specify the IPv6 RPC address with -rpcbind."); ```
hodlinator (Migrated from github.com) reviewed 2026-09-11 11:13:45 +00:00
hodlinator (Migrated from github.com) left a comment
Latest push avoids stringly typing `endpoints_seen` and addresses points from https://github.com/bitcoin/bitcoin/pull/36187#pullrequestreview-5172841125.
hodlinator (Migrated from github.com) commented 2026-09-11 11:10:16 +00:00

Good point. Default behavior for IPv6-only hosts should at least be to get an informative error message.

Good point. Default behavior for IPv6-only hosts should at least be to get an informative error message.
hodlinator commented 2026-09-21 09:40:17 +00:00 (Migrated from github.com)

Updated PR description, primarily the History-section.

Updated PR description, primarily the History-section.
First-time contributor

Earlier concerns remain unresolved; see the Run archive linked from the Review report.

🔵 Suggestion · RPC bind startup changes lack upgrade guidance

Configurations that previously started with partial RPC bind success can now fail initialization, but the PR adds no release note and the help text does not explain the new requirements.

Location: src/httpserver.cpp:1387 (head).

🔵 Suggestion · IPv6 bind failure policies lack regression coverage

Both new failure cases occupy only IPv4, so they do not distinguish optional default IPv6 from required explicit IPv6.

Location: test/functional/rpc_bind.py:63 (head).

🔵 Suggestion · IPv4-only runs skip the default occupied-port check

The new default occupied-IPv4 case runs only through the IPv6-gated branch, leaving IPv4-only hosts without this regression check.

Location: test/functional/rpc_bind.py:175 (head).

Review coverage was incomplete.


Reviewed: 061eb6f43458 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:6a916fa059320c1e3f0a79c4f7490636461ad967153b8442c21450419af74010:24633968ff336fb935794e53e586f29b4eaaa2a15575a2c0392a2c8b9ace382c --> <!-- ralph-base:a527a0077a0fcae913188410214efe98021c0cca --> <!-- ralph-head:061eb6f43458d15bb12330b0667240a3a7d6e4da --> <!-- ralph-case:1735274781f83eaab8c26fbabbd60f96b35dac6e3828dd24fbd2c943eb6f4f8d --> Earlier concerns remain unresolved; see the Run archive linked from the Review report. **🔵 Suggestion · RPC bind startup changes lack upgrade guidance** Configurations that previously started with partial RPC bind success can now fail initialization, but the PR adds no release note and the help text does not explain the new requirements. Location: [`src/httpserver.cpp:1387`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/061eb6f43458d15bb12330b0667240a3a7d6e4da/src/httpserver.cpp#L1387>) (head). **🔵 Suggestion · IPv6 bind failure policies lack regression coverage** Both new failure cases occupy only IPv4, so they do not distinguish optional default IPv6 from required explicit IPv6. Location: [`test/functional/rpc_bind.py:63`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/061eb6f43458d15bb12330b0667240a3a7d6e4da/test/functional/rpc_bind.py#L63>) (head). **🔵 Suggestion · IPv4-only runs skip the default occupied-port check** The new default occupied-IPv4 case runs only through the IPv6-gated branch, leaving IPv4-only hosts without this regression check. Location: [`test/functional/rpc_bind.py:175`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/061eb6f43458d15bb12330b0667240a3a7d6e4da/test/functional/rpc_bind.py#L175>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`061eb6f43458`](<https://git.fish.foo/bitcoin/bitcoin/commit/061eb6f43458d15bb12330b0667240a3a7d6e4da>) · [Review report](<https://review.fish.foo/report/36187-061eb6f43458d15bb12330b0667240a3a7d6e4da-2674-5.html>) · [Previous reports](<https://review.fish.foo/traces/36187/>) [permalink](<https://review.fish.foo/report/36187-061eb6f43458d15bb12330b0667240a3a7d6e4da-2674-5.html>)
janb84 (Migrated from github.com) reviewed 2026-11-05 14:47:31 +00:00
janb84 (Migrated from github.com) left a comment

ACK 05de7be9d7

This PR will solve the problem stated in the PR description. Some observations/ NITS:

"Node runners who only have IPv6 are now required to override -rpcbind to only specify the working interface if they were not doing so already."

Isn't it more correct to say that: "Node runners who only have IPv6 are now required to override -rpcbind and -rpcallowip to only specify the working interface if they were not doing so already." Without -rpcallowip=::1 it will still fail.

The code will solve a ipv4 squatter situation, but not the case when there is a ipv6 sqatter and localhost is used for bitcoin-cli , 'bitcoin-cli -rpcconnect=localhost` tries [::1] before 127.0.0.1 . Not a blocker because 127.0.0.1 is explicitly used but just an observation.

Found a non-blocking NIT in the code, see below.

ACK 05de7be9d745df64b04fbedc08abd2fd5159b837 This PR will solve the problem stated in the PR description. Some observations/ NITS: "Node runners who only have IPv6 are now required to override -rpcbind to only specify the working interface if they were not doing so already." Isn't it more correct to say that: "Node runners who only have IPv6 are now required to override -rpcbind and -rpcallowip to only specify the working interface if they were not doing so already." Without -rpcallowip=::1 it will still fail. The code will solve a ipv4 squatter situation, but not the case when there is a ipv6 sqatter and `localhost` is used for bitcoin-cli , 'bitcoin-cli -rpcconnect=localhost` tries [::1] before 127.0.0.1 . Not a blocker because 127.0.0.1 is explicitly used but just an observation. Found a non-blocking NIT in the code, see below.
Lines 213-217
janb84 (Migrated from github.com) commented 2026-11-05 14:23:31 +00:00

NIT: current BindAddress keeps the address as a string, and InitHTTPServer parses it later with Lookup. This "late" lookup has the consequence that an invalid -rpcbind value is only detected inside the bind loop. Resulting that possible earlier endpoints may already be listening, and StopListening() has to undo them.

I think we can do this lookup (with fAllowLookup=false) sooner, as pure numeric parse without DNS (So it is safe to call it in GetBindAddresses) and store it typed. This is the same way the lookup is done in the bind loop.
This has the benefit that any invalid -rpcbind address fails before any socket is opened, equal to the port logic. And, to me, failing fast without the "risk" of opening sockets, is the better security posture.

patch
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 10f1cb85f8..6b21120c29 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -207,8 +207,7 @@ static void RejectRequest(std::unique_ptr<HTTPRequest> hreq)
 }
 
 struct BindAddress {
-    std::string address;
-    uint16_t port;
+    CService addr;
     bool required{true};
 };
 
@@ -232,8 +231,10 @@ static std::vector<BindAddress> GetBindAddresses()
         // We allow the default IPv6 bind to fail, but IPv4 is required even
         // with the default port as bitcoin-cli will default to handing RPC
         // credentials in plaintext to whatever process is running on that port.
-        endpoints.push_back({.address = "::1",       .port = http_port, .required = false});
-        endpoints.push_back({.address = "127.0.0.1", .port = http_port, .required = true});
+        // Numeric literals always parse, InitHTTPAllowList relies on the same.
+        // Never fall back to CService{}, which is [::]:0 and binds every interface.
+        endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value(),       .required = false});
+        endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value(), .required = true});
         if (!gArgs.GetArgs("-rpcallowip").empty()) {
             LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
         }
@@ -248,7 +249,14 @@ static std::vector<BindAddress> GetBindAddresses()
                 LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
                 return {}; // empty
             }
-            endpoints.emplace_back(host, port);
+            // Don't allow hostname lookups when binding to local interfaces.
+            const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)};
+            if (!addr) {
+                LogError("Could not bind RPC on address \"%s\" port %i: Address lookup failed "
+                         "(only numeric addresses are allowed).", host, port);
+                return {}; // empty
+            }
+            endpoints.push_back({.addr = *addr, .required = true});
         }
     }
     return endpoints;
@@ -1361,32 +1369,22 @@ bool InitHTTPServer()
             LogWarning("%s", msg);
         }
     };
-    for (const auto& [address_string, port, required] : endpoints) {
-        // Don't allow hostname lookups when binding to local interfaces. This
-        // means numeric collisions on available interfaces detected by endpoints_seen
-        // are probably just repeated instances - skip without logging why.
-        const std::optional<CService> addr{Lookup(address_string, port, /*fAllowLookup=*/false)};
-        if (addr) {
-            if (!endpoints_seen.insert(*addr).second) continue;
-            LogInfo("Binding RPC on address %s port %i", address_string, port);
-            if (addr->IsBindAny()) {
-                LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
-            }
-            auto result{g_http_server->BindAndStartListening(addr.value())};
-            if (!result) {
-                on_failure(required,
-                           strprintf("Binding RPC on %s address %s failed: %s",
-                                     required ? "required" : "optional",
-                                     addr->ToStringAddrPort(), result.error()));
-            } else {
-                bind_success = true;
-            }
-        } else {
+    for (const auto& [addr, required] : endpoints) {
+        // Addresses are numeric, so collisions detected by endpoints_seen are
+        // probably just repeated instances - skip without logging why.
+        if (!endpoints_seen.insert(addr).second) continue;
+        LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
+        if (addr.IsBindAny()) {
+            LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
+        }
+        auto result{g_http_server->BindAndStartListening(addr)};
+        if (!result) {
             on_failure(required,
-                       strprintf("Could not bind RPC on %s address \"%s\" port %i: Address lookup failed "
-                                 "(only numeric addresses are allowed).",
+                       strprintf("Binding RPC on %s address %s failed: %s",
                                  required ? "required" : "optional",
-                                 address_string, port));
+                                 addr.ToStringAddrPort(), result.error()));
+        } else {
+            bind_success = true;
         }
     }
 

NIT: current `BindAddress` keeps the address as a string, and `InitHTTPServer` parses it later with Lookup. This "late" lookup has the consequence that an invalid `-rpcbind` value is only detected inside the bind loop. Resulting that possible earlier endpoints may already be listening, and `StopListening()` has to undo them. I think we can do this lookup (with fAllowLookup=false) sooner, as pure numeric parse without DNS (So it is safe to call it in `GetBindAddresses`) and store it typed. This is the same way the lookup is done in the bind loop. This has the benefit that any invalid -rpcbind address fails before any socket is opened, equal to the `port` logic. And, to me, failing fast without the "risk" of opening sockets, is the better security posture. <details> <summary>patch</summary> ```patch diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 10f1cb85f8..6b21120c29 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -207,8 +207,7 @@ static void RejectRequest(std::unique_ptr<HTTPRequest> hreq) } struct BindAddress { - std::string address; - uint16_t port; + CService addr; bool required{true}; }; @@ -232,8 +231,10 @@ static std::vector<BindAddress> GetBindAddresses() // We allow the default IPv6 bind to fail, but IPv4 is required even // with the default port as bitcoin-cli will default to handing RPC // credentials in plaintext to whatever process is running on that port. - endpoints.push_back({.address = "::1", .port = http_port, .required = false}); - endpoints.push_back({.address = "127.0.0.1", .port = http_port, .required = true}); + // Numeric literals always parse, InitHTTPAllowList relies on the same. + // Never fall back to CService{}, which is [::]:0 and binds every interface. + endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value(), .required = false}); + endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value(), .required = true}); if (!gArgs.GetArgs("-rpcallowip").empty()) { LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense"); } @@ -248,7 +249,14 @@ static std::vector<BindAddress> GetBindAddresses() LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original); return {}; // empty } - endpoints.emplace_back(host, port); + // Don't allow hostname lookups when binding to local interfaces. + const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)}; + if (!addr) { + LogError("Could not bind RPC on address \"%s\" port %i: Address lookup failed " + "(only numeric addresses are allowed).", host, port); + return {}; // empty + } + endpoints.push_back({.addr = *addr, .required = true}); } } return endpoints; @@ -1361,32 +1369,22 @@ bool InitHTTPServer() LogWarning("%s", msg); } }; - for (const auto& [address_string, port, required] : endpoints) { - // Don't allow hostname lookups when binding to local interfaces. This - // means numeric collisions on available interfaces detected by endpoints_seen - // are probably just repeated instances - skip without logging why. - const std::optional<CService> addr{Lookup(address_string, port, /*fAllowLookup=*/false)}; - if (addr) { - if (!endpoints_seen.insert(*addr).second) continue; - LogInfo("Binding RPC on address %s port %i", address_string, port); - if (addr->IsBindAny()) { - LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); - } - auto result{g_http_server->BindAndStartListening(addr.value())}; - if (!result) { - on_failure(required, - strprintf("Binding RPC on %s address %s failed: %s", - required ? "required" : "optional", - addr->ToStringAddrPort(), result.error())); - } else { - bind_success = true; - } - } else { + for (const auto& [addr, required] : endpoints) { + // Addresses are numeric, so collisions detected by endpoints_seen are + // probably just repeated instances - skip without logging why. + if (!endpoints_seen.insert(addr).second) continue; + LogInfo("Binding RPC on address %s", addr.ToStringAddrPort()); + if (addr.IsBindAny()) { + LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); + } + auto result{g_http_server->BindAndStartListening(addr)}; + if (!result) { on_failure(required, - strprintf("Could not bind RPC on %s address \"%s\" port %i: Address lookup failed " - "(only numeric addresses are allowed).", + strprintf("Binding RPC on %s address %s failed: %s", required ? "required" : "optional", - address_string, port)); + addr.ToStringAddrPort(), result.error())); + } else { + bind_success = true; } } ``` </details>
winterrdog (Migrated from github.com) reviewed 2026-11-05 23:38:03 +00:00
Lines 236-237
winterrdog (Migrated from github.com) commented 2026-11-05 21:15:55 +00:00

not a blocker, just wanted to understand why IPv4 does not come first in the vector, given that it is the required endpoint for successful startup ?

not a blocker, just wanted to understand why IPv4 does not come first in the vector, given that it is the required endpoint for successful startup ?
winterrdog (Migrated from github.com) commented 2026-11-05 21:32:28 +00:00

GetBindAddresses() can sometimes return an empty vector. I think we could handle that here and return early

`GetBindAddresses()` can sometimes return an _empty_ vector. I think we could handle that here and return early
winterrdog (Migrated from github.com) reviewed 2026-11-05 23:39:07 +00:00
Lines 213-217
winterrdog (Migrated from github.com) commented 2026-11-05 23:39:07 +00:00

+1, i think it makes sense to fail-fast

went ahead and extended your patch a little by making InitHTTPServer() fail fast (as well) when a required endpoint fails to bind. this removes the need for bind_success, required_failure, and the failure-handling helper. we just handle the failure where it happens and return immediately.

i think this will make the control flow simpler and easier to follow, with less state to keep track of. plus, it also avoids attempting further binds when we already know startup cannot succeed

extended patch
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 10f1cb85f8..88f87e9ac9 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -207,8 +207,7 @@ static void RejectRequest(std::unique_ptr<HTTPRequest> hreq)
 }
 
 struct BindAddress {
-    std::string address;
-    uint16_t port;
+    CService addr;
     bool required{true};
 };
 
@@ -232,8 +231,10 @@ static std::vector<BindAddress> GetBindAddresses()
         // We allow the default IPv6 bind to fail, but IPv4 is required even
         // with the default port as bitcoin-cli will default to handing RPC
         // credentials in plaintext to whatever process is running on that port.
-        endpoints.push_back({.address = "::1",       .port = http_port, .required = false});
-        endpoints.push_back({.address = "127.0.0.1", .port = http_port, .required = true});
+        // Numeric literals always parse, InitHTTPAllowList relies on the same.
+        // Never fall back to CService{}, which is [::]:0 and binds every interface.
+        endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value(), .required = true});
+        endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value(), .required = false});
         if (!gArgs.GetArgs("-rpcallowip").empty()) {
             LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
         }
@@ -248,7 +249,15 @@ static std::vector<BindAddress> GetBindAddresses()
                 LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
                 return {}; // empty
             }
-            endpoints.emplace_back(host, port);
+            // Don't allow hostname lookups when binding to local interfaces.
+            const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)};
+            if (!addr) {
+                LogError("Could not bind RPC on address \"%s\" port %i: Address lookup failed "
+                         "(only numeric addresses are allowed).",
+                         host, port);
+                return {}; // empty
+            }
+            endpoints.push_back({.addr = *addr, .required = true});
         }
     }
     return endpoints;
@@ -1350,58 +1359,38 @@ bool InitHTTPServer()
 
     // Bind HTTP server to specified addresses
     std::vector<BindAddress> endpoints{GetBindAddresses()};
+    if (endpoints.empty()) {
+        LogError("Unable to bind any endpoint for RPC server");
+        return false;
+    }
+
     std::set<CService> endpoints_seen;
-    bool bind_success{false};
-    bool required_failure{false};
-    auto on_failure = [&required_failure](bool required, std::string_view msg) {
-        if (required) {
-            LogError("%s", msg);
-            required_failure = true;
-        } else {
-            LogWarning("%s", msg);
+    for (const auto& [addr, required] : endpoints) {
+        // Addresses are numeric, so collisions detected by endpoints_seen are
+        // probably just repeated instances - skip without logging why.
+        if (!endpoints_seen.insert(addr).second) continue;
+        LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
+        if (addr.IsBindAny()) {
+            LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
         }
-    };
-    for (const auto& [address_string, port, required] : endpoints) {
-        // Don't allow hostname lookups when binding to local interfaces. This
-        // means numeric collisions on available interfaces detected by endpoints_seen
-        // are probably just repeated instances - skip without logging why.
-        const std::optional<CService> addr{Lookup(address_string, port, /*fAllowLookup=*/false)};
-        if (addr) {
-            if (!endpoints_seen.insert(*addr).second) continue;
-            LogInfo("Binding RPC on address %s port %i", address_string, port);
-            if (addr->IsBindAny()) {
-                LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
-            }
-            auto result{g_http_server->BindAndStartListening(addr.value())};
-            if (!result) {
-                on_failure(required,
-                           strprintf("Binding RPC on %s address %s failed: %s",
+        auto result{g_http_server->BindAndStartListening(addr)};
+        if (!result) {
+            const auto msg{strprintf("Binding RPC on %s address %s failed: %s",
                                      required ? "required" : "optional",
-                                     addr->ToStringAddrPort(), result.error()));
-            } else {
-                bind_success = true;
+                                     addr.ToStringAddrPort(), result.error())};
+            if (required) {
+                LogError("%s", msg);
+                g_http_server->StopListening();
+                if (BindDefaultLoopbackAddresses()) {
+                    LogError("Unable to bind default required IPv4 endpoint. Ensure the "
+                             "port is free and retry, or specify endpoints via -rpcbind.");
+                } else {
+                    LogError("Unable to bind all specified endpoints for RPC server.");
+                }
+                return false;
             }
-        } else {
-            on_failure(required,
-                       strprintf("Could not bind RPC on %s address \"%s\" port %i: Address lookup failed "
-                                 "(only numeric addresses are allowed).",
-                                 required ? "required" : "optional",
-                                 address_string, port));
-        }
-    }
-
-    if (!bind_success) {
-        LogError("Unable to bind any endpoint for RPC server");
-        return false;
-    } else if (required_failure) {
-        g_http_server->StopListening();
-        if (BindDefaultLoopbackAddresses()) {
-            LogError("Unable to bind default required IPv4 endpoint. Ensure the "
-                     "port is free and retry, or specify endpoints via -rpcbind.");
-        } else {
-            LogError("Unable to bind all specified endpoints for RPC server.");
+            LogWarning("%s", msg);
         }
-        return false;
     }
 
     LogDebug(BCLog::HTTP, "Initialized HTTP server");

WDYT ?

+1, i think it makes sense to fail-fast went ahead and extended your patch a little by making `InitHTTPServer()` fail fast (as well) when a required endpoint fails to bind. this removes the need for `bind_success`, `required_failure`, and the failure-handling helper. we just handle the failure where it happens and return immediately. i think this will make the control flow simpler and easier to follow, with less state to keep track of. plus, it also avoids attempting further binds when we already know startup cannot succeed <details><summary><i>extended</i> patch</summary> ```diff diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 10f1cb85f8..88f87e9ac9 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -207,8 +207,7 @@ static void RejectRequest(std::unique_ptr<HTTPRequest> hreq) } struct BindAddress { - std::string address; - uint16_t port; + CService addr; bool required{true}; }; @@ -232,8 +231,10 @@ static std::vector<BindAddress> GetBindAddresses() // We allow the default IPv6 bind to fail, but IPv4 is required even // with the default port as bitcoin-cli will default to handing RPC // credentials in plaintext to whatever process is running on that port. - endpoints.push_back({.address = "::1", .port = http_port, .required = false}); - endpoints.push_back({.address = "127.0.0.1", .port = http_port, .required = true}); + // Numeric literals always parse, InitHTTPAllowList relies on the same. + // Never fall back to CService{}, which is [::]:0 and binds every interface. + endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value(), .required = true}); + endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value(), .required = false}); if (!gArgs.GetArgs("-rpcallowip").empty()) { LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense"); } @@ -248,7 +249,15 @@ static std::vector<BindAddress> GetBindAddresses() LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original); return {}; // empty } - endpoints.emplace_back(host, port); + // Don't allow hostname lookups when binding to local interfaces. + const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)}; + if (!addr) { + LogError("Could not bind RPC on address \"%s\" port %i: Address lookup failed " + "(only numeric addresses are allowed).", + host, port); + return {}; // empty + } + endpoints.push_back({.addr = *addr, .required = true}); } } return endpoints; @@ -1350,58 +1359,38 @@ bool InitHTTPServer() // Bind HTTP server to specified addresses std::vector<BindAddress> endpoints{GetBindAddresses()}; + if (endpoints.empty()) { + LogError("Unable to bind any endpoint for RPC server"); + return false; + } + std::set<CService> endpoints_seen; - bool bind_success{false}; - bool required_failure{false}; - auto on_failure = [&required_failure](bool required, std::string_view msg) { - if (required) { - LogError("%s", msg); - required_failure = true; - } else { - LogWarning("%s", msg); + for (const auto& [addr, required] : endpoints) { + // Addresses are numeric, so collisions detected by endpoints_seen are + // probably just repeated instances - skip without logging why. + if (!endpoints_seen.insert(addr).second) continue; + LogInfo("Binding RPC on address %s", addr.ToStringAddrPort()); + if (addr.IsBindAny()) { + LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); } - }; - for (const auto& [address_string, port, required] : endpoints) { - // Don't allow hostname lookups when binding to local interfaces. This - // means numeric collisions on available interfaces detected by endpoints_seen - // are probably just repeated instances - skip without logging why. - const std::optional<CService> addr{Lookup(address_string, port, /*fAllowLookup=*/false)}; - if (addr) { - if (!endpoints_seen.insert(*addr).second) continue; - LogInfo("Binding RPC on address %s port %i", address_string, port); - if (addr->IsBindAny()) { - LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); - } - auto result{g_http_server->BindAndStartListening(addr.value())}; - if (!result) { - on_failure(required, - strprintf("Binding RPC on %s address %s failed: %s", + auto result{g_http_server->BindAndStartListening(addr)}; + if (!result) { + const auto msg{strprintf("Binding RPC on %s address %s failed: %s", required ? "required" : "optional", - addr->ToStringAddrPort(), result.error())); - } else { - bind_success = true; + addr.ToStringAddrPort(), result.error())}; + if (required) { + LogError("%s", msg); + g_http_server->StopListening(); + if (BindDefaultLoopbackAddresses()) { + LogError("Unable to bind default required IPv4 endpoint. Ensure the " + "port is free and retry, or specify endpoints via -rpcbind."); + } else { + LogError("Unable to bind all specified endpoints for RPC server."); + } + return false; } - } else { - on_failure(required, - strprintf("Could not bind RPC on %s address \"%s\" port %i: Address lookup failed " - "(only numeric addresses are allowed).", - required ? "required" : "optional", - address_string, port)); - } - } - - if (!bind_success) { - LogError("Unable to bind any endpoint for RPC server"); - return false; - } else if (required_failure) { - g_http_server->StopListening(); - if (BindDefaultLoopbackAddresses()) { - LogError("Unable to bind default required IPv4 endpoint. Ensure the " - "port is free and retry, or specify endpoints via -rpcbind."); - } else { - LogError("Unable to bind all specified endpoints for RPC server."); + LogWarning("%s", msg); } - return false; } LogDebug(BCLog::HTTP, "Initialized HTTP server"); ``` </details> WDYT ?
hodlinator (Migrated from github.com) reviewed 2026-11-09 11:53:49 +00:00
hodlinator (Migrated from github.com) left a comment

Pushed 1e5767518a to address latest round of review.

Pushed 1e5767518ac5e1b760401deeb353cf02743c85ce to address latest round of review.
Lines 213-216
hodlinator (Migrated from github.com) commented 2026-11-09 11:27:34 +00:00

thread https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4481607697:

Good ideas! Added as refactor-commit in the middle. Nice to get rid of the on_failure-lambda.

thread https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4481607697: Good ideas! Added as refactor-commit in the middle. Nice to get rid of the `on_failure`-lambda.
Lines 236-237
hodlinator (Migrated from github.com) commented 2026-11-09 10:30:53 +00:00
re https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4486162809: I prefer maintaining the same order as on master.
janb84 (Migrated from github.com) reviewed 2026-11-09 12:46:59 +00:00
janb84 (Migrated from github.com) left a comment

t ACK 1e5767518a

As per description, this PR closes a real credential leak. Checked, verified and tested.

Thanks for taking the lookup suggestion!

LGTM !

t ACK 1e5767518ac5e1b760401deeb353cf02743c85ce As per description, this PR closes a real credential leak. Checked, verified and tested. Thanks for taking the lookup suggestion! LGTM !
winterrdog (Migrated from github.com) reviewed 2026-11-09 19:50:40 +00:00
Lines 236-237
winterrdog (Migrated from github.com) commented 2026-11-09 19:50:40 +00:00

i had put IPv4 first mostly because bitcoin-cli defaults to 127.0.0.1. so, if that endpoint cannot be bound, we already know that the default client cannot safely connect to bitcoind

with this ordering, we can abort before even attempting IPv6, rather than starting an RPC server that bitcoin-cli cannot reliably reach.

that was my reasoning

i had put IPv4 first mostly because `bitcoin-cli` [defaults to `127.0.0.1`](https://github.com/bitcoin/bitcoin/blob/44901d8f64cb617714707bd025ecd83f108353c2/src/bitcoin-cli.cpp#L63). so, if that endpoint cannot be bound, we already know that the default client cannot safely connect to `bitcoind` with this ordering, we can abort before even attempting IPv6, rather than starting an RPC server that `bitcoin-cli` cannot reliably reach. that was my reasoning
winterrdog (Migrated from github.com) reviewed 2026-11-09 19:54:43 +00:00
winterrdog (Migrated from github.com) left a comment

tested ACK 1e5767518a

successfully built and tested with clang++-20 on Debian, targeting x86_64

tested ACK 1e5767518ac5e1b760401deeb353cf02743c85ce successfully built and tested with `clang++-20` on Debian, targeting `x86_64`
l0rinc (Migrated from github.com) reviewed 2026-11-09 21:46:20 +00:00
l0rinc (Migrated from github.com) left a comment

I'll review this in more detail a bit later, left a few low-effort suggestions in the meantime...

I'll review this in more detail a bit later, left a few low-effort suggestions in the meantime...
l0rinc (Migrated from github.com) commented 2026-11-09 21:37:45 +00:00

1e57675 http: fail closed on partial binds:

Could we deduplicate while building endpoints? It's quadratic, but likely a lot faster because we don't expect many element. Then the bind loop can use the collected list directly without keeping a separate set.

Deduplicate while collecting RPC endpoints
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 83cf042a3e..eb085dc50d 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -28,12 +28,12 @@
 #include <util/time.h>
 #include <util/translation.h>
 
+#include <algorithm>
 #include <condition_variable>
 #include <cstdio>
 #include <cstdlib>
 #include <memory>
 #include <optional>
-#include <set>
 #include <span>
 #include <string>
 #include <string_view>
@@ -257,6 +257,8 @@ static std::vector<BindAddress> GetBindAddresses()
                          "(only numeric addresses are allowed).", host, port);
                 return {}; // empty
             }
+            // Skip repeated endpoints, binding the same one twice would fail.
+            if (std::ranges::find(endpoints, *addr, &BindAddress::addr) != endpoints.end()) continue;
             endpoints.push_back({.addr = *addr, .required = true});
         }
     }
@@ -1393,12 +1395,7 @@ bool InitHTTPServer()
         return false;
     }
 
-    std::set<CService> endpoints_seen;
     for (const auto& [addr, required] : endpoints) {
-        // Addresses are numeric, so collisions detected by endpoints_seen are
-        // probably just repeated instances - skip without logging why.
-        if (!endpoints_seen.insert(addr).second) continue;
-
         LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
         if (addr.IsBindAny()) {
             LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
> [1e57675](https://github.com/bitcoin/bitcoin/pull/36187/changes/1e5767518ac5e1b760401deeb353cf02743c85ce) _http: fail closed on partial binds_: Could we deduplicate while building `endpoints`? It's quadratic, but likely a lot faster because we don't expect many element. Then the bind loop can use the collected list directly without keeping a separate set. <details> <summary>Deduplicate while collecting RPC endpoints</summary> ```diff diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 83cf042a3e..eb085dc50d 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -28,12 +28,12 @@ #include <util/time.h> #include <util/translation.h> +#include <algorithm> #include <condition_variable> #include <cstdio> #include <cstdlib> #include <memory> #include <optional> -#include <set> #include <span> #include <string> #include <string_view> @@ -257,6 +257,8 @@ static std::vector<BindAddress> GetBindAddresses() "(only numeric addresses are allowed).", host, port); return {}; // empty } + // Skip repeated endpoints, binding the same one twice would fail. + if (std::ranges::find(endpoints, *addr, &BindAddress::addr) != endpoints.end()) continue; endpoints.push_back({.addr = *addr, .required = true}); } } @@ -1393,12 +1395,7 @@ bool InitHTTPServer() return false; } - std::set<CService> endpoints_seen; for (const auto& [addr, required] : endpoints) { - // Addresses are numeric, so collisions detected by endpoints_seen are - // probably just repeated instances - skip without logging why. - if (!endpoints_seen.insert(addr).second) continue; - LogInfo("Binding RPC on address %s", addr.ToStringAddrPort()); if (addr.IsBindAny()) { LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-09 21:40:42 +00:00

1e57675 http: fail closed on partial binds:

My understanding is that without -rpcallowip, the suggested -rpcbind is ignored and an IPv6-only host gets the same startup failure again.

Include both required options in the IPv4 failure hint
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index eb085dc50d..ad873c770f 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -1410,7 +1410,8 @@ bool InitHTTPServer()
                 g_http_server->StopListening();
                 if (BindDefaultLoopbackAddresses()) {
                     LogError("Unable to bind default required IPv4 endpoint. Ensure the "
-                             "port is free and retry, or specify endpoints via -rpcbind.");
+                             "port is free and retry, or specify endpoints via -rpcbind "
+                             "together with -rpcallowip.");
                 } else {
                     LogError("Unable to bind all specified endpoints for RPC server.");
                 }
> [1e57675](https://github.com/bitcoin/bitcoin/pull/36187/changes/1e5767518ac5e1b760401deeb353cf02743c85ce) _http: fail closed on partial binds_: My understanding is that without `-rpcallowip`, the suggested `-rpcbind` is ignored and an IPv6-only host gets the same startup failure again. <details> <summary>Include both required options in the IPv4 failure hint</summary> ```diff diff --git a/src/httpserver.cpp b/src/httpserver.cpp index eb085dc50d..ad873c770f 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -1410,7 +1410,8 @@ bool InitHTTPServer() g_http_server->StopListening(); if (BindDefaultLoopbackAddresses()) { LogError("Unable to bind default required IPv4 endpoint. Ensure the " - "port is free and retry, or specify endpoints via -rpcbind."); + "port is free and retry, or specify endpoints via -rpcbind " + "together with -rpcallowip."); } else { LogError("Unable to bind all specified endpoints for RPC server."); } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-09 21:40:21 +00:00

1e57675 http: fail closed on partial binds:

I'd keep the credential capture in the characterization commit and use assert_start_raises_init_error() for the permanent regression test.

Use the existing startup-error helper
diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
index 5d923f8415..02b42fce35 100755
--- a/test/functional/rpc_bind.py
+++ b/test/functional/rpc_bind.py
@@ -5,13 +5,11 @@
 """Test running bitcoind with the -rpcbind and -rpcallowip options."""
 
 import socket
-import subprocess
-import time
 
 from test_framework.netutil import NETWORK_ERRORS, all_interfaces, addr_to_hex, get_bind_addrs, test_ipv6_local
 from test_framework.test_framework import BitcoinTestFramework, SkipTest
-from test_framework.test_node import ErrorMatch, FailedToStartError
-from test_framework.util import assert_equal, get_auth_cookie, rpc_port, str_to_b64str
+from test_framework.test_node import ErrorMatch
+from test_framework.util import assert_equal, rpc_port
 
 class RPCBindTest(BitcoinTestFramework):
     def set_test_params(self):
@@ -64,63 +62,12 @@ class RPCBindTest(BitcoinTestFramework):
 
     def run_partial_bind_test(self, explicit_binds):
         self.log.info(f'Check startup when the {"explicit" if explicit_binds else "default IPv4"} RPC address is already owned')
-        self.nodes[0].rpchost = '[::1]'
-        error = ''
-        credential_captured = False
-        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
-            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-            sock.bind(('127.0.0.1', self.defaultport))
-            sock.listen()
-            sock.settimeout(0.1)
-            try:
-                extra_args = ['-disablewallet', '-nolisten']
-                if explicit_binds:
-                    extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
-                self.start_node(0, extra_args=extra_args)
-                started = True
-                cli = subprocess.Popen([
-                    self.nodes[0].binaries.paths.bitcoincli,
-                    f'-datadir={self.nodes[0].datadir_path}',
-                    '-noipcconnect',
-                    '-rpcclienttimeout=2',
-                    'getblockcount',
-                ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-                try:
-                    conn = None
-                    deadline = time.monotonic() + 5
-                    while conn is None and time.monotonic() < deadline:
-                        try:
-                            conn = sock.accept()[0]
-                        except TimeoutError:
-                            if cli.poll() is not None:
-                                _, stderr = cli.communicate()
-                                raise AssertionError(f'bitcoin-cli exited before connecting: {stderr.decode()}')
-                    assert conn is not None
-                    with conn:
-                        conn.settimeout(5)
-                        request = b''
-                        while b'\r\n\r\n' not in request:
-                            chunk = conn.recv(4096)
-                            assert chunk
-                            request += chunk
-                        conn.sendall(b'HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')
-                    cli.communicate(timeout=5)
-                finally:
-                    if cli.poll() is None:
-                        cli.kill()
-                        cli.wait()
-                user, password = get_auth_cookie(self.nodes[0].datadir_path, self.chain)
-                credential_captured = f'Authorization: Basic {str_to_b64str(f"{user}:{password}")}\r\n'.encode() in request
-                self.stop_node(0)
-            except FailedToStartError as e:
-                started = False
-                error = str(e)
-                self.cleanup_partially_started_nodes()
-        self.nodes[0].rpchost = None
-
-        assert_equal(started, False)
-        assert_equal(credential_captured, False)
-        assert 'Unable to start HTTP server' in error
+        extra_args = ['-disablewallet', '-nolisten']
+        if explicit_binds:
+            extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
+        with socket.create_server(('127.0.0.1', self.defaultport)):
+            with self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']):
+                self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
 
     def run_allowip_test(self, allow_ips, rpchost, rpcport):
         '''
> [1e57675](https://github.com/bitcoin/bitcoin/pull/36187/changes/1e5767518ac5e1b760401deeb353cf02743c85ce) _http: fail closed on partial binds_: I'd keep the credential capture in the characterization commit and use `assert_start_raises_init_error()` for the permanent regression test. <details> <summary>Use the existing startup-error helper</summary> ```diff diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py index 5d923f8415..02b42fce35 100755 --- a/test/functional/rpc_bind.py +++ b/test/functional/rpc_bind.py @@ -5,13 +5,11 @@ """Test running bitcoind with the -rpcbind and -rpcallowip options.""" import socket -import subprocess -import time from test_framework.netutil import NETWORK_ERRORS, all_interfaces, addr_to_hex, get_bind_addrs, test_ipv6_local from test_framework.test_framework import BitcoinTestFramework, SkipTest -from test_framework.test_node import ErrorMatch, FailedToStartError -from test_framework.util import assert_equal, get_auth_cookie, rpc_port, str_to_b64str +from test_framework.test_node import ErrorMatch +from test_framework.util import assert_equal, rpc_port class RPCBindTest(BitcoinTestFramework): def set_test_params(self): @@ -64,63 +62,12 @@ class RPCBindTest(BitcoinTestFramework): def run_partial_bind_test(self, explicit_binds): self.log.info(f'Check startup when the {"explicit" if explicit_binds else "default IPv4"} RPC address is already owned') - self.nodes[0].rpchost = '[::1]' - error = '' - credential_captured = False - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - sock.bind(('127.0.0.1', self.defaultport)) - sock.listen() - sock.settimeout(0.1) - try: - extra_args = ['-disablewallet', '-nolisten'] - if explicit_binds: - extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]'] - self.start_node(0, extra_args=extra_args) - started = True - cli = subprocess.Popen([ - self.nodes[0].binaries.paths.bitcoincli, - f'-datadir={self.nodes[0].datadir_path}', - '-noipcconnect', - '-rpcclienttimeout=2', - 'getblockcount', - ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - try: - conn = None - deadline = time.monotonic() + 5 - while conn is None and time.monotonic() < deadline: - try: - conn = sock.accept()[0] - except TimeoutError: - if cli.poll() is not None: - _, stderr = cli.communicate() - raise AssertionError(f'bitcoin-cli exited before connecting: {stderr.decode()}') - assert conn is not None - with conn: - conn.settimeout(5) - request = b'' - while b'\r\n\r\n' not in request: - chunk = conn.recv(4096) - assert chunk - request += chunk - conn.sendall(b'HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n') - cli.communicate(timeout=5) - finally: - if cli.poll() is None: - cli.kill() - cli.wait() - user, password = get_auth_cookie(self.nodes[0].datadir_path, self.chain) - credential_captured = f'Authorization: Basic {str_to_b64str(f"{user}:{password}")}\r\n'.encode() in request - self.stop_node(0) - except FailedToStartError as e: - started = False - error = str(e) - self.cleanup_partially_started_nodes() - self.nodes[0].rpchost = None - - assert_equal(started, False) - assert_equal(credential_captured, False) - assert 'Unable to start HTTP server' in error + extra_args = ['-disablewallet', '-nolisten'] + if explicit_binds: + extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]'] + with socket.create_server(('127.0.0.1', self.defaultport)): + with self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']): + self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.') def run_allowip_test(self, allow_ips, rpchost, rpcport): ''' ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-09 21:39:23 +00:00

1e57675 http: fail closed on partial binds:

If we move this to the end of the else branch in _run_loopback_tests(), it would remove the extra check and leave run_test() unchanged.

Run partial-bind cases after the existing loopback tests
diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
index 450e00df58..5d923f8415 100755
--- a/test/functional/rpc_bind.py
+++ b/test/functional/rpc_bind.py
@@ -188,9 +188,6 @@ class RPCBindTest(BitcoinTestFramework):
         self.defaultport = rpc_port(0)
 
         if not self.options.run_nonloopback:
-            if not self.options.run_ipv4:
-                for explicit_binds in [False, True]:
-                    self.run_partial_bind_test(explicit_binds)
             self._run_loopback_tests()
             if self.options.run_ipv4:
                 self.run_invalid_bind_test(['127.0.0.1'], ['127.0.0.1:notaport', '127.0.0.1:-18443', '127.0.0.1:0', '127.0.0.1:65536'])
@@ -227,6 +224,8 @@ class RPCBindTest(BitcoinTestFramework):
             # check both IPv4 and IPv6 localhost (explicit)
             self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],
                 [('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
+            for explicit_binds in [False, True]:
+                self.run_partial_bind_test(explicit_binds)
 
     def _run_nonloopback_tests(self):
         self.log.info("Using interface %s for testing" % self.non_loopback_ip)
> [1e57675](https://github.com/bitcoin/bitcoin/pull/36187/changes/1e5767518ac5e1b760401deeb353cf02743c85ce) _http: fail closed on partial binds_: If we move this to the end of the `else` branch in `_run_loopback_tests()`, it would remove the extra check and leave `run_test()` unchanged. <details> <summary>Run partial-bind cases after the existing loopback tests</summary> ```diff diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py index 450e00df58..5d923f8415 100755 --- a/test/functional/rpc_bind.py +++ b/test/functional/rpc_bind.py @@ -188,9 +188,6 @@ class RPCBindTest(BitcoinTestFramework): self.defaultport = rpc_port(0) if not self.options.run_nonloopback: - if not self.options.run_ipv4: - for explicit_binds in [False, True]: - self.run_partial_bind_test(explicit_binds) self._run_loopback_tests() if self.options.run_ipv4: self.run_invalid_bind_test(['127.0.0.1'], ['127.0.0.1:notaport', '127.0.0.1:-18443', '127.0.0.1:0', '127.0.0.1:65536']) @@ -227,6 +224,8 @@ class RPCBindTest(BitcoinTestFramework): # check both IPv4 and IPv6 localhost (explicit) self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'], [('127.0.0.1', self.defaultport), ('::1', self.defaultport)]) + for explicit_binds in [False, True]: + self.run_partial_bind_test(explicit_binds) def _run_nonloopback_tests(self): self.log.info("Using interface %s for testing" % self.non_loopback_ip) ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-09 21:38:41 +00:00

1e57675 http: fail closed on partial binds:

nit: move a repeated endpoint to the existing multi-port case and drop this separate restart.

Combine duplicate and multi-port coverage
diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
index ffc23c57de..450e00df58 100755
--- a/test/functional/rpc_bind.py
+++ b/test/functional/rpc_bind.py
@@ -208,13 +208,11 @@ class RPCBindTest(BitcoinTestFramework):
             # check only IPv4 localhost (explicit)
             self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
                 [('127.0.0.1', self.defaultport)])
-            self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '127.0.0.1'],
-                [('127.0.0.1', self.defaultport)])
             # check only IPv4 localhost (explicit) with alternative port
             self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
                 [('127.0.0.1', 32171)])
-            # check only IPv4 localhost (explicit) with multiple alternative ports on same host
-            self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],
+            # check only IPv4 localhost (explicit) with multiple alternative ports on same host, one of them repeated
+            self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172', '127.0.0.1:32171'],
                 [('127.0.0.1', 32171), ('127.0.0.1', 32172)])
         else:
             # check default without rpcallowip (IPv4 and IPv6 localhost)
> [1e57675](https://github.com/bitcoin/bitcoin/pull/36187/changes/1e5767518ac5e1b760401deeb353cf02743c85ce) _http: fail closed on partial binds_: nit: move a repeated endpoint to the existing multi-port case and drop this separate restart. <details> <summary>Combine duplicate and multi-port coverage</summary> ```diff diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py index ffc23c57de..450e00df58 100755 --- a/test/functional/rpc_bind.py +++ b/test/functional/rpc_bind.py @@ -208,13 +208,11 @@ class RPCBindTest(BitcoinTestFramework): # check only IPv4 localhost (explicit) self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'], [('127.0.0.1', self.defaultport)]) - self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '127.0.0.1'], - [('127.0.0.1', self.defaultport)]) # check only IPv4 localhost (explicit) with alternative port self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'], [('127.0.0.1', 32171)]) - # check only IPv4 localhost (explicit) with multiple alternative ports on same host - self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'], + # check only IPv4 localhost (explicit) with multiple alternative ports on same host, one of them repeated + self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172', '127.0.0.1:32171'], [('127.0.0.1', 32171), ('127.0.0.1', 32172)]) else: # check default without rpcallowip (IPv4 and IPv6 localhost) ``` </details>
hodlinator (Migrated from github.com) reviewed 2026-11-11 15:48:20 +00:00
hodlinator (Migrated from github.com) left a comment

Pushed new version based on l0rinc's initial feedback, sorry for invalidating the 2 ACKs.

Pushed new version based on l0rinc's initial feedback, sorry for invalidating the 2 ACKs.
hodlinator (Migrated from github.com) commented 2026-11-10 09:22:16 +00:00

re https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4518281015:

Was thinking deduplicating on the receiver side was somehow better defensive programming, but within the same file it's not that important, and we indeed do not expect many bind-addresses. Taken.

re https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4518281015: Was thinking deduplicating on the receiver side was somehow better defensive programming, but within the same file it's not that important, and we indeed do not expect many bind-addresses. Taken.
hodlinator (Migrated from github.com) commented 2026-11-10 10:07:57 +00:00

re https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4518305687:

Flipping the assert_equal()s felt clear, but agree that it's good to keep the test simpler going forward. Taken with little modification. Simplified the initial characterization commit as well to make the diff smaller.

re https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4518305687: Flipping the `assert_equal()`s felt clear, but agree that it's good to keep the test simpler going forward. Taken with little modification. Simplified the initial characterization commit as well to make the diff smaller.
hodlinator (Migrated from github.com) commented 2026-11-10 10:03:51 +00:00

re https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4518289854:

Taken, although I opted for repeating 127.0.0.1:32172 so one can more easily compare.

re https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4518289854: Taken, although I opted for repeating `127.0.0.1:32172` so one can more easily compare.
hodlinator commented 2026-11-11 19:22:49 +00:00 (Migrated from github.com)

Removed AI Disclaimer from PR desc as it could be taken as avoidance of responsibility. Credits for finding the credential exfiltration vulnerability and the initial broad strokes solution still go in part to LLMs.

Removed AI Disclaimer from PR desc as it could be taken as avoidance of responsibility. Credits for finding the credential exfiltration vulnerability and the initial broad strokes solution still go in part to LLMs.
l0rinc (Migrated from github.com) requested changes 2026-11-11 20:43:22 +00:00
l0rinc (Migrated from github.com) commented 2026-11-11 20:41:22 +00:00

a8e7faa http: fail closed on partial binds:

(edited)
CService equality ignores the IPv6 scope ID, so the new dedupe drops -rpcbind=[fe80::1%2] after -rpcbind=[fe80::1%1] without a warning, while master attempts both binds.
ToStringAddrPort() comparison should probably fix it.

Bind one link-local address on two interfaces
diff --git a/src/test/httpserver_tests.cpp b/src/test/httpserver_tests.cpp
index 3a5947a7d7..f961682a73 100644
--- a/src/test/httpserver_tests.cpp
+++ b/src/test/httpserver_tests.cpp
@@ -857,6 +857,23 @@ BOOST_AUTO_TEST_CASE(http_should_disconnect_tests)
     }
 }
 
+BOOST_AUTO_TEST_CASE(rpc_bind_scopes)
+{
+    // Same link-local address on two interfaces: both must be bound
+    const char* argv[]{"", "-rpcbind=[fe80::1%1]", "-rpcbind=[fe80::1%2]"};
+    std::string error;
+    BOOST_REQUIRE(gArgs.ParseParameters(std::size(argv), argv, error));
+
+    int sockets{0};
+    CreateSock = [&sockets, create_sock{CreateSock}](int domain, int type, int protocol) {
+        ++sockets;
+        return create_sock(domain, type, protocol);
+    };
+    BOOST_CHECK(InitHTTPServer());
+    StopHTTPServer();
+    BOOST_CHECK_EQUAL(sockets, 2);
+}
+
 BOOST_AUTO_TEST_CASE(http_server_socket_tests)
 {
     // Hard code the timestamp for the Date header in the HTTP response
> [a8e7faa](https://github.com/bitcoin/bitcoin/pull/36187/changes/a8e7faa47760528c1a1e20165a3567abbe323e21) _http: fail closed on partial binds_: (edited) `CService` equality ignores the IPv6 scope ID, so the new dedupe drops `-rpcbind=[fe80::1%2]` after `-rpcbind=[fe80::1%1]` without a warning, while master attempts both binds. `ToStringAddrPort()` comparison should probably fix it. <details> <summary>Bind one link-local address on two interfaces</summary> ```diff diff --git a/src/test/httpserver_tests.cpp b/src/test/httpserver_tests.cpp index 3a5947a7d7..f961682a73 100644 --- a/src/test/httpserver_tests.cpp +++ b/src/test/httpserver_tests.cpp @@ -857,6 +857,23 @@ BOOST_AUTO_TEST_CASE(http_should_disconnect_tests) } } +BOOST_AUTO_TEST_CASE(rpc_bind_scopes) +{ + // Same link-local address on two interfaces: both must be bound + const char* argv[]{"", "-rpcbind=[fe80::1%1]", "-rpcbind=[fe80::1%2]"}; + std::string error; + BOOST_REQUIRE(gArgs.ParseParameters(std::size(argv), argv, error)); + + int sockets{0}; + CreateSock = [&sockets, create_sock{CreateSock}](int domain, int type, int protocol) { + ++sockets; + return create_sock(domain, type, protocol); + }; + BOOST_CHECK(InitHTTPServer()); + StopHTTPServer(); + BOOST_CHECK_EQUAL(sockets, 2); +} + BOOST_AUTO_TEST_CASE(http_server_socket_tests) { // Hard code the timestamp for the Date header in the HTTP response ``` </details>
l0rinc (Migrated from github.com) requested changes 2026-11-12 09:43:16 +00:00
l0rinc (Migrated from github.com) left a comment

Thanks for taking my earlier suggestions! I went over the change more thoroughly now and left a few nits and cleanups. The reason I'm not acking yet is that the new deduplication drops IPv6 binds that differ only in their scope.

Thanks for taking my earlier suggestions! I went over the change more thoroughly now and left a few nits and cleanups. The reason I'm not acking yet is that the new deduplication drops IPv6 binds that differ only in their scope.
l0rinc (Migrated from github.com) commented 2026-11-12 08:15:31 +00:00

85e3162 refactor: Lookup bind addresses already during GetBindAddresses():

This refactor already changes the endpoint type, so it seems like the natural place to introduce BindAddress, with just the CService for now. The fail-closed commit would then only need to add required, and the endpoint types wouldn't change twice.

Introduce the wrapper before adding bind requirements
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -206,10 +206,14 @@
     WriteNoStoreErrorReply(*hreq, HTTP_SERVICE_UNAVAILABLE);
 }
 
-static std::vector<CService> GetBindAddresses()
+struct BindAddress {
+    CService addr;
+};
+
+static std::vector<BindAddress> GetBindAddresses()
 {
     uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
-    std::vector<CService> endpoints;
+    std::vector<BindAddress> endpoints;
 
     // Determine what addresses to bind to
     // To prevent misconfiguration and accidental exposure of the RPC
@@ -219,8 +223,8 @@
     if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
         // Numeric literals always parse, InitHTTPAllowList() relies on the same.
         // Never fall back to CService{}, which is [::]:0 and binds every interface.
-        endpoints.push_back(Lookup("::1", http_port, /*fAllowLookup=*/false).value());
-        endpoints.push_back(Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value());
+        endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value()});
+        endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value()});
 
         if (!gArgs.GetArgs("-rpcallowip").empty()) {
             LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
@@ -243,7 +247,7 @@
                            "(only numeric addresses are allowed).", host, port);
                 continue;
             }
-            endpoints.push_back(*addr);
+            endpoints.push_back({.addr = *addr});
         }
     }
     return endpoints;
@@ -1373,9 +1377,9 @@
     g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1));
 
     // Bind HTTP server to specified addresses
-    std::vector<CService> endpoints{GetBindAddresses()};
+    auto endpoints{GetBindAddresses()};
     bool bind_success{false};
-    for (const auto& addr : endpoints) {
+    for (const auto& [addr] : endpoints) {
         LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
         if (addr.IsBindAny()) {
             LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
> [85e3162](https://github.com/bitcoin/bitcoin/pull/36187/changes/85e31621da75e7dbb890ce7504d6d6373c457009) _refactor: Lookup bind addresses already during GetBindAddresses()_: This refactor already changes the endpoint type, so it seems like the natural place to introduce `BindAddress`, with just the `CService` for now. The fail-closed commit would then only need to add `required`, and the endpoint types wouldn't change twice. <details> <summary>Introduce the wrapper before adding bind requirements</summary> ```diff --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -206,10 +206,14 @@ WriteNoStoreErrorReply(*hreq, HTTP_SERVICE_UNAVAILABLE); } -static std::vector<CService> GetBindAddresses() +struct BindAddress { + CService addr; +}; + +static std::vector<BindAddress> GetBindAddresses() { uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))}; - std::vector<CService> endpoints; + std::vector<BindAddress> endpoints; // Determine what addresses to bind to // To prevent misconfiguration and accidental exposure of the RPC @@ -219,8 +223,8 @@ if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs // Numeric literals always parse, InitHTTPAllowList() relies on the same. // Never fall back to CService{}, which is [::]:0 and binds every interface. - endpoints.push_back(Lookup("::1", http_port, /*fAllowLookup=*/false).value()); - endpoints.push_back(Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value()); + endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value()}); + endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value()}); if (!gArgs.GetArgs("-rpcallowip").empty()) { LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense"); @@ -243,7 +247,7 @@ "(only numeric addresses are allowed).", host, port); continue; } - endpoints.push_back(*addr); + endpoints.push_back({.addr = *addr}); } } return endpoints; @@ -1373,9 +1377,9 @@ g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1)); // Bind HTTP server to specified addresses - std::vector<CService> endpoints{GetBindAddresses()}; + auto endpoints{GetBindAddresses()}; bool bind_success{false}; - for (const auto& addr : endpoints) { + for (const auto& [addr] : endpoints) { LogInfo("Binding RPC on address %s", addr.ToStringAddrPort()); if (addr.IsBindAny()) { LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-12 08:42:35 +00:00

a8e7faa http: fail closed on partial binds:

nit: with the lookup in the if initializer, addr only lives in the branch that uses it, and the happy path comes first (similarly to a try/catch) - the same in the parsing refactor would also drop its continue.

Scope the lookup result to its branch
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 070e14d402..80a0d97726 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -251,16 +251,16 @@ static std::vector<BindAddress> GetBindAddresses()
                 return {}; // empty
             }
             // Don't allow hostname lookups when binding to local interfaces.
-            const auto addr{Lookup(host, port, /*fAllowLookup=*/false)};
-            if (!addr) {
+            if (const auto addr{Lookup(host, port, /*fAllowLookup=*/false)}) {
+                // Skip repeated endpoints, binding the same one twice would fail.
+                if (std::ranges::find(endpoints, *addr, &BindAddress::addr) == endpoints.end()) {
+                    endpoints.push_back({.addr = *addr, .required = true});
+                }
+            } else {
                 LogError("Could not lookup RPC bind address \"%s\" port %i "
                          "(only numeric addresses are allowed).", host, port);
                 return {}; // empty
             }
-            // Skip repeated endpoints, binding the same one twice would fail.
-            if (std::ranges::find(endpoints, *addr, &BindAddress::addr) == endpoints.end()) {
-                endpoints.push_back({.addr = *addr, .required = true});
-            }
         }
     }
     return endpoints;
> [a8e7faa](https://github.com/bitcoin/bitcoin/pull/36187/changes/a8e7faa47760528c1a1e20165a3567abbe323e21) _http: fail closed on partial binds_: nit: with the lookup in the `if` initializer, `addr` only lives in the branch that uses it, and the happy path comes first (similarly to a try/catch) - the same in the parsing refactor would also drop its `continue`. <details> <summary>Scope the lookup result to its branch</summary> ```diff diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 070e14d402..80a0d97726 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -251,16 +251,16 @@ static std::vector<BindAddress> GetBindAddresses() return {}; // empty } // Don't allow hostname lookups when binding to local interfaces. - const auto addr{Lookup(host, port, /*fAllowLookup=*/false)}; - if (!addr) { + if (const auto addr{Lookup(host, port, /*fAllowLookup=*/false)}) { + // Skip repeated endpoints, binding the same one twice would fail. + if (std::ranges::find(endpoints, *addr, &BindAddress::addr) == endpoints.end()) { + endpoints.push_back({.addr = *addr, .required = true}); + } + } else { LogError("Could not lookup RPC bind address \"%s\" port %i " "(only numeric addresses are allowed).", host, port); return {}; // empty } - // Skip repeated endpoints, binding the same one twice would fail. - if (std::ranges::find(endpoints, *addr, &BindAddress::addr) == endpoints.end()) { - endpoints.push_back({.addr = *addr, .required = true}); - } } } return endpoints; ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-12 08:42:20 +00:00

a8e7faa http: fail closed on partial binds:

nit: the initializers and ranges already have unambiguous types, so auto works for endpoints, both ports, the lookup result and the -rpcbind loop element. Reading the port with GetArg<uint16_t> also removes the static_cast, and CheckHostPortOptions() already rejects an out-of-range -rpcport at startup.

Deduce types supplied by initializers and ranges
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index adb85f43d3..070e14d402 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -220,7 +220,7 @@ static bool BindDefaultLoopbackAddresses()
 
 static std::vector<BindAddress> GetBindAddresses()
 {
-    uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
+    auto http_port{gArgs.GetArg<uint16_t>("-rpcport", BaseParams().RPCPort())};
     std::vector<BindAddress> endpoints;
 
     // Determine what addresses to bind to
@@ -243,15 +243,15 @@ static std::vector<BindAddress> GetBindAddresses()
             LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
         }
     } else { // Specific bind addresses
-        for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
-            uint16_t port{http_port};
+        for (const auto& strRPCBind : gArgs.GetArgs("-rpcbind")) {
+            auto port{http_port};
             std::string host;
             if (!SplitHostPort(strRPCBind, port, host)) {
                 LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
                 return {}; // empty
             }
             // Don't allow hostname lookups when binding to local interfaces.
-            const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)};
+            const auto addr{Lookup(host, port, /*fAllowLookup=*/false)};
             if (!addr) {
                 LogError("Could not lookup RPC bind address \"%s\" port %i "
                          "(only numeric addresses are allowed).", host, port);
@@ -1390,7 +1390,7 @@ bool InitHTTPServer()
     g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1));
 
     // Bind HTTP server to specified addresses
-    std::vector<BindAddress> endpoints{GetBindAddresses()};
+    auto endpoints{GetBindAddresses()};
     if (endpoints.empty()) {
         // GetBindAddresses() already emitted a LogError() before returning empty.
         return false;
> [a8e7faa](https://github.com/bitcoin/bitcoin/pull/36187/changes/a8e7faa47760528c1a1e20165a3567abbe323e21) _http: fail closed on partial binds_: nit: the initializers and ranges already have unambiguous types, so `auto` works for `endpoints`, both ports, the lookup result and the `-rpcbind` loop element. Reading the port with `GetArg<uint16_t>` also removes the `static_cast`, and `CheckHostPortOptions()` already rejects an out-of-range `-rpcport` at startup. <details> <summary>Deduce types supplied by initializers and ranges</summary> ```diff diff --git a/src/httpserver.cpp b/src/httpserver.cpp index adb85f43d3..070e14d402 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -220,7 +220,7 @@ static bool BindDefaultLoopbackAddresses() static std::vector<BindAddress> GetBindAddresses() { - uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))}; + auto http_port{gArgs.GetArg<uint16_t>("-rpcport", BaseParams().RPCPort())}; std::vector<BindAddress> endpoints; // Determine what addresses to bind to @@ -243,15 +243,15 @@ static std::vector<BindAddress> GetBindAddresses() LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect"); } } else { // Specific bind addresses - for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) { - uint16_t port{http_port}; + for (const auto& strRPCBind : gArgs.GetArgs("-rpcbind")) { + auto port{http_port}; std::string host; if (!SplitHostPort(strRPCBind, port, host)) { LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original); return {}; // empty } // Don't allow hostname lookups when binding to local interfaces. - const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)}; + const auto addr{Lookup(host, port, /*fAllowLookup=*/false)}; if (!addr) { LogError("Could not lookup RPC bind address \"%s\" port %i " "(only numeric addresses are allowed).", host, port); @@ -1390,7 +1390,7 @@ bool InitHTTPServer() g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1)); // Bind HTTP server to specified addresses - std::vector<BindAddress> endpoints{GetBindAddresses()}; + auto endpoints{GetBindAddresses()}; if (endpoints.empty()) { // GetBindAddresses() already emitted a LogError() before returning empty. return false; ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-12 08:42:43 +00:00

a8e7faa http: fail closed on partial binds:

nit: some of these messages quote the bind address and some don't. Single quotes throughout would make them consistent, and the lookup error would no longer need escaped double quotes.

Use single quotes around RPC bind addresses
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 80a0d97726..4ad082523b 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -257,8 +257,7 @@ static std::vector<BindAddress> GetBindAddresses()
                     endpoints.push_back({.addr = *addr, .required = true});
                 }
             } else {
-                LogError("Could not lookup RPC bind address \"%s\" port %i "
-                         "(only numeric addresses are allowed).", host, port);
+                LogError("Could not lookup RPC bind address '%s' port %i (only numeric addresses are allowed).", host, port);
                 return {}; // empty
             }
         }
@@ -1397,13 +1396,13 @@ bool InitHTTPServer()
     }
 
     for (const auto& [addr, required] : endpoints) {
-        LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
+        LogInfo("Binding RPC on address '%s'", addr.ToStringAddrPort());
         if (addr.IsBindAny()) {
             LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
         }
         auto result{g_http_server->BindAndStartListening(addr)};
         if (!result) {
-            const auto msg{strprintf("Binding RPC on %s address %s failed: %s",
+            const auto msg{strprintf("Binding RPC on %s address '%s' failed: %s",
                                      required ? "required" : "optional",
                                      addr.ToStringAddrPort(), result.error())};
             if (required) {
diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
index 2ca7a206c0..9ef2e5b6c9 100755
--- a/test/functional/rpc_bind.py
+++ b/test/functional/rpc_bind.py
@@ -68,7 +68,7 @@ class RPCBindTest(BitcoinTestFramework):
 
         with (
             socket.create_server(('127.0.0.1', self.defaultport)),
-            self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']),
+            self.nodes[0].assert_debug_log([f"Binding RPC on required address '127.0.0.1:{self.defaultport}' failed:"]),
         ):
             self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
 
> [a8e7faa](https://github.com/bitcoin/bitcoin/pull/36187/changes/a8e7faa47760528c1a1e20165a3567abbe323e21) _http: fail closed on partial binds_: nit: some of these messages quote the bind address and some don't. Single quotes throughout would make them consistent, and the lookup error would no longer need escaped double quotes. <details> <summary>Use single quotes around RPC bind addresses</summary> ```diff diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 80a0d97726..4ad082523b 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -257,8 +257,7 @@ static std::vector<BindAddress> GetBindAddresses() endpoints.push_back({.addr = *addr, .required = true}); } } else { - LogError("Could not lookup RPC bind address \"%s\" port %i " - "(only numeric addresses are allowed).", host, port); + LogError("Could not lookup RPC bind address '%s' port %i (only numeric addresses are allowed).", host, port); return {}; // empty } } @@ -1397,13 +1396,13 @@ bool InitHTTPServer() } for (const auto& [addr, required] : endpoints) { - LogInfo("Binding RPC on address %s", addr.ToStringAddrPort()); + LogInfo("Binding RPC on address '%s'", addr.ToStringAddrPort()); if (addr.IsBindAny()) { LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); } auto result{g_http_server->BindAndStartListening(addr)}; if (!result) { - const auto msg{strprintf("Binding RPC on %s address %s failed: %s", + const auto msg{strprintf("Binding RPC on %s address '%s' failed: %s", required ? "required" : "optional", addr.ToStringAddrPort(), result.error())}; if (required) { diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py index 2ca7a206c0..9ef2e5b6c9 100755 --- a/test/functional/rpc_bind.py +++ b/test/functional/rpc_bind.py @@ -68,7 +68,7 @@ class RPCBindTest(BitcoinTestFramework): with ( socket.create_server(('127.0.0.1', self.defaultport)), - self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']), + self.nodes[0].assert_debug_log([f"Binding RPC on required address '127.0.0.1:{self.defaultport}' failed:"]), ): self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.') ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-12 08:42:51 +00:00

a8e7faa http: fail closed on partial binds:

Since required already picks the branch, each branch can log its own message, which drops the temporary msg and its required ? "required" : "optional" ternary.

Inline required and optional failure messages
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 4ad082523b..3fcea1c04f 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -1402,11 +1402,8 @@ bool InitHTTPServer()
         }
         auto result{g_http_server->BindAndStartListening(addr)};
         if (!result) {
-            const auto msg{strprintf("Binding RPC on %s address '%s' failed: %s",
-                                     required ? "required" : "optional",
-                                     addr.ToStringAddrPort(), result.error())};
             if (required) {
-                LogError("%s", msg);
+                LogError("Binding RPC on required address '%s' failed: %s", addr.ToStringAddrPort(), result.error());
                 g_http_server->StopListening();
                 if (BindDefaultLoopbackAddresses()) {
                     LogError("Unable to bind default required IPv4 endpoint. Ensure the port is free "
@@ -1416,7 +1413,7 @@ bool InitHTTPServer()
                 }
                 return false;
             }
-            LogWarning("%s", msg);
+            LogWarning("Binding RPC on optional address '%s' failed: %s", addr.ToStringAddrPort(), result.error());
         }
     }
 
> [a8e7faa](https://github.com/bitcoin/bitcoin/pull/36187/changes/a8e7faa47760528c1a1e20165a3567abbe323e21) _http: fail closed on partial binds_: Since `required` already picks the branch, each branch can log its own message, which drops the temporary `msg` and its `required ? "required" : "optional"` ternary. <details> <summary>Inline required and optional failure messages</summary> ```diff diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 4ad082523b..3fcea1c04f 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -1402,11 +1402,8 @@ bool InitHTTPServer() } auto result{g_http_server->BindAndStartListening(addr)}; if (!result) { - const auto msg{strprintf("Binding RPC on %s address '%s' failed: %s", - required ? "required" : "optional", - addr.ToStringAddrPort(), result.error())}; if (required) { - LogError("%s", msg); + LogError("Binding RPC on required address '%s' failed: %s", addr.ToStringAddrPort(), result.error()); g_http_server->StopListening(); if (BindDefaultLoopbackAddresses()) { LogError("Unable to bind default required IPv4 endpoint. Ensure the port is free " @@ -1416,7 +1413,7 @@ bool InitHTTPServer() } return false; } - LogWarning("%s", msg); + LogWarning("Binding RPC on optional address '%s' failed: %s", addr.ToStringAddrPort(), result.error()); } } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-12 08:15:10 +00:00

a8e7faa http: fail closed on partial binds:

I don't think reuse_port=True is needed: create_server() already sets SO_REUSEADDR on POSIX, and both occupied-port cases pass without it on macOS and Linux. The characterization commit has the same flag.

nit: since this statement changes anyway, a parenthesized with gets rid of the weird trailing backslash.

Reserve the IPv4 port without SO_REUSEPORT
diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
index 8682b2581f..2ca7a206c0 100755
--- a/test/functional/rpc_bind.py
+++ b/test/functional/rpc_bind.py
@@ -66,8 +66,10 @@ class RPCBindTest(BitcoinTestFramework):
         if explicit_binds:
             extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
 
-        with socket.create_server(('127.0.0.1', self.defaultport), reuse_port=True), \
-             self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']):
+        with (
+            socket.create_server(('127.0.0.1', self.defaultport)),
+            self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']),
+        ):
             self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
 
     def run_allowip_test(self, allow_ips, rpchost, rpcport):
> [a8e7faa](https://github.com/bitcoin/bitcoin/pull/36187/changes/a8e7faa47760528c1a1e20165a3567abbe323e21) _http: fail closed on partial binds_: I don't think `reuse_port=True` is needed: `create_server()` already sets `SO_REUSEADDR` on POSIX, and both occupied-port cases pass without it on macOS and Linux. The characterization commit has the same flag. nit: since this statement changes anyway, a parenthesized `with` gets rid of the weird trailing backslash. <details> <summary>Reserve the IPv4 port without SO_REUSEPORT</summary> ```diff diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py index 8682b2581f..2ca7a206c0 100755 --- a/test/functional/rpc_bind.py +++ b/test/functional/rpc_bind.py @@ -66,8 +66,10 @@ class RPCBindTest(BitcoinTestFramework): if explicit_binds: extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]'] - with socket.create_server(('127.0.0.1', self.defaultport), reuse_port=True), \ - self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']): + with ( + socket.create_server(('127.0.0.1', self.defaultport)), + self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']), + ): self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.') def run_allowip_test(self, allow_ips, rpchost, rpcport): ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-12 08:15:20 +00:00

f103468 test: characterize partial HTTP binds:

nit: assert_equal(started, True) can never fail, since a failing start_node() already leaves the function before it. Dropping started and the initial credential_captured = False changes nothing, and the TODO fits on the start_node() line itself.

Remove dead startup state from the characterization
--- a/test/functional/rpc_bind.py
+++ b/test/functional/rpc_bind.py
@@ -69,12 +69,9 @@
             extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
 
         self.nodes[0].rpchost = '[::1]'
-        credential_captured = False
-        started = False
         with socket.create_server(('127.0.0.1', self.defaultport), reuse_port=True) as sock:
             sock.settimeout(0.1)
-            self.start_node(0, extra_args=extra_args)
-            started = True # Not set if start_node() raises FailedToStartError
+            self.start_node(0, extra_args=extra_args)  # TODO: an occupied RPC listener must abort startup to protect credentials
             cli = subprocess.Popen([
                 self.nodes[0].binaries.paths.bitcoincli,
                 f'-datadir={self.nodes[0].datadir_path}',
@@ -111,7 +108,6 @@
             self.stop_node(0)
         self.nodes[0].rpchost = None
 
-        assert_equal(started, True)  # TODO: an occupied RPC listener must abort startup to protect credentials
         assert_equal(credential_captured, True)  # TODO: a client credential must not reach another process's listener
 
     def run_allowip_test(self, allow_ips, rpchost, rpcport):
> [f103468](https://github.com/bitcoin/bitcoin/pull/36187/changes/f103468712e6985e670dbcc16b9810ec76bff9df) _test: characterize partial HTTP binds_: nit: `assert_equal(started, True)` can never fail, since a failing `start_node()` already leaves the function before it. Dropping `started` and the initial `credential_captured = False` changes nothing, and the TODO fits on the `start_node()` line itself. <details> <summary>Remove dead startup state from the characterization</summary> ```diff --- a/test/functional/rpc_bind.py +++ b/test/functional/rpc_bind.py @@ -69,12 +69,9 @@ extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]'] self.nodes[0].rpchost = '[::1]' - credential_captured = False - started = False with socket.create_server(('127.0.0.1', self.defaultport), reuse_port=True) as sock: sock.settimeout(0.1) - self.start_node(0, extra_args=extra_args) - started = True # Not set if start_node() raises FailedToStartError + self.start_node(0, extra_args=extra_args) # TODO: an occupied RPC listener must abort startup to protect credentials cli = subprocess.Popen([ self.nodes[0].binaries.paths.bitcoincli, f'-datadir={self.nodes[0].datadir_path}', @@ -111,7 +108,6 @@ self.stop_node(0) self.nodes[0].rpchost = None - assert_equal(started, True) # TODO: an occupied RPC listener must abort startup to protect credentials assert_equal(credential_captured, True) # TODO: a client credential must not reach another process's listener def run_allowip_test(self, allow_ips, rpchost, rpcport): ``` </details>
hodlinator (Migrated from github.com) reviewed 2026-11-13 14:56:14 +00:00
hodlinator (Migrated from github.com) left a comment
Latest push addresses https://github.com/bitcoin/bitcoin/pull/36187#discussion_r4543016954 and https://github.com/bitcoin/bitcoin/pull/36187#pullrequestreview-5871193906 + adds anonymous namespace to make `BindAddress` fully local to httpserver.cpp.
hodlinator (Migrated from github.com) commented 2026-11-13 13:28:56 +00:00

Thanks for finding this! Added the test and fixed in latest push, but I had to expose an accessor for CNetAddr::m_scope_id.

Thanks for finding this! Added the test and fixed in latest push, but I had to expose an accessor for `CNetAddr::m_scope_id`.
hodlinator (Migrated from github.com) commented 2026-11-13 14:49:26 +00:00

Good point regarding GetArg<uint16_t>()! Kept slightly more explicit local type info in the other cases for now.

Good point regarding `GetArg<uint16_t>()`! Kept slightly more explicit local type info in the other cases for now.
hodlinator (Migrated from github.com) commented 2026-11-13 13:44:01 +00:00

There's no clear winner to me, but guess avoiding an extra branch is nice and msg was just used in 2 places.

There's no clear winner to me, but guess avoiding an extra branch is nice and `msg` was just used in 2 places.
hodlinator (Migrated from github.com) commented 2026-11-13 13:37:19 +00:00
> `create_server()` already sets `SO_REUSEADDR` on POSIX True (https://docs.python.org/3/library/socket.html#socket.create_server), removed in latest push.
l0rinc (Migrated from github.com) approved these changes 2026-11-13 18:39:23 +00:00
l0rinc (Migrated from github.com) left a comment

ACK 44bcdbd1c6

If you need to touch this again, consider using a smaller reproducer in the characterization commit (showing that startup succeeds despite the occupied IPv4 port), with the full credential-capture proof in a collapsible section of the PR description as an optional demo. That would avoid removing all that code we just introduced in the earlier commit.

ACK 44bcdbd1c6bb8409434af09f3bfa0581b5867e42 If you need to touch this again, consider using a smaller reproducer in the characterization commit (showing that startup succeeds despite the occupied IPv4 port), with the full credential-capture proof in a collapsible section of the PR description as an optional demo. That would avoid removing all that code we just introduced in the earlier commit.
l0rinc (Migrated from github.com) commented 2026-11-13 18:26:04 +00:00

418aeaf http: Skip duplicate bind addresses:

This looked fishy: why compare internal CService state separately after ==? Extending the shared operator here looks tempting, but it would also change peer connection deduplication, inbound onion listener matching and AddrMan key lookup, so we definitely should not do it in this PR.
And if we do that, ordering and hashing should also be adjusted in a separate follow-up.

The explicit scope check seems fine here, but maybe we could add a comment explaining why it is needed, something like:

// CService equality ignores IPv6 scope IDs, but binding must distinguish interfaces
return *addr == e.addr && addr->GetScope() == e.addr.GetScope();
> [418aeaf](https://github.com/bitcoin/bitcoin/pull/36187/changes/418aeaf90c47738b707090d95d656352201c1fcb) _http: Skip duplicate bind addresses_: This looked fishy: why compare internal `CService` state separately after `==`? Extending the shared operator here looks tempting, but it would also change peer connection deduplication, inbound onion listener matching and AddrMan key lookup, so we definitely should not do it in this PR. And if we do that, ordering and hashing should also be adjusted in a separate follow-up. The explicit scope check seems fine here, but maybe we could add a comment explaining why it is needed, something like: ```C++ // CService equality ignores IPv6 scope IDs, but binding must distinguish interfaces return *addr == e.addr && addr->GetScope() == e.addr.GetScope(); ```
hodlinator (Migrated from github.com) reviewed 2026-11-14 09:57:10 +00:00
hodlinator (Migrated from github.com) commented 2026-11-14 09:57:10 +00:00

Agreed, I independently realized this while thinking it over again yesterday. Pushed a variation of the comment.
Also realized the "Don't allow hostname lookups when binding to local interfaces."-comment above applies to other Lookup() calls so extracted allow_names-variable and hoisted it up above.

Agreed, I independently realized this while thinking it over again yesterday. Pushed a variation of the comment. Also realized the "Don't allow hostname lookups when binding to local interfaces."-comment above applies to other `Lookup()` calls so extracted `allow_names`-variable and hoisted it up above.
l0rinc commented 2026-11-15 19:59:05 +00:00 (Migrated from github.com)

reACK 061eb6f434

Just the explanatory comment and the shared allow_names variable and the lambda capture cleanup since my last ack.

reACK 061eb6f43458d15bb12330b0667240a3a7d6e4da Just the explanatory comment and the shared `allow_names` variable and the lambda capture cleanup since my last ack.
hodlinator (Migrated from github.com) reviewed 2026-11-16 07:49:55 +00:00
Lines 236-237
hodlinator (Migrated from github.com) commented 2026-11-16 07:49:55 +00:00

Yes, it comes down to keeping the diffs clear vs avoiding unnecessary work in the case that IPv6 binding succeeds but then IPv4 binding fails. I guess optimizing for the end state after the PR is also an aspect in your favor. I'll swap the order if I need to re-touch, unless others are against the swap.

Yes, it comes down to keeping the diffs clear vs avoiding unnecessary work in the case that IPv6 binding succeeds but then IPv4 binding fails. I guess optimizing for the end state after the PR is also an aspect in your favor. I'll swap the order if I need to re-touch, unless others are against the swap.
fanquake commented 2026-11-16 11:02:31 +00:00 (Migrated from github.com)

cc @pinheadmz

cc @pinheadmz
janb84 (Migrated from github.com) reviewed 2026-11-18 15:02:02 +00:00
janb84 (Migrated from github.com) left a comment

re ACK 061eb6f434

There are some behavioral changes in startup, maybe consider adding a release-note (Ralph suggested the same, but cryptic in his reasoning).
The change that could use a release note is for Ipv6 only hosts, a host or jail without 127.0.0.1 / ipv4 used to start (on master) on ::1 alone. The same functionality now needs -rpcbind=[::1] -rpcallowip=::1 other wise the node will error out.

re ACK 061eb6f43458d15bb12330b0667240a3a7d6e4da There are some behavioral changes in startup, maybe consider adding a release-note (Ralph suggested the same, but cryptic in his reasoning). The change that could use a release note is for Ipv6 only hosts, a host or jail without 127.0.0.1 / ipv4 used to start (on master) on `::1` alone. The same functionality now needs `-rpcbind=[::1] -rpcallowip=::1` other wise the node will error out.
janb84 (Migrated from github.com) commented 2026-11-18 14:15:07 +00:00

Nit, non-block. Adding something like the test below will fix 2 of the gaps in test as reported by corecheck.


    def run_optional_ipv6_bind_test(self):
        self.log.info('Check that the node starts on IPv4 when the default IPv6 RPC address is already owned')
        self.nodes[0].rpchost = None
        with socket.create_server(('::1', self.defaultport), family=socket.AF_INET6):
            with self.nodes[0].assert_debug_log([f"Binding RPC on optional address '[::1]:{self.defaultport}' failed:"]):
                self.start_node(0, ['-disablewallet', '-nolisten'])
            assert_equal(set(get_bind_addrs(self.nodes[0].process.pid)), {(addr_to_hex('127.0.0.1'), self.defaultport)})
            self.stop_node(0)

    def run_unbindable_bind_test(self):
        self.log.info('Check that startup fails when an explicit RPC address cannot be bound, even if others succeed')
        # 192.0.2.1 (TEST-NET-1, RFC 5737) is not assigned to a local interface,
        # so bind() fails with EADDRNOTAVAIL rather than EADDRINUSE.
        extra_args = ['-disablewallet', '-nolisten', '-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=192.0.2.1']
        with self.nodes[0].assert_debug_log([
            f"Binding RPC on address '127.0.0.1:{self.defaultport}'",
            f"Binding RPC on required address '192.0.2.1:{self.defaultport}' failed:",
        ]):
            self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')

    def run_unresolvable_bind_test(self):
        self.log.info('Check that startup fails when an explicit RPC address is not numeric, even if others are')
        extra_args = ['-disablewallet', '-nolisten', '-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=localhost']
        with self.nodes[0].assert_debug_log(
            [f"Could not lookup RPC bind address 'localhost' port {self.defaultport} (only numeric addresses are allowed)."],
            unexpected_msgs=["Binding RPC on address"],  # fails before any bind is attempted
        ):
            self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')

Nit, non-block. Adding something like the test below will fix 2 of the gaps in test as reported by corecheck. ```suggestion def run_optional_ipv6_bind_test(self): self.log.info('Check that the node starts on IPv4 when the default IPv6 RPC address is already owned') self.nodes[0].rpchost = None with socket.create_server(('::1', self.defaultport), family=socket.AF_INET6): with self.nodes[0].assert_debug_log([f"Binding RPC on optional address '[::1]:{self.defaultport}' failed:"]): self.start_node(0, ['-disablewallet', '-nolisten']) assert_equal(set(get_bind_addrs(self.nodes[0].process.pid)), {(addr_to_hex('127.0.0.1'), self.defaultport)}) self.stop_node(0) def run_unbindable_bind_test(self): self.log.info('Check that startup fails when an explicit RPC address cannot be bound, even if others succeed') # 192.0.2.1 (TEST-NET-1, RFC 5737) is not assigned to a local interface, # so bind() fails with EADDRNOTAVAIL rather than EADDRINUSE. extra_args = ['-disablewallet', '-nolisten', '-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=192.0.2.1'] with self.nodes[0].assert_debug_log([ f"Binding RPC on address '127.0.0.1:{self.defaultport}'", f"Binding RPC on required address '192.0.2.1:{self.defaultport}' failed:", ]): self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.') def run_unresolvable_bind_test(self): self.log.info('Check that startup fails when an explicit RPC address is not numeric, even if others are') extra_args = ['-disablewallet', '-nolisten', '-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=localhost'] with self.nodes[0].assert_debug_log( [f"Could not lookup RPC bind address 'localhost' port {self.defaultport} (only numeric addresses are allowed)."], unexpected_msgs=["Binding RPC on address"], # fails before any bind is attempted ): self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.') ```
hodlinator commented 2026-11-18 20:53:45 +00:00 (Migrated from github.com)

Thanks for the review @janb84! As stated out-of-band, starting to write the release notes you suggested motivated me to look into being less harsh on IPv6-only hosts.

Upon failure to bind the IPv4 loopback port, we could create an IPv4 socket and try to bind it to a random ephemeral port. If that also fails, we could assume that we don't have an IPv4 stack at all and let the IPv6-only bind be sufficient. I'll need some more time to investigate this.

Thanks for the review @janb84! As stated out-of-band, starting to write the release notes you suggested motivated me to look into being less harsh on IPv6-only hosts. Upon failure to bind the IPv4 loopback port, we could create an IPv4 socket and try to bind it to a random ephemeral port. If that *also* fails, we could assume that we don't have an IPv4 stack at all and let the IPv6-only bind be sufficient. I'll need some more time to investigate this.
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!36187
No description provided.