0% found this document useful (0 votes)
25 views

CBT Lab Manual - Ex No 5

Uploaded by

Annes zovitta
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
0% found this document useful (0 votes)
25 views

CBT Lab Manual - Ex No 5

Uploaded by

Annes zovitta
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/ 8

Ex:No: 5 Asset-transfer app using blockchain within

Hyperledger Fabric network.


Aim:
To Deploy an asset-transfer app using blockchain. Learn app development within a Hyperledger
Fabric network.

Procedure:

Pre requesites : install pug : sudo apt install pug

Install Fabric and Fabric Samples

mkdir fabric

cd fabric

Download fabric samples

curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/main/scripts/bootstrap.sh | bash -s --


2.4.0

Move to Fabcar folder

cd fabcar

Up the network

./startFabric.sh javascript

Move to javascript folder

cd javascript

Copy and paste uiserver.js file there

Install node modules

npm install

Enroll Admin

node enrolladmin.js

Register user

node registeruser.js

run the server(invoking and querying

node uiserver.js
Program:

uiserver.js:

var express = require('express');


var bodyParser = require('body-parser');

var app = express();


var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(bodyParser.json());
// Setting for Hyperledger Fabric
const { Gateway,Wallets } = require('fabric-network');
const path = require('path');
const fs = require('fs');
//const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations',
'org1.example.com', 'connection-org1.json');
// const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
app.set("view engine","pug");

app.get('/api/', function (req, res) {

res.render('index');

});

app.get('/api/createcar', function (req, res) {

res.render('createcar');

});

app.get('/api/queryallcars', async function (req, res) {


try {
const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations',
'org1.example.com', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);

// Check to see if we've already enrolled the user.


const identity = await wallet.get('appUser1');
if (!identity) {
console.log('An identity for the user "appUser1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost:
true } });

// Get the network (channel) our contract is deployed to.


const network = await gateway.getNetwork('mychannel');

// Get the contract from the network.


const contract = network.getContract('fabcar');
// Evaluate the specified transaction.
// queryCar transaction - requires 1 argument, ex: ('queryCar', 'CAR4')
// queryAllCars transaction - requires no arguments, ex: ('queryAllCars')
const result = await contract.evaluateTransaction('queryAllCars');
console.log(JSON.parse(result));
console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
res.render("allcars",{ list:JSON.parse(result)});
} catch (error) {
console.error(`Failed to evaluate transaction: ${error}`);
res.status(500).json({error: error});
process.exit(1);
}
});

app.get('/api/query/:car_index', async function (req, res) {


try {
const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations',
'org1.example.com', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);

// Check to see if we've already enrolled the user.


const identity = await wallet.get('appUser1');
if (!identity) {
console.log('An identity for the user "appUser1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost:
true } });

// Get the network (channel) our contract is deployed to.


const network = await gateway.getNetwork('mychannel');

// Get the contract from the network.


const contract = network.getContract('fabcar');
// Evaluate the specified transaction.
// queryCar transaction - requires 1 argument, ex: ('queryCar', 'CAR4')
// queryAllCars transaction - requires no arguments, ex: ('queryAllCars')
const result = await contract.evaluateTransaction('queryCar', req.params.car_index);
console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
res.status(200).json({response: result.toString()});
} catch (error) {
console.error(`Failed to evaluate transaction: ${error}`);
res.status(500).json({error: error});
process.exit(1);
}
});

app.post('/api/addcar/', urlencodedParser, async function (req, res) {


try {

const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations',


'org1.example.com', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);

// Check to see if we've already enrolled the user.


const identity = await wallet.get('appUser1');
if (!identity) {
console.log('An identity for the user "appUser1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost:
true } });

// Get the network (channel) our contract is deployed to.


const network = await gateway.getNetwork('mychannel');

// Get the contract from the network.


const contract = network.getContract('fabcar');
// Submit the specified transaction.
// createCar transaction - requires 5 argument, ex: ('createCar', 'CAR12', 'Honda', 'Accord', 'Black',
'Tom')
// changeCarOwner transaction - requires 2 args , ex: ('changeCarOwner', 'CAR10', 'Dave')

await contract.submitTransaction('createCar', req.body.carid, req.body.make, req.body.model,


req.body.colour, req.body.owner);

console.log('Transaction has been submitted');


res.send('Transaction has been submitted CAR ADDED');
// Disconnect from the gateway.
await gateway.disconnect();
} catch (error) {
console.error(`Failed to submit transaction: ${error}`);
process.exit(1);
}
})

app.put('/api/changeowner/:car_index', async function (req, res) {


try {
const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations',
'org1.example.com', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);

// Check to see if we've already enrolled the user.


const identity = await wallet.get('appUser1');
if (!identity) {
console.log('An identity for the user "appUser1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost:
true } });

// Get the network (channel) our contract is deployed to.


const network = await gateway.getNetwork('mychannel');

// Get the contract from the network.


const contract = network.getContract('fabcar');
// Submit the specified transaction.
// createCar transaction - requires 5 argument, ex: ('createCar', 'CAR12', 'Honda', 'Accord', 'Black',
'Tom')
// changeCarOwner transaction - requires 2 args , ex: ('changeCarOwner', 'CAR10', 'Dave')
await contract.submitTransaction('changeCarOwner', req.params.car_index, req.body.owner);
console.log('Transaction has been submitted');
res.send('Transaction has been submitted');
// Disconnect from the gateway.
await gateway.disconnect();
} catch (error) {
console.error(`Failed to submit transaction: ${error}`);
process.exit(1);
}
})

app.listen(8080);

Frontend:
Index.pug

doctype html
html
head
title FABCAR
body
h1 First Page
a(href='/api/queryallcars') View All Cars
br
a(href='/api/createcar') Insert a new car
Output:
Frontend:
Result:
Thus the deployment of an asset-transfer app using blockchain within a Hyperledger Fabric network
are executed successfully.

You might also like