├── LICENSE.md ├── README.md ├── blockchain.json ├── registration.py ├── requirements.txt ├── voter.py └── voter_data.json /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Harishkumar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🔐 Blockchain-based Voting System 2 | [![License](https://img.shields.io/github/license/whitehatboy005/Blockchain-Based-Voting-System)](LICENSE.md) 3 | 4 | This project is a Blockchain-based Voting System application built using Python and Tkinter. It uses blockchain technology to ensure the integrity and transparency of the voting process by securely recording each vote in a tamper-proof ledger. 5 | 6 | ## 📌 Features 7 | 8 | 1. **Blockchain Integration** 9 | - Each vote is added as a block to the blockchain, containing a timestamp, candidate choice, and hash of the previous block. 10 | - Blockchain ensures that once recorded, a vote cannot be altered, providing transparency and immutability. 11 | 12 | 2. **Voter Registration** 13 | - Unique voter IDs are hashed and stored to securely register voters and prevent duplicate votes. 14 | - Voter information is securely loaded from a `voter_data.json` file. 15 | 16 | 3. **Vote Casting** 17 | - Users enter their Voter ID and select a candidate from predefined options. 18 | - The system verifies the voter's registration and voting status before allowing a vote to be cast. 19 | 20 | 4. **Results Display** 21 | - After voting, results show the number of votes each candidate received. 22 | - Results update in real-time as votes are cast. 23 | 24 | 5. **Blockchain Viewing** 25 | - View the blockchain to display each block's details, such as index, timestamp, data (candidate choice), and hash. 26 | - This transparency enhances trust in the voting process. 27 | 28 | 6. **Educational Section** 29 | - A simple explanation of blockchain technology and its application in this system is provided. 30 | 31 | ## How to Use 32 | 33 | 1. **Setup** 34 | - Ensure Python is installed along with required dependencies. 35 | - Run the main script to start the application. 36 | 37 | 2. **Cast Vote** 38 | - Enter a valid Voter ID and choose a candidate to cast a vote. 39 | - Each voter can vote only once. 40 | 41 | 3. **View Results and Blockchain** 42 | - Click on "Show Results" to view the voting outcomes. 43 | - Click on "View Blockchain" to see the chain of blocks and verify each recorded vote. 44 | 45 | ## Usage 46 | 47 | This application serves as a prototype for secure, transparent voting systems. It highlights how blockchain technology can be leveraged to securely manage sensitive data and provide transparent voting records. 48 | 49 | ## ✖️ Disclaimer 50 | 51 | This application is a demonstration and should not be used in real elections without further security and scalability considerations. 52 | # Registration page 53 | ![Screenshot 2024-11-05 150655](https://github.com/user-attachments/assets/c30216c1-5b63-4712-8f11-95951123b17f) 54 | # 55 | # Voting Page 56 | ![Screenshot 2024-11-05 150715](https://github.com/user-attachments/assets/ae10e167-0a3a-4099-85c1-06173735854b) 57 | # 58 | ## ⚙️ Installation 59 | ## Clone the Repository 60 | ```bash 61 | git clone https://github.com/whitehatboy005/Blockchain-Based-Voting-System 62 | cd Blockchain-Based-Voting-System 63 | ``` 64 | ## Install Dependencies 65 | ```bash 66 | pip install -r requirements.txt 67 | ``` 68 | ## Register the voter ID 69 | ```bash 70 | python registration.py 71 | ``` 72 | ## Run the Voting Program 73 | ```bash 74 | python voter.py 75 | ``` 76 | # 77 | ## 📝 License 78 | 79 | This project is licensed under the terms of the [MIT license](LICENSE.md). 80 | 81 | -------------------------------------------------------------------------------- /blockchain.json: -------------------------------------------------------------------------------- 1 | [{"index": 0, "vote": "Genesis Block", "previous_hash": "0"}, {"index": 1, "vote": "Candidate A", "previous_hash": "d894de287307c6e646599a69ef054fe0bf9c157e46d2d396232d320dbe326b3d"}, {"index": 2, "vote": "Candidate B", "previous_hash": "46f23fc92dc9eda8dbca3381488a4300efe57d4ae12aeadf65f21e4d5f54db83"}, {"index": 3, "vote": "Candidate C", "previous_hash": "3c6664d3a7e087e826512b3ea3cdd45cc48a79e7af23e46c4e26ef420bbec2b9"}, {"index": 4, "vote": "Candidate A", "previous_hash": "177d9491fbe38f1ccbe2dce351ef299499c0d592799b8c974b7dbac521ed65f2"}] -------------------------------------------------------------------------------- /registration.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | import tkinter as tk 4 | from tkinter import messagebox, font 5 | 6 | 7 | def hash_voter_id(voter_id): 8 | return hashlib.sha256(voter_id.encode()).hexdigest() 9 | 10 | 11 | def register_voter(voter_id): 12 | voter_id_hash = hash_voter_id(voter_id) 13 | 14 | # Check if the voter ID is already registered 15 | if is_voter_registered(voter_id_hash): 16 | messagebox.showwarning("Registration Error", "This Voter ID is already registered.") 17 | return 18 | 19 | # Create voter info dictionary 20 | voter_info = { 21 | 'voter_id_hash': voter_id_hash 22 | } 23 | 24 | # Append voter info to JSON file 25 | with open('voter_data.json', 'a') as f: 26 | json.dump(voter_info, f) 27 | f.write('\n') 28 | messagebox.showinfo("Success", f"Voter ID {voter_id} registered successfully!") 29 | 30 | 31 | def remove_voter(voter_id): 32 | voter_id_hash = hash_voter_id(voter_id) 33 | 34 | # Load existing voters 35 | voters = load_voter_data() 36 | 37 | # Check if the voter ID exists 38 | if voter_id_hash not in voters: 39 | messagebox.showwarning("Removal Error", "This Voter ID is not registered.") 40 | return 41 | 42 | # Remove the voter ID from the list 43 | voters.remove(voter_id_hash) 44 | 45 | # Write the updated list back to the JSON file 46 | with open('voter_data.json', 'w') as f: 47 | for voter in voters: 48 | json.dump({'voter_id_hash': voter}, f) 49 | f.write('\n') 50 | 51 | messagebox.showinfo("Success", f"Voter ID {voter_id} removed successfully!") 52 | 53 | 54 | def is_voter_registered(voter_id_hash): 55 | voters = load_voter_data() 56 | return voter_id_hash in voters 57 | 58 | 59 | def load_voter_data(): 60 | voters = [] 61 | try: 62 | with open('voter_data.json', 'r') as f: 63 | # Check if the file is empty 64 | if f.readable(): 65 | f.seek(0) # Go back to the start of the file 66 | for line in f: 67 | if line.strip(): # Check if the line is not empty 68 | voter_info = json.loads(line.strip()) 69 | voters.append(voter_info['voter_id_hash']) # Append only the voter ID hash 70 | except FileNotFoundError: 71 | return [] 72 | except json.JSONDecodeError: 73 | messagebox.showerror("Data Error", "Voter data file is corrupted or contains invalid JSON.") 74 | return voters 75 | 76 | 77 | def register(): 78 | voter_id = id_entry.get() 79 | 80 | if not voter_id: 81 | messagebox.showwarning("Input Error", "Please fill in the Voter ID.") 82 | else: 83 | register_voter(voter_id) 84 | id_entry.delete(0, tk.END) 85 | 86 | 87 | def remove(): 88 | voter_id = id_entry.get() 89 | 90 | if not voter_id: 91 | messagebox.showwarning("Input Error", "Please fill in the Voter ID.") 92 | else: 93 | remove_voter(voter_id) 94 | id_entry.delete(0, tk.END) 95 | 96 | 97 | # Set up the GUI 98 | app = tk.Tk() 99 | app.title("Voter Registration") 100 | app.geometry("400x300") 101 | app.configure(bg="#f0f0f0") 102 | 103 | # Custom font for labels and buttons 104 | custom_font = font.Font(family="Helvetica", size=12, weight="bold") 105 | 106 | # Create and place widgets 107 | tk.Label(app, text="Voter ID:", bg="#f0f0f0", font=custom_font).pack(pady=10) 108 | id_entry = tk.Entry(app, font=custom_font) 109 | id_entry.pack(pady=10) 110 | 111 | register_button = tk.Button(app, text="Register", command=register, bg="#4CAF50", fg="white", font=custom_font) 112 | register_button.pack(pady=10, padx=20, fill='x') 113 | 114 | remove_button = tk.Button(app, text="Remove Voter ID", command=remove, bg="#f44336", fg="white", font=custom_font) 115 | remove_button.pack(pady=10, padx=20, fill='x') 116 | 117 | # Add a footer label 118 | footer_label = tk.Label(app, text="Voter Registration System", bg="#f0f0f0", font=font.Font(size=10)) 119 | footer_label.pack(side="bottom", pady=15) 120 | 121 | app.mainloop() 122 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tk-tools 2 | -------------------------------------------------------------------------------- /voter.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | import datetime 4 | import tkinter as tk 5 | from tkinter import messagebox 6 | from tkinter import ttk 7 | 8 | 9 | class Block: 10 | def __init__(self, index, previous_hash, timestamp, data): 11 | self.index = index 12 | self.previous_hash = previous_hash 13 | self.timestamp = timestamp 14 | self.data = data 15 | self.hash = self.calculate_hash() 16 | 17 | def calculate_hash(self): 18 | block_string = f"{self.index}{self.previous_hash}{self.timestamp}{json.dumps(self.data)}" 19 | return hashlib.sha256(block_string.encode()).hexdigest() 20 | 21 | 22 | class Blockchain: 23 | def __init__(self): 24 | self.chain = [] 25 | self.voters = {} 26 | self.candidate_votes = {} 27 | self.create_genesis_block() 28 | 29 | def create_genesis_block(self): 30 | genesis_block = Block(0, '0', datetime.datetime.now(), "Genesis Block") 31 | self.chain.append(genesis_block) 32 | 33 | def add_voter(self, voter_id_hash): 34 | self.voters[voter_id_hash] = False # Store the hash as a key and set voting status to False 35 | 36 | def cast_vote(self, voter_id, candidate): 37 | voter_id_hash = hashlib.sha256(voter_id.encode()).hexdigest() # Hash the voter ID for comparison 38 | if voter_id_hash in self.voters: 39 | if self.voters[voter_id_hash]: 40 | raise Exception("This voter has already voted.") 41 | self.voters[voter_id_hash] = True # Mark the voter as having voted 42 | self.candidate_votes[candidate] = self.candidate_votes.get(candidate, 0) + 1 43 | index = len(self.chain) 44 | previous_hash = self.chain[-1].hash 45 | timestamp = datetime.datetime.now() 46 | data = { 47 | 'vote': candidate # Only include the candidate voted for 48 | } 49 | new_block = Block(index, previous_hash, timestamp, data) 50 | self.chain.append(new_block) 51 | return 52 | raise Exception("Voter not registered.") 53 | 54 | def show_results(self): 55 | results = "" 56 | for candidate, votes in self.candidate_votes.items(): 57 | results += f"{candidate}: {votes} votes\n" 58 | return results.strip() if results else "No votes cast yet." 59 | 60 | def get_chain_data(self): 61 | chain_data = [] 62 | for block in self.chain: 63 | chain_data.append({ 64 | 'Index': block.index, 65 | 'Previous Hash': block.previous_hash, 66 | 'Timestamp': block.timestamp, 67 | 'Data': block.data, # Data now only contains the candidate vote 68 | 'Hash': block.hash 69 | }) 70 | return chain_data 71 | 72 | 73 | class VotingApp: 74 | def __init__(self, master): 75 | self.master = master 76 | self.blockchain = Blockchain() 77 | self.registered_voters = self.load_voter_data() 78 | 79 | for voter_id_hash in self.registered_voters: 80 | self.blockchain.add_voter(voter_id_hash) 81 | 82 | # Predefined candidate names 83 | self.candidates = ["Candidate A", "Candidate B", "Candidate C"] 84 | 85 | self.master.title("Voting System") 86 | self.master.geometry("400x400") 87 | self.master.configure(bg="#f0f8ff") # Light background color 88 | 89 | tk.Label(master, text="Enter your Voter ID:", bg="#f0f8ff", font=("Arial", 12)).pack(pady=10) 90 | self.voter_id_entry = tk.Entry(master, font=("Arial", 12), width=25) 91 | self.voter_id_entry.pack(pady=5) 92 | 93 | tk.Label(master, text="Select candidate:", bg="#f0f8ff", font=("Arial", 12)).pack(pady=10) 94 | self.candidate_combobox = ttk.Combobox(master, values=self.candidates, font=("Arial", 12)) 95 | self.candidate_combobox.pack(pady=5) 96 | 97 | self.vote_button = tk.Button(master, text="Cast Vote", command=self.cast_vote, bg="#4CAF50", fg="white", font=("Arial", 12)) 98 | self.vote_button.pack(pady=20) 99 | 100 | self.results_button = tk.Button(master, text="Show Results", command=self.show_results, bg="#2196F3", fg="white", font=("Arial", 12)) 101 | self.results_button.pack(pady=5) 102 | 103 | self.view_blockchain_button = tk.Button(master, text="View Blockchain", command=self.view_blockchain, bg="#FF9800", fg="white", font=("Arial", 12)) 104 | self.view_blockchain_button.pack(pady=5) 105 | 106 | self.explanation_button = tk.Button(master, text="How Blockchain Works", command=self.show_explanation, bg="#9C27B0", fg="white", font=("Arial", 12)) 107 | self.explanation_button.pack(pady=5) 108 | 109 | def cast_vote(self): 110 | voter_id = self.voter_id_entry.get() 111 | candidate = self.candidate_combobox.get() 112 | 113 | if not voter_id or not candidate: 114 | messagebox.showwarning("Input Error", "Please fill in all fields.") 115 | return 116 | 117 | try: 118 | self.blockchain.cast_vote(voter_id, candidate) 119 | messagebox.showinfo("Success", "Vote cast successfully!") 120 | self.voter_id_entry.delete(0, tk.END) 121 | self.candidate_combobox.set('') # Clear selection 122 | except Exception as e: 123 | messagebox.showwarning("Error", str(e)) 124 | 125 | def show_results(self): 126 | results = self.blockchain.show_results() 127 | messagebox.showinfo("Voting Results", results) 128 | 129 | def view_blockchain(self): 130 | chain_data = self.blockchain.get_chain_data() 131 | blockchain_info = "" 132 | for block in chain_data: 133 | blockchain_info += (f"Index: {block['Index']}\n" 134 | f"Previous Hash: {block['Previous Hash']}\n" 135 | f"Timestamp: {block['Timestamp']}\n" 136 | f"Data: {block['Data']}\n" 137 | f"Hash: {block['Hash']}\n\n") 138 | if not blockchain_info: 139 | blockchain_info = "The blockchain is empty." 140 | messagebox.showinfo("Blockchain Information", blockchain_info) 141 | 142 | def show_explanation(self): 143 | explanation = ( 144 | "How Blockchain Works:\n\n" 145 | "1. A block contains data, a timestamp, and a hash of the previous block.\n" 146 | "2. Each block is linked to the previous one, forming a chain.\n" 147 | "3. Once data is recorded in a block, it cannot be altered without changing all subsequent blocks.\n" 148 | "4. This structure ensures transparency and security, making it tamper-proof.\n" 149 | "5. In the context of voting, this means every vote is securely recorded and cannot be changed." 150 | ) 151 | messagebox.showinfo("Blockchain Explanation", explanation) 152 | 153 | def load_voter_data(self): 154 | voters = [] 155 | try: 156 | with open('voter_data.json', 'r') as f: 157 | for line in f: 158 | voter_info = json.loads(line.strip()) 159 | voters.append(voter_info['voter_id_hash']) # Append only the voter ID hash 160 | except FileNotFoundError: 161 | return [] 162 | return voters 163 | 164 | 165 | if __name__ == "__main__": 166 | root = tk.Tk() 167 | app = VotingApp(root) 168 | root.mainloop() 169 | -------------------------------------------------------------------------------- /voter_data.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whitehatboy005/Blockchain-Based-Voting-System/290ccdd6347693b77960f02bb620da4d141c88a4/voter_data.json --------------------------------------------------------------------------------