Chapter 1: Introduction

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

CHAPTER 1: INTRODUCTION

In every democracy, the security of an election is a matter of national security. The


computer security field has for a decade studied the possibilities of electronic voting
systems with the goal of minimizing the cost of having a national election, while
fulfilling and increasing the security conditions of an election. From the dawn of
democratically electing candidates, the voting system has been based on pen and paper.
Replacing the traditional pen and paper scheme with a new election system is critical to
limit fraud and having the voting process traceable and verifiable. Electronic voting
machines have been viewed as flawed, by the security community, primarily based on
physical security concerns. Anyone with physical access to such machine can sabotage
the machine, thereby affecting all votes cast on the aforementioned machine. Enter
blockchain technology. A blockchain is distributed immutable, incontrovertible, public
ledger. This new technology works through four main features:

 The ledger exists in many different locations: No single point of failure in the
maintenance of the distributed ledger.
 There is distributed control over who can append new transactions to the ledger.
 Any proposed “new block” to the ledger must reference the previous version of
the ledger, creating an immutable chain from where the blockchain gets its
name, and thus preventing tampering with the integrity of previous entries.

The blockchain technology was introduced in 2008 when Satoshi Nakamoto created
the first crypto currency called Bit-coin. The Bitcoin blockchain technology uses a
decentralized public ledger combined with PoW(Proof-of-Work) based stochastic
consensus protocol, with financial incentives to record a totally ordered sequence of
blocks, the blockchain. The chain is replicated, cryptographically signed and publicly
verifiable at every transaction so that no-one can tamper with the data that has been
written onto the blockchain. The blockchain structure is an append-only data structure,
such that new blocks of data can be written to it, but cannot be altered or deleted The
blocks are chained in such a way that each block has a hash that is a function of the
previous block, providing the assurance of immutability.

1
1.1 GOALS AND OBJECTIVES
The blockchain is a shared, programmable, cryptographically secure and therefore trusted
ledger which no single user controls and which can be inspected by anyone. A blockchain
is a permanent record of transactions (votes) that are distributed, every vote can
irrefutably be traced back to exactly when and where it happened without revealing the
voter’s identity. In addition, past votes cannot be changed, while the present can’t be
hacked, because every transaction is verified by every single node in the network. And
any outside or inside attacker must have control of 51% of the nodes to alter the record.

1.2 PROJECT SCOPE


A great decentralized application utilizing blockchain technology allows you perform
the same actions you would today (like transferring money) without a trusted third
party. The best dApps have a specific real world use-case that leverages the unique
characteristics of blockchain.

1.3 SOFTWARE CONTEXT


Smart Contracts act as the back-end logic and storage. A contract is written in Solidity,
a smart contract language, and is a collection of code and data that resides at a specific
address on the Ethereum blockchain. It’s very similar to a class in Object Oriented
Programming, where it includes functions and state variables. Smart Contracts, along
with the Blockchain, are the basis of all Decentralized Applications. They are, like
Blockchain, immutable and distributed, which means upgrading them will be a pain if
they are already on the Ethereum Network.

1.4 PROBLEM STATEMENT


The applications built on Ethereum public blockchain is immense, and the possibilities
are limitless. Ethereum builds what is essentially the ultimate abstract foundational
layer: a blockchain with a built-in Turing-complete programming language, allowing
anyone to write smart contracts and decentralized applications where they can create
their own arbitrary rules for ownership, transaction formats and state transition
functions. We intend to build a similar decentralized application that solves the issue of
digital voting by leveraging blockchain technology.

2
CHAPTER 2: MOTIVATION

2.1 TRADITIONAL VOTING


One basic principle of a democracy is an equal and fair voting system: eligible voters
are allowed to freely vote for their favorable party or candidate. This is one of the
pillars of our political system and therefore needs to be guaranteed in a democracy.

Some Problems in Parliamentary Elections

Democracy and voting are great ideas, but the classical paper ballots are prone to fraud;
ballots can be counted incorrectly or ballots sent via mail might get lost in transit. To
show examples for failure or fraud, we focus for this list on the parliamentary elections
from Germany in 2005, because they are well documented. Examples are:

 First counting in Bochum-Langendreer marked 491 of 689 votes as invalid. Two


