When a new transaction is received it is added to the memory pool (after checking for conflicts). While mining, only the transactions which are in the pool are considered. What happens to the transactions after they are included in a newly mined block? Are they deleted from the pool? Where is the UTXO stored? Which function handles it?
1 Answer
I assume this question is about Bitcoin Core's internal operations. This description is valid for version 0.8 and later (up to 0.14 at least).
One part of the system deals with the active chain, which is the longest valid chain of blocks (stored in $DATADIR/blocks
) that we know of. This active chain gets blocks appended to - and occasionally removed when there is a reorganization.
Where is the UTXO stored?
For the tip (the last block in the active chain), we maintain a database with the set of unspent transaction outputs (UTXOs), stored in $DATADIR/chainstate
, and aggressively cached in memory. When a new block is received, we remove the UTXOs spent by transactions in the block, and add the outputs of those transactions. When a reorganization happens, we use undo data (stored in $DATADIR/blocks/rev*.dat
) to roll back the changes to the UTXO set. In a way, you can see blocks as patches to the UTXO set - but the UTXO set is never explicitly committed to or stored in blocks, it is merely implied by them.
What happens to the transactions after they are included in a newly mined block? Are they deleted from the pool?
The mempool is a set of transactions that are valid but not in a block. We don't treat those as part of the UTXO set. Rather, it's just a group of transactions that are internally consistent and consistent with the active chain. This means that any mempool transaction only spends outputs that are in the UTXO set, or from other mempool transactions. Whenever a new block comes in, we remove its transactions from the mempool (assuming they were there), and we remove any mempool transactions and their dependencies that conflict with the new UTXO set. When a reorganization happens, we try to move the removed block's transactions back to the mempool.
Which function handles it?
That's too long to answer here. A significant part of src/validation.*
(in 0.14) or src/main.*
(in older versions) together with src/coins.*
deals with maintenance and caching of the mempool and UTXO set.