A cryptocurrency is a ledger of payments kept by agents who do not trust each other. We start with two simple currencies. Goofycoin shows the central problem, double spending. Scroogecoin solves it with a trusted bank. Bitcoin keeps the same kind of ledger with nobody in charge. It was described by Satoshi Nakamoto in 2008, and its network has run since January 2009.
This lecture uses the tools of the cryptography lecture — hash functions, block chains, Merkle trees, signatures and search puzzles — and follows section 1.5 and chapters 2 and 3 of Narayanan, Bonneau, Felten, Miller and Goldfeder, Bitcoin and Cryptocurrency Technologies (bitcoinbook.cs.princeton.edu). Parts 1 and 2 study the algorithm; part 3 shows how it is engineered.
Three parts Part 1 (sections 1–5): how agents who do not trust each other agree on one ledger. Part 2 (sections 6–9): why agents take part, and what attackers can and cannot do. Part 3 (sections 10–14): how Bitcoin is engineered — transactions, scripts, blocks and the network.
Goofycoin has two rules.
pk. Anyone can check the chain
of signatures back to Goofy.Every signature in Goofycoin verifies, and nobody can forge one. Yet it has a fatal flaw.
The double-spending problem Signatures show who authorized a payment. They cannot show that the payer had not already spent the coin. For that, everyone must agree on one history of all transactions.
Scroogecoin fixes double spending with a trusted bank, Scrooge,
who keeps the one history. Agents are identified by their public keys.
The bank keeps a tamper-evident ledger: a block chain of
transactions, with the hash pointer to its head signed by the bank. A
transaction either creates coins, which the bank gives to
agents, or pays coins: agents (the payers) give coins they own
to other agents (the payees). A coin is named by
(transaction id, index): coin (1, 0) is the
first coin created by transaction 1.
Before appending a payment, the bank checks that
Rule 3 is what stops double spending: an agent cannot pay Amazon and then pay Walmart with the same coins. The bank groups transactions into blocks and signs the hash pointer to the head of the chain. Agents keep copies of the ledger and can check every transaction themselves, and the bank cannot rewrite the history without being caught.
(1, 0) and
gets 3 back as change. In transaction 3, Ana tries to pay Chuck with
the same coin (1, 0). It was consumed in transaction 2, so
Scrooge rejects it. Transaction 4 shows a payment that is valid.
The key property The bank holds the master copy of the ledger. An agent’s copy can differ from the master copy in only one way: it may be a prefix of the master copy — it may not yet have the newest blocks.
| Advantages | Disadvantages |
|---|---|
| Every agent can verify every transaction in its copy. | The bank is a single point of failure. |
| An agent’s copy is a prefix of the master copy. | The bank can refuse service to agents it dislikes. |
| Nobody, not even the bank, can forge a payer’s signature. | The bank can create as many coins as it likes. |
| Agents are anonymous: they are known only by public keys. | Agents must trust the bank. |
Scroogecoin works, but everything depends on Scrooge. Can we get rid of him? Suppose there is no bank: every agent keeps its own copy of the ledger, and the agents themselves must do the bank’s work. Four challenges appear.
The key problem All agents must come to a consensus about which block enters the ledger next.
Question for you. Why can’t we use Paxos or the Byzantine generals algorithm to reach that consensus?
t on the number of
faulty agents.And the FLP theorem says that in an asynchronous system no algorithm can guarantee consensus if even one agent may be faulty. So how does Bitcoin work?
Bitcoin’s answer Bitcoin reaches consensus with very high probability, and the probability grows the longer you wait. It does not guarantee consensus, so FLP does not rule it out.
How can the agents choose one of themselves, at random, to act as the bank for the next block? Imagine a room of people solving puzzles. The first to solve hers shouts “I’ve solved it!”, and everyone agrees that she is “it”: she adds the next block.
Bitcoin uses the search puzzles of the
cryptography lecture. An agent
collects valid transactions into a block trans, and
searches for a number nonce such that
where H is a cryptographic hash function (SHA-256),
ptr is the hash pointer to the head of the agent’s
chain, and target is a number: the smaller the target, the
harder the puzzle. This is called proof of work, and the search
is called mining.
Questions for you, from the room of puzzle solvers:
H is puzzle friendly, the time to solve
is random, and agents have different amounts of computing power. But
collisions do happen; section 5 deals with them.Why puzzles defeat the Sybil attack An agent’s chance of winning is proportional to its share of the total computing power, not to its number of identities. A million public keys cost nothing; a million computers do not.
Bitcoin adjusts the target every 2,016 blocks, about every two weeks, so that the whole network solves one puzzle about every 10 minutes on average, however much computing power joins or leaves.
When an agent solves its puzzle, it appends its block to its copy of the chain and broadcasts the new chain to everyone. That is “I’ve solved it!” shouted across the room. Every agent that follows the protocol obeys one rule:
The longest-chain rule Accept a chain only if every block and every transaction in it is valid. Keep the longest valid chain you have seen; on a tie, keep the one you saw first. Always mine on top of the chain you keep.
When agent A′ receives a longer chain
L + B, it stops solving its own puzzle and starts a new
one, to extend L + B. If message delays are short compared
with the time to solve a puzzle (10 minutes), it is unlikely that
A′ solves its old puzzle while L + B is
in transit. Unlikely, but possible.
A collision. Agent A’s chain is
L. It receives L + X and switches to it,
because it is longer. Then it receives L + Y, from an agent
that solved its puzzle at about the same time. L + Y is
not longer, so A ignores it. Other agents may have received
L + Y first and kept it. The chain has forked.
The fork ends when someone solves the next puzzle. If an agent with
L + X finds X′, then
L + X + X′ is the longest chain, and everyone
switches to it. Block Y becomes an orphan. Its
transactions are not lost: they return to the pool, and a later block
includes them.
Collisions can continue: B appends X′
to L + X while C appends
Y′ to L + Y, and so on. But each
further collision is again unlikely, so a run of k
collisions becomes very unlikely as k grows.
With a bank, every agent’s copy was a prefix of the master copy. Bitcoin has no master copy. What it has instead is figure 4’s shaded region: honest agents’ copies share a long common prefix and may differ only in the last few blocks.
Suppose agent B’s chain is
L + X1 + … + Xk. How likely
is it that some other honest agent’s chain does not start with
L? For that to happen, there must have been a run of about
k collisions, and that becomes very unlikely as
k grows.
Confidence grows with depth
A block that is k blocks deep is in every honest
agent’s chain with a probability that approaches 1 quickly as
k grows. Old blocks are settled with very high confidence;
the newest blocks with low confidence. A common rule is to treat a
payment as final after 6 confirmations: six blocks on top of
the block holding it, about an hour.
Mining costs computing power and electricity. Agents do the bank’s work because they get paid, in two ways.
Incentives keep miners honest A miner is paid only if its block ends up in the chain that everyone keeps. So it pays to mine on the longest chain, and to include only valid transactions: an invalid block is rejected by every honest agent, and its reward is worthless.
Putting sections 2–6 together, every mining agent runs this loop. The checks are the bank’s three rules, now carried out by everyone.
loop: # keep the longest valid chain heard so far if a valid chain longer than mine arrives: switch to it # build a block on the head of my chain trans = valid transactions not yet in my chain # signed, in = out, unspent trans = [reward to my public key] + trans ptr = hash pointer to the head of my chain # proof of work try nonces until H(nonce ‖ ptr ‖ trans) < target, or until a longer chain arrives if solved: append the block to my chain and broadcast it
The block itself is small: a header with the hash pointer to the previous block, the root of a Merkle tree of its transactions, the target and the nonce; then the transactions. The Merkle root lets a phone check that one payment is in a block without downloading the whole block.
| Attack | Does it work? |
|---|---|
| Steal coins by spending someone else’s coins | No. A payment must be signed by the owner, and signatures cannot be forged. |
| Mine an invalid block, for example creating extra coins | No. Honest agents check every block and reject it, so the miner is never paid. |
| Denial of service: a miner leaves your transaction out | Only briefly. The next honest miner includes it. |
| Fraud outside the ledger: you pay for a video and it never arrives | Bitcoin cannot help. It records payments; it cannot enforce what is bought. |
| Double spend: pay a seller, then replace the block holding the payment with a longer chain that leaves it out | Only if the attacker can outrun all honest miners. The seller defends by waiting for confirmations. |
| 51% attack: an attacker with most of the computing power | Can double spend and censor transactions. Still cannot steal, because it cannot forge signatures. |
The double spend is the attack that the longest-chain rule must stop.
The attacker pays a seller in a block, waits until the seller sees
z confirmations and hands over the goods, then tries to
build, in secret, a longer chain without the payment. It starts
z blocks behind. If the attacker has a fraction
q of the computing power and the honest miners
p = 1 − q, each new block is the attacker’s with
probability q: the race is a random walk. Nakamoto showed
that the probability the attacker ever catches up is
(q/p)z that an
attacker with share q ever catches up from z
blocks behind. With 25% of the power and 6 confirmations it is under
0.2%. Move the slider: the probability falls exponentially with
z while q is below one half, and jumps to 1
when the attacker has a majority. Simulate runs 1,000 random
races from 6 behind and compares the fraction the attacker wins with
the formula.
The security assumption Bitcoin is safe as long as honest agents control most of the computing power — not most of the identities, which would be worthless, but most of the work.
| Paxos | Byzantine (signed) | Bitcoin | |
|---|---|---|---|
| Who takes part | Known agents | Known agents | Anyone, at any time |
| Timing | Asynchronous | Synchronous rounds | Delays short compared with 10 minutes |
| Faults | Agents halt | Up to t faulty agents | A minority of the computing power |
| Agreement | Certain | Certain | With probability growing with depth |
| Cost | Messages | Messages, t+1 rounds | Messages and a great deal of computation |
The cost in the last row is real: Bitcoin mining uses as much electricity as a small country, roughly. Other cryptocurrencies replace proof of work with proof of stake, in which the chance of adding the next block depends on the coins an agent has locked up rather than on its computing power. Ethereum, the second-largest cryptocurrency, switched to proof of stake in 2022.
Parts 1 and 2 describe the algorithm. Part 3 describes how Bitcoin actually stores coins, checks payments, packs them into blocks and spreads them across the Internet. It follows chapter 3 of the Princeton book, and leaves out byte-level details.
Bitcoin has no accounts and no balances. Like Scroogecoin, it has only
transactions, and a coin is an output of a transaction:
a value and the identity of its owner. An output is named by
(transaction id, index). For example, the transaction
has id 3146 and two outputs: (3146, 0) gives 2.1 coins to
the owner of public key 7xxxx…, and
(3146, 1) gives 3.2 coins to 8xxxx….
A payment has inputs and outputs. Each input names an earlier output that the payer owns, and is signed by its owner. Each output is a value and a payee. Every output is spent in full, the first time it is used as an input; if the payer wants to pay less, it pays the rest back to itself as change. Whatever the inputs hold beyond the outputs is the transaction fee for the miner.
Unspent outputs At any moment, the coins that exist are exactly the unspent transaction outputs. To check a payment, a node checks that every input is an unspent output, signed by its owner, and that the inputs hold at least as much as the outputs.
(7359, 3) worth 8.5 to
6xxxx. Transaction 8001 spends (3146, 1)
and (7359, 3), so it must be signed by both owners, and
creates three outputs worth 0.5, 3.5 and 7.6. The inputs hold 11.7
and the outputs 11.6: the remaining 0.1 is the fee. The two spent
outputs leave the set of unspent outputs, and the three new ones
join it.
An output does not simply name its owner. It holds a small program, a script, that says what anyone must provide in order to spend it. The input that spends it supplies the data, and every node runs the two together. The output can be spent only if the script finishes with true.
Almost every output uses the same script, pay to public key hash. The output holds the hash of the owner’s public key — this hash is the owner’s address. To spend it, the owner supplies a signature and the public key itself. The script checks that the key hashes to the address, and that the signature verifies with that key.
# supplied by the spender (in the input) <sig> <pubKey> # in the output being spent DUP HASH160 <pubKeyHash> EQUALVERIFY CHECKSIG
The script language works on a stack. Data items are pushed on
it. DUP copies the top item; HASH160 replaces
the top item by its hash; EQUALVERIFY removes the top two
items and stops with false unless they are equal;
CHECKSIG removes a public key and a signature and pushes
true if the signature verifies on the transaction. The language
deliberately has no loops, so every script finishes quickly.
EQUALVERIFY,
because its key does not hash to the address.
Scripts allow more than plain payments. A multisignature output needs, say, any 2 of 3 named keys to sign. That gives escrow: a buyer pays into an output that needs 2 signatures out of the buyer, the seller and a judge. If the video arrives, buyer and seller sign and the seller is paid; if not, the judge signs with whichever side is right. This answers, in part, the “video never arrives” attack of section 8. A lock time can also make an output spendable only after a given block.
A block has a small header and a list of transactions. The header holds
Mining hashes only the header (with SHA-256, twice), so a miner can try billions of nonces without touching the transactions. Because the header contains the Merkle root, the proof of work covers every transaction in the block. The first transaction in every block is the coinbase transaction: it has no inputs, and its outputs pay the block reward plus all the fees of the block to the miner.
Bitcoin’s nodes form a peer-to-peer network: each node is connected to a few others, chosen at random, and anyone can join by contacting a few known nodes. There is no central server.
A new transaction or block spreads by flooding, also called gossip. A node that hears something new checks that it is valid, passes it on to its neighbors, and ignores any copy it has already seen. Each node keeps the valid transactions it has heard of but not yet seen in a block in a pool, the mempool, and miners build their blocks from it. If two transactions spend the same output, a node keeps the first it hears and drops the other.
Not every node does everything. A full node stores the whole block chain and checks every transaction. A lightweight node keeps only block headers and trusts that the longest chain is valid. Miners are full nodes that also search for proofs of work.
| Problem | Bitcoin’s answer |
|---|---|
| Who acts as the bank for the next block? | Whoever solves a search puzzle first (proof of work) |
| Identities are free (Sybil attacks) | Winning depends on computing power, not identities |
| Two blocks found at once (forks) | Keep the longest valid chain; the fork soon ends |
| No master copy | A common prefix, settled with confidence that grows with depth |
| Why do the work? | Block rewards and transaction fees |
| Double spending | Wait for confirmations; safe while honest miners have most of the power |
| What is a coin? | An unspent output of a transaction, locked by a script |
| How does news spread? | Flooding over a peer-to-peer network; each node validates before relaying |