0% found this document useful (0 votes)
11 views20 pages

CBT Lab Manual

The document outlines a laboratory course on Cryptocurrency and Blockchain at St. Mother Theresa Engineering College, detailing various experiments related to setting up and deploying blockchain networks using Hyperledger Fabric and Ethereum. It includes step-by-step instructions for installing necessary software, creating applications to interact with blockchain networks, and deploying asset-transfer applications. Additionally, it emphasizes the development of a web app to track fitness club rewards using blockchain technology.

Uploaded by

KING GAMING
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)
11 views20 pages

CBT Lab Manual

The document outlines a laboratory course on Cryptocurrency and Blockchain at St. Mother Theresa Engineering College, detailing various experiments related to setting up and deploying blockchain networks using Hyperledger Fabric and Ethereum. It includes step-by-step instructions for installing necessary software, creating applications to interact with blockchain networks, and deploying asset-transfer applications. Additionally, it emphasizes the development of a web app to track fitness club rewards using blockchain technology.

Uploaded by

KING GAMING
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/ 20

St.

MOTHER THERESA ENGINEERING COLLEGE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CCS339: CRYPTOCURRENCY AND BLOCKCHAIN


LABORATORY

NAME

REGNO.

YEAR

SEM

STAFF IN-CHARGE HEAD OF THE DEPARTMENT

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

EX.NO DATE NAME OFEXPERIMENT PAGE NO. SIGN

1 Install and understand Docker


container, Node.js, Java and
Hyperledger Fabric, Ethereum and
perform necessary software installation
on local machine/create instance on
cloud to run
2 Create and deploy a blockchain
network using Hyperledger Fabric
SDK for Java Set up and initialize the
channel, install and instantiate chain
code, and perform invoke and query
on your blockchain network.
3 Interact with a blockchain network.
Execute transactions and requests
against a blockchain network by
creating an app to test the network and
its rules.
4 Deploy an asset-transfer app using
blockchain. Learn app development
within a Hyperledger Fabric network.
5 Use blockchain to track fitness club
rewards. Build a web app that uses
Hyperledger Fabric to track and trace
member rewards.

6 Car auction network: A Hello World


example with Hyperledger Fabric Node
SDK and IBM Blockchain Starter Plan.
Use Hyperledger Fabric to invoke
chain code while storing results and
data in the starter plan
Ex.No. 1
Date: Install and understand Docker container, Node.js, Java and Hyperledger Fabric,
Ethereum and perform necessary software installation on local machine/create
instance on cloud to run

AIM:To get started with setting up Docker, Node.js, Java, Hyperledger Fabric, and Ethereum on your local
machine or on a cloud instance, follow these steps:

Prerequisites:
• Local Machine or Cloud Instance: Decide whether you want to set this up on your local machine (e.g.,
laptop or desktop) or on a cloud platform (e.g., AWS, Azure, Google Cloud).
Installation Steps:
1. Install Docker:
Docker is a platform for developing, shipping, and running applications using containerization. Follow these
steps to install Docker:

• Local Machine:
• Download Docker Desktop for your operating system from the Docker website.
• Install Docker by following the installation instructions specific to your operating system.
• Cloud Instance:
• Use the appropriate package manager (e.g., apt for Ubuntu, yum for CentOS) to install Docker on
your cloud instance.
2. Install Node.js and npm:
Node.js is a JavaScript runtime that allows you to run JavaScript on the server-side. npm is the Node.js
package manager.

• Local Machine or Cloud Instance:


• Download and install Node.js from the Node.js website.
• Follow the installation instructions for your operating system.
3. Install Java Development Kit (JDK):
Java is required for running Hyperledger Fabric.

• Local Machine or Cloud Instance:


• Download and install the JDK from the Oracle website or use OpenJDK.
• Set up the JAVA_HOME environment variable.
4. Install Hyperledger Fabric:
Hyperledger Fabric is a permissioned blockchain infrastructure.

• Local Machine or Cloud Instance:


• Follow the official Hyperledger Fabric documentation to install Hyperledger Fabric.
• This involves setting up prerequisites, downloading binaries, and setting up your first network.
5. Install Ethereum:
Ethereum is a decentralized platform that runs smart contracts.
Local Machine or Cloud Instance:

