Be It 2019 Lp-Vi (BCT)
Be It 2019 Lp-Vi (BCT)
Be It 2019 Lp-Vi (BCT)
FINAL YEAR
INFORMATION TECHNOLOGY
(2019 COURSE)
LABORATORY MANUAL
FOR
Laboratory Practice – VI (Blockchain Technology)
SEMESTER - VIII
[Subject code: 414455]
[Prepared By]
1
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
VISION
To become a "Globally Recognized" technical institute providing world class education and
research facilities to the wards of Defense personnel.
MISSION
(a) Provide the right environment, to the wards of Defense personnel, for development of physical,
intellectual, emotional and spiritual quotients, with a view to produce total quality engineers.
(b) Create an ecosystem which can foster the culture of research, innovation, creative thinking and
higher studies.
(c) Develop an education system which creates entrepreneurs and technology leaders who are
committed towards sustainable development of society and nation building.
VISION
Towards providing world class education in Information Technology with societal focus.
MISSION
M1: Empowering students with state of art knowledge and skills to meet global challenges.
M2: To carry out high quality research leading to the creation and commercialization of
intellectual property.
2
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
3
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
4
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Objective:
To study about crypto wallets.
To setup a wallet on the browser.
Problem Statement:
To setup a crypto wallet
i) hosted wallets ii) self-custody wallet iii) hardware wallets (optional) and evaluate each of these
5
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
3.Hardware Wallets:
A hardware wallet is a special type of bitcoin wallet which stores the user's private keys in a
secure hardware device.
They have major advantages over standard software wallets:
Private keys are often stored in a protected area of a microcontroller, and cannot be
transferred out of the device in plaintext immune to computer viruses that steal from software
wallets can be used securely and interactively, private keys never need to touch potentially-
vulnerable software much of the time, the software is open source, allowing a user to validate
the entire operation of the device hardware wallet could fail to protect your Bitcoin:
1. Malware swaps recipient Bitcoin addresses: a hardware wallet won't protect you from
being tricked into sending Bitcoin to the wrong address. For example, malware on a PC could
monitor for high value transactions and then swap out the recipient's authentic Bitcoin address
for an address controlled by the attacker. When the stakes are high, multi factor (e.g., over the
phone) confirmation of a recipient's Bitcoin address is recommended.
2. Insecure RNG (Random Number Generator): hardware wallets rely on the security of an
RNG, often embedded in hardware, to generate your wallet's private keys securely.
Unfortunately, it is notoriously difficult to verify the true randomness of the RNG. An insecure
6
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
RNG may create wallet keys that can later be recreated by an attacker, by generating psuedo-
randomness that would seem statistically indistinguishable from true randomness yet still be
predictable to an advanced attacker. An RNG may become insecure as a result of malicious
weakening or an unintentional mistake. This failure mode is common to any wallet generation
procedure in which the true randomness of the source of entropy being used can not be verified.
3. Imperfect implementation: the security of all computing devices relies on the quality of
their implementation. Hardware wallets are no exception. Bugs at the software, firmware or
hardware level may allow attackers to break into a hardware wallet and gain unauthorized access
to secrets. Even if the design is perfect, proving the security of a hardware or software
implementation is a very hard, mostly unsolved problem. To date, no wallet in existence is
implemented using provably correct software.
Set up a wallet-Metamask:
Metamask is an self hosted wallet. MetaMask is a decentralized wallet with vast features and
Web3 applications that make it a central hub for NFT and Web3 enthusiasts who desire to build
decentralized applications on the Ethereum blockchain.
How to use MetaMask: A step by step guide
MetaMask is one of the most popular browser extensions that serves as a way of storing your
Ethereum and other ERC-20 Tokens. The extension is free and secure, allowing web applications
to read and interact with Ethereum’s blockchain.
7
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
8
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
And it’s as easy as that to install the extension on your browser, continue reading the next step to
figure out how to create an account.
Step 2. Create an account.
Click on the extension icon in the upper right corner to open MetaMask.
To install the latest version and be up to date, click Try it now.
9
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Click Continue.
You will be prompted to create a new password. Click Create.
10
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
11
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Verify your secret phrase by selecting the previously generated phrase in order. Click
Confirm.
And that’s it; now you have created your MetaMask account successfully. A new Ethereum wallet
address has just been created for you. It’s waiting for you to deposit funds, and if you want to
learn how to do that, look at the next step below.
Conclusion:
Thus we studied the different types of wallets and setup a wallet on our browser.
12
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Assignment No: 01 -b
Objective:
To learn operations in a wallet
Problem Statement:
Understand the basic operations in the wallet on bitcoin such as 1) buy 2) sell 3) send 4) receive
5) exchange 6) mining.
13
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
transactions that have been completed in the past. This ensures that you can’t spend a Bitcoin
you don’t have, or that you have previously spent.
Receiving Bitcoin
1. Open your Bitcoin.com wallet app and tap the ‘Receive’ button at the top of the Home
screen.
2. Choose which wallet you want to receive Bitcoin to. Make sure you select a (BCH) wallet
if you are receiving Bitcoin Cash or a (BTC) wallet if you are receiving Bitcoin.
3. Your chosen wallet will generate an address that lets you receive coins. Copy this by
tapping the QR code.
4. Provide this address to the sending party, or if you’re in person, the sender can simply
scan your wallet QR code with their device.
Sending Bitcoin
1. Open your Bitcoin.com wallet app and tap the ‘Send’ button at the top of the Home
screen.
2. Copy and paste the recipient’s wallet address into your own wallet app. If you’re in
person, select “Scan QR code” and simply scan it with your app.
14
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
3. Choose which wallet you want to send Bitcoin from. Make sure you select a BCH wallet
if you want to send Bitcoin Cash or a BTC wallet if you want to send Bitcoin.
4. Enter how much you want to send and tap on ‘Continue’.
15
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
v. exchanging a bitcoin:
Bitcoin exchange platforms match buyers with sellers. Like a traditional stock exchange, traders
can opt to buy and sell bitcoin by inputting either a market order or a limit order. When a market
order is selected, the trader is authorizing the exchange to trade the coins for the best available
price in the online marketplace. With a limit order set, the trader directs the exchange to trade
coins for a price below the current ask or above the current bid, depending on whether they are
buying or selling.
To transact in bitcoin on an exchange, a user has to register with the exchange and go through
a series of verification processes to authenticate their identity. Once the authentication is
successful, an account is opened for the user who then has to transfer funds into this account
before they can buy coins.
16
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Conclusion:
Thus, we studied the basic operations of bitcoin wallet.
17
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Objective:
Deploying a smart contract locally .
To deploy a contract using test net and connect it to wallet
Problem Statement:
1) Create a local Ethereum network using Hardhat or any other tool, build a smart contract that
lets you send a $ (wave) to your contract and keep track of the total # of waves. Compile it to
run locally.
Requirements:
VS code, Nodejs
18
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
It's backed by the @ethereumjs/vm EVM implementation, the same one used by ganache,
Remix and Ethereum Studio.
Procedure:
Creating a local Ethereum network and compiling it locally :
1. Install Node.js and npm (if you haven't already).
2. Install Hardhat
To install it, you need to create an npm project by going to an empty folder, running npm
init, and following its instructions. By running this command
npm install --save-dev hardhat.
3. Initialize a new Hardhat project by running npx hardhat init.
4. Install the necessary dependencies for our project by running npm install ethers hardhat-
deploy
5. Open the hardhat.config.js file and add the following lines of code to the networks
section:
7. Create a new file called WavePortal.sol in the contracts directory and add the following code:
This smart contract has a totalWaves variable that keeps track of the number of waves sent to
the contract, and a wave function that increments this variable by 1 every time it's called.
7. Compile the smart contract by running npx hardhat compile.
19
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
8. Create a new file called deploy.js in the scripts directory and add the following code:
This script deploys the WavePortal smart contract to the local network.
9. Deploy the smart contract by running npx hardhat run scripts/deploy.js --network
hardhat.
10. Now we can interact with the contract using the Hardhat console. Run npx hardhat
console to start the console, and then run the following commands to send a wave to the contract
and check the current number of waves:
Conclusion: Thus we studied the use of hardhat tool and to run the contract locally.
20
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Title: Build and deploy a smart contract using hardhat on a web app.
Objective:
Deploying a smart contract locally.
To deploy a contract using test net and connect it to wallet.
Problem Statement:
Create a local Ethereum network using Hardhat or any other tool, build a smart contract that lets
you send a $ (wave) to your contract and keep track of the total # of waves. onnect to any
Ethereum wallet. Metamask. Deploy the contract with testnet. Connect your wallet with your
web app. Call the deployed contract through your web app. Then store the wave messages from
users in arrays using structs.
Requirements:
VS code, NodeJS
Steps to follow to create an app web app to call the smart contract:
1. Create the smart contract: Write the smart contract code in Solidity programming language.
You can use tools like Remix or Visual Studio Code with Solidity plugins to write, compile and
debug your contract code.
2. Deploy the smart contract to a testnet: Deploy the smart contract to a testnet like Rinkeby,
Ropsten or Kovan to test and validate its functionality. You can use a tool like Truffle or Remix
to deploy your contract to a testnet.
3. Connect your wallet to your web app: In order to connect your wallet to your web app, you will
need to use a Web3 provider like Metamask. Metamask is a browser extension that allows you
to interact with the Ethereum network and your wallet from your web app. You can integrate
Metamask by adding its script to your web app and calling its functions to interact with the
Ethereum network.
4. Call the deployed contract through your web app: Once your wallet is connected to your web
app, you can call the functions of the deployed contract using the Web3 provider. You will need
21
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
to use the contract address and ABI (Application Binary Interface) to interact with the contract
functions.
Here's a high-level example of how you can connect your web app to a deployed smart contract
on the Rinkeby testnet using Metamask:
1. Write the smart contract code in Solidity and compile it using Remix.
2. Deploy the smart contract to the Rinkeby testnet using Truffle.
3. Create a new web app and integrate the Metamask script by adding the following code to
your HTML file:
4. Connect your wallet to the web app by calling the window.ethereum.request function when
the user clicks a "Connect Wallet" button:
5. Call the contract functions by creating a new instance of the contract object using the
contract address and ABI, and calling the desired function:
Smart Contract :
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract WavePortal {
struct Wave {
address sender;
string message;
uint256 timestamp;
}
uint256 totalWaves;
Wave[] waves;
22
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
return totalWaves;
}
Conclusion: Thus we studied the use of hardhat tool and to run the contract and called the
contract using web app.
23
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Assignment No: 03
Title: Solidity
Objective:
1. To learn solidity basics.
2.To create contracts using solidity
Problem Statement:
Prepare your build system and Building Bitcoin Core.
a. Write Hello World smart contract in a higher programming language (Solidity).
b. Solidity example using arrays and functions.
Requirements: Remix IDE
Theory / Procedure / Diagrams / Circuits:
Solidity is a contract-oriented, high-level programming language for implementing smart
contracts. Solidity is highly influenced by C++, Python and JavaScript and has been designed to
target the Ethereum Virtual Machine (EVM).
A Solidity source files can contain an any number of contract definitions, import directives and
pragma directives.
Let's start with a simple source file of Solidity. Following is an example of a Solidity file −
pragma solidity >=0.4.0 <0.6.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
Pragma:
The first line is a pragma directive which tells that the source code is written for Solidity version
0.4.0 or anything newer that does not break functionality up to, but not including, version 0.6.0.A
pragma directive is always local to a source file and if you import another file, the pragma from
that file will not automatically apply to the importing file.So a pragma for a file which will not
24
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
compile earlier than version 0.4.0 and it will also not work on a compiler starting from version
0.5.0 will be written as follows −
pragma solidity ^0.4.0;
Contract
A Solidity contract is a collection of code (its functions) and data (its state) that resides at a
specific address on the Ethereum Blockchain.
The line uint stored Data declares a state variable called stored Data of type uint and the functions
set and get can be used to modify or retrieve the value of the variable.
We're using Remix IDE to Compile and Run our Solidity Code base.
Step 1 − Copy the given code in Remix IDE Code Section.
Example
pragma solidity ^0.5.0;
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(uint){
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Step 2 − Under Compile Tab, click Start to Compile button.
Step 3 − Under Run Tab, click Deploy button.
Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down.
Step 5 − Click getResult Button to display the result.
Output
0: uint256: 3
Value Types
Solidity offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types –
25
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Integer int8 to Signed int from 8 bits to 256 bits. int256 is the same
int256 as int.
Integer uint8 to Unsigned int from 8 bits to 256 bits. uint256 is the
uint256 same as uint.
String string
adress address address holds the 20 byte value representing the size
of an Ethereum address.
Strings:
Solidity supports String literal using both double quote (") and single quote ('). It provides string
as a data type to declare a variable of type String.
pragma solidity ^0.5.0;
contract SolidityTest {
string data = "test";
}
In above example, "test" is a string literal and data is a string variable. More preferred way is to
use byte types instead of String as string operation requires more gas as compared to byte
operation. Solidity provides inbuilt conversion between bytes to string and vice versa. In Solidity
we can assign String literal to a byte32 type variable easily. Solidity considers it as a byte32
literal.
pragma solidity ^0.5.0;
contract SolidityTest {
bytes32 data = "test";
}
26
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
27
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
}
return string(bstr);
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: string: 3
Arrays:
Creating an Array
To declare an array in Solidity, the data type of the elements and the number of elements should
be specified. The size of the array must be a positive integer and data type should be a valid
Solidity type
Syntax:
<data type> <array name>[size] = <initialization>
Fixed-size Arrays
uint[6] data1;
Dynamic Array:
The size of the array is not predefined when it is declared.
int[] data1=[10,20,30];
Array Operations
1. Accessing Array Elements: The elements of the array are accessed by using the index. If you
want to access ith element then you have to access (i-1)th index.
Example: In the below example, the contract Types first initializes an array[data] and then
retrieves the value at specific index 2.
28
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
// Creating a contract
contract Types {
// Declaring an array
uint[6] data;
// Defining function to
// assign values to array
function array_example(
) public payable returns (uint[6] memory){
data
= [uint(10), 20, 30, 40, 50, 60];
return data;
}
Output :
29
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
2. Length of Array: Length of the array is used to check the number of elements present in an
array. The size of the memory array is fixed when they are declared, while in case the dynamic
array is defined at runtime so for manipulation length is required.
Example: In the below example, the contract Types first initializes an array[data] and then the
length of the array is calculated.
Solidity
// Creating a contract
contract Types {
// Declaring an array
uint[6] data;
// Defining a function to
// assign values to an array
function array_example(
) public payable returns (uint[6] memory){
data = [uint(10), 20, 30, 40, 50, 60];
return data;
}
// Defining a function to
// find the length of the array
function array_length(
) public returns(uint) {
uint x = data.length;
return x;
}
}
30
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Output :
3. Push: Push is used when a new element is to be added in a dynamic array. The new element
is always added at the last position of the array.
Example: In the below example, the contract Types first initializes an array[data], and then more
values are pushed into the array.
Solidity
// Creating a contract
contract Types {
data.push(60);
data.push(70);
data.push(80);
return data;
}
}
31
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Output :
Conclusion:
Thus we studied the accessing and manipulation of arrays and string in solidity.
32
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Assignment No: 04
Pre-requisites:
Metamask Account
Basics understanding of solidity
Requirements
Visual Studio Code
Node.js
33
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Solidity
Solidity is a smart contract programming language on Ethereum. Developed on the top of the
EVM, it is similar to the object-oriented programming language that uses class and methods. It
allows you to perform arbitrary computations, but it is used to send and receive tokens and store
states. When it comes to syntax,Solidity is greatly influenced by C++, Python, and Javascript so
that developers can understand its syntax quickly.It would be best to have a good understanding
of Solidity programming language to efficiently write an Ethereum Smart Contract.
What is Solidity?
Solidity is a Javascript-like language developed specifically for creating smart contracts. It
is typed statically and supports libraries, inheritance and complex user-defined types.
Solidity compiler converts code into EVM bytecode which is sent to the Ethereum network as a
deployment transaction.
34
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
that allows us to communicate with the Ethereum chain without running a node ourselves.
Alchemy also has developer tools for monitoring and analytics.
2. Create your app and api key: Once you've created an Alchemy account, you can generate an
API key by creating an app. This will allow you to make requests to the Goerli testnet. If you're
not familiar with testnets you can. Click create App and create the new app. Give your app the
name and write a short description. Select staging as your environment and Goerli as your
network. Click Create App. Your app will appear in the table below.
3. Add ether from a faucet: you already have an account, make sure to switch over to the “Goerli
Test Network” in the upper right (so that we’re not dealing with real money). To deploy your
smart contract to the test network, you'll need some fake ETH. To get ETH on the Goerli network,
go to a Goerli faucet and enter your Goerli account address.
35
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
5. install packages:
First install yarn package manager
npm I -g install yarn
packages to :
Install solc
Yarn add [email protected]
Yarn add ethers
Yarn add fs-extra
6.Compiling the contract:
To compile a contract that imports other contracts via relative paths:
solcjs --bin –abi --include-path node_modules/ --base-path .contractname.sol
Use the --base-path and --include-path options to describe the layout of your project. --
base-path represents the root of your own source tree while --include-path allows you to
specify extra locations containing external code.
7. Create a deploy.js javascript file :
9. In ethers.wallet need to provide private key of your metamask account for this:
Go to metamask->click on 3 dots ->open account details->export private key by putting
password for metamask
37
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
10. The Contract Factory function will create an instance of the smart contract which requires
Abi ,bin which are autogenerated when we compile using solc.
11. now run using node deploy.js the contract will get deployed over test network and you can
check the transaction details over ethers can using contract address.
Conclusion:
Thus, we deployed the smart contract over a blockchain network.
38
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Assignment No: 05
Title: Polling/voting system using Solidity, Ethereum and a data structure hashmap (optional).
Objective:
1) To study the concepts in Solidity.
2) To study different methods in Ethereum.
3) To understand the use of hashmap.
Problem Statement: Implement a polling/voting system with the help of Solidity, Ethereum
and a data structure such as hashmap.
Voting System
A voting system using Solidity and Ethereum is a decentralised and transparent system for
conducting elections. The system uses a smart contract written in Solidity, a programming
language for creating smart contracts on the Ethereum blockchain.
39
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
The voting system allows eligible voters to cast their votes securely and anonymously using their
Ethereum addresses. The system uses the Ethereum blockchain to store the voting data, which
makes the system transparent, secure, and tamper-proof. The results of the election are publicly
accessible, and anyone can verify the authenticity and accuracy of the results.
The system can be designed to support various voting methods, including online voting, mail-in
ballots, and in-person voting. The voting process can be automated and managed by the smart
contract, which reduces the risk of human error and fraud.
Overall, a voting system using Solidity and Ethereum provides a transparent, secure, and
efficient way to conduct elections. The system's decentralised nature and use of the Ethereum
blockchain make it a powerful tool for promoting democracy and ensuring the integrity of the
voting process.
Smart contracts are where all the business logic of our application lives. Smart contracts are in
charge of reading and writing data to the blockchain, as well as executing business logic. Smart
contracts are written in a programming language called Solidity.
The function of smart contracts on the blockchain is very similar to a microservice on the web.
If the public ledger represents the database layer of the blockchain, then smart contracts are
where all the business logic that transacts with that data lives.
Also, they're called smart contracts because they represent a covenant or agreement. In the case
of this voting system, it is an agreement that your vote will count, that other votes are only
counted once, and that the candidate with the most votes will actually win the election.
The objectives of a voting system using Solidity, a programming language for creating
smart contracts on the Ethereum blockchain, can include:
Transparency: The voting system should be transparent to ensure that the results of the voting
process are visible to all stakeholders. With Solidity, transparency can be achieved by using a
public blockchain that allows anyone to access the voting data.
40
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Security: The voting system should be secure to ensure that the votes are authentic and tamper-
proof. With Solidity, security can be achieved through the use of cryptographic algorithms and
by designing the smart contract in a way that prevents unauthorized access to the voting data.
Immutability: The voting system should be immutable to ensure that the results of the vote
cannot be changed or altered after the voting process has concluded. With Solidity, immutability
can be achieved by storing the voting data on a blockchain, which makes it nearly impossible to
alter once it has been recorded.
Efficiency: The voting system should be efficient to ensure that the results are generated in a
timely manner. With Solidity, efficiency can be achieved by designing the smart contract to
minimise the computational resources required for vote counting and result tabulation.
Accessibility: The voting system should be accessible to ensure that all stakeholders can
participate in the voting process. With Solidity, accessibility can be achieved by designing the
smart contract to support multiple voting methods, such as online voting, mail-in ballots, and in-
person voting.
Implementing a voting system using Solidity and Ethereum involves the following steps:
Design the smart contract: The first step is to design the smart contract that will facilitate the
voting process. The smart contract should include functions to create new elections, register
voters, cast votes, and tally results. The contract should also include data structures to store
information about the election and the votes cast.
Define the rules: The rules of the voting system should be defined in the smart contract. This
includes the eligibility criteria for voters, the number of votes each voter can cast, and the
duration of the voting period.
Deploy the contract: Once the smart contract is designed, it should be deployed to the Ethereum
blockchain. This can be done using a development environment like Remix, which provides a
Solidity compiler and an interface to interact with the smart contract.
41
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
Register voters: The next step is to register the eligible voters for the election. This can be done
using a function in the smart contract that takes the voter's address as input and adds it to a list
of eligible voters.
Conduct the vote: Once the voters are registered, they can cast their votes using another function
in the smart contract. The function should take the voter's address and the candidate they want
to vote for as input, and record the vote in the contract.
Tally the results: After the voting period ends, the smart contract should tally the votes and
determine the winner of the election. This can be done using a function that iterates over the
votes cast and updates a data structure to keep track of the number of votes each candidate
received.
Declare the winner: Once the results are tallied, the smart contract should declare the winner of
the election. This can be done by returning the candidate with the most votes to the calling
function.
Overall, implementing a voting system using Solidity and Ethereum requires careful planning
and attention to detail to ensure that the system is transparent, secure, and accessible to all
stakeholders.
Input:
● Solidity Functions
1. Modifiers
/**
* @notice To check if the voter's age is greater than or equal to 18
* @param currentTime_ Current epoch time of the voter
*/
modifier votingLinesAreOpen(uint256 currentTime_) {
require(currentTime_ >= votingStartTime);
require(currentTime_ <= votingEndTime);
_;
}
/**
42
AIT, BE-IT (2019 Course) Laboratory Practice – VI (Blockchain Technology)
/**
* @notice To check if the user is Election Chief or not
*/
modifier isElectionChief() {
require(msg.sender == electionChief);
_;
}
2. Voting timelines
● Voting will only be opened between a particular date(s) & election chief has the right to
update the start & end dates of the voting process.
● start date can only be updated only if the voting process is not started yet
● Can extend the voting end date after the voting is started & before the voting is ended
/**
* @dev used to update the voting start & end times
* @param startTime_ Start time that needs to be updated
* @param currentTime_ Current time that needs to be updated
*/
function updateVotingStartTime(uint256 startTime_, uint256 currentTime_)
public
43
AIT, BE-IT (2019 Course)
Laboratory Practice – VI (Blockchain Technology)
isElectionChief
{
require(votingStartTime > currentTime_);
votingStartTime = startTime_;
}
/**
* @dev To extend the end of the voting
* @param endTime_ End time that needs to be updated
* @param currentTime_ Current time that needs to be updated
*/
function extendVotingTime(uint256 endTime_, uint256 currentTime_)
public
isElectionChief
{
require(votingStartTime < currentTime_);
require(votingEndTime > currentTime_);
votingEndTime = endTime_;
}
3. Results
Everyone can check the voting results once the voting lines are closed
function getResults(uint256 currentTime_)
public
view
returns (Types.Results[] memory)
{
require(votingEndTime < currentTime_);
Types.Results[] memory resultsList_ = new Types.Results[](
candidates.length
);
// Since the candidates will be lesser in count than voter.
// So looping is acceptable.
for (uint256 i = 0; i < candidates.length; i++) {
resultsList_[i] = Types.Results({
name: candidates[i].name,
partyShortcut: candidates[i].partyShortcut,
44
AIT, BE-IT (2019 Course)
Laboratory Practice – VI (Blockchain Technology)
partyFlag: candidates[i].partyFlag,
nominationNumber: candidates[i].nominationNumber,
stateCode: candidates[i].stateCode,
constituencyCode: candidates[i].constituencyCode,
voteCount: votesCount[candidates[i].nominationNumber]
});
}
return resultsList_;
}
Output:
Conclusion:
Smart contracts in voting systems are self-executing computer programs that ensure the
integrity and transparency of the voting process. They specify the rules and requirements for an
45
AIT, BE-IT (2019 Course)
Laboratory Practice – VI (Blockchain Technology)
election and automate certain aspects of the voting process, such as voter registration and identity
verification. Once deployed on a blockchain network, the smart contract cannot be altered or
tampered with, making the voting process secure and transparent.
Solidity is a programming language used to write smart contracts that run on Ethereum
blockchain. In the context of voting systems, Solidity can be used to create smart contracts that
automate the voting process, such as vote casting, vote counting, and result declaration. Solidity
is specifically designed to work with blockchain technology, which provides a secure,
transparent, and decentralized platform for running the voting system. By using Solidity, the
voting system can be coded with specific rules and requirements, such as eligibility criteria for
voters, the number of votes required to win, and the deadline for casting votes.
3. What are the benefits of using a blockchain-based voting system over traditional voting
systems?
There are several potential benefits of using a blockchain-based voting system over traditional
voting systems:
1) Security: Blockchain technology provides a high level of security, as the data stored on
the blockchain is cryptographically secured and cannot be altered or deleted without the
consensus of the network participants. This makes it less vulnerable to fraud and
manipulation, which is a major concern in traditional voting systems.
2) Transparency: A blockchain-based voting system provides transparency by allowing
every participant to view the entire voting process in real-time. The transactions on the
blockchain can be tracked and verified, making it more difficult to cheat the system.
3) Decentralization: Blockchain-based voting systems are decentralized, which means that
there is no central authority or single point of failure. This makes the system more
resilient and less vulnerable to attacks.
4) Efficiency: A blockchain-based voting system can automate several aspects of the voting
process, such as voter registration, identity verification, and vote counting, making it
more efficient and less prone to errors.
5) Accessibility: Blockchain-based voting systems can be designed to be accessible to a
wider range of voters, including those who are physically unable to vote in person or
those who are in remote areas.
46
AIT, BE-IT (2019 Course)
Laboratory Practice – VI (Blockchain Technology)
This is for Student’s Journal First Page for every assignment would be
Assignment No.:
Title:
Course Outcome:
Date of Completion:
Assessment Grade / Marks:
Assessor’s Sign with Date:
Assignment No: 1
Title
Objective:
Problem Statement:
Conclusion:
47