Appendices Appendix E

Mining a Block โ€” From Mempool to Chain

Proof-of-work is essentially one-CPU-one-vote.โ€”Satoshi Nakamoto, Bitcoin whitepaper (2008)

Chapter 14 dissected a coinbase transaction. This appendix zooms out to the full process: what the miner does before the ASIC starts grinding, what the ASIC actually does, and what happens the instant a valid nonce is found. The interactive grinder in ยงE.6.1 runs a real Bitcoin-style block-header search in your browser โ€” at a toy difficulty, because the real network hashes on the order of 1015โ€“1016 times faster than a laptop.

E.1The Mining Pipeline

Producing a valid Bitcoin block is an eight-stage pipeline. The ASIC's role โ€” the part everyone thinks of as "mining" โ€” is a single step. Everything else is book-keeping that the pool's software, not the hash hardware, performs.

#StageWhoOutput
1Build block templatePool softwareTransaction list, fees, weight
2Construct the coinbasePool softwarescriptSig, reward outputs, witness commitment
3Compute Merkle rootsPool softwaretxid Merkle root (for header)
4Assemble 80-byte headerPool softwareHeader with nonce = 0
5Nonce searchASICNonce with H < target
6Broadcast blockPool nodeinv/block messages to peers
7Validate blockEvery full nodeAccept or reject
8Chain extendsNetwork consensusBlock becomes tip, +100 โ†’ matured coinbase
The Coinbase Exists Before the Block Is Found

A common misconception is that the coinbase is created after the hash is found. The opposite is true: the coinbase must exist before the ASIC begins hashing, because changing the coinbase changes the Merkle root, which changes the 80-byte header, which is what the ASIC is hashing. The ASIC iterates only the 4-byte nonce field; everything else is fixed at the moment the search starts.

E.2Step 1 โ€” Build the Block Template

The miner's software polls the local mempool for unconfirmed transactions and constructs a candidate block subject to two consensus limits:

Within those limits, miners maximize fee revenue. The standard algorithm is greedy by fee-per-weight: sort candidate transactions by fee รท weight, descending, and pack them in. Bitcoin Core's implementation uses a more refined algorithm that accounts for ancestor package feerate โ€” a child transaction paying a large fee can "pull in" a low-fee parent, so the effective feerate of the package is what matters (this is how CPFP fee-bumping works; see Chapter 17).

The coinbase transaction sits at index 0 of the block's transaction list. Every other transaction is ordered by the miner's choosing โ€” the consensus rules impose no order beyond "coinbase first."

E.3Step 2 โ€” Construct the Coinbase Transaction

With fees computed, the miner builds the coinbase. Chapter 14 described every field; this section frames the sequence from a constructor's point of view.

E.3.1Input: the Null Reference

One input, fixed structure:

The scriptSig contains three logical segments:

<BIP 34 height>
block height,
mandatory since block 227,931
<pool tag>
optional ASCII branding,
merge-mining commitments
<extranonce>
4โ€“8 additional bytes
the pool rolls when the
header nonce is exhausted

E.3.2Outputs: Reward and Commitment

A modern coinbase has at least two outputs:

  1. Reward output(s). Value = subsidy + \(\sum\) fees. The subsidy at a given height is \(50 \cdot 10^8 \cdot 2^{-\lfloor h/210{,}000\rfloor}\) sats. If the outputs in aggregate exceed this cap, the block is invalid. Paid to whatever scriptPubKey the pool designates โ€” typically a pool-controlled P2WPKH or P2PKH address; pools then pay miners from accumulated pool balances via normal transactions.
  2. Witness commitment output. OP_RETURN carrying the 36-byte payload aa21a9ed || <commitment-hash>. Required by BIP 141 whenever any transaction in the block has a witness. The commitment-hash is computed in the next sub-step.

Optional additional outputs may carry sidechain commitments (RSK, Namecoin, Elements), sponsor OP_RETURNs, or dust outputs the pool uses for internal accounting. None of these are consensus-required; they are pool-chosen conventions.

E.3.3The Witness Commitment โ€” A Commitment Inside a Commitment

The witness commitment is what binds SegWit witness data to the block header, whose Merkle root only covers txids (not wtxids). It is computed in two nested steps.

Inner step: the witness Merkle root. Build a Merkle tree of the block's wtxids, but with one twist โ€” the coinbase's wtxid is replaced with 32 zero bytes. This is because the coinbase's wtxid depends on the commitment that is itself the output of this step, creating a circular dependency. Replacing it with zeros breaks the cycle.

\[ \text{witness\_root} = \text{Merkle}\bigl(\underbrace{00\ldots00}_{32\text{ bytes}},\ \text{wtxid}_1,\ \text{wtxid}_2,\ \ldots,\ \text{wtxid}_n\bigr) \]

Outer step: the commitment hash. Concatenate the witness root with a 32-byte coinbase witness nonce (which lives in the coinbase's single witness stack item, typically all zeros), then double-SHA-256:

\[ \text{commitment} = \text{SHA256d}\bigl(\text{witness\_root}\ \Vert\ \text{coinbase\_witness\_nonce}\bigr) \]

That 32-byte commitment is prefixed with aa21a9ed and dropped into the coinbase's OP_RETURN output. Only now is the coinbase's byte content final โ€” and only now can its txid be computed.

E.4Step 3 โ€” Compute the Block's Merkle Root

The 32-byte merkle_root field of the block header is the root of a binary hash tree over all the block's txids. Leaves are txids (not wtxids); the coinbase is at index 0.

Bitcoin's Merkle tree has one unusual rule: when a level has an odd number of nodes, the last one is duplicated to pair with itself. This design choice has a known vulnerability (CVE-2012-2459) that sophisticated validators must account for โ€” two different transaction lists can collide to the same root in specific odd-count cases โ€” but the consensus rules require this exact algorithm.

Each internal node is the double-SHA-256 of its two children concatenated:

\[ \text{parent} = \text{SHA256d}(\text{left}\ \Vert\ \text{right}) \]

For a block with four transactions \(T_0, T_1, T_2, T_3\):

\[ \text{merkle\_root} = \text{SHA256d}\bigl(\,\text{SHA256d}(t_0 \Vert t_1)\ \Vert\ \text{SHA256d}(t_2 \Vert t_3)\,\bigr) \]

where each \(t_i\) is the txid of \(T_i\) in its raw 32-byte internal byte order (not the reversed display form you see on block explorers).

Every field in the header is little-endian. Total size: exactly 80 bytes.

OffsetSizeFieldMeaning
04 BversionBlock version; BIP 9 signaling bits
432 Bprev_blockSHA256d of the previous block's header (internal byte order)
3632 Bmerkle_rootRoot from ยงE.4
684 BtimestampUnix epoch seconds; must be > median of previous 11 blocks and โ‰ค network-adjusted time + 2 h
724 BbitsCompact-encoded target (difficulty)
764 BnonceThe 32-bit search variable

The target is recovered from bits as a 256-bit unsigned integer. A block is valid if SHA256d(header) < target, where the 32-byte hash is interpreted as a uint256 in the same byte order as the target (which is the reverse of how hashes appear on explorers โ€” explorers display the byte-reversed form, so "lots of leading zeros" in display = "the uint256 is small").

E.6Step 5 โ€” The Nonce Search

With the 80-byte header fully assembled, the ASIC begins iterating the 4-byte nonce field, hashing each variation and comparing to the target. A modern ASIC (e.g., Antminer S21) performs on the order of \(2 \times 10^{14}\) double-SHA-256 operations per second. The whole 32-bit nonce space (\(2^{32} \approx 4.3\) billion) is exhausted in ~21 microseconds at this rate.

When the nonce space is exhausted without finding a valid hash, the pool software rolls the extranonce โ€” increments the extranonce bytes in the coinbase scriptSig, which changes the coinbase's txid, which changes the Merkle root, which yields a fresh 80-byte header. The ASIC then re-scans the full 32-bit nonce space. The timestamp field may also be incremented by one second as wall-clock time advances; Bitcoin accepts any timestamp within the network's time window, providing another small amount of grinding entropy.

E.6.1Interactive: Grind a Toy Nonce

Below is a constructed 80-byte teaching header โ€” realistic field layout, synthetic prev-block and Merkle-root values โ€” with all fields fixed except the nonce. Set a toy difficulty (number of leading zero bits the resulting hash must have when read in Bitcoin-display order) and click Grind. Your browser will iterate the 4-byte nonce, computing double-SHA-256 over the 80-byte header for each value, and stop the moment it finds a hash that meets the target.

Scale Reality Check

The Bitcoin network currently produces around \(6 \times 10^{20}\) double-SHA-256 hashes per second. Your browser will manage \(10^5\) โ€” about \(10^{-15}\) of the network. At the real ~80-bit target used by mainnet, your laptop would take longer than the age of the universe to find a single valid block. The "toy difficulty" slider below tops out at 22 bits.

Toy Nonce Grinder

version: 20000000 prev_block: 00000000000000000002a9e8f6c13a9f7b5d8e4c1a2b3d4e5f6789abcdef0123 merkle_root:6b3e0d125d0a5e72f5b12c4d9e1a2b3c4f5a8b0d3e9c2a1f8b7d4c5e6a0f9d1b timestamp: 6626a1f3 (= Apr 22, 2024 17:44:19 UTC) bits: 17034219 (real mainnet target โ€” ignored here; toy target is from slider) nonce: 00000000
Click Grind to start iterating the 4-byte nonce field.
What the Grinder Proves

Every hash you just computed is exactly what a Bitcoin ASIC computes โ€” the same SHA-256 compression function, the same 80-byte header layout, the same "is the hash less than the target" check. The only thing the ASIC does differently is scale: hundreds of thousands of specialized chips hashing in parallel, each running on the order of \(10^{11}\) hashes per second. The algorithm is identical.

E.7Step 6 โ€” Propagate the Block

The instant the ASIC returns a valid nonce, the pool node broadcasts the new block over the Bitcoin p2p network.

  1. Inventory announcement. The node sends an inv message to every connected peer, containing the block's 32-byte hash (MSG_BLOCK type = 2).
  2. Data request. A peer that does not already have this block responds with getdata requesting the full block.
  3. Block delivery. The winning node replies with a block message containing the full serialized block: 80-byte header, compact-size transaction count, then each transaction's raw bytes (coinbase first). For modern nodes, compact blocks (BIP 152) are used instead: a cmpctblock message with short transaction IDs lets the peer reconstruct the block from its mempool in a single round-trip.

Each peer that receives the block validates it and then announces it to its own peers. Block propagation to most of the network takes 1โ€“3 seconds typically; the "FIBRE" and similar relay networks push the tail of propagation below 500 ms to reduce orphan risk for miners.

E.8Step 7 โ€” Every Node Validates

Receiving a block is only the start. Every full node independently re-verifies it against the consensus rules before accepting. Validation checks include, in rough order:

If any check fails, the node rejects the block and may ban the peer that sent it. If all checks pass, the block is written to disk and the UTXO set is updated: every input is removed, every output is added.

E.9Step 8 โ€” Confirmation and Finality

Once the block is accepted as the new tip of the most-work chain, miners building the next block use it as their prev_block. Each subsequent block that extends this one counts as one more confirmation.

The probability that a block is reorganized out of the chain falls roughly as \(p^n\) where \(p\) is the reorg probability of any single block (in practice \(\ll 0.01\) for the honest majority assumption) and \(n\) is confirmation depth. Common conventions:

ConfirmationsUse case
1Small payments, acknowledgment
3Typical exchange deposit threshold for small amounts
6Historical "Nakamoto standard" for large payments
100Coinbase maturity gate โ€” consensus-enforced, not policy

The 100-block maturity rule is special because it is a hard consensus rule, not a social convention. Even if the miner controls the address that received the coinbase, no transaction spending that output will be accepted into any valid block until 100 confirmations have passed. This protects the chain from reorganizations invalidating downstream spends of a reward that turned out to be orphaned.

E.10What We Learned

โ† Previous Next โ†’