minor parties were announced as the strongest in this district. After recounting
the ballots, only 13 ballots were marked as invalid. A different, third party
became strongest party.

 In one state the ballots were not correctly assigned to the parties, which led to a
bad result for a small party.

 Paper ballots sent via postal mail take a long time until they are tallied.
Observations showed that even ten days might not be sufficient to re quest and
send the ballot back before the election ends.

 An external company was delegated to distribute paper ballots for one city.
Unfortunately, they sent 50,000 ballots to the wrong recipients. Due to this
error 10,533 ballots became invalid.

 These are only a few examples for potential problems with traditional paper
voting and they are not the only exceptions. This does not mean that all
elections are compromised or completely insecure.

3
High Cost

Another factor are the costs of an election. We focus on the numbers from Germany
again.
The parliamentary election for the Bundestag in 2009 did cost about 67 million Euros
in total. Cities with less than 100,000 eligible voters received 0.48 Euro per voter, big-
ger cities even 0.74 Euro [The11]. Additionally, volunteers, who support an election,
received another monetary compensation for their help. This is a massive amount of
money being normally spent every parliamentary election.

One possible solution to reduce the costs and to optimize the general voting process is
the usage of computers.

2.2 ELECTRONIC VOTING SYSTEMS


As technology evolves, it is obvious to consider about using computers for elections. In
this thesis we will focus on decentralization voting systems, which we define as
systems using the Internet to realize political elections. To access these voting systems,
each eligible voter can use her own device, for example personal computer,
smartphone or tablet. These systems will also secure and anonymize the ballots to
ensure the election, which fulfills the democratic rights of each citizen. We take a
further look at these requirements and constructions in the next chapters.

Electronic voting systems attempt to be as easy to use and secure as ideal traditional
elections and attempt to eliminate the human errors described in 1.1. This is hard to
achieve, because electronic voting systems need a strong encryption to guarantee
security, integrity and anonymity of the vote. This must be ensured and still result in a
user-friendly application, which is often hard to achieve.
But to assume that traditional elections are completely secure and correct is also
questionable, as we already showed in section 1.1. So, this is a good opportunity to
think about reinventing elections with the help of computers and cryptography.

One of the main advantages of electronic voting systems is the chance to call a
completely verifiable election, which means that all voters are able to verify if their
vote was properly counted and even that the complete election was properly tallied.
Some countries use dedicated voting machines, which are used to place votes in polling
stations. These voting machines are exclusively used for the voting process and can
either tally the votes electronically or create strips of papers with the voter's choice,
which must later be tallied. Usually, it is not possible to verify tallying steps of these
black boxes, because the companies do not provide details about the implementation of

4
their machines; only the main developers have access to the source code and know in
detail, how these machines operate.
After an analysis of 74 voting machines, the Chaos Computer Club (CCC), which is
Europe's largest association of hackers, summarized their results with one short quote:

“Trust is a good thing, control not possible”

The CCC observed in 2006 a pilot project in Cottbus, Germany, where voting
machines were used. They explained in their analysis of this election that with these
issues in security and verifiability, voting machines should be banned and not be used
in any election. Missing verifiability led to the prohibition of current voting machines
for elections in Germany. As long as the essential steps of the voting process are not in
public verifiable by a typical citizen, voting machines are forbidden in parliamentary
elections [The09]. These are also the reasons why we do not consider voting machines
in this thesis.

Electronic Voting Systems in the Real World


Some governments already implemented electronic voting systems and use them for
par-limitary elections. For example Estonia has several years of experience in this field
and successfully uses electronic voting for all of their elections. Other projects encoun-
tered, but they all had big security issues and were often cancelled. That the Estonian
electronic voting system is still being used in practice does not mean that this voting
system is secure. We will analyze it in section.

We feel confident that many countries will use electronic vot ing systems in the future
to realize their elections, because this technology could heavily improve the voting
process. Therefore, it is essential to analyze existing systems, learn from their
experiences and try to solve the issues which emerged during their trials, which is the
core of this thesis. We also describe basic approaches to realize a voting system with
clients and servers and give a brief view into a peer-to-peer approach using the
blockchain.

