Build Your Own Blockchain
๐ 12 min read ยท ๐ Python
Quick Answer
The best way to understand a blockchain is to build one. In about 50 lines of Python you can create a working toy blockchain with hashing, a chain of blocks, proof-of-work mining, and tamper detection โ the same core ideas that secure Bitcoin. No prior blockchain knowledge needed.
โ ๏ธ This is a learning model, not production code. It teaches the data structure behind Bitcoin โ it is not secure money and should never hold real value.
Step 1 โ A block and its fingerprint
A block holds some data (transactions), a link to the previous block, and a "nonce" (a number we can change). Its identity is a SHA-256 hash of all its contents โ change one character and the hash changes completely. That hash is the blockโs tamper-evident fingerprint.
import hashlib, json, time
class Block:
def __init__(self, index, transactions, previous_hash, nonce=0):
self.index = index
self.timestamp = time.time()
self.transactions = transactions
self.previous_hash = previous_hash
self.nonce = nonce
def hash(self):
# A block's fingerprint = SHA-256 of all its contents.
payload = json.dumps({
"index": self.index,
"timestamp": self.timestamp,
"transactions": self.transactions,
"previous_hash": self.previous_hash,
"nonce": self.nonce,
}, sort_keys=True).encode()
return hashlib.sha256(payload).hexdigest()Step 2 โ Mining (Proof of Work)
Mining means finding a hash that meets a rule โ here, starting with a set number of zeros. There is no formula; you brute-force the nonce until the hash fits. Checking a solution is instant, but finding one takes work. That asymmetry is the heart of Proof of Work.
DIFFICULTY = 4 # require this many leading zeros
def mine(block):
# Proof of Work: keep changing the nonce until the hash
# starts with DIFFICULTY zeros. There is no shortcut โ
# you just have to guess, which is what costs energy.
target = "0" * DIFFICULTY
while not block.hash().startswith(target):
block.nonce += 1
return block.hash()Step 3 โ Chaining the blocks
Each new block stores the hash of the previous one, welding them into a chain that starts with a hard-coded "genesis" block. Because every block commits to the one before it, the order is fixed and the history is linked together.
class Blockchain:
def __init__(self):
# The genesis block โ the very first, hard-coded block.
genesis = Block(0, [{"note": "genesis"}], "0")
mine(genesis)
self.chain = [genesis]
def add_block(self, transactions):
prev = self.chain[-1]
block = Block(len(self.chain), transactions, prev.hash())
mine(block) # do the work
self.chain.append(block)
return blockStep 4 โ Validating the chain
To trust a chain, you re-check it: every block must point to the real hash of the previous block, and every block must satisfy the proof-of-work rule. If either check fails anywhere, the chain is invalid.
def is_valid(chain):
for i in range(1, len(chain)):
current, previous = chain[i], chain[i - 1]
# 1) Each block must point to the real hash of the one before it.
if current.previous_hash != previous.hash():
return False
# 2) Each block must satisfy the proof-of-work rule.
if not current.hash().startswith("0" * DIFFICULTY):
return False
return TrueStep 5 โ Run it and try to cheat
Now add a few blocks and then tamper with an old transaction. The moment you change past data, that blockโs hash no longer matches what the next block expects โ and validation instantly returns False. This is, in miniature, why you cannot quietly rewrite Bitcoinโs history.
bc = Blockchain()
bc.add_block([{"from": "Alice", "to": "Bob", "amount": 5}])
bc.add_block([{"from": "Bob", "to": "Carol", "amount": 2}])
print("Chain valid?", is_valid(bc.chain)) # True
# Now try to cheat: tamper with an old transaction.
bc.chain[1].transactions[0]["amount"] = 5000
print("Chain valid?", is_valid(bc.chain)) # False โ tampering is caught!๐ Key takeaway
A blockchain is just data structures plus rules: hash each block, link it to the last, and make adding blocks costly via proof-of-work. Tampering breaks the chain of hashes โ which is exactly how Bitcoin stays tamper-evident without a central authority.
What real Bitcoin adds
Our toy chain teaches the skeleton. Real Bitcoin adds a global peer-to-peer network of nodes, digital signatures that prove who can spend coins, automatic difficulty adjustment, the UTXO model, block rewards and halvings, and the consensus rules that let strangers agree without trust. Explore each in our explainers below.
Frequently asked questions
Is this a real blockchain like Bitcoin?โผ
It is a simplified teaching model that shares Bitcoinโs core ideas โ hashing, chaining, and proof-of-work โ but leaves out the networking, digital signatures, and economic incentives that make Bitcoin secure at global scale. It is for learning, not for running money.
Do I need to be a programmer?โผ
Basic familiarity with Python helps, but the explanations are written so anyone can follow the logic. You can read it to understand the concepts even without running the code.
Why does mining just add zeros?โผ
Requiring the hash to start with a number of zeros is an easy-to-check but hard-to-find condition. The only way to find a valid hash is to keep guessing (changing the nonce), which is exactly why real mining costs energy.
What is missing compared to real Bitcoin?โผ
A real network of nodes, digital signatures proving ownership, a peer-to-peer protocol, difficulty adjustment, the UTXO model, and block rewards. This tutorial teaches the data structure; see our explainers for the full system.