Chapter 6 · Lectures 16 to 18
Bitcoin
Digital bits can be copied, so digital money needs a way to make the same coin unspendable twice. Bitcoin answers with a public ledger that no one operates. Miners win the right to append the next block in a hash lottery. Every node follows the chain carrying the most accumulated proof of work.
Lecture 16 (13/11/25) is sections 1 to 6, Lecture 17 (18/11/25) is sections 7 to 10 and Lecture 18 (25/11/25) is sections 11 to 13. Study plans: Lecture 16, Lecture 17, Lecture 18.
Section 1The Double-Spending Problem
Lecture 16.
A digital coin can be copied like any other data. Its owner can send the same bitstring to two merchants, each of whom sees a valid payment. Paper money avoids this problem because the note changes hands. A bank ledger avoids it by debiting one account, crediting another and refusing the second payment. The bank is the trusted center. Chaum's eCash (1990) kept that center. The bank issued blinded coins (coins the bank signed without learning which coin it signed) and stopped double spending by checking each deposit against a database of spent coins. The cryptography protected privacy. Money did not circulate without the bank.
Bitcoin removes the center and keeps the ledger. The users emulate a public bulletin board listing every transaction, in the form "user $P_i$ transfers coin 16fab13fc6890 to user $P_j$". A coin is identified by the transaction that created it. Everyone can read the board, so everyone can check whether a coin was already spent. The board has no operator. Two parties want to cheat: a payer who wants the same coin to count twice and a payee who wants a payment to vanish after delivery.
The bulletin board is therefore a consensus problem. Proof-of-work consensus can provide eventual agreement when honest miners control a majority of the hash power and the network meets its timing assumptions. In an open network identities are free, so an attacker can create a million pseudonyms and outvote the honest users. This is the Sybil attack. It makes majority of identities meaningless. Bitcoin counts votes by a resource that cannot be created for free, computing power. Majority becomes majority of hash rate. The evidence is the proof of work of section 3.
Double spending is a consensus problem. Bitcoin replaces the trusted center with anonymous miners, and majority of identities with majority of computing power.
Section 2Design Principles, and What Decentralization Costs
Lecture 16.
The difference from eCash is the trust model. Bitcoin is decentralized, so money circulates without a center and fees float.
Chaum's company went bankrupt in 1998. Nakamoto announced Bitcoin in 2008; it became popular between 2011 and 2013 as the payment method of anonymous marketplaces such as Silk Road. Its market price skyrocketed at the end of 2013.
The protocol limits the eventual supply to about 21 million BTC. New issuance continues until that limit is reached. The exchange rate fluctuates. A bitcoin's value comes from the expectation that others will accept it later. Enthusiasts call it real money and sceptics call it a Ponzi scheme. Some economists, including Ben Bernanke, have been more measured, granting long-term promise for a faster, more secure and more efficient payment system while flagging law-enforcement risks.
"No trusted server" describes the protocol itself. The client software is written by people who can change the system and contains hardcoded checkpoints, discussed in section 4. Around the protocol sit the blockchain data, an industry of exchanges, mining pools and remote wallets. These form an economy of agents, goods and markets. Bitcoin spread for ideological reasons, for timing, for the seeming anonymity of pseudonymity, because payments were cheap for a long time and because it is a new distributed-systems construction.
The downsides follow from the absence of a regulator.
- MtGox, which handled 70% of all Bitcoin transactions, shut down in February 2014 reporting 850,000 BTC stolen, about 450 million USD at the time.
- Transactions cannot be reversed.
- Software bugs are immediately profitable to exploit, which attracts ransomware and coin-stealing malware.
- The ledger is public, so pseudonymity can be attacked, as section 9 describes.
Bitcoin is pseudonymous. Anonymous is a stronger claim. Payments are linked to keys. Keys can be linked to people. Section 9 covers the privacy story. Chapter 7 covers Zerocash, a stronger construction.
Section 3Proof of Work: The Hash Lottery
Lecture 16.
Counting hash power requires a proof. The tool is proof of work, due to Dwork and Naor (1992): a puzzle moderately hard to solve and trivial to verify. The digital version uses a cryptographic hash function $\Hash$ with running time $\mathrm{TIME}(\Hash)$. Given a random challenge $x$, find an answer $s$ such that $\Hash(s \| x)$ starts with $n$ zero bits. Verification is one hash evaluation, time $\mathrm{TIME}(\Hash)$. Finding a solution is a sequence of independent trials, each successful with probability $2^{-n}$, so the expected time is $2^{n} \cdot \mathrm{TIME}(\Hash)$.
Common mistake. After a long dry spell a miner feels due for a block. Each hash is an independent trial, so an hour of failures changes nothing. The expected wait to the next block stays ten minutes, now and at every later moment.
For a challenge $x$ and a hardness parameter $n$, a valid proof of work is an $s$ such that the first $n$ bits of $\Hash(s \| x)$ are zero. The expected number of trials to find $s$ is $2^{n}$. A valid proof of work is evidence that finding it required substantial expected work at the stated difficulty.
History. Adam Back announced Hashcash in 1997, a partial hash-inversion proof of work aimed at email spam. Nakamoto cited it in the 2008 whitepaper; Bitcoin's puzzle follows its design closely.
The asymmetry is the point. Producing a valid block costs real energy and dedicated hardware; checking it costs one hash evaluation. The puzzle computes nothing useful. Its value is deterrence, paid for in electricity and machines. The cost is what makes a stranger's block credible evidence of spent computing power.
Common mistake. Miners solve a difficult mathematical puzzle, so cleverness should pay. Mining is blind search: vary the nonce, hash the header twice and hope the result falls below the target. Only the hash rate helps.
Bitcoin hashes block headers twice with SHA-256 (Secure Hash Algorithm with a 256-bit output). Block capacity is measured in weight units, and transaction throughput varies with transaction size and block use. The genesis block (the first block of the chain) was created by Nakamoto on 03/01/09. To extend the chain, a miner searches a salt $s$ such that $\Hash(s \| \Hash(B_i) \| \mathrm{TX})$ starts with $n$ zeroes, where $\mathrm{TX}$ summarizes the transactions and $\Hash(B_i)$ links to the previous block.
Common mistake. Mining is secure because SHA-256 is collision resistant. Mining needs only partial preimage resistance: nobody should find an input whose hash lands below the target faster than guessing. A collision attack would not speed up mining.
The total mining power changes, so the target retunes every 2016 blocks. At 10
minutes per block, 2016 blocks should take two weeks; nodes compare the timestamps
of the window's first and last block and scale the target by the ratio of elapsed
time to two weeks. Difficulty is then defined as
difficulty = difficulty_1_target / current_target. The block header
packs the current target into a four-byte Bits field, one exponent byte $e$ and a
three-byte mantissa $m$, decoded as $m \cdot 256^{e-3}$. The genesis block carries
Bits 0x1d00ffff, which decodes to
$\texttt{0x00ffff} \cdot 256^{26}$; that value is
difficulty_1_target by definition, so the genesis difficulty is 1.
The deck's hash-rate figures show the growth the retargeting absorbs: 2,550,000
TH/s (terahashes per second) in January 2017, 15,000,000 TH/s in January 2018, 50,000,000 TH/s in
September 2018 and 114 EH/s (exahashes per second) by October 2019. Every doubling of hash rate doubles
the difficulty, so the expected work per block stays
$2^{n} \cdot \mathrm{TIME}(\Hash)$.
Worked number. Suppose 2016 blocks arrive in 7 days against the 14 day goal. The measured interval is half the target, so the difficulty doubles for the next period. A single retarget can multiply or divide the difficulty by at most four.
The Hash Lottery
Choose a difficulty $n$ and watch the nonce search. The toy hash is 32-bit A Fowler-Noll-Vo Hash (FNV-1a); Bitcoin uses SHA-256. The geometric structure is the same.
Worked number. At difficulty 100 trillion a block needs about $4.3 \times 10^{23}$ hashes in expectation. A global fleet at 800 exahashes per second finds one in about 537 seconds, close to the 600 second target.
Proof of work is expensive to produce and cheap to check. It is the only place in the protocol where physical resources enter.
Common mistake. The ten minute block interval is a timer the network enforces. Ten minutes is a statistical average produced by the retargets. Actual gaps follow an exponential distribution. Gaps of one minute or of one hour are routine.
Section 4The Blockchain, and How a New Node Validates It
Lecture 16.
The bulletin board is stored as a chain of blocks. Each block contains the transactions of one period and a header carrying the hash of the previous block, the Merkle root (the top hash of a tree of hashes) summarizing the transactions and the salt used in the proof of work. The hash link is what makes the structure a chain. Changing any transaction in any block changes its hash, which changes the header of the next block and so on to the tip. Rewriting history means redoing the proof of work for every block after the change.
Transactions inside a block form a Merkle tree. The root is a single fixed-size hash, easy to transmit in pooled mining and convenient for hardware hashing. An inclusion proof has length $O(\log d)$ and verifies in $O(\log d)$ time for tree depth $d$, which lets light clients check payments without processing entire blocks and lets old transactions be pruned once their Merkle proofs are no longer needed.
A new user deciding which chain is valid needs two things, the initial rules of the game and the genesis block, and among candidate chains picks the one that verifies correctly and is strongest in the sense of section 5. Full verification is expensive. The deck records the blockchain at about 185 GB in September 2018, and verification can take several hours.
Checkpoints are old block hashes hardcoded into the client software. In theory they are unnecessary and sit uncomfortably with decentralization. In practice they do two jobs.
- They stop fake-chain attacks, both the denial-of-service kind that floods nodes with unusable chains and the kind that isolates a node and feeds it a fake chain.
- They speed up the initial blockchain download.
Protocol changes are specified in Bitcoin Improvement Proposals (BIPs). Developers, node operators, miners and users adopt each change through its defined activation method.
The genesis block must be fresh. If its creator had known it before launch, a secret chain started decades earlier could be published later and outwork the public one. The genesis block contains the hash of a front-page title from the London Times of 3 January 2009, a heuristic timestamp proof.
Section 5Forks and the Rule That Settles Them
Lecture 16.
Forks are routine. Two miners can solve the proof of work for the same height almost at the same time; each broadcasts a block, so each node starts extending the block it heard first. For a while the network holds two valid chains with the same prefix. Nodes choose the valid chain with the most cumulative proof of work. When both branches use the same difficulty, block count is a proxy for cumulative work. One branch keeps growing, the other dies and its blocks are discarded.
A transaction that lived only in the dead branch returns to the pool and can be included again later. The payee's risk is a payment that appears confirmed and then disappears when its branch loses the race. A double spender rides this race:
| # | Party | Action |
|---|---|---|
| 1 | Attacker | Broadcasts a payment to the merchant on the public chain. |
| 2 | Honest miners | Confirm it; the merchant delivers after several confirmations. |
| 3 | Attacker | Privately re-mines the history from before the payment, building a fork that excludes it. |
| 4 | Attacker | Publishes the fork. If it carries the most work, nodes switch to it and the payment disappears. |
The probability that a confirmed block is superseded falls exponentially with each added block, and with minority computing power the attempt is unlikely from the start, because the honest miners stay ahead. The deck's recommendation is to wait 6 blocks, about one hour, before treating a payment as settled.
Worked number. Section 11 of the whitepaper computes the probability that a minority attacker catches up from $z$ blocks behind. With 10% of the hash power it is 0.0009137 at $z = 5$, about 0.09%, and 0.0000012 at $z = 10$, about one in a million.
Length alone is the wrong measure when the difficulty changes. An adversary can secretly mine a chain with fake timestamps claiming that the blocks took a very long time to produce. When the next retarget arrives, the difficulty on that secret chain drops, the adversary quickly produces many cheap blocks and publishes a chain that is longer than the valid one. Bitcoin therefore selects the strongest chain. The strength of a block mined at hardness $n$ is $2^{n}$. The strength of a chain is the sum of the strengths of its blocks. A chain of 10 blocks at $n = 5$ has strength $10 \cdot 2^{5} = 320$, while a chain of 8 blocks at $n = 8$ has strength $8 \cdot 2^{8} = 2048$; the shorter chain is stronger, so the fake-timestamp attack fails.
The selection rule is commonly misstated. The word fork covers several different events.
- "The longest chain" is shorthand for the chain carrying the most cumulative proof of work. Length is a proxy for work only while the difficulty is constant; when difficulty varies, the strongest-chain rule decides.
- A chain reorganization is the routine event of this section, in which a stronger branch supersedes recent blocks and nodes switch to it. It is temporary and resolves itself.
- A hard fork is a protocol change under which blocks valid under the new rules were invalid under the old ones. Nodes that do not upgrade reject the new blocks, so the chain splits permanently unless everyone upgrades.
- A soft fork is a protocol change that narrows the validity rules. Blocks valid under the new rules remain valid under the old ones, so upgraded and non-upgraded nodes stay on one chain.
A Fork Race
Two branches grow from a common fork point. Each round, one block is found: by the adversary with probability $\alpha$, by the honest miners with probability $1 - \alpha$. The longest branch wins.
The chain with the most accumulated work wins. Confirmations are probabilistic. 6 blocks is the standard trade-off between waiting and risk.
What went wrong. In 2011 Hal Finney described how a miner can prebuild a block paying himself, spend the same coins with a merchant who accepts zero confirmations, then publish his block to erase the payment. Confirmations exist to close this option.
Section 6Where Bitcoins Come from: The Reward and the Fee
Lecture 16.
The ledger needs writers. Writers need payment. A miner that solves the proof of work receives a block reward of 50 BTC for each of the first 210,000 blocks, about four years; 25 BTC for the next 210,000; 12.5 for the next; and so on, halving at every epoch. The total supply is the geometric sum
$$210000 \cdot (50 + 25 + 12.5 + \cdots) = 21{,}000{,}000.$$Worked number. The geometric sum gives the 21 million figure. Rewards are paid in whole satoshis, so later halvings round down to zero and the true cap is 20,999,999.9769 BTC.
The reward is paid through the ledger itself. Each block contains one coinbase transaction transferring the reward to the miner, which gives miners a direct income and makes them broadcast a newly found block quickly, because the coinbase pays only if the block is adopted.
Fees are the second incentive. The total value of a transaction's inputs may exceed the total value of its outputs; the difference is the fee and goes to the miner. Users who want fast inclusion pay higher fees, so miners choose transactions accordingly. The deck's money-mechanics example uses the 25 BTC coinbase of one miner paying Alice, then a split and a merge, ending with balances of 5, 5 and 40 BTC; the stage in section 7 animates that graph.
When everyone follows the protocol, a miner $P_i$ whose computing power is an $\alpha_i$-fraction of the total mines an $\alpha_i$-fraction of the blocks, because $P_i$'s chance of solving the proof of work is proportional to the hash evaluations $P_i$ contributes. Fraction of computing power translates into fraction of revenue. This invariant is the fairness claim of Bitcoin mining, and selfish mining in section 10 breaks it.
The coinbase transaction and the fee make ledger maintenance profitable. The fixed reward schedule caps the supply at 21 million BTC. The reward is only paid on a block the network accepts.
Section 7Transactions, Unspent Transaction Outputs (UTXOs) and the Money Graph
Lecture 17.
Bitcoin is transaction based; technically there is no notion of a coin. A transaction names earlier transactions as its inputs and creates new outputs. In the deck's simplified syntax, $T_0$ is a coinbase in which $P_0$ creates 25 BTC; $T_1$ says "$P_0$ sends 25 BTC from $T_0$ to $P_1$" and carries $P_0$'s signature on $T_1$; $T_2$ says "$P_1$ sends 25 BTC from $T_1$ to $P_2$" and carries $P_1$'s signature on $T_2$. We say $T_2$ redeems $T_1$. Ownership is enforced through digital signatures. Bitcoin historically uses ECDSA, an elliptic-curve signature scheme over secp256k1, with serialized signatures of variable length. The syntax is simplified. Although a production transaction also carries the scripts of section 12 in a serialized format, the state transition is the same.
An unspent transaction output, UTXO, is an output of a confirmed transaction that has not yet been named as an input of another confirmed transaction. The state of the system is the UTXO set. A balance is a derived quantity, the sum of all UTXOs controlled by a key or script.
The UTXO set is the state of the system. A transaction is a state transition $\mathrm{APPLY}(S, \mathrm{TX}) = S'$ that removes from $S$ the outputs the transaction spends and adds the outputs it creates. As a worked example, suppose Alice holds a 6.00 BTC output from $T_1$ and a 2.50 BTC output from $T_2$ and pays Bob 3.00 BTC. Her transaction spends both inputs (8.50 BTC in), creates a 3.00 BTC output to Bob and a 5.00 BTC change output back to herself. The remaining 0.50 BTC is the fee. The lab below runs this payment and four broken variants.
Transactions split and merge value. One input can feed several outputs, as when a 25 BTC input pays 10 BTC to one party, 8 BTC to a second and 7 BTC to a third. Several inputs can feed one output, as when 10, 8 and 7 BTC from three earlier transactions combine into a single 25 BTC output. Each input must satisfy the condition that controls it. A transaction can also carry a timelock, making it valid only after a time $t$ measured in blocks or in real time. The conditions for redeeming an output can be more general than a signature; section 12 treats the scripting language that expresses them.
Validation is local and mechanical. The following three checks illustrate how full nodes reject common abuses.
| Check | Abuse it blocks |
|---|---|
| Every input must be in the UTXO set. | Spending coins that do not exist. Naming an already-spent output fails this check whatever signature it carries, which is what rejects a double spend against the confirmed chain. |
| The signature on each input must verify under the key that controls it. | Spending other people's coins. |
| The sum of the inputs must be at least the sum of the outputs. | Breaking conservation of value. The difference between the input and output sums is the fee. |
If consensus validation fails, full nodes reject the transaction. A separate race can occur when conflicting transactions remain unconfirmed.
Validate a Transaction
Alice builds a transaction paying Bob. Select the inputs, set the outputs and read the checks a full node runs. The fifth UTXO was already spent in a transaction $T_6$.
Money in Bitcoin is a directed acyclic graph of unspent outputs. There are no accounts to debit, only outputs to consume. Every node can check a transaction with the UTXO set and the signatures alone.
Section 8Mining Pools, and How to Pay Their Members
Lecture 17.
Solo mining has enormous income variance. The deck's estimate as of November 2018 puts the total network hash rate at about 40,000,000 TH/s (terahashes per second), while an Application-Specific Integrated Circuit (ASIC) Antminer S9, costing around 3,000 USD, delivers 14 TH/s. The ratio is about 2,857,142, so a solo miner with one such device waits about 54 years in expectation for a single block. Miners therefore form mining pools, operated centrally or peer to peer. A pool operator may charge a fee $\varphi$, so if the pool receives 25 BTC for a block, the members share $25 - \varphi$ BTC. Expected revenue is slightly lower; the variance is dramatically smaller.
The design question is how to reward members. The operator builds the block, including a coinbase transaction paying the pool's key $pk$, and sends each miner a transaction $T_i$ and a hash $\Hash(B_i)$. Miner $i$ searches $s_i$ such that $\Hash(s_i, \Hash(B_i), T_i)$ starts with $n$ zeroes, and submits the winning nonce. One full solution reveals nothing about how much work each miner did, so pools count partial solutions, or shares: values $s_i'$ whose hash starts with $n' \ll n$ zeroes. A miner's share rate is proportional to that miner's hash rate $\alpha_i$.
In the proportional method, when the pool wins, Alice receives $25 \cdot \frac{\alpha_A}{\alpha_A + \alpha_B + \alpha_C}$ BTC, her expected fair share. Pool hopping is the counter-strategy, in which a miner leaves a pool with many shareholders and joins a fresher one. Slush's method fixes this with a scoring function $\sigma = e^{-T/c}$, where $T$ is the time since the round began and $c$ is a constant; rewards follow scores, so late shares count more. Pay-per-share pays for every share whether or not the pool wins, transferring the variance to the operator and raising fees. Rosenfeld's 2011 analysis compares these reward systems.
Peer-to-peer mining removes the operator. Miners build a secondary chain with hardness $n' \ll n$ on top of the last main-chain block, tuned so that a new $n'$-block appears about every 30 seconds. Each such block stores hashes of the previous secondary blocks. The secondary chain eventually enters the main chain as one block whose reward is split by a formula among the secondary miners. Each miner is incentivized to extend the secondary chain honestly.
Pools convert a lottery ticket with a 54-year expected wait into a steady income stream. Shares are the proof of work inside the pool, easier than the real puzzle and proportional to the work contributed.
Section 9Attacks on the Ledger, the Pools and the Users
Lecture 17.
The deck considers attackers who seek to double spend, collect more than their fair share, profit from a collapse in Bitcoin's price or shut the system down. The 51% attack sets the baseline. Majority hash power grants specific abilities and leaves others out of reach:
| Majority hash power can | It cannot |
|---|---|
| Fork the chain and double spend its own recent payments; reject all other miners' blocks; exclude chosen transactions from blocks. | Steal money from earlier transactions, because that requires forging the owner's signature; generate money without effort, because coinbase outputs still require solved proofs of work. |
What went wrong. Bitcoin Gold (May 2018) and Ethereum Classic (January 2019 and August 2020) suffered double-spends from hash power rented by the hour. Exchanges lost millions of dollars. Confirmation counts must scale with the value at risk.
Mining pools assume an honest operator, because the operator has reputation. The miners are untrusted. Two attacks withhold blocks.
- Sabotage: a miner submits only partial solutions and never the complete one. The pool loses money. The dishonest miner earns nothing and loses a little. The goal is to bankrupt a competing pool. The deck records Eligus losing 300 BTC in 2014.
- Lie-in-wait: one party mines for several pools, each with about one third of its power. When a full solution is found for pool $P_1$, the attacker delays submitting it, mines only for $P_2$ and sends the solution to $P_2$ later, because $P_1$ is a likely winner of the current round.
Implementation failures have done more damage than protocol attacks. Block 74638, in August 2010, contained a transaction with two outputs summing to over 184 billion BTC, caused by an integer overflow in the Bitcoin software; the fix was a software update plus a manual fork. The fork at block 225430 was caused by an error in a software update and solved by reverting to the older version. The deck's moral is that nothing can be fully decentralized, because human intervention is sometimes needed.
What went wrong. Bitcoin Improvement Proposal 50 documents the cause: a Berkeley DB limit made version 0.7 nodes reject a block version 0.8 accepted. The chain split for 24 blocks and one merchant lost about $10,000 to a double-spend.
Transaction malleability is a subtlety of The Elliptic Curve Digital Signature Algorithm (ECDSA). Transactions are identified by their hash, $\mathrm{TxId} = \Hash(T)$, and if $\sigma = (r, s)$ is a valid ECDSA signature on a message, then $\sigma' = (r, -s)$ is also valid. Anyone can therefore maul a signature and change the TxId while the payment stays semantically the same, which breaks contracts that refer to transactions by TxId. The claimed MtGox attack used malleability to make a withdrawal look unconfirmed and then withdraw again; Decker and Wattenhofer (2014) judge this explanation probably false.
The ledger is public, and payments can be linked. Meiklejohn et al. ("A Fistful of Bitcoin", 2013) show heuristic de-anonymization. Hardware mining evolved from CPUs to Graphics Processing Units (GPUs), Field-Programmable Gate Arrays (FPGAs) and Application-Specific Integrated Circuits (ASICs); ASICs exclude casual miners and concentrate power. They also make botnet mining unprofitable and tie miners to the system's long-term stability. In June 2014 the Ghash.io pool passed 50% of total hash power. The deck's closing attacks are economic.
- Start pools with negative fees, wait for majority power and rely on miners joining if they care only about block reward.
- Whale transactions with huge fees that incentivize mining on old blocks.
- Flood attacks with many small transactions, countered by raising transaction fees.
Every guarantee in this section is conditional on the majority of hash power behaving honestly even when dishonesty pays. Selfish mining, next, shows a case where it does pay.
Section 10Selfish Mining: Majority Is Not Enough
Lecture 17.
Eyal and Sirer ("Bitcoin Mining is Vulnerable", Communications of the ACM 61(7), 2018) show that the honest strategy is incentive incompatible. Under honesty, a miner with an $\alpha$-fraction of computing power receives an $\alpha$-fraction of the revenue. Any strategy yielding more attracts switchers. As $\alpha$ grows, the dishonest strategy pays more, so miners have an incentive to join a large pool that runs it.
The strategy is withholding. When the adversary finds a block, it keeps the block secret and continues mining privately. When the public chain catches up, the adversary publishes enough of its private branch to force a race. If its branch wins, the honest block is orphaned and the work spent on it is wasted. The attack's payoff depends on the adversary's private lead and its ability to attract honest miners during a tie.
The first analysis assumes the adversary always wins ties, for example through many fake sensor nodes, although the Bitcoin specification only says to mine on the chain received first. The full attack removes the assumption. Let $\gamma$ be the probability that an honest miner, facing a tie, mines on the adversary's branch, and let the adversary control an $\alpha$-fraction of the hash power with $\alpha < 1/2$. When a tie is broadcast, the adversary's branch grows with probability
$$\delta = \alpha + (1 - \alpha)\gamma.$$Eyal and Sirer model the adversary's lead as a Markov chain with states $0, 0', 1, 2, \dots$, compute the stationary distribution and obtain the expected revenue, which exceeds the honest share whenever
$$\alpha > \frac{1 - \gamma}{3 - 2\gamma}.$$At $\gamma = 1/2$ the threshold is $1/4$. Uniform random tie-breaking gives $\gamma = 1/2$, so it does not remove the selfish-mining incentive.
The invariant of section 6, revenue proportional to hash power, fails below 50%. A quarter of the hash power can already earn more than a quarter of the rewards. The attack strengthens as the pool grows.
Section 11What Bitcoin Actually Achieves: Eventual Consensus
Lecture 18.
This section states the guarantee, following Garay, Kiayias and Leonardos ("The Bitcoin backbone protocol", EUROCRYPT 2015) and Pass, Seeman and shelat (EUROCRYPT 2017). With overwhelming probability, Bitcoin achieves eventual consensus.
- Safety: if two or more honest parties report a transaction as stable, meaning buried more than $k$ blocks deep, then that transaction stays in the same position forever.
- Liveness: every valid transaction is eventually committed by all honest nodes.
Both properties follow from three chain properties.
- Common prefix: for any two chains $C_1, C_2$ held by honest parties, pruning $k$ blocks from one yields a prefix of the other.
- Chain quality: in any chain adopted by honest parties, at least one of the last $k$ blocks was honestly generated.
- Chain growth: in any portion of an honest chain spanning $s$ prior slots, the number of blocks is at least $\tau s$.
Nakamoto's consensus is the protocol being analyzed: mine on the longest chain; upon adopting a new longest chain, broadcast the newly acquired blocks; commit a block once it is buried at least $k$ blocks deep. The main theorem, in the deck's synchronous model with known delay bound $\Delta$ and memoryless Poisson mining at constant honest and malicious rates $\alpha$ and $\beta$, sets $g = e^{-\alpha\Delta}$ and states that safety and liveness hold as long as
$$\alpha g^{2} > \beta.$$The adversary controls the message delay inside $(0, \Delta)$. The factor $g^{2}$ is the loss caused by network delays. In a Poisson process the probability of $k$ events in a window $t$ is $e^{-\lambda t}(\lambda t)^{k}/k!$. The gap $T$ between consecutive blocks is exponentially distributed with $\Pr[T > \Delta] \le e^{-\lambda\Delta}$. An honest block $B$ mined at time $t$ is a non-tailgater if no other honest block is mined between $t - \Delta$ and $t$; every other honest block is a tailgater. Non-tailgaters never share a height, so they extend the longest chain; each honest block is a non-tailgater with probability $g$, giving liveness from the growth rate $g\alpha$. A loner is an honest block with no other honest block in $[t - \Delta, t + \Delta]$; it is the only honest block at its height, its probability is $g^{2}$ and its rate is $g^{2}\alpha$. Violating safety requires two honest chains diverging by more than $k$ blocks, which forces the adversary to mine more blocks than the honest parties mine loners; the condition $\alpha g^{2} > \beta$ rules that out. Badertscher, Maurer, Tschudi and Zikas (CRYPTO 2017) give a composable treatment of Bitcoin as a transaction ledger.
Bitcoin's guarantee is probabilistic and asymptotic in $k$: safety and liveness hold with overwhelming probability under an honest-majority condition weakened by network delay. The 6-confirmation rule of section 5 is the practical instance. Section 9 states the boundary, what an adversary with majority hash power can and cannot do.
Section 12Scripts, Conditions and Bitcoin Contracts
Lecture 18.
The signature condition of section 7 is one instance of a general mechanism. A transaction output can carry an arbitrary boolean condition $C_i$. The spending transaction supplies a witness $W_i$. In the deck's notation, $T_j$ redeems $T_i$ if $C_i$ outputs true on the input $([T_j], W_i)$, where $[T_j]$ is the spending transaction itself. A standard payment uses $C_i([T_j], W_i) = \mathbf{V}(pk_i, [T_j], W_i)$, where the witness is a signature verified under the key that controls the output.
Each output of $T_i$ specifies a condition $C_i$. A transaction $T_j$ that names that output as an input is valid exactly when $C_i([T_j], W_j)$ evaluates to true for the supplied witness $W_j$. Signatures, hash preimages, timelocks and multisignature requirements are all instances of $C_i$.
As a concrete example, let $C([T], p, q, \sigma)$ be
true if and only if $p, q > 1$, $p \cdot q = 2501$ and $\sigma$ is Bob's
signature on $[T]$. The output can be spent by revealing the factorization
$p = 41$, $q = 61$ together with Bob's signature. Conditions are written in
Bitcoin's scripting language, deliberately Turing incomplete (it has no loops and every script terminates) so transactions
verify quickly and predictably, and miners may refuse strange transactions. A
standard pay-to-public-key-hash script is
OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG, which
duplicates the public key, hashes it, compares it with the hash in the output and
then checks the signature.
A $k$-out-of-$n$ multisignature condition requires signatures from any $k$ users out of a set of $n$. Timelock conditions make an output spendable only after a block height or a real time. Combining these pieces yields Bitcoin contracts; the deck's examples are payment channels, paying whoever knows a password, assurance contracts, deposits against spam, payments conditional on an event and decentralized organizations that replace lawyers with scripts. Micropayments push contracts off-chain, because on-chain payments worth a fraction of a cent face non-negligible fees, confirmation delays and the ceiling of about 7 transactions per second. The next section builds the fix.
A Bitcoin output is a predicate; a transaction input is a witness that satisfies it. The scripting language keeps the predicate language small enough to verify fast. Contracts are compositions of the same few predicates.
Section 13Payment Channels and the Lightning Network
Lecture 18.
A payment channel lets two parties adjust a balance off-chain and normally uses one on-chain funding transaction and one on-chain closing transaction. Alice and Bob open the channel by charging it with 1 BTC each. The state is a pair $(x, y)$ with $x + y = 2$, where $x$ is Alice's claim and $y$ is Bob's. If Alice pays $x' \le x$ to Bob, the new state is $(x - x',\; y + x')$, neglecting fees. Opening and closing are blockchain operations; every adjustment between them is offline.
The construction starts with a unidirectional channel, where only Alice pays Bob, built on a multisignature transaction. Alice creates a funding transaction $T_F$ whose output can be spent only by a transaction carrying both Alice's and Bob's signatures. Posting $T_F$ immediately is risky, since if Bob stops cooperating, Alice's money is locked forever. The fix is a refund. Before publishing $T_F$, Alice asks Bob to sign a refund transaction $T'$ returning the funds to Alice after 30 days. With $T'$ in hand, Alice can safely post $T_F$.
To pay 0.01 BTC, Alice signs a commitment $T_1$ splitting $T_F$ into 0.99 BTC for Alice and 0.01 BTC for Bob, spendable after 29 days, and sends $T_1$ to Bob. Bob obtains real money by adding his signature and posting $T_1$, but he must do so before day 30, when Alice's refund becomes valid. Each further payment sends a new commitment $T_{i+1}$ with a shorter timelock, and only the latest one matters. To close, Bob signs the last commitment and posts it by day 29. In a bidirectional channel Bob can also pay Alice; when the balance starts moving back, Bob's commitments carry a 28-day timelock, because Bob is now the party losing money and Alice needs time to react before his older 29-day commitment becomes spendable.
Channels compose into a network. To pay Dave through intermediaries, Dave picks a secret $X$ and gives Alice $Y = \Hash(X)$. Every hop along the route locks its payment to the reveal of $X$ before a timelock expires, paying 0.01 BTC against an $X$ with $\Hash(X) = Y$. When Dave claims the final payment by publishing $X$, every intermediary uses the same $X$ to claim from the previous hop. This is the Lightning construction.
Plasma: Committing an Off-Chain Ledger to the Chain
The deck closes with Plasma (Poon and Buterin, 2017). The blockchain can timestamp a commitment to a message $M$. Publishing only $\Hash(M)$ saves space. A Merkle tree over many messages saves more. Neither proves data availability; if the operator hides the underlying data, excludes a message or refuses to reveal the data behind a commitment, the injured user publishes the message directly. Plasma applies the same idea to ledgers. An operator maintains $L$ off-chain and periodically publishes $\Hash(L)$ on-chain in a smart contract. Users can exit at any time, so a dishonest operator cannot steal money. Users must still monitor both chains. Data unavailability is the open problem. Plasma Cash has large exits and avoids non-uniquely attributable faults; fungible Plasma has short exits and admits them. Dziembowski et al. (ITCS 2021) prove that one cannot have both.
Payment channels move the frequent case off-chain and keep the blockchain as the final settlement mechanism. Two on-chain transactions can carry arbitrarily many payments between them. Hash locks (payments locked to the reveal of a secret) extend one channel into a network.
Section 14Further Resources
- Bitcoin whitepaper (Nakamoto). The primary source; the double-spending and proof-of-work sections state most of this chapter's mechanism in nine pages.
- Mastering Bitcoin (Antonopoulos and Harding). Free; chapters on transactions, scripts, the blockchain, mining and security.
- Bitcoin Wiki. Protocol internals; the Difficulty page has the retarget formula with worked numbers.
- Bitcoin and Cryptocurrency Technologies (Princeton). Free academic textbook with video lectures and programming assignments.
- Learn Me A Bitcoin (Greg Walker). One visual page per concept, with raw-hex walkthroughs and built-in tools.
- MIT OCW (OpenCourseWare) 15.S12 Blockchain and Money. A complete recorded course.
- Majority is not Enough: Bitcoin Mining is Vulnerable (Eyal and Sirer). The selfish-mining paper and its 1/4 threshold.
- Interactive blockchain demo (Anders Brownworth). Edit block data and watch hashes break down the chain.
- mempool.space. Live blocks, mempool (broadcast transactions waiting for confirmation) and difficulty charts.
Section 15Exercises
A miner searches for a nonce at difficulty $n = 20$. How many hash evaluations are expected, and why does verification stay cheap? Drill
Each trial succeeds with probability $2^{-20}$, independently of the previous ones, so the number of trials is a geometric random variable with mean $2^{20} = 1{,}048{,}576$. The expected work is $2^{20} \cdot \mathrm{TIME}(\Hash)$. Verification checks the single candidate $(s, x)$ with one evaluation of $\Hash(s \| x)$ and a comparison of the first 20 bits, time $\mathrm{TIME}(\Hash)$. The asymmetry between finding and checking is the whole point of proof of work.
Show that the reward schedule caps the total supply at 21,000,000 BTC. Drill
Each epoch has 210,000 blocks. The reward starts at 50 BTC and halves every epoch, so the total is
$$210000 \cdot 50 \cdot \sum_{i=0}^{\infty} 2^{-i} = 210000 \cdot 50 \cdot 2 = 21{,}000{,}000.$$The geometric series converges because the halving ratio is $1/2$. The deck states the same computation as $210000 \cdot (50 + 25 + 12.5 + \cdots)$.
An adversary secretly produces 8 blocks at hardness $n = 8$ while the honest chain grows 10 blocks at hardness $n = 5$. Which chain does Bitcoin select, and why does this stop the fake-timestamp attack? Attack
Chain strength is the sum of $2^{n}$ over all blocks. The honest chain has strength $10 \cdot 2^{5} = 320$. The adversary chain has strength $8 \cdot 2^{8} = 2048$. Bitcoin selects the stronger chain, so the honest chain loses despite being longer. The fake-timestamp attack works by making the retarget drop the difficulty on a secret chain. Blocks mined at the lower difficulty contribute little strength, so the attack cannot accumulate enough work to beat the public chain.
In the Unspent Transaction Output (UTXO) lab, Alice selects her 6.00 BTC UTXO, pays Bob 3.00 BTC and sets change to 2.50 BTC. What is the fee? Which check fails if she also selects the already-spent 3.00 BTC output? Drill
Inputs are 6.00 BTC. Outputs are $3.00 + 2.50 = 5.50$ BTC. The fee is the difference, 0.50 BTC. It goes to the miner. If Alice also selects the already-spent 3.00 BTC output, the check that every input is unspent fails. The output was consumed by the earlier transaction $T_6$, so every full node rejects the new transaction, whatever signatures it carries. This is the confirmed-chain half of double-spending protection; the fork race of section 5 is the other half.
List what an adversary with 51% of the hash power can do, and what such an adversary cannot do. Attack
Cannot: steal money from earlier transactions, because that requires forging the owner's ECDSA (Elliptic Curve Digital Signature Algorithm) signature; generate money without effort, because coinbase outputs still require solved proofs of work and valid blocks. Can: fork the chain and double spend the adversary's own recent payments; reject blocks mined by everyone else; exclude chosen transactions from blocks. Censorship and double spending are the real powers of a majority; theft and inflation are outside them.
State the selfish-mining threshold as a function of $\gamma$, evaluate it at $\gamma = 1/2$ and state the proposed protocol fix. Attack
Eyal and Sirer's Markov-chain analysis gives revenue above the honest share whenever
$$\alpha > \frac{1 - \gamma}{3 - 2\gamma},$$where $\alpha$ is the adversary's hash-power fraction and $\gamma$ is the probability that an honest miner mines on the adversary's branch during a tie. At $\gamma = 1/2$ the threshold is $\frac{1/2}{3 - 1} = \frac{1}{4}$. The proposed fix is to choose between equal-length branches uniformly at random, making $\gamma = 1/2$; the system then needs a $3/4$ honest majority of hash power.
In the unidirectional channel, why is the refund timelock 30 days, the first commitment 29 days and a reverse-payment commitment 28 days? What goes wrong if the order is reversed? Project
The 30-day refund is Alice's exit: if Bob disappears, she recovers the whole funding output after 30 days. Commitments must become spendable before the refund, so the first commitment is timelocked at 29 days; Bob must sign and post the latest commitment before day 30, or Alice's refund preempts it. When payments flow back from Bob to Alice, Bob's balance decreases, so an old commitment favors Bob. The new commitment is timelocked at 28 days so that it becomes spendable before the old 29-day one; Alice can post the newer state before Bob can post the stale one. If the order were reversed, the stale state would become spendable first, and Bob could cheat by publishing the old balance instead of the latest one.
These pages are written by a student of the course. The mathematics is stated in the standard way. The formulation is the author's own, taken from no slide. Errors are the author's alone. Prof. Venturi bears no responsibility for them; where this page and the PDFs differ, the PDFs are authoritative and only material in them is examinable.