Voting System Using Blockchain in Python Free Source Code

Voting System Using Blockchain in Python Free Source Code

UI-Based Voting System Using Blockchain in Python

Introduction

In an era where trust in electoral processes is paramount, blockchain technology presents a revolutionary solution for secure and transparent voting systems. Traditional voting methods often face challenges such as fraud and inaccessibility, undermining democratic integrity. This blog post delves into creating a voting system using blockchain in Python, showcasing how to develop a robust backend with a user-friendly interface. By harnessing the power of blockchain, we can enhance the electoral experience, ensuring that every vote is counted accurately and securely.

Blockchain for Voting

Blockchain brings several advantages to voting systems:

  • Security: Each vote is securely recorded and cannot be altered.
  • Transparency: The entire voting process can be audited without compromising voter privacy.
  • Decentralization: No central authority can manipulate the results, ensuring election integrity.
  • Anonymity: Voters’ identities are protected while their votes are securely tracked.
Voting System Using Blockchain in  Python
Voting System Using Blockchain in Python

Overview

Our voting system will consist of two main components:

  1. Blockchain Backend: This will store and secure the votes.
  2. Graphical User Interface (GUI): A user-friendly front-end where voters can easily cast their votes.
See also  Hotel Billing System in Python With Source Code

We will use the Tkinter library to build the GUI and the PyCryptodome library for cryptographic security in the blockchain. Let’s dive into the development process.

Step 1: Setting Up the Blockchain Backend

First, let’s create a simple blockchain in Python to store votes securely.

import hashlib
import json
from time import time

class Blockchain:
    def __init__(self):
        self.chain = []
        self.current_votes = []
        self.create_block(previous_hash='1', proof=100)

    def create_block(self, proof, previous_hash):
        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'votes': self.current_votes,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }
        self.current_votes = []
        self.chain.append(block)
        return block

    def add_vote(self, voter_id, candidate):
        vote = {'voter_id': voter_id, 'candidate': candidate}
        self.current_votes.append(vote)

    def proof_of_work(self, previous_proof):
        proof = 0
        while self.valid_proof(previous_proof, proof) is False:
            proof += 1
        return proof

    @staticmethod
    def valid_proof(previous_proof, proof):
        guess = f'{previous_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"

    @staticmethod
    def hash(block):
        encoded_block = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(encoded_block).hexdigest()

    def get_last_block(self):
        return self.chain[-1]

Step 2: Explanation of the Code

  1. Blockchain Class:
  • Manages the chain of blocks and the list of current votes.
  1. create_block() Method:
  • Creates a new block to store the votes and appends it to the blockchain.
  1. add_vote() Method:
  • Adds a vote to the list of votes, which will be included in the next block.
  1. Proof of Work:
  • Implements the proof-of-work algorithm to ensure the security of each new block.
  1. Hashing:
  • Uses the SHA-256 cryptographic hash function to ensure that each block is linked securely to the previous one.

Step 3: Creating the User Interface (UI) with Tkinter

Now that we have the blockchain set up, let’s build the user interface using the Tkinter library. The UI will allow voters to enter their voter ID and choose a candidate.

import tkinter as tk
from tkinter import messagebox

blockchain = Blockchain()

def cast_vote():
    voter_id = voter_id_entry.get()
    candidate = candidate_var.get()

    if voter_id and candidate:
        blockchain.add_vote(voter_id, candidate)
        proof = blockchain.proof_of_work(blockchain.get_last_block()['proof'])
        previous_hash = blockchain.hash(blockchain.get_last_block())
        blockchain.create_block(proof, previous_hash)

        messagebox.showinfo("Vote Cast", "Your vote has been successfully cast!")
    else:
        messagebox.showerror("Error", "Please enter a valid voter ID and select a candidate.")

# Setting up the main window
window = tk.Tk()
window.title("Blockchain Voting System")

# Voter ID Input
tk.Label(window, text="Enter your Voter ID:").pack()
voter_id_entry = tk.Entry(window)
voter_id_entry.pack()

# Candidate Selection
tk.Label(window, text="Select a Candidate:").pack()
candidate_var = tk.StringVar(value="Candidate1")
tk.Radiobutton(window, text="Candidate 1", variable=candidate_var, value="Candidate1").pack(anchor=tk.W)
tk.Radiobutton(window, text="Candidate 2", variable=candidate_var, value="Candidate2").pack(anchor=tk.W)
tk.Radiobutton(window, text="Candidate 3", variable=candidate_var, value="Candidate3").pack(anchor=tk.W)

# Vote Button
vote_button = tk.Button(window, text="Cast Vote", command=cast_vote)
vote_button.pack()

window.mainloop()
Voting System Using Blockchain in Python Free Source Code
Voting System Using Blockchain in Python Free Source Code

Step 4: Explanation of the UI Code

  1. Tkinter Interface:
  • We use Tkinter to create the main window with labels, entry fields, and radio buttons for the candidates.
  1. cast_vote() Function:
  • This function takes the voter’s ID and selected candidate and adds the vote to the blockchain. After the vote is cast, a new block is created and a message is displayed to confirm the vote.
  1. Simple and Intuitive:
  • The UI is simple, allowing voters to easily input their voter ID, select a candidate, and cast their vote.
See also  Hospital Management System in Python with Source Code

Step 5: Running the Application

To run the voting system:

  1. Install the required libraries:
   pip install tkinter pycryptodome
  1. Run the Python script:
   python voting_system.py

Once the application is running, voters can cast their votes through the GUI. Each vote is recorded in a block on the blockchain, ensuring that it is secure and transparent.

Step 6: Enhancing the Voting System

While this is a basic voting system, there are many ways you can enhance it:

  • Voter Authentication: Integrate a more robust system for voter verification using a digital identity system or smart contracts.
  • Candidate Addition: Allow the UI to dynamically update based on the list of candidates, making the system adaptable for different elections.
  • Real-Time Vote Count: Display live results based on the blockchain data, providing instant insights into election results.

  • Voting System Using Blockchain in Python Free Source Code
  • Voting System Using Blockchain in Python

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *