Bitcoin from zero
No background assumed. The key mechanisms come with experiments you can run in this page, including SHA-256, the genesis header, a Merkle tree, mining, forks, and confirmation risk. In a hurry? The one page summary covers the whole series.
Contents
- 01Who writes the next page
- 02What a hash even is
- 03What a signature cannot do
- 04Inside a block
- 05A fingerprint of fingerprints
- 06Where the effort actually is
- 07A field for free scribbling
- 08The network's clock
- 09Nobody trusts anybody
- 10What a node is, and how one joins
- 11Why history hardens
- 12When two miners win at once
- 13The math behind six confirmations
- 14The dark side of ordering
- 15Do we have to burn electricity
- 16The questions, one by one
01 Who writes the next page
Hashing and mining can wait. Here's the problem they exist to solve. Bitcoin is one ledger: who holds what, who paid whom. Millions of strangers share that ledger. Nobody is in charge of it. So who gets to write the next page?
A bank puts an employee on that job. He writes, and you're forced to trust him. Remove the employee and two traps open immediately. The first is the double spend: I write one page saying I sent you my coin, and at the same moment I write another page sending the same coin to a laptop shop, and I broadcast both. Who decides which one is "real"? The second trap is voting. If you say "let the network vote", I'll spin up a million fake accounts and vote with all of them, because identities on the internet are free. That one has a name, a Sybil attack. The puzzle under it is older. Computer scientists have called it the Byzantine Generals Problem since 1982. Solutions existed, but every one of them assumed the list of participants was known and fixed. A bank.
Bitcoin's answer sits here. The right to write the next page is won in a lottery whose ticket costs real electricity, which nobody can counterfeit. One vote per watt, not one vote per person. That lottery is mining. The rest of this page takes it apart.
A cost worth naming now. This design makes every payment public, readable by anyone, forever. The chains that treat privacy as a requirement rather than an afterthought are covered in Monero under the hood.
02 What a hash even is
People mix this up constantly. a hash is not encryption. Encryption is a lock with a key, whoever holds the key can unlock and recover the message. A hash has no key and no way back at all. It's a machine that takes any input, of any length, and produces a fixed size fingerprint, for SHA-256, always 64 hex characters (256 bits).
The machine's properties carry everything that follows.
Deterministic means the same input produces the same fingerprint every time, on every device, forever. One way means from the fingerprint you cannot recover the input, like a blender: fruit to smoothie is easy, smoothie back to fruit is impossible. Avalanche means change one character of the input and the entire fingerprint flips into something with no relationship to the old one. Not one digit changes. All 64 do.
Right under the title, that first machine is the real SHA-256 running inside your browser.
Scroll back up. Click the first two preset buttons back and forth. One digit of difference in the amount, and the two fingerprints share nothing. Even a period at the end of the sentence flips everything. This property is what will make the "lock" ahead work.
03 What a signature cannot do
This objection sounds like it kills mining. why not have everyone sign their payment with a digital signature and gossip it around the network? A signature proves the money is theirs.
That proposal is already 90% of Bitcoin. Every Bitcoin transaction carries a digital signature proving the owner authorized it. Everyone does broadcast. The network does gossip. Verifying a signature is nearly free. A Raspberry Pi does it. Mining doesn't exist to verify transactions at all. It exists for the one thing a signature is helpless against.
I own coin #42. I sign a payment of it to Alice, and in the same second I sign a second payment of the same coin to a laptop shop. Both signatures are 100% valid: I really am the owner, and both prove exactly that, exactly as the proposal demands. Half the network receives Alice's version first. The other half receives the shop's version first, because messages travel at different speeds. Now "the network talks it out". Talks out what? Which was "first"? There is no universal clock on the internet, and the timestamp is written by me, so I'll lie in it freely. Deeper hole. "The money is his" is not a property of a transaction. It's a consequence of ordering history. After my double spend, do I still own the coin? The answer depends on which payment "happened first", so the proposal assumes the very thing it's trying to build.
The lab below generates a real P-256 ECDSA keypair in your browser and signs two conflicting messages. Bitcoin uses secp256k1 rather than P-256, but the experiment isolates the same point: valid authorization does not choose between two conflicting spends.
04 Inside a block
A block is a "page" of the ledger, a bag holding thousands of payments that were waiting in a queue called the mempool. The miner gathers them and adds, at the top, a special transaction called the coinbase, paying himself the reward. So couldn't he just write himself any amount?
No. The protocol rulebook, which every device on the network runs a copy of, caps the coinbase at the current subsidy (3.125 BTC, halving roughly every four years) plus the fees of the transactions he included. One satoshi over the cap and the whole block is invalid. Nobody has to get upset. Every device will drop the block automatically, as section 9 shows.
The bag itself is not what goes into the fingerprint machine. The thing that gets ground trillions of times is a small summary card called the block header, exactly 80 bytes, smaller than an SMS. Six things are written on it.
| Field | Size | What it means |
|---|---|---|
version | 4 bytes | Which ruleset the block follows |
prev block hash | 32 bytes | The fingerprint of the previous block's card. That's what makes the "chain" |
merkle root | 32 bytes | One fingerprint summarizing every transaction (next section) |
timestamp | 4 bytes | Seconds since January 1, 1970 (section 8) |
bits | 4 bytes | The required difficulty. The fingerprint must land below this target |
nonce | 4 bytes | The counter that changes every attempt (section 7) |
Below are the actual 80 bytes, verbatim, of the first block in history, the one Satoshi mined on January 3, 2009. Click the button and your browser will run SHA-256 over them twice (exactly as Bitcoin does) and produce the fingerprint that has sat in the chain for seventeen years.
05 A fingerprint of fingerprints
How can 32 bytes on the card represent thousands of transactions? You fingerprint fingerprints. Hash each transaction alone, then take each pair of hashes side by side and hash them into one. Repeat layer after layer until a single hash remains at the top, the Merkle root.
The machine grinds 80 bytes per attempt, not megabytes of transactions. That's the speed. The lock is separate. Any edit to any transaction below climbs the tree. The transaction's hash changes, the pair's hash follows, the root moves with them, and the card is now a different card. Any winning hash the miner found on the old card is worthless. Edit and watch.
06 Where the effort actually is
The sharpest question in the whole conversation is this. If a fingerprint is free, and the content is known, where is the effort in any of this?
Computing the fingerprint isn't the work. The demand runs backwards. The assignment isn't "hash this card". It's "bring me a version of the card whose fingerprint starts with this many zeros" (technically: lands below a number called the target, leading zeros are what that looks like). Section 2 already named the machine's properties: one way and chaotic. There's no formula saying "to get zeros, set these bits". The machine doesn't take requests. There isn't even a "getting warmer". A fingerprint with 4 zeros teaches you nothing about reaching 5. Every attempt is a fresh lottery draw.
Only move in the universe: change the counter, try, change, try. One attempt is free, the winning attempt is astronomically rare. The effort is the number of attempts, not the difficulty of any one of them. Loop's below.
Hit the same zero count a few times and the attempt count swings wildly. Sometimes an early lucky strike. Sometimes a long dry spell. Pure lottery. In this toy rule, each extra hex zero multiplies the expected work by 16. Bitcoin uses a numeric target rather than a fixed count of visible zeros, and that target adjusts every 2,016 blocks to keep the long run average near ten minutes.
07 A field for free scribbling
If you come from security, the name misleads you. Borrowed from your world, different job. In the protocols you know, a nonce prevents replay. In Bitcoin it's an empty field with no meaning at all. Four bytes at the end of the card holding a number that represents nothing.
Why does it exist? The miner must change the card's content between attempts because the hash is deterministic. The nonce is the fastest field to vary. Miners can also change the timestamp, version bits, transaction selection, or an extraNonce inside the coinbase, which changes the Merkle root. Trying nonce = 500 twice on the same header wastes work because it produces the same hash.
4 bytes means only 4,294,967,296 values. A modern mining rig performs hundreds of trillions of attempts per second, so it exhausts the entire nonce space in a fraction of a second, usually with no winner. Then what? Change something else to produce a fresh card with a clean nonce space. Bump the timestamp by a second, or, the standard move, twiddle a number inside a free slot in the coinbase transaction itself, called the extraNonce. Section 5's tree still applies: any change to the coinbase climbs up and changes the root, so the card is a new card, with 4.3 billion fresh tickets attached.
08 The network's clock
The timestamp is a number saying "this card was built at this moment", stored as seconds since January 1, 1970. In the genesis experiment above, the yellow field decodes to January 3, 2009, 18:15 UTC.
It exists because the network needs a clock to calibrate difficulty against. The protocol wants a block every ten minutes on average. Hardware improves, miners multiply, how would it know blocks started arriving faster? From the stamps. Every 2,016 blocks (about two weeks), it computes the actual elapsed time from the stamp differences. Less than two weeks? Difficulty rises. More? It falls. Without a stamp inside each block, there's no agreed time reference at all.
The miner writes this stamp himself. Why trust it? Don't. The rules fence it from both sides: it must be greater than the median of the last 11 blocks, and less than the verifying node's clock plus two hours. Approximate clock, not a precise one. You can find a block whose stamp is a minute older than the block before it, and that's accepted. Manipulation large enough to distort the difficulty calculation is fenced out.
09 Nobody trusts anybody
Back to the very first question of the conversation: fine, the winner writes the page, why would anyone believe him? Answer: nobody believes anybody, and nobody needs to. When a miner announces his block, every device (node) on the network takes a copy and re checks everything itself, locally, without asking anyone:
Is the card's fingerprint really below the target? (One fingerprint, under a second, exactly what you did with the genesis block above.) Does every transaction carry a valid digital signature from the money's owner? Was no coin spent twice? Is the coinbase within the cap (3.125 + fees)? Is the timestamp within bounds? Are the size and format right?
One broken rule, and the node drops the block and relays it to no one, no reporting, no negotiating, just dropped. And the miner has burned months of electricity for nothing. So cheating isn't "forbidden", cheating is economically losing: the most expensive way in existence to set your own money on fire.
That also answers the empty block question: can a miner publish a block with no transactions at all? Yes, and the rules accept it. It actually happens, in the seconds after a new block arrives, when miners start work on the new tip before assembling a template with transactions. The only loser is the miner himself: he left the transaction fees, the tips, on the table, and the waiting payments confirm in the next block.
10 What a node is, and how one joins
The last section kept saying "every device re checks", time to name the device. Bitcoin is not a service with servers; it's a program. The reference one is Bitcoin Core (open source, the direct descendant of the code Satoshi shipped in January 2009), and it runs fine on an ordinary laptop. Worth separating three roles people constantly blur: a full node runs the program and enforces every rule, it needs no permission, no stake, and no mining hardware; a miner plays the lottery of section 6 and proposes blocks (and typically runs a node too); a wallet just holds keys and signs. Light wallets on phones skip validation and ask someone else's node, convenient, but that's borrowed trust. Tens of thousands of reachable full nodes run today, and nothing stops yours from being one of them tonight.
So how does a machine that has never heard of the network become one of its enforcers? It ships knowing exactly one block: genesis, hardcoded into the source, the same 80 bytes you hashed in section 4. Everything else it earns. First it needs peers: it queries a handful of DNS seeds, volunteer run hostnames baked into the code that answer with IP addresses of reachable nodes (with a compiled in fallback list if DNS fails), opens about ten outbound connections on port 8333, and thereafter learns of more peers through addr gossip, the network's own address book. Each connection starts with a two message handshake, version, answered by verack, where the peers state their protocol version and how tall their chain is.
Then comes the elegant part, and it reuses the hero of this whole page. The node does headers first sync: before touching any transaction, it asks peers for headers only, the 80-byte cards. From those headers it verifies proof of work and computes which candidate chain carries the most accumulated work. Then Initial Block Download fetches full blocks and validates their consensus rules locally. Pruned mode can discard old block files after validation, and the documented assume valid optimization can skip old script checks while preserving the other consensus checks.
Once caught up, the node lives at the tip: peers announce new items with inv messages, it fetches transactions into its mempool and blocks into its chain, relays what passes validation, and drops what doesn't, the fan out drawing in section 9, running forever. Notice this is also the concrete answer to the "everyone announces and the network talks it out" proposal from section 3: the network really does talk, in exactly these messages, and the reason the talking works is that every listener independently recomputes everything, starting from nothing but genesis.
11 Why history hardens
Every block grips the one before it by its hash. That is the "chain" in blockchain. Change a payment in an old block and its Merkle root changes, which changes the header hash. The prev field of the next block no longer matches. Rewriting from there requires rebuilding the proof of work while the honest chain continues growing. The required work grows with the depth of the edit and the competing hash power.
The miniature chain below uses 3 zeros so your device can mine it in seconds. Green means the hash meets the toy target and its prev field matches. Change any character in block 1, then re mine the blocks in order. You will redo every block after the edit.
12 When two miners win at once
The lottery pays out roughly every ten minutes. Block propagation takes seconds. Collisions are rare, under 1% of blocks, but they happen: two miners find two different valid solutions to the same round within moments of each other. (Never the same hash. Each miner's coinbase pays his own address, so his merkle root differs, so his card differs, so his hash differs. Two winning tickets, one round.) That's a fork.
This runs opposite to intuition. the system doesn't know which block is better, and doesn't try. There's no jury and no quality score. Both are equally legal. Each node keeps whichever arrived first and sets the other aside, so the world temporarily splits into two camps, each camp's miners digging on their own tip. Resolution comes from the next lottery draw. The moment anyone finds the next block, necessarily built on one of the two, that branch now carries more accumulated work, and the losing camp's miners jump over instantly. They're not being sportsmanlike. Digging on a losing branch burns electricity toward a reward that will never be spendable. The losing block is called stale. Its miner forfeits the reward (which is why miners compete ferociously on propagation speed). Its transactions, mostly already present in the winning block anyway, return to the mempool and ride the next one.
If the tie repeats, both camps finding their next block simultaneously again? Then the tie continues, and nothing breaks. Bitcoin doesn't need instant resolution. It tolerates temporary ambiguity and promises eventual convergence. The lottery is memoryless, so the collision probability multiplies itself each round, 1%, then one in ten thousand, then one in a million. A tie surviving three rounds is practically unheard of. The intuition of "longest chain" is slightly off. The rule is the chain with the most accumulated work (the heaviest, by summed difficulty), identical to longest when difficulty is constant, different when it isn't.
Each click is one lottery draw across the whole planet. The slider sets how the hash power is split between the camps:
13 The math behind six confirmations
Truth in Bitcoin isn't a moment. It hardens by accumulation. A payment in the very latest block is still "soft": if its branch loses a race, it can vanish back into the mempool. Every block built on top of yours makes reversing it exponentially harder, which is why the convention for large amounts is to wait 6 confirmations, about an hour.
Satoshi did the math in section 11 of the whitepaper. An attacker who secretly mines a rival branch (to reverse his own payment) is running a race where each block is a coin flip weighted by his share of hash power. The probability he ever catches up from z blocks behind follows a closed formula, a Poisson weighted gambler's ruin, and it collapses fast. The calculator below implements that exact formula. At 10% attacker hash power and 6 confirmations it prints 0.0002428, 0.02%, the very number in the whitepaper's table. Your browser is re deriving the paper.
14 The dark side of ordering
Strongest objection against everything above, and the one an offensive security brain hits first. The block writer holds ordering power. Can't he skim only the high fee transactions? Worse, he sees a fat trade in the mempool. Can he slot his own transaction in front of it?
Those are not the same complaint. High fee picking is intended. Reordering for profit is the live hole. Mining gets blamed for a chain that isn't even mining. picking high fee transactions is not a bug, it's the design. Block space is scarce (a few thousand transactions per block regardless of demand), and fees are the auction for it. Nobody promised FIFO. The writer doesn't ask who you are or what your government thinks. Only what you paid.
The real problem begins when money can be made from the ordering itself, past the fees. I see a large buy about to move a token's price, so I place my buy before it and my sell after it (a sandwich). I see a hot mint and shove myself to the front. Neutrality dies there. The writer became player and referee in the same block. This is MEV, Maximal Extractable Value. Real money. Billions extracted to date.
The correction makes the objection heavier, not lighter. The chain where this is most visible, Solana, doesn't mine at all. Proof of stake, leader schedule known in advance. Frontrunning there is not evidence against mining. The sharper irony: Bitcoin, the original mining network, has the least MEV of any major chain. Not saintly miners. Bitcoin transactions are plain transfers whose outcome doesn't depend on what executed before them. There's nothing to sandwich. MEV is born from two ingredients together: ordering power plus a live financial market on chain (DEXes, prices that move per transaction). Ethereum and Solana have the second in abundance. Bitcoin doesn't. The right defendant isn't the writer selection mechanism. It's embedding trading into a layer that has a single ordering writer.
Your turn as block builder. This simplified constant product pool uses x·y=k without trading fees or execution uncertainty. A victim's 10 SOL buy sits in the queue. Order it fairly, or sandwich it:
Call the mechanism "bad" after you've looked at the other shop. Frontrunning in traditional finance predates blockchains by decades. HFT firms spent fortunes on straighter cables to beat orders by microseconds (read Flash Boys). Brokers sell order flow. You see none of it. On chain, for the first time, ordering power became visible and measurable, and a whole field grew to fence it. Ethereum separated block building from proposing (PBS / MEV Boost) and researches encrypted mempools where the writer orders transactions he cannot read. On Solana, Jito shut down its public mempool in 2024 specifically to break sandwiching, and the Solana Foundation removed validators caught sandwiching from its stake delegation program. Application layer next. Slippage limits and batch auctions (CoW Swap) erase ordering advantage by settling a whole batch at one price.
15 Do we have to burn electricity
Honest objection, then. Fine, it works. It burns electricity "for nothing". Couldn't everyone just announce, sign, gossip, done? Section 3 showed why announcing and signing alone collapses at the first double spend and the first million fake identities: some scarce resource must weight the votes. The electricity isn't burned to compute anything useful. It's burned to make lying more expensive than honesty. Like a bank vault's door. The thick steel does no useful work. Its entire job is being expensive to get through.
Your instinct that this is overpriced was shared by half the industry. They built the alternative: Proof of Stake. Ethereum switched to it entirely in September 2022, cutting its energy use by roughly 99.95%. Instead of the lottery ticket being burned electricity, the ticket is locked money. You deposit 32 ETH as collateral, get randomly selected to write blocks, and if you're caught cheating, signing two conflicting versions, say, the protocol burns your deposit (slashing). The "burn" moved from electricity paid upfront to capital held hostage. Solana, the chain from section 14, is from this family. Even PoS is not "everyone just announces". There's still a selected writer and consensus rounds. They changed the ticket's price, because the ordering problem itself never disappears under any technology.
The switch isn't free either. The trade offs cut in directions you've already complained about. In PoS the voting resource is the coin itself. The system derives its security from the thing it secures. Whoever holds more earns more and concentrates further. Amassing a large stake happens quietly with a buy order. Building mining farms shows up on satellite imagery and takes years, steel, and power contracts. And there's a subtle technical cost called weak subjectivity. A brand new device on PoW can verify the entire chain from genesis by pure computation, the work is carved into the fingerprints, as you saw yourself. On PoS, a device that was offline for a year needs a recent checkpoint from a source it trusts, because old signing keys can be reused for free to construct an alternate history (the deposit that once threatened them was withdrawn long ago). Straight: PoW pays a continuous power bill so its security is external and physical; PoS saves the power at the cost of security that is internal and circular.
16 The questions, one by one
This page started as a real conversation. Questions in the order they were asked, each answered in two lines with a pointer to its section.
Couldn't the miner include no transactions at all, and people would just accept it?
An empty block (coinbase only) is legal. The network accepts it. That miner forfeited the transaction fees, so he only hurt himself. "People accepting it" isn't a thing. Every device re checks every rule itself (section 9).
Why can't he just write himself whatever amount he wants?
He can write it. Every device on the network will drop the block in under a second because the coinbase exceeds the cap (3.125 + fees). He's wasted the entire lottery's electricity (sections 4 and 9).
What is mining even for?
The guesses carry no application meaning. Proof of work makes proposing blocks costly and weights the race by performed work rather than cheap identities. Mining can still concentrate in pools, so "unmonopolizable" would be too strong. The reward pays miners to supply that work.
If the input is known, where's the effort in hashing it?
One fingerprint really is free. The expensive bit is the inverted demand: find a version of the card whose fingerprint has the zeros. The machine is one way and chaotic, so there's no path but trial, and winning is astronomically rare. Effort = number of attempts, not the cost of one (section 6; run the pocket mine).
What exactly gets hashed?
The block header card. 80 bytes holding the previous block's hash, one summarizing hash of all transactions (the Merkle root), the timestamp, the difficulty, and the nonce. Transactions get summarized once into the root. The little card is what gets ground (sections 4 and 5, you ran Satoshi's actual 80 bytes yourself).
What is the timestamp for?
It gives the network a shared clock to recalibrate difficulty against every 2,016 blocks, keeping blocks near ten minutes. It isn't trusted blindly. It's fenced between the median of the last 11 blocks and the verifier's clock plus two hours (section 8).
Isn't a nonce a 'number used once'?
The name is borrowed. The job is different. Not an anti replay device, a 4-byte free scribble field the miner twiddles to change the card between attempts. "Once" survives only as this: repeating a value on the same card wastes electricity, since the machine is deterministic. When the counter runs out, the extraNonce inside the coinbase refreshes the space by changing the root (section 7).
But the writer can cherry pick high fees and frontrun, like on Solana. Doesn't that make mining a bad solution?
Fee picking is the intended auction for scarce block space. Profiting from the ordering itself is real, that's MEV. Solana doesn't mine (it's proof of stake with a known leader schedule). Bitcoin, the mining chain, has the least MEV because plain transfers offer nothing to sandwich. The culprit is on chain trading under a single orderer, not the writer selection mechanism (section 14; run the sandwich lab).
Why not just have everyone sign and announce, and the network talks it out? Why burn electricity?
A signature answers "who", never "which first". I can validly sign two conflicting payments of the same coin (section 3 proves it with real signatures in your browser). Ordering needs votes. Votes need weighting by something unfakeable. Identities are free. The electricity is the unfakeable thing (sections 1 and 15).
So the real problem behind double spending is latency, time itself?
Yes. There's no shared "now" on a distributed planet, so "which came first" has no objective answer at millisecond scale. The blockchain answers a weaker but sufficient question, "which entered the ledger first", settling races in a new time unit: the block (sections 3 and 8).
But isn't the ordering done by the timestamp?
No. Stamps can be out of order between consecutive blocks and still be valid. Ordering comes from each block carrying its parent's hash and from accumulated proof of work. Timestamps help enforce time bounds, difficulty adjustment, and time based consensus rules. They do not decide block order.
Can two miners really win at the same moment? And how does the system pick the better block, what if both branches are the same length?
Yes (different blocks, never the same hash, each coinbase differs, so each header differs). The system doesn't pick. Both are equally legal, the world splits briefly, and the next lottery draw breaks the tie via the most accumulated work rule. Equal length ties simply persist and decay geometrically. Memoryless lottery, so a repeated collision multiplies its own improbability each round (section 12; run the fork race). This soft window is exactly why large payments wait 6 confirmations (section 13).
What actually runs all of this, and how does a brand new machine join the network?
A program, not a service: Bitcoin Core, runnable on a laptop. A fresh node knows only the hardcoded genesis block. It finds peers through DNS seeds, handshakes with version/verack, pulls the 80-byte headers first to verify the proof of work skeleton, then downloads and re validates every block since 2009 itself. After that it's a full enforcer of section 9's rules, trusting nothing it didn't recompute (section 10).
The SHA-256 lab uses the browser's real implementation, and the genesis lab hashes Bitcoin's recorded 80-byte genesis header. The signature lab uses browser supported P-256 ECDSA to demonstrate conflicting authorization; Bitcoin signatures use secp256k1. The attacker calculator implements the formula from section 11 of the whitepaper. The current subsidy is 3.125 BTC, and difficulty retargets every 2,016 blocks.