Skip to content

[RFC] ipc: add Events interface for chain and mempool notifications - #36985

Draft
ViniciusCestarii wants to merge 4 commits into
bitcoin:masterfrom
ViniciusCestarii:ipc-events
Draft

ViniciusCestarii wants to merge 4 commits into
bitcoin:masterfrom
ViniciusCestarii:ipc-events

Conversation

@ViniciusCestarii

Copy link
Copy Markdown
Contributor

This adds an Events IPC interface that streams block and mempool events in one ordered stream, addressing gaps in ZMQ notifications and providing a more modular interface. It supports the following subscriptions:

  • blockConnected: fires for every block connected to the active chain, including during IBD (blocks connected by a background assumeutxo chainstate are skipped). Carries hash, height and optionally the serialized block. ZMQ hashblock/rawblock are driven by UpdatedBlockTip, so they skip intermediate blocks when several connect at once and don't fire during IBD.
  • blockDisconnected: fires for every block disconnected during a reorg, with hash, height and optionally the serialized block.
  • txAddedToMempool: fires only for mempool acceptance. Carries txid, wtxid, mempool sequence, fee, vsize and optionally the serialized tx. ZMQ hashtx/rawtx also fire for every tx in connected and disconnected blocks, so a subscriber can't tell whether a tx entered the mempool (pain point of Add zmq notifications for evicted transactions, tests #19462 (comment), zmq: add rawmempooltx publisher #23624 (comment) and zmq: mempool notifications #7753).
  • txRemovedFromMempool: fires for every removal, including txs removed because they were mined (reason block), except during IBD, with txid, wtxid, mempool sequence, removal reason and optionally the serialized tx.

ZMQ sequence covers all four of these, but only carries hashes (plus the mempool sequence for "A"/"R"), and "R" doesn't include block-inclusion removals or a reason.

Why not just do it with ZMQ?

  • One ordered stream that includes the data. rawblock/rawtx have their own sequence numbers and can't be ordered against sequence. Here every event can include its serialized block or tx in the same ordered stream. Events come in the same order as ZMQ sequence, plus block-inclusion removals.
  • Typed, versioned interface. Cap'n Proto generates the client code and lets the schema evolve without breaking older clients. With ZMQ, clients parse raw bytes by hand which can't evolve existing topics without breaking changes.
  • Fixing these in ZMQ would need new topics reporting on the same events as existing ones, which is confusing for users, and changing the existing topics would break current consumers.
  • Bounded buffering. Events are buffered per subscription up to a byte limit (-ipceventsbuffer), and the client pulls them in batches with waitNext. ZMQ limits are message counts per topic (-zmqpub*hwm), which don't bound memory when messages are full blocks.

Why additional data, including derivable ones?

  • fee, vsize: neither can be derived from the tx alone, so including them saves RPC calls per tx. RPC calls can also fail if the tx was removed in the time in between.
  • mempool sequence: lets a client line events up with getrawmempool (mempool_sequence=true) to bootstrap and keep a mempool mirror in sync.
  • height: not in the serialized block, and needed to handle reorgs without an extra RPC call.
  • hash, txid, wtxid: identifiers are always included, so clients don't need to branch on include_data.

Example of simple clients using this interface, including a mempool mirror: https://github.com/ViniciusCestarii/bitcoin-ipc-events-client

Note: to make this interface usable in this PR, the Cap'n Proto union that this uses is mapped by hand in events-types.h. Ideally this support would be added to libmultiprocess first.

@DrahtBot

DrahtBot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK 0xB10C, m4ycon

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36188 (crypto: plug hardware optimized SHA256 into libsecp256k1's context by furszy)

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

The upcoming Events interface needs the same default timeout as
Mining. Move the constant to common.capnp so it can be shared without
importing mining.capnp. No behavior change.
Transactions removed from the mempool because they were included in a
block are only reported through MempoolTransactionsRemovedForBlock,
which did not carry the mempool sequence consumed by each removal.
Without it, subscribers cannot order these removals relative to other
mempool additions and removals.

Return the sequence from removeUnchecked and store it in
RemovedMempoolTransactionInfo. It is used by the Events interface
added in the next commit.
@ViniciusCestarii
ViniciusCestarii force-pushed the ipc-events branch 2 times, most recently from 7b41bf3 to 19e212f Compare November 26, 2026 13:30
@ViniciusCestarii

Copy link
Copy Markdown
Contributor Author

Force-pushed 19e212f fixing a Ralph comment

@ViniciusCestarii

Copy link
Copy Markdown
Contributor Author

cc @0xB10C @instagibbs @ryanofsky I believe you might be interested in this :)

@edilmedeiros edilmedeiros left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think the zmq interface is quite light. Have you had the chance to measure the overhead this adds to the node operation and how it compares to zmq? Also, would be nice to have a latency comparison between them. By latency, I mean the time from the actual state transition to the notification becoming available and the time until the client receives it.

Conceptually, I don't see people talking about deprecating the zmq interface, there are probably many clients out there that depend on it. You are not proposing that here, but that's something that I anticipate from this RFC, better to think better about how a change like this would co-exist with zmq. An obvious advantage is to have more room for upgrading the interface without breaking downstream. But zmq is read-only, contrary to the potential of an interface like this.

Which makes me wonder if there's room to abstract an event interface from the "transport" mechanism used to communicate them to external consumers. I think a comparison with zmq in this regard could also be useful long-term. May also be part of a broader monitoring facility (reminds me of #35142).

Comment thread src/interfaces/events.h Outdated
Comment on lines +79 to +82
//! Pull-based stream of chain and mempool events. Events are buffered on the
//! node side from the moment the interface is created, so a slow client never
//! slows down the node. If the client falls too far behind, the oldest events
//! are dropped and the client sees a gap in Event::sequence.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

never slows down the node.

That's something I would like to see empirically.

Some potential scenarios:

  • A client subscribes but never consumes events.
  • Several clients subscribe with different consumption rates.
  • A client repeatedly connects and disconnects.
  • A burst of mempool activity causes buffers to overflow.
  • A large reorganization occurs while clients are consuming events.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, these are good cases to measure. I'll test them and share the results. I'll also rewrite the comment to be more precise saying the node never waits for a slow client instead of that a slow client never slows down the node.

@ViniciusCestarii

Copy link
Copy Markdown
Contributor Author

I think the zmq interface is quite light. Have you had the chance to measure the overhead this adds to the node operation and how it compares to zmq? Also, would be nice to have a latency comparison between them. By latency, I mean the time from the actual state transition to the notification becoming available and the time until the client receives it.

Performance isn't the motivation for this PR but I agree it's worth knowing. I'll measure that and the latency compared to ZMQ.

Conceptually, I don't see people talking about deprecating the zmq interface, there are probably many clients out there that depend on it. You are not proposing that here, but that's something that I anticipate from this RFC, better to think better about how a change like this would co-exist with zmq.

Yes, I don't intend this to replace or deprecate ZMQ. I see it like the Mining IPC interface and getblocktemplate where the new interface covers needs the older one doesn't serve well, while existing clients can keep using the older one.

Which makes me wonder if there's room to abstract an event interface from the "transport" mechanism used to communicate them to external consumers. I think a comparison with zmq in this regard could also be useful long-term.

The internal event notifications are already abstracted from the transport by CValidationInterface, which both ZMQ and this PR build on. What differs is what each exposes on top of it ZMQ publishes raw bytes per topic, while this provides typed events in a single ordered stream that clients pull from. Sharing more than that would mean refactoring ZMQ without a clear benefit, while risking behavior changes for existing clients.

Add a pull-based stream of chain and mempool events (block connected,
block disconnected, transaction added to and removed from the
mempool). Each subscription chooses which event types it wants and
whether to include the serialized block or transaction.

Events are buffered on the node side from the moment the interface is
created, so a slow client never slows down the node. The buffer is
limited by the new -ipceventsbuffer option. When it is full, the
oldest events are dropped and the client sees a gap in the per
subscription Event::sequence. waitNext acknowledges events up to
"after" and returns a batch limited by max_events and MAX_BATCH_BYTES.

The mutex and condition variable live in KernelNotifications so that
Interrupt() can wake pending waitNext calls on shutdown.
Add events.capnp and an Init.makeEvents method so IPC clients can
subscribe to chain and mempool events.

libmultiprocess does not map std::variant to capnp unions, so
interfaces::Event is converted to and from the Event union by hand in
events-types.h, reusing the generated code for each union member.

Add a functional test covering the interface.
@0xB10C

0xB10C commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Concept ACK (assuming there are a few consumers of this interface, I'm certainly interested!).

In 2020, I stood up a Bitcoin Core source code fork for coinmetrics.io (now called Talos) called Bitcoin ZMCE (ZMQ Mempool and Chain Events) that does something very similar. They use this in their mempool+chain data collection and monitoring. The current patch sets can be found in https://github.com/coinmetrics/fullnode/tree/master/fullnodes/bitcoin-zmce/patches - I'll ping them, maybe they have input on this PR.

Here's an LLM assisted comparison of your proposal and what I implemented back then. I think you cover most of it, but if there's an easy and cheap way of getting slightly more information out of such interface, why not? I haven't looked into any details.

ZMCE feature In this PR? Notes
Millisecond timestamp on every message No Events here carry no time field. I think that's fine, taking the timestamp on event arrival should be accurate enough for most applications.
chainheaderadded: hash, height and 80-byte header for any accepted header, including ones off the best chain No No header-level event. ZMCE adds a validation signal in AcceptBlockHeader for this. This might be useful to have, but might also be a lot of extra code & work here?
mempoolreplaced: replaced and replacement tx paired, with both fees No Here a replacement shows up as a txRemovedFromMempool with reason replaced plus a separate txAddedToMempool, with nothing linking the two. Having data on replacements has been very interesting, but also probably a bit more work
mempoolconfirmed: tx with block height, block hash and header Partial txRemovedFromMempool with reason block has no block hash or height, and is sent before the blockConnected events.
Header or prev hash without the full block (chaintipchanged, chainconnected) Partial BlockEvent has hash and height; the header and prev hash are only available inside the full block via include_data.
chaintipchanged: one event per tip update Partial Events has blockConnected per block but no tip event. Mining.waitTipChanged returns hash and height on a different interface.
mempooladded: txid, raw tx, fee Yes This PR also has wtxid, vsize and mempool sequence.
mempoolremoved with removal reason, including block Yes This PR also has wtxid and mempool sequence.
chainconnected: hash, height, raw block Yes This PR also has blockDisconnected, which ZMCE has no new topic for.
Per-topic sequence number Yes Here it is a per-subscription sequence where a jump means dropped events.
Send high-water mark raised to 100,000 Not applicable This PR uses a byte-based buffer (-ipceventsbuffer, default 128 MiB).

Thank you for working on this!

@m4ycon

m4ycon commented Dec 3, 2026

Copy link
Copy Markdown

Concept ACK

Currently, I'm working on Cluster Mempool Observer as part of 0xB10C/project-ideas#15. It does a similar thing as Vinicius' mempool mirror, but by polling the current txids on mempool via RPC and based on this, watch how clusters are being handled (via RPC). All this data is persisted to a SQL database for later analysis.

It has worked well so far, but as I'm aiming for a good correctness rate over time (as polling can leave gaps), I'd probably change to ZMQ and let the RPC polling just as a backfiller.

Your "Why not just do it with ZMQ?" and "Why additional data, including derivable ones?" have some really great points on why I would change to IPC in my case. block(Dis)Connected not losing any batch of blocks coming or dealing with reorg, would make my life easier for sure. txAddedToMempool would save me some RPC calls and txRemovedFromMempool including why they were removed it's useful data.

It makes me wonder whether Core should always prefer extending it over ZMQ (idk the current project thoughts around it), having more freedom to change the interface (versioning), sounds like a strong pro to keep developing IPC as a long-term tooling.

@enochaz

enochaz commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

A few thoughts from my first read through. I had something similar in mind a few months ago but didnt take it further because of the overlap with #29409. That PR would also let a client follow block and mempool changes through UnstableChain. If I’m following it correctly, the node waits for the client to return from each callback. When there are more than 10 callbacks pending, it looks like ActivateBestChain can end up waiting too.

With the pull model here, the client can fall behind and still tell from a gap in the stream that it missed something. Was the wait in #29409 part of why you went with a separate interface? Perhaps worth mentioning that PR in the description. It would help me understand where you see each one being used. Small thing I noticed too is that both PRs use @5 for a new method on Init.

I generally like the idea of using IPC outside of mining. Sjors put together a list of projects using ZMQ a while back. Have you had a chance to try this with any of those? A block explorer came to mind since it could get the tx and its fee together, and outside IBD it could tell which mempool txs got mined without having to work that out from the block. Saw your reply about measuring latency against ZMQ. I’d be curious how the numbers look if you include the RPC call a client would otherwise make to get the fee.

One thing I’m still unsure about is access. With ZMQ a client can just listen, but if I give it access to the ipcbind socket, it looks like it can also get Rpc and call any enabled RPC by default, wallet ones included. rpcwhitelist does seem to be checked, though from what I can tell the client supplies the username. Is there already a way to expose just Events on a socket? Perhaps that could be an option alongside the connection limit if there isn’t one already.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants