The Mining Process � Step by Step
Mining is the process by which new blocks are added to a Proof of Work blockchain. Miners are economic actors who invest in hardware and electricity to compete for block rewards. Understanding mining reveals how Bitcoin's security is funded.
Mining Step-by-Step
- Step 1 � Connect to network: Miner runs full node software, syncs the full blockchain, and connects to mining pool or mines solo
- Step 2 � Monitor mempool: Continuously monitor incoming transactions. Select transactions to include � prioritize by fee rate (sat/byte) to maximize revenue
- Step 3 � Build candidate block: Assemble the block body with selected transactions plus coinbase transaction (mining reward)
- Step 4 � Construct header: Build 80-byte header: version + previous block hash + Merkle root of transactions + timestamp + bits (difficulty target) + nonce = 0
- Step 5 � Hash loop: Compute double-SHA256 of the 80-byte header. Compare result to difficulty target. If hash < target: broadcast block immediately. If hash >= target: increment nonce and repeat
- Step 6 � Nonce exhaustion: If nonce reaches 2^32 (~4.3 billion) with no solution: change timestamp by 1 second OR modify extra nonce in coinbase tx (changes Merkle root) ? effectively a new problem
- Step 7 � Win and collect: Broadcast found block. Network validates and builds on top. After 100 blocks (maturity), miner can spend the coinbase reward
Full Mining Loop in Python
import hashlib, time, struct
def double_sha256(data: bytes) -> bytes:
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
def compact_to_target(bits: int) -> int:
"""Convert compact 'bits' field to 256-bit target integer"""
exponent = bits >> 24
mantissa = bits & 0x7FFFFF
return mantissa * (256 ** (exponent - 3))
def mine_block(prev_hash: str, merkle_root: str, bits: int,
version: int = 0x20000000) -> dict:
"""Full mining loop � returns first valid block found"""
target = compact_to_target(bits)
timestamp = int(time.time())
nonce = 0
attempts = 0
start = time.time()
# Pack header (80 bytes): version(4) + prev(32) + merkle(32) + time(4) + bits(4) + nonce(4)
prev_bytes = bytes.fromhex(prev_hash.zfill(64))
merkle_bytes = bytes.fromhex(merkle_root.zfill(64))
while True:
header = struct.pack("<I", version) + prev_bytes + merkle_bytes + struct.pack("<III", timestamp, bits, nonce)
block_hash = double_sha256(header)
hash_int = int.from_bytes(block_hash, "big")
attempts += 1
if hash_int < target:
elapsed = time.time() - start
return {
"nonce": nonce,
"hash": block_hash[::-1].hex(), # Reverse for display (Bitcoin convention)
"hash_int": hash_int,
"target": target,
"attempts": attempts,
"time_s": round(elapsed, 4),
"hash_rate": round(attempts / max(elapsed, 0.001)),
}
nonce = (nonce + 1) & 0xFFFFFFFF # Wrap at 4 bytes
if nonce == 0:
# Nonce exhausted � change timestamp to reset search space
timestamp += 1
# Mine with very easy difficulty (for demonstration speed)
easy_bits = 0x207fffff # Easiest Bitcoin target
result = mine_block(
prev_hash="0" * 64,
merkle_root="a1b2c3d4e5f6" + "0" * 52,
bits=easy_bits,
)
print(f"Block mined!")
print(f" Nonce : {result['nonce']:,}")
print(f" Attempts : {result['attempts']:,}")
print(f" Time : {result['time_s']}s")
print(f" Hash rate: {result['hash_rate']:,} H/s")
print(f" Hash : {result['hash'][:20]}...")Common Mistakes
- Thinking miners verify all transactions independently � professional mining pools often use Stratum protocol where miners only receive block headers and prove work, delegating full validation to pool servers. This creates a risk: pools could include invalid transactions
- Assuming mining is 'solving math problems' � mining is not solving an equation. It is a brute-force search: try random inputs until one produces a hash meeting the difficulty threshold. Pure probabilistic trial-and-error
Tip
Tip
Practice The Mining Process Step by Step in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Each block references the previous block's hash, forming an immutable chain
Practice Task
Note
Practice Task — (1) Write a working example of The Mining Process Step by Step from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with The Mining Process Step by Step is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready blockchain code.
Key Takeaways
- Mining is the process by which new blocks are added to a Proof of Work blockchain.
- Step 1 � Connect to network: Miner runs full node software, syncs the full blockchain, and connects to mining pool or mines solo
- Step 2 � Monitor mempool: Continuously monitor incoming transactions. Select transactions to include � prioritize by fee rate (sat/byte) to maximize revenue
- Step 3 � Build candidate block: Assemble the block body with selected transactions plus coinbase transaction (mining reward)