Blockchain Manual 25-26
Blockchain Manual 25-26
CSDL7022
Blockchain Lab Computer
Lab Objectives:
1 To explore Blockchain concepts.
2 To implement public and private Blockchain.
3 To create applications using Blockchain.
4 Demonstrate the concept of blockchain in real world application.
Lab Outcomes:
1 Creating Cryptographic hash using merkle tree.
2 Design Smart Contract using Solidity.
3 Implementing ethereum blockchain using Geth.
List of Experiments
Cryptography is the process of developing a set of techniques and protocols to prevent any third
party from gaining access to the data during a communication process. The word ‘cryptography’ is
derived from two Greek terms, ‘Kryptos’ meaning ‘hidden’ and ‘Graphein’ meaning ‘to write’.
Some terminologies used in cryptography: The method used to secure data from unauthorised
access is called cryptography. Blockchain was built on the concept of enabling secure
communication between two parties therefore, it uses cryptography to secure the transactions that
take place between two nodes on the network. Blockchain uses two main concepts, cryptography
and hashing. The former is used to encrypt messages in a peer-to-peer network, and the latter is
used to secure information on the block and link the blocks in a blockchain.
● Merkle trees, also known as Binary hash trees, are a prevalent sort of data structure in computer
science.
● In bitcoin and other cryptocurrencies, they're used to encrypt blockchain data more efficiently
and securely.
● It's a mathematical data structure made up of hashes of various data blocks that summarize all
the transactions in a block.
● It also enables quick and secure content verification across big datasets and verifies the
consistency and content of the data.
What Is a Merkle Root?
A Merkle root is a simple mathematical method for confirming the facts on a Merkle tree.They're
used in cryptocurrency to ensure that data blocks sent through a peer-to-peer network are whole,
undamaged, and unaltered.They play a very crucial role in the computation required to keep
cryptocurrencies like bitcoin and ether running.
A hash function maps any type of arbitrary data of any length to a fixed-size output. It is
commonly used in cryptography since it is a cryptographic function.
● They are efficient and are well-known for one property: they are irreversible. It's a one-way
function that's only meant to work in one direction.
● Some of the Hash families available are Message Direct (MD), Secure Hash Function (SHF),
and RIPE Message Direct (RIPEMD).
Now, take an example, if you use the SHA256 hash algorithm and pass 101Blockchains as input,
you will get the following output
fbffd63a60374a31aa9811cbc80b577e23925a5874e86a17f712bab874f33ac9
● They're built from the bottom, using Transaction IDs, which are hashes of individual
transactions.
● Each non-leaf node is a hash of its previous hash, and every leaf node is a hash of transactional
data.
Merkle trees provide four significant advantages -Validate the data's integrity: It can be used to
validate the data's integrity effectively.
● Takes little disk space: Compared to other data structures, the Merkle tree takes up very little
disk space.
● Tiny information across networks: Merkle trees can be broken down into small pieces of data
for verification.
● Efficient Verification: The data format is efficient, and verifying the data's integrity takes only a
few moments.
● If Bitcoin didn't include Merkle Trees, per se, every node on the network would have to retain a
complete copy of every single Bitcoin transaction ever made. One can imagine how much
information that would be.
● To confirm that there were no modifications, a computer used for validation would need a lot of
computing power to compare ledgers.
Merkle Trees are a solution to this issue. They hash records in accounting, thereby separating the
proof of data from the data itself.
● Proving that giving tiny amounts of information across the network is all that is required for a
transaction to be valid.
● Furthermore, it enables you to demonstrate that both ledger variations are identical in terms of
nominal computer power and network bandwidth.
Output
Conclusion: Thus we have successfully studied cryptography in block using
merkle tree.
Experiment No-2
Create the embedded wallet and perform the transaction using Meta-mask
What is MetaMask?
MetaMask is a blockchain (Cryptocurrency) wallet used for storing digital coins and money in
online mode safely and securely. It provides a digital bank where you can keep your bitcoin and
other cryptocurrencies.It is mainly used to interact with the Ethereum blockchain. It is fully
equipped with safety and straightforward to use.In simple words, MetaMask is one of the globally
known cryptocurrency wallets. It is a type of browser extension used with the help of web
browsers. An extension is a specific type of application that makes interacting with the Ethereum
network simpler using modern web browsers.MetaMask supplies its customers a software that
allows them to manage Ether and other ERC 20 currencies and engage with Ethereum
decentralized Apps.Its browser extension is use to transmit, buy, receive, and acquire Ethereum or
Ethereum-compatible tokens.Public blockchains like Ethereum are the next evolution of Internet
databases, and MetaMask is the next evolution of the browser. MetaMask keeps no information on
you: not your email address, not your password, and not your Secret Recovery Phrase or other
private keys. You retain all power over your crypto-identity.
● Browser extension
● Mobile app
● Chrome,Firefox,Edge,Brave
● Alternatively, you could also access each browser's extension store and search
for MetaMask. Whatever you prefer!
● Configure your privacy settings
// When installing the MetaMask extension, you'll be able to adjust privacy settings
one-by-one to ensure the app is set up according to your privacy preferences.
To do this, simply hit the 'Advanced configuration' button in the wallet set-up process.
Extension permissions
When adding MetaMask to your browser, you may ask why you 'd have to approve an extension to
“read and change all your data on the websites you visit”. Get ready, the answer is technical:
In order to enable dapps (decentralized applications) to access the blockchain, MetaMask needs to
inject a Web3 JavaScript object into each page. By doing so, it will not change the website, but
merely allows it to access the network. For a fuller explanation of this, see here.
If you are still not convinced, a good way to experiment and manage your browser is to sandbox
your MetaMask: create a separate browser profile so that MetaMask is only installed there. This
will let you get used to MetaMask and Web3 in an environment that's separate from your existing
web identity.
That said, MetaMask is safe for browsing. Welcome — you're joining over 30 million MetaMask
users all over the world!
Fund your wallet
Adding some tokens to your wallet allows you to fully engage in web3. After creating your wallet,
you'll see a prompt in the MetaMask extension to fund your wallet.
From there, you can buy crypto with a debit or credit card, receive crypto from another account, or
transfer crypto from a CEX. Select the option you'd like to start with; you can always use a
different method later.
Configure your privacy settings
When installing the MetaMask extension, you'll be able to adjust privacy settings one-by-one to
ensure the app is set up according to your privacy preferences.
To do this, simply hit the 'Advanced configuration' button in the wallet set-up process. Here you
can toggle/configure settings including:
Gas
Gas is the unit of measure for how much computational work is required to process transactions
and smart contracts. Essentially a transaction fee, the term originates from Ethereum, in which
context it refers to computation undertaken on the Ethereum Virtual Machine (EVM). Since
Ethereum was founded, numerous EVM-compatible (and non-EVM-compatible!) networks have
emerged and adopted similar models.
The term is analogous to the gas that powers a car engine: it's the fluctuating, occasionally
expensive cost of operation. More complex smart contracts require more gas to power their
computation, just as a bigger, more powerful car takes more gas to run.
The method for calculating gas fees varies depending on the network. For example, calculating gas
on Ethereum used to be very complicated, but was considerably simplified with the
implementation of Ethereum Improvement Protocol (EIP) 1559 in August 2021 (also known as the
London Upgrade). Essentially, you pay a base fee for every unit of gas, which is burned (read: it is
deleted, and disappears) upon successful completion of the transaction. On top of the base fee, you
add a priority fee, again per unit of gas, the value of which depends on how quickly you want the
transaction to go through.
Across the broad range of EVM-compatible networks available, gas, or similarly-functioning
alternatives, have essentially become the standard method of calculating transaction costs. Fees are
paid in the network's native token: for example, any transaction on Ethereum requires ETH; using
BSC requires BNB; using Polygon requires POL (previously MATIC). Some networks have
adopted Ethereum's EIP-1559 model wholesale, such as Polygon, whilst others have made
adjustments, including Avalanche, for their C-Chain (which burns both the base fee and priority
fee, rather than just the former).
If you want to read a more in-depth look at how gas works on Ethereum, see here.
Here are some essential details for dealing with gas in MetaMask:
The gas limit is the maximum number of units of gas you are willing to pay for in order to carry
out a transaction or EVM operation. Different operations demand different quantities of gas units.
A normal transaction sending ETH or a token normally costs 21,000 gas, whereas an ERC-20
token approval requires 45,000. Many networks, such as EVM-compatible blockchain Harmony,
use an identical model in which standard transactions also cost 21,000 gas.
info
Do I need to edit gas limit?
No! MetaMask automatically sets your gas limit depending on the transaction you're trying to
execute. In the vast majority of cases, this will be adequate to complete your transaction. If you
want to check or edit it, make sure you have advanced gas controls turned on and hit the button
next to the gas information on the transaction confirmation screen that reads 'Market', 'Low', or
'Aggressive'.
Step1-
Step2-
Expt 5 : Blockchain platform Ganache.
Ganache is used for setting up a personal Ethereum Blockchain for testing your
Solidity contracts. It provides more features when compared to Remix.Ganache is a
popular development tool provided by Truffle Suite for creating a personal Ethereum
blockchain for development and testing purposes. It is designed to make blockchain
development faster and easier by providing a fully controlled environment.
Downloading Ganache
he following URL −
https://archive.trufflesuite.com/ganache/
Now locate Ganache in your Application folder and double-click on its icon to start
Ganache.
Ganache Desktop
Ganache is used for setting up a personal Ethereum Blockchain for testing your
Solidity contracts. It provides more features when compared to Remix.Ganache is a
popular development tool provided by Truffle Suite for creating a personal Ethereum
blockchain for development and testing purposes. It is designed to make blockchain
development faster and easier by providing a fully controlled environment.
Downloading Ganache
https://archive.trufflesuite.com/ganache/
Now locate Ganache in your Application folder and double-click on its icon to start
Ganache.
Ganache Desktop
In order to start the first Hyperledger fabric network Fabric-samples repository will be
used.
1. Install Docker
Installation on Windows: Visit the link to install the Docker setup on Windows.
Hyperledger Fabric samples being used here are highly dependent on the bash script. So
in windows where you need to install docker, it is recommended to use
WSL2(Windows Subsystem for LinuxFor WSL2 you need to ensure that the Docker
desktop has enabled Integration so that WSL2 can Properly interact with the docker
elements. you can do this by going into settings in docker desktop GUI and under the
Resources tab you need to find wsl integration and ensure the checkbox for enable
integration is checked.
Note:
In case if you are using wsl2 in windows you need to mount your local disk or
alternatively you can use mnt command to temporarily mount your local disk at a time.
Installation on Linux: Install the latest version of Docker if it is not already installed.
Run the below command to install:
The Xcode command line tools will be installed as part of the Homebrew installation.
Once Homebrew is ready, installing the necessary prerequisites is very easy:
Homebrew v3.x:
Docker Desktop must be launched to complete the installation so be sure to open the
application after installing it:
open /Applications/Docker.app
2. Install Golang-go
Install the latest version of Go if it is not already installed (only required if writing Go
chaincode or SDK applications).
Installation on Linux/Windows-wsl2:
Installation on Mac:
Install the latest version of jq if it is not already installed (only required for channel
configuration transactions).
Installation on Linux/Windows-wsl2:
Installation on Mac:
brew install jq
4. Install Node/java
You can Install Node/java or use typescript to run the default queries present in fabric
samples.
Installation on Linux/Windows-wsl2:
You can install the node in Linux/wsl2 using the below command:
If needed for Linux you can install npm using the below command:
Install Node on Mac with the below command (npm will be installed with Node):
To start out with fabric samples install the Fabric-samples bash script:
curl -sSLO
https://raw.githubusercontent.com/hyperledger/fabric/main/scripts/install-fabric.sh &&
chmod +x install-fabric.sh
Then you can pull docker containers by running one of these commands:
./install-fabric.sh d s
To install binaries for Fabric samples you can use the command below:
./install-fabric.sh binary
After that installing all the above-required binaries and docker-compose containers you
can check the compose containers either through docker desktop or in the case of Linux
you can use the docker ps -a command to check all available containers and their
respective status.
Fabric samples by default provide a Test Network that we can use to run our first
network. Follow the steps below to build the first network:
Step 1: Navigate through the Fabric-samples folder and then through the Test network
folder where you can find script files using these we can run our network. The test
network is provided for learning about Fabric by running nodes on your local machine.
Developers can use the network to test their smart contracts and applications. It is
recommended not to change the script file.
cd fabric-samples/test-network
Step 2: From inside this directory, you can directly run ./network.sh script file through
which we run the Test Network. By default, we would be running ./network.sh down
command to remove any previous network containers or artifacts that still exist. This is
to ensure that there are no conflicts when we run a new network.
./network.sh down
Step 3: Now you can bring up a network using the following command. This command
creates a fabric network that consists of two peer nodes and one ordering node. No
channel is created when you run ./network.sh up
./network.sh up
If the above command completes successfully, you will see the logs of the nodes being
created below picture:
Congratulation you have successfully run your first Hyperledger Fabric Network.
Summer-time is here and so is the time to skill-up! More than 5,000 learners have now
completed their journey from basics of DSA to advanced level development
programs such as Full-Stack, Backend Development, Data Science.
Sample Case Study on Hyperledger
Overview: Walmart, one of the world's largest retailers, has been using Hyperledger Fabric
to enhance the traceability and transparency of its food supply chain. The project aims to
improve food safety by tracking the provenance of products from farm to shelf.
Implementation:
● Blockchain Network: Hyperledger Fabric was chosen for its modularity and
scalability.
● Data Tracking: The solution records every transaction and movement of products
across the supply chain on the blockchain.
● Verification: The system enables quick tracing of products to their source, allowing
Walmart to address potential issues rapidly and improve overall food safety.
Results:
Industry: Automotive
Overview: IBM has leveraged Hyperledger Sawtooth to develop a blockchain solution for
the automotive industry, specifically to address issues related to vehicle lifecycle
management and the provenance of parts.
Implementation:
Results:
Results:
● User Empowerment: Users have greater control over their identity and personal
data, reducing reliance on central authorities.
● Enhanced Privacy: The system ensures that personal data is shared only with user
consent and in a secure manner.
Overview: Soramitsu, a Japanese fintech company, has used Hyperledger Iroha to develop
a digital asset management platform. The platform is aimed at improving the efficiency of
financial transactions and asset management.
Implementation:
● Blockchain Network: Hyperledger Iroha was chosen for its simplicity and ease of
integration.
● Digital Assets: The platform supports the creation, management, and transfer of
digital assets, including cryptocurrencies and other financial instruments.
Results:
Industry: Finance
Implementation:
Results:
Implementation:
● Blockchain Network: Hyperledger Burrow was chosen for its integration with the
Ethereum Virtual Machine (EVM) and support for smart contract execution.
● Legal Contracts: The platform allows for the creation, management, and automatic
execution of legal contracts based on predefined conditions.
Results:
Industry: Interoperability
Implementation:
Results:
Conclusion
Hyperledger provides a range of blockchain frameworks suited for various industries and
use cases. From supply chain management to digital identity and financial services,
Hyperledger projects offer solutions that address specific business needs through secure,
transparent, and efficient blockchain technology. Each case study demonstrates the
versatility and impact of Hyperledger frameworks in real-world applications, showcasing
their potential to transform industries and streamline operations.
Industry: Finance
Implementation:
● Platform: Ethereum
● Smart Contracts: Uniswap uses Ethereum’s smart contract functionality to
automate and manage trading, liquidity provision, and token swaps.
● Automated Market Maker (AMM): The protocol employs AMM
algorithms to facilitate trading and liquidity provision.
Results:
Overview: Bitcoin is often referred to as "digital gold" due to its function as a store
of value and hedge against inflation. It operates on a proof-of-work blockchain and
has become a significant asset class for institutional and retail investors.
Implementation:
● Platform: Bitcoin
● Security: Utilizes a decentralized network and proof-of-work consensus
mechanism to secure the blockchain.
● Adoption: Widely accepted by both individual and institutional investors as a
digital asset and investment vehicle.
Results:
Implementation:
Results:
Implementation:
● Platform: EOSIO
● Scalability: EOSIO’s high throughput and scalability support the operation of
the Voice platform with fast transaction speeds.
● Tokenization: Uses EOS tokens for incentivizing and rewarding user
engagement and content creation.
Results:
Overview: Nomadic Labs, a research and development entity, has used Tezos to
develop smart contracts and decentralized applications with a focus on on-chain
governance and upgradability.
Implementation:
● Platform: Tezos
● Governance: Tezos employs an on-chain governance mechanism that allows
stakeholders to propose and vote on protocol upgrades.
● Smart Contracts: Supports formal verification of smart contracts to ensure
correctness.
Results:
Implementation:
Results:
Overview: Voltron, a trade finance platform, uses Corda to streamline and digitize
the trade finance process, enabling faster and more efficient trade transactions
between parties.
Implementation:
● Platform: Corda
● Private Transactions: Corda’s design focuses on privacy and confidentiality,
allowing only authorized parties to access transaction details.
● Smart Contracts: Uses Corda’s smart contracts to automate trade finance
workflows and reduce paperwork.
Results:
● Efficiency: The platform has improved the efficiency of trade finance
processes by reducing transaction times and paperwork.
● Cost Savings: Streamlined processes have led to cost savings for businesses
involved in trade finance.
Implementation:
● Platform: Algorand
● Consensus Mechanism: Utilizes a pure proof-of-stake (PPoS) consensus
protocol to achieve high performance and scalability.
● Digital Assets: Supports the creation and management of custom digital
assets and tokens.
Results:
Conclusion
Table Of Contents
1.Abstract
2.Introduction
3. Implementation
4.Result
5.Conclusion
Implementation
Creating a blockchain application as a mini-project is a great way to understand the
practical aspects of blockchain technology. For this mini-project, we’ll build a
simple Decentralized Voting Application using Ethereum and Solidity. This example
will cover:
○
bash
Copy code
mkdir voting-app
cd voting-app
truffle init
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Voting {
// Declare state variables
address public owner;
mapping(address => bool) public voters;
mapping(string => uint) public
votesReceived;
string[] public candidateList;
// Constructor
constructor(string[] memory
candidateNames) {
owner = msg.sender;
candidateList = candidateNames;
}
bash
Copy code
truffle compile
javascript
Copy code
const Voting = artifacts.require("Voting");
module.exports = function(deployer) {
const candidateNames = ["Alice", "Bob",
"Charlie"];
deployer.deploy(Voting, candidateNames);
};
●
bash
Copy code
truffle migrate --network development
Create a new directory client inside your project and initialize it with a basic
HTML and JavaScript setup:
bash
Copy code
mkdir client
cd client
npm init -y
npm install web3
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Voting App</title>
</head>
<body>
<h1>Voting Application</h1>
<div>
<h2>Vote for a Candidate</h2>
<input type="text" id="candidateName"
placeholder="Candidate Name">
<button
onclick="vote()">Vote</button>
</div>
<div>
<h2>Get Vote Count</h2>
<input type="text"
id="candidateNameCount"
placeholder="Candidate Name">
<button onclick="getVoteCount()">Get
Vote Count</button>
<p id="voteCountResult"></p>
</div>
<script
src="https://cdn.jsdelivr.net/npm/web3@latest
/dist/web3.min.js"></script>
<script src="app.js"></script>
</body>
</html>
javascript
Copy code
const Web3 = require('web3');
const web3 = new
Web3('http://localhost:8545'); // Connect to
Ganache
const contractAddress =
'YOUR_CONTRACT_ADDRESS';
const contractABI = [ /* ABI generated by
Truffle */ ];
document.getElementById('voteCountResult').in
nerText = `Vote Count: ${count}`;
}
You can use a simple HTTP server to serve your frontend files:
bash
Copy code
npm install -g http-server
http-server client