Implementation Plan: Unified Boost.Beast HTTP/WebSocket Server, /chronik/* Single-Port Delegation, and /p2p/ws Encrypted/Compressed P2P Transport
Target Baseline: Existing eCash bitcoind (daemon/patches/ecash/, layered right after ecash/054 before the v2/ patch stack, so both eCash bitcoind and Lotus V2 inherit it cleanly).
Architectural Overview
- Replace
libevent(evhttp) insrc/httpserver.cppwithBoost.Beast(<boost/beast/http.hpp>,<boost/beast/websocket.hpp>,<boost/beast/ssl.hpp>) running on the existingBoost.AsioC++20co_awaitcoroutine pool (HTTPCoroutinePool), while keeping the publicHTTPRequest,RegisterHTTPHandler,RegisterHTTPAsyncHandler, andHTTPEventsignatures insrc/httpserver.h100% source-compatible so zero existing RPC/REST handlers (src/httprpc.cpp,src/rest.cpp) break. - Auto-Detect TLS vs. Plain HTTP/WS on the Same Port (
boost::beast::async_detect_ssl): - Each bound RPC/HTTP port (
-rpcport, default8332in eCash /10604in Lotus V2) peeks at the first bytes of each incoming TCP connection viaboost::beast::async_detect_ssl. - If the client sends a TLS
ClientHello(https://orwss://), the connection is wrapped inboost::beast::ssl_streamusing either-tlscert/-tlskeyor an auto-generated in-memory ECDSA P-256 self-signed certificate (-tlsephemeral=1, default enabled). - If the client sends plain ASCII (
http://orws://, e.g., localhost or behind a TLS-terminating Kubernetes Ingress / Cloudflare / Alchemy Load Balancer), it runs directly overboost::beast::tcp_stream. - Optional permissive mTLS (
-tlsmutual=1): setsboost::asio::ssl::verify_peer(withoutverify_fail_if_no_peer_certon the port, enforcing peer cert presence orv2hellosignature specifically on/p2p/ws). - Delegate
/chronik/*(HTTP +/chronik/wsWebSocket) on the Main RPC Port to Chronik (hyper/axum): - Chronik keeps its existing secondary port (
-chronikbind, default127.0.0.1:8321), ANDsrc/httpserver.cppregisters a built-in prefix route/chronik(exempt from-rpcuser/-rpcpasswordbasic auth, configurable via-chronikpubliconrpcport=1, default1when-chronik=1). - Regular HTTP requests to
/chronik/<subpath>strip the/chronikprefix and asynchronously proxy over a pooled loopbackboost::asio::ip::tcp::socketto Chronik's boundSocketAddr(127.0.0.1:8321). - WebSocket upgrade requests to
/chronik/wsupgrade the client viaboost::beast::websocket::stream(or raw TCP splice after101 Switching Protocols) and bidirectionally pump frames between the client socket and127.0.0.1:8321/ws. - When built with
-DBUILD_CHRONIK=OFFor run with-chronik=0,/chronik/*simply returns404 Not Foundwith zero compile-time dependency on Rust/Chronik. - Additive P2P over WebSockets on
/p2p/wswith Streamingzstd+ Prebaked Dictionary (p2p-zstd-v1) Alongside Existing Raw TCP P2P: - Normal TCP P2P (
-port=8333,CConnman::ListenSocket,CConnman::AcceptConnection,CConnman::ConnectNode("ip:port")) remains 100% intact, unmodified, and enabled by default. A single node simultaneously accepts legacy raw TCP peers on port8333and WebSocket peers on/p2p/ws, relaying blocks and transactions seamlessly across both transports. - Inbound requests to
GET /p2p/wswithUpgrade: websocketon the HTTP port negotiate streaminglibzstdcompression with a prebaked P2P/Script dictionary (Sec-WebSocket-Protocol: p2p-zstd-v1) (with automatic fallback to raw streamingp2p-zstdor RFC 7692permessage-deflatefor generic WebSocket clients) and hand the upgraded connection toCConnmanvia a localsocketpair(AF_UNIX, SOCK_STREAM, 0)bridge. - Using
ZSTD_CCtx_refCDict+ZSTD_compressStream2(..., ZSTD_e_flush)on a persistent per-peerZSTD_CCtxgives immediate high compression on the very first small packet (via the prebaked dictionary of P2P headers,inv/avaprefixes, P2PKH/P2SH/CashToken/Lotus V2TMPL_SCRIPTtemplates, and sequence/version boilerplate) and maintains a live 128 KB sliding window across consecutive P2P messages at 500+ MB/s (< 3 uslatency per message). - Every Bitcoin/Lotus P2P message flows through the existing 24-byte
CMessageHeader || payloadwire format inside binary WebSocket frames (ws.binary(true)), soV1TransportDeserializer,V1TransportSerializer,CNode, andsrc/net_processing.cpprequire zero modifications. - Outbound peers use normal raw TCP when given
"ip:port"or"host:port", and use the WebSocket dialer when prefixed withws://orwss://(-addnode=wss://node.example.com:443/p2p/wsor-connect=ws://...), setting TLS SNI (SSL_set_tlsext_host_name) and the HTTPHost:header so standard Kubernetes Ingresses, Cloudflare tunnels, and L7 load balancers route P2P traffic identically to normal web traffic.
5-Commit Atomic Implementation Sequence
Implement this as 4 sequential, self-contained commits on top of the eCash bitcoind tree (daemon/patches/ecash/), plus a 5th commit in daemon/patches/v2/ for Lotus V2. Every commit must compile cleanly (ninja bitcoind test_bitcoin) and pass test_bitcoin and httpserver_tests.
Commit 1: http: replace libevent evhttp with Boost.Beast HTTP/1.1 + async_detect_ssl + zstd server
Files to Modify
cmake/modules/FindZstd.cmake(new file followingcmake/modules/FindJemalloc.cmake):- Uses
include(BrewHelper)(find_brew_prefix(_Zstd_BREW_HINT zstd)) andinclude(ExternalLibraryHelper)(find_component(Zstd zstd NAMES zstd HINTS "${_Zstd_BREW_HINT}" ...)), exposingZstd::zstd. On a developer's machine CMake uses its standard default library resolution; in an isolated Guix/dependsbuild,CMAKE_FIND_ROOT_PATHresolvesZstd::zstdto the staticlibzstd.abuilt independs/. src/CMakeLists.txt:- Link
OpenSSL::SSL,OpenSSL::Crypto, andZstd::zstd(find_package(Zstd REQUIRED)+target_compile_definitions(server PRIVATE HAVE_ZSTD=1)) toserver. depends/packages/zstd.mk&depends/packages/packages.mk:- Add
zstdtopackagesindepends/packages/packages.mkand createdepends/packages/zstd.mk(pinned tarball +sha256_hash, building$(MAKE) -C lib libzstd.aand staging$(MAKE) -C lib DESTDIR=$($(package)_staging_dir) PREFIX=$(host_prefix) install-static install-includes) so isolated Guix release builds compile and statically linklibzstd.a. src/httpserver.hsrc/httpserver.cppsrc/httprpc.cppsrc/init.cpp(register CLI args-tlscert,-tlskey,-tlsephemeral,-tlsmutual)src/test/httpserver_tests.cpp
Exact Implementation Steps
HTTPEventTimer Replacement (src/httpserver.h,src/httpserver.cpp,src/httprpc.cpp):EventBase()andHTTPEventare only used byHTTPRPCTimerinsrc/httprpc.cpp:48-76.- Replace
HTTPEvent's internalstruct event *evwith aboost::asio::steady_timerrunning ong_work_queue->GetExecutor()(keepEventBase()returning a non-null dummy token orreinterpret_cast<struct event_base*>(1)soassert(eventBase)insrc/httprpc.cpp:947still passes without changinghttprpc.cppcallers, or updateHTTPRPCTimerto useGetHTTPThreadPoolExecutor()). HTTPRequestBacking Store & HTTPzstdCompression (src/httpserver.h,src/httpserver.cpp):- Replace
struct evhttp_request *reqinsideHTTPRequestwith an opaquestruct HTTPRequestImpl: ``cpp struct HTTPRequestImpl { boost::beast::http::request<boost::beast::http::string_body> beast_req; boost::beast::http::response<boost::beast::http::string_body> beast_res; CService peer_address; bool is_tls{false}; bool has_valid_client_cert{false}; std::string client_cert_fingerprint_hex; std::function<void(boost::beast::http::response<boost::beast::http::string_body>&&)> send_reply_fn; };`` - Implement all existing
HTTPRequestmethods againstHTTPRequestImpl: GetURI(): returnsstd::string(m_impl->beast_req.target()).GetPeer(): returnsm_impl->peer_address.GetRequestMethod(): mapshttp::verb::get -> GET,post -> POST,head -> HEAD,put -> PUT,options -> OPTIONS, elseUNKNOWN.GetHeader(hdr): looks uphdrcase-insensitively inm_impl->beast_req(m_impl->beast_req.find(hdr)).ReadBody(): ifbeast_req[http::field::content_encoding] == "zstd", decompress withZSTD_decompress(bounded tomax_body_size); then move and clearm_impl->beast_req.body().WriteHeader(hdr, value): callsm_impl->beast_res.set(hdr, value).WriteReply(nStatus, strReply):- If
strReply.size() >= 512,beast_res.find(http::field::content_encoding) == beast_res.end(), andbeast_req[http::field::accept_encoding]contains"zstd", compressstrReplyviaZSTD_compress(..., level = 1)and setbeast_res.set(http::field::content_encoding, "zstd"). - Set
m_impl->beast_res.result(static_cast<unsigned>(nStatus)), assignm_impl->beast_res.body(), callm_impl->beast_res.prepare_payload(), and invokem_impl->send_reply_fn(std::move(m_impl->beast_res)). - RFC 3986 Query Parameter Parser (
GetQueryParameterFromUriinsrc/httpserver.cpp): - Keep
GetQueryParameterFromUri(const char *uri, const std::string &key)passing all cases insrc/test/httpserver_tests.cpp(validate%hex escapes so a trailing or non-hex%throwsstd::runtime_error("URI parsing failed, it likely contained RFC 3986 invalid characters")exactly as tested inhttpserver_tests.cpp:43-48). Boost.BeastListener +async_detect_sslSession Coroutine (src/httpserver.cpp):- Create an
ssl::context g_ssl_ctx{ssl::context::tlsv12}(supporting TLS 1.2 and TLS 1.3): - If
-tlscertand-tlskeyare set, load them viause_certificate_chain_file/use_private_key_file. - Otherwise, generate or load
<datadir>/node_tls_key.pemand<datadir>/node_tls_cert.pem(EC P-256 key viaEVP_EC_gen("P-256")and self-signedX509cert valid for 10 years) and load intog_ssl_ctx. - If
-tlsmutual=1, setg_ssl_ctx.set_verify_mode(ssl::verify_peer)with a verify callback that accepts self-signed peer node certs and records their SHA-256 fingerprint inclient_cert_fingerprint_hex. - Bind
tcp::acceptors on all(host, port)pairs produced byHTTPBindAddresses(). - For each accepted
tcp::socket: - Spawn a coroutine
HandleConnection(tcp::socket sock, CService peer, Config &config): - Set socket timeout (
DEFAULT_HTTP_SERVER_TIMEOUTviabeast::get_lowest_layer(stream).expires_after(...)). - Call
bool is_tls = co_await boost::beast::async_detect_ssl(tcp_stream, flat_buffer, boost::asio::use_awaitable); - If
is_tls, wrap inboost::beast::ssl_stream<boost::beast::tcp_stream>andco_await ssl_stream.async_handshake(ssl::stream_base::server, flat_buffer.data(), use_awaitable)(consuming buffered bytes). - Loop over HTTP/1.1 Keep-Alive requests using
http::request_parser<http::string_body>withheader_limit(MAX_HEADERS_SIZE)andbody_limit(MIN_SUPPORTED_BODY_SIZE + 2 * config.GetMaxBlockSize()): - Check
boost::beast::websocket::is_upgrade(req): if true, dispatch to registered WebSocket handlers (Commit 2 & Commit 3). - Otherwise check
ClientAllowed(peer)(for non-public paths) and dispatch topathHandlersviag_work_queue, awaiting the reply and writing it viahttp::async_write.
Commit 2: http: delegate /chronik/* and /chronik/ws on main RPC port to Chronik server
Files to Modify
src/httpserver.hsrc/httpserver.cppsrc/init.cppchronik/chronik-cpp/chronik.cpp(orsrc/httpserver.cppvia-chronikbind/ default Chronik port8321)test/functional/chronik_rpc_port_proxy.py(new test)
Exact Implementation Steps
- Public Prefix Whitelist on Main RPC Port (
src/httpserver.h,src/httpserver.cpp): - Add
void RegisterPublicHTTPPrefix(const std::string &prefix);(or abool allowPublicAccessflag onHTTPPathHandler) so requests matching/chronikand/p2p/wsbypassClientAllowed(peer)IP subnet rejection when-chronikpubliconrpcport=1(default1) is enabled, while/and/wallet/*continue to strictly enforceClientAllowed(peer)and RPC Basic/Auth credentials. - Async HTTP Proxy Handler for
/chronik(src/httpserver.cpp): - Register a prefix handler for
"/chronik"(exactMatch = false): - Compute target URI: strip
"/chronik"prefix (if empty, use"/"). - Connect asynchronously to Chronik's local listener (
127.0.0.1:8321, or the firstSocketAddrconfigured by-chronikbind) viaboost::beast::tcp_stream. - Forward method (
GET,POST,OPTIONS), target URI, headers (Content-Type,Accept,Origin,X-Forwarded-For), and body usingboost::beast::http::async_write. - Read the response with
boost::beast::http::async_read(usinghttp::string_body), copy status code and response headers (Content-Type,Access-Control-Allow-*) intoHTTPRequest, and callreq->WriteReply(status, body)(which also automatically appliesContent-Encoding: zstdif the client requestedAccept-Encoding: zstd!). - Async WebSocket Proxy for
/chronik/ws(src/httpserver.cpp): - When
boost::beast::websocket::is_upgrade(req)is true andreq.target()starts with"/chronik/ws": - Upgrade the incoming client stream (
tcp_streamorssl_stream) usingboost::beast::websocket::stream. - Open an outbound
boost::beast::websocket::stream<boost::beast::tcp_stream>to127.0.0.1:8321/ws. - Run two concurrent coroutines (
client_to_chronikandchronik_to_client) forwarding binary/text WebSocket frames until either side closes.
Commit 3: net: add WebSocket P2P transport (/p2p/ws) with streaming zstd and prebaked P2P dictionary
Files to Modify
src/net_zstd_dict.h(new file: static prebaked P2P/Script dictionary + RAIIP2PZstdStreamwrapper)src/httpserver.hsrc/httpserver.cppsrc/net.hsrc/net.cppsrc/test/net_tests.cpp
Exact Implementation Steps
- Prebaked P2P + Script Dictionary & Streaming
zstdContext (src/net_zstd_dict.h): - Define
inline constexpr uint8_t P2P_ZSTD_DICT_V1[](~8–16 KB deterministic byte array) containing: - P2P Framing & Command Headers: Network magic sequences (
\xe3\xe1\xf3\xe8,\xf0\xb5\xf2\xf4,\xda\xb5\xbf\xfa), 12-byte zero-padded command names ("version\0\0\0\0\0","verack\0\0\0\0\0\0","sendheaders\0","sendcmpct\0\0\0","sendaddrv2\0\0","feefilter\0\0\0","inv\0\0\0\0\0\0\0\0\0","getdata\0\0\0\0\0","notfound\0\0\0\0","tx\0\0\0\0\0\0\0\0\0\0","headers\0\0\0\0\0","cmpctblock\0\0","getblocktxn\0","blocktxn\0\0\0\0","avapoll\0\0\0\0\0","avaresponse\0","avaproof\0\0\0\0","ping\0\0\0\0\0\0\0\0","pong\0\0\0\0\0\0\0\0"), and commonCInv4-byte type tags (\x01\x00\x00\x00,\x02\x00\x00\x00,\x04\x00\x00\x00,\x00\x00\x00\x02). - Transaction & Script Templates: Standard transaction version/sequence/locktime bytes (
\x02\x00\x00\x00,\x01\x00\x00\x00,\xff\xff\xff\xff,\xfe\xff\xff\xff,\x00\x00\x00\x00), P2PKH (\x19\x76\xa9\x14,\x88\xac), P2SH (\x17\xa9\x14,\x87), CashToken prefix (\xef), and Lotus V2 Taproot /TMPL_SCRIPTcovenant sequences (\x22\x51\x20,\x50,\x62,\x6d,\xeb,\xec,\xed,\xdf,\xde,\xbd,\xac). - Initialize singleton
const ZSTD_CDict *GetP2PZstdCDict(int level = 1)andconst ZSTD_DDict *GetP2PZstdDDict()once on first call viaZSTD_createCDict(P2P_ZSTD_DICT_V1, sizeof(P2P_ZSTD_DICT_V1), level)andZSTD_createDDict(P2P_ZSTD_DICT_V1, sizeof(P2P_ZSTD_DICT_V1)). - Implement
class P2PZstdSession: - Owns
ZSTD_CCtx *m_cctxandZSTD_DCtx *m_dctx, callingZSTD_CCtx_refCDict(m_cctx, GetP2PZstdCDict())andZSTD_DCtx_refDDict(m_dctx, GetP2PZstdDDict())whenuse_dict == true(p2p-zstd-v1). CompressFrame(Span<const uint8_t> in, std::vector<uint8_t> &out): callsZSTD_compressStream2(m_cctx, &out_buf, &in_buf, ZSTD_e_flush)so the sliding window stays warm across all subsequent P2P messages on that connection!DecompressFrame(Span<const uint8_t> in, std::vector<uint8_t> &out): callsZSTD_decompressStream(m_dctx, &out_buf, &in_buf).- Inbound
/p2p/wsEndpoint &socketpairBridge insrc/httpserver.cpp: CConnmaninsrc/net.cppinteracts with every peer strictly throughstd::shared_ptr<Sock> m_sock(m_sock->Send(...),m_sock->Recv(...), andm_sock->Get()forpoll()/select()) plusV1TransportSerializer/V1TransportDeserializer.- Register a WebSocket upgrade handler at
/p2p/ws: - Inspect
req[http::field::sec_websocket_protocol]: - If it contains
"p2p-zstd-v1", respond withSec-WebSocket-Protocol: p2p-zstd-v1and enableP2PZstdSession(/*use_dict=*/true)on the pump coroutines (leavingpermessage_deflatedisabled so we don't double-compress). - Else if it contains
"p2p-zstd", respond withSec-WebSocket-Protocol: p2p-zstdand enableP2PZstdSession(/*use_dict=*/false). - Otherwise, enable
boost::beast::websocket::permessage_deflate(pmd.server_enable = true; pmd.client_enable = true; ws.set_option(pmd);) as a standard RFC 7692 fallback. - Call
ws.binary(true); co_await ws.async_accept(req, boost::asio::use_awaitable); - Create
int sv[2]; socketpair(AF_UNIX, SOCK_STREAM, 0, sv); - Hand
sv[0]+ the peer's realCAddress(from the TCP connection orX-Forwarded-Forwhen behind a trusted local proxy) toCConnman::AcceptWebSocketPeer(SOCKET fd, const CAddress &addr, bool is_tls, const std::string &peer_cert_fp). - Spawn two coroutines pumping bytes between
sv[1]andws: sv[1] -> ws: reads available P2P wire bytes fromsv[1](up to 256 KB per batch), runszstd_session.CompressFrame(...)(ifzstdnegotiated), and writes as a single binary WebSocket frame viaws.async_write.ws -> sv[1]: reads each binary WebSocket frame viaws.async_read, runszstd_session.DecompressFrame(...)(ifzstdnegotiated), and writes the raw P2P bytes tosv[1].
Commit 4: net: support outbound wss:// and ws:// domain:port P2P connections and BIP155 ADDRv2 advertisement
Files to Modify
src/netaddress.hsrc/netaddress.cppsrc/net.hsrc/net.cppsrc/net_processing.cppsrc/init.cpptest/functional/p2p_websocket_tls.py(new end-to-end functional test)
Exact Implementation Steps
- Backward-Compatible Return-Path Advertisement via BIP155
ADDRv2(src/netaddress.h,src/netaddress.cpp,src/net_processing.cpp): - Legacy
addr(BIP155Encoding::V1) only supports fixed 16-byte IPv4/IPv6 addresses (V1_SERIALIZATION_SIZE = 16), so adomain:portreturn path cannot be sent inADDRv1messages. - However, BIP155
ADDRv2(src/netaddress.h:305-344) supports variable-length addresses up toMAX_ADDRV2_SIZE = 512bytes, and unpatchedADDRv2nodes are Already Required by BIP155 (SetNetFromBIP155Networkinsrc/netaddress.h:337) to silently ignore unrecognized BIP155 network IDs without banning or disconnecting! - Therefore:
- Add
NET_WSS(beforeNET_MAX) toenum NetworkandWSS_DOMAIN = 0x10toenum BIP155Network : uint8_tinsrc/netaddress.h(withADDR_WSS_MAX_SIZE = 253, the maximum DNS FQDN length). - In
CNetAddr(src/netaddress.h/src/netaddress.cpp), allowm_addrto store the ASCII lowercase FQDN bytes whenm_net == NET_WSS, and implementToStringAddr()returning the domain string. - In
SerializeV1Array(src/netaddress.h:349), serializeNET_WSSas all-zeros (0.0.0.0, non-routable) and insrc/net_processing.cpp(wherePushAddresscheckspeer->m_wants_addrv2), only relayNET_WSSaddresses to peers that negotiatedsendaddrv2(m_wants_addrv2 == true), identically to howNET_TORV3,NET_I2P, andNET_CJDNSare already gated insrc/net_processing.cpp! - Add
-externaldomain=<domain[:port]>insrc/init.cppwhich registers aNET_WSSlocal service address viaAddLocal(CService(wss_netaddr, port), LOCAL_MANUAL). - Result:
- Legacy
ADDRv1peers never receivedomain:port. - Unpatched
ADDRv2peers silently skipBIP155Network::WSS_DOMAIN (0x10)per BIP155 rules. - Upgraded peers store
NET_WSSinAddrMan, gossip it to otherADDRv2peers, and dial it viawss://<domain>:<port>/p2p/ws! - Strictly Additive Outbound WebSocket Dialer (
CConnman::ConnectWebSocketNodeinsrc/net.cpp): - Keep
CConnman::ConnectNodefor normalNET_IPV4/NET_IPV6"ip:port"peers 100% unchanged so existing TCP P2P behavior, DNS seeds, andaddrgossip are completely unaffected. - When
ConnectNodeis given aCAddresswithGetNetwork() == NET_WSSOR a string starting withws://orwss://(e.g.,wss://node.example.com:443/p2p/wsorws://127.0.0.1:8332/p2p/ws), dispatch toCConnman::ConnectWebSocketNode: - Parse scheme (
wsvswss),domain,port(default80forws,443forwss), andtarget(default"/p2p/ws"). - Resolve
domain:portviaboost::asio::ip::tcp::resolveron theBoost.AsioIO context. - If
wss://, wrap inboost::beast::ssl_stream<boost::beast::tcp_stream>, set TLS SNI viaSSL_set_tlsext_host_name(ssl_stream.native_handle(), domain.c_str()), and runasync_handshake(ssl::stream_base::client). - Wrap in
boost::beast::websocket::stream, setws.binary(true), attach a decorator settingreq.set(http::field::sec_websocket_protocol, "p2p-zstd-v1, p2p-zstd"), and pass awebsocket::response_type restows.async_handshake(res, host_header, target)(withHost: <domain>:<port>). - Inspect
res[http::field::sec_websocket_protocol]: if"p2p-zstd-v1", enableP2PZstdSession(/*use_dict=*/true); else if"p2p-zstd", enableP2PZstdSession(/*use_dict=*/false);Createsocketpair(AF_UNIX, SOCK_STREAM, 0, sv), pumpsv[1] <-> wson theBoost.Asiocoroutine pool, and passstd::make_unique<Sock>(sv[0])intoCNodecreation insideCConnman::ConnectNode! - End-to-End Hybrid TCP + WebSocket +
zstdDictionary Verification (test/functional/p2p_websocket_tls.py): - Start a 3-node network (
Node 0,Node 1,Node 2): Node 0is configured with-externaldomain=localhost:<node0_rpcport>.Node 1connects toNode 0overwss://localhost:<node0_rpcport>/p2p/ws(WebSocket + TLS +p2p-zstd-v1prebaked dictionary streaming compression).Node 2connects toNode 0over normal raw TCP P2P (127.0.0.1:<node0_p2pport>).- Verify:
- JSON-RPC (
getblockchaininfo) works over bothhttp://andhttps://onNode 0's RPC port (async_detect_ssl), includingAccept-Encoding: zstd(Content-Encoding: zstd). /chronik/blockchain-infoand/chronik/wswork onNode 0's main RPC port.Node 0advertises itsNET_WSS(localhost:<node0_rpcport>) address viaaddrv2without breakingADDRv1peers.- Transactions broadcast on
Node 1(WSS/p2p/wswithp2p-zstd-v1) relay throughNode 0toNode 2(normal TCP P2P), and blocks mined onNode 2(normal TCP P2P) relay throughNode 0toNode 1(WSS/p2p/ws).
Commit 5 (Lotus V2-Only Final Patch in daemon/patches/v2/): v2: remove legacy raw TCP P2P listener and use /p2p/ws exclusively
Note: Commits 1–4 live in
daemon/patches/ecash/(upstream-compatible with eCash ABC, keeping raw TCP P2P and/p2p/wsside-by-side). Commit 5 is layered at the very end ofdaemon/patches/v2/for Lotus (lotusd), where we do not want legacy raw TCP P2P sockets at all.
Files to Modify
src/net.cppsrc/init.cppsrc/chainparams.cpp
Exact Implementation Steps
- Remove Raw TCP P2P Socket Listener (
src/init.cpp,src/net.cpp): - In
AppInitMain(src/init.cpp) andCConnman::InitBinds(src/net.cpp), skip binding raw TCP P2PvhListenSocketlisteners (BindListenPort). Inbound P2P connections are accepted exclusively via/p2p/wson the unifiedBoost.BeastHTTP/TLS port (10604mainnet /11604testnet /12604regtest). - In
CConnman::ThreadSocketHandler(src/net.cpp), skip thevhListenSocketaccept loop (all inbound WebSocket peers arrive viaCConnman::AcceptWebSocketPeerfrom/p2p/ws). - Default All Outbound P2P Connections to
/p2p/ws(src/net.cpp): - In
CConnman::ConnectNode, route all outbound peer connections (ip:portanddomain:portalike) throughConnectWebSocketNode(wss://<host>:<port>/p2p/wswithasync_detect_sslfallback tows://on regtest/local loopback if-tlsephemeral=0), so every Lotus node communicates exclusively over WebSocket/p2p/wson a single unified port per daemon.
Isolated Worktree, 2-Node Regtest WebSocket Test & A/B Benchmark Plan
To execute this cleanly in parallel without interfering with any ongoing patch rebasing in daemon/workspace-v2 or other worktrees:
Phase 1: Isolated Worktree & Baseline Binary Capture (evhttp + Boost.Asio Coroutine Pool)
- Create Dedicated Worktree at
ecash-optimizations-tip(8ea9ea122a): ``bash git -C /Users/shammah/repos/lotus-v2-optimizations/daemon/workspace-v2 \ worktree add -b feat/beast-http-ws-p2p /private/tmp/wt-beast-http-p2p ecash-optimizations-tip`` - Strict Isolation Rule: Only modify files inside
/private/tmp/wt-beast-http-p2pand build inside/private/tmp/build-beast-http-p2p. Never touch/Users/shammah/repos/lotus-v2-optimizations/daemon/workspace-v2or rungit gc/git worktree prune. - Configure & Build Baseline (
evhttp+HTTPCoroutinePoolfromecash/012–013) First: ``bash cmake -GNinja -B /private/tmp/build-beast-http-p2p -S /private/tmp/wt-beast-http-p2p \ -DCMAKE_BUILD_TYPE=Release \ -DBUILD_BITCOIN_WALLET=ON \ -DBUILD_BITCOIN_QT=OFF \ -DBUILD_BITCOIN_ZMQ=OFF \ -DBUILD_CHRONIK=OFF \ -DENABLE_UPNP=OFF \ -DENABLE_NATPMP=OFF ninja -C /private/tmp/build-beast-http-p2p bitcoind test_bitcoin cp /private/tmp/build-beast-http-p2p/src/bitcoind /private/tmp/bitcoind-baseline-evhttp-asio`` - Saving
/private/tmp/bitcoind-baseline-evhttp-asiobefore touchingsrc/httpserver.cppgives an exact apples-to-apples binary for benchmarking the existingevhttp+Boost.AsioHTTPCoroutinePoolimplementation against the newBoost.Beast+HTTPCoroutinePoolimplementation, AND pre-compiles 98% of the object files in/private/tmp/build-beast-http-p2pso subsequentninjarebuilds after editingsrc/httpserver.cppandsrc/net.cpptake< 5 seconds!
Phase 2: 2-Node Regtest WebSocket P2P Verification (wss:// + p2p-zstd-v1 vs. Raw TCP)
Write and run /private/tmp/wt-beast-http-p2p/test/functional/p2p_websocket_regtest_bench.py (or standalone Python harness) that launches two regtest bitcoind nodes from /private/tmp/build-beast-http-p2p/src/bitcoind:
- Node Setup:
- Node 0:
-regtest -server=1 -rpcport=18443 -port=18444 -tlsephemeral=1 -externaldomain=localhost:18443 - Node 1:
-regtest -server=1 -rpcport=18445 -port=18446 -tlsephemeral=1 -addnode=wss://localhost:18443/p2p/ws - Functional Assertions:
- Verify
getpeerinfoon both nodes shows the peer connected over/p2p/wswithtls=trueandcompression="p2p-zstd-v1". - Verify
Node 0's single port18443responds to: - Plain
http://127.0.0.1:18443/JSON-RPC (getblockchaininfo) - Encrypted
https://127.0.0.1:18443/JSON-RPC (getblockchaininfowith-k) Accept-Encoding: zstdJSON-RPC (getblockwith verbosity 2), verifyingContent-Encoding: zstdheader and validzstddecompression- WebSocket P2P upgrade at
wss://localhost:18443/p2p/ws - Mine 101 blocks on Node 0; verify Node 1 syncs to height 101 over
wss://localhost:18443/p2p/ws. - Broadcast 500 transactions on Node 1; verify all 500 enter Node 0's mempool, mine 1 block on Node 0, and verify both nodes reach height 102 with empty mempools.
- P2P Bandwidth & Latency Comparison (
wss://+p2p-zstd-v1vs. Legacy Raw TCP): - Run the exact same 500-tx + 10-block relay workload between:
- Pair A: 2 nodes connected via
wss://localhost:18443/p2p/ws(p2p-zstd-v1prebaked dictionary + streamingZSTD_e_flush) - Pair B: 2 nodes connected via legacy raw TCP (
127.0.0.1:18444) - Query
getnettotals(totalbytesrecv,totalbytessent) and measure wall-clock sync time for both pairs to quantify the exact bandwidth reduction (%) and relay latency.
Phase 3: A/B HTTP Server Benchmark (Boost.Beast vs. evhttp + Boost.Asio Coroutine Tasks)
Run an automated Python/asyncio (or wrk / multi-threaded keep-alive socket) benchmark script /private/tmp/bench_http_ab.py against:
- Target A (Baseline):
/private/tmp/bitcoind-baseline-evhttp-asio(libeventevhttp+Boost.AsioHTTPCoroutinePoolasync task pool fromecash/012–013) - Target B (New - Plain HTTP):
/private/tmp/build-beast-http-p2p/src/bitcoind(Boost.BeastHTTP/1.1 Keep-Alive +HTTPCoroutinePool) - Target C (New - HTTPS TLS 1.3):
/private/tmp/build-beast-http-p2p/src/bitcoindoverhttps://(async_detect_ssl+ssl_stream) - Target D (New - HTTP +
zstd):/private/tmp/build-beast-http-p2p/src/bitcoindwithAccept-Encoding: zstd
Measure at concurrency levels c = 1, c = 16, and c = 64 (10,000 requests per run over HTTP/1.1 Keep-Alive connections):
| Workload | Description | Metrics Collected |
|---|---|---|
1. Small Fast-Path RPC (getblockchaininfo) |
Measures pure HTTP parser + HTTPCoroutinePool dispatch + response serialization overhead (~400 B body) |
Throughput (req/s), p50 latency (us), p99 latency (us) |
2. Large Payload RPC (getblock w/ 1,000 txs, verbosity=2) |
Measures large JSON body allocation, socket write throughput, and Content-Encoding: zstd wire compression (~500 KB uncompressed $\rightarrow$ zstd) |
Throughput (req/s), MB/s wire bandwidth, p50/p99 latency (ms) |
3. JSON-RPC Batch ([getblockhash x 50]) |
Measures parallel co_await batch fan-out on HTTPCoroutinePool under Boost.Beast vs evhttp |
Throughput (batches/s), p50/p99 latency (us) |
| 4. Pipelined / Mixed RPC + P2P Load | Concurrent getrawmempool RPCs on port 18443 while /p2p/ws is actively syncing blocks on the same port |
RPC p99 tail latency under P2P load |