Blockchain Lab1
Blockchain Lab1
Affiliated to
GURU GOBIND SINGH INDRAPRASTHA
UNIVERSITY
Sector - 16c Dwarka, Delhi - 110075, India
LABORATORY FILE
For
LANGUAGE - Python.
OUTPUT :
EXPERIMENT - 2
AIM - Use Geth to Implement Private Ethereum Blockchain.
fabric-client-app/
│
├── connection-org1.json // Connection profile for Org1
├── wallet/ // Stores identities (certificates) of users
└── index.js // Main client application code
{
"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"
}
}
}
'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();
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.
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));
}
}
}
OUTPUT :
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/)
Directory Structure
blockchain-app/
│
├── connection.json # Connection profile
├── wallet/ # Wallet to store user credentials
└── index.js # Main application file
{
"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"
}
}
}
Code :
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.
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.
STEPS -
1. Set up a Hyperledger Fabric environment :
● Install Docker, Docker Compose, and download the Fabric
samples.
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.
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).
STEPS -
1. Set up the environment :
● Install the necessary programming tools (e.g., Python or
JavaScript).
● Create a new project for the blockchain simulation.
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.
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.
CODE :
Solidity Code for Supply Chain Contract :
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.