Chain Reorgs

hard · bitcoin, consensus, reorg

Chain Selection and Reorgs

Implement most-work chain selection with UTXO undo/redo.

Types

type Outpoint struct {
    TxID  [32]byte
    Index uint32
}

type TxIn struct {
    Prev Outpoint
}

type TxOut struct {
    Value uint64
}

type Transaction struct {
    ID       [32]byte
    Inputs   []TxIn
    Outputs  []TxOut
    Coinbase bool
}

type Block struct {
    ID   [32]byte
    Prev [32]byte
    Work uint64
    Txs  []Transaction
}

type UTXOSet map[Outpoint]TxOut

type UndoEntry struct {
    Outpoint Outpoint
    Output   TxOut
}

type ChainState struct {
    Tip       [32]byte
    Blocks    map[[32]byte]Block
    Height    map[[32]byte]int
    TotalWork map[[32]byte]uint64
    UTXO      UTXOSet
    Undo      map[[32]byte][]UndoEntry
}

func NewChainState(genesis Block) *ChainState
func ProcessBlock(state *ChainState, block Block) (reorg bool, ok bool)

Rules

  • ProcessBlock must store the block and compute its Height and TotalWork.
  • If the parent is unknown, return (false, false).
  • Select the chain tip with highest TotalWork (strictly greater to reorg).
  • On reorg:
    1. Find the fork point.
    2. Undo blocks on the old tip down to (but excluding) the fork.
    3. Apply blocks from fork child to the new tip (in forward order).
  • ApplyBlock must fail if any input is missing or spent twice within the block.

Notes

  • Coinbase transactions have zero inputs and are always allowed.
  • Undo entries should restore spent outputs on rollback.
  • You do not need to validate signatures or scripts in this problem.
Run tests to see results
No issues detected