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.
- The task names HEAD
3cf1891b91. While this design was being written the branchreview/lotus-v2-repaired-source-20261019moved to596537e978(lane E's final composition: 101 eCash + 57 V2 commits; stack-repaircb178fc7"Integrate ordered lane E delivery"). - At
596537e978the eCash tier tip is9541e65da6. - At
3cf1891b91the eCash tier tip isfe649023c3. - The two eCash tips differ only in
src/rpc/server.cppandsrc/test/CMakeLists.txt. - None of the files this design changes differ between them, so the analysis covers both.
- V2-side file numbers below are from
596537e978. - Patch numbers are the stack-repair series (
daemon/patches/ecash/series,daemon/patches/v2/series). eCashNNN= commitNNN+1in the source log. - Hand-off read:
/private/tmp/beast-http-p2p-patches/HANDOFF-20261019.mdand the hunk headers ofadditions-20261019b/{generic,v2-only}. - Coordinator notes read:
/private/tmp/build-zero-copy-slab/v2-identity/handoff/*.
Verified in source (each item cites code read):
NotificationsProxy(src/node/interfaces.cpp:439-475) callsChain::Notificationssynchronously on the ValidationSignals scheduler thread.NotificationsHandlerImpl::disconnect()only unregisters.SyncTransactionQueue()already exists and is already fenced by bothSyncWithValidationInterfaceQueue()andFlushBackgroundCallbacks(). It came from eCash060(18d5b2c847).BoundedTaskQueue(src/util/bounded_task_queue.h) only has a fail-closed overflow mode.chain.handleNotificationshas two more callers:- Avalanche
src/avalanche/processor.cpp:178; src/bench/wallet_balance.cpp.BroadcastTransaction(wait_callback=true)(src/node/transaction.cpp:93-113) waits only on the main scheduler queue.sendrawtransactionadditionally callsSyncWithValidationInterfaceQueue()(src/rpc/mempool.cpp:133-136).submitpackage(src/rpc/mempool.cpp:1158) does not.- Wallet:
AttachChainregisters the handler while holdingcs_wallet.BlockUntilSyncedToCurrentChainasserts!cs_wallet.chainStateFlushedtakes no wallet lock.m_best_block_timeis atomic. TheCreateWalletunit test blocks the scheduler with a promise. - Shutdown order (
src/init.cppShutdown):FlushBackgroundCallbacks()runs beforeclient->stop()(UnloadWallets). - libevent uses at the eCash tip are exactly:
src/bitcoin-cli.cpp;src/torcontrol.cpp;src/util/url.cpp(evhttp_uridecode);src/support/events.h;src/test/raii_event_tests.cpp;src/httpserver.cpp(log callback,event_enable_debug_logging, plus a dead<event2/event.h>include);- a dead
<event2/http.h>include insrc/wallet/rpcwallet.cpp; - CMake
link_eventonutil,server(+pthreads) andbitcoin-cli; cmake/modules/FindEvent.cmake,cmake/utils/EventCheckVersion.cpp;depends/packages/libevent.mk,packages.mk;- docs and contrib files (list in E1.6).
- No fuzz or bench target uses libevent.
src/bench/nanobench.hPERF_EVENT_*is unrelated. - No functional test exercises the Tor control protocol. Only
torcontrol_tests.cpptests the two parsers. - ZeroMQ inventory at the V2 tip is section Z1.1.
rpc_misc.pyassertslen(logging()) >= 26. Today there are 28 categories. V2-only0001removesi2p.- V2
003(d74c3f0b08, branding): - renames the
bitcoin-cliCMake target tolotus-cli, including thelink_event(...)line; - edits strings inside
CallRPC. - V2 still starts Tor control. At hand-off tip
dd093f72ec,init.cpp:3390callsStartTorControl,-listenonionstays, and onion binds become WebSocket listeners (v2-only0002).
Assumed (verify during implementation; each has a characterization test below):
- CLI error codes. libevent reports connection refused to
bitcoin-cliasEVREQ_HTTP_EOF(1, "EOF reached"), and a timeout asEVREQ_HTTP_TIMEOUT(0). E1.1 records the real outputs before the port. - Tor control address parsing.
evutil_parse_sockaddr_port: - accepts IPv4,
[IPv6]and bare IPv6, with an optional port; - rejects host names;
- rejects ports outside 1β65535 when a port is given. E1.1 checks this differentially against libevent.
- Unit-test fixture.
TestChain100Setupsetsm_node.chain. If it does not, the tests create it withinterfaces::MakeChain(m_node, Params()). - eCash-tier wallet suites. These pass at the eCash tip
9541e65da6. The coordinator's failing lists and lane E's residuals are V2-tier results; this design did not run any eCash-tier gate. - Bitcoin Core precedent. Core has worked on removing libevent from torcontrol and the HTTP client. This design neither copies nor depends on that work, and did not look at it.
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:
- the worker is one thread;
- it is FIFO;
- it receives events in scheduler order.
So the CValidationInterface contract (serial callbacks, in generation order) still holds for each wallet. The changes are confined to these:
- Cross-subscriber timing. A wallet may lag Chronik, PeerManager, etc. No ordering across subscribers is documented (
validationinterface.hclass comment), so this is allowed. - Fences. Fences that wait only on the main queue no longer cover the wallet. Fixed in W1.3.
- Lifetime. Unregister must drain and join the worker.
- 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
- Scope. Opt-in through a new
interfaces::Chain::NotificationDeliveryargument. The default staysSCHEDULER_THREAD. OnlyCWallet::AttachChainpassesDEDICATED_WORKER. - One worker per wallet registration. Not one shared worker:
- each wallet's FIFO stays independent;
- unload drains only that wallet;
- a thread per loaded wallet is acceptable. Thread name:
walletnotify(12 characters, within the Linux 15-character limit). - Backpressure: block the producer. Do not use Chronik's fail-closed mode.
- The producer is the scheduler thread, or the
FlushBackgroundCallbackscaller at shutdown. - Why:
AttachChainholdscs_walletfor the whole load rescan, which can take minutes on a busy node, while events keep arriving. A fail-closed queue would shut the node down during a normal wallet load. - Blocking adds nothing new. In the worst case it reproduces today's behaviour, where the scheduler waits on
cs_wallet. That wait already throttles validation throughLimitValidationInterfaceQueue(validation.cpp:4731,CallbacksPending() > 10). - Limits (bounded memory, not lossy):
MAX_TASKS = 65536,MAX_BYTES = 64 MiBper wallet,TASK_OVERHEAD = 256bytes. - A single task larger than the byte limit is admitted only when the queue is empty, so a 32 MB block never deadlocks the queue.
- Exceptions. Today an exception thrown by a wallet callback on the scheduler thread terminates the process. New behaviour:
- On the first worker exception,
m_failedis set. - The node logs
FATAL: wallet notification worker failed; shutting down. The wallet rescans from its last flushed best block on restart.and callsStartShutdown(). This is the same mechanism Chronik uses (<shutdown.h>). - All later queued tasks for that wallet are discarded, not run. In particular a later
chainStateFlushedmust not advance the persisted locator past a block the wallet failed to apply. Sync()still completes. Discarded tasks count as completed.- Unload.
NotificationsHandlerImpl::disconnect()unregisters, then callsStopWorker(). StopWorker()runs every accepted task, then joins. Accepted events are real wallet updates.- Events that reach
EnqueueafterStopare dropped. The wallet is unloading, and its persisted locator makes the next load rescan. - The caller must not hold
cs_wallet. Every in-tree caller already satisfies this:RemoveWalletfrom RPC,UnloadWalletsat shutdown, theCWallet::Createfailure path atwallet.cpp:3003-3005, which is outsideAttachChain's lock, andTestUnloadWallet. The rule is documented onHandler. - Fence completeness. Add
ValidationSignals::SyncSecondaryQueues().BroadcastTransaction(wait_callback=true)calls it after its main-queue promise resolves. This coverssubmitpackage, Qtwalletview.cpp:315and future callers. As a side effectsubmitpackagealso waits for Chronik indexing (eCash060), which is the documented intent ofwait_callback.
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).
- Add
enum class Overflow { FAIL, BLOCK };. - New constructor:
BoundedTaskQueue(size_t byte_limit, size_t count_limit, std::function<void()> fail, Overflow overflow = Overflow::FAIL, std::string thread_name = {}). - Chronik's call is unchanged, which keeps it at
FAIL. - The worker calls
util::ThreadRename(thread_name)when the name is non-empty. Include<util/threadnames.h>. EnqueuewithBLOCK:assert(std::this_thread::get_id() != m_worker.get_id()).- Under
m_mutex, wait onm_drained(reused as the "space freed" condition variable) for:m_stopping || m_count == 0 || (m_count < m_count_limit && bytes <= m_byte_limit && m_bytes <= m_byte_limit - bytes). This form cannot underflow, even when an oversized task was admitted. - If
m_stopping, returnfalse. - Otherwise push exactly as today, including the allocation-failure path, which calls
m_failand setsm_failed/m_stopping. FAILmode keeps today's code path byte-for-byte in behaviour.Stop()additionally callsm_drained.notify_all()after settingm_stopping, so blocked producers wake and returnfalse.Run()is unchanged. It already notifiesm_drainedafter every task.
Tests, in src/test/validationinterface_tests.cpp: extend the existing suite, so no CMake change is needed.
bounded_worker_block_policy_waits_for_space:- Count limit 2. The worker is held on a latch. Enqueue 1 and 2.
- Enqueue 3 from a helper thread. Its future is not ready after 50 ms.
- Release the latch. Order is
{1,2,3},BytesRetained()==0, andfailis never called. bounded_worker_block_policy_admits_oversized_when_empty:- Byte limit 8. A 9-byte task is accepted on an empty queue.
- A second 1-byte task waits until the first completes.
bounded_worker_block_policy_stop_releases_producer: a blocked producer returnsfalsewhenStop()is called. The accepted tasks still ran.bounded_worker_fail_policy_unchanged: the existing three cases pass untouched.
Commit W1-b: validation: fence secondary queues for broadcast callers that wait
src/validationinterface.{h,cpp}:- Add public
void SyncSecondaryQueues() LOCKS_EXCLUDED(cs_main);, which runsAssertLockNotHeld(cs_main)and the existingIterate(... SyncTransactionQueue()). SyncWithValidationInterfaceQueue()andFlushBackgroundCallbacks()call it in place of their inline lambdas. Their behaviour is identical.src/node/transaction.cpp: afterpromise.get_future().wait();(line 112), addnode.validation_signals->SyncSecondaryQueues();. Thecallback_setbranch is already outsidecs_main.src/node/transaction.h: extend thewait_callbackdoc comment to say "and their secondary worker queues". The deadlock warning forcs_main/cs_mempool/cs_walletnow also covers the wallet worker.- Test, in
validationinterface_tests.cpp,broadcast_wait_fences_secondary_queue: - Register the existing
SecondaryQueueSubscriber-style fake. ItsTransactionAddedToMempoolenqueues work on a held worker. - Call
node::BroadcastTransaction(..., wait_callback=true)from a helper thread. - It must not return while the worker is held, and must return after release. Use
TestChain100Setupwith a valid coinbase spend.
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:
NotificationsProxy(std::shared_ptr<Chain::Notifications>, Chain::NotificationDelivery).- With
DEDICATED_WORKER, it constructsstd::optional<BoundedTaskQueue> m_queuewith(64 MiB, 65536, [this]{ OnWorkerFailure(); }, Overflow::BLOCK, "walletnotify"). - With
SCHEDULER_THREAD,m_queuestays empty and every callback runs inline exactly as today. - Add
using CValidationInterface::TransactionAddedToMempool;. template <typename F> void Dispatch(size_t bytes, F &&f):- inline when there is no queue;
- otherwise
m_queue->Enqueue(TASK_OVERHEAD + bytes, [this, f = std::forward<F>(f)]() mutable { if (!m_failed.load()) f(); });. - Callbacks. Copy the payloads; never keep a
CBlockIndex*:
| 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() |
void SyncTransactionQueue() override { if (m_queue) m_queue->Sync(); }.Sync()already returns when called from the worker itself.void StopWorker() { if (m_queue) m_queue->Stop(); }. Call it from~NotificationsProxy()as well.OnWorkerFailure(): setm_failed = true, log the FATAL line, callStartShutdown(). Include<shutdown.h>and<util/validation_queue_memory.h>.NotificationsHandlerImpltakesdelivery.disconnect():if (m_proxy) { m_signals.UnregisterSharedValidationInterface(m_proxy); m_proxy->StopWorker(); m_proxy.reset(); }.ChainImpl::handleNotifications(n, delivery)forwardsdelivery.
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:
- Delivery tests use a fake
Chain::Notifications, notCWallet. They live insrc/test/validationinterface_tests.cpp, withTestChain100Setupandm_node.chain->handleNotifications(fake, DEDICATED_WORKER). They do not depend on wallet IsMine, so they also run unchanged at the V2 tier, where lane E records legacy-CWallet ownership failures. async_notifications_offload_scheduler:- The fake's
blockConnectedblocks on a latch. - Mine 3 blocks.
- A main-queue-only fence (
CallFunctionInValidationInterfaceQueueplus a promise) completes while the fake is still blocked. This proves the offload. SyncWithValidationInterfaceQueue()from a helper thread does not complete until the latch is released.- The fake then saw heights in order and
updatedBlockTipafter the lastblockConnected. async_notifications_preserve_order_across_reorg:InvalidateBlockplus re-mine.- The fake's recorded sequence (removed, disconnected, connected, added events with heights) equals the sequence recorded by a synchronous registration of a second fake, run side by side.
async_notifications_disconnect_drains:- Hold the fake. Queue 10 events. Call
handler.reset()on a helper thread. - It returns only after all 10 ran.
- Events generated after
resetare not delivered. async_notifications_worker_exception_discards_rest:- The fake throws on the second
blockConnected. - Shutdown is requested (
ShutdownRequested()), then cleared at the end of the test withAbortShutdown(). - The third
blockConnectedand the followingchainStateFlushedare not delivered. SyncWithValidationInterfaceQueue()returns.- End-to-end tests in
src/wallet/test/wallet_tests.cpp, eCash tier: - The existing
CreateWalletandZapSelectTxmust pass unchanged. They exercise attach and rescan with a blocked queue,HandleLoadWalletsyncing during load, andTestUnloadWallet. - New
wallet_async_broadcast_visible: - A helper thread holds
cs_walletfor 200 ms. - The test calls
BroadcastTransaction(wait_callback=true)with a spend to a wallet key. - After return,
mapWallet.count(txid)==1andfInMempoolis true.
Commit W1-d: doc: wallet notification worker
doc/developer-notes.mdthread list: addwalletnotify.doc/release-notes.md:- wallet callbacks no longer run on the validation thread;
unloadwalletwaits for queued notifications;- a wallet notification failure shuts the node down instead of aborting it.
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
- Ordering. One producer (the scheduler), FIFO, one consumer. The ordering doc in
validationinterface.h(TransactionRemovedFromMempoolbeforeBlockConnected, and so on) is preserved per wallet. BlockUntilSyncedToCurrentChain. It doeswaitForNotificationsIfTipChangedβSyncWithValidationInterfaceQueue():- The main queue drains, so every earlier event has been handed to the wallet queue.
SyncSecondaryQueues()then waits form_completed >= m_submitted. Because the main fence passed, no producer is blocked mid-Enqueuefor an earlier event, so the target count is complete. The unchanged-tip early return behaves exactly as today. Its mempool staleness is today's semantics, andsendrawtransaction/submitpackageare covered by the explicit fences.- Shutdown (verified order):
client->flush().scheduler->stop().ForceFlushStateToDisk, which generatesChainStateFlushed.FlushBackgroundCallbacks(). This flushes the main queue on the shutoff thread, which may block on a full wallet queue while the worker keeps draining, then waits for the wallet queues. The wallet's best-block locator is therefore written before unload.- The second flush's
ChainStateFlushedis never dispatched: the scheduler has stopped. That is the same as today. client->stop()βUnloadWalletsβRemoveWalletβdisconnect()drains (normally empty) and joins.UnregisterAllValidationInterfaces()finds no live workers.- Wallet unload during operation.
unloadwalletnow waits for that wallet's queued events (bounded by the limits) beforeNotifyUnload/WaitForDeleteWallet. Previously the scheduler could still run wallet callbacks after unregister through the in-flightshared_ptr. Draining is strictly safer. - Rescans.
AttachChain: register, then rescan undercs_wallet. Queued events wait oncs_walletin the worker instead of the scheduler, so the documented duplicate-processing semantics are unchanged.m_attaching_chain-gatedchainStateFlushed: FIFO puts it after theblockConnectedevents that waited for the lock, exactly as today.rescanblockchain/import rescans run on RPC threads, concurrently with the worker, as they ran concurrently with the scheduler before.requestMempoolTransactionscalls the wallet directly, bypassing the proxy, as before.- Deadlocks.
- New waits: producer β worker (when full), and fence callers β worker. The worker needs
cs_wallet, and throughchain()calls alsocs_main/mempool.cs. - Every fence caller already waited on the main queue, which today runs the same wallet code. So any caller that holds one of those locks already deadlocks today.
SyncWithValidationInterfaceQueueasserts!cs_main;BlockUntilSyncedToCurrentChainasserts!cs_wallet. - The worker never waits on the scheduler. No wallet callback calls a fence.
- The producer blocks only in proxy callbacks, which run with no lock held.
Enqueue(BLOCK)asserts it is not on the worker. The newdisconnect()drain documents and asserts!cs_walletthrough the call-site comment. AddAssertLockNotHeld(wallet->cs_wallet)inRemoveWallet.- Memory. Validation can now run up to 64 MiB / 65536 events per wallet ahead of a stalled wallet before backpressure reaches
LimitValidationInterfaceQueue. That bound is deliberate. - Qt.
CWalletsignals (NotifyTransactionChanged, ...) now fire onwalletnotifyrather than the scheduler thread. Qt connects them with queued connections, so this is thread-safe. Not exercised: Qt is not built in the coordinator gates.
W1.5 Conflicts
- eCash
060(bounded_task_queue.h,validationinterface.{h,cpp},validationinterface_tests.cpp): W1 is appended after it and is additive. - eCash
059(entry_time overload): W1 adds theusingdeclaration. - eCash
020/040(rpc/mempool.cpp,node/transaction.cpp): W1 touches only lines 108-113 oftransaction.cpp. - V2
032(validationinterface.cpplog-format hunks): different hunks. - V2
033(wallet.cppstorage hunks): different hunks. - Networking hand-off: none. W1 touches neither
init.cppnor the HTTP or net files. - Lane 3 logging call-site conversion: may rewrite the new
LogPrintf. Trivial to rebase.
W1.6 Test plan and acceptance
eCash tier (replay ecash series + W1):
test_bitcoinbuilds; Chronik ON and OFF; wallet ON.- One-process run of the full
test_bitcoin: 100 % pass, except the known/privatelogargspath issue. Includevalidationinterface_tests,wallet_tests,walletdb_tests,coinselector_tests,ismine_tests,scriptpubkeyman_tests,psbt_wallet_tests,wallet_crypto_tests,db_tests,init_tests. - Repeat the new tests plus
wallet_tests/CreateWallet200 times (--run_test=β¦loop). No failure. - Full functional suite passes. Name these in the report:
wallet_*.py, includingwallet_multiwallet.py --usecli,wallet_reorgsrestore,wallet_abandonconflict,wallet_resendwallettransactions,wallet_backup,wallet_startup,wallet_importdescriptors,wallet_import_rescan,wallet_listsinceblock;feature_notifications,rpc_rawtransaction,rpc_packages,mempool_persist;feature_pruning(--extended).- TSan. Linux,
-DENABLE_SANITIZERS=thread:test_bitcoin -t validationinterface_tests,wallet_tests, plus functionalwallet_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. - Optional evidence, no speedup claim without an interleaved baseline: scheduler callback latency during
generatetoaddress 100with a 10k-tx wallet, before and after.
V2 tier (replay ecash + W1 + v2):
- The fake-subscriber tests and
validationinterface_testspass. - Wallet suites show exactly lane E's recorded residual failures and nothing new.
W1.7 What W1 must wait for
- Lane E composition (landed at
596537e978, eCash tip9541e65da6). Rebase onto it. - V2 wallet residuals. Lane E reports that the full-process wallet-ON gate still fails 3 legacy-
CWalletcases: scan, import andListCoinswith native-coinbase ownership. They fail because native V2 outputs keep their canonical V2 bytes while the oldCWalletexpects legacy scripts. - Until those are fixed, V2-tier wallet results cannot validate W1. That is why W1's delivery tests use a fake subscriber.
- W1 can land on the eCash tier first, with eCash-tier gates only.
- The V2-tier claim waits for lane E's residual fix and for J3 (native MiniWallet) before functional wallet tests mean anything at V2.
- W1 needs nothing from the networking hand-off.
W1.8 Risks
unloadwalletlatency is now bounded by the queue depth, not instant.- Repeated rescans. A wallet stalled by a long rescan lets up to 64 MiB of events accumulate. Bounded, but visible in memory.
- Hidden lock dependency in the drain. Some out-of-tree caller may reset the handler under
cs_wallet(Qt was checked: unload is on the GUI thread without the lock; not run). The assert catches it in debug builds. - Exception policy. Moves from terminate to shutdown-plus-discard. This is safer, but different.
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:
- Keep the
libeventlog category as an accepted category with no effect. Three reasons: - Operator configs and the test framework pass
-debug/-debugexclude=libevent. - Removing it would turn those into "Unsupported logging category" warnings.
rpc_misc.pyasserts>= 26categories. 28 today; V2-only0001removesi2p; Z1 removeszmq. Removinglibeventtoo would leave V2 at 25 and fail the test.
Document it in the release note as deprecated.
- Keep the opaque
struct event_base/EventBase()token. It is an incomplete type and needs no libevent header or library. Renaming it would conflict with v2-only0002, whosehttpserver.hhunk context includesstruct event_base;and theEventBase()comment. A rename can come later, after the hand-off settles. - Preserved quirks: the Tor reconnect backoff has no cap, and
MAX_LINE_LENGTHdisconnects without invokingdisconnected_cb, so there is no reconnect. Both are kept exactly. Fixing either is a separate change. - One intentional CLI deviation. For a
-rpcconnecthost name, libevent's blocking resolve connects only to the firstgetaddrinforesult (assumed). The port tries each resolved endpoint in order, throughasio::async_connectover the resolver results. The result is identical whenever the first endpoint works. E1.1's characterization records libevent's behaviour forlocalhost.
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.
- Replace the libevent transport with
static HTTPReply HTTPPost(const std::string &host, uint16_t port, const std::string &target, const std::string &auth_header, std::string body, int timeout_secs). HTTPReplykeepsstatus,error(default -1) andbody.- Keep
http_errorstring(int)with identical numbers and strings, using a local enum that mirrors libevent's values:
| 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:
- One
boost::asio::io_context,tcp::resolver,beast::tcp_stream, async operations,io.run(). - Resolve
host/portwithasync_resolve, flags none. Thenbeast::async_connectover the results. - Resolve or connect failure β
status = 0and the error mapping below.
Request (http::request<http::string_body>):
- Method POST,
target="/"or"/wallet/" + urlEncode(rpcwallet), version 11. - Fields, in this order:
Host: <host>(host only, no port, as today),Connection: close,Content-Type: application/json,Authorization: Basic <b64>. - Body = the request with its trailing
"\n".prepare_payload()setsContent-Length. - No
User-Agentand noAccept-Encoding, so the server never compresses. - Header order and the exact header set are checked against the E1.1 recording. If libevent's order differs, match it.
Response:
http::response_parser<http::string_body>withbody_limit(boost::none)(unlimited; libevent's client default) andheader_limit(1 << 20).- Read in a loop of
http::async_read_someuntilis_done(). Beast's handling covers chunked encoding and EOF-delimited bodies. - Timeout = inactivity, matching
evhttp_connection_set_timeout: - if
timeout_secs > 0, callstream.expires_after(seconds(timeout_secs))before resolve+connect, before the write, and before eachasync_read_some; - if
<= 0, callstream.expires_never(). This replaces the 5-year emulation, which was a libevent limitation.
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:
- the status-handling block from
if (response.status == 0) {through thereturn reply;ofCallRPC, including the strprintf text and\n\nMake sure the bitcoind server is runningβ¦; - credential and cookie logic;
ConnectAndCallRPC(-rpcwait1-second retry; the warmup check).
Do not reflow these lines. V2 003 changes bitcoind β lotusd at the old line 813 and needs that context.
Removals:
libevent_log_cb;event_set_log_callbackinmain;#include <support/events.h>,<event2/*>.
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:
std::optional<tcp::socket> m_socket;std::string m_rbuf;std::deque<std::string> m_wqueue;bool m_writing;uint64_t m_gen(generation; increments on everyDisconnect());connected,disconnected,message,reply_handlers,async_handler, as today.
Connect(center, connected, disconnected):
- If a socket exists,
Disconnect(). - Parse with
ParseTorControlAddress, numeric only, same accepted forms asevutil_parse_sockaddr_port. On failure, logtor: Error parsing socket address %sand return false (no reconnect, as today). - Create the socket. On a synchronous open failure, log
tor: Error connecting to address %sand return false. - Store the callbacks, call
async_connect, and return true. - On completion, if the generation still matches:
- success β log
tor: Successfully connected!and callconnected(*this), then start reading; - error β log
tor: Error connecting to Tor control socket,Disconnect(),disconnected(*this). - 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':
- Take the line and strip one trailing
'\r'(matchesEVBUFFER_EOL_CRLF: optional CR before LF). - Apply the unchanged body of today's
readcbloop: lines of fewer than 4 characters are skipped; the status code and lines are accumulated;' 'dispatches. Codes>= 600go toasync_handler, otherwise toreply_handlers.front()followed bypop_front, or to the "Received unexpected sync reply" log. - 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):
- Return false if there is no socket.
- Append
cmd + "\r\n"tom_wqueueand push the handler. - If idle and connected, start
async_write. - 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)
asio::steady_timer m_reconnect_timer{io}replacesreconnect_ev. The constructor's out-of-memory log goes away.disconnected_cb:- Remove the local service.
- If
reconnect, log as today. m_reconnect_timer.expires_after(std::chrono::milliseconds(int64_t(reconnect_timeout * 1000.0))), thenasync_waitβ if not aborted,Reconnect().reconnect_timeout *= RECONNECT_TIMEOUT_EXP.connected_cbresetsreconnect_timeout = RECONNECT_TIMEOUT_START.RECONNECT_TIMEOUT_START = 1.0,RECONNECT_TIMEOUT_EXP = 1.5. No cap (preserved).- The authentication and onion logic is unchanged text-for-text:
protocolinfo_cb: password beats NULL, NULL beats SAFECOOKIE, then the HASHEDPASSWORD-missing message. Quote escaping in-torpassword.authchallenge_cb: 32-byte nonce check, ServerHash verification.ComputeResponseHMACs.auth_cb: the-oniondefault proxy127.0.0.1:9050; theSetReachablerule.ADD_ONION %s Port=%i,%swithNEW:ED25519-V3.add_onion_cb: the 250/510/other branches;ServiceID/PrivateKey;WriteBinaryFile(onion_v3_private_key);AddLocal(LOCAL_MANUAL).- Destructor
RemoveLocal.
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(); } }
io_context::stop()is thread-safe. It is sticky if called beforerun(), which matchesevent_base_once+loopbreak.- Pending handlers are destroyed without being invoked. They capture only raw
this, so this is safe. evthread_use_*disappears.
Logging: every log string and category (BCLog::TOR) is unchanged.
E1.4 Commit plan (eCash tier; one concern each; each builds and passes)
- E1-a
test: characterize the RPC client and Tor control behaviour. libevent is still present. - New
test/functional/interface_bitcoin_cli_http.py. A Python raw-socket HTTP server records the request bytes. Cases: - default request: line, header set,
Content-Length, body ending in\n; -rpcwallet="a b/Γ©%~-._"β path/wallet/a%20b%2F%C3%A9%25~-._;- chunked response; no-
Content-Length+ close response; - 401 with and without credentials (both messages);
- 503 β
Server response: β¦; 403 βserver returned HTTP error 403; - 404/500 with JSON body passed through;
- empty 200 β
no response from server; non-JSON βcouldn't parse reply from server; - 50 MB body succeeds;
-rpcclienttimeout=1with a silent server β(error code 0 - "timeout reached");- a trickle server (1 byte every 0.6 s for 3 s) with timeout 1 succeeds (inactivity semantics);
- refused port β
Could not connect to the server 127.0.0.1:<p> (error code 1 - "EOF reached"); - server closes after accept β record the message;
-rpcconnect=localhostβ record.
The outputs recorded on libevent become the expected values.
- New
test/functional/feature_torcontrol.py. A Python mock control port (threading+socket). Cases: - NULL auth β
AUTHENTICATE, thenADD_ONION NEW:ED25519-V3 Port=<defaultport>,127.0.0.1:<onion target>. Reply250-ServiceID=<56 chars>,250-PrivateKey=ED25519-V3:k,250 OK. Check: getnetworkinfo.localaddressescontains<id>.onion:<port>;- the onion proxy is
127.0.0.1:9050and reachable; - the file
onion_v3_private_keyholdsED25519-V3:k. - Restart β
ADD_ONION ED25519-V3:k β¦. - SAFECOOKIE with a 32-byte cookie file β the client HMAC verifies. A wrong ServerHash β log
does not match expected ServerHashand noAUTHENTICATE. -torpassword=pa"sswith HASHEDPASSWORD βAUTHENTICATE "pa\"ss". A password without HASHEDPASSWORD β log.- The mock closes β onion removed from
localaddresses. Reconnect intervals β₯0.9 s, then β₯1.35 s. - 510 β
You probably need to upgrade Tor. - 100001 bytes without LF β
MAX_LINE_LENGTH exceededand no reconnect within 3 s. -torcontrol=localhost:9051βError parsing socket address.- LF-only line endings and replies split across TCP segments work.
- Unit tests:
src/test/torcontrol_tests.cppgainsParseTorControlAddressvectors, differential againstevutil_parse_sockaddr_port. Add the new parser here, unused.src/test/util_tests.cppgains aurlDecodecorpus checked differentially againstevhttp_uridecode(including%00truncation, invalid%zz, a trailing%,+kept) and aurlEncodecorpus againstevhttp_uriencode. - E1-b
util: decode and encode URLs without libevent. src/util/url.{h,cpp}: ownurlDecode. Semantics:%XXwith two hex digits (any case) decodes;- anything else is copied;
- no
+mapping; - the result truncates at the first decoded NUL, matching today's
std::string(char*). - New
urlEncode: unreservedA-Za-z0-9-._~is kept; everything else becomes%XXin uppercase hex. - Keep the differential tests; they now compare the new code with libevent.
link_event(util event)stays until E1-e.- E1-c
cli: send RPC requests with Boost.Beast instead of libevent. Per E1.2. Removelink_event(bitcoin-cli event).interface_bitcoin_cli*.pypasses unchanged. - E1-d
torcontrol: run the Tor controller on Boost.Asio. Per E1.3. AddTorControlConnectionunit tests intorcontrol_tests.cppusing an in-testtcp::acceptoron127.0.0.1:0: framing, async 650, MAX_LINE without callback, EOF with callback, command queued before connect.feature_torcontrol.pypasses unchanged. - E1-e
build: remove libevent. - Remove everything in the E1.1 table marked "E1-e".
- The differential tests become fixed vectors, the values recorded in E1-a.
loggingkeeps"libevent".rpc/misc.cppdrops itsUpdateHTTPServerLoggingcall.httpserver.hdrops theUpdateHTTPServerLoggingdeclaration. It sits afterStopHTTPServer, outside v2-only0002's hunk at lines 42-62. Verifygit amof0002after this.- E1-f
doc,contrib: drop libevent from build instructions and packaging. - Update the docs and contrib list.
- Release note: libevent removed;
-debug=libeventaccepted with no effect. - Thread docs:
b-httpis now Boost.Asio;torcontrolis now Boost.Asio. - Do not touch
electrum/.
Outside the source tree (coordinator, stack-repair repo). Scope these per component; V1 still uses libevent:
.github/workflows/release-daemon.yml,release-components.yml(libevent-dev, brewlibevent);daemon/scripts/package-linux.py:67,component-release.py:252,prepare-release.py:138-141runtime deps.
These change only for components built from the eCash/V2 tier.
E1.5 V2
- Nothing V2-specific is needed for removal. The V2 tier inherits the eCash tier.
- V2 should keep Tor control enabled (
-listenoniondefault 1, unchanged). At hand-off tipdd093f72ec: - V2 still calls
StartTorControl; - it keeps
-onion/-proxy; - it turns onion binds into HTTP/WebSocket listeners (v2-only
0002). - So the ephemeral onion service maps virtual port = default P2P port β onion target. That target is now a WebSocket listener, and onion peers dial
ws://<id>.onion:<port>/p2p/wsthrough Tor. auth_cbalso supplies the onion proxy when-onionis unset. WebSocket-only P2P removes neither function.- Not verified at runtime for V2. Add a V2-only follow-up check: run
feature_torcontrol.pyat the V2 tip, plus onews://onion dial through the mock path.
E1.6 Conflicts
- V2
003(branding). Itssrc/CMakeLists.txthunk containslink_event(bitcoin-cli event)βlink_event(lotus-cli event), which E1-c deletes. The coordinator must refresh V2003to drop that line pair. Itsbitcoin-cli.cppstring hunks apply only if E1-c keeps theCallRPCstatus block verbatim (required above). - eCash
073and generic0029/0032-0034(httpserver.*,src/CMakeLists.txt,src/test/CMakeLists.txt): E1 is appended after them. - v2-only
0002.httpserver.hcontext isstruct event_base;/EventBase()comment; E1 keeps both. It also touchesinit.cpp, which E1 does not. - v2-only
0001. It removesi2pfromlogging.{h,cpp}; E1 does not touch those lines. - Hand-off lane 3 (logging/metrics;
logging.*, possiblyhttprpc.cpp): E1 does not edit these beyond therpc/misc.cppbranch. It is a trivial rebase. - Identity patches (
chainparams, test CMake): no overlap.
E1.7 Acceptance
- E1-a passes on libevent.
- After each later commit, these pass with identical output:
interface_bitcoin_cli.py,interface_bitcoin_cli_http.py,feature_torcontrol.py;feature_proxy.py,feature_config_args.py,rpc_misc.py,wallet_multiwallet.py --usecli;torcontrol_tests,util_tests;- the full functional suite with
--useclifor a sample of wallet tests. - After E1-e:
git grep -nE 'event2/|evhttp|evbuffer|bufferevent|evutil|event_base_|libevent\.mk|FindEvent|link_event'oversrc cmake depends testreturns only the keptstruct event_basetoken and logging-category lines;otool -L/lddofbitcoind(lotusd) andbitcoin-cli(lotus-cli) show no libevent;- a clean
dependsbuild (make -C depends NO_QT=1) and acontrib/guixLinux build succeed. - macOS and Linux both. Windows (mingw depends): build only. If not run, say so.
E1.8 Risks
- CLI error text outside the characterized cases (DNS failure text, half-closed connections). Mitigated by the recording.
- Tor control has no real-Tor test in CI. The mock tests the protocol as the code speaks it, not Tor's behaviour. Run once by hand against a real
torwithControlPort+CookieAuthentication 1and withHashedControlPassword, and record the result. - Unbounded inactivity timeout.
-rpcclienttimeout=0is now truly unbounded instead of five years.
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:
-zmq*is rejected after removal. No hidden-arg compatibility; V2 is a new chain. On the command line it is an unknown-parameter error. In a config file, standardArgsManagerunknown-key handling applies, whatever the base does today; do not special-case it.- Remove
BCLog::ZMQ. Leave bit 5 unused; do not renumber.rpc_misc.py's>= 26still holds: 28 βi2pβzmq= 26, withlibeventkept (E1). Assert the exact count in the Z1 report. - Stale
BUILD_ZMQ=ONfails. Removeoption(BUILD_ZMQ). Add tosrc/CMakeLists.txt:if(BUILD_ZMQ) message(FATAL_ERROR "ZeroMQ is not part of Lotus V2; remove -DBUILD_ZMQ=ON") endif().-DBUILD_ZMQ=OFF, passed by the stack-repairpatch-progression.py, stays harmless. DropZMQfrom the deprecationforeach.
Z1.2 Commit plan (V2 tier; [v2 only]; each builds and passes)
- Z1-a
[v2 only] test: drop ZeroMQ tests and framework helpers. - Remove
interface_zmq.py, itstiming.jsonentry, theZmqbranch inrpc_help.py,skip_if_no_py3_zmq/skip_if_no_bitcoind_zmq/is_zmq_compiled, and theENABLE_ZMQline inconfig.ini.cmake.in. Remove the last two only together with their only users. git grep -n zmq test/functionalmust then be empty.- Source still builds with ZMQ. All tests pass.
- Z1-b
[v2 only] node: remove the ZeroMQ notification interface. - Delete
src/zmq/. - Remove the
init.cppblocks (all six locations),OptionsCategory::ZMQ(+ help group + fuzzsystem.cppentry),BCLog::ZMQ, thecheck-doc.pyignore entries, the TSan suppressions, the CMake option/subdirectory/native flag/config define, theFindZeroMQ.cmakemodule, and theconfig.iniline if Z1-a left it. - Add the FATAL_ERROR guard.
- Add a test to
feature_config_args.py: starting with-zmqpubhashblock=tcp://127.0.0.1:1fails with the unknown-parameter error. - Z1-c
[v2 only] depends: remove the ZeroMQ package.zeromq.mk, its patch,packages.mk,MakefileNO_ZMQlines, README. A passedNO_ZMQ=1is ignored. - Z1-d
[v2 only] doc,contrib: remove ZeroMQ documentation and packaging. - The docs and contrib rows of the table.
- The Guix flag, plus TeamCity: delete the
build-without-zmqjob and the qemu note. - Release note: ZeroMQ was removed from V2. Use Chronik WebSocket (
/chronik/ws) for block and transaction push.
Z1.3 Conflicts
init.cpp. The Z1 regions (100-104, 398-405, 1318-1373, 2644, 2750, 2936) were checked against:- V2
056sharepool hunks at 68, 1559, 2222; - V2
054at 706; - v2-only
0001I2P hunks at 1115-1159, 1964, 2338, 2622, 2701, 3459; - v2-only
0002at 2515, 3464-3498.
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.
- Identity patches
0001β0003. They touch chainparams, test CMake andTEST_FRAMEWORK_MODULES. No overlap. - V2
033. It editsdepends/Makefile:140-148(bdb). Z1-c edits lines 40, 146, 168-169. Line 146 is three lines from033's context. Z1-c is applied after033, so there is no conflict on replay. It would conflict only if033were regenerated after Z1. - Lane 3 logging. If its call-site conversion includes
src/zmq/call sites at the V2 tier, those hunks disappear with Z1. Order Z1 after lane 3, or let lane 3 skipsrc/zmq/at V2. It cannot skip at the eCash tier, which keeps ZMQ.
Z1.4 Acceptance
- Each commit:
lotusd/lotus-cli/test_bitcoinbuild. test_bitcoinin one process: pass, except lane E's recorded residuals.- Full functional suite, with
interface_zmqgone: passes. This depends on J3 native MiniWallet; report the subset if J3 is open. test/lintcheck-doc.pyandlint-files.pypass.- After Z1-d:
git grep -n -i -E 'zmq|zeromq' -- src cmake depends test doc contrib ':!src/qt/locale' ':!electrum'returns nothing. Expected exception: theBUILD_ZMQFATAL_ERROR guard. rpc_misc.pypasses, with the exact category count reported.- Clean
dependsbuild and Guix Linux build withoutzeromq. - The eCash tier (replay of the eCash series only) is unchanged:
interface_zmq.pystill passes there.
Z1.5 Risks
- External V2 tooling that expected ZMQ (miners, explorers) breaks loudly at startup. That is intended; document it.
- Lost
BUILD_ZMQOFF coverage. The TeamCitybuild-without-zmqjob is removed. Nothing replaces it, and nothing needs to.