0% found this document useful (0 votes)
11 views44 pages

Technology

Uploaded by

baisuras
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views44 pages

Technology

Uploaded by

baisuras
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

N

TECHNOLOGY

A PROJECT REPORT

Submitted by

ESWARAMOORTI.M (710422243014)

GAYATHRI.M (710422243015)

MERCY.P (710422243031)

ELAKKIYA.K (710422243013)

in partial fulfillment for the award of the degree


of
BACHELOR OF ENGINEERING
IN
ELECTRONICS AND COMMUNICATION ENGINEERING

CHRIST THE KING ENGINEERING COLLEGE KARAMADAI,


COIMBATORE- 641104
ANNA UNIVERSITY: CHENNAI 600 025

APRIL - MAY 2024

BONAFIDE CERTIFICATE

Certified that this project report “ONLINE VOTING SYSTEM BY USING BLOCK CHAIN
TECHNOLOGY” is the bonafide work of “ESWARAMOORTHI.M, GAYATHRI.M,
MERCY.P, ELAKKIYA.K” who carried out the project work under my supervision.
.

…………………………………… …………………………
SIGNATURE
SIGNATURE
Mrs. K.R. SUGUNAMUGI.,
Mrs. J.REVATHY., SUPERVISOR,
HEAD OF THE DEPARTMENT, Department of AIDS,
Department of AIDS,
Christ The King Engineering College,
Christ The King Engineering College, Karamadai, Coimbatore – 641104.
Karamadai, Coimbatore – 641104.

Submitted for Anna University Project Viva-Voce examination held on

----------------------------------- --------------------------------------
INTERNAL EXAMINER EXTERNAL EXAMINER
ACKNOWLEDGEMENT

I am very grateful and gifted in taking up this opportunity to thank the LORD
ALMIGHTY for showering his unlimited blessings upon us.
It is a genuine pleasure to express our gratitude to our beloved Chairman Rev.Fr.
Dr. J. E. Arulraj and DFT Managing Trustee Rev. Sr. S. Gnanaselvam, DMI for facilitating
me in this bravura college.
I wish to express my sincere thanks to our beloved Administrator
Rev. Fr. S. Xavior Manoj, DMI and our beloved Principal Dr. M. Jeyakumar, M.E., Ph.D.,
for their stable and ethical support to finish my project successfully.
I express my deep sense of gratitude to our esteemed Head of the Department
Mrs. J. Revathy,M.E.,Ph.D., of Artificial Intelligence and Data Science Engineering for
his scintillating discussions and encouragement towards my project work.
I am immensely pleased to thank our internal guide Mrs. K. R. Sugunamugi,
M.E., Assistant Professor, Department of Artificial Intelligence and Data Science
Engineering for her excellent guidance and co-operation during the project work.
It is pleasure to acknowledge my indebtedness to all the Staff Members of our
Department who aided me successfully to bring my project as effective one. Further thanks to
Non-Teaching Staff for extending the Lab facilities.

I thank my family members and friends for their honorable support.

Eswaramoorthi.M (710422243014)
Gayathri.M (710422243015)
Mercy.P (710422243031)
Elakkiya.K (710422243013)
TABLE OF CONTENTS

CHAPTER TITLE PAGE


NO NO
ABSTRACT
LIST OF FIGUIRES
LIST OF ABBREVATIONS

1. INTRODUCTION 4
 SYSTEM
REQUIREMENTS
 TOOLS AND VERSIONS
 FLOW CHART
2. PROGRAM CODE 7
OUTPUT

3. CONCLUSION 41
FUTURE SCOPE

FIGURE LIST OF FIGURE


NO

1. FLOW CHART 5
ONLINE VOTING SYSTEM BY USING BLOCK CHAIN TECHNOLOGY

ELAKKIYA K1, GAYATHRI M2, MERCY P3, ESWARAMOORTHI M4

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE, CHRIST THE KING


ENGINEERING COLLEGE, COIMBATORE, INDIA.

ABSTRACT: Voting online presents a viable alternative to traditional paper-


based and electronic voting machine systems. However, ensuring the security
and integrity of an electronic voting platform is paramount. This paper
proposes an electronic voting system built on blockchain technology to
address some of the shortcomings of existing democratic processes. A peer-
to-peer (P2P) network is employed to maintain a distributed ledger of
voting transactions, creating a private blockchain. The user interface of the
application is designed to shield voters from the complexities of the
underlying architecture. Each voter is uniquely identified by their Aadhar
number, endorsed by the government, to ensure one-person-one-vote
integrity. When a vote is cast, it is transmitted as a transaction, updating all
peers in the network. To enhance security, votes are encrypted and hashed
before being added to the blockchain, generating a chain of blocks where
each peer possesses both a private and public key.