• Install Ethereum tools like geth (Go Ethereum client) or ganache (local Ethereum blockchain server)
based on your requirements.
• Refer to the Ethereum website for detailed instructions.
Additional Considerations:
• Resource Requirements: Ensure that your machine or cloud instance meets the minimum resource
requirements for running these technologies effectively.
• Networking: Configure any necessary networking settings, especially if you're running on a cloud instance.
• Security: Follow security best practices, especially when dealing with blockchain technologies which involve
sensitive data.
Running and Testing:
Once everything is installed:

• Start Docker.
• Start your Hyperledger Fabric network.
• Start your Ethereum node or Ganache server.
• Develop and test your applications using Node.js and Java, integrating with Hyperledger Fabric and Ethereum
as needed.

This setup will provide you with a local development environment where you can experiment and develop
applications using blockchain technologies. For production deployments, additional considerations and
configurations may be required.

Result:
Thus, the installation process has successfully done.
Ex.No. 2 Create and deploy a blockchain network using Hyperledger Fabric SDK for Java Set up and initialize
Date: the channel, install and instantiate chain code, and perform invoke and query on your blockchain
network.

AIM:
To create and deploy a blockchain network using Hyperledger Fabric SDK for Java, you will go through
several steps: setting up the environment, initializing the channel, installing and instantiating chain code, and
performing invoke and query operations on your network. Let's break down these steps:
Prerequisites:
1. Hyperledger Fabric Network: Ensure you have a running Hyperledger Fabric network (either local or on a
cloud platform like AWS or Azure).
2. Java Development Environment: Set up Java and Maven in your development environment.
Step 1: Set Up Your Java Project
Create a new Java project using your preferred IDE (e.g., IntelliJ IDEA, Eclipse) or using Maven from the
command line.

Step 2: Add Hyperledger Fabric SDK Dependency


Include the Hyperledger Fabric SDK for Java dependency in your pom.xml file if you're using Maven:

Step 3: Initialize the Channel and Client


In your Java code, initialize the Hyperledger Fabric client and channel to interact with the blockchain
network:
Step 4: Install and Instantiate Chaincode
Before interacting with the chaincode, ensure it's installed and instantiated on the channel:

Step 5: Perform Invoke and Query Operations


Now you can interact with your chaincode through invoke and query operations:
Step 6: Run Your Java Application
Compile and run your Java application. Ensure that your network connection profile ( networkConfigPath)
and user identity (wallet) are correctly set up

Result:
Thus, to Create and deploy a blockchain network using Hyperledger Fabric SDK for Java Set up and
initialize the channel, install and instantiate chain code, and perform invoke and query on your blockchain
network.
Ex.No.3 Interact with a blockchain network. Execute transactions and requests against a
Date: blockchain network by creating an app to test the network and its rules.

AIM:
To interact with a blockchain network, you can create a simple application that communicates with the
network to execute transactions and query information.
Prerequisites:
1. Hyperledger Fabric Network: Ensure you have a running Hyperledger Fabric network (either local or on a
cloud platform like AWS or Azure).
2. Node.js and npm: Install Node.js and npm on your development environment.
Step 1: Set Up Your Node.js Project
Create a new directory for your project and initialize a Node.js project:

Step 2: Install Fabric SDK and Required Dependencies


Install the Hyperledger Fabric SDK for Node.js and other required dependencies:

Step 3: Write Your Application Code


Create an app.js file in your project directory and write the code to interact with your blockchain network.

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


const fs = require('fs');
const path = require('path');

