TeachMeBitcoin

UTXO Rollback Mechanics

From TeachMeBitcoin, the free encyclopedia ⏱️ 3 min read

Transaction Rollback: UTXO Management During Reorgs

When a Bitcoin node performs a Chain Reorganization, it must do more than just update a pointer. It must physically "roll back" the state of the global UTXO (Unspent Transaction Output) Set to ensure that the ledger remains consistent.

This guide explores the high-performance database operations that occur during a reorg: DisconnectBlock and ConnectBlock.


💾 1. The UTXO Set: The Source of Truth

The UTXO set (stored in chainstate/) is the list of all spendable coins. * When a block is Connected, its inputs are removed from the set, and its outputs are added. * When a block is Disconnected, the process is reversed: its outputs are removed, and its inputs are restored.


🔙 2. DisconnectBlock: Undoing History

If a node decides a block is no longer part of the best chain, it calls DisconnectBlock.

  1. Removing Outputs: Every UTXO created by this block is deleted from the database.
  2. Restoring Inputs: The node looks at the "undo data" (stored in .dat files on disk). This data contains the original scripts and values of the UTXOs that were consumed by this block. The node re-inserts these into the active UTXO set.
  3. Result: The ledger state is now exactly as it was before this block existed.

📥 3. Mempool Re-insertion

What happens to the transactions from the disconnected block? * Nodes don't want to lose these transactions. * They are moved into the Mempool. * If these transactions are still valid (i.e., they don't conflict with the new winning branch), they will be available for inclusion in the next block.


🚀 4. Performance: The "Undo" Data

To make reorgs fast, Bitcoin Core pre-calculates "Undo Data" (CBlockUndo) whenever a block is first connected.

Without this data, a node would have to search the entire blockchain history to find the original values of the consumed inputs just to roll back a single block. By storing the inputs' original states alongside the block, Bitcoin can perform reorgs of hundreds of blocks in just a few seconds.


🛡️ 5. Consistency Guarantees

The UTXO set and the Block Tree are always kept in sync. If a node crashes during a reorg, it uses a journaling system to either finish the reorg or roll back to the last known good state upon restart. This ensures that a node never ends up with a "corrupted" view of who owns which coins.

☕ Help support TeachMeBitcoin

TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!