In this section, we’re going to build a simple blockchain-like application with Python and Flask to create a voting system. This project is a replica of a blockchain running on a single server and aims to demonstrate key blockchain concepts, such as block creation, linking, and validation. While it mimics some aspects of a blockchain, it does not incorporate full decentralization, consensus mechanisms, or immutability features of a true blockchain system.
If you wanna apply full decentralization, consensus mechanisms, or immutability features checkout Section 4.
This application will display each vote as a new block in a chain, and we’ll validate the blockchain structure to ensure its integrity. This is a simplified version of a blockchain, created for educational purposes, and is designed to help you understand how basic blockchain elements work in a controlled, single-server environment.
Let’s break down each part to make it easy to follow.
Block
and BlockChain
Classesapp.py
)index.html
)You need Python and Flask installed. Open a terminal and install Flask with:
pip install flask
Create a folder for your project, and within it, set up the following structure:
project/
├── app.py # Main Flask application
├── PyChain.py # Blockchain classes (Block and BlockChain)
└── templates/
└── index.html # HTML template with Bootstrap
A blockchain is a linked list of blocks, each block containing:
Each new vote will create a new block linked to the previous one, making it tamper-resistant.
Block
and BlockChain
Classes (PyChain.py
)Here, we define two classes, Block
and BlockChain
.
# PyChain.py
import hashlib, time
class Block:
def __init__(self, data, prev_hash=""):
self.data = data
self.prev_hash = prev_hash
self.timestamp = time.time()
self.hash = self.calc_hash()
def calc_hash(self):
return hashlib.sha256((str(self.data) + self.prev_hash + str(self.timestamp)).encode()).hexdigest()
class BlockChain:
def __init__(self):
self.chain = [self.create_genesis()]
def create_genesis(self):
return Block("Genesis")
def addBlock(self, block):
block.prev_hash = self.chain[-1].hash
block.hash = block.calc_hash()
self.chain.append(block)
def chainValid(self):
for i in range(1, len(self.chain)):
b, pb = self.chain[i], self.chain[i - 1]
if b.hash != b.calc_hash() or b.prev_hash != pb.hash:
return False
return True
Block Class:
__init__
: Initializes the block with data, a timestamp, and calculates its hash.calc_hash
: Generates a SHA-256 hash from the block’s contents.BlockChain Class:
addBlock
: Links the new block to the previous block.chainValid
: Checks the integrity of the blockchain by verifying each block’s hash.app.py
)This file handles the web server and routes for the application.
# app.py
from flask import Flask, render_template, request, redirect
from PyChain import BlockChain, Block
app = Flask(__name__)
chain = BlockChain()
@app.route('/')
def index():
return render_template('index.html', chain=chain.chain, valid=chain.chainValid())
@app.route('/vote', methods=['POST'])
def vote():
choice = request.form.get('choice')
if choice:
chain.addBlock(Block(choice))
return redirect('/')
if __name__ == "__main__":
app.run(debug=True)
index
Route: Loads the main voting page and displays the blockchain status.vote
Route: Receives vote submissions from the form and adds them as new blocks.templates/index.html
)This HTML page will display the voting form and blockchain status.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Blockchain Voting</title>
</head>
<body>
<div class="container mt-5">
<h1 class="text-center">Blockchain Voting System</h1>
<div class="card mt-4">
<div class="card-body">
<form method="POST" action="/vote">
<label for="choice" class="form-label">Select your choice:</label>
<select class="form-select mb-3" name="choice" required>
<option value="Candidate 1">Candidate 1</option>
<option value="Candidate 2">Candidate 2</option>
<option value="Candidate 3">Candidate 3</option>
</select>
<button type="submit" class="btn btn-primary">Vote</button>
</form>
</div>
</div>
<h2 class="mt-5">Blockchain Status</h2>
<p>Blockchain Valid: {{ 'Yes' if valid else 'No' }}</p>
<ul class="list-group">
{% for block in chain %}
<li class="list-group-item">
<strong>Block {{ loop.index }}</strong><br>
Data: {{ block.data }}<br>
Hash: {{ block.hash }}<br>
Previous Hash: {{ block.prev_hash }}<br>
Timestamp: {{ block.timestamp }}
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
To run the application:
In the terminal, navigate to your project folder.
Start the Flask server by running:
python app.py
Open your browser and go to http://127.0.0.1:5000/
.
You’ll see the voting interface with the blockchain status below.
Congratulations! You’ve built a simple blockchain-based voting app with Python.
This project will demonstrate the core concept of blockchain and how blocks are linked together securely.