DisSysLab

Bitcoin

Consensus without a trusted party

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.

Part 1. Consensus without a bank

1. Signatures are not enough: Goofycoin

Goofycoin has two rules.

  1. Goofy creates coins. He signs the statement “CreateCoin [uniqueCoinID]”. The new coin belongs to Goofy.
  2. An owner spends a coin by signing “Pay this coin to pk”, together with a hash pointer to the coin. The coin now belongs to the owner of 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.

Figure 1. Double spending in Goofycoin. Goofy creates a coin and pays it to Alice. Alice signs a payment of the coin to Bob, and then signs a payment of the same coin to Chuck. Both chains of signatures verify. Bob and Chuck each believe they own the coin: it has been spent twice.

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.

2. A trusted bank: Scroogecoin

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

  1. it is signed by every payer;
  2. the coins paid in equal the coins paid out;
  3. every coin paid in is genuine — created in an earlier transaction — and not already spent.

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.

Transactions sent to Scrooge

Coins (unspent coins are not struck through)

Figure 2. Scroogecoin stops a double spend. Scrooge checks each transaction against the three rules before he appends it. Transaction 1 creates coins for Ana and Ben. In transaction 2, Ana pays Ben 2 with her coin (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.

AdvantagesDisadvantages
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.

3. Removing 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.

  1. Selection. Some single agent must play the role of the bank for the next block.
  2. Synchronization. Agents must wait long enough for everyone to update their copies.
  3. Incentives. Why would an agent do the bank’s work?
  4. Untrustworthy agents. Some agents will cheat.

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?

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.

4. Selecting one agent with a puzzle

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

H(nonce ‖ ptr ‖ trans) < target

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:

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.

Figure 3. A mining race. Four miners own 40%, 30%, 20% and 10% of the computing power, so in each instant they try 8, 6, 4 and 2 nonces respectively. Each hashes its own block — its own puzzle — with real SHA-256, and wins if the hash starts with 10 zero bits (about 1 chance in 1,000 per try). Press Race to watch one race. Press Run 200 races: each miner wins about its share of the races. Luck decides each race; computing power decides the long run.

5. Forks and the longest chain

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.

Message delay
Figure 4. Forks, and the prefix everyone agrees on. Each row is one agent’s copy of the chain; a block is colored by the agent that mined it. Blocks are found at random, on average once every 10 steps, and reach the other agents after the message delay. The shaded part is the common prefix: the blocks that every agent’s copy shares. With long delays, two agents sometimes find blocks before hearing of each other’s, and the copies differ at the end. The fork never lasts: soon one branch is longer, and the shaded prefix catches up. Orphaned blocks are counted below the chains. This figure is a simulation of the rules, not of real mining.

Is there a master copy?

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.

Part 2. Incentives and attacks

6. Why would anyone mine?

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.

7. What an agent does

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.

8. Attacks

AttackDoes 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   if q < p,   and 1 if q ≥ p.
Attacker’s share of computing power q 25%
Figure 5. Can an attacker catch up? Each bar is the probability (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.

9. Bitcoin compared

PaxosByzantine (signed)Bitcoin
Who takes partKnown agentsKnown agents Anyone, at any time
TimingAsynchronousSynchronous rounds Delays short compared with 10 minutes
FaultsAgents haltUp to t faulty agents A minority of the computing power
AgreementCertainCertain With probability growing with depth
CostMessagesMessages, 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.

Part 3. How Bitcoin is engineered

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.

10. Transactions

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

(3146, create, [(2.1, 7xxxx…), (3.2, 8xxxx…)])

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.

Figure 6. Following coins through transactions. Transaction 3146 creates two outputs. An earlier transaction 7359 left an output (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.

11. Scripts

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.

Figure 7. Running a script. Each step runs one instruction; the stack is on the right. With the owner’s key, the hash matches the address, the signature verifies, and the script ends with true: the output may be spent. Press Try someone else’s key: a thief who supplies its own public key and signature fails at 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.

12. Blocks

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.

Figure 8. The structure of a block. The header (top) is hashed for the proof of work and points to the previous block. Its Merkle root covers the transactions below it; the first is the coinbase transaction that pays the miner. A lightweight node, such as a phone wallet, keeps only the headers, and checks that its payment is in a block with a Merkle proof, as in the cryptography lecture.

13. The network

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.

Figure 9. Flooding a transaction through the network. Each of 40 nodes is connected to a few peers, mostly nearby ones, plus a few long links. A transaction starts at one node (orange). At each step, every node that heard it in the previous step passes it to all its neighbors; a node that has already seen it does nothing. In the real network, peers are chosen at random from all over the Internet, so the number of steps grows only with the logarithm of the number of nodes. That is why a new block reaches most of the network within seconds.

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.

14. Limitations

Summary

ProblemBitcoin’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

Exercises

  1. List three ways Scrooge could harm users. Which of them can users detect from the ledger?
  2. Why can’t Bitcoin decide the next block by a majority vote of all agents?
  3. In figure 3, a miner has 10% of the computing power. About how many blocks a day does it win, if a block is found every 10 minutes?
  4. In figure 4, choose a very long delay. What happens to the number of orphaned blocks, and why? Why does Bitcoin choose a block time of 10 minutes rather than 10 seconds?
  5. A transaction is in an orphaned block. Is the money lost? What happens to the transaction?
  6. An attacker has 30% of the computing power. Using the formula of section 8, how many confirmations should a seller wait for to make the probability of a successful double spend less than 0.1%?
  7. An attacker with 51% of the computing power wants to take coins from your public key. Can it? What can it do?
  8. The block reward halves every 210,000 blocks. Why does this make the total number of bitcoins less than 21 million? (Hint: 210,000 × 50 × (1 + 1/2 + 1/4 + …).)
  9. Ana owns one output worth 5 coins and wants to pay Ben 2 coins with a fee of 0.1. Write down the inputs and outputs of her transaction.
  10. In figure 7, why does the script hash the public key and compare it with the address, instead of storing the public key in the output? What would a thief need in order to spend the output?
  11. Design an escrow for buying a video, using a 2-of-3 multisignature output. Who are the three key holders, and who signs in each case?
  12. In figure 9, about how many steps does flooding take with 40 nodes? Roughly how would that change with 40,000 nodes?