Build Your Own Blockchain with Python and Flask 🚀
- Debapriya Mukherjee
- Feb 5
- 4 min read

Introduction 🏗️
Blockchain technology is at the core of cryptocurrencies like Bitcoin and Ethereum. But did you know that you can build your own blockchain using Python and Flask? In this article, we’ll create a simple blockchain that allows you to mine blocks, view the entire chain, and validate its integrity! 💡
What is a Blockchain? 🔗
A blockchain is a decentralized, distributed ledger that records transactions in a secure, tamper-proof way. Each block contains:
Index: Position in the blockchain
Timestamp: When the block was created
Proof: A cryptographic puzzle solution
Previous Hash: Hash of the previous block (to maintain the chain)
Tech Stack Used 🛠️
Python 🐍 (for the backend logic)
Flask 🌍 (for the web interface)
SHA-256 Hashing 🔐 (for securing blocks)
Proof of Work ⛏️ (to validate mining)
Let's break down each code snippet in detail so you fully understand how the Flask Blockchain Project works. 🚀
1️⃣ Setting Up the Project
📌 Installing Flask
pip install flask
🔹 Explanation:
This installs Flask, a lightweight web framework in Python that allows us to create APIs and web applications.
2️⃣ Creating the Blockchain Class
📌 Defining the Blockchain
import datetime
import hashlib
import json
from flask import Flask, jsonify, render_template
🔹 Explanation:
datetime: Helps us add timestamps to blocks.
hashlib: Provides SHA-256 hashing, which is crucial for securing blocks.
json: Allows conversion of Python objects to JSON format (useful for API responses).
Flask: The web framework to create the blockchain’s interface.
jsonify: Converts Python objects to JSON format for API responses.
render_template: Renders HTML templates for better UI integration.
📌 Initializing the Blockchain
class Blockchain:
def __init__(self):
self.chain = []
self.create_block(proof=1, previous_hash='0') # Genesis block
🔹 Explanation:
self.chain = []: Initializes an empty list to store the blockchain.
self.create_block(proof=1, previous_hash='0'): Creates the Genesis Block (the first block of the chain).
📌 Creating a New Block
def create_block(self, proof, previous_hash):
block = {
'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.now()),
'proof': proof,
'previous_hash': previous_hash
}
self.chain.append(block)
return block
🔹 Explanation:
index: Position of the block in the chain.
timestamp: Captures the exact time the block is created.
proof: A number that satisfies the proof-of-work condition.
previous_hash: Stores the hash of the previous block to maintain the blockchain’s integrity.
self.chain.append(block): Adds the new block to the chain.
3️⃣ Implementing Proof of Work (Mining Blocks)
def proof_of_work(self, previous_proof):
new_proof = 1
check_proof = False
while check_proof is False:
hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:5] == '00000': # Difficulty level
check_proof = True
else:
new_proof += 1
return new_proof
🔹 Explanation:
previous_proof: The proof from the last block.
new_proof: Starts at 1 and keeps increasing until it meets the condition.
The while loop keeps running until a valid proof is found.
SHA-256 hashing is used to generate a hash, and we check if the first 5 characters are '00000' (difficulty level).
If the condition is met, we return new_proof.
👉 Why Proof of Work?
Ensures blocks are mined fairly by making the process computationally expensive.
Prevents spam mining and ensures security.
4️⃣ Hashing Blocks
def hash(self, block):
encoded_block = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()
🔹 Explanation:
json.dumps(block, sort_keys=True).encode(): Converts the block into a JSON string and encodes it.
hashlib.sha256(...).hexdigest(): Creates a SHA-256 hash of the block, which acts as its unique identifier.
👉 Why Hashing?
Ensures block integrity.
Prevents tampering, as modifying a block would change its hash.
5️⃣ Validating the Blockchain
def chain_valid(self, chain):
previous_block = chain[0]
block_index = 1
while block_index < len(chain):
block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
proof = block['proof']
hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:5] != '00000':
return False
previous_block = block
block_index += 1
return True
🔹 Explanation:
Loops through each block and checks:
If the previous_hash stored in the block matches the actual hash of the previous block.
If the proof-of-work condition is satisfied.
If any check fails, the blockchain is invalid.
👉 Why Validation?
Ensures no tampering has occurred.
Makes sure every block links correctly with the previous one.
6️⃣ Building the Flask API
📌 Setting Up Flask
app = Flask(__name__)
blockchain = Blockchain()
🔹 Explanation:
app = Flask(__name__): Initializes a Flask app.
blockchain = Blockchain(): Creates a blockchain instance.
📌 Mining a Block
@app.route('/mine_block', methods=['GET'])
def mine_block():
previous_block = blockchain.chain[-1]
proof = blockchain.proof_of_work(previous_block['proof'])
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash)
return render_template('mine_block.html', block=block)
🔹 Explanation:
Retrieves the last block.
Calls proof_of_work() to mine a new block.
Computes the previous hash.
Creates a new block and returns it.
📌 Viewing the Blockchain
@app.route('/get_chain', methods=['GET'])
def display_chain():
return render_template('get_chain.html', chain=blockchain.chain)
🔹 Explanation:
Displays the entire blockchain using an HTML template.
📌 Checking Blockchain Validity
@app.route('/valid', methods=['GET'])
def valid():
is_valid = blockchain.chain_valid(blockchain.chain)
return render_template('valid.html', is_valid=is_valid)
🔹 Explanation:
Calls chain_valid() to verify if the blockchain is tamper-proof.
7️⃣ Running the Flask App
python app.py
🔹 Explanation:
Runs the Flask server.
Open http://127.0.0.1:5000 in your browser to interact with the blockchain.
Conclusion 🎯
🔹 You now have a fully functional blockchain using Python and Flask! 🚀
🔹 This project covers block creation, mining, and validation.
🔹 You can extend it further by adding transactions, smart contracts, or a UI.
💡 Have Questions? Drop them in the comments!
😊📌 GitHub Repo: GitHub Link
Comments