0% found this document useful (0 votes)
63 views34 pages

Blockchain Lab1

assignment

Uploaded by

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

Blockchain Lab1

assignment

Uploaded by

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

HMR

Institute Of Technology And Management


HAMIDPUR, DELHI - 110036

Affiliated to
GURU GOBIND SINGH INDRAPRASTHA
UNIVERSITY
Sector - 16c Dwarka, Delhi - 110075, India

LABORATORY FILE

Blockchain Technology Lab


(CIE - 403P)

For

Computer Science and Engineering

Submitted To: Submitted By :


Mrs. Preeti Kalra Abhishek Kumar
Assistant Professor 06613302721
CSE Department CSE 7th Sem
INDEX

S.NO NAME OF EXPERIMENT DAT REMARKS SIGNATU


. E RE
Create a Simple Blockchain in any
1.
suitable programming language.

Use Geth to Implement Private


2.
Ethereum BlockChain.

Build Hyperledger Fabric Client


3.
Application.

Create and deploy a block chain


network using Hyperledger Fabric SDK
4. for Java Set up and initialize the
channel, install and instantiate
chaincode, and perform invoke and
query on your block chain network.

Interact with a block chain network.


Execute transactions and requests
against a block chain network by
5. creating an app to test the network
and its rules.
(https://developer.ibm.com/patterns/in
teracting-with-ablock chain-network/)

Deploy an asset-transfer app using


block chain. Learn app development
within a Hyperledger Fabric network
6. (https://developer.ibm.com/patterns/d
eploy-an-asset-transfer-app-using-
block chain/)

Use block chain to track fitness club


rewards Build a web app that uses
7. Hyperledger Fabric to track and trace
member rewards.

Interact with a blockchain network.


Execute transactions and requests
8. against a blockchain network by
creating an app to test the network
and its rules.

To implement a Proof of Stake (PoS)


consensus algorithm in a simple
9. blockchain system using a suitable
programming language (e.g., Python,
JavaScript).
To develop and deploy a smart
10. contract using Solidity to manage a
supply chain system on the Ethereum
blockchain.
EXPERIMENT - 1
AIM - Create a simple Blockchain in any suitable programming
language.

LANGUAGE - Python.

CODE : import hashlib


import json
from time import time
class Blockchain:
def __init__(self):
self.chain = []
self.pending_transactions = []
self.create_block(proof=1, previous_hash='0') # Create
the genesis block
def create_block(self, proof, previous_hash):
transactions, proof, and the hash of the previous block
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.pending_transactions,
'proof': proof,
'previous_hash': previous_hash
}
self.pending_transactions = [] # Clear pending
transactions once added to the block
self.chain.append(block)
return block
def get_previous_block(self):
return self.chain[-1]
def proof_of_work(self, previous_proof):
new_proof = 1
check_proof = False
equation while check_proof is False:
while check_proof is False:
hash_operation = hashlib.sha256(str(new_proof**2 -
previous_proof**2).encode()).hexdigest()
if hash_operation[:4] == '0000':
check_proof = True
else:
new_proof += 1
return new_proof
def hash(self, block):
encoded_block = json.dumps(block,
sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()
def is_chain_valid(self, chain):
previous_block = chain[0]
block_index = 1
while block_index < len(chain):
block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
proof = block['proof']
hash_operation = hashlib.sha256(str(proof**2 -
previous_proof**2).encode()).hexdigest()
if hash_operation[:4] != '0000':
return False
previous_block = block
block_index += 1
return True
def add_transaction(self, sender, receiver, amount):
self.pending_transactions.append({
'sender': sender,
'receiver': receiver,
'amount': amount
})
previous_block = self.get_previous_block()
return previous_block['index'] + 1
blockchain = Blockchain()
blockchain.add_transaction(sender="Alice", receiver="Bob",
amount=50)
blockchain.add_transaction(sender="Bob", receiver="Charlie",
amount=25)
previous_block = blockchain.get_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash)
print("Blockchain: ", blockchain.chain)
print("Is Blockchain Valid? ",
blockchain.is_chain_valid(blockchain.chain))

OUTPUT :
EXPERIMENT - 2
AIM - Use Geth to Implement Private Ethereum Blockchain.

IMPLEMENTATION - To implement a private Ethereum blockchain


