Blockchain foundations in Go · 5 MIN READ
Account model versus UTXO: two ledgers and two ways to stop a double spend
Implement minimal UTXO and account ledgers in Go, reject double spends in each, and explain what each model makes easy or hard for an indexer.
Every ledger must answer one question before it accepts a payment: has this value already been spent? Bitcoin answers with a set of unspent transaction outputs that each transaction consumes and creates. Ethereum answers with a balance and a nonce per account that each transaction updates. Neither stores a wallet's balance as a primary fact; both derive it from accepted history, and that choice shapes every indexer built on top.
blockchain · A MAP OF THE IDEA
- Check inputs or nonce
- Reject before mutating
- Apply debits and credits
- Derive balances from history
Useful when
- UTXO spends are explicit, so provenance and undo are mechanical.
- Account balances are a direct read at a chosen block.
Watch out
- Skipping the duplicate-input check creates money.
- Contract-internal transfers never appear as top-level transactions.
Implementation & operation cost: UTXO indexers maintain an owner index over outputs and spends; account indexers need logs or traces and per-block undo journals.
Two shapes of state
In the UTXO model the state is a set of coins: outputs of earlier transactions, each with an amount and a locking condition. Bitcoin locks outputs with scripts; this lesson uses an owner name. A transaction names the exact outputs it consumes, which disappear, and creates new outputs, usually including change back to the sender, and whatever the inputs hold beyond the outputs is the fee. In the account model the state maps each address to an account with a balance, a nonce and, for contracts, code and storage. A transaction says from, to, value and nonce, and the ledger debits one balance and credits another. The double-spend defense follows from the shape: a UTXO ledger deletes the coin, so a second spend names something that no longer exists; an account ledger demands the next nonce, so a replay is stale.
Both ledgers in one program
UTXOSet.Apply checks every input before it changes anything: each must exist, belong to the signer and appear only once, and the outputs may not exceed the inputs. Ledger.Apply checks the nonce and the balance, then debits, credits and increments the nonce. Owner fields stand in for the signature checks that the signatures lesson covers. After the transfers, the program rebuilds the account state from the history of accepted transfers and compares it with the live state.
package main
import (
"errors"
"fmt"
)
// ---- UTXO model: state is the set of unspent outputs ----
type OutPoint struct {
Tx string
Index int
}
type Output struct {
Owner string
Amount uint64
}
type Tx struct {
ID string
Owner string // stands in for a signature check on every input
Inputs []OutPoint
Outputs []Output
}
type UTXOSet map[OutPoint]Output
func (u UTXOSet) Apply(tx Tx) error {
var in, out uint64
seen := map[OutPoint]bool{}
for _, op := range tx.Inputs {
if seen[op] {
return fmt.Errorf("input %s:%d used twice", op.Tx, op.Index)
}
seen[op] = true
prev, ok := u[op]
if !ok {
return fmt.Errorf("input %s:%d is spent or unknown", op.Tx, op.Index)
}
if prev.Owner != tx.Owner {
return fmt.Errorf("input %s:%d not owned by %s", op.Tx, op.Index, tx.Owner)
}
in += prev.Amount
}
for _, o := range tx.Outputs {
out += o.Amount
}
if out > in {
return fmt.Errorf("outputs %d exceed inputs %d", out, in)
}
// Validate everything first, then mutate: a rejected tx leaves no trace.
for _, op := range tx.Inputs {
delete(u, op)
}
for i, o := range tx.Outputs {
u[OutPoint{tx.ID, i}] = o
}
return nil
}
// Balance is derived: nobody stores it, an indexer sums unspent outputs.
func (u UTXOSet) Balance(owner string) uint64 {
var sum uint64
for _, o := range u {
if o.Owner == owner {
sum += o.Amount
}
}
return sum
}
// ---- Account model: state is a balance and a nonce per account ----
type Account struct{ Balance, Nonce uint64 }
type Transfer struct {
From, To string
Amount, Nonce uint64
}
type Ledger map[string]*Account
var errUnknown = errors.New("unknown sender")
func (l Ledger) Apply(t Transfer) error {
from := l[t.From]
if from == nil {
return errUnknown
}
if t.Nonce != from.Nonce {
return fmt.Errorf("nonce %d rejected, next is %d", t.Nonce, from.Nonce)
}
if from.Balance < t.Amount {
return fmt.Errorf("balance %d < %d", from.Balance, t.Amount)
}
if l[t.To] == nil {
l[t.To] = &Account{}
}
from.Balance -= t.Amount
l[t.To].Balance += t.Amount
from.Nonce++
return nil
}
func report(label string, err error) {
if err != nil {
fmt.Printf("%-28s rejected: %v\n", label, err)
return
}
fmt.Printf("%-28s ok\n", label)
}
func main() {
utxo := UTXOSet{{"genesis", 0}: {"alice", 50}}
pay := Tx{ID: "t1", Owner: "alice", Inputs: []OutPoint{{"genesis", 0}},
Outputs: []Output{{"bob", 30}, {"alice", 19}}} // 1 unit left over is the fee
report("utxo: alice pays bob 30", utxo.Apply(pay))
report("utxo: spend genesis:0 again", utxo.Apply(Tx{ID: "t2", Owner: "alice",
Inputs: []OutPoint{{"genesis", 0}}, Outputs: []Output{{"carol", 50}}}))
report("utxo: same input twice", utxo.Apply(Tx{ID: "t3", Owner: "alice",
Inputs: []OutPoint{{"t1", 1}, {"t1", 1}}, Outputs: []Output{{"carol", 38}}}))
fmt.Println("utxo balances: alice", utxo.Balance("alice"), "bob", utxo.Balance("bob"), "outputs", len(utxo))
genesis := func() Ledger { return Ledger{"alice": {Balance: 50}} }
ledger := genesis()
var history []Transfer
for _, step := range []struct {
label string
t Transfer
}{
{"account: alice pays bob 30", Transfer{"alice", "bob", 30, 0}},
{"account: replay nonce 0", Transfer{"alice", "bob", 30, 0}},
{"account: alice pays carol 30", Transfer{"alice", "carol", 30, 1}},
} {
err := ledger.Apply(step.t)
if err == nil {
history = append(history, step.t)
}
report(step.label, err)
}
fmt.Println("account balances: alice", ledger["alice"].Balance, "bob", ledger["bob"].Balance, "alice nonce", ledger["alice"].Nonce)
rebuilt := genesis()
for _, t := range history {
if err := rebuilt.Apply(t); err != nil {
panic(err) // accepted history must always replay
}
}
fmt.Println("rebuilt from history matches:", *rebuilt["alice"] == *ledger["alice"] && *rebuilt["bob"] == *ledger["bob"])
}Alice spends the 50-unit genesis output into 30 for bob and 19 change, and the missing 1 is the fee. Spending genesis:0 again fails because the first Apply deleted it. A transaction listing t1:1 twice would count those 19 units twice; the seen map rejects it before any sum is used. The account ledger rejects the replayed nonce 0 and then a correctly numbered transfer that exceeds the 20 remaining. UTXO balances are computed on demand by summing unspent outputs, and the account state rebuilt from history matches.
The duplicate-input check is not optional
The seen map in UTXOSet.Apply looks redundant until you remove it. Without it, one transaction can reference the same output twice, the input sum counts the coin twice, and the ledger creates money. This is not hypothetical: CVE-2018-17144 was a Bitcoin Core bug in which an optimization skipped the duplicate-input check during block validation. Nodes running 0.14 could be crashed by such a block, and versions 0.15.0 to 0.16.2 would have accepted one that inflated the supply. Validate everything first and mutate only after every check passes, as both Apply functions do, so that a rejected transaction leaves no partial state. Production code also range-checks every amount (Bitcoin caps values at 21 million coins) and guards unsigned addition against overflow; this model uses small numbers and leaves that out.
What each model means for an indexer
UTXO makes provenance easy: every payment names its inputs, so tracing where a coin came from is a direct walk, and undoing a block is mechanical, re-adding the outputs it spent and deleting the ones it created, which is what Bitcoin Core's per-block undo data stores. Per-address balance and history are the hard part. An indexer must maintain an owner index over outputs and their spends, and one wallet uses many addresses and change outputs, so a user's balance is an aggregation the chain knows nothing about. The account model makes balances easy, a single read at a chosen block, and hides history: value moves inside contract execution without a top-level transaction, token balances live in contract storage and surface only through logs such as the ERC-20 Transfer event, and full history needs logs or traces. Undoing a block needs the previous value of every key it touched, which the fork-choice lesson uses.
Balances are derived; test that they stay derivable
The rebuild at the end of the program is the most valuable test either model can have: start from genesis, replay accepted history and compare with the live state. Run it in CI against fixtures and periodically against production projections. Add property tests: total supply stays constant apart from issuance and fees in the UTXO model, or explicit mints and burns in the account model; a rejected transaction changes nothing; applying an accepted transaction a second time is rejected. If a projection keeps a balance column, treat it as a cache of a derivation and keep the means to recompute it, because the chain will never tell you the column drifted.
TAKE THIS WITH YOU
Validate every input or nonce before mutating state, treat balances as derived from accepted history, and choose indexing structures that match how the model records spends.
Check your understanding
In the UTXO ledger, why is a second transaction that spends genesis:0 rejected?
Go to the source
Progress stays in this browser. No account needed.