Source: docs/lotus-v2/research/addendum-designs/W1-E1-Z1.md
Research β€” non-normative. This page records an investigation. It defines no rule; a research result enters the specification only through a decision recorded in decision history.

Designs: W1 (async wallet notifications), E1 (remove libevent), Z1 (remove ZeroMQ from V2)

Status: design only. Nothing here was built or run. Section 0 separates what was read in the source from what is assumed.

0. Baseline, method, verified vs assumed

Source read (read-only, git show/git grep, no checkout or build): /Users/shammah/repos/lotus-v2-repaired-source.

Verified in source (each item cites code read):

Assumed (verify during implementation; each has a characterization test below):

Placement summary

Item Tier Position
W1 eCash Append to the eCash series after the coordinator's Lane-1 integration of hand-off generic 0029–0034. It does not depend on them.
E1 eCash After W1 (independent of it). Must follow 073 and generic 0029/0032–0034, because E1.5 edits httpserver.{h,cpp} and src/CMakeLists.txt.
Z1 V2 Append after hand-off v2-only 0001–0003 and after the identity patches (v2-identity/handoff/0001–0003). No functional dependency on either.

All three should wait for lane E's composition (596537e978, now landed). This keeps them from composing against a moving tip. W1 has an additional wait on lane E's wallet residuals; see W1.7.


W1. Async wallet notification queue (eCash tier)

W1.1 What changes, and what must not change

Move delivery of Chain::Notifications callbacks for wallets only from the shared scheduler thread to a per-registration FIFO worker. The worker blocks the producer when it is full.

Why per-subscriber semantics stay identical:

So the CValidationInterface contract (serial callbacks, in generation order) still holds for each wallet. The changes are confined to these:

  1. Cross-subscriber timing. A wallet may lag Chronik, PeerManager, etc. No ordering across subscribers is documented (validationinterface.h class comment), so this is allowed.
  2. Fences. Fences that wait only on the main queue no longer cover the wallet. Fixed in W1.3.
  3. Lifetime. Unregister must drain and join the worker.
  4. Overflow and exceptions. These get explicit policies, below.

Avalanche is not moved. avalanche::Processor registers through the same handleNotifications. Its updatedBlockTip/transactionAddedToMempool timing feeds polling. Making it asynchronous is a behaviour change outside W1, so delivery is opt-in per registration. bench/wallet_balance.cpp keeps synchronous delivery.

W1.2 Decisions

W1.3 Exact changes

Commit W1-a: util: let BoundedTaskQueue block producers instead of failing on overflow

File: src/util/bounded_task_queue.h (owned by eCash 060; the change is additive).

Tests, in src/test/validationinterface_tests.cpp: extend the existing suite, so no CMake change is needed.

Commit W1-b: validation: fence secondary queues for broadcast callers that wait

Commit W1-c: wallet: deliver chain notifications to each wallet on its own FIFO worker

src/interfaces/chain.h:

//! How a Notifications subscriber receives callbacks.
enum class NotificationDelivery {
    SCHEDULER_THREAD, //!< inline on the shared ValidationSignals thread (default)
    DEDICATED_WORKER, //!< FIFO worker owned by the handler; fenced by
                      //!< SyncWithValidationInterfaceQueue(), drained on disconnect
};
virtual std::unique_ptr<Handler>
handleNotifications(std::shared_ptr<Notifications> notifications,
                    NotificationDelivery delivery) = 0;
std::unique_ptr<Handler>
handleNotifications(std::shared_ptr<Notifications> notifications) {
    return handleNotifications(std::move(notifications),
                               NotificationDelivery::SCHEDULER_THREAD);
}

Declare the enum inside class Chain. In ChainImpl, add using Chain::handleNotifications; so the one-argument overload is not hidden.

src/node/interfaces.cpp:

Callback Captures Byte charge
TransactionAddedToMempool tx, mempool_sequence; not spent_coins (the wallet ignores them) validation_queue::TxBytes(tx)
TransactionRemovedFromMempool tx, reason, sequence TxBytes
BlockConnected role, block (shared_ptr), const int height = index->nHeight BlockBytes(block)
BlockDisconnected block, height BlockBytes
UpdatedBlockTip nothing 0
ChainStateFlushed role, CBlockLocator by value 32 * locator.vHave.size()

