Skip to content

Replace libevent with our own HTTP and socket-handling implementation - #35182

Merged
fanquake merged 29 commits into
bitcoin:masterfrom
pinheadmz:http-rewrite-30Apr2026
Jun 22, 2026
Merged

fanquake merged 29 commits into
bitcoin:masterfrom
pinheadmz:http-rewrite-30Apr2026

Conversation

@pinheadmz

@pinheadmz pinheadmz commented Apr 30, 2026 •

Copy link
Copy Markdown
Member

Continued from #32061.

This is a major component of removing libevent as a dependency of the project, by replacing the HTTP server used for RPC and REST with one implemented entirely within the Bitcoin Core codebase. The new HTTPServer class runs its own I/O thread, handling socket connections with code based on #30988, but tailored specifically for HTTP.

Commit strategy:

  • Isolate the existing libevent-based HTTP server in a namespace http_libevent
  • Implement HTTP in a new namespace http_bitcoin (classes like HTTPRequest, HTTPClient, etc...)
  • Switch bitcoind from the libevent server to the new server
  • Clean up (delete http_libevent)

RFC compliance

I ran https://www.http-probe.com/ against v31.0 release and this PR branch at commit ddefe42. While both HTTP servers failed several of the very picky compliance tests, the only differences in test results between the two branches is an improvement in the test results of the PR branch.

Raw test results:

Test result comparison:

Fuzz testing

libfuzzer

fuzzamoto

Integration testing:

I am testing the new HTTP server by forking projects that integrate with bitcoin via HTTP and running their integration tests with bitcoind built from this branch (on Github actions). I will continue adding integrations over time, and re-running these CI tests as this branch gets rebased:

  • ✅ lnd master at f21262dd6 tested with this branch at ddefe4263b

  • ✅ NodeJS rpc-bitcoin master at eb0c5da7d1094629cb4a381733cb01c9bb9a4608 tested with this branch at ddefe4263b

  • ✅ electrs master at d81dc35ae8f71c22b96cf23ee279b69683f29919 tested with this branch at ddefe4263b

  • ✅ eclair master at 2dda79468a8b69a2acf7962cdac63245f7cc3ee8 tested with this branch at ddefe4263b

  • ✅ corepc master at 818e5f2929ea5113176150b2d9f7c0248992d99c tested with this branch at ddefe4263b

  • ✅ bitcoinjs-lib master at ab9fad5978bc1f4fb6542d1cde903d4427c3344e tested with this branch at ddefe4263b

  • ✅ NodeJS bitcoin-core master at 24f3d0be7ab73089542de42cc8e31903727dbdf8 tested with this branch at ddefe4263b

Benchmarks

To get a general idea of server speed vs. master I ran the functional test suite on all three platforms, three trials each, from the first and last commit of this branch. The first commit represents master, but adds a few extra functional tests, so the overall suite is the same in the last commit.

Full results

Summary:

Tested at 37ff331f60

There appears to be a 1-2% slow down on Ubuntu and MacOS but a 5% speed up on Windows

Ubuntu - master Ubuntu - branch MacOS - master Macos - branch Windows - master Windows - branch
AVERAGE 253 260 187 190 521 493
% diff to master 2.766798419 1.604278075 -5.37428023

@DrahtBot

DrahtBot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35182.

Reviews

See the guideline for information on the review process.

Type Reviewers
ACK vasild, theStack
Concept ACK rkrux, fanquake, 0xB10C, hodlinator
Stale ACK fjahr, janb84

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:

  • #35387 (logging: make trace logging easily usable by ryanofsky)
  • #35355 (Use atomics for determining whether trace logging is enabled by ajtowns)
  • #35322 (logging: streamline Logger state and drop redundant methods by ryanofsky)
  • #34411 ([POC] Full Libevent removal by fanquake)
  • #34038 (logging: replace -loglevel with -trace, expose trace logging via RPC by ajtowns)
  • #26022 (Add util::ResultPtr class by ryanofsky)
  • #25665 (refactor: Add util::Result failure types and ability to merge result values by ryanofsky)

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

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • Lookup(address_string, port, false) in src/httpserver.cpp

2026-06-22 09:48:44

@vasild vasild left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK e728c71f5adafdcbc4b6a29d154ea5705003ba60

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK e728c71f5adafdcbc4b6a29d154ea5705003ba60
-----BEGIN PGP SIGNATURE-----

iQQzBAEBCAAdFiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmnzjdkACgkQVN8G9ktV
y7/UOSAAgi7UxBy3GrlhfUNH2hLetiZDtswp6EWjSgcRj3GjYUdKjhikRaED4zqc
bOSh942CdU0LFTm14PqZ4bhybqjfMe8mZmvSoBWx+kGJKyiNOWM0P4qDzscKq5IC
adAvv6A9SxzfnFSskf1aM97X3WeFgTBeT4S2ycZ6uurdqCCbfwtMtGgj0wqBw+Na
r8p17RjJUiz78FNPaQ5Y0GDXsKhiTbs1OXZ8Tn2qtviy1QjAyDZLxo9tR768Cf8d
32VcOMRoxBQ70fCtds5Zne+CjlGlAqw4P5tCKd337L2/3wO+uxwIAlAQHu1MM41f
itFV8+d34lM7VdsyWTNYYgc0dDqgvUroNZdTHwGJJzEni3RbTYv4H6bW13Av76ci
ncUOYJFTW+XexMLKvl8QZaWNASKZGPHtp9jciOvEtORRIdPDmEJxgLpQEYT3ITES
oI5uLCd9uGcUK/zOvIdfUDMdL30fiB0YCcRU9kW3DebdYAWdBdovB/S0NP0VP0J2
F18MHXGybUektYyqYavjuRzBE+lmfZlHW3cblUvbVTzU6/BeCiJHDDaDiRYcV3ba
qz6D+JU67f+Q8HxDk/oLXfHRQYODn847USgaFuc9TqK495+jEyBfSNmGWGZPVMAX
GA6hTPmVq5z6pqoKTbvF1v4aCv4k6n+2EJBH1o4N7Q+fHxNVlzOsff/yCiZ88oaw
W1aM2Co2pJ2YESxddUR1QnpbP9JFMRAlJYzGkDfMjD8rLKZppQm2v4fnu0R5xZxX
Q6bBSeRhzBs+QLs180rzluUNJ8laIAzAmuJe4zOH6MPT/Js7siogj1NYQK4/t123
3/QQiSFWJ1hHbg8D6M5wAaBjpEoxzJ825xjMc6zud7UjHlslBYPsWbYxvz2gDZ8r
5gbsqoprGOteHvc0eyuDf7yxLoSdqUYtl9EXwZmLt20edBcbDHW49hGd6JsTCZk8
MNGOISi4MiXkPjOa/XBil3IN25YuB4rAr4Bx71D/ptgl8JjuVGU6HIYpoySMj89D
uWR/IV15UcPXQBAhJsh7ZCOsY9MzfQ8QLskiLsX9Mfpe6/MOfi1N3XFWjozehPkq
YzQ/82BK8HwmMJ/hXIppJhlwWncHvnQrtZ1NSsR8Bs0ca86GZKHR6s7LFFupej40
OWEI6cNzSk2hUosNgttmcHdjznIwxNcDF7wfVDW1yc7h9XEUUgiMzU69E53J6Hgk
GTW92NM/kw5kvY54ghehJDvNLY8Pq1PblIOZmXakMYrWpDxYlu2l0zN+sYZ7sdkV
JfU7yWtymLHrg0TdIPuTzuhTrvpQTksYO/vo3hyJS/5XqrIWbyEgc+LtZvnIl8wY
Cf6tnL9dxbIWtp0UoqzGrooYBUvXlA==
=2kAW
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

Comment thread src/httpserver.h Resolved
Comment thread src/httpserver.cpp Resolved
Comment thread src/httpserver.cpp Resolved
@pinheadmz
pinheadmz force-pushed the http-rewrite-30Apr2026 branch from e728c71 to 0a4929c Compare April 30, 2026 19:51

@pinheadmz pinheadmz left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

push to 0a4929c0bf:

Address feedback from @vasild

Comment thread src/httpserver.h Resolved
Comment thread src/httpserver.cpp Resolved
Comment thread src/httpserver.cpp Resolved
@pinheadmz
pinheadmz force-pushed the http-rewrite-30Apr2026 branch from 0a4929c to 5952e48 Compare April 30, 2026 20:14
@pinheadmz

Copy link
Copy Markdown
Member Author

push to 5952e48ff4:

rebase on master to fix CI (see #35186)

Comment thread src/httpserver.cpp Resolved
Comment thread src/test/httpserver_tests.cpp Resolved
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/25186108957/job/73843745290
LLM reason (✨ experimental): CI failed because IWYU reported missing/incorrect includes (auto-fix required) and the job was forced to fail (Failure generated from IWYU).

Hints

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

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

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

  • An intermittent issue.

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

@rkrux rkrux left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK 5952e48ff4490e3c0607bd34284112bcdbdeee05, will review

Can update the developer notes as well in this PR by replacing the libevent occurrences with the new one here:

- [ThreadHTTP (`b-http`)](https://doxygen.bitcoincore.org/httpserver_8cpp.html#abb9f6ea8819672bd9a62d3695070709c)
: Libevent thread to listen for RPC and REST connections.
- [HTTP worker threads (`b-http_pool_x`)](https://doxygen.bitcoincore.org/httpserver_8cpp.html#a2ad0a49dc9b5e8117c0dee98c24187d8)
: Threads to service RPC and REST requests.
- [Indexer threads (`b-txindex`, etc)](https://doxygen.bitcoincore.org/class_base_index.html#a96a7407421fbf877509248bbe64f8d87)
: One thread per indexer.
- [SchedulerThread (`b-scheduler`)](https://doxygen.bitcoincore.org/class_c_scheduler.html#a14d2800815da93577858ea078aed1fba)
: Does asynchronous background tasks like dumping wallet contents, dumping
addrman and running asynchronous validationinterface callbacks.
- [TorControlThread (`b-torcontrol`)](https://doxygen.bitcoincore.org/torcontrol_8cpp.html#a52a3efff23634500bb42c6474f306091)
: Libevent thread for tor connections.

@vasild vasild left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 5952e48ff4490e3c0607bd34284112bcdbdeee05

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 5952e48ff4490e3c0607bd34284112bcdbdeee05
-----BEGIN PGP SIGNATURE-----

iQQzBAEBCAAdFiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmn0arQACgkQVN8G9ktV
y7+8Lx/9G3dv9qVk1OA65C7SeNOOMc/jE2gXqkmhSQ6M9SKzrsUjBAetZb5vH7Q1
XiVOc7WKC2UKXWm7kvl0+LoBNpI2T33KkAE+WUsD82AgFHIlt+vWWlqCDBRbrrVq
iKOPBcr4WJL7vvvs/x86+w8J8kGvZVATDijujqm5k3SP5FimJ6eGSw4cStrp0yrb
Jm0ZXAwT5Aplg/7w496KxvR8W1+n9af8RX8aoWl3Ooc6XSd+tlFrM8sSDxCumekB
QQmW5PdBlr9n40kMXJd42ItcbV35fZSlIYafH9Zgj3N9M4W3aV5w4CiVVr9sd0tR
oH2KTSV8L+S8RnM/O6v3DQmj9vL0cPxYl2gV5P25wQozz3KzOdMS7wRnYPEg5+qj
UQPr7cSMf31PzolScHbGsxjZNYpvHy5Db3IJ0coG6wC2Cv1ARV2K0XF5JhyvtmYS
3KWOMtelQ52rYzmHgG1QDDYn9LL8rcEQbHGeBRunwQiiutG/VMAMnfPAeUamNj3Y
QsNWV3NQwTfbQCM8P8Pwso5k5k53sh0eOGGofsPh2q7fLwS1WIRjzikAOVjPDThJ
JF57PPcgC3Zq0YmDKWyHa7fi7WiYDAzYVE+Z8ML65efhFQpQCoE4dvZalj/jCDWV
/CfSTyuEAAsJJpDqLV5NO6bJcxbYPdcb1KmMrgMjKkNNUw8RPP8nYucjOHTHu8ku
CT9y23+uB6p5uphVaRk6Ay8/yolucaHWx/ykBp0gldU2bb/PO2sTvl/pWJ6mAl+g
+t5Ei89CvbdzjvOIbHOEP7Oiim52ZPuYQ9owr85v1tCkdZHBRJYf1BuxI2RefMAo
EikQk35kDqk0fW3+uY4OTiG21bnvbK1R/ISXtmrX1tbmwBCAuyr3CfXv0dxqsKqM
BQW5vf/5vMAfYCepzB0xBrAL+nb71m5IIiTOtuTZLFboNdt6klOv9W8ksJvjvtNg
4crJwWsL8zx9xdCgoashHQ55kuNnKfaCXt6Z8DGLxtfQKRiPFW+06ZVaq9dkhBmO
vjmqDej2Tiic9bWIDgUhwca+FP4KRRwx7bEB6P4tcA/GDRRfr6RiKWiMjCmvqNwS
jF/vaXMa7kHp/bbF2qJVWtKg14kJMBlsEDMdfXtgccs38lDehNqZRQHHVp/fyKth
IIp5tRjqsVInakGkpuDvzEQxYxOgtxrc7/7L7ZBKHC/28dZL1JtL92BlHeO0g3mb
QlaCAyJnXcg5lhN03VtjKuGFrRQ7mRS1DfUucN6D7LaqP2k4P4gqM+QjwA4DnfiI
d9OecGJleocumnbFfaMsWOgKnS1T2TFhojxnGxCY31+HpnR0Kzb7D7n1srEHOH1t
e9YQXXclQIn+SwIlERiph5QNPimXCA==
=xzuk
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

@DrahtBot
DrahtBot requested a review from rkrux May 1, 2026 08:56
@b-l-u-e

b-l-u-e commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

i noticed a behavior that PUT is being treated as a known HTTPRequestMethod but the HTTP dispatch layer only rejects UNKNOWN methods. so PUT / is allowed through the registered path handler and is later rejected by JSON-RPC rather than being rejected at the HTTP layer like other unsupported methods.

i tested the behavior:

 curl -i --user user:pass -X PUT \
  -H 'Content-Type: application/json' \
  --data '{"method":"getblockcount","params":[]}' \
  http://127.0.0.1:18443/
echo
HTTP/1.1 405 Method Not Allowed
Date: Fri, 01 May 2026 12:19:35 GMT
Content-Length: 41
Content-Type: text/html; charset=ISO-8859-1

JSONRPC server handles only POST requests

@pinheadmz

Copy link
Copy Markdown
Member Author

@b-l-u-e

PUT is being treated as a known HTTPRequestMethod

I think this is correct, and on master with libevent your curl command has the same result. In the future bitcoin might support an HTTP API with PUT so I don't think it needs to be rejected here. Also note there is a functional test in this PR that covers the more suspicious methods:

    def check_disallowed_http_methods(self):
        self.log.info("Check that unsafe or unsupported HTTP methods are rejected")
        for method in ['TRACE', 'CONNECT', 'DELETE', 'PATCH', 'OPTIONS']:

@b-l-u-e

b-l-u-e commented May 1, 2026

Copy link
Copy Markdown
Contributor

I think this is correct, and on master with libevent your curl command has the same result. In the future bitcoin might support an HTTP API with PUT so I don't think it needs to be rejected here. Also note there is a functional test in this PR that covers the more suspicious methods:

    def check_disallowed_http_methods(self):
        self.log.info("Check that unsafe or unsupported HTTP methods are rejected")
        for method in ['TRACE', 'CONNECT', 'DELETE', 'PATCH', 'OPTIONS']:

ahh yes it was an existing behavior confirmed with libevent and yeah these methods carries more risk as well thanks for clarificaton

@b-l-u-e

b-l-u-e commented May 1, 2026

Copy link
Copy Markdown
Contributor

i think theres data race on m_request_dispatcher during shutdown
when SetRequestHandler is called from the main thread during InterruptHTTPServer() while the I/O thread is still inside MaybeDispatchRequestsFromClient invoking the same function

heres main thread during shutdown

diff --git a/src/httpserver.h b/src/httpserver.h
+++ b/src/httpserver.h
@@ -0,0 +238,1 @@
+    void SetRequestHandler(std::function<void(std::unique_ptr<HTTPRequest>&&)> func) { m_request_dispatcher = func; }

here were its called from

+++ b/src/httpserver.cpp
@@ -0,0 +1195,7 @@
+void InterruptHTTPServer()
+{
+    LogDebug(BCLog::HTTP, "Interrupting HTTP server");
+    if (g_http_server) {
+        // Reject all new requests
+        g_http_server->SetRequestHandler(RejectRequest);
+    }

HTTP I/O thread

+++ b/src/httpserver.cpp
@@ -0,0 +977,5 @@
+    if (!client->m_req_queue.empty()) {
+        client->m_req_busy = true;
+        m_request_dispatcher(std::move(client->m_req_queue.front()));
+        client->m_req_queue.pop_front();
+    }

called from I/O thread started by StartSocketsThreads()

+++ b/src/httpserver.cpp
@@ -0,0 +709,5 @@
+void HTTPServer::StartSocketsThreads()
+{
+    m_thread_socket_handler = std::thread(&util::TraceThread,
+                                          "http",
+                                          [this] { ThreadSocketHandler(); });
output
build-tsan/tsan.log.115918
2:WARNING: ThreadSanitizer: data race (pid=115918)
6:    #2 http_bitcoin::HTTPServer::MaybeDispatchRequestsFromClient(std::shared_ptr<http_bitcoin::HTTPClient> const&) const /home/user/projects/bitcoin/src/httpserver.cpp:979 (test_bitcoin+0x13e581b)
26:    #3 http_bitcoin::HTTPServer::SetRequestHandler(std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>) /home/user/projects/bitcoin/src/httpserver.h:238 (test_bitcoin+0x90c1c6)
100:SUMMARY: ThreadSanitizer: data race /usr/include/c++/13/bits/std_function.h:247 in std::_Function_base::_M_empty() const
103:WARNING: ThreadSanitizer: data race (pid=115918)
106:    #1 http_bitcoin::HTTPServer::MaybeDispatchRequestsFromClient(std::shared_ptr<http_bitcoin::HTTPClient> const&) const /home/user/projects/bitcoin/src/httpserver.cpp:979 (test_bitcoin+0x13e583c)
126:    #3 http_bitcoin::HTTPServer::SetRequestHandler(std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>) /home/user/projects/bitcoin/src/httpserver.h:238 (test_bitcoin+0x90c213)
200:SUMMARY: ThreadSanitizer: data race /usr/include/c++/13/bits/std_function.h:591 in std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>::operator()(std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&) const
203:WARNING: ThreadSanitizer: data race (pid=115918)
209:    #4 http_bitcoin::HTTPServer::MaybeDispatchRequestsFromClient(std::shared_ptr<http_bitcoin::HTTPClient> const&) const /home/user/projects/bitcoin/src/httpserver.cpp:979 (test_bitcoin+0x13e5849)
229:    #3 http_bitcoin::HTTPServer::SetRequestHandler(std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>) /home/user/projects/bitcoin/src/httpserver.h:238 (test_bitcoin+0x90c17d)
303:SUMMARY: ThreadSanitizer: data race /usr/include/c++/13/bits/invoke.h:60 in __invoke_impl<void, httpserver_tests::race_set_request_handler_during_dispatch::test_method()::<lambda(std::unique_ptr<http_bitcoin::HTTPRequest>&&)>&, std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> > >

build-tsan/tsan.log.45095
2:WARNING: ThreadSanitizer: data race (pid=45095)
6:    #2 http_bitcoin::HTTPServer::MaybeDispatchRequestsFromClient(std::shared_ptr<http_bitcoin::HTTPClient> const&) const /home/user/projects/bitcoin/src/httpserver.cpp:979 (test_bitcoin+0x13e581b)
26:    #3 http_bitcoin::HTTPServer::SetRequestHandler(std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>) /home/user/projects/bitcoin/src/httpserver.h:238 (test_bitcoin+0x90c385)
100:SUMMARY: ThreadSanitizer: data race /usr/include/c++/13/bits/std_function.h:247 in std::_Function_base::_M_empty() const
103:WARNING: ThreadSanitizer: data race (pid=45095)
106:    #1 http_bitcoin::HTTPServer::MaybeDispatchRequestsFromClient(std::shared_ptr<http_bitcoin::HTTPClient> const&) const /home/user/projects/bitcoin/src/httpserver.cpp:979 (test_bitcoin+0x13e583c)
126:    #3 http_bitcoin::HTTPServer::SetRequestHandler(std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>) /home/user/projects/bitcoin/src/httpserver.h:238 (test_bitcoin+0x90c213)
200:SUMMARY: ThreadSanitizer: data race /usr/include/c++/13/bits/std_function.h:591 in std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>::operator()(std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&) const
203:WARNING: ThreadSanitizer: data race (pid=45095)
209:    #4 http_bitcoin::HTTPServer::MaybeDispatchRequestsFromClient(std::shared_ptr<http_bitcoin::HTTPClient> const&) const /home/user/projects/bitcoin/src/httpserver.cpp:979 (test_bitcoin+0x13e5849)
229:    #3 http_bitcoin::HTTPServer::SetRequestHandler(std::function<void (std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> >&&)>) /home/user/projects/bitcoin/src/httpserver.h:238 (test_bitcoin+0x90c17d)
303:SUMMARY: ThreadSanitizer: data race /usr/include/c++/13/bits/invoke.h:60 in __invoke_impl<void, httpserver_tests::race_set_request_handler_during_dispatch::test_method()::<lambda(std::unique_ptr<http_bitcoin::HTTPRequest>&&)>&, std::unique_ptr<http_bitcoin::HTTPRequest, std::default_delete<http_bitcoin::HTTPRequest> > >

Comment thread src/httpserver.cpp Resolved
@pinheadmz
pinheadmz force-pushed the http-rewrite-30Apr2026 branch from 5952e48 to 2c1deb6 Compare May 4, 2026 17:39

@pinheadmz pinheadmz left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

push to 2c1deb6329:

Address feedback from @janb84 and @b-l-u-e. Fix a race condition and chunked transfer edge case.

i think theres data race on m_request_dispatcher during shutdown

Great catch. I fixed this by putting a lock on m_request_dispatcher

Can update the developer notes as well in this PR by replacing the libevent occurrences with the new one here:

Added this change and also fixed the torcontrol thread in which libevent was removed by #34158!

Comment thread src/httpserver.cpp Resolved
Comment thread src/httpserver.cpp Resolved
maflcko pushed a commit to bitcoin-core/qa-assets that referenced this pull request Sep 23, 2026
LoadBody()'s Transfer-Encoding: chunked branch has been in master since
bitcoin/bitcoin#35182, and bitcoin/bitcoin#35759 added an assertion in
the http_request target for the body that branch produces. Neither one
runs against the corpus here: of the 146 http_request inputs in main,
none enters the chunked branch and none reaches that assertion.

Getting there needs the header name and the value together inside an
otherwise valid request, and the fuzzer does not find that on its own.
Against master's target, seeded from the current corpus, neither 1.66M
executions with fuzz_dicts/http_request.dict nor 1.79M with "chunked"
added to it entered the branch, both with -use_value_profile=1 and
-max_len=32768.

Seeded with the current corpus plus one hand-written chunked request and
run for the 100 minutes generate_corpus uses, 15.7M executions, then
merged back with the flags merge_inputs uses. Of the 120 inputs, 52
enter the chunked branch and 3 reach the assertion from #35759; the rest
are what that run turned up along the way.
pmazzocchi added a commit to btclib-org/functional-tests that referenced this pull request Oct 15, 2026
A bare `#35182` names an issue of this repository. Write it as
`bitcoin/bitcoin#35182`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: pmazzocchi <[email protected]>
pmazzocchi pushed a commit to btclib-org/functional-tests that referenced this pull request Oct 15, 2026
…) (#465)

`test_noncontinuous_headers_msg` joins
`p2p_invalid_messages_misbehaving_test.py` and asks for `Capability.MINE`.
`p2p_nobloomfilter_messages.py`'s filtered-block step and
`interface_http.py`'s `check_excessive_request_size` each get a module of
their own. Each wire half reads the disconnect or the HTTP answer. Each log
half asks for `Capability.DEBUG_LOG`.

The filtered-block and HTTP steps test changes in Core's `master` and
`v32.0rc1`: bitcoin/bitcoin#35832 and bitcoin/bitcoin#35182. The pinned
`v31.1` keeps the peer, answers 404 to the request with many short header
lines, and writes no `HTTPResponse` line. So each of their bodies reads
the build's `getnetworkinfo` `version` (ISS 35). btclib-node behaves as
`v31.1` does there. It is held to `master`'s claim, as the other per-build
bodies hold it, so its wire rows for both steps read fail:
btclib-org/btclib-node#1949 and btclib-org/btclib-node#1950.

`BitcoindAdapter` starts with `-debug=http`, the category of the
`HTTPResponse` line.

`TF2.md` gains the rows and their entries, and `btclib_node_verdict.py`
maps the new tests to the rows. The misbehaving modules' docstrings count
none of their checks, and name `check_headers_pow` as where a refused
`headers` message goes on btclib-node. The btclib-node runners of the
misbehaving, `dropped` and `p2p_handshake` modules expect no failure: PyPI's
`2026.10.8` and `main` pass those wire checks, and their rows read pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Ferdinando Ametrano <[email protected]>
Signed-off-by: pmazzocchi <[email protected]>
pmazzocchi added a commit to btclib-org/btclib-node that referenced this pull request Oct 15, 2026
…wn server's (closes #1950)

Two Core releases count the 8192-octet limit on a request's header
section in different ways:

- v31.1's libevent counts every line without its ending, the request
  line included;
- Core's own HTTP server, which replaces libevent from v32.0rc1
  (bitcoin/bitcoin#35182), counts the field lines with their endings,
  the empty line after them included and the request line left out,
  and a chunked body's trailer on from them (`HTTPHeaders::Read`, read
  at bitcoin/bitcoin@cce32b1687). Past it, it answers 400 and
  disconnects.

A header section of many short lines passes the first count and not the
second, which is the request Core's `check_excessive_request_size`
expects a 400 for.

This node keeps libevent's count. Holding the header section to both
counts turns `integration-bitcoind` red on
`rpc_framing_test.py::test_the_answer_is_bitcoind_s[size-8192-many-lines]`:
bitcoind v31.1.0, the release that workflow pins, answers that request.
The comment beside `MAX_HEADER_BYTES` says so, and issue #1972 is the
change for a v32 pin.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: pmazzocchi <[email protected]>
pmazzocchi added a commit to btclib-org/btclib-node that referenced this pull request Oct 15, 2026
…wn server's (closes #1950)

Two Core releases count the 8192-octet limit on a request's header
section in different ways:

- v31.1's libevent counts every line without its ending, the request
  line included;
- Core's own HTTP server, which replaces libevent from v32.0rc1
  (bitcoin/bitcoin#35182), counts the field lines with their endings,
  the empty line after them included and the request line left out,
  and a chunked body's trailer on from them (`HTTPHeaders::Read`, read
  at bitcoin/bitcoin@cce32b1687). Past it, it answers 400 and
  disconnects.

A header section of many short lines passes the first count and not the
second, which is the request Core's `check_excessive_request_size`
expects a 400 for.

This node keeps libevent's count. Holding the header section to both
counts turns `integration-bitcoind` red on
`rpc_framing_test.py::test_the_answer_is_bitcoind_s[size-8192-many-lines]`:
bitcoind v31.1.0, the release that workflow pins, answers that request.
The comment beside `MAX_HEADER_BYTES` says so, and issue #1972 is the
change for a v32 pin.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: pmazzocchi <[email protected]>
pmazzocchi added a commit to btclib-org/btclib-node that referenced this pull request Oct 15, 2026
…wn server's (closes #1950) (#1977)

Core counts the 8192-octet limit on a request's header section two
ways:

- v31.1's libevent counts every line without its ending, the request
  line included;
- Core's own HTTP server, which replaces libevent from v32.0rc1
  (bitcoin/bitcoin#35182), counts the field lines with their endings,
  the empty line after them included and the request line left out,
  and a chunked body's trailer on from them (`HTTPHeaders::Read`, read
  at bitcoin/bitcoin@cce32b1687). Past it, it answers 400 and
  disconnects.

A header section of many short lines passes the first count and not the
second, which is the request Core's `check_excessive_request_size`
expects a 400 for.

This node keeps libevent's count. Holding the header section to both
counts turns `integration-bitcoind` red on
`rpc_framing_test.py::test_the_answer_is_bitcoind_s[size-8192-many-lines]`:
bitcoind v31.1.0, the release that workflow pins, answers that request.
The comment beside `MAX_HEADER_BYTES` says so, and issue #1972 tracks the
change for a v32 pin.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: pmazzocchi <[email protected]>
sedited added a commit that referenced this pull request Oct 19, 2026
2abf671 http: Flatten control flow in HTTPRemoteClient::ShouldDisconnect() (Hodlinator)
5b98d56 test: Verify behavior of HTTPRemoteClient::ShouldDisconnect() (Hodlinator)
59a3e88 refactor: Switch client idle timeout to mockable clock (Hodlinator)
5fba330 refactor: Rename MaybeDisconnect() to ShouldDisconnect() and make it const (Hodlinator)
cb8f4b0 http: Add log message for remaining case where we set m_disconnect = true (Hodlinator)

Pull request description:

  ### Issues

  #35182 had 1 case where we flag a client for disconnect where we do not log the reason.

  #35829 introduced the somewhat poorly named non-`const` `HTTPRemoteClient::MaybeDisconnect()`. It also lacks testing.

  The control-flow in `MaybeDisconnect()/ShouldDisconnect()` is somewhat complex. #35829 (comment)

  ### Commits solving these issues in same order

  * http: Add log message for remaining case where we set `HTTPRemoteClient::m_disconnect = true`
  * refactor: Rename `MaybeDisconnect()` to `ShouldDisconnect()` and make it `const`
  * refactor: Enable mocking the time around `ShouldDisconnect()`
  * test: Add test for behavior of `ShouldDisconnect()`
  * refactor: Flatten control flow in `ShouldDisconnect()`

ACKs for top commit:
  pinheadmz:
    ACK 2abf671
  winterrdog:
    reACK 2abf671
  sedited:
    ACK 2abf671

Tree-SHA512: eb5d16d50f80fb31abc21134dddba9b23469b57a4846f2f80fd882e83e87f3c29b076d0f4a871ff6f7f629c2037e7a45fff27ac370314ba69ba7832d4f3a1c58
ajtowns pushed a commit to ajtowns/bitcoin that referenced this pull request Oct 23, 2026
…me it to bitcoin_http

http_bitcoin was mostly used during bitcoin#35182 to distinguish from http_libevent counterpart:
- The http_libevent namespace was introduced around the legacy code in 89c54ae.
- The http_bitcoin namespace was introduced in 68b5d28 and extended in subsequent commits.
- The http_libevent namespace together with code it contained was removed in 8c1eea0.

bitcoin_http is a better name as it is Bitcoin Core's implementation of the HTTP protocol, not HTTP protocol's implementation of bitcoin 402 payment required codes or anything like that.
The namespace only remains for a few constants and a type which don't have HTTP in their names.
fanquake added a commit that referenced this pull request Nov 16, 2026
…_http.py

75a23e7 test: drop flaky "server too slow" check from interface_http.py (Matthew Zipkin)

Pull request description:

  Closes #36755

  To cover `-rpcservertimeout` behavior our test expected the Bitcoin Core HTTP server to disconnect the test framework client after the configured duration but also *before* a somewhat arbitrary upper bound. This was helpful during development of #35182 but has led to false negatives in CI on platforms that are just plain slow.

  Solve the flakiness by simply deleting the test case. Note that a regression is still caught by both the functional test and unit test suite. #36159 added a mock clock in the unit test to assert the disconnect timing. A server with no timeout would also fail the functional test which will time out during `sock.recv()` waiting for the EOF.

  Both regression test failures can be observed on top of this branch by disabling rpcservertimeout:

  ```diff
  diff --git a/src/httpserver.cpp b/src/httpserver.cpp
  index 069eace..7a090c4ca8 100644
  --- a/src/httpserver.cpp
  +++ b/src/httpserver.cpp
  @@ -1205,7 +1205,7 @@ bool HTTPRemoteClient::ShouldDisconnect(MockableSteadyClock::time_point now, std
                    "HTTP client idle timeout %s (id=%llu)",
                    m_origin,
                    m_id);
  -        return true;
  +        return false;
       // Disconnect this client because the server is shutting down and we need to
       // disconnect all clients... Unless the client is still being handled by a
       // worker thread, in which case we'd rather continue the I/O loop (but might

  ```

ACKs for top commit:
  maflcko:
    lgtm ACK 75a23e7
  Pranav-error:
    tACK 75a23e7. Ran `interface_http.py` with the PR and it passes. With the mutant from the description, it fails with a `TimeoutError` after about 71 seconds in `recv_raw`.

Tree-SHA512: 61ad6efcc0a8dc6141f8bdd28b1a8f62d9f89b162796c4bffe605867f0b67617b764a0ff071318bbc81631fc407ea1c8e7608d533627758bf7c752df10c9a5bb
mxaddict pushed a commit to mxaddict/navio-core that referenced this pull request Nov 29, 2026
Replace libevent-based approach with using the Sock class and CThreadInterrupt.

Backport of bitcoin#34158 (upstream
commit eae193e). Adapted: navio's logger does not add a missing
newline (bitcoin#30929 is not ported), so the new log lines end in \n,
and lines that only moved keep navio's LogPrint/LogPrintf. The receive
buffer is a std::string read with the string_view LineReader and
Consumed(), the form upstream reached in bitcoin#35182 and bitcoin#35828,
whose LineReader changes navio already has. Context: no PoW retry,
TOR_REPLY_* constants or std::bind_front callbacks. Upstream's
std::span parameters use navio's Span: libc++ 14, which navio's clang-14
CI jobs build with, has no std::span constructor from a container.
(cherry picked from commit eae193e)
mxaddict pushed a commit to mxaddict/navio-core that referenced this pull request Nov 30, 2026
Backport of bitcoin#35182 (upstream
commit 0cdbb19). Adapted: only the LineReader change itself; navio
has neither the bitcoin-cli HTTP client nor the libevent-free torcontrol
that upstream also updated here, so those hunks are dropped. Ported as a
prerequisite of bitcoin#35828, which builds on it.

(cherry picked from commit 0cdbb19)

Co-authored-by: Hodlinator <[email protected]>
mxaddict pushed a commit to mxaddict/navio-core that referenced this pull request Nov 30, 2026
The utility can not be opinionated about CR or SP on either end of a
line it reads. That decision is up to the caller and in fact in the
case of HTTP should be allowed in some places and rejected in others.

Replace TrimStringView() with more surgical operation.

Backport of bitcoin#35182 (upstream
commit 5aa3629). Adapted: navio lacks RemoveSuffixView (added
upstream in bitcoin#30485), so its two calls are written out with
ends_with and remove_suffix, to the same effect. Ported as a
prerequisite of bitcoin#35828, which replaces this code.

(cherry picked from commit 5aa3629)
mxaddict pushed a commit to mxaddict/navio-core that referenced this pull request Nov 30, 2026
Replace libevent-based approach with using the Sock class and CThreadInterrupt.

Backport of bitcoin#34158 (upstream
commit eae193e). Adapted: navio's logger does not add a missing
newline (bitcoin#30929 is not ported), so the new log lines end in \n,
and lines that only moved keep navio's LogPrint/LogPrintf. The receive
buffer is a std::string read with the string_view LineReader and
Consumed(), the form upstream reached in bitcoin#35182 and bitcoin#35828,
whose LineReader changes navio already has. Context: no PoW retry,
TOR_REPLY_* constants or std::bind_front callbacks. Upstream's
std::span parameters use navio's Span: libc++ 14, which navio's clang-14
CI jobs build with, has no std::span constructor from a container.
(cherry picked from commit eae193e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.