Sample code for block chain voting

We could solve any voting issues by simply creating a blockchain for voting.

It would be secure, verifiable, and results available in real time.

Here is a simple example using python.

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) # Genesis block

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,
    }
    self.current_votes = []  # Reset current votes
    self.chain.append(block)
    return block

def add_vote(self, voter_id, candidate):
    self.current_votes.append({
        'voter_id': voter_id,
        'candidate': candidate,
    })
    return self.last_block['index'] + 1

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

@property
def last_block(self):
    return self.chain[-1]

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

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

Create a blockchain instance

blockchain = Blockchain()

Simulate adding votes

blockchain.add_vote(“voter1”, “candidateA”)
blockchain.add_vote(“voter2”, “candidateB”)

Mining a new block

last_proof = blockchain.last_block[‘proof’]
proof = blockchain.proof_of_work(last_proof)
previous_hash = blockchain.hash(blockchain.last_block)
blockchain.create_block(proof, previous_hash)

Print the blockchain

print(json.dumps(blockchain.chain, indent=2))

Leave Comment