100% found this document useful (1 vote)
268 views37 pages

Building Private Blockchain Lab Manual (1-10)

how to build a private block chain technology .

Uploaded by

Charan
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
100% found this document useful (1 vote)
268 views37 pages

Building Private Blockchain Lab Manual (1-10)

how to build a private block chain technology .

Uploaded by

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

Department of CIC

BUILDING PRIVATE BLOCKCHAIN


LAB(AK20)

ANNAMACHARYAINSTITUTEOFTECHNOLOGY&SCIENCES::TIRUPATI

(AutonomousInstitution -UGC,Govt.ofIndia)
(Recognizedunder2(f)and 12(B)ofUGC ACT 1956)

(Affiliated to JNTUA, Anantapuramu, Approved by AICTE - Accredited by NBA & NAAC –


‘A’Grade, Accredited by Institute of Engineers, Kolkata, A-Grade Awarded by AP
KnowledgeMission)
Tirupati,Andhra Pradesh-517520
LISTOFEXPERIMENTS&SCHEDULE

COURSECODE:20APC3623
COURSETITLE:BUILDING PRIVATE BLOCKCHAIN LAB

Exp. No. Title WeekNo.

CREATE A SIMPLE BLOCKCHAIN 1


1

2 1
BUILDING AND DEPLOYING MULTICHAIN PRIVATE

3 DEPOSIT SOME ETHER IN YOUR METAMASK ACCOUNTS. 2

4 CREATE SEVERAL ACCOUNTS AND MAKE SOME TRANSACTIONS 3


BETWEEN THESE ACCOUNTS

5 3
CREATING A BUSINESS NETWORK USING HYPERLEDGER

CREATING A BUSINESS NETWORK USING HYPERLEDGER 4


6 – II

7 IMPLEMENTATION OF USE CASE – 1: BLOCKCHAIN IN FINANCIAL 5


SOFTWARE AND SYSTEMS

8 . IMPLEMENTATION OF USE CASE – 2: BLOCKCHAIN FOR 6


GOVERNMENT.

BUILDING A PRIVATE ETHEREUM NETWORK. 7


9

10 DEPLOYING SMART CONTRACT & SECURITY 8


1. Create a Simple Blockchain.
Aim:
To Create a Simple Blockchain.
Description:
A blockchain is a decentralized, distributed ledger that is used to record transactions across a
network of computers. Here's a brief overview of how you can create a simple blockchain in
Python:
1. Choose a programming language to implement the blockchain. Python is a popular
choice for its simplicity and large library of modules.
2. Define the structure of each block in the blockchain, including the data it will contain
(e.g., transactions), a timestamp, and a unique identifier (hash) that links it to the
previous block in the chain.
3. Implement the consensus mechanism that will be used to validate and add new blocks
to the blockchain. For example, you might use a proof-of-work algorithm like the one
used by Bitcoin.
4. Implement a method for transmitting new blocks to all nodes in the network, such as a
broadcast protocol like gossip.
5. Test your blockchain to ensure that it is working correctly and that blocks are being
added and validated as expected.

Program:
import hashlib
import datetime
class Block:
def init (self, data, previous_hash):
self.timestamp = datetime.datetime.now()
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
def calculate_hash(self):
sha = hashlib.sha256()
sha.update((str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode('utf-8'))
return sha.hexdigest()
class Blockchain:
def init (self):
self.blocks = [self.get_genesis_block()]
def get_genesis_block(self):
return Block("Genesis Block", "0")
def get_latest_block(self):
return self.blocks[-1]
def add_block(self, data):
previous_hash = self.get_latest_block().hash
new_block = Block(data, previous_hash)
self.blocks.append(new_block)
blockchain = Blockchain()
blockchain.add_block("Rakesh")
blockchain.add_block("Addams")
blockchain.add_block("Thanos")
for block in blockchain.blocks:
print("Data: ", block.data)
print("Timestamp: ", block.timestamp)
print("Previous Hash: ", block.previous_hash)
print("Hash: ", block.hash)
print()
Output:
Data: Genesis Block
Timestamp: 2023-02-06 17:48:21.558570
Previous Hash: 0
Hash: 798b28529bb5e671d4bd770d75a18bfbd3cc48e3434791c16d5e8e982e3ddef3

Data: Rakesh
Timestamp: 2023-02-06 17:48:21.558629
Previous Hash:
798b28529bb5e671d4bd770d75a18bfbd3cc48e3434791c16d5e8e982e3ddef3
Hash: 1808d903e2e4a90d3879420db01b55ebf036d8b493f4488e6755594a72fdfaae
Data: Addams
Timestamp: 2023-02-06 17:48:21.558637
Previous Hash: 1808d903e2e4a90d3879420db01b55ebf036d8b493f4488e6755594a72fdfaae
Hash: a2189be1959baa07aab60605138595d2981f09fdb443149366a87cc9b6680c31

2. Building and Deploying Multichain private


Aim:
To Build and Deploying Multichain private
Description:
Building and deploying a private multichain involves several steps which are as follows:
The above program creates a MultiChain private blockchain using the Python
programminglanguage. The program uses the "os" library to run shell commands. The
"run_command"function takes a shell command as an argument and returns the output of the
command.The"create_multichain_private_blockchain" function takes the name of the
blockchain as anargument and creates a new MultiChain blockchain with private permissions.
It first creates anew MultiChain blockchain using the "multichain-util create" command and
then starts theblockchain using the "multichaind" command. Finally, it grants the necessary
permissions (suchas sending, receiving, creating, and issuing assets) to the default node using
the "multichain-cli" command.The program creates a MultiChain private blockchain named
"mychain".
Program:
import os
def run_command(command):
return os.popen(command).read()
def create_multichain_private_blockchain(chain_name):
run_command("multichain-util create " + chain_name)
run_command("multichaind " + chain_name + " -daemon")
run_command("multichain-cli " + chain_name + " grant $(multichain-cli " + chain_name +
" getaddresses | sed -n 1p) send,receive,create,issue")
print("Creating MultiChain Blockchain...")
create_multichain_private_blockchain("mychain")
print("MultiChain Blockchain created and deployed successfully.")
transactions = []
def add_transaction(sender, receiver, amount):
transaction = {'sender': sender, 'receiver': receiver, 'amount': amount}
transactions.append(transaction)
print("Transaction added to the blockchain: ", transaction)
add_transaction("Alice", "Bob", 10)
print("Transaction created in block 1")
add_transaction("Bob", "Charlie", 5)
print("Transaction created in block 2")
add_transaction("Charlie", "Alice", 20)
print("Transaction created in block 3")
print("Transactions on the Multichain: ", transactions)

Output :
Creating MultiChain Blockchain...
MultiChain Blockchain created and deployed successfully.
Transaction added to the blockchain: {'sender': 'Alice', 'receiver': 'Bob', 'amount': 10}
Transaction created in Genesis block
Transaction added to the blockchain: {'sender': 'Bob', 'receiver': 'Charlie', 'amount': 5}
Transaction created in block 1
Transaction added to the blockchain: {'sender': 'Charlie', 'receiver': 'Alice', 'amount': 20}
Transaction created in block 2
Transactions on the Multichain: [{'sender': 'Alice', 'receiver': 'Bob', 'amount': 10}, {'sender':
'Bob',
'receiver': 'Charlie', 'amount': 5}, {'sender': 'Charlie', 'receiver': 'Alice', 'amount': 20}]
3. Deposit some Ether in your Meta Mask accounts.
Aim:
To Deposit some Ether in your MetaMask accounts.
Description:
Metamask is a popular cryptocurrency wallet compatible with most Ethereum-based
platforms, connecting to over 3,700 crypto and Web3 services. If you are looking to trade
NFTs, tokens or interact with the Ethereum platform, you will need funds in your Metamask
wallet. Adding funds to your account is pretty straightforward, but you risk losing your
money if you do it wrong. step-by-step guide will walk you through various methods you can
use to fund your Metamask account.
How to Add Funds to a Metamask Wallet on a PC
If you are using Metamask on your PC, you will probably access the platform from a browser
extension. There are two primary methods to add funds to your account. You can buy Ether
(ETH) or Ether Tokens (ERC-20) directly on Metamask or transfer funds from a crypto
exchange. Check out how to use these methods.
Buy ETH or ERC-20 on Metamask
Depending on where you live, you may be able to purchase Ethereum directly on Metamask
using a credit card or debit card. You should know that this method can incur additional fees,
and you might not receive the ETH immediately as transactions can take time to complete.
Let’s look at how to buy ETH on Metamask:
Step 1. Install MetaMask on your browser.
To create a new wallet, you have to install the extension first. Depending on your browser,
there are different marketplaces to find it. Most browsers have MetaMask on their stores, so
it’s not that hard to see it, but either way, here they are Chrome, Firefox, and Opera.

1 2
• Click on Install MetaMask as a Google Chrome extension.
• Click Add to Chrome.
• Click Add Extension.

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.
• Click Continue.
• You will be prompted to create a new password. Click Create.

• Proceed by clicking Next and accept the Terms of Use.

Click Reveal Secret Words. There you will see a 12 words seed phrase. This is really
important and usually not a good idea to store digitally, so take your time and write it down.
• 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.
Depositing:
1. Open the Metamask wallet browser extension and tap “Buy ETH.”

2. Select a third-party service like MoonPay or Wyre to facilitate the transaction.


3. Follow the prompts given by the service. These generally include Know Your
Customer (KYC) requirements and filling in your credit card information.

4. Once you are done with the instructions, your funds should appear in your Metamask
wallet.

Program:
class Wallet:
def init (self, address, balance):
self.address = address
self.balance = balance
def add_funds(self, amount):
self.balance += amount
address = input("Enter the Ether wallet address: ")
balance = float(input("Enter the initial Ether balance: "))
my_wallet = Wallet(address, balance)
print("Address:", my_wallet.address)
print("Balance:", my_wallet.balance)
amount = float(input("Enter the amount of Ether to Deposit on the wallet: "))
my_wallet.add_funds(amount)
print("New balance:", my_wallet.balance)
Output:
Enter the Ether wallet address: 0x165CD37b4C644C2921454429E7F9358d18A45e14
Enter the initial Ether balance: 0.25405
Address: 0x165CD37b4C644C2921454429E7F9358d18A45e14
Balance: 0.25405
Enter the amount of Ether to Deposit on the wallet: 0.1220475
New balance: 0.3760975
>>>
4.Create Several Accounts and Make Some Transactions Between These Accounts.
Aim:
Create Several Accounts And Make Some Transactions Between These Accounts
Description:
Metamask is a popular cryptocurrency wallet that allows users to store, manage, and transfer
various cryptocurrencies. Here's an overview of how to make a transaction using Metamask:
1. Install and set up Metamask on your browser. You can download Metamask as a
browser extension for Chrome, Firefox, Opera, and Brave. Once installed, create a
new wallet and make sure to securely store your seed phrase.
2. Fund your wallet. You can purchase cryptocurrencies using a bank transfer, credit
card, or other methods, depending on the options supported by the exchange or
service provider that you use.
3. Open the Metamask wallet and connect it to the website or application where you
want to make a transaction. You can do this by clicking the Metamask extension icon
on your browser and selecting the account that you want to use.
4. Enter the recipient's address and the amount you want to send. Make sure that you
have the correct recipient address and that you double-check the amount of crypto
currency you want to send.
5. Check the transaction details and confirm the transaction. You can review the gas fee,
which is the cost to process the transaction on the blockchain. If you're happy with the
gas fee and other transaction details, click the "Confirm" button.
6. Wait for the transaction to be processed. Depending on the network traffic and other
factors, it may take a few minutes or longer for the transaction to be confirmed on the
blockchain. You can check the transaction status and history on Metamask or other
blockchain explorers.
Program:
class Wallet:
def init (self, wallet_address, balance=0):
self.wallet_address = wallet_address
self.balance = balance
def add_funds(self, amount):
self.balance += amount
def make_transaction(self, amount, receiver_wallet_address):
if amount > self.balance:
print("Error: Insufficient funds")
else:
self.balance -= amount
print("-----------------Transaction successful----------------- ")
print("New balance of Sender:", self.balance)
print("Receiver Wallet Address:", receiver_wallet_address)
accounts = {}
while True:
print("----WELCOME TO METAMASK ---- \n")
option = input('''
Select a option
'create' to create a new account
'add' to add funds
'transaction' to make a transaction,
'quit' to exit:
>''')
if option == "create":
wallet_address = input("Enter wallet address: ")
amount = float(input("Enter the initial balance: "))
accounts[wallet_address] = Wallet(wallet_address, amount)
print("New account created successfully.")
elif option == "add":
wallet_address = input("Enter wallet address: ")
amount = float(input("Enter the amount to add to the wallet: "))
if wallet_address in accounts:
accounts[wallet_address].add_funds(amount)
print("New balance:", accounts[wallet_address].balance)
else:
print("Error: Account not found.")
elif option == "transaction":
sender_wallet_address = input("Enter sender wallet address: ")
receiver_wallet_address = input("Enter receiver wallet address: ")
amount = float(input("Enter the amount to send: "))
if sender_wallet_address in accounts and receiver_wallet_address in accounts:
accounts[sender_wallet_address].make_transaction(amount, receiver_wallet_address)
accounts[receiver_wallet_address].add_funds(amount)
print("New balance of receiver:", accounts[receiver_wallet_address].balance)
else:
print("Error: One or both accounts not found.")
elif option == "quit":
break
else:
print("Invalid option. Please try again.")
Output
:----WELCOME TO METAMASK----
Select a option
'create' to create a new account
'add' to add funds
'transaction' to make a transaction,
'quit' to exit:
>create
Enter wallet address: 123456
Enter the initial balance: 1000
New account created successfully.
----WELCOME TO METAMASK----
Select a option
'create' to create a new account
'add' to add funds
'transaction' to make a transaction,
'quit' to exit:
>create
Enter wallet address: 456789
Enter the initial balance: 1000
New account created successfully.
5.Creating A Business Network Using Hyperledger.
Aim:
Creating A Business Network Using Hyperledger
Description:
We can Create a Business Network Using Hyperledger By AWS Console In order to do that Follow
The Steps Given Below:

• Create a AWS Account and Login To The signin.aws.amazon.com

• Go To Services and then blockchain --> Amazon Managed Blockchain.

1. Choose Create private network.

2. Under Blockchain frameworks:


a. Select the blockchain framework to use. This tutorial is based on Hyperledger Fabric
version 2.2.

b. Select the Network edition to use. The network edition determines attributes of the
network, such as the maximum number of members, nodes per member.
3. Enter a Network name and description.

4. Under Voting Policy, choose the following:


a. Enter the Approval threshold percentage along with the comparator, either Greater
than or Greater than or equal to. For a proposal to pass, the Yes votes cast must meet this
threshold before the vote duration expires.

b. Enter the Proposal duration in hours. If enough votes are not cast within this duration to
either approve or reject a proposal, the proposal status is EXPIRED, no further votes on this
proposal are allowed, and the proposal does not pass.
5. Choose Next, and then, under Create member, do the following to define the first member for the
network, which you own:
a. Enter a Member name that will be visible to all members and an optional Description.
b. Under Hyperledger Fabric certificate authority (CA) configuration specify a username
and password to be used as the administrator on the Hyperledger Fabric CA. Remember the
user name and password. You need them later any time that you create users and resources
that need to authenticate.
c. Choose Next.
6. Choose Admin Username,Passowrd, and then, enable certificate ,Click Next.
7. Review Network options and Member options, and then choose Create network and member.

The Networks list shows the name and Network ID of the network you created, with
a Status of Creating. It takes around 30 minutes for Managed Blockchain to create your network, after
which the Status is Available.

The Business Network Using Hyperledger Have Been Created Successfully,We Can See The Network
Status Is Avaialable.
6. CREATING A BUSINESS NETWORK USING HYPERLEDGER – II
Aim:
To Create A Business Network Using Hyperledger
Description:
Hyperledger Composer is an extensive, open development toolset and framework to make
developing blockchain applications easier. The primary goal is to accelerate time to value,
and make it easier to integrate your blockchain applications with the existing business
systems.
• You can use Composer to rapidly develop use cases and deploy a blockchain solution
in days.
• Composer allows you to model your business network and integrate existing systems
and data with your blockchain applications.

Let’s create first Hyperledger Composer Application


Step 1: Start Hyperledger Composer Online version of Local. Click on Deploy a new
business network
Step 2: Select empty business network

Step 3: Fill basic information, select empty business network and click “deploy” button from
right pannel
Step 4: Connect to “hardware-assets” business network that we have just deployed
Step 5: Click on “+Add a file…” from left panel and select “model file (.cto)”

Write following code in model file. Model file contain asset in our case it’s hardware,
participant in our case participants are employee of organisation and transaction as Allocate
hardware to employee. Each model has extra properties. Make sure your have proper and
unique namespace. In this example I am using “com.kpbird” as namespace. You can access
all models using this namespace i.e. com.kpbird.Hardware, com.kpbird.Employee
/**
* Hardware model
*/namespace com.kpbirdasset Hardware identified by hardwareId {
o String hardwareId
o String name
o String type
o String description
o Double quantity
→ Employee owner
}
participant Employee identified by employeeId {
o String employeeId
o String firstName
o String lastName
}
transaction Allocate {
→ Hardware hardware
→ Employee newOwner
}

Step 6: After Adding Click on Hardware.

Step 7: Create Assets. Click on “Hardware” from left panel and click “+ Create New Assets”
from right top corner and add following code. We will create Employee#01 in next step.
Click on “Create New” button
{
“$class”: “com.kpbird.Hardware”,
“hardwareId”: “MAC01”,
“name”: “MAC Book Pro 2015”,
“type”: “Laptop”,
“description”: “Mac Book Pro”,
“quantity”: 1,
“owner”: “resource:com.kpbird.Employee#01”
}

Steps 8: Let’s create participants. Click “Employee” and click “+ Create New Participants”
and add following code. We will add two employees
{
“$class”: “com.kpbird.Employee”,
“employeeId”: “01”,
“firstName”: “Ketan”,
“lastName”: “Parmar”
}
Click on “Create New” on dialog
{
“$class”: “com.kpbird.Employee”,
“employeeId”: “02”,
“firstName”: “Nirja”,
“lastName”: “Parmar”
}
We have Successfully Created a Business Network and Added Employees in Our
Business
7. Implementation of Use case – 1: Blockchain in Financial Software and Systems
Aim : To Implement Use case – 1: Blockchain in Financial Software and Systems

Description :

Blockchain technology has been adopted in the financial industry for various use cases, including payment
processing, asset management, trade finance, and more. The decentralized nature of blockchain provides a
secure and transparent platform for financial transactions, which can help reduce costs, increase efficiency,
and minimize fraud.

Let's consider a simple example of using blockchain for payment processing in a financial software system. In
this example, we will create a blockchain-based payment processing system that enables users to transfer
cryptocurrencies from one account to another.

To create this system, we will use Python programming language and the hashlib library for generating
cryptographic hashes. Here's how we can implement this system:

Program :

import hashlib

blockchain = []

def add_block():

data = input("Enter Purpouse of Payment: ")

sender = input("Enter sender address: ")

available_currency = print('''List of Crypto Available in your Account

>Bitcoin

>Ether

>Binance Coin

>Tether

''')

crypto_type = input("Choose the Type of Crypto Curreny that you want to make Transaction:")

receiver = input("Enter receiver address: ")

amount = float(input(f"Enter {crypto_type} amount to be transferred: "))

previous_block = blockchain[-1] if len(blockchain) > 0 else None

previous_hash = previous_block['hash'] if previous_block else None


block = {

'data': data,

'sender': sender,

'receiver': receiver,

'amount': amount,

'previous_hash': previous_hash,

'hash': hashlib.sha256(str(data).encode('utf-8') + str(previous_hash).encode('utf-8') +


str(sender).encode('utf-8') + str(receiver).encode('utf-8') + str(amount).encode('utf-8')).hexdigest()

blockchain.append(block)

return block['hash'], block['sender'], block['receiver'], block['amount']

hash1, sender1, receiver1, amount1 = add_block()

print(blockchain)

print("----TRANSACTION RECEIPT --- ")

print('Transaction Hash 1:', hash1)

print('Sender:', sender1)

print('Receiver:', receiver1)

print('Amount:', amount1)

print(' ')

Output :

Enter Purpouse of Payment: Bank Loan Payment

Enter sender address: 77807nielesh@axl

List of Crypto Available in your Account

>Bitcoin

>Ether

>Binance Coin

>Tether
Choose the Type of Crypto Curreny that you want to make Transaction:Ether

Enter receiver address: SBIN00010450

Enter Ether amount to be transferred: 50

[{'data': 'Bank Loan Payment', 'sender': '77807nielesh@axl', 'receiver': 'SBIN00010450', 'amount': 50.0,
'previous_hash': None, 'hash': '8b55dc3dca7789a6a716d7b089f122b186ef9d38aa39c5c75c56b1e02e6ef8aa'}]

-----------TRANSACTION RECEIPT----------

Transaction Hash 1: 8b55dc3dca7789a6a716d7b089f122b186ef9d38aa39c5c75c56b1e02e6ef8aa

Sender: 77807nielesh@axl

Receiver: SBIN00010450

Amount: 50.0

Result : Usecase of blockchain in Financial software and systems has been executed successfully
8. Usecase of Blockchain in Government - VOTING SYSTEM

Aim: To Implement usecase of Blockhain In Government sector –VOTING SYSTEM

Description :

This is a program for an e-voting system. It allows voters to vote for one of the candidates listed in the
"candidates" list, and records each vote in a blockchain.

The program uses the SHA-256 hashing algorithm to create a unique hash for each block in the
blockchain, which is a digital ledger that records all votes cast during an election.

The program starts by asking the user to enter the number of voters. Then, for each voter, it asks for the
voter's ID and the candidate they want to vote for.

If the vote is valid, the program records it in the blockchain and updates the vote count for the candidate.
After all votes have been cast, the program displays the blockchain and the vote counts for each
candidate.

Finally, the program determines the winner based on the candidate with the most votes and displays the
result.

Program :

import hashlib

candidates = ['JAGANANNA', 'CHANDRANNA', 'KA PAUL']

vote_counts = {candidate: 0 for candidate in candidates}

print("ANDHRA PRADESH STATE ELECTION COMMISSION")

print("WELCOME TO E-VOTING SYSTEM")

print(" ------------------------------------------------ ")

blockchain = []

num_voters = int(input('Enter the number of voters: '))


for i in range(num_voters):

voter_id = input(f'\nEnter voter ID for Voter {i + 1}: ')

print(f'Voter {i + 1}, please select a candidate:')

for j, candidate in enumerate(candidates):

print(f'{j + 1}: {candidate}')

vote = int(input()) - 1
if vote in range(len(candidates)):

block_data = {'voter': f'{voter_id}', 'candidate': candidates[vote]}


block_hash = hashlib.sha256(str(block_data).encode()).hexdigest()
blockchain.append({'voter': f'{voter_id}', 'elected_candidate': candidates[vote], 'hash': block_hash})

vote_counts[candidates[vote]] += 1

print(f'{voter_id} voted for {candidates[vote]}')

else:

print("Invalid vote. Please try again.")

print("\nBlockchain:")

for block in blockchain:

print(block)
print()

total_votes = sum(vote_counts.values())

print(f"\nTotal number of votes registered: {total_votes}")

print("\nVote counts:")

for candidate, count in vote_counts.items():

print(f"{candidate}: {count}")
majority_count = max(vote_counts.values())

if list(vote_counts.values()).count(majority_count) == 1:

winner = list(vote_counts.keys())[list(vote_counts.values()).index(majority_count)]

print(f"\n{winner} won with {majority_count} votes.")

else:

print("\nThere is no clear winner.")

print("THANKS FOR USING E-VOTING SYSTEM")


Output:

ANDHRA PRADESH STATE ELECTION COMMISSION

WELCOME TO E-VOTING SYSTEM


-------------------------------------------------

Enter the number of voters: 3

Enter voter ID for Voter 1: 123

Voter 1, please select a candidate:

1: JAGANANNA

2: CHANDRANNA
3: KA PAUL
1

123 voted for JAGANANNA

Enter voter ID for Voter 2: 321

Voter 2, please select a candidate:

1: JAGANANNA

2: CHANDRANNA

3: KA PAUL

321 voted for JAGANANNA

Enter voter ID for Voter 3: 456


Voter 3, please select a candidate:

1: JAGANANNA

2: CHANDRANNA

3: KA PAUL

456 voted for JAGANANNA

Blockchain:

{'voter': '123', 'elected_candidate': 'JAGANANNA', 'hash':


'40319195c103138cf6f8154846ff79e8b47613c7feade55aaea2e6b73d9bbe8e'}

{'voter': '321', 'elected_candidate': 'JAGANANNA', 'hash':


'01f266c60c76bf3aff7f68ab913c0cee4028e18192c709dc7460ff8a3146f36e'}

{'voter': '456', 'elected_candidate': 'JAGANANNA', 'hash':


'2b29ce914f72ead5ac38a47ab73df250aa1671d8853d14d890a20fe8743244c3'}

Total number of votes registered: 3

Vote counts:

JAGANANNA: 3

CHANDRANNA: 0

KA PAUL: 0

JAGANANNA won with 3 votes.


THANKS FOR USING E-VOTING SYSTEM

Result : Usecase of blockchain in Government-voting system has been executed successfully


9. BUILDING A PRIVATE ETHEREUM NETWORK.
Aim:
Building a Private Ethereum Network.

Description:
Ethereum is a decentralized open-source blockchain system that features its own
cryptocurrency which is called ether(ETH). It is a platform that can be used for various apps
which can be deployed by using Smart Contracts.
Step 1: Install Geth on Your System
Go to the official Geth download page and download setup according to your operating system.

While installing Geth make sure to select both checkboxes as shown below.
After installing Geth on your system open PowerShell or command prompt and type geth and
press enter, the following output will be displayed.

Step 2: Create a Folder For Private Ethereum


Create a separate folder for this project. In this case, the folder is MyNetwork.
Step 3: Create a Genesis Block
{
“config”:{
“chainId”:987,
“homesteadBlock”:0,
“eip150Block”:0,
“eip155Block”:0,
“eip158Block”:0
},
“difficulty”:”0x400″,
“gasLimit”:”0x8000000″,
“alloc”:{}
}

Step 4: Execute genesis file


Open cmd or PowerShell in admin mode enter the following command-
geth –identity “yourIdentity” init \path_to_folder\CustomGenesis.json –datadir
\path_to_data_directory\MyPrivateChain
Parameters-
path_to_folder- Location of Genesis file.
path_to_data_directory- Location of the folder in which the data of our private chain will be
stored.
Step 5: Initialize the private network
Launch the private network in which various nodes can add new blocks for this we have to
run the command-
geth –datadir \path_to_your_data_directory\MyPrivateChain –networkid 8080
Create an account by using the command-
personal.newAccount()
After executing this command enter Passphrase and you will get your account number and
save this number for future use.

To check the balance status of the account execute the following command-

Step 7: Mining our private chain of Ethereum


we can start mining by using the following command-
miner.start()
After that, one can stop mining by using the following command-
miner.stop()

Result :
We Have Successfully Builded a Private Ethereum Network.
10. Deploying Smart Contract & Security

AIM: TO Deploy Smart contract and security.


Description:
A smart contract is a self-executing program that automates the actions required in an
agreement or contract. Once completed, the transactions are trackable and irreversible.
Smart contracts permit trusted transactions and agreements to be carried out among disparate,
anonymous parties without the need for a central authority, legal system, or external
enforcement mechanism.

Step 1: Create a wallet at meta-mask

Install MetaMask in your Chrome browser and enable it. Once it is installed, click on its icon
on the top right of the browser page. Clicking on it will open it in a new tab of the browser.
Click on “Create Wallet” and agree to the terms and conditions by clicking “I agree” to
proceed further. It will ask you to create a password.

Step 2: Select any one test network


You might also find the following test networks in your MetaMask wallet:
Robsten Test Network ot etc.
Step 3: Add some dummy Ethers to your wallet
In case you want to test the smart contract, you must have some dummy ethers in your
MetaMask wallet.

To proceed, you need to click “request one ether from the faucet,” and 1 ETH will be added
to your wallet. You can add as many Ethers you want to the test network.
Once the dummy ethers are added to the wallet, you can start writing smart contracts on the
Remix Browser IDE in the Solidity programming language.

Step 4: Deploy your contract


Deploy the smart contract at the Ethereum test network by pressing the deploy button at the
Remix window’s right-hand side.
Wait until the transaction is complete.

Result:
Smart Contract and Security Has been Deployed Successfully.

You might also like