CRYPTOGRAPHY PROJECT 1
A REPORT
ON
BLOCKCHAIN BASED VOTING SYSTEM
BY
Names of the Student ID.No
Gaddam Abhishek Reddy 2017A7PS0222P
Sankeerth Nalam 2017A7PS0070P
BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE, PILANI
(October 2019)
CRYPTOGRAPHY PROJECT 2
Abstract
This report briefly explains the technology of Blockchain, and it’s a unique approach to
establish trust and privacy. Then we move on to the traditional Election process, where we will
briefly discuss various phases in the process. Later we discuss the statement of our project, the
execution of our system, a brief explanation of decentralised application and its working is
provided. Then we discussed the strategies involved in our project and list out the benefits of our
project. At last, we submitted our code files in the appendix and concluded our report.
Keywords: Dapp, Ethereum, Smart Contact, Truffle, Web3
CRYPTOGRAPHY PROJECT 3
Table of Contents
Abstract……………………………………………………………………………………2
1. Introduction….………………………………………………………………………….4
1.1 What is Blockchain…………………………………………………………………..4
1.2 Ethereum……………………………………………………………………………..5
1.3 Election Process……………………………………………………………………...5
2. Implementation……...………………………………………………………………….6
2.1 Proposed Solution……………………………………………………………………6
2.1.1 Working of Decentralised Application………………………………………….7
2.1.2 Execution………………………………………………………………………..7
2.2 Benefits………………………………………………………………………………8
3. Progress…………………………………………………………………………………9
4. Work Left……………………………………………………………………………….10
5. Conclusion………………………………………………………………………………10
6. Appendix………………………………………………………………………………..11
6.1 Smart Contract
6.2 Index.html
6.3 App.js
6. References………………………………………………………………………………17
CRYPTOGRAPHY PROJECT 4
1. Introduction
Internet is the greatest thing invented by humanity. But there are some flaws on the
internet. Consider a situation where you are depositing money or casting a vote, there is a single
point of authority, and we are supposed to believe him/her with our data/money/vote. The
limitation of the present system is a single point of control/failure. The Authority may or may not
be telling the truth or corrupted. The solution to this is to employ a decentralised and distributed
system where the consensus of the users/peers is used to evaluate the transactions./votes/data.
1.1 What is Blockchain
A blockchain is a collection of blocks linked together with chains using cryptography.
Here the data is divided into blocks and linked together. Each block is associated with a hash
value(which represents the block), and the link is made possible by listing the hash of the
previous block into the current block. To summarise a block consists of the data section, hash,
previous hash.
Now the created chain of blocks doesn’t get stored in a single computer. All the users
have there own copy of the blockchain which known as Distributed Ledger. If someone tries to
tamper with the data, the hash value gets changed, and the link is broken. To make the attempt
successful, the attacker needs to change and recalculate the hashes of subsequent blocks.
Each block, when created, is curated by the users and based on their consensus, and the
block may be added or rejected. Hence the blockchains provide Security, Immutability,
Transparency.
There are three main types of blockchains in practice; they are Public, Private and
Consortium Blockchains.
CRYPTOGRAPHY PROJECT 5
Three Parts of Blockchain
A blockchain can be studied as a database that is distributed across its users. The essential
requirements of a blockchain are Peer to Peer networking, Asymmetric Cryptography, Hashing.
1.2 Ethereum
Ethereum is an open-source, public blockchain network. It is widely used in several
fields. It is launched in 2015 and became the world’s leading programmable blockchain. It
follows the Proof of Work (POW) Consensus technique to validate the blocks. A smart contract
is a piece of code lying on the block, which is used to make decisions/transactions. Ethereum
uses Solidity Programming Language to write its Smart Contracts.
Ehtereum has a native cryptocurrency called Ether (ETH) which is similar to a Bitcoin.
Being a programmable blockchain, many developers can use this blockchain service in their
applications.
Smart Contracts (Piece of code on blocks) are executed in every node of the chain, which
is tied with a lot of computation and usage of energy. So to perform or deploy the contract, a cost
is associated with it, called Gas. In general, it is expensive and slow to execute on the shared
network than to perform in a traditional setup.
1.3 Election Process
The election is a formal way of making decisions. A democratic society has its
foundations from voting. Elections are powerful as they are the deciding factors for the fate of an
organisation/country. The question of Transparency and Security is still unanswered.
CRYPTOGRAPHY PROJECT 6
Traditional elections use a centralised system where a body is trusted to conduct and
manage the whole process. Some problems with this structure are the administrative authority
may be compromised, tampered may be occurred.
• Administrator – Manages and conducts the election
• Candidate – Participant in the election
• Voter – Person who is entitled to vote
The fundamental principles of voting are Secret Ballot, One Vote for Each, Eligibility,
Accuracy, Reliability. These principles ensure that our vote remains secret and untampered.
In general, the admin creates the election. Nomination takes place; eligible candidates
apply for the position. Voting begins, eligible voters are allowed to cast their votes. All the votes
are evaluated, and results are announced. In further sections, we will apply the knowledge of
blockchain to transform this traditional process.
2. Implementation
We prefer the Ethereum environment for development because it provides a wide range
of uses with the power of smart contracts, whereas bitcoin provides only coin transaction. To
revolutionalise the traditional elections, we should solve the problems of transparency,
authentication, and no one should be able to change the vote cast.
2.1 Proposed Solution
Now, we know that a blockchain is a permanent set of transactions that are distributed
over the network. We can make the votes tamperproof. We will be making a client-side app that
CRYPTOGRAPHY PROJECT 7
will communicate with our blockchain using web3.js, which consists of a clean interface to cast a
vote.
2.1.1 Working of Decentralised Application
A traditional web application has server-side and user/client-side. All the server-side code
and database lies on a single computer. Your data stored in your account may have tampered.
Instead of having a server and database, we can use a blockchain service.
A Decentralised application is an app where the server-side is distributed over a chain of
nodes. Now your server-side is termed as Smart Contract(Piece of code). Ethereum has a vast
number of tools to help create dapps. For our application development, we use node.js with
Truffle framework, which helps with testing and other tools. For accessing the blockchain we
need a service, We use Azure Blockchain Workbench for this purpose. To perform any
transactions, we need to have a wallet or called a dapp browser. For this purpose, we use
metamask extension(allows us to use ether or gas for transactions).
2.1.2 Execution
• First, we will setup up our environment, install the dependencies required such as
node.js, truffle, blockchain network(Ganache or Azure Blockchain Workbench),
metamask.
• Now we unbox a basic truffle box, no this will create a basic directory structure for
our smart contracts, migrations(for deploying the smart contracts and changing the
state of our blockchain), client-side code and truffle.js configuration file.
CRYPTOGRAPHY PROJECT 8
• Now we start writing our contract(written in solidity language) Election.sol. Initially,
we will model a Candidate inside the Election.sol file. A candidate has an Id, Name,
Vote Count. No we will create some functions such as createCandidate(string _name),
Vote(uint _candidateId).
• Now we finish off by writing the client-side application of this project. It consists of
two files, one for HTML and the other with Web3.js including Render function.
Firstly create a basic HTML file which displays the candidates with respective
buttons and Voter account number. It should also display the transaction number after
casting a vote. Secondly, the app.js file has three parts in it: Set up web3, initialise
the contract, displaying the contents of contract and voter details to the client-side
portal and taking the client-side info back to the contract.
2.2 Benefits
Blockchain is distributed to all of the users connected to it. Hence the entire data is
available with every single user of the network. This eliminates the problem of transparency.
Blockchain uses cryptography to digitally sign and create the hashes for the blocks. It
Proof of Work consensus system makes it difficult to alter the records. Hence it is practically
immutable, solving the fear of tampering and verification of the vote.
Privacy, One Vote for each, Verifiability, Accuracy are all satisfied with the blockchain
without a need for a central authority.
CRYPTOGRAPHY PROJECT 9
3. Progress
The learning requirement for this project is very high. We completed the learning basics of
solidity and JavaScript (web3.js and node.js). We managed to complete the project with a local
testing blockchain (Ganache). The code files are attached in the appendix of this report.
Figure 1: Election Home Page
Figure 2: Metamask Confirmation Figure 3: Transaction Complete
CRYPTOGRAPHY PROJECT 10
4. Work Left
A lot of work has been completed, yet still, some refinement is required. The remaining
work to be done is listed below:
• Remove bugs in the client-side application (Front-end part of the app).
• As of now, we are using a local blockchain (Ganache) for testing purpose; we are
looking to upgrade to Azure Blockchain service.
• Customise the client-side application for electing more roles.
5. Conclusion
Online is the future of the world, and we know that voting is heading into this trajectory.
To make this transition a robust and reliable one, we must incorporate Blockchain. It can solve
the problems we face in the electoral system. The ledger, consensus system makes the blockchain
a unique concept which needs expertise from a vast number of fields and domains for the
research and development of it. What we are going to build requires users/voters to be connected
onto the ethereum network, Hence scaling this to a huge extent can be difficult. Some drawbacks
of the blockchain are scalability, substantial cost associated with it. We will be submitting our
project within few days for remarks and opinions.
6. Appendix
6.1 Smart Contract
pragma solidity 0.5.11;
contract Election {
CRYPTOGRAPHY PROJECT 11
struct Candidate {
uint id;
string name;
uint voteCount;
}
mapping(address => bool) public voters;
mapping(uint => Candidate) public candidates;
uint public candidatesCount;
event votedEvent (
uint indexed _candidateId
);
constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate (string memory _name) private {
candidatesCount ++;
candidates[candidatesCount] = Candidate(candidatesCount
, _name, 0);
}
function vote (uint _candidateId) public {
// require that they haven't voted before
require(!voters[msg.sender],'Voter already voted');
// require a valid candidate
require(_candidateId > 0 && _candidateId <= candidatesC
ount, 'Candidate not Present');
voters[msg.sender] = true;
candidates[_candidateId].voteCount ++;
emit votedEvent(_candidateId);
}
}
CRYPTOGRAPHY PROJECT 12
6.2 Index HTML Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>Election Results</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="width: 650px;">
<div class="row">
<div class="col-lg-12">
<h1 class="text-center">Election Results</h1>
<hr/>
<br/>
<div id="loader">
<p class="text-center">Loading...</p>
</div>
<div id="content" style="display: none;">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="candidatesResults">
</tbody>
</table>
<hr/>
<form onSubmit="App.castVote(); return false;">
CRYPTOGRAPHY PROJECT 13
<div class="form-group">
<label for="candidatesSelect">Select Candidate<
/label>
<select class="form-
control" id="candidatesSelect">
</select>
</div>
<button type="submit" class="btn btn-
primary">Vote</button>
<hr />
</form>
<p id="accountAddress" class="text-center"></p>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1
.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
6.3 App.js File
App = {
web3Provider: null,
contracts: {},
account: '0x0',
hasVoted: false,
init: function() {
CRYPTOGRAPHY PROJECT 14
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
ethereum.enable();
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http:
//localhost:7545');
web3 = new Web3(App.web3Provider);
ethereum.enable();
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact
App.contracts.Election = TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider);
App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
listenForEvents: function() {
App.contracts.Election.deployed().then(function(instance) {
CRYPTOGRAPHY PROJECT 15
instance.votedEvent({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function(error, event) {
console.log("event triggered", event)
// Reload when a new vote is recorded
App.render();
});
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load account data
web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
// Load contract data
App.contracts.Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(candidatesCount) {
var candidatesResults = $("#candidatesResults");
candidatesResults.empty();
var candidatesSelect = $('#candidatesSelect');
CRYPTOGRAPHY PROJECT 16
candidatesSelect.empty();
for (var i = 1; i <= candidatesCount; i++) {
electionInstance.candidates(i).then(function(candidate)
{
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>"
+ name + "</td><td>" + voteCount + "</td></tr>"
candidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption = "<option value='" + id + "' >"
+ name + "</ option>"
candidatesSelect.append(candidateOption);
});
}
return electionInstance.voters(App.account);
}).then(function(hasVoted) {
// Do not allow a user to vote
if(hasVoted) {
$('form').hide();
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
},
castVote: function() {
var candidateId = $('#candidatesSelect').val();
App.contracts.Election.deployed().then(function(instance) {
CRYPTOGRAPHY PROJECT 17
return instance.vote(candidateId, { from: App.account });
}).then(function(result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
}).catch(function(err) {
console.error(err);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
4. References
• Ethereum Basics: https://medium.com/@mattcondon/getting-up-to-speed-on-
ethereum-63ed28821bbe
• Voting: https://medium.com/coinmonks/voting-on-a-blockchain-how-it-works-
3bb41582f403
• Truffle: https://www.trufflesuite.com/docs/truffle/quickstart
• Solidity: https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html