src/wallet/wallet.cpp:3046-3047 (AttachChain): chain().handleNotifications(walletInstance, interfaces::Chain::NotificationDelivery::DEDICATED_WORKER). Extend the comment above it: "notifications queue on the wallet's worker until cs_wallet is released".

src/wallet/wallet.h, comment on m_chain_notifications_handler: "resetting it drains queued notifications; never reset it while holding cs_wallet."

Tests:

Commit W1-d: doc: wallet notification worker

Each commit builds and passes its own tests. W1-a and W1-b are useful on their own.

W1.4 Ordering, shutdown, unload, rescans: argument

W1.5 Conflicts

W1.6 Test plan and acceptance

eCash tier (replay ecash series + W1):

  1. test_bitcoin builds; Chronik ON and OFF; wallet ON.
  2. One-process run of the full test_bitcoin: 100 % pass, except the known /private logargs path issue. Include validationinterface_tests, wallet_tests, walletdb_tests, coinselector_tests, ismine_tests, scriptpubkeyman_tests, psbt_wallet_tests, wallet_crypto_tests, db_tests, init_tests.
  3. Repeat the new tests plus wallet_tests/CreateWallet 200 times (--run_test=… loop). No failure.
  4. Full functional suite passes. Name these in the report:
  5. wallet_*.py, including wallet_multiwallet.py --usecli, wallet_reorgsrestore, wallet_abandonconflict, wallet_resendwallettransactions, wallet_backup, wallet_startup, wallet_importdescriptors, wallet_import_rescan, wallet_listsinceblock;
  6. feature_notifications, rpc_rawtransaction, rpc_packages, mempool_persist;
  7. feature_pruning (--extended).
  8. TSan. Linux, -DENABLE_SANITIZERS=thread: test_bitcoin -t validationinterface_tests,wallet_tests, plus functional wallet_basic, wallet_multiwallet, wallet_reorgsrestore, feature_notifications, wallet_backup. Zero reports, no new suppressions. macOS TSan does not substitute for this; say so if only macOS was run.
  9. Optional evidence, no speedup claim without an interleaved baseline: scheduler callback latency during generatetoaddress 100 with a 10k-tx wallet, before and after.

V2 tier (replay ecash + W1 + v2):

W1.7 What W1 must wait for

W1.8 Risks


E1. Remove libevent from the eCash tier (and so from V2)

E1.1 Inventory (verified at eCash tip)