using Geth (Go Ethereum), you need to follow a
series of steps. Geth is a powerful tool that can help
you create, manage, and interact with private
Ethereum networks.

PREREQUISITES - Geth installed on your system. You can download


it from Go Ethereum.
Solidity Compiler if you plan to write and deploy
smart contracts.
Node.js & NPM for developing DApps.

STEP-BY-STEP GUIDE TO SET UP A PRIVATE ETHEREUM


BLOCKCHAIN WITH GETH

Step 1 : Install Geth


On Windows/Mac: Download the installer from Geth’s official page.

Step 2 : Create a Genesis Block


The genesis block is the starting point of your blockchain. It’s a JSON
file that defines the configuration of your private blockchain.
Create a file called genesis.json with the following content :
{
"config": {
"chainId": 1234,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0
},
"difficulty": "1",
"gasLimit": "8000000",
"alloc": {}
}
Step 3 : Initialise the Genesis Block
Once you have your genesis.json file, you need to initialise your
private blockchain using Geth :
geth --datadir ./myPrivateChain init genesis.json

Step 4 : Start the Private Blockchain


Now, you can start your private Ethereum network with the following
command :
geth --datadir ./myPrivateChain --networkid 1234 --http --http.addr
127.0.0.1 --http.port 8545 --http.corsdomain "*" --http.api
"eth,net,web3,personal,miner" console

Step 5 : Create Accounts for Mining and Transactions


In the Geth console, you can create new accounts that will be used
for mining and performing transactions.
> personal.newAccount("your-password")

Step 6 : Start Mining


Now, you can start mining on your private blockchain. Mining will help
generate Ether and validate transactions.
> miner.start(1)
Once you start mining, the Geth console will display block generation
information, and you’ll start earning Ether for your account. To check
your balance, use :
> eth.getBalance(eth.accounts[0])

Step 7 : Stop Mining


To stop mining, use :
> miner.stop()
EXPERIMENT - 3
AIM - Build Hyperledger Fabric Client Application.

IMPLEMENTATION - Building a Hyperledger Fabric


client application involves interacting with the
Fabric blockchain through the Fabric SDK (e.g.,
Hyperledger Fabric SDK for Node.js, Java, or Go).
We will go through creating a Node.js client
application, as it’s one of the most commonly used
options for developing Hyperledger Fabric client
applications.

PREREQUISITES - Hyperledger Fabric Network : A running Fabric


network (or test network). You can set one up locally
using the official Fabric samples.
Node.js and npm : Make sure you have Node.js and
npm installed.
Fabric SDK for Node.js : Install the SDK.
Basic understanding of Hyperledger Fabric : You
should be familiar with concepts like peers, orderers,
channels, smart contracts (chaincode), and identity
management.

STEP-BY-STEP GUIDE TO BUILD HYPERLEDGER FABRIC CLIENT


APPLICATION

Step 1 : Set Up Hyperledger Fabric Network


Clone the fabric-samples repository :
git clone https://github.com/hyperledger/fabric-samples
cd fabric-samples/test-network
Use the test network script to start the network :
./network.sh up createChannel -c mychannel -ca
Deploy the chaincode (e.g., basic asset management chaincode) :
./network.sh deployCC -ccn basic -ccp
../asset-transfer-basic/chaincode-javascript -ccl javascript

Step 2 : Install Hyperledger Fabric SDK for Node.js


Create a directory for your client application and navigate to it :
mkdir fabric-client-app
cd fabric-client-app
npm init -y

Now, install the required packages for interacting with Hyperledger


Fabric :
npm install fabric-network fabric-ca-client
npm install --save [email protected]

Step 3 : Configure the Client Application


In the root of your project, create the following directory structure :

fabric-client-app/

├── connection-org1.json // Connection profile for Org1
├── wallet/ // Stores identities (certificates) of users
└── index.js // Main client application code

Connection Profile (connection-org1.json) :


Create a connection-org1.json file that specifies the connection
details for Org1 (this is already available in the test network
configuration) :

{
"name": "fabric-network",
"version": "1.0.0",
"client": {
"organization": "Org1",
"connection": {
"timeout": {
"peer": {
"endorser": "300"
}
}
}
},
"organizations": {
"Org1": {
"mspid": "Org1MSP",
"peers": ["peer0.org1.example.com"],
"certificateAuthorities": ["ca.org1.example.com"]
}
},
"peers": {
"peer0.org1.example.com": {
"url": "grpc://localhost:7051"
}
},
"certificateAuthorities": {
"ca.org1.example.com": {
"url": "http://localhost:7054",
"caName": "ca-org1"
}
}
}

