Blockchain foundations in Go · 5 MIN READ

Fork choice and reorgs: follow the heaviest chain and undo what the old branch indexed

Implement a heaviest-chain fork-choice rule, compute a reorganization's undo and apply path, apply confirmation depth, and use Ethereum's safe and finalized tags.

Two valid blocks can extend the same parent, and nodes need a rule that makes them converge on one branch. Proof-of-work chains follow the branch with the most cumulative work; when a heavier branch appears, the node reorganizes, and blocks it had accepted stop being canonical. Anything an indexer derived from those blocks must be undone, and anything irreversible should have waited for finality.

blockchain · A MAP OF THE IDEA

  1. Store blocks by hash
  2. Pick head by total work
  3. Undo to common ancestor
  4. Credit at finalized

Useful when

  • Cumulative work makes every honest node converge on one head.
  • Per-block undo data turns a reorg into a mechanical replay.

Watch out

  • Confirmations are a probability; recompute them from the head.
  • latest and safe can both move backwards; only finalized is final.

Implementation & operation cost: Undo journals for every block, an atomic undo-apply-checkpoint transaction, and roughly 13 minutes of waiting for finality on Ethereum.

01

Forks are normal; the rule decides

Forks happen without any attacker: two miners find blocks at nearly the same moment, or a proposer's block arrives late. Each node keeps every valid block in a tree keyed by hash, and a fork-choice rule picks one leaf as the head. Longest chain is the informal name, but the rule that resists manipulation is most cumulative work, using the Work value from the proof-of-work lesson, so a branch of fewer, harder blocks beats a branch of more, easier ones. Ties keep the block seen first. The events-finality lesson in the next unit shows an indexer refusing a block that does not extend its tip; this lesson supplies the step that follows, walking both branches back to their common ancestor.

02

A node and an indexer that survive a reorg

Node.Add rejects a block whose parent is unknown or whose height is not the parent's plus one, computes cumulative work and switches head only on strictly more work. route walks the old and new tips back to their common ancestor and returns the blocks to undo, newest first, and to apply, oldest first. The Indexer keeps a small projection, deposit to including block, that it applies and undoes per block, and computes confirmations as head height minus inclusion height plus one.

go
package main

import (
	"fmt"
	"slices"
)

type Block struct {
	ID, Parent string
	Height     uint64
	Work       uint64   // expected hashes for this block, from its target
	Deposits   []string // transactions the indexer cares about
}

type Node struct {
	blocks map[string]Block
	total  map[string]uint64 // cumulative work from genesis
	head   string
}

func NewNode(genesis Block) *Node {
	return &Node{blocks: map[string]Block{genesis.ID: genesis}, total: map[string]uint64{genesis.ID: 0}, head: genesis.ID}
}

// Add stores a block and applies the fork-choice rule: the tip with the most
// cumulative work wins; on a tie the block seen first stays head.
func (n *Node) Add(b Block) (ancestor string, undo, apply []string, err error) {
	parent, ok := n.blocks[b.Parent]
	if !ok || b.Height != parent.Height+1 {
		return "", nil, nil, fmt.Errorf("%s rejected: unknown parent or wrong height", b.ID)
	}
	n.blocks[b.ID] = b
	n.total[b.ID] = n.total[b.Parent] + b.Work
	if n.total[b.ID] <= n.total[n.head] {
		return "", nil, nil, nil
	}
	old := n.head
	n.head = b.ID
	ancestor, undo, apply = n.route(old, b.ID)
	return ancestor, undo, apply, nil
}

// route walks both tips back to their common ancestor.
func (n *Node) route(from, to string) (string, []string, []string) {
	a, b := n.blocks[from], n.blocks[to]
	var undo, apply []string
	for a.Height > b.Height {
		undo, a = append(undo, a.ID), n.blocks[a.Parent]
	}
	for b.Height > a.Height {
		apply, b = append(apply, b.ID), n.blocks[b.Parent]
	}
	for a.ID != b.ID {
		undo, a = append(undo, a.ID), n.blocks[a.Parent]
		apply, b = append(apply, b.ID), n.blocks[b.Parent]
	}
	slices.Reverse(apply)
	return a.ID, undo, apply
}

// Indexer keeps a projection that can be rolled back block by block.
type Indexer struct {
	node     *Node
	included map[string]string // deposit -> canonical block containing it
}

func (ix *Indexer) Apply(id string) {
	for _, d := range ix.node.blocks[id].Deposits {
		ix.included[d] = id
	}
}

func (ix *Indexer) Undo(id string) {
	for _, d := range ix.node.blocks[id].Deposits {
		delete(ix.included, d)
	}
}

func (ix *Indexer) Add(b Block) {
	ancestor, undo, apply, err := ix.node.Add(b)
	if err != nil {
		fmt.Println(err)
		return
	}
	if len(undo) > 0 {
		fmt.Printf("%s arrives: reorg via %s, undo %v, apply %v\n", b.ID, ancestor, undo, apply)
	}
	for _, id := range undo {
		ix.Undo(id) // newest first: the reverse of how they were applied
	}
	for _, id := range apply {
		ix.Apply(id)
	}
}

func (ix *Indexer) Status(dep string, need uint64) {
	head := ix.node.blocks[ix.node.head]
	id, ok := ix.included[dep]
	if !ok {
		fmt.Printf("%s: not on the canonical chain (head %s)\n", dep, head.ID)
		return
	}
	conf := head.Height - ix.node.blocks[id].Height + 1
	fmt.Printf("%s: in %s, confirmations %d, credit at %d: %v\n", dep, id, conf, need, conf >= need)
}