2.3 STRUCTURE
In chapter 2 we define the preliminaries and requirements of a n election. This also
includes some assumptions we had to include to realize a voting system. Since
security, anonymity and integrity must be guaranteed by computers, we have to use
cryptography to solve these issues. The cryptographic primitives used by many voting
systems are described.

5
CHAPTER 3: DESIGN

3.1 DECENTRALIZED SYSTEM

Figure 3.1 : (Decentralized System)

One of the most exciting aspects of blockchain technology is that it is entirely


decentralized, rather than stored in one central point. This removes the need for
powerful central authorities and instead hands control back to the individual user. Here
we will examine how this system works, what it means for our future and why it is so
revolutionary. The decentralized nature of blockchain technology means that it doesn’t
rely on a central point of control. A lack of a single authority makes the system fairer
and considerably more secure. The way in which data is recorded onto a blockchain
epitomizes its most revolutionary quality: its value of decentralization. Rather than
relying on a central authority to securely transact with other users, blockchain utilizes
innovative consensus protocols across a network of nodes, to validate transactions and
record data in a manner that is incorruptible. As a blockchain is a ledger of information
it is extremely important that the information being stored is honest and accurate. As
the system does not rely on a central authority, the fees that are normally collected by
these organisations are no longer a factor.

6
3.2 BLOCKCHAIN

A blockchain is, in the simplest of terms, a time-stamped series of immutable record of


data that is managed by cluster of computers not owned by any single entity. Each of
these blocks of data (i.e. block) are secured and bound to each other using
cryptographic principles (i.e. chain).So, what is so special about it and why are we
saying that it has industry disrupting capabilities The blockchain network has no
central authority it is the very definition of a democratized system. Since it is a shared
and immutable ledger, the information in it is open for anyone and everyone to see.
Hence, anything that is built on the blockchain is by its very nature transparent and
everyone involved is accountable for their actions.

Figure 3.2 : (BLOCKCHAIN)

A blockchain carries no transaction cost. (An infrastructure cost yes, but no transaction
cost.) The blockchain is a simple yet ingenious way of passing information from A to
B in a fully automated and safe manner. One party to a transaction initiates the process
by creating a block. This block is verified by thousands, perhaps millions of computers
distributed around the net. The verified block is added to a chain, which is stored
across the net, creating not just a unique record, but a unique record with a unique
history. Falsifying a single record would mean falsifying the entire chain in millions of
instances. That is virtually impossible. Bitcoin uses this model for monetary
transactions, but it can be deployed in many others ways.

7
3.3 ETHEREUM

Ethereum is an open software platform based on blockchain technology that enables


developers to build and deploy decentralized applications. Ethereum is a distributed
public blockchain network. Although there are some significant technical differences
between the two, the most important distinction to note is that Bitcoin and Ethereum
differ substantially in purpose and capability. Bitcoin offers one particular application
of blockchain technology, a peer to peer electronic cash system that enables online
Bitcoin payments. While the Bitcoin blockchain is used to track ownership of digital
currency (bitcoins), the Ethereum blockchain focuses on running the programming
code of any decentralized application.In the Ethereum blockchain, instead of mining
for bitcoin, miners work to earn Ether, a type of crypto token that fuels the network.
Beyond a tradeable cryptocurrency, Ether is also used by application developers to pay
for transaction fees and services on the Ethereum network. There is a second type of
token that is used to pay miners fees for including transactions in their block, it is
called gas, and every smart contract execution requires a certain amount of gas to be
sent along with it to entice miners to put it in the blockchain.

Figure 3.3 : (ETHEREUM)

8
3.3.1 SMART CONTRACT

Smart contract is just a phrase used to describe a computer code that can facilitate the
exchange of money, content, property, shares, or anything of value. When running on
the blockchain a smart contract becomes like a self-operating computer program that
automatically executes when specific conditions are met. Because smart contracts run
on the blockchain, they run exactly as programmed without any possibility of
censorship, downtime, fraud or third-party interference.

Figure 3.3.1 : (Smart Contract)

3.3.2 ELECTION ROLES AND PROCESS

Figure 3.3.2 : Election roles and process

9
3.3.3 DECENTRALIZED VOTING SYSTEM STRUCTURE

BROWSER

Front End
HTML , CSS,JS

Node

Node Node

Smart Contract
Node
Block Chain
Ledger

Figure 3.3.3 : Decentralized Voting System Structure

10
3.3.4 USE CASE DIAGRAM

A use case diagram is a dynamic or behavior diagram in UML. Use case diagrams
model the functionality of a system using actors and use cases. Use cases are a set of
actions, services, and functions that the system needs to perform. In this context, a
"system" is something being developed or operated, such as a web site. The "actors"
are people or entities operating under defined roles within the system.

Basic Use Case Diagram Symbols and Notations


System
Draw your system's boundaries using a rectangle that contains use cases. Place actors
outside the system's boundaries.

Use Case
Draw use cases using ovals. Label the ovals with verbs that represent the system's
functions.

Actors
Actors are the users of a system. When one system is the actor of another system, label
the actor system with the actor stereotype.

Relationships
Illustrate relationships between an actor and a use case with a simple line. For
relationships among use cases, use arrows labeled either "uses" or "extends." A "uses"
relationship indicates that one use case is needed by another in order to perform a task.
An "extends" relationship indicates alternative options under a certain use case.

11
Use Case Diagram For Decentralized Voting System

Figure 3.3.4 : (Use Case Diagram For Decentralized Voting System)

3.3.5 VARIOUS PROCESS VERIFICATION OF THE


VOTERS

Figure 3.3.5: (various process verification of the voters)

12
3.3.6 SYSTEM DATA-FLOW DIAGRAM

Figure 3.3.6 : (SYSTEM DATA-FLOW DIAGRAM)

A data flow diagram (DFD) maps out the flow of information for any process or
system. It uses defined symbols like rectangles, circles and arrows, plus short text
labels, to show data inputs, outputs, storage points and the routes between each
destination. Data flowcharts can range from simple, even hand-drawn process
overviews, to in-depth, multi-level DFDs that dig progressively deeper into how the
data is handled. They can be used to analyse an existing system or model a new one.
Like all the best diagrams and charts, a DFD can often visually “say” things that would
be hard to explain in words, and they work for both technical and nontechnical
audiences, from developer to CEO. That’s why DFDs remain so popular after all these
years. While they work well for data flow software and systems, they are less
applicable nowadays to visualizing interactive, real-time or database-oriented software
or systems.

13
CHAPTER 4 : SOFTWARE USED

4.1 INSTALL ETHEREUM DEPENDENCIES

 NODE JS
 NPM
 TRUFFLE
 METAMASK
 GANACHE
 LITE-SERVER

4.1.1 NODE JS

Figure 4.1.1 : (NODE JS)

Node.js is a JavaScript runtime environment. The Node run-time environment includes


everything you need to execute a program written in JavaScript. Node.js came into
existence when the original developers of JavaScript extended it from something you

14
could only run in the browser to something you could run on your machine as a
standalone application.Now you can do much more with JavaScript than just making
websites interactive. JavaScript now has the capability to do things that other scripting
languages like Python can do.Both your browser JavaScript and Node.js run on the V8
JavaScript runtime engine. This engine takes your JavaScript code and converts it into a
faster machine code. Machine code is low-level code which the computer can run
without needing to first interpret it.

4.1.2 NPM (NODE PACKAGE MANAGER)

Figure 4.1.2 (a) : (NPM)

npm (short for Node.js package manager) is a package manager for


the JavaScript programming language. It is the default package manager for the
JavaScript runtime environment Node.js. It consists of a command line client, also
called npm, and an online database of public and paid-for private packages, called the
npm registry. The registry is accessed via the client, and the available packages can be
browsed and searched via the npm website. The package manager and the registry are
managed by npm.

15
INSTALL NPM

E:\FInal Project> npm install

Figure 4.1.2 (b) : (Check Version of NPM)

4.1.3 TRUFFLE

Truffle is a development environment, testing framework and asset pipeline for


Ethereum, aiming to make life as an Ethereum developer easier. With Truffle, you get:

 Built-in smart contract compilation, linking, deployment and binary


management.
 Automated contract testing with Mocha and Chai.
 Configurable build pipeline with support for custom build processes.
 Scriptable deployment & migrations framework.
 Network management for deploying to many public & private networks.
 Interactive console for direct contract communication.
 Instant rebuilding of assets during development.
 External script runner that executes scripts within a Truffle environment.

INSTALL

> npm install -g truffle

16
Figure 4.1.3 (b) : (TRUFFLE)

4.1.4 METAMASK

MetaMask is a bridge that allows you to visit the distributed web of tomorrow in your
browser today. It allows you to run Ethereum dApps right in your browser without running
a full Ethereum node.

Figure 4.1.4 : (METAMASK)

MetaMask includes a secure identity vault, providing a user interface to manage your
identities on different sites and sign blockchain transactions.

17
4.1.5 GANACHE

 Ganache can use to run tests, execute commands, and inspect state while
controlling how the chain operates.
 Ganache is an ethereum client which one can use for Ethereum development.
 Ganache can use for the development of DAPP and once it is developed and
tested on the ganache you can deploy your DAPP on ethereum client like geth
or parity.

Figure 4.1.5 : (GANACHE)

Ganache allows you to create a private Ethereum blockchain for you to run tests,
execute commands, and inspect state while controlling how the chain operates. It gives
you the ability to perform all actions you would on the main chain without the cost.
Many developers use this to test their smart contracts during development. It provides
convenient tools such as advanced mining controls and a built-in block explorer.

18
4.1.6 LITE – SERVER

 Lightweight development only node server that serves a web app, opens it in
the browser, refreshes when html or javascript change, injects CSS changes
using sockets, and has a fallback page when a route is not found.
 lite-server is a simple customized wrapper around BrowserSync to make it easy
to serve SPAs.
 BrowserSync does most of what we want in a super fast lightweight
development server. It serves the static content, detects changes, refreshes the
browser, and offers many customizations.

Install: > npm i lite-server

Figure 4.1.6 : (LITE - SERVER)

19
CHAPTER 5 : CODING

5.1 FRONT END

Used Languages:

 HTML(Hyper Text Markup Language)

 CSS (Cascading Style Sheet)

 JAVA SCRIPT

 BOOTSTRAP

5.1.1 HTML CODE


<!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">

<!-- The above 3 meta tags *must* come first in the head; any other head content
must come *after* these tags -->

<title>Election Results</title>

<!-- Bootstrap -->

<link href="css/bootstrap.min.css" rel="stylesheet">

<link href="21.css" rel="stylesheet" >

<link href="style.css" rel="stylesheet" >

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media
queries -->

<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->

20
<!--[if lt IE 9]>

<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>

<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>

<![endif]-->

</head>

<body>

<div class="header">

<nav>

<img src="1.jpeg" width="200" height="80">

<ul>

<li><a href="index.html">HOME</a></li>

<li><a href="about.html">ABOUT</a></li>

<li><a href="explain.html">How It Works</a></li>

<li><a href="#">GALLERY</a></li>

<li><a href="#">CONTACT</a></li>

</ul>

</nav>

</div>

<div class="hero-image">

<br><br><br><br>

<div class="container" style="width: 650px;">

<div class="row">

<div class="col-lg-12">

<h1 class="text-center">Election Results</h1>

<hr/>

21
<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;">

<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 />

22
</form>

<p id="accountAddress" class="text-center"></p>

</div>

</div>

</div>

</div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->

<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>

</div>

<div class="box box1">

<h2>Devloped by Project07</h2>

</div>

<div class="box box2">

<h2>Devloped by Project07</h2>

</div>

</body>

</html>

23
5.1.2 CSS CODE
body, html {

height: 100%;

/* The hero image */

.hero-image {

background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("1.jpeg");

/* Set a specific height */

height: 100%;

/* Position and center the image to scale nicely on all screens */

background-position: center;

background-repeat: no-repeat;

background-size: cover;

position: relative;

.header{

position: sticky;

nav{

width: 100%;

height: :80px;

background-color: #0009;

line-height: 80px;

24
nav ul{

float:right;

margin-right: 30px;

nav ul li{

list-style-type: none;

display:inline-block;

transition:0.8s all;

nav ul li a{

text-decoration: none;

color: #fff;

padding:30px;

nav ul li:hover{

background-color: #f39d1a;

5.1.3 JAVASCRIPT CODE


App = {

web3Provider: null,

contracts: {},

account: '0x0',

hasVoted: false,

init: function() {

return App.initWeb3();

25
},

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);

} else {

// Specify default instance if no web3 instance provided

App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');

web3 = new Web3(App.web3Provider);

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

26
listenForEvents: function() {

App.contracts.Election.deployed().then(function(instance) {

// Restart Chrome if you are unable to receive this event

// This is a known issue with Metamask

// https://github.com/MetaMask/metamask-extension/issues/2393

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;

27
$("#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');

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);

});

28
5.1.4 INITIAL MIGRATION CODE

var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {

deployer.deploy(Migrations);

};

5.1.5 DEPLOY CONTRACTS


var Election = artifacts.require("./Election.sol");

module.exports = function(deployer) {

deployer.deploy(Election);

};

5.1.6 CREATE CONTRACTS FOR ELECTIONS


pragma solidity 0.4.25;

contract Election {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}

// Store accounts that have voted


mapping(address => bool) public voters;
// Store Candidates
// Fetch Candidate
mapping(uint => Candidate) public candidates;
// Store Candidates Count
uint public candidatesCount;

// voted event
event votedEvent (
uint indexed _candidateId
);

constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}

function addCandidate (string _name) private {


candidatesCount ++;
candidates[candidatesCount] = Candidate(candidatesCount,
_name, 0);

29
}

function vote (uint _candidateId) public {


// require that they haven't voted before
require(!voters[msg.sender]);

// require a valid candidate


require(_candidateId > 0 && _candidateId <= candidatesCount);

// record that voter has voted


voters[msg.sender] = true;

// update candidate vote Count


candidates[_candidateId].voteCount ++;

// trigger voted event


emit votedEvent(_candidateId);
}
}

5.1.7 CREATE CONTRACTS FOR MIGRATIONS


pragma solidity ^0.4.2;

contract Migrations {
address public owner;
uint public last_completed_migration;

modifier restricted() {
if (msg.sender == owner) _;
}

constructor () public {
owner = msg.sender;
}

function setCompleted(uint completed) public restricted {


last_completed_migration = completed;
}

function upgrade(address new_address) public restricted {


Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}

30
CHAPTER 6 : SNAPSHOTS

6.1 COMPILE CODE

Figure 6.1: (COMPILE CODE)

6.2 RUN CODE

Figure 6.2 : (RUN CODE)

31
6.3 FRONT PAGE

Figure 6.3 (a): (FRONT PAGE)

Figure 6.3 (b): (FRONT PAGE)

32
6.4 ABOUT PAGE

Figure 6.4 : (ABOUT PAGE)

6.5 HOW IT WORKS PAGE

Figure 6.5 : (HOW IT WORKS PAGE)

33
6.6 START METAMASK

Figure 6.6 : (START METAMASK)

34
6.7 SET RPC SERVER

Figure 6.7 : (SET RPC SERVER)

6.8 IMPORT NEW ACCOUNT

Figure 6.8 : (IMPORT NEW ACCOUNT)

35
6.9 VOTE

Figure 6.9 : (VOTE)

6.10 CONFORMATION PAGE

Figure 6.10 : (CONFORMATION PAGE)

36
6.11 RESULT

Figure 6.11 : (RESULT)

6.12 RESOURCES
I know, it’s a lot You might have this article open for a while as you slowly develop this
application and really understand what’s going on. But that’s learning! Please
supplement this guide with all the documentation from Ethereum, Truffle, and what I
have provided below. I’ve tried to hit many of the key points in this article, but it’s just
a brief overview and these resources will help a lot.

 Everything about Solidity and Smart Contracts - I mean Everything

 Everything about Truffle

 Truffle Contracts Docs

 Web3 Javascript API -  this will be great to know and reference, but Truffle
Contracts abstracts many parts of this

 Useful DApp patterns

 Ethereum Docs -  look to the side bar and there’s plenty of stuff

 CryptoKitties Code Explanation -  The writer goes through the important parts of
CryptoKitties’ Smart Contract

 Smart Contract Best Practices -  a must read

37
CHAPTER 7: CONCLUSION

In this thesis we describe and analyze the general structure of the biggest internet
voting systems being used so far. Many countries are involved in the development of
secure electronic voting systems and we could therefore pick the most relevant around
the globe, which were practically used or were supposed to be used in parliamentary
elections. Our analysis starts with the description of the cryptographic primitives over
the complete voting process up to the security flaws each system has.

Each analyzed system is unique in the way it solves the problems of electronic voting.
All aim to be secure, anonymous and trustworthy so that the eligible users are ready to
participate via Internet in the election. With the knowledge we gained during the
analysis of existing systems and their failures, we construct a theoretical end-to-end
verifiable electronic voting system, which fulfills more preliminaries than the real-
world e voting systems from chapter 4. Our system also aims to eliminate many of the
original system's flaws or at least reduce them. The construction chapter can be used as
a template to implement a voting system, which fulfills most of the preliminaries.

Our contribution to this topic is a modified version of the proof-of-stake, which makes
it possible to construct a secure blockchain without needing masses of computational
power to discover the specific hashes needed for the proof-of -work, which are used by
the Bitcoin protocol. This even allows small devices, like smartphones, to participate in
the network to ensure the blockchain's integrity. It can be easily implemented as a
small application, which keeps the voter's device online to work as a full node in the
blockchain-based peer-to-peer voting system. Electronic voting systems should only be
used when there are no concerns about their security. These issues might be solved in
the next years and there are many promising publications in this field, but they are
temporarily not adaptable due to their usability. Building applications on Ethereum is
pretty similar to a regular application calling a backend service. The hardest part is
writing a robust and complete smart contract. I hope this guide helped you understand
the core knowledge of decentralized applications and Ethereum and will help you kick-
start your interest in developing them.

38
If you’d like to build off of what we’ve built, here are some ideas. I’ve actually written
the smart contract in such a way that it’s easily implemented with everything I’ve given
you in this guide.

 Display the party of each Candidate. We already get the party of a


candidatewhen we run getCandidate(id).
 Check if the User-entered ID is unique.

 Ask and store more information about a User, such as their date of birth and
home address.

 Add in an option to see whether a person with a specific id has voted or


not. You would create a new form to enter in an ID, which you would then search
for that certain user in the blockchain.

 Write a new smart contract function that counts the votes for BOTH
candidates at once. Currently, we have to make two separate calls for two
candidates, requiring the contract to loop through all the Users twice.

 Allow new Candidates to be added. This means adding a new form to add
Candidates, but also changing up a little on how we display and vote for candidates
in the frontend.

 Require Users to have an Ethereum Address to vote. My logic for not including
user addresses is because voters wouldn’t be expected to have Ethereum to
participate in this voting process. However, many DApps will require users to have
an Ethereum Address.

Also, here are some tips that could prevent some roadblocks from happening:

 Double and triple check your smart contract functions when something weird is
happening. I spent a couple hours on a bug to figure out that I returned the wrong
value in one of my functions.

 Check whether your URL and port are correct when you connect to your
development blockchain. Remember: 7545 is for truffle develop and 9545 is for

39
Ganache. These are defaults, so if you can’t connect to your blockchain, you
might’ve changed them.
 I didn’t go over this because this guide would’ve been too long and I probably will
make another post on this — but you should test your contracts! It will help a lot.

 If you aren’t familiar with promises, go through how they work and how to use
them. Truffle Contracts uses promises and the beta for web3 will also support
promises. They can, if you do them wrong, mess up a lot of the data you’re
retrieving.

7.1 FUTURE WORK


We described the basic template with cryptographic primitives and building blocks
pro-vided by the best-practices in network security and with already implemented
voting systems. Now, there is still work necessary to a really secure voting system.

7.1.1 SECURE PLATFORM


we assumed that we can trust the voter's computer she is voting with. But many
computers are infected with viruses; some reports say that about 32% of all computers
in the world are infected with viruses and malware. The real numbers do not matter,
but we can be sure that there will always be security issues in our computer systems
and that there might be some viruses attacking the ballots of electronic voting systems
from the voter's computer. So, we have to research how to prevent malicious software
might being able to attack and manipulate electronic voting systems.

7.1.2 PROGRAMMING LANGUAGES AND PARADIGMS


We criticized in subsection that Civitas used Jif in their implementation, which is an
unpopular programming language with only few people being able to use this
language. The Cornell University, who invented Civitas, also developed Jif1, which
extends Java with the support for information flow-control and access con trol. We
should make this an object to analyze other languages and check, if they are more
suitable for security-critical applications, like voting systems. In further research we
should also concern about different programming paradigms, like logical or functional
programming, and try to evaluate, which is the best choice in voting systems.

40
7.1.3 USABILITY ANALYSIS
Several voting schemes have been published, which aim to solve the last issues in
electronic voting. These systems are mostly too complicated or have a very bad
usability experience, like Civitas. This is one reason why they are not successful and
are not used for real-world elections.
Usability is a very important point: if the voters do not understand how to use the
voting system, they will not try it. Therefore some guidelines should be designed to
simplify

7.1.4 IMPLEMENTATION
Theoretical systems have the advantage that they solve all issues in theory, but it is not
possible to evaluate them in real elections. Therefore, this system needs to be
implemented for a real comparison with the other big voting systems. There will also
be a button that counts and displays the number of votes per candidate.

This way, we will be able to focus the process of creating and interacting with the smart
contracts within an application. The source code for this entire application will be in this
repository, and you will need to have Node.js and npm installed. For any
application, you want your smart contracts to be as simple as possible, even stupidly
simple. Remember that you have to pay for every computation/transaction you make,
and your smart contracts will be on the Blockchain forever. So, you really want it to
work perfectly––meaning, the more complex it is, the easier it is to make a mistake.

41
CHAPTER 8: REFERENCES
1. Zyskind, G., et al.: Decentralizing privacy: using blockchain to protect personal
data. In:Security and Privacy Workshops (SPW), pp. 180–184. IEEE (2015).

2. Kosba, A., et al.: Hawk: the blockchain model of cryptography and privacy-
preserving smartcontracts. In: IEEE Symposium on Security and Privacy (SP),
pp. 839–858. IEEE (2016).

3. Shamir, A.: How to share a secret. Commun. ACM 22(11), 612–613 (1979).

4. Rabin, M.O: How to exchange secrets by oblivious transfer. Technical report,


AikenComputation Laboratory, Harvard University (1981).

5. Paillier, P: Public-key cryptosystems based on composite degree residuosity


classes residues.In: Advances in Cryptology, Eurocrypt 1999, pp. 223–238
(1999).

6. Nair, D.G, et al: An Improved E-voting scheme using Secret Sharing based
Secure MultipartyComputation. arXiv preprint arXiv:1502.07469 (2015).

7. F. Brandt. “Efficient cryptographic protocol design based on distributed


ElGamal encryption”. In International Conference on Information Security and
Cryptology, Springer, Berlin, Heidelberg, pp. 32-47, 2005.

8. T. Pedersen. “Non-interactive and information-theoretic secure verifiable secret


sharing”. In J. Feigenbaum, editor, Proc. of 11th CRYPTO Conference, volume
576 of LNCS, pages 129?C140. Springer, 1991.

9. J. Katz. “Digital signatures”. Springer Science and Business Media, 2010.

10. Y. Takabatake, D. Kotani, and Y. Okabe. “An anonymous distributed electronic


voting system using Zerocoin”. IEICE Techinical Report. vol. 54, no. 11, pp.
127-131, 2016.

11. R. Cramer, I. Damga˙rd and B. Schoenmakers. “Proofs of partial knowledge


and simplified design of witness hiding protocols”. In Annual International
Cryptology Conference. Springer, Berlin, Heidelberg, pp. 174-187, 1994. A.

42
43

You might also like