Python Central HubSign in

Python Projects / Advanced

Blockchain-Based Voting System

A Python application for secure voting using blockchain technology, featuring transaction management, cryptography, and a CLI interface.

Abstract

Blockchain-Based Voting System is a Python project that uses blockchain technology for secure voting. The application features transaction management, cryptography, and a CLI interface, demonstrating best practices in security and distributed systems.

Prerequisites

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of blockchain and cryptography
  • Required libraries: hashlib, json, time

Before you Start

Install Python and the required libraries:

Shell
# Standard libraries only

Getting Started

Create a Project

  1. Create a folder named blockchain-based-voting-system.
  2. Open the folder in your code editor or IDE.
  3. Create a file named blockchain_based_voting_system.py.
  4. Copy the code below into your file.
diagram how the pieces call each other mermaid
Derived from projects/advance/blockchain_based_voting_system.py by parsing it, not by hand. Arrows are calls between the file's own functions and methods; library calls are left out, and only calls the parser could resolve with certainty are shown.

Write the Code

Blockchain-Based Voting SystemSource
Blockchain-Based Voting System
"""
Blockchain-Based Voting System

Features:
- Secure voting using blockchain
- User authentication
- Result dashboard
- Modular design
- CLI interface
- Error handling
"""
import hashlib
import json
import sys
import time
from collections import defaultdict

class Block:
    def __init__(self, index, timestamp, data, prev_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.prev_hash = prev_hash
        self.hash = self.compute_hash()

    def compute_hash(self):
        block_string = json.dumps(self.__dict__, sort_keys=True)
        return hashlib.sha256(block_string.encode()).hexdigest()

class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]

    def create_genesis_block(self):
        return Block(0, time.time(), {"votes": {}}, "0")

    def add_block(self, data):
        prev = self.chain[-1]
        block = Block(len(self.chain), time.time(), data, prev.hash)
        self.chain.append(block)

    def is_valid(self):
        for i in range(1, len(self.chain)):
            if self.chain[i].prev_hash != self.chain[i-1].hash:
                return False
            if self.chain[i].hash != self.chain[i].compute_hash():
                return False
        return True

class VotingSystem:
    def __init__(self):
        self.blockchain = Blockchain()
        self.users = {"alice": "pass1", "bob": "pass2", "carol": "pass3"}
        self.votes = defaultdict(str)
        self.candidates = ["A", "B", "C"]

    def authenticate(self, user, pwd):
        return self.users.get(user) == pwd

    def vote(self, user, candidate):
        if candidate not in self.candidates:
            raise ValueError("Invalid candidate")
        self.votes[user] = candidate
        self.blockchain.add_block({"user": user, "vote": candidate})

    def results(self):
        tally = defaultdict(int)
        for v in self.votes.values():
            tally[v] += 1
        return dict(tally)

    def dashboard(self):
        print("Voting Results:")
        for c, v in self.results().items():
            print(f"{c}: {v}")
        print(f"Blockchain valid: {self.blockchain.is_valid()}")

class CLI:
    @staticmethod
    def run():
        system = VotingSystem()
        print("Candidates: A, B, C")
        while True:
            user = input("Username: ")
            pwd = input("Password: ")
            if not system.authenticate(user, pwd):
                print("Authentication failed.")
                continue
            print("Vote for (A/B/C): ")
            candidate = input().strip().upper()
            try:
                system.vote(user, candidate)
                print("Vote recorded.")
            except Exception as e:
                print(f"Error: {e}")
            if input("Show dashboard? (y/n): ").lower() == 'y':
                system.dashboard()
            if input("Exit? (y/n): ").lower() == 'y':
                break

if __name__ == "__main__":
    try:
        CLI.run()
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

Example Usage

Shell
python blockchain_based_voting_system.py

Explanation

Key Features

  • Blockchain Transactions: Manages votes as blockchain transactions.
  • Cryptography: Secures votes using hashing.
  • Error Handling: Validates inputs and manages exceptions.
  • CLI Interface: Interactive command-line usage.

Code Breakdown

  1. What it imports (lines 12–16)
Python
import hashlib
import json
import sys
import time
from collections import defaultdict
  1. Block — the class (lines 18–28)
Python
class Block:
    def __init__(self, index, timestamp, data, prev_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.prev_hash = prev_hash
        self.hash = self.compute_hash()
 
    def compute_hash(self):
        block_string = json.dumps(self.__dict__, sort_keys=True)
        return hashlib.sha256(block_string.encode()).hexdigest()
  1. Blockchain — the class (lines 30–48)
Python
class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]
 
    def create_genesis_block(self):
        return Block(0, time.time(), {"votes": {}}, "0")
 
    def add_block(self, data):
        prev = self.chain[-1]
        block = Block(len(self.chain), time.time(), data, prev.hash)
        self.chain.append(block)
 
    def is_valid(self):
        for i in range(1, len(self.chain)):
            if self.chain[i].prev_hash != self.chain[i-1].hash:
                return False
            if self.chain[i].hash != self.chain[i].compute_hash():
                return False
        return True
  1. VotingSystem — the class (lines 50–76)
Python
class VotingSystem:
    def __init__(self):
        self.blockchain = Blockchain()
        self.users = {"alice": "pass1", "bob": "pass2", "carol": "pass3"}
        self.votes = defaultdict(str)
        self.candidates = ["A", "B", "C"]
 
    def authenticate(self, user, pwd):
        return self.users.get(user) == pwd
 
    def vote(self, user, candidate):
        if candidate not in self.candidates:
            raise ValueError("Invalid candidate")
        self.votes[user] = candidate
        self.blockchain.add_block({"user": user, "vote": candidate})
 
    def results(self):
        tally = defaultdict(int)
# ... 3 more lines in the file ...
 
    def dashboard(self):
        print("Voting Results:")
        for c, v in self.results().items():
            print(f"{c}: {v}")
        print(f"Blockchain valid: {self.blockchain.is_valid()}")
  1. CLI — the class (lines 78–99)
Python
class CLI:
    @staticmethod
    def run():
        system = VotingSystem()
        print("Candidates: A, B, C")
        while True:
            user = input("Username: ")
            pwd = input("Password: ")
            if not system.authenticate(user, pwd):
                print("Authentication failed.")
                continue
            print("Vote for (A/B/C): ")
            candidate = input().strip().upper()
            try:
                system.vote(user, candidate)
                print("Vote recorded.")
            except Exception as e:
                print(f"Error: {e}")
            if input("Show dashboard? (y/n): ").lower() == 'y':
                system.dashboard()
            if input("Exit? (y/n): ").lower() == 'y':
                break

The file defines 4 top-level symbols in all; the whole thing is above under Write the Code.

Features

  • Secure Voting: Blockchain transactions and cryptography
  • Modular Design: Separate classes and functions
  • Error Handling: Manages invalid inputs and exceptions
  • Production-Ready: Scalable and maintainable code

Next Steps

Enhance the project by:

  • Integrating with real-world voting datasets
  • Supporting distributed consensus
  • Creating a GUI for voting
  • Adding encryption for votes
  • Unit testing for reliability

Educational Value

This project teaches:

  • Security: Blockchain and cryptography
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • E-Voting Platforms
  • Secure Transactions
  • Distributed Systems

Checkpoint exercise

This exercise practises a hash chain whose blocks commit to the previous hash, so tampering with any vote is detectable.

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Conclusion

Blockchain-Based Voting System demonstrates how to build a scalable and secure voting tool using Python. With modular design and extensibility, this project can be adapted for real-world applications in security, governance, and more. For more advanced projects, visit Python Central Hub.

Was this page helpful?

Let us know how we did