Building Private Blockchain Lab Manual (1-10)
Building Private Blockchain Lab Manual (1-10)
ANNAMACHARYAINSTITUTEOFTECHNOLOGY&SCIENCES::TIRUPATI
(AutonomousInstitution -UGC,Govt.ofIndia)
(Recognizedunder2(f)and 12(B)ofUGC ACT 1956)
COURSECODE:20APC3623
COURSETITLE:BUILDING PRIVATE BLOCKCHAIN LAB
2 1
BUILDING AND DEPLOYING MULTICHAIN PRIVATE
5 3
CREATING A BUSINESS NETWORK USING HYPERLEDGER
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
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.
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.”
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:
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.
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.
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 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():
>Bitcoin
>Ether
>Binance Coin
>Tether
''')
crypto_type = input("Choose the Type of Crypto Curreny that you want to make Transaction:")
'data': data,
'sender': sender,
'receiver': receiver,
'amount': amount,
'previous_hash': previous_hash,
blockchain.append(block)
print(blockchain)
print('Sender:', sender1)
print('Receiver:', receiver1)
print('Amount:', amount1)
print(' ')
Output :
>Bitcoin
>Ether
>Binance Coin
>Tether
Choose the Type of Crypto Curreny that you want to make Transaction:Ether
[{'data': 'Bank Loan Payment', 'sender': '77807nielesh@axl', 'receiver': 'SBIN00010450', 'amount': 50.0,
'previous_hash': None, 'hash': '8b55dc3dca7789a6a716d7b089f122b186ef9d38aa39c5c75c56b1e02e6ef8aa'}]
-----------TRANSACTION RECEIPT----------
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
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
blockchain = []
vote = int(input()) - 1
if vote in range(len(candidates)):
vote_counts[candidates[vote]] += 1
else:
print("\nBlockchain:")
print(block)
print()
total_votes = sum(vote_counts.values())
print("\nVote counts:")
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)]
else:
1: JAGANANNA
2: CHANDRANNA
3: KA PAUL
1
1: JAGANANNA
2: CHANDRANNA
3: KA PAUL
1: JAGANANNA
2: CHANDRANNA
3: KA PAUL
Blockchain:
Vote counts:
JAGANANNA: 3
CHANDRANNA: 0
KA PAUL: 0
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.
To check the balance status of the account execute the following command-
Result :
We Have Successfully Builded a Private Ethereum Network.
10. Deploying Smart Contract & Security
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.
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.
Result:
Smart Contract and Security Has been Deployed Successfully.