func main() {
	ix := &Indexer{node: NewNode(Block{ID: "G"}), included: map[string]string{}}
	for _, b := range []Block{
		{ID: "A1", Parent: "G", Height: 1, Work: 1},
		{ID: "A2", Parent: "A1", Height: 2, Work: 1},
		{ID: "A3", Parent: "A2", Height: 3, Work: 1, Deposits: []string{"dep-7"}},
		{ID: "A4", Parent: "A3", Height: 4, Work: 1},
	} {
		ix.Add(b)
	}
	fmt.Println("head", ix.node.head, "work", ix.node.total[ix.node.head])
	ix.Status("dep-7", 3)

	ix.Add(Block{ID: "B2", Parent: "A1", Height: 2, Work: 2})
	fmt.Println("after B2 head", ix.node.head, "(B2 total work", ix.node.total["B2"], "is not more)")
	ix.Add(Block{ID: "B3", Parent: "B2", Height: 3, Work: 2})
	fmt.Println("head", ix.node.head, "height 3 work", ix.node.total["B3"], "beats A4 height 4 work", ix.node.total["A4"])
	ix.Status("dep-7", 3)

	ix.Add(Block{ID: "X9", Parent: "unknown", Height: 9, Work: 100})

	ix.Add(Block{ID: "B4", Parent: "B3", Height: 4, Work: 2, Deposits: []string{"dep-7"}})
	ix.Status("dep-7", 3)
}
Read the code

dep-7 lands in A3 and has two confirmations at head A4, below the policy of three, so it is not credited. B2 brings its branch to work 3, not more than 4, so the head stays. B3 brings it to 5, and the node reorganizes via A1: it undoes A4, A3 and A2 and applies B2 and B3, even though A4 is higher. dep-7 then has no canonical block. X9 is rejected because its parent is unknown; a real node would hold it as an orphan until the parent arrives. When B4 re-includes dep-7, its confirmations restart from one.

03

Confirmation depth is a probability policy

Waiting for k confirmations means waiting until the including block and k-1 blocks after it are all canonical. Under proof of work, the chance that an attacker with a minority of hash rate overtakes a k-block lead falls exponentially with k; the Bitcoin whitepaper works through the numbers, and six confirmations became the convention. It is still a probability, and the right k depends on what is at stake. Recompute confirmations from the current canonical head on every change instead of storing a counter, because a reorg can remove the including block, as happened to dep-7 after B3, or move the transaction to a different height, as B4 did. Identify transactions by their hash, never by block and position.

04

After the Merge: credit from the finalized tag

Ethereum's proof of stake picks the head with LMD-GHOST and finalizes checkpoints with Casper FFG. When validators holding two thirds of the stake attest to a checkpoint pair, the earlier checkpoint is finalized, and reverting it would require at least one third of all stake to be slashed. Normally that takes about two epochs, 64 slots of 12 seconds, a little under 13 minutes. The JSON-RPC tags expose this: latest is the head and can reorg; safe is the block the consensus client expects not to reorg under normal conditions, which clients derive from the latest justified checkpoint; finalized is the latest finalized block. Release irreversible effects such as withdrawals from finalized, and use safe or latest only for views that tolerate rollback.

go
// Runs against your own node; not executed in the app.
finalized, err := client.HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber)))
if err != nil {
	return fmt.Errorf("finalized head: %w", err)
}
safe, err := client.HeaderByNumber(ctx, big.NewInt(int64(rpc.SafeBlockNumber)))
if err != nil {
	return fmt.Errorf("safe head: %w", err)
}
// Promote rows at or below the finalized height whose stored block hash
// matches the canonical hash; a mismatch here is an incident, not a reorg.
if err := store.Finalize(ctx, finalized.Number.Uint64(), finalized.Hash()); err != nil {
	return err
}
log.Printf("safe=%d finalized=%d", safe.Number, finalized.Number)
Read the code

This fragment runs in the reader's own native environment against their own node; it is not executed by the app. ethclient turns the negative rpc.BlockNumber constants into the finalized and safe tags (FinalizedBlockNumber is -3 and SafeBlockNumber is -4 in go-ethereum v1.17.10), so no heights are guessed. store.Finalize is a placeholder for your projection. A stored hash that differs from the finalized hash at the same height means the indexer followed another chain or a misbehaving provider, which calls for an alert, not an automatic rollback.

05

What an indexer undoes, and how to test it

For every block the projection applied, keep enough to reverse it, keyed by block hash: the rows it inserted, or the previous values of rows it updated, like the account journal from the ledger lesson. Undo newest first, then apply the new branch oldest first, in one database transaction together with the checkpoint, so a crash cannot leave a half-reorganized state. Bound the depth you support: below finalized no reorg should happen, and a deeper one is an incident. Finality can also stall when too few validators participate, which has happened on mainnet; then finalized lags far behind latest, and the right response is to wait and alert, not to fall back to latest. Test with scripted block trees like the program's: a one-block replacement, a deep reorg, a heavier but shorter branch, an unknown parent, a re-included transaction and a crash between undo and apply.

TAKE THIS WITH YOU

Choose the head by cumulative work, walk to the common ancestor to undo and apply atomically, recompute confirmations from the current head, and release irreversible effects only at finalized.

Check your understanding

After the Merge, which block tag should an indexer wait for before releasing an irreversible withdrawal?

Go to the source

Progress stays in this browser. No account needed.