async function main() {


try {
// Load connection profile
const ccpPath = path.resolve(__dirname, 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);

// Create a new file system based wallet for managing identities


const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);

// Check if user exists in wallet


const identityLabel = 'user1';
const exists = await wallet.get(identityLabel);
if (!exists) {
console.log(`An identity for ${identityLabel} does not exist in the wallet`);
return;
}

// Create a new gateway for connecting to our peer node


const gateway = new Gateway();
await gateway.connect(ccp, {
wallet,
identity: identityLabel,
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('mychaincode');

// Submit a transaction
const result = await contract.submitTransaction('invokeFunction', 'arg1', 'arg2');
console.log(`Transaction has been submitted, result: ${result.toString()}`);

// Evaluate a query
const queryResult = await contract.evaluateTransaction('queryFunction', 'arg');
console.log(`Query result: ${queryResult.toString()}`);

// Disconnect from the gateway


await gateway.disconnect();

} catch (error) {
console.error(`Failed to submit transaction: ${error}`);
process.exit(1);
}
}

main();
Step 4: Configure Connection Profile ( connection.json)
Create a connection.json file in your project directory to define your network connection profile. Replace the
placeholders (<your-network-details>) with actual network details.

Replace placeholders (<your-organization>, <orderer-endpoint>, <peer-endpoint>, <ca-endpoint>, <your-


mspid>, <orderer-url>, <peer-url>, <ca-url>) with your actual network details.

{
"name": "mychannel",
"version": "1.0",
"client": {
"organization": "<your-organization>",
"connection": {
"timeout": {
"peer": {
"endorser": "300"
}
}
}
},
"channels": {
"mychannel": {
"orderers": ["<orderer-endpoint>"],
"peers": {
"<peer-endpoint>": {}
}
}
},
"organizations": {
"<your-organization>": {
"mspid": "<your-mspid>",
"peers": ["<peer-endpoint>"],
"certificateAuthorities": ["<ca-endpoint>"]
}
},
"orderers": {
"<orderer-endpoint>": {
"url": "<orderer-url>"
}
},
"peers": {
"<peer-endpoint>": {
"url": "<peer-url>"
}
},
"certificateAuthorities": {
"<ca-endpoint>": {
"url": "<ca-url>"
}
}
}
Step 5: Run Your Application
Execute your Node.js application to interact with the blockchain network:

This application will connect to your Hyperledger Fabric network using the specified connection profile
(connection.json), submit a transaction to invoke a chaincode function (invokeFunction), and query the
blockchain network using a chaincode function (queryFunction). Make sure to replace mychannel and
mychaincode with your actual channel and chaincode names, and adjust the function names and arguments
based on your chaincode implementation.

Result:
Thus these are executed successfully.
Ex.No.4 Deploy an asset-transfer app using blockchain. Learn app development within a Hyperledger
Date: Fabric network.

AIM:
To deploy an asset-transfer application using Hyperledger Fabric, you'll develop a basic blockchain
application that allows users to transfer assets (e.g., tokens, digital assets) between different parties on the
network. Below, I'll guide you through the steps to set up and implement such an application using Node.js
and Hyperledger Fabric.
Prerequisites:
1. Hyperledger Fabric Network: Ensure you have a running Hyperledger Fabric network (either local or on a
cloud platform like AWS or Azure) with a configured channel and deployed chaincode.
2. Node.js and npm: Install Node.js and npm on your development environment.
Step 1: Set Up Your Node.js Project
Create a new directory for your project and initialize a Node.js project:

Step 2: Install Fabric SDK and Required Dependencies


Install the Hyperledger Fabric SDK for Node.js and other required dependencies:
Step 3: Define the Chaincode
Ensure you have a chaincode (smart contract) deployed on your Hyperledger Fabric network that supports
asset transfer operations (e.g., transferring tokens between users).

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

const fs = require('fs');

const path = require('path');

async function main() {

try {

// Load connection profile

const ccpPath = path.resolve(__dirname, 'connection.json');

const ccpJSON = fs.readFileSync(ccpPath, 'utf8');

const ccp = JSON.parse(ccpJSON);


// Create a new file system based wallet for managing identities

const walletPath = path.join(process.cwd(), 'wallet');

const wallet = await Wallets.newFileSystemWallet(walletPath);

// Check if user exists in wallet

const identityLabel = 'user1';

const exists = await wallet.get(identityLabel);

if (!exists) {

console.log(`An identity for ${identityLabel} does not exist in the wallet`);

return;

// Create a new gateway for connecting to our peer node

const gateway = new Gateway();

await gateway.connect(ccp, {

wallet,

identity: identityLabel,

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('asset-transfer');

// Submit a transaction to transfer an asset

const assetId = 'asset1';

const newOwner = 'newOwner';

const transferResult = await contract.submitTransaction('TransferAsset', assetId, newOwner);

console.log(`Asset transfer transaction has been submitted, result: ${transferResult.toString()}`);


// Evaluate a query to get asset details

const queryResult = await contract.evaluateTransaction('ReadAsset', assetId);

console.log(`Asset details: ${queryResult.toString()}`);

// Disconnect from the gateway

await gateway.disconnect();

} catch (error) {

console.error(`Failed to submit transaction: ${error}`);

process.exit(1);

}
main();
Step 4: Implement the Application
Create an app.js file in your project directory and write the code to interact with your blockchain network.

Step 5: Configure Connection Profile ( connection.json)


Create a connection.json file in your project directory to define your network connection profile (similar to
the one used in the previous example).

Step 6: Run Your Application


Execute your Node.js application to transfer an asset on the blockchain network:

node app.js

Customization:
• Replace mychannel and mychaincode with your actual channel and chaincode names.
• Modify the TransferAsset function call and arguments based on your chaincode implementation.
• Implement additional features like querying asset ownership, listing assets, etc., by extending the application
logic.

RESULT:

This application demonstrates how to interact with a blockchain network to perform asset transfer
transactions. Customize and expand the application based on your specific use case
Ex. No. 5 Use blockchain to track fitness club rewards. Build a web app that uses
Date: Hyperledger Fabric to track and trace member rewards

AIM:
To build a web app that uses Hyperledger Fabric to track fitness club rewards, you will need to create a
blockchain network using Hyperledger Fabric, develop smart contracts (chain code) to manage the reward
system, and build a frontend web application to interact with this network. Below are the steps you can
follow:
Step 1: Set Up Hyperledger Fabric Network
1. Install Hyperledger Fabric: Set up a Hyperledger Fabric network by following the official
documentation. This involves installing the necessary binaries and Docker images.
2. Create Network Components:
• Define network participants (e.g., fitness club, members).
• Define the necessary certificates, MSP (Membership Service Provider) configurations, and channel
configurations.
3. Define Chain code (Smart Contract):
• Define the structure of the fitness club reward system using GoLang or Node.js (for JavaScript-based
chaincode).
• Implement functionalities such as:
• Registering members.
• Issuing and redeeming rewards.
• Querying reward balances.
Step 2: Develop Chain code (Smart Contract)
1. Define Chain code Logic:
• Implement chain code functionalities using Hyperledger Fabric SDK.
• Define functions for:
• Registering new members.
• Issuing rewards based on activities (e.g., gym visits, achievements).
• Redeeming rewards for discounts or perks.
2. Package and Install Chain code:
• Package the chain code.
• Install and instantiate it on the Hyperledger Fabric network.
Step 3: Build Web Application
1. Frontend Development:
• Develop a frontend using a web framework like React.js, Angular, or Vue.js.
• Design UI components for:
• Member registration.
• Displaying reward balances.
• Activities to earn rewards.
• Redeeming rewards.
2. Backend Integration:
• Use Node.js or another backend technology to interact with the Hyperledger Fabric network.
• Implement API endpoints to communicate with the chaincode (smart contract).

3. Implement API Functions:


• Implement functions to:
• Register new members on the blockchain.
• Query member reward balances.
• Issue rewards for completed activities.
• Redeem rewards for discounts.
Step 4: Connect Web App to Blockchain Network
1. Hyperledger Fabric SDK:
• Use Hyperledger Fabric SDK (Node.js SDK) to interact with the chaincode from your web
application.
• Implement functions to invoke chaincode methods (e.g., issueReward, redeemReward).
Step 5: Testing and Deployment
1. Testing:
• Test your web application locally with the Hyperledger Fabric network.
• Simulate different scenarios to ensure the reward system functions correctly.
2. Deployment:
• Deploy your web application and the Hyperledger Fabric network to a production environment.
• Set up secure connections (TLS) between your frontend and backend.
Step 6: Maintain and Monitor
1. Monitoring and Analytics:
• Implement logging and monitoring to track system usage and performance.
• Use tools like Prometheus and Grafana for monitoring.
2. Regular Updates and Bug Fixes:
• Maintain and update your application and blockchain network as needed.
• Address any reported issues or bugs.
Additional Considerations
• Security: Ensure that sensitive information (e.g., member data, rewards) is handled securely using
encryption and proper access controls.
• Scalability: Design your system to handle a growing number of members and transactions
efficiently.
• User Experience: Focus on creating an intuitive and responsive user interface for your fitness club
members.
RESULT:
By following these steps, you can create a robust web application that leverages Hyperledger Fabric to track
and manage fitness club rewards securely and transparently on a blockchain network.
Ex. No. 6 Car auction network: A Hello World example with Hyperledger Fabric Node
Date: SDK and IBM Blockchain Starter Plan. Use Hyperledger Fabric to invoke
chain code while storing results and data in the starter plan

AIM:
To create a "Hello World" example of a car auction network using Hyperledger Fabric Node SDK and the
IBM Blockchain Starter Plan, we'll set up a basic blockchain network, deploy a simple chaincode (smart
contract) for a car auction, and use the Node SDK to interact with this network. We'll also utilize the IBM
Blockchain Starter Plan to manage and store the blockchain network.

Prerequisites
1. IBM Cloud Account: Sign up for an IBM Cloud account if you don't have one already.
2. Access to IBM Blockchain Starter Plan: Ensure you have access to the IBM Blockchain Starter Plan on
IBM Cloud.
Step 1: Set Up IBM Blockchain Starter Plan
1. Create a Blockchain Service Instance:
• Log in to IBM Cloud.
• Navigate to the IBM Blockchain Platform.
• Create a new service instance of the Starter Plan.
2. Create a Blockchain Network:
• Use the IBM Blockchain Platform to create a new blockchain network.
• Configure the network with the desired specifications (e.g., number of peers, orderers).
Step 2: Develop Chaincode (Smart Contract)
1. Define Chaincode Logic:
• Define a simple chaincode for a car auction in GoLang or Node.js.
• Implement basic functionalities like bidding, querying highest bids, etc.
• Use IBM Blockchain SDK for chaincode development.
Step 3: Deploy Chaincode to IBM Blockchain
1. Package and Install Chaincode:
• Package the chaincode into a .tar.gz file.
• Use IBM Blockchain Platform to install and instantiate the chaincode on your created network.
Step 4: Set Up Hyperledger Fabric Node SDK
1. Install Node.js and Hyperledger Fabric SDK:
• Set up Node.js on your local machine if not already installed.
• Install the Hyperledger Fabric Node SDK ( fabric-network package).
Step 5: Interact with the Blockchain Network
1. Initialize Fabric Network Connection:
• Use the IBM Blockchain SDK to initialize a connection to your deployed network.
• Provide necessary credentials and connection details.
2. Invoke Chaincode Functions:
• Use the SDK to invoke chaincode functions (e.g., placeBid, getHighestBid) from your Node.js
application.
• Send transactions to the blockchain network and interact with the deployed chaincode.
const { Gateway, Wallets } = require('fabric-network');
const fs = require('fs');
const path = require('path');

async function main() {


try {
// Connect to the IBM Blockchain Platform network
const ccpPath = path.resolve(__dirname, 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);

const walletPath = path.join(__dirname, 'wallet');


const wallet = await Wallets.newFileSystemWallet(walletPath);

const gateway = new Gateway();


await gateway.connect(ccp, {
wallet,
identity: 'user1', // Use the identity stored in wallet
discovery: { enabled: true, asLocalhost: true }
});

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


const contract = network.getContract('mycc');

// Invoke chaincode function (e.g., placeBid)


const response = await contract.submitTransaction('placeBid', 'car123', '5000');
console.log('Transaction submitted:', response.toString());

// Disconnect from the gateway


await gateway.disconnect();
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
}

main();

Additional Steps
1. Handle Events and Responses: Implement event listeners and response handling for chaincode invocations.
2. Error Handling: Implement error handling for SDK interactions and blockchain transactions.
3. Frontend Integration: Develop a frontend interface (e.g., using React.js) to interact with the blockchain
network through the Node SDK.
Conclusion
This example demonstrates a basic workflow of setting up a car auction network using Hyperledger Fabric
Node SDK and IBM Blockchain Starter Plan. You can expand upon this by adding more complex
functionalities to your chaincode and integrating with other parts of your application. Make sure to refer to
the official IBM Blockchain Platform documentation for detailed guides and tutorials.

You might also like