Show contents
Chapter 1 of 6 · 20 min
Transactions and the UTXO model
By the end of this chapter, you'll be able to
- Tell the account model and the UTXO model apart
- Build a transaction with inputs, outputs, change and fees
- Update the set of unspent outputs after a transaction
- Reject an invalid transaction and a double spend within a block
Two ways of keeping accounts
- The account model (a bank's, or Ethereum's): a balance is stored per person, and a transaction says "take 12,000 from Awa's account, add 12,000 to the seller's".
- The UTXO model (Unspent Transaction Output, Bitcoin's): each transaction consumes outputs of previous transactions (its inputs) and creates new outputs. Awa's "balance" exists nowhere: it is the sum of the unspent outputs that belong to Awa.
An output is referred to by the identifier of the transaction that created it and its position: "a3f9…:0". A transaction's identifier is the SHA-256 fingerprint of its content.
The two old outputs are spent forever; the two new ones can be spent in turn.
Text description of the animation
- Awa entirely consumes two outputs that belong to Awa.
- The actual payment.
- The change is a new output that goes back to Awa.
- The difference between inputs and outputs goes to the miner who includes the transaction.
- The two old outputs are spent forever; the two new ones can be spent in turn.
import hashlib
import json
def identifier(tx):
return hashlib.sha256(json.dumps(tx, sort_keys=True).encode()).hexdigest()[:8]
# The set of unspent outputs: "id:position" → {"to": owner, "amount": ...}
utxos = {"tx1:0": {"to": "Awa", "amount": 10000},
"tx2:1": {"to": "Awa", "amount": 5000},
"tx2:0": {"to": "Kofi", "amount": 7000}}
def balance(utxos, person):
return sum(o["amount"] for o in utxos.values() if o["to"] == person)
tx = {"inputs": ["tx1:0", "tx2:1"],
"outputs": [{"to": "Fatou", "amount": 12000}, {"to": "Awa", "amount": 2900}]}
tx_id = identifier(tx)
fees = sum(utxos[i]["amount"] for i in tx["inputs"]) - sum(o["amount"] for o in tx["outputs"])
for i in tx["inputs"]: # the inputs are consumed
del utxos[i]
for n, o in enumerate(tx["outputs"]): # the outputs become spendable
utxos[f"{tx_id}:{n}"] = o
print("transaction", tx_id, "| fees:", fees)
for person in ("Awa", "Fatou", "Kofi"):
print(f"{person:<6} {balance(utxos, person):>6}")
transaction 9249af12 | fees: 100
Awa 2900
Fatou 12000
Kofi 7000
The validation rules
Before accepting a transaction, every node of the network checks that:
- each input refers to an output that exists and is not yet spent;
- the same input does not appear twice in the transaction;
- the sum of the outputs does not exceed the sum of the inputs (otherwise money would be created);
- no amount is negative or zero;
- the owner of the inputs really signed the transaction (that is the next chapter).
def validate(tx, utxos):
if len(set(tx["inputs"])) != len(tx["inputs"]):
return "same input used twice"
for i in tx["inputs"]:
if i not in utxos:
return f"input {i} unknown or already spent"
if any(o["amount"] <= 0 for o in tx["outputs"]):
return "negative or zero amount"
total_in = sum(utxos[i]["amount"] for i in tx["inputs"])
total_out = sum(o["amount"] for o in tx["outputs"])
if total_out > total_in:
return f"creates money: {total_out} out for {total_in} in"
return "valid"
utxos = {"tx1:0": {"to": "Awa", "amount": 10000}, "tx2:0": {"to": "Kofi", "amount": 7000}}
print(validate({"inputs": ["tx1:0"], "outputs": [{"to": "Mei", "amount": 9900}]}, utxos))
print(validate({"inputs": ["tx9:0"], "outputs": [{"to": "Mei", "amount": 100}]}, utxos))
print(validate({"inputs": ["tx2:0"], "outputs": [{"to": "Kofi", "amount": 70000}]}, utxos))
print(validate({"inputs": ["tx1:0", "tx1:0"], "outputs": [{"to": "Mei", "amount": 20000}]}, utxos))
print(validate({"inputs": ["tx2:0"], "outputs": [{"to": "Mei", "amount": 8000}, {"to": "Kofi", "amount": -1000}]}, utxos))
valid
input tx9:0 unknown or already spent
creates money: 70000 out for 7000 in
same input used twice
negative or zero amount
Rule 4 is not a detail: without it, an output of −1,000 would allow creating another one of 8,000 from 7,000. In 2010, a bug of this kind (an overflow on amounts) created more than 184 billion bitcoins in one block, cancelled a few hours later.
Mini-lab: Kofi's walletPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: applying a block
Write apply_block(utxos, transactions, miner, reward, number) that:
- validates and applies the transactions in order, on a copy of
utxos; - adds up the fees of all the transactions;
- adds an output for the miner equal to
reward + fees(the reward transaction, with no input); - returns the new set, or an error message and the original set if a transaction is invalid.
Test with a valid block of two transactions, then with a block containing a double spend.
Hint 1
new = dict(utxos). After each validated transaction, remove its inputs from new and add its outputs with the keys f"{identifier(tx)}:{n}".Hint 2
{"inputs": [], "outputs": [{"to": miner, "amount": ...}], "block": number}: the block number makes it unique.Show the solution and common mistakes
import hashlib
import json
def identifier(tx):
return hashlib.sha256(json.dumps(tx, sort_keys=True).encode()).hexdigest()[:8]
def validate(tx, utxos):
if len(set(tx["inputs"])) != len(tx["inputs"]) or any(i not in utxos for i in tx["inputs"]):
return False
if any(o["amount"] <= 0 for o in tx["outputs"]):
return False
return sum(o["amount"] for o in tx["outputs"]) <= sum(utxos[i]["amount"] for i in tx["inputs"])
def apply_block(utxos, transactions, miner, reward, number):
new, fees = dict(utxos), 0
for k, tx in enumerate(transactions):
if not validate(tx, new):
return f"block rejected: transaction {k} invalid", utxos
fees += sum(new[i]["amount"] for i in tx["inputs"]) - sum(o["amount"] for o in tx["outputs"])
for i in tx["inputs"]:
del new[i]
for n, o in enumerate(tx["outputs"]):
new[f"{identifier(tx)}:{n}"] = o
gain = {"inputs": [], "outputs": [{"to": miner, "amount": reward + fees}], "block": number}
new[f"{identifier(gain)}:0"] = gain["outputs"][0]
return f"block accepted, {fees} in fees", new
def balances(utxos):
r = {}
for o in utxos.values():
r[o["to"]] = r.get(o["to"], 0) + o["amount"]
return dict(sorted(r.items()))
utxos = {"tx1:0": {"to": "Awa", "amount": 10000}, "tx2:0": {"to": "Kofi", "amount": 7000}}
good = [{"inputs": ["tx1:0"], "outputs": [{"to": "Fatou", "amount": 6000}, {"to": "Awa", "amount": 3900}]},
{"inputs": ["tx2:0"], "outputs": [{"to": "Mei", "amount": 6950}]}]
message, utxos = apply_block(utxos, good, "Miner", 500, number=1)
print(message, balances(utxos))
fatou_key = next(k for k, o in utxos.items() if o["to"] == "Fatou")
fraud = [{"inputs": [fatou_key], "outputs": [{"to": "Yao", "amount": 6000}]},
{"inputs": [fatou_key], "outputs": [{"to": "Kofi", "amount": 6000}]}]
message, utxos = apply_block(utxos, fraud, "Miner", 500, number=2)
print(message, balances(utxos))
block accepted, 150 in fees {'Awa': 3900, 'Fatou': 6000, 'Mei': 6950, 'Miner': 650}
block rejected: transaction 1 invalid {'Awa': 3900, 'Fatou': 6000, 'Mei': 6950, 'Miner': 650}
The first block earns the miner 500 in reward and 150 in fees. The second is rejected entirely, and the balances stay unchanged: a block applies all or nothing.
Common mistakes:
- Modifying
utxosdirectly: if the third transaction fails, the first two are already applied and the state is inconsistent. - Forgetting the block number in the reward transaction: two identical rewards would have the same identifier, and the second would overwrite the first.
- Granting the miner a reward above the rule: the other nodes must reject that block.
Summary
- 1In the UTXO model, a transaction entirely consumes existing outputs and creates new outputs, including change.
- 2Fees are the difference between the sum of the inputs and the sum of the outputs; they go to the miner.
- 3A valid transaction only uses unspent outputs, without duplicates, negative amounts or money creation.
- 4The transactions of a block are validated in order, on an updated state, and the block applies all or nothing.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.