Use Location Action
HTTP client src/bitcoin-cli.cpp: lines 19, 28-29 includes; libevent_log_cb 168-174; HTTPReply/http_errorstring/http_request_done/http_error_cb 248-311; CallRPC transport 710-806; event_set_log_callback 1138 Port to Beast (E1-c)
Tor control src/torcontrol.cpp (whole transport, timer, thread) Port to Asio (E1-d)
URL decode src/util/url.cpp (evhttp_uridecode); used by wallet/rpc/util.cpp:56, fuzz string.cpp:228 Own implementation (E1-b)
RAII wrappers src/support/events.h, src/test/raii_event_tests.cpp, src/test/CMakeLists.txt:219/230 Delete (E1-e)
HTTP server remnants src/httpserver.cpp:36-38 include, libevent_log_cb 1705-1723, 1903-1906, UpdateHTTPServerLogging 2005-2011; src/httpserver.h:64 decl; src/rpc/misc.cpp:710-714 Delete (E1-e)
Stray include src/wallet/rpcwallet.cpp:43 <event2/http.h> Delete (E1-e)
Build src/CMakeLists.txt:482-486 link_event macro and link_event(util event), 736-739 (server event, server pthreads), 814 (bitcoin-cli); cmake/modules/FindEvent.cmake; cmake/utils/EventCheckVersion.cpp; test/lint/lint-files.py:49 Delete (E1-e)
depends depends/packages/libevent.mk; packages.mk:1 packages:=boost libevent zstd β†’ boost zstd Delete (E1-e)
Docs/contrib doc/build-osx.md:24, doc/build-unix.md:33,64,147,237, doc/build-windows.md:65, doc/dependencies.md:18, doc/developer-notes.md:538,551 (thread descriptions), contrib/debian/control:12, contrib/docker/chronik-plugins/Dockerfile:25-26, contrib/utils/install-dependencies-bookworm.sh:51, contrib/aur/bitcoin-abc{,-qt}/PKGBUILD:9, web/docs.e.cash/content/chronik/setup/build-chronik.md:19 E1-f
Not libevent electrum/contrib/* (Electrum ABC bundles its own Tor), src/bench/nanobench.h PERF_EVENT_*, Qt QEvent, src/wallet/rpc/encrypt.cpp:79 comment Leave
Logging category BCLog::LIBEVENT / "libevent" (logging.{h,cpp}); -debugexclude=libevent in test_node.py:150 and setup_common.cpp:96 Keep as a no-op category (decision below)
Opaque token struct event_base / EventBase() / HTTPEvent(struct event_base*) in httpserver.h, httprpc.cpp Keep (decision below)

Decisions:

Document it in the release note as deprecated.

E1.2 bitcoin-cli HTTP client (Beast), exact behaviour

New code in src/bitcoin-cli.cpp. Keep it in this file so V2 003's string hunks still apply.

Value Name String
0 TIMEOUT "timeout reached"
1 EOF "EOF reached"
2 INVALID_HEADER "error while reading header, or invalid header"
3 BUFFER_ERROR "error encountered while reading or writing"
4 REQUEST_CANCEL "request was canceled"
5 DATA_TOO_LONG "response body is larger than allowed"

Transport:

Request (http::request<http::string_body>):

Response:

Error mapping (status = 0, error = …):

Condition Code
beast::error::timeout 0
http::error::end_of_stream / asio::error::eof / connection_refused / connection_reset / resolve failure / any connect failure 1
http::error::* header or body parse errors 2
Other socket read/write errors 3
Body limit 5 (unreachable when unlimited)

E1.1 verifies refused β†’ 1 and timeout β†’ 0 against libevent. If libevent reports refused differently, adopt libevent's value.

URI encoding: urlEncode (E1-b) can no longer fail. The "uri-encode failed" throw becomes unreachable; delete it.

Everything after transport stays verbatim. That covers:

Do not reflow these lines. V2 003 changes bitcoind β†’ lotusd at the old line 813 and needs that context.

Removals:

Add <boost/asio/...> and <boost/beast/core.hpp>/<boost/beast/http.hpp>. Beast is header-only; common→util already carries the Boost headers; Windows sockets come from link_windows_dependencies(util).

Options: none change: -rpcconnect, -rpcport, -rpccookiefile, -rpcuser/-rpcpassword, -rpcwait, -rpcclienttimeout, -stdin, -stdinrpcpass, -stdinwalletpassphrase, -rpcwallet, -named, -getinfo, -netinfo, -generate.

E1.3 torcontrol on Asio, exact behaviour

Move the declarations of TorControlReply, TorControlConnection, SplitTorReplyLine, ParseTorReplyMapping and new std::optional<CService> ParseTorControlAddress(const std::string&) into src/torcontrol.h, so unit tests can drive them. TorController stays in the .cpp. The public functions keep their signatures: StartTorControl(CService), InterruptTorControl(), StopTorControl(), DefaultOnionServiceTarget(), DEFAULT_TOR_CONTROL, DEFAULT_LISTEN_ONION. Therefore init.cpp is untouched, which avoids conflicts with every hand-off init.cpp patch.

TorControlConnection(boost::asio::io_context &io)

Members:

Connect(center, connected, disconnected):

  1. If a socket exists, Disconnect().
  2. Parse with ParseTorControlAddress, numeric only, same accepted forms as evutil_parse_sockaddr_port. On failure, log tor: Error parsing socket address %s and return false (no reconnect, as today).
  3. Create the socket. On a synchronous open failure, log tor: Error connecting to address %s and return false.
  4. Store the callbacks, call async_connect, and return true.
  5. On completion, if the generation still matches:
  6. success β†’ log tor: Successfully connected! and call connected(*this), then start reading;
  7. error β†’ log tor: Error connecting to Tor control socket, Disconnect(), disconnected(*this).
  8. Writes queued before connect start once the connection succeeds.

Read loop: async_read_some into a 64 KiB buffer and append to m_rbuf. Then, while m_rbuf holds a '\n':

  1. Take the line and strip one trailing '\r' (matches EVBUFFER_EOL_CRLF: optional CR before LF).
  2. Apply the unchanged body of today's readcb loop: lines of fewer than 4 characters are skipped; the status code and lines are accumulated; ' ' dispatches. Codes >= 600 go to async_handler, otherwise to reply_handlers.front() followed by pop_front, or to the "Received unexpected sync reply" log.
  3. Check the generation after each dispatch. A handler may have called Disconnect(); if so, stop.

After the loop: if m_rbuf.size() > MAX_LINE_LENGTH, log tor: Disconnecting because MAX_LINE_LENGTH exceeded and call Disconnect() without disconnected (preserved). On EOF, log tor: End of stream; on any other error, log tor: Error connecting to Tor control socket. Either way, call Disconnect() then disconnected(*this).

Command(cmd, handler):

  1. Return false if there is no socket.
  2. Append cmd + "\r\n" to m_wqueue and push the handler.
  3. If idle and connected, start async_write.
  4. Return true.

A write error is handled like a read error: Disconnect() + disconnected.

Disconnect(): ++m_gen, close the socket with error-code overloads, reset the socket, and clear m_rbuf and m_wqueue. reply_handlers and message are not cleared. This mirrors today, where only the bufferevent is freed. Completion handlers check m_gen and ignore operation_aborted.

TorController(io_context &io, center, target)

Thread:

static std::unique_ptr<boost::asio::io_context> g_tor_io;
static std::thread torControlThread;
static void TorControlThread(CService target) {
    auto guard = boost::asio::make_work_guard(*g_tor_io);
    TorController ctrl(*g_tor_io, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), target);
    g_tor_io->run();
}   // ctrl destroyed on the tor thread: RemoveLocal as today
void StartTorControl(CService t) {
    assert(!g_tor_io);
    g_tor_io = std::make_unique<boost::asio::io_context>(1);
    torControlThread = std::thread(&util::TraceThread, "torcontrol", [t] { TorControlThread(t); });
}
void InterruptTorControl() { if (g_tor_io) { LogPrintf("tor: Thread interrupt\n"); g_tor_io->stop(); } }
void StopTorControl() { if (g_tor_io) { torControlThread.join(); g_tor_io.reset(); } }

Logging: every log string and category (BCLog::TOR) is unchanged.

E1.4 Commit plan (eCash tier; one concern each; each builds and passes)

  1. E1-a test: characterize the RPC client and Tor control behaviour. libevent is still present.
  2. New test/functional/interface_bitcoin_cli_http.py. A Python raw-socket HTTP server records the request bytes. Cases:
  3. default request: line, header set, Content-Length, body ending in \n;
  4. -rpcwallet="a b/Γ©%~-._" β†’ path /wallet/a%20b%2F%C3%A9%25~-._;
  5. chunked response; no-Content-Length + close response;
  6. 401 with and without credentials (both messages);
  7. 503 β†’ Server response: …; 403 β†’ server returned HTTP error 403;
  8. 404/500 with JSON body passed through;
  9. empty 200 β†’ no response from server; non-JSON β†’ couldn't parse reply from server;
  10. 50 MB body succeeds;
  11. -rpcclienttimeout=1 with a silent server β†’ (error code 0 - "timeout reached");
  12. a trickle server (1 byte every 0.6 s for 3 s) with timeout 1 succeeds (inactivity semantics);
  13. refused port β†’ Could not connect to the server 127.0.0.1:<p> (error code 1 - "EOF reached");
  14. server closes after accept β†’ record the message;
  15. -rpcconnect=localhost β†’ record.

The outputs recorded on libevent become the expected values.

Outside the source tree (coordinator, stack-repair repo). Scope these per component; V1 still uses libevent:

These change only for components built from the eCash/V2 tier.

E1.5 V2

E1.6 Conflicts

E1.7 Acceptance

E1.8 Risks


Z1. Remove ZeroMQ from V2 only

Z1.1 Inventory at the V2 tip (verified, 596537e978)

Area Files
Source src/zmq/ (CMakeLists.txt, zmqabstractnotifier.{h,cpp}, zmqnotificationinterface.{h,cpp}, zmqpublishnotifier.{h,cpp}, zmqrpc.{h,cpp} with getzmqnotifications, zmqutil.{h,cpp})
init src/init.cpp: includes 100-104; shutdown unregister 398-405; -zmqpub*/-zmqpub*hwm args 1318-1362 and the hidden-arg block 1364-1373; RegisterZMQRPCCommands 2644-2646; sensitive-arg table 2750-2754; create/register 2936-2946
Options/logging src/common/args.{h,cpp} OptionsCategory::ZMQ and its help group; src/test/fuzz/system.cpp:62; src/logging.{h,cpp} BCLog::ZMQ / "zmq"
Build/config src/CMakeLists.txt (foreach(FEATURE … ZMQ …) deprecation line 13, option(BUILD_ZMQ) 18, native flag 83, if(BUILD_ZMQ) 783-791); src/config/CMakeLists.txt:198-199; src/config/bitcoin-config.h.cmake.in:57; cmake/modules/FindZeroMQ.cmake; test/config.ini.cmake.in:28
depends depends/packages/zeromq.mk, depends/patches/zeromq/remove_libstd_link.patch, packages.mk (zmq_packages=zeromq), depends/Makefile:40,146,168-169 (NO_ZMQ), depends/README.md:96
Tests test/functional/interface_zmq.py, timing.json:623, rpc_help.py:126-127, test_framework/test_framework.py:1064-1069,1097-1100,1148-1150, test/lint/check-doc.py:33-42, test/sanitizer_suppressions/tsan:9,48
Docs/contrib doc/zmq.md, doc/README.md:113, doc/functional-tests.md:29-32 (318/327 are naming examples: change them to interface_rest.py/interface_http.py), doc/build-osx.md, doc/build-unix.md, doc/dependencies.md, contrib/zmq/zmq_sub.py, contrib/CMakeLists.txt:20, contrib/guix/libexec/build.sh:236, contrib/teamcity/build-configurations.yml:412-418,620-623, contrib/debian/control, contrib/docker/chronik-plugins/Dockerfile, contrib/utils/install-dependencies-bookworm.sh, contrib/aur/*/PKGBUILD
Leave src/qt/locale/*.ts (generated; Qt removal is Q1), Base64 noise matches in src/qt/test/paymentrequestdata.h, secp256k1 vectors, JS apps

Decisions:

Z1.2 Commit plan (V2 tier; [v2 only]; each builds and passes)

  1. Z1-a [v2 only] test: drop ZeroMQ tests and framework helpers.
  2. Remove interface_zmq.py, its timing.json entry, the Zmq branch in rpc_help.py, skip_if_no_py3_zmq/skip_if_no_bitcoind_zmq/is_zmq_compiled, and the ENABLE_ZMQ line in config.ini.cmake.in. Remove the last two only together with their only users.
  3. git grep -n zmq test/functional must then be empty.
  4. Source still builds with ZMQ. All tests pass.
  5. Z1-b [v2 only] node: remove the ZeroMQ notification interface.
  6. Delete src/zmq/.
  7. Remove the init.cpp blocks (all six locations), OptionsCategory::ZMQ (+ help group + fuzz system.cpp entry), BCLog::ZMQ, the check-doc.py ignore entries, the TSan suppressions, the CMake option/subdirectory/native flag/config define, the FindZeroMQ.cmake module, and the config.ini line if Z1-a left it.
  8. Add the FATAL_ERROR guard.
  9. Add a test to feature_config_args.py: starting with -zmqpubhashblock=tcp://127.0.0.1:1 fails with the unknown-parameter error.
  10. Z1-c [v2 only] depends: remove the ZeroMQ package. zeromq.mk, its patch, packages.mk, Makefile NO_ZMQ lines, README. A passed NO_ZMQ=1 is ignored.
  11. Z1-d [v2 only] doc,contrib: remove ZeroMQ documentation and packaging.
  12. The docs and contrib rows of the table.
  13. The Guix flag, plus TeamCity: delete the build-without-zmq job and the qemu note.
  14. Release note: ZeroMQ was removed from V2. Use Chronik WebSocket (/chronik/ws) for block and transaction push.

Z1.3 Conflicts

The numbers come from different bases, so they are approximate, but no region overlaps. The closest are 0001's 2622 deletion, which sits next to RegisterZMQRPCCommands at ~2644 after shifts, and 0001's 2701 against the -zmq sensitive-arg table. Verify with git am -3.

Z1.4 Acceptance

Z1.5 Risks