INDEX TERMS: Blockchain, E-voting, Smart Contract, Privacy, Web


Application, Solana.

3
SYSTEM REQUIREMENTS

HARDWARE REQUIREMENTS:
High-performance computing hardware (e.g., multi-core CPU,
GPU, or specialized AI accelerators like TPUs) for training and inference
tasks.
RAM-4 GB or higher

SOFTWARE REQUIREMENTS :
Operating System- Windows, Linux, or macOS.
Development Environment- Meta Mask wallet, Ganache, Remix
IDE,
Scikit-learn

TOOLS AND VERSIONS:


1. Meta Mask wallet - Version: 2.7.0
2. Ganache - Version: 20.10.11
3. Remix IDE -Version: 2.0.2
4. Scikit-learn-Version : 0.24.2
FLOW CHART:

5
PROGRAM CODE :

#include <libsolc/libsolc.h>
#include <libsolidity/interface/StandardCompiler.h>
#include <libsolidity/interface/Version.h>
#include <libyul/YulString.h>

#include <cstdlib>
#include <list>
#include <string>

#include "license.h"

using namespace solidity;


using namespace solidity::util;

using solidity::frontend::ReadCallback;
using solidity::frontend::StandardCompiler;

namespace
{

// The std::strings in this list must not be resized after they have been
added here (via solidity_alloc()), because
// this may potentially change the pointer that was passed to the caller
from solidity_alloc().
static std::list<std::string> solidityAllocations;

/// Find the equivalent to @p _data in the list of allocations of


solidity_alloc(),
/// removes it from the list and returns its value.
///
/// If any invalid argument is being passed, it is considered a programming
error
/// on the caller-side and hence, will call abort() then.
std::string takeOverAllocation(char const* _data)
{
for (auto iter = begin(solidityAllocations); iter !=
end(solidityAllocations); ++iter)
if (iter->data() == _data)
{
std::string chunk = std::move(*iter);
solidityAllocations.erase(iter);

7
return chunk;
}

abort();
}

/// Resizes a std::std::string to the proper length based on the occurrence


of a zero terminator.
void truncateCString(std::string& _data)
{
size_t pos = _data.find('\0');
if (pos != std::string::npos)
_data.resize(pos);
}

ReadCallback::Callback wrapReadCallback(CStyleReadFileCallback
_readCallback, void* _readContext)
{
ReadCallback::Callback readCallback;
if (_readCallback)
{
readCallback = [=](std::string const& _kind, std::string const&
_data)
{
char* contents_c = nullptr;
char* error_c = nullptr;
_readCallback(_readContext, _kind.data(), _data.data(),
&contents_c, &error_c);
ReadCallback::Result result;
result.success = true;
if (!contents_c && !error_c)
{
result.success = false;
result.responseOrErrorMessage = "Callback not supported.";
}
if (contents_c)
{
result.success = true;
result.responseOrErrorMessage =
takeOverAllocation(contents_c);
}
if (error_c)
{
result.success = false;
result.responseOrErrorMessage = takeOverAllocation(error_c);
}
truncateCString(result.responseOrErrorMessage);
return result;
};
}
return readCallback;
}

std::string compile(std::string _input, CStyleReadFileCallback


_readCallback, void* _readContext)
{
StandardCompiler compiler(wrapReadCallback(_readCallback,
_readContext));
return compiler.compile(std::move(_input));
}

extern "C"
{
extern char const* solidity_license() noexcept
{
static std::string fullLicenseText = otherLicenses + licenseText;
return fullLicenseText.c_str();
}

extern char const* solidity_version() noexcept


{
return frontend::VersionString.c_str();
}

extern char* solidity_compile(char const* _input, CStyleReadFileCallback


_readCallback, void* _readContext) noexcept
{
return solidityAllocations.emplace_back(compile(_input, _readCallback,
_readContext)).data();
}

extern char* solidity_alloc(size_t _size) noexcept


{
try
{
return solidityAllocations.emplace_back(_size, '\0').data();
}
catch (...)
9
{
// most likely a std::bad_alloc(), if at all.
return nullptr;
}
}

extern void solidity_free(char* _data) noexcept


{
takeOverAllocation(_data);
}

extern void solidity_reset() noexcept


{
// This is called right before each compilation, but not at the end, so
additional memory
// can be freed here.
yul::YulStringRepository::reset();
solidityAllocations.clear();
}
}
#pragma once

#include <test/tools/ossfuzz/Generators.h>

#include <liblangutil/Exceptions.h>

#include <memory>
#include <random>
#include <set>
#include <variant>

namespace solidity::test::fuzzer::mutator
{
/// Forward declarations
class SolidityGenerator;

/// Type declarations


#define SEMICOLON() ;
#define FORWARDDECLAREGENERATORS(G) class G
GENERATORLIST(FORWARDDECLAREGENERATORS, SEMICOLON(), SEMICOLON())
#undef FORWARDDECLAREGENERATORS
#undef SEMICOLON

#define COMMA() ,
using GeneratorPtr = std::variant<
#define VARIANTOFSHARED(G) std::shared_ptr<G>
GENERATORLIST(VARIANTOFSHARED, COMMA(), )
>;
#undef VARIANTOFSHARED
using Generator = std::variant<
#define VARIANTOFGENERATOR(G) G
GENERATORLIST(VARIANTOFGENERATOR, COMMA(), )
>;
#undef VARIANTOFGENERATOR
#undef COMMA
using RandomEngine = std::mt19937_64;
using Distribution = std::uniform_int_distribution<size_t>;

struct UniformRandomDistribution
{
explicit UniformRandomDistribution(std::unique_ptr<RandomEngine>
_randomEngine):
randomEngine(std::move(_randomEngine))
{}

/// @returns an unsigned integer in the range [1, @param _n] chosen
/// uniformly at random.
[[nodiscard]] size_t distributionOneToN(size_t _n) const
{
return Distribution(1, _n)(*randomEngine);
}
/// @returns true with a probability of 1/(@param _n), false otherwise.
/// @param _n must be non zero.
[[nodiscard]] bool probable(size_t _n) const
{
solAssert(_n > 0, "");
return distributionOneToN(_n) == 1;
}
std::unique_ptr<RandomEngine> randomEngine;
};

struct TestState
{
explicit TestState(std::shared_ptr<UniformRandomDistribution> _urd):
sourceUnitPaths({}),
currentSourceUnitPath({}),
uRandDist(std::move(_urd))
{}
/// Adds @param _path to @name sourceUnitPaths updates
/// @name currentSourceUnitPath.
11
void addSourceUnit(std::string const& _path)
{
sourceUnitPaths.insert(_path);
currentSourceUnitPath = _path;
}
/// @returns true if @name sourceUnitPaths is empty,
/// false otherwise.
[[nodiscard]] bool empty() const
{
return sourceUnitPaths.empty();
}
/// @returns the number of items in @name sourceUnitPaths.
[[nodiscard]] size_t size() const
{
return sourceUnitPaths.size();
}
/// Prints test state to @param _os.
void print(std::ostream& _os) const;
/// @returns a randomly chosen path from @param _sourceUnitPaths.
[[nodiscard]] std::string randomPath(std::set<std::string> const&
_sourceUnitPaths) const;
/// @returns a randomly chosen path from @name sourceUnitPaths.
[[nodiscard]] std::string randomPath() const;
/// @returns a randomly chosen non current source unit path.
[[nodiscard]] std::string randomNonCurrentPath() const;
/// List of source paths in test input.
std::set<std::string> sourceUnitPaths;
/// Source path being currently visited.
std::string currentSourceUnitPath;
/// Uniform random distribution.
std::shared_ptr<UniformRandomDistribution> uRandDist;
};

struct GeneratorBase
{
explicit GeneratorBase(std::shared_ptr<SolidityGenerator> _mutator);
template <typename T>
std::shared_ptr<T> generator()
{
for (auto& g: generators)
if (std::holds_alternative<std::shared_ptr<T>>(g))
return std::get<std::shared_ptr<T>>(g);
solAssert(false, "");
}
/// @returns test fragment created by this generator.
std::string generate()
{
std::string generatedCode = visit();
endVisit();
return generatedCode;
}
/// @returns a string representing the generation of
/// the Solidity grammar element.
virtual std::string visit() = 0;
/// Method called after visiting this generator. Used
/// for clearing state if necessary.
virtual void endVisit() {}
/// Visitor that invokes child grammar elements of
/// this grammar element returning their string
/// representations.
std::string visitChildren();
/// Adds generators for child grammar elements of
/// this grammar element.
void addGenerators(std::set<GeneratorPtr> _generators)
{
generators += _generators;
}
/// Virtual method to obtain string name of generator.
virtual std::string name() = 0;
/// Virtual method to add generators that this grammar
/// element depends on. If not overridden, there are
/// no dependencies.
virtual void setup() {}
virtual ~GeneratorBase()
{
generators.clear();
}
/// Shared pointer to the mutator instance
std::shared_ptr<SolidityGenerator> mutator;
/// Set of generators used by this generator.
std::set<GeneratorPtr> generators;
/// Shared ptr to global test state.
std::shared_ptr<TestState> state;
/// Uniform random distribution
std::shared_ptr<UniformRandomDistribution> uRandDist;
};

class TestCaseGenerator: public GeneratorBase


{
public:
13
explicit TestCaseGenerator(std::shared_ptr<SolidityGenerator>
_mutator):
GeneratorBase(std::move(_mutator)),
m_numSourceUnits(0)
{}
void setup() override;
std::string visit() override;
std::string name() override
{
return "Test case generator";
}
private:
/// @returns a new source path name that is formed by concatenating
/// a static prefix @name m_sourceUnitNamePrefix, a monotonically
/// increasing counter starting from 0 and the postfix (extension)
/// ".sol".
[[nodiscard]] std::string path() const
{
return m_sourceUnitNamePrefix + std::to_string(m_numSourceUnits) +
".sol";
}
/// Adds @param _path to list of source paths in global test
/// state and increments @name m_numSourceUnits.
void updateSourcePath(std::string const& _path)
{
state->addSourceUnit(_path);
m_numSourceUnits++;
}
/// Number of source units in test input
size_t m_numSourceUnits;
/// String prefix of source unit names
std::string const m_sourceUnitNamePrefix = "su";
/// Maximum number of source units per test input
static constexpr unsigned s_maxSourceUnits = 3;
};

class SourceUnitGenerator: public GeneratorBase


{
public:
explicit SourceUnitGenerator(std::shared_ptr<SolidityGenerator>
_mutator):
GeneratorBase(std::move(_mutator))
{}
void setup() override;
std::string visit() override;
std::string name() override { return "Source unit generator"; }
};

class PragmaGenerator: public GeneratorBase


{
public:
explicit PragmaGenerator(std::shared_ptr<SolidityGenerator> _mutator):
GeneratorBase(std::move(_mutator))
{}
std::string visit() override;
std::string name() override { return "Pragma generator"; }
};

class ImportGenerator: public GeneratorBase


{
public:
explicit ImportGenerator(std::shared_ptr<SolidityGenerator> _mutator):
GeneratorBase(std::move(_mutator))
{}
std::string visit() override;
std::string name() override { return "Import generator"; }
private:
/// Inverse probability with which a source unit
/// imports itself. Keeping this at 17 seems to
/// produce self imported source units with a
/// frequency small enough so that it does not
/// consume too many fuzzing cycles but large
/// enough so that the fuzzer generates self
/// import statements every once in a while.
static constexpr size_t s_selfImportInvProb = 17;
};

class SolidityGenerator: public


std::enable_shared_from_this<SolidityGenerator>
{
public:
explicit SolidityGenerator(unsigned _seed);

/// @returns the generator of type @param T.


template <typename T>
std::shared_ptr<T> generator();
/// @returns a shared ptr to underlying random
/// number distribution.
std::shared_ptr<UniformRandomDistribution> uniformRandomDist()
{
15
return m_urd;
}
/// @returns a pseudo randomly generated test case.
std::string generateTestProgram();
/// @returns shared ptr to global test state.
std::shared_ptr<TestState> testState()
{
return m_state;
}
private:
template <typename T>
void createGenerator()
{
m_generators.insert(
std::make_shared<T>(shared_from_this())
);
}
template <std::size_t I = 0>
void createGenerators();
void destroyGenerators()
{
m_generators.clear();
}
/// Sub generators
std::set<GeneratorPtr> m_generators;
/// Shared global test state
std::shared_ptr<TestState> m_state;
/// Uniform random distribution
std::shared_ptr<UniformRandomDistribution> m_urd;
};
}
const routes = require('next-routes')();

routes
.add('/homepage','/homepage')
.add('/company_login','/company_login')
.add('/voter_login','/voter_login')
.add('/election/:address/company_dashboard','/election/company_dashboa
rd')
.add('/election/:address/voting_list','/election/voting_list')
.add('/election/:address/addcand','/election/addcand')
.add('/election/:address/vote','/election/vote')
.add('/election/:address/candidate_list','/election/candidate_list');
module.exports = routes;
const next = require('next');
const express = require('express');
const voter = require('./routes/voter');
const company = require('./routes/company');
const candidate = require('./routes/candidate');
const bodyParser = require('body-parser');
const mongoose = require('./config/database');
const exp = express();
const path = require('path');

require('dotenv').config({ path: __dirname + '/.env' });

mongoose.connection.on('error', console.error.bind(console, 'MongoDB


connection error:'));

exp.use(
bodyParser.urlencoded({
extended: true,
})
);
exp.use(bodyParser.json());
exp.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/pages/homepage.js'));
});

exp.use('/company', company);

exp.use('/voter', voter);

exp.use('/candidate', candidate);

const app = next({


dev: process.env.NODE_ENV !== 'production',
});

const routes = require('./routes');


const handler = routes.getRequestHandler(app);

app.prepare().then(() => {
exp.use(handler).listen(3000, function () {
console.log('Node server listening on port 3000');
});
});

authors:
-
17
family-names: Mehta
given-names: Ansh
-
family-names: Mehta
given-names: Charmee
-
family-names: Gada
given-names: Sayyam
-
affiliation: "Prof."
family-names: Kadukar
given-names: Neeta
cff-version: "1.1.0"
date-released: 2019-06-01
message: "If you use this software, please cite it using these metadata."
repository-code: "https://github.com/mehtaAnsh/BlockChainVoting"
title: BlockChainVoting
version: "v1.0"
...
const VoterModel = require('../models/voter');

const bcrypt = require('bcrypt');

const path = require('path');

var nodemailer = require('nodemailer');

const saltRounds = 10;

module.exports = {
create: function (req, res, cb) {
VoterModel.findOne(
{ email: req.body.email, election_address:
req.body.election_address },
function (err, result) {
if (err) {
cb(err);
} else {
if (!result) {
VoterModel.create(
{
email: req.body.email,
password: req.body.email,
election_address: req.body.election_address,
},
function (err, voter) {
if (err) cb(err);
else {
console.log(voter);

console.log(voter.email);

console.log(req.body.election_descript
ion);

console.log(req.body.election_name);

var transporter =
nodemailer.createTransport({
service: 'gmail',

auth: {
user: process.env.EMAIL,

pass: process.env.PASSWORD,
},
});

const mailOptions = {
from: process.env.EMAIL, // sender
address

to: voter.email, // list of receivers

subject: req.body.election_name, //
Subject line

html:
req.body.election_description
+
'<br>Your voting id is:' +
voter.email +
'<br>' +
'Your password is:' +
voter.password +
'<br><a
href="http://localhost:3000/homepage">Click here to visit the website</a>',
// plain text body
};

19
transporter.sendMail(mailOptions,
function (err, info) {
if (err) {
res.json({
status: 'error',
message: 'Voter could not
be added',
data: null,
});

console.log(err);
} else {
console.log(info);

res.json({
status: 'success',
message: 'Voter added
successfully!!!',
data: null,
});
}
});
}
}
);
} else {
res.json({ status: 'error', message: 'Voter already
exists ', data: null });
}
}
}
);
},

authenticate: function (req, res, cb) {


VoterModel.findOne({ email: req.body.email, password:
req.body.password }, function (err, voterInfo) {
if (err) cb(err);
else {
if (voterInfo)
res.json({
status: 'success',
message: 'voter found!!!',
data: { id: voterInfo._id, election_address:
voterInfo.election_address },
});
//res.sendFile(path.join(__dirname+'/index.html'));
else {
res.json({ status: 'error', message: 'Invalid
email/password!!!', data: null });
}
}
});
},

getAll: function (req, res, cb) {


let voterList = [];

VoterModel.find({ election_address: req.body.election_address },


function (err, voters) {
if (err) cb(err);
else {
for (let voter of voters) voterList.push({ id: voter._id,
email: voter.email });

count = voterList.length;

res.json({
status: 'success',
message: 'voters list found!!!',
data: { voters: voterList },
count: count,
});
}
});
},

updateById: function (req, res, cb) {


VoterModel.findOne({ email: req.body.email }, function (err, result)
{
if (err) {
cb(err);
} else {
console.log('email:' + req.body.email);
console.log('findOne:' + result);
if (!result) {
password = bcrypt.hashSync(req.body.email, saltRounds);
console.log('email not found');
console.log('voterID:' + req.params.voterId);
VoterModel.findByIdAndUpdate(
21
req.params.voterId,
{ email: req.body.email, password: password },
function (err, voter) {
if (err) cb(err);
console.log('update method object:' + voter);
}
);
VoterModel.findById(req.params.voterId, function (err,
voterInfo) {
if (err) cb(err);
else {
console.log('Inside find after update' +
voterInfo);
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},
});
const mailOptions = {
from: process.env.EMAIL, // sender address
to: voterInfo.email, // list of receivers
subject: req.body.election_name, // Subject
line
html:
req.body.election_description +
'<br>Your voting id is:' +
voterInfo.email +
'<br>' +
'Your password is:' +
voterInfo.password +
'<br><a href="url">Click here to visit
the website</a>', // plain text body
};
transporter.sendMail(mailOptions, function (err,
info) {
if (err) {
res.json({ status: 'error', message:
'Voter could not be added', data: null });
console.log(err);
} else {
console.log(info);
res.json({
status: 'success',
message: 'Voter updated
successfully!!!',
data: null,
});
}
});
}
});
} else {
res.json({ status: 'error', message: 'Voter already
exists ', data: null });
}
}
});
},

deleteById: function (req, res, cb) {


VoterModel.findByIdAndRemove(req.params.voterId, function (err,
voterInfo) {
if (err) cb(err);
else {
res.json({ status: 'success', message: 'voter deleted
successfully!!!', data: null });
}
});
},

resultMail: function (req, res, cb) {


VoterModel.find({ election_address: req.body.election_address },
function (err, voters) {
if (err) cb(err);
else {
const election_name = req.body.election_name;

const winner_candidate = req.body.winner_candidate;

for (let voter of voters) {


var transporter = nodemailer.createTransport({
service: 'gmail',

auth: {
user: process.env.EMAIL,

pass: process.env.PASSWORD,
},
23
});

const mailOptions = {
from: process.env.EMAIL, // sender address

to: voter.email, // list of receivers

subject: election_name + ' results', // Subject


line

html:
'The results of ' +
election_name +
' are out.<br>The winner candidate is: <b>' +
winner_candidate +
'</b>.',
};

transporter.sendMail(mailOptions, function (err, info)


{
if (err) {
res.json({ status: 'error', message: 'mail
error', data: null });

console.log(err);
} else console.log(info);

res.json({ status: 'success', message: 'mails sent


successfully!!!', data: null });
});
}

var transporter = nodemailer.createTransport({


service: 'gmail',

auth: {
user: process.env.EMAIL,

pass: process.env.PASSWORD,
},
});

const mailOptions = {
from: process.env.EMAIL, // sender address
to: req.body.candidate_email, // list of receivers

subject: req.body.election_name + ' results !!!', //


Subject line

html: 'Congratulations you won ' + req.body.election_name


+ ' election.', // plain text body
};

transporter.sendMail(mailOptions, function (err, info) {


if (err) {
res.json({ status: 'error', message: 'mail error',
data: null });

console.log(err);
} else console.log(info);

res.json({ status: 'success', message: 'mail sent


successfully!!!', data: null });
});
}
});
},
};
const VoterModel = require('../models/voter');

const bcrypt = require('bcrypt');

const path = require('path');

var nodemailer = require('nodemailer');

const saltRounds = 10;

module.exports = {
create: function (req, res, cb) {
VoterModel.findOne(
{ email: req.body.email, election_address:
req.body.election_address },
function (err, result) {
if (err) {
cb(err);
} else {
if (!result) {
VoterModel.create(
25
{
email: req.body.email,
password: req.body.email,
election_address: req.body.election_address,
},
function (err, voter) {
if (err) cb(err);
else {
console.log(voter);

console.log(voter.email);

console.log(req.body.election_descript
ion);

console.log(req.body.election_name);

var transporter =
nodemailer.createTransport({
service: 'gmail',

auth: {
user: process.env.EMAIL,

pass: process.env.PASSWORD,
},
});

const mailOptions = {
from: process.env.EMAIL, // sender
address

to: voter.email, // list of receivers

subject: req.body.election_name, //
Subject line

html:
req.body.election_description
+
'<br>Your voting id is:' +
voter.email +
'<br>' +
'Your password is:' +
voter.password +
'<br><a
href="http://localhost:3000/homepage">Click here to visit the website</a>',
// plain text body
};

transporter.sendMail(mailOptions,
function (err, info) {
if (err) {
res.json({
status: 'error',
message: 'Voter could not
be added',
data: null,
});

console.log(err);
} else {
console.log(info);

res.json({
status: 'success',
message: 'Voter added
successfully!!!',
data: null,
});
}
});
}
}
);
} else {
res.json({ status: 'error', message: 'Voter already
exists ', data: null });
}
}
}
);
},

authenticate: function (req, res, cb) {


VoterModel.findOne({ email: req.body.email, password:
req.body.password }, function (err, voterInfo) {
if (err) cb(err);
else {
if (voterInfo)
27
res.json({
status: 'success',
message: 'voter found!!!',
data: { id: voterInfo._id, election_address:
voterInfo.election_address },
});
//res.sendFile(path.join(__dirname+'/index.html'));
else {
res.json({ status: 'error', message: 'Invalid
email/password!!!', data: null });
}
}
});
},

getAll: function (req, res, cb) {


let voterList = [];

VoterModel.find({ election_address: req.body.election_address },


function (err, voters) {
if (err) cb(err);
else {
for (let voter of voters) voterList.push({ id: voter._id,
email: voter.email });

count = voterList.length;

res.json({
status: 'success',
message: 'voters list found!!!',
data: { voters: voterList },
count: count,
});
}
});
},

updateById: function (req, res, cb) {


VoterModel.findOne({ email: req.body.email }, function (err, result)
{
if (err) {
cb(err);
} else {
console.log('email:' + req.body.email);
console.log('findOne:' + result);
if (!result) {
password = bcrypt.hashSync(req.body.email, saltRounds);
console.log('email not found');
console.log('voterID:' + req.params.voterId);
VoterModel.findByIdAndUpdate(
req.params.voterId,
{ email: req.body.email, password: password },
function (err, voter) {
if (err) cb(err);
console.log('update method object:' + voter);
}
);
VoterModel.findById(req.params.voterId, function (err,
voterInfo) {
if (err) cb(err);
else {
console.log('Inside find after update' +
voterInfo);
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},
});
const mailOptions = {
from: process.env.EMAIL, // sender address
to: voterInfo.email, // list of receivers
subject: req.body.election_name, // Subject
line
html:
req.body.election_description +
'<br>Your voting id is:' +
voterInfo.email +
'<br>' +
'Your password is:' +
voterInfo.password +
'<br><a href="url">Click here to visit
the website</a>', // plain text body
};
transporter.sendMail(mailOptions, function (err,
info) {
if (err) {
res.json({ status: 'error', message:
'Voter could not be added', data: null });
29
console.log(err);
} else {
console.log(info);
res.json({
status: 'success',
message: 'Voter updated
successfully!!!',
data: null,
});
}
});
}
});
} else {
res.json({ status: 'error', message: 'Voter already
exists ', data: null });
}
}
});
},

deleteById: function (req, res, cb) {


VoterModel.findByIdAndRemove(req.params.voterId, function (err,
voterInfo) {
if (err) cb(err);
else {
res.json({ status: 'success', message: 'voter deleted
successfully!!!', data: null });
}
});
},

resultMail: function (req, res, cb) {


VoterModel.find({ election_address: req.body.election_address },
function (err, voters) {
if (err) cb(err);
else {
const election_name = req.body.election_name;

const winner_candidate = req.body.winner_candidate;

for (let voter of voters) {


var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,

pass: process.env.PASSWORD,
},
});

const mailOptions = {
from: process.env.EMAIL, // sender address

to: voter.email, // list of receivers

subject: election_name + ' results', // Subject


line

html:
'The results of ' +
election_name +
' are out.<br>The winner candidate is: <b>' +
winner_candidate +
'</b>.',
};

transporter.sendMail(mailOptions, function (err, info)


{
if (err) {
res.json({ status: 'error', message: 'mail
error', data: null });

console.log(err);
} else console.log(info);

res.json({ status: 'success', message: 'mails sent


successfully!!!', data: null });
});
}

var transporter = nodemailer.createTransport({


service: 'gmail',

auth: {
user: process.env.EMAIL,

pass: process.env.PASSWORD,
},
31
});

const mailOptions = {
from: process.env.EMAIL, // sender address

to: req.body.candidate_email, // list of receivers

subject: req.body.election_name + ' results !!!', //


Subject line

html: 'Congratulations you won ' + req.body.election_name


+ ' election.', // plain text body
};

transporter.sendMail(mailOptions, function (err, info) {


if (err) {
res.json({ status: 'error', message: 'mail error',
data: null });

console.log(err);
} else console.log(info);

res.json({ status: 'success', message: 'mail sent


successfully!!!', data: null });
});
}
});
},
};
import Web3 from 'web3';

let web3;

if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {


console.log(window.ethereum.enable());
web3 = new Web3(window.web3.currentProvider);
console.log('Web3: ', web3);
} else {
const provider = new
Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/29bcae4ee7454a1
18a2b0f0f4d86c0e0');
web3 = new Web3(provider);
console.log('Web3 else: ', web3);
}
export default web3;

const mongoose = require('mongoose');


const bcrypt = require('bcrypt');
const saltRounds = 10;
//Define a schema
const Schema = mongoose.Schema;
const VoterSchema = new Schema ({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true
},
election_address: {
type: String,
required: true
}
});
// hash user password before saving into database
VoterSchema.pre('save', function(cb) {
this.password = bcrypt.hashSync(this.password, saltRounds);
cb();
});
module.exports = mongoose.model('VoterList', VoterSchema)

33
OUTPUT:
35
37
39
FUTURE SCOPE :

Implementing an online voting system using blockchain technology could address many of the challenges
faced by traditional voting systems, such as security concerns, transparency, and trust issues. Here's how such
a system might work and the benefits it could provide:

1. Transparency and Security: Blockchain technology provides a decentralized and tamper-proof ledger
where all transactions (in this case, votes) are recorded. Each vote would be encrypted and recorded as a
transaction on the blockchain, making it nearly impossible to alter or manipulate without consensus from
the network.
2. Immutable Record: Once a vote is recorded on the blockchain, it cannot be changed or deleted. This
ensures the integrity of the voting process and prevents any attempts at fraud or tampering.
3. Traceability: Blockchain allows for a transparent and auditable trail of every vote cast. Each participant
can verify that their vote was correctly recorded and counted, increasing trust in the electoral process.
4. Elimination of Intermediaries: With blockchain, there's no need for intermediaries such as election
officials or central authorities to oversee the voting process. This reduces the potential for human error or
bias.
5. Accessibility: An online voting system based on blockchain technology could potentially increase
accessibility for voters, especially those who may face barriers such as physical disabilities or geographical
limitations.
6. Reduced Costs and Time: Traditional voting systems can be costly and time-consuming to set up and
administer. By automating much of the process through blockchain technology, costs could be reduced,
and the voting process could become more efficient.
7. Enhanced Voter Participation: The convenience of online voting could encourage higher voter turnout,
as it eliminates the need for physical travel to polling stations and allows voters to cast their ballots from
anywhere with an internet connection.

However, there are also challenges and considerations to address when implementing such a system:

1. Security Concerns: While blockchain technology offers enhanced security, it's not immune to cyber
threats. Measures would need to be implemented to safeguard against hacking attempts or other malicious
activities.
2. Identity Verification: Ensuring that each voter is who they claim to be in an online environment presents
challenges. Robust identity verification mechanisms would be necessary to prevent fraudulent voting.
3. Privacy: While blockchain provides transparency, it's essential to balance this with the privacy of
individual voters. Encryption techniques can help protect voter anonymity while still ensuring the integrity
of the voting process.
4. Scalability: Blockchain networks may face scalability issues when dealing with a large number of
transactions, such as those that occur during elections. Scalability solutions would need to be implemented
to handle peak loads effectively.
5. Digital Divide: Not everyone has access to the internet or may be comfortable using online platforms for
voting. Ensuring equitable access to the voting system would be crucial to prevent disenfranchisement.

41
6. Regulatory and Legal Challenges: Implementing an online voting system would require navigating
various regulatory and legal frameworks, which may vary significantly between jurisdictions.

Overall, while the use of blockchain technology in online voting systems holds promise for improving the
integrity, accessibility, and efficiency of elections, careful planning, testing, and collaboration with
stakeholders are essential to address challenges and ensure the system's success.

You might also like