Eight days of building — all connected
Today we pause building and zoom out. We'll walk through the complete tiny blockchain end-to-end, connect every piece to a real Polkadot concept, and clear up misconceptions before the mini-project.
import hashlib, time, random
# ── HASHING ──────────────────────────────────────────
def hash_block(block):
content = (str(block["index"]) + block["timestamp"] +
str(block["transactions"]) +
block["previous_hash"] + str(block["nonce"]))
return hashlib.sha256(content.encode()).hexdigest()
# ── BLOCK CREATION ───────────────────────────────────
def make_block(index, transactions, previous_hash, nonce=0):
block = {
"index": index,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"transactions": transactions,
"previous_hash": previous_hash,
"nonce": nonce,
"hash": "",
}
block["hash"] = hash_block(block)
return block# ── MINING ───────────────────────────────────────────
def mine_block(index, transactions, previous_hash, difficulty=3):
target = "0" * difficulty
nonce = 0
while True:
block = make_block(index, transactions, previous_hash, nonce)
if block["hash"].startswith(target):
return block
nonce += 1
# ── CHAIN OPERATIONS ──────────────────────────────────
def add_block(chain, transactions, difficulty=3):
chain.append(mine_block(len(chain), transactions,
chain[-1]["hash"], difficulty))
def is_valid_chain(chain):
for i, b in enumerate(chain):
if b["hash"] != hash_block(b): return False
if i > 0 and b["previous_hash"] != chain[i-1]["hash"]: return False
return True# ── START THE CHAIN ───────────────────────────────────
chain = [make_block(0, [], "0" * 64)] # genesis
# Add blocks with transactions
add_block(chain, [{"from":"Alice","to":"Bob","amount":10}])
add_block(chain, [{"from":"Bob","to":"Carol","amount":4},
{"from":"Alice","to":"Dave","amount":2}])
# View the chain
for b in chain:
print(f"Block {b['index']}: {len(b['transactions'])} txns | "
f"hash={b['hash'][:12]}...")
# Validate
print("Valid:", is_valid_chain(chain)) # True| Feature | Our Tiny Blockchain | Polkadot Relay Chain |
|---|---|---|
| Block structure | index, timestamp, transactions, prev_hash, nonce, hash |
number, parent_hash, state_root, extrinsics_root, timestamp |
| Consensus | Proof of Work (nonce guessing) | NPoS — 300 validators elect block authors |
| Validation | hash integrity + chain links | signatures + state transitions + runtime logic |
| Persistence | Python list in memory | RocksDB database on every validator node |