Step 4 : Write the Client Application


Create a file index.js in the root of your project directory. This script
will :
● Enroll an admin identity and register a new user.
● Submit a transaction to the deployed chaincode.

'use strict';
const { Gateway, Wallets } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const fs = require('fs');
const path = require('path');
async function main() {
try {
const ccpPath = path.resolve(__dirname, 'connection-
org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
const caURL =
ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await
Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
const adminExists = await wallet.get('admin');
if (!adminExists) {
const enrollment = await ca.enroll({
enrollmentID: 'admin',
enrollmentSecret: 'adminpw'
});
const identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put('admin', identity);
console.log('Successfully enrolled admin user "admin"
and imported it into the wallet');
}
const userExists = await wallet.get('appUser');
if (!userExists) {
const adminIdentity = await wallet.get('admin');
const provider =
wallet.getProviderRegistry().getProvider(adminIdentity.type);
const adminUser = await
provider.getUserContext(adminIdentity, 'admin');
const secret = await ca.register({
affiliation: 'org1.department1',
enrollmentID: 'appUser',
role: 'client'
}, adminUser);
const enrollment = await ca.enroll({
enrollmentID: 'appUser',
enrollmentSecret: secret
});
const userIdentity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put('appUser', userIdentity);
console.log('Successfully registered and enrolled user
"appUser" and imported it into the wallet');
}
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'appUser',
discovery: { enabled: true, asLocalhost: true } });
const network = await gateway.getNetwork('mychannel');
const contract = network.getContract('basic');
await contract.submitTransaction('CreateAsset', 'asset1',
'Blue', '5', 'Tom', '1000');
console.log('Transaction has been submitted');
await gateway.disconnect();
} catch (error) {
console.error(`Failed to submit transaction: ${error}`);
process.exit(1);
}
}
main();

Step 5 : Run the Application


Make sure your Fabric network is running. Then run the Node.js
application :
node index.js

If everything is set up correctly, you should see :

EXPERIMENT - 4
AIM - Create and deploy a block chain network using Hyperledger
Fabric SDK for Java Set up and initialise the channel, install and
instantiate chaincode, and perform invoke and query on your
block chain network.

IMPLEMENTATION - To create and deploy a


blockchain network using Hyperledger Fabric SDK
for Java, you need to set up a Hyperledger Fabric
network, install and instantiate the chaincode, and
use the Fabric SDK to interact with it. This involves :

1. Setting up the Hyperledger Fabric network (create


a channel and join peers).
2. Deploying chaincode (installing and instantiating it
on the network).
3. Writing a Java client application using the Fabric
SDK for Java to interact with the network (invoke
transactions and query the blockchain).
Here’s a step-by-step guide.

PREREQUISITES - Hyperledger Fabric Network:


Either a local test network or a cloud-hosted network.
Java JDK 8 or later.
Maven to manage dependencies.
Docker for running the Fabric containers.
Hyperledger Fabric SDK for Java (we’ll configure it via
Maven).

STEP-BY-STEP GUIDE TO BUILD HYPERLEDGER FABRIC

Step 1 : Set Up Hyperledger Fabric Network


Clone the fabric-samples repository :
git clone https://github.com/hyperledger/fabric-samples
cd fabric-samples/test-network
Use the test network script to start the network :
./network.sh up createChannel -c mychannel -ca

Deploy the chaincode (e.g., basic asset management chaincode) :


./network.sh deployCC -ccn basic -ccp
../asset-transfer-basic/chaincode-javascript -ccl javascript
Ensure the network is running and chaincode is deployed :
docker ps

Step 2 : Set Up the Java Client Application


Now that the network is running, we’ll set up the Hyperledger Fabric
SDK for Java and create a Java client application to interact with the
blockchain.
Create a directory for your client application and navigate to it :
mkdir fabric-client-app
cd fabric-client-app

Inside the project folder, create a basic Maven project :


mvn archetype:generate -DgroupId=com.example.fabric -
DartifactId=fabric-java-client -DarchetypeArtifactId=maven-
archetype-quickstart -DinteractiveMode=false

Open pom.xml and add the following dependencies :


<dependencies>
<!-- Hyperledger Fabric SDK -->
<dependency>
<groupId>org.hyperledger.fabric-sdk-java</groupId>
<artifactId>fabric-sdk-java</artifactId>
<version>2.2.13</version>
</dependency>
<dependency>
<groupId>org.hyperledger.fabric-sdk-java</groupId>
<artifactId>fabric-gateway-java</artifactId>
<version>2.2.13</version>
</dependency>
<!-- JSON for handling configuration files -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
</dependencies>

Build the project to download dependencies :


mvn clean install

You need a connection profile and identity to connect to the Fabric


network.
Copy the connection-org1.yaml from the test network into your
project :
cp
fabric-samples/test-network/organizations/peerOrganizations/org1.ex
ample.com/connection-org1.yaml .
Use the admin identity from Org1. Export the admin certificates using
this command :
cp -r
fabric-samples/test-network/organizations/peerOrganizations/org1.ex
ample.com/users/[email protected]/msp ./wallet/org1-admin

Step 3 : Write Java Code to Interact with the Blockchain


Initialize Fabric SDK
This step connects the Java application to the Fabric network using
the connection profile and identity.

package com.example.fabric;
import org.hyperledger.fabric.gateway.*;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FabricClientApp {
public static void main(String[] args) throws Exception {
Path walletPath = Paths.get("wallet");
Wallet wallet = Wallets.newFileSystemWallet(walletPath);
Path networkConfigPath = Paths.get("connection-org1.yaml");
Gateway.Builder builder = Gateway.createBuilder()
.identity(wallet, "admin")
.networkConfig(networkConfigPath)
.discovery(true);
try (Gateway gateway = builder.connect()) {
Network network = gateway.getNetwork("mychannel");
Contract contract = network.getContract("basic");
contract.submitTransaction("CreateAsset", "asset1", "Blue",
"100", "Tom", "5000");
System.out.println("Asset 'asset1' has been created");
byte[] result = contract.evaluateTransaction("ReadAsset",
"asset1");
System.out.println("Query Result: " + new String(result));
}
}
}

Compile the Application :


mvn package
Run the Application :
java -cp target/fabric-java-client-1.0-SNAPSHOT.jar
com.example.fabric.FabricClientApp

OUTPUT :

Step 4 : Invoke More Transactions and Query the Blockchain


You can extend the client application to invoke other transactions
provided by the basic chaincode. For example :

Transfer an Asset :
contract.submitTransaction("TransferAsset", "asset1", "Jerry");
Delete an Asset :
contract.submitTransaction("DeleteAsset", "asset1");
Query All Assets :
byte[] result = contract.evaluateTransaction("GetAllAssets");
System.out.println("Query All Assets Result: " + new String(result));

EXPERIMENT - 5
AIM - Interact with a block chain network. Execute transactions
and requests against a block chain network by creating an app
to test the network and its rules
(https://developer.ibm.com/patterns/interacting-with-a-block
chain-network/)

This example demonstrates how to connect to the network, submit a


transaction, and query an asset.

PREREQUISITES - • Node.js installed


• Hyperledger Fabric network running
• IBM Blockchain Platform or a local Hyperledger
Fabric setup
• A smart contract deployed on the network
• Node.js SDK (fabric-network) installed

Directory Structure

blockchain-app/

├── connection.json # Connection profile
├── wallet/ # Wallet to store user credentials
└── index.js # Main application file

Step 1 : Install Hyperledger Fabric SDK for Node.js

Initialize a new Node.js project and install the necessary


dependencies :
npm init -y
npm install fabric-network fabric-ca-client
Step 2 : Sample Smart Contract
Assume you have a smart contract deployed with the following
functions :
● createAsset(assetID, color, size, owner): Creates a new asset.
● readAsset(assetID): Returns the asset details.

Step 3 : Connection Profile

The connection.json file is your connection profile to connect to the


Hyperledger Fabric network. This file can be generated by the IBM
Blockchain Platform when exporting your network configuration.

Here is an example of what the connection.json file might look like :

{
"name": "fabric-network",
"version": "1.0.0",
"channels": {
"mychannel": {
"orderers": ["orderer.example.com"],
"peers": {
"peer0.org1.example.com": {}
}
}
},
"organizations": {
"Org1": {
"mspid": "Org1MSP",
"peers": ["peer0.org1.example.com"]
}
},
"orderers": {
"orderer.example.com": {
"url": "grpcs://localhost:7050"
}
},
"peers": {
"peer0.org1.example.com": {
"url": "grpcs://localhost:7051"
}
}
}

Step 4 : Main Application Code (index.js)


The index.js file is the main application that connects to the
blockchain network, submits a transaction, and queries the asset.

Code :

const { Gateway, Wallets } = require('fabric-network');


const path = require('path');
const fs = require('fs');
async function main() {
try {
const ccpPath = path.resolve(__dirname, 'connection.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await
Wallets.newFileSystemWallet(walletPath);
const identity = await wallet.get('admin');
if (!identity) {
console.log('An identity for the user "admin" does not
exist in the wallet');
return;
}
const gateway = new Gateway();
await gateway.connect(ccp, {
wallet,
identity: 'admin',
discovery: { enabled: true, asLocalhost: true }
});
const network = await gateway.getNetwork('mychannel');
const contract = network.getContract('mySmartContract');
console.log('Submitting transaction to create an asset...');
await contract.submitTransaction('createAsset', 'asset1',
'blue', '100', 'owner1');
console.log('Transaction has been submitted');
console.log('Querying the created asset...');
const result = await
contract.evaluateTransaction('readAsset', 'asset1');
console.log(`Asset details: ${result.toString()}`);

await gateway.disconnect();
} catch (error) {
console.error(`Failed to submit transaction: ${error}`);
process.exit(1);
}
}
main();
Step 5 : Run the Application
Make sure your Fabric network is running. Then run the Node.js
application :
node index.js

OUTPUT :

EXPERIMENT - 6
AIM - Deploy an asset-transfer app using block chain. Learn app
development within a Hyperledger Fabric network.
(https://developer.ibm.com/patterns/deploy-an-asset-transfer-
app-using-block chain/)
THEORY - Hyperledger Fabric is an open-source
framework used to build blockchain-based distributed
applications. The asset-transfer app allows transferring
digital assets between parties, providing a transparent and
secure mechanism to handle transactions. This experiment
focuses on learning app development within a Hyperledger
Fabric network, which includes setting up the network,
installing chaincode (smart contracts), and interacting with
the blockchain ledger to manage assets.

STEPS -
1. Set up a Hyperledger Fabric environment :
● Install Docker and Docker Compose.
● Download the Hyperledger Fabric binaries and samples.

2. Launch the test network :


● Navigate to the fabric-samples/test-network directory.
● Run the command ./network.sh up createChannel to start the
network and create a channel.

3. Deploy the asset-transfer chaincode :


● Install and approve the chaincode for the asset-transfer app.
● Run the command ./network.sh deployCC -ccn asset-transfer -ccp
../asset-transfer-basic/chaincode-go -ccl go.

4. Write the application logic :


● Use the Fabric SDK to create an application that interacts with
the network.
● Implement methods to create, transfer, and query assets.

5. Test the app :


● Use the application to perform various transactions, such as
creating an asset and transferring it to another user.
CODE :
Here is a snippet of the code used to deploy the chaincode and
interact with the app :
./network.sh deployCC -ccn asset-transfer -ccp ../asset-transfer-
basic/chaincode-go -ccl go
Go code for asset creation :
func CreateAsset(ctx contractapi.TransactionContextInterface, id
string, owner string, value int) error {
asset := Asset{
ID: id,
Owner: owner,
Value: value,
}
assetJSON, err := json.Marshal(asset)
if err != nil {
return err
}
return ctx.GetStub().PutState(id, assetJSON)
}

OUTPUT :

CONCLUSION
In this experiment, we successfully deployed an asset-transfer app
using the Hyperledger Fabric blockchain. We learned how to set up a
Fabric network, deploy chaincode, and create an app to manage
digital assets within the network.

EXPERIMENT - 7
AIM - Use block chain to track fitness club rewards Build a web app
that uses Hyperledger Fabric to track and trace member
rewards.

THEORY - A blockchain network consists of multiple nodes


and smart contracts that define the rules governing the
ledger. To interact with such a network, we can build an
application that interfaces with the blockchain, submits
transactions, and queries the ledger. This experiment will
help in understanding how to execute operations like
querying data, invoking chaincode, and validating
transactions on a Hyperledger Fabric network.

STEPS -
1. Set up a Hyperledger Fabric environment :
● Install Docker, Docker Compose, and download the Fabric
samples.

2. Start the network :


● Navigate to fabric-samples/test-network.
● Use ./network.sh up createChannel to start the network.

3. Deploy chaincode for testing transactions :


● Write a simple chaincode to allow operations like asset creation
and transfer.
● Deploy the chaincode using ./network.sh deployCC.

4. Create an app to interact with the blockchain :


● Build a Node.js or Go application.
● Connect to the Fabric network using the SDK.
● Create functions to submit transactions (like asset creation or
transfer) and query the ledger.

5. Test transactions and queries :


● Use the app to test various blockchain operations (e.g., creating
assets, querying their status, executing transfers).

CODE :
Smart contract code for fitness rewards :
func AddRewardPoints(ctx contractapi.TransactionContextInterface,
memberID string, points int) error {
rewards := Rewards{
MemberID: memberID,
Points: points,
}
rewardJSON, err := json.Marshal(rewards)
if err != nil {
return err
}
return ctx.GetStub().PutState(memberID, rewardJSON)
}

OUTPUT :

CONCLUSION
We successfully built a web application using Hyperledger Fabric to
track and trace fitness club rewards. The application ensures secure
tracking of member rewards and provides a tamper-proof record of
activities and points using blockchain technology.

EXPERIMENT - 8
AIM - Interact with a blockchain network. Execute transactions and
requests against a blockchain network by creating an app to test
the network and its rules.
THEORY - A blockchain network consists of multiple nodes
and smart contracts that define the rules governing the
ledger. To interact with such a network, we can build an
application that interfaces with the blockchain, submits
transactions, and queries the ledger. This experiment will
help in understanding how to execute operations like
querying data, invoking chaincode, and validating
transactions on a Hyperledger Fabric network.

STEPS -
1. Set up a Hyperledger Fabric environment :
● Install Docker, Docker Compose, and download the Fabric
samples.

2. Start the network :


● Navigate to fabric-samples/test-network.
● Use ./network.sh up createChannel to start the network.

3. Deploy chaincode for testing transactions :


● Write a simple chaincode to allow operations like asset creation
and transfer.
● Deploy the chaincode using ./network.sh deployCC.

4. Create an app to interact with the blockchain :


● Build a Node.js or Go application.
● Connect to the Fabric network using the SDK.
● Create functions to submit transactions (like asset creation or
transfer) and query the ledger.

5. Test transactions and queries :


● Use the app to test various blockchain operations (e.g., creating
assets, querying their status, executing transfers).

CODE :
Example transaction execution in Node.js :
const { Gateway, Wallets } = require('fabric-network');
const path = require('path');
async function main() {
const ccpPath = path.resolve(__dirname, 'connection.json');
const wallet = await Wallets.newFileSystemWallet('./wallet');
const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'admin' });
const network = await gateway.getNetwork('mychannel');
const contract = network.getContract('asset-transfer');
await contract.submitTransaction('CreateAsset', 'asset1', 'User1',
'100');
console.log('Asset created successfully');
}
main();

OUTPUT :

CONCLUSION
In this experiment, we created an app to interact with a blockchain
network, tested its rules, and executed transactions. The experiment
demonstrates how applications can be built to submit requests to a
blockchain and validate transactions within a decentralized system.

EXPERIMENT - 9
AIM - To implement a Proof of Stake (PoS) consensus algorithm
in a simple blockchain system using a suitable programming
language (e.g., Python, JavaScript).

THEORY - Consensus mechanisms are essential in


blockchain systems to validate transactions and ensure
agreement across the distributed network. Proof of Stake
(PoS) is a consensus algorithm where validators are chosen
to create new blocks and confirm transactions based on the
number of coins they hold (their stake) rather than
computational power (as in Proof of Work). PoS is more
energy-efficient than PoW and is used in many modern
blockchain networks, including Ethereum 2.0.
In PoS, a validator is randomly selected based on their
stake. Validators are rewarded for validating blocks, and
any malicious behavior can lead to penalties, such as losing
their stake. This experiment involves creating a basic
blockchain with a PoS mechanism to simulate the selection
of validators and block creation.

STEPS -
1. Set up the environment :
● Install the necessary programming tools (e.g., Python or
JavaScript).
● Create a new project for the blockchain simulation.

2. Implement the blockchain structure :


● Define the core components of a blockchain, such as blocks,
transactions, and the ledger.
● Implement the functionality to add blocks to the blockchain.

3. Implement Proof of Stake (PoS) :


● Create a staking mechanism where participants can stake their
coins.
● Implement the validator selection logic, where a validator is
selected based on their stake and a random number.
● Simulate block validation and block rewards for validators.
4. Simulate transactions and block validation :
● Simulate multiple users submitting transactions.
● Test the selection of validators and the addition of new blocks to
the chain.

5. Run the simulation and observe results :


● Execute the simulation and observe how the PoS consensus
mechanism works, including the selection of validators and the
formation of new blocks.

CODE :
Python Code for PoS Validator Selection :

import random
class Validator:
def __init__(self, name, stake):
self.name = name
self.stake = stake
validators = [Validator("Validator1", 50), Validator("Validator2", 100),
Validator("Validator3", 200)]
def select_validator(validators):
total_stake = sum([validator.stake for validator in validators])
r = random.uniform(0, total_stake)
cumulative_stake = 0
for validator in validators:
cumulative_stake += validator.stake
if r < cumulative_stake:
return validator.name
selected_validator = select_validator(validators)
print(f"Selected Validator: {selected_validator}")
OUTPUT :

CONCLUSION
In this experiment, we successfully implemented a simple Proof of
Stake (PoS) consensus mechanism in a blockchain system. The
experiment demonstrated how validators are selected based on their
stake in the network, providing a more energy-efficient alternative to
Proof of Work (PoW). This shows how PoS can be applied in
decentralized systems to achieve consensus and validate
transactions.
EXPERIMENT - 10
AIM - To develop and deploy a smart contract using Solidity to
manage a supply chain system on the Ethereum blockchain.

THEORY - Smart contracts are self-executing contracts


with the terms of the agreement directly written into code.
They run on blockchain networks, such as Ethereum, and
allow secure and automated transactions without the need
for intermediaries. In supply chain management, smart
contracts can be used to track goods as they move through
various stages, ensuring transparency, reducing fraud, and
automating payments.
This experiment focuses on building a smart contract using
the Solidity programming language to simulate a supply
chain. The contract will allow tracking products from the
manufacturer to the end customer, with information about
product ownership and the current status.

STEPS -
Set up the environment :
● Install the necessary tools like Node.js, Truffle, and Ganache.
● Set up a new Solidity project using the Truffle framework.

Write the smart contract :


● Use the Truffle framework to compile and deploy the smart
contract to the local Ethereum network using Ganache.

Deploy the smart contract :


● Use Truffle's console or a front-end interface to create products
and simulate the supply chain process (e.g., from manufacturer
to distributor to retailer to customer).

Interact with the smart contract :


● Build a Node.js or Go application.
● Connect to the Fabric network using the SDK.
● Create functions to submit transactions (like asset creation or
transfer) and query the ledger.

Test and observe the results :


● Perform several transactions to test the contract’s ability to track
product ownership and status through the supply chain.

CODE :
Solidity Code for Supply Chain Contract :

pragma solidity ^0.8.0;


contract SupplyChain {
struct Product {
uint id;
string name;
address owner;
string status;
}
mapping(uint => Product) public products;
uint public productCount = 0;
function createProduct(string memory _name) public {
productCount++;
products[productCount] = Product(productCount, _name,
msg.sender, "Manufactured");
}
function transferOwnership(uint _productId, address _newOwner)
public {
require(products[_productId].owner == msg.sender, "You are
not the owner");
products[_productId].owner = _newOwner;
}
function updateStatus(uint _productId, string memory _status)
public {
require(products[_productId].owner == msg.sender, "You are
not the owner");
products[_productId].status = _status;
}
function getProduct(uint _productId) public view returns (string
memory, address, string memory) {
Product memory product = products[_productId];
return (product.name, product.owner, product.status);
}
}

OUTPUT :

CONCLUSION
In this experiment, we successfully implemented a smart contract for
supply chain management using Solidity. The contract allowed
tracking of products through the supply chain, updating ownership
and status at each stage. This experiment demonstrates the potential
of blockchain to bring transparency, security, and automation to
supply chain management, enhancing trust and efficiency.

You might also like