Bitcoin Core ZMQ Sequence Events: Mempool and Block State Tracking
The Bitcoin Core ZMQ sequence topic distinguishes changes to the active chain from changes to the local mempool. This makes it useful for applications that need more than a simple stream of transaction hashes.
Event body structure
A sequence notification body begins with a 32-byte hash followed by a one-byte event label. C identifies a connected block and D identifies a disconnected block. A identifies a transaction added to the mempool and R identifies a transaction removed for a reason other than inclusion in a block. A and R bodies also carry an eight-byte little-endian mempool sequence value.
The outer multipart notification counter is separate from this mempool sequence value. Do not compare the two as if they shared the same numbering system.
Maintaining a local transaction set
For an A event, record that the transaction entered this node's mempool. Retrieve additional transaction details when needed. For an R event, remove the transaction from the local mempool cache, but do not conclude that it was replaced or permanently invalidated. The event alone does not identify the removal reason or a replacement transaction.
When a block connects, process its transactions and reconcile the cached mempool. Transactions mined into a block are not individually reported as ordinary R events by this topic. A disconnected block requires a review of affected confirmations; its transactions are not guaranteed to return to the mempool.
Snapshot synchronization
The RPC call getrawmempool false true can return the transaction identifiers together with a mempool sequence value on supporting versions. Subscribe and buffer notifications while obtaining this snapshot. Apply subsequent mempool events using the documented sequence boundary; events already reflected in the snapshot must not be applied twice. Reconcile block events separately against the active chain.
If buffering overflows, the publisher restarts or the notification counter indicates a gap, discard the uncertain incremental state and obtain another snapshot. A mempool sequence is local to the node and is not a network-wide ordering guarantee.
Application state design
Represent observed, confirmed, removed and unknown as distinct states. A transaction that disappears from a local mempool may still exist at another peer. Use active-chain membership and wallet-specific evidence to determine whether a payment is confirmed. Persist application state atomically with its reconciliation checkpoint, rather than committing a balance change independently of its supporting transaction records.
Primary references
Bitcoin Core ZMQ documentation: https://github.com/bitcoin/bitcoin/blob/master/doc/zmq.md
Bitcoin Core RPC documentation: https://bitcoincore.org/en/doc/
