Sub topic 3
How Networks Agree: Proof of Work and Proof of Stake
Prerequisites and scope
This chapter assumes you know what a blockchain ledger is (blocks of transactions linked by hashes). It also assumes you know what a hash function and a public/private key pair do at a high level, and that you can read short Python snippets. It covers how a network of strangers agrees on one history of transactions. It does not cover Bitcoin's transaction format or Ethereum's account model. Later chapters cover those.
The problem consensus solves
A blockchain has no central operator. Thousands of nodes (computers running the protocol) each hold a copy of the ledger. Any user can send a transaction to any node. Two problems follow:
- Double spending. Someone signs two conflicting transactions that spend the same coins and sends them to different parts of the network.
- Ordering. Nodes must agree which transaction came first. Otherwise their ledgers diverge.
A consensus mechanism is the rule set that lets nodes agree on one ordered history without trusting each other. It must answer two questions:
- Who gets to propose the next block?
- What makes it costly to cheat?
Proof of work (PoW) and proof of stake (PoS) answer both questions differently. Both make attacks expensive, but they charge the attacker in different currencies.
Sybil resistance: why identity cannot decide
If one vote per node or per IP address decided who proposes blocks, an attacker could create millions of fake identities. This is called a Sybil attack. Both mechanisms tie influence to a scarce resource instead of to identity.
| Mechanism | Scarce resource | What an attacker must acquire |
|---|---|---|
| Proof of work | Computation (hash power, electricity, hardware) | Most of the network's hash rate |
| Proof of stake | Locked capital (staked coins) | A large share of the staked coins |
Proof of work
Bitcoin uses proof of work. A miner collects pending transactions into a candidate block. The miner then searches for a number called a nonce so that the hash of the block header is below a target. Finding such a nonce takes many guesses on average. Checking a claimed solution takes one hash.
The following program shows the idea with a toy difficulty. It requires the SHA-256 hash to start with a number of zero hex digits. Real Bitcoin hashes the 80-byte block header twice with SHA-256 and compares the result to a 256-bit target, but the search logic is the same.
import hashlib
def mine(data, zeros):
prefix = "0" * zeros
nonce = 0
while True:
digest = hashlib.sha256(f"{data}{nonce}".encode()).hexdigest()
if digest.startswith(prefix):
return nonce, digest
nonce += 1
def verify(data, nonce, zeros):
digest = hashlib.sha256(f"{data}{nonce}".encode()).hexdigest()
return digest.startswith("0" * zeros)
nonce, digest = mine("block 1: alice pays bob 1", 4)
print(nonce, digest)
print(verify("block 1: alice pays bob 1", nonce, 4))
print(verify("block 1: alice pays bob 100", nonce, 4))Each extra zero hex digit multiplies the expected work by 16. Verification stays a single hash. This asymmetry is the core of PoW: solutions are expensive to find and cheap to check. The last line prints False in almost every run, because changing the data changes the hash. A tampered block would need to be mined again.
Difficulty adjustment
Bitcoin aims for one block roughly every 10 minutes. Total hash rate changes over time, so the protocol retargets difficulty every 2,016 blocks (about two weeks). If the last 2,016 blocks arrived faster than expected, the target is lowered and mining gets harder. If they arrived slower, it gets easier. Bitcoin clamps each adjustment to a factor of 4 up or down.
The longest-chain rule
Two miners can find valid blocks at nearly the same moment. The network then briefly has two competing tips. Nodes follow the chain with the most accumulated work (commonly called the "longest chain"). When the next block extends one tip, the other becomes an orphaned or stale block, and its transactions return to the pending pool.
Because forks happen, a transaction in the newest block is not final. Each new block built on top is a confirmation, and the chance of reversal drops quickly as confirmations grow. This is probabilistic finality. Exchanges often wait several confirmations, and Bitcoin users commonly cite 6 as a conventional figure for larger payments.
Cost of attack under PoW
To rewrite history, an attacker must out-mine the honest network from some earlier block. That requires controlling a majority of hash rate (a 51% attack), which means buying or renting hardware and paying for electricity. A successful attacker can reorder recent blocks and double spend. The attacker cannot forge signatures, so they cannot spend other people's coins. The cost is ongoing and external: hardware and power are real-world expenses, and the hardware can be reused honestly.
Proof of stake
In proof of stake, participants called validators lock up coins as a stake. The protocol chooses validators to propose and vote on blocks, with selection weighted by stake. Ethereum switched from PoW to PoS at the Merge in September 2022. Its design today works like this:
- A validator deposits 32 ETH to activate.
- Time is divided into 12-second slots. Each slot has one randomly chosen proposer. A committee of validators attests (votes) to the block.
- 32 slots form an epoch. Validators vote to justify and then finalize checkpoints at epoch boundaries.
- Honest behavior earns rewards in the form of newly issued ETH. Failing to participate costs small penalties.
The following sketch shows stake-weighted selection. It uses a fixed random seed so the result is reproducible. Real protocols derive randomness from the chain itself, not from a local seed.
import random
stakes = {"alice": 32, "bob": 64, "carol": 96}
def pick_proposer(stakes, rng):
names = list(stakes)
weights = [stakes[n] for n in names]
return rng.choices(names, weights=weights, k=1)[0]
rng = random.Random(7)
counts = {n: 0 for n in stakes}
for _ in range(10_000):
counts[pick_proposer(stakes, rng)] += 1
print(counts)Over many slots, each validator proposes in proportion to its stake. Carol holds half the stake, so she proposes about half of the blocks. Note that in practice Ethereum treats each 32 ETH as a separate validator, so a large holder runs many validators.
Slashing and economic finality
PoS adds a penalty that PoW lacks. Slashing destroys part of a validator's stake if the validator provably breaks a safety rule, for example by signing two conflicting blocks for the same slot. Because the stake is inside the protocol, the protocol can punish an attacker directly. In PoW, the protocol cannot confiscate an attacker's hardware.
Ethereum also reaches economic finality. Once a checkpoint is finalized, reverting it would require at least one third of the total stake to be slashed. That makes a reversal a quantifiable cost, not only a probability.
Cost of attack under PoS
Attackers need a large amount of the staked coin. Roughly, controlling over one third of stake can stall finality, and over two thirds can finalize conflicting history. An attacker who tries this risks slashing and a sharp drop in the coin's price, which hurts their own holdings. The community can also coordinate a social recovery, for example by forking away the attacker's stake. This option is a social decision, not a guarantee the protocol enforces.
Comparing the two
| Property | Proof of work (Bitcoin) | Proof of stake (Ethereum) |
|---|---|---|
| Resource at risk | Hardware and electricity spent | Staked coins |
| Block proposer | First miner to find a valid nonce | Randomly chosen, stake-weighted validator |
| Finality | Probabilistic | Probabilistic plus explicit finalization |
| Direct penalty for attack | None from protocol | Slashing |
| Energy use | High, by design | Much lower |
| Barrier to entry | Specialized hardware, cheap power | Capital (32 ETH for a solo validator) |
| Main centralization pressure | Mining pools, hardware makers, cheap-power regions | Staking pools and liquid staking services |
Edge cases and common errors
- "PoW is wasteful, so it's broken." The energy spent is the security budget. Whether the cost is acceptable is a value judgment. Whether it secures the chain is a technical fact.
- "PoS means the rich control everything." Wealth does affect influence, but PoW is also tilted toward those who can afford hardware and cheap power. Compare the actual concentration of pools and staking providers for each network.
- "51% means the attacker can steal any coins." No. An attacker with majority power can reorder recent transactions, double spend their own coins, and censor. They cannot sign for other people's keys or change protocol rules that nodes enforce.
- "Hash rate is a vote on rules." Miners and validators order transactions. Full nodes enforce the rules and reject invalid blocks, no matter how much work or stake backs them.
- Treating one confirmation as final. On PoW chains, short reorganizations of one or two blocks happen. Wait for confirmations that match the payment's value.
- The "nothing at stake" worry. Early PoS designs worried that validators could vote on every fork at no cost. Slashing for conflicting votes addresses this in Ethereum's design.
- Long-range attacks. An attacker with old keys could build an alternative history from far back. PoS clients defend against this with weak subjectivity: a new node must start from a recent trusted checkpoint, not only from the genesis block. This is a real trust assumption that PoW does not need, since a new Bitcoin node can verify the most-work chain from genesis alone.
Exercises
Exercise
In the toy mine function, you raise the required zeros from 4 to 6. About how much more work do you expect on average, and does verification get slower?
Show answer
Each extra hex zero multiplies the expected work by 16, so two more zeros means about 16 × 16 = 256 times more guesses. Verification still needs one hash, so it stays equally fast.
Exercise
A PoS chain has validators with 10, 20, and 70 units of stake. Over 1,000 slots with stake-weighted random selection, about how many blocks does each validator propose?
Show answer
About 100, 200, and 700 blocks. Selection probability equals each validator's share of the total stake (10%, 20%, 70%). Real counts vary around these numbers by chance.
Exercise
An attacker controls 55% of a PoW network's hash rate. Name one thing they can do and one thing they cannot do.
Show answer
They can double spend their own recent transactions by privately mining a longer chain, or censor transactions. They cannot spend other people's coins, because they cannot create valid signatures without the private keys, and full nodes will reject blocks that break protocol rules.