ANNA UNIVERSITY REGIONAL CAMPUS
MADURAI – 625 019
BONAFIDE CERTIFICATE
Certified that this is a Bonafide Record of the practical work done by
Reg. No of
sixth semester, Bachelor of Engineering (Computer Science and Engineering) in
CCS339 CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES during
the academic year 20 -20 .
STAFF-IN-CHARGE HEAD OF THE DEPARTMENT
Submitted for the Anna University Practical Examination held on
at Anna University Regional Campus, Madurai.
INTERNAL EXAMINER EXTERNAL EXAMINER
1
S. No NAME OF THE EXPERIMENTS DATE PAGE NO SIGNATURE
1. SMART CONTRACT- HELLO
WORLD APPLICATION
2. SMART CONTRACT ELECTRONIC
VOTING SYSTEM
3. CONNECTING METAMASK AND
GANACHE
HYPERLEDGER FABRIC NETWORK
4. DEPLOYMENT USING JAVA SDK
5. CREATE AND DEPLOY ERC20 TOKEN
USE BLOCKCHAIN TO TRACK FITNESS
6. CLUB REWARDS. BUILD A WEBAPP
THAT USES HYPERLEDGER FABRIC TO
TRACK AND TRACE MEMBER
REWARDS
DEPLOY AN ASSET TRANSFER APP
7. USING BLOCKCHAIN – LEARN APP
DEVELOPMENT WITH HYPERLEDGER
FABRIC NETWORK
8.
CAR AUCTION NETWORK USING
NODE JS (BLOCK CHAIN
SIMULATION)
2
EX.NO:01
SMART CONTRACT- HELLO WORLD APPLICATION
DATE:
Aim:
To develop and deploy a simple smart contract on the Ethereum blockchain that returns
a greeting message using Solidity.
Procedure:
1. Set up the Environment
i. Open Remix IDE in your browser.
ii. Select the Solidity environment.
2. Create a new file
iii. Click on the “+” button and create a new file “HelloWorld.sol”.
3. Write the Smart contract code
4. Compile the code
iv. Go to the Solidity Compiler tab.
v. Select the correct compiler version(0.8.17 or higher).
vi. Click compile HelloWorld.sol.
5. Deploy the contract
vii. Go to the Deploy and Run Transactions tab
viii. Select the Helloworld Contract.
ix. Click deploy.
6. Interact with the contract
x. Once deployed, you will see the contract listed under Deployed Contracts.
xi. Click on the Greet button.
xii. You will see the output below the Greet button.
Input:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract hw {
string public greet = "Hello world";
3
Output:
Result:
The smart contract for the hello world was successfully completed and verified.
4
EX.NO:02
SMART CONTRACT ELECTRONIC VOTING SYSTEM
DATE:
Aim:
To develop a smart contract using solidity that facilitates an electronic voting system where users
can cast, remove, and view their votes securely on the Ethereum blockchain.
Procedure :
1. Set up the development environment
i. Open the Remix IDE in your browser.
ii. Select the Solidity environment for coding and deploying the contract.
2. Create a new Solidity file
iii. Click the ‘+’ icon and name the file Voting.sol.
3. Write the smart contract code
iv. Code in the workspace for the smart contract. Compile the contract.
v. Navigate to the Solidity Compiler tab.
vi. Select Compiler version 0.8.0 or higher.
vii. Click Compile voting.sol.
4. Deploy the contract
viii. Go to the Deploy and Run Transactions tab.
ix. Choose the Voting contract.
x. Click Deploy.
5. Interact with the contract functions
xi. Use StartVoting() function to begin the voting system.
xii. Use AddVote(Address) to cast your vote to a candidate's address.
xiii. Use GetVoteAddress() to view the vote of a voter.
xiv. Use RemoveVote() to delete your vote.
xv. Use StopVoting() to end the voting session.
5
Input:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Voting {
bool public
isVoting; struct
Vote {
address receiver;
uint256 timestamp;
}
mapping(address => Vote) public votes;
event AddVote(address indexed voter, address receiver, uint256 timestamp);
event RemoveVote(address voter);
event StartVoting(address startedBy);
event StopVoting(address stoppedBy);
constructor() {
isVoting = false;
function startVoting() external returns (bool) {
isVoting = true;
emit StartVoting(msg.sender);
return true;
}
function stopVoting() external returns (bool) {
isVoting = false;
emit StopVoting(msg.sender);
return true;
6
}
function addVote(address _receiver) external returns (bool) {
votes[msg.sender].receiver = _receiver;
votes[msg.sender].timestamp = block.timestamp;
emit AddVote(msg.sender, votes[msg.sender].receiver, votes[msg.sender].timestamp);
return true;
function removeVote() external returns (bool) {
delete votes[msg.sender];
emit RemoveVote(msg.sender);
return true;
function getVote(address voterAddress) external view returns (address) {
return votes[voterAddress].receiver;
OUTPUT:
Result:
The smart contract for the electronic voting system where users were able to start and stop voting,
cast, remove, and view votes was successfully completed and verifie
7
EX.NO:03
CONNECTING METAMASK AND GANACHE
DATE:
Aim:
To demonstrate the process of creating a MetaMask wallet, connecting it to a local Ethereum
blockchain using Ganache, and transferring Ether (ETH) between accounts..
Procedure:
1. Install Ganache:
• Download and install Ganache from https://trufflesuite.com/ganache/.
• Launch Ganache and create a new workspace or use the default Quickstart setup.
• Note the RPC server URL (usually http://127.0.0.1:7545) and the list of generated accounts
with their private keys and balances.
2. Install MetaMask:
• Install the MetaMask browser extension from https://metamask.io/.
• Create a new wallet and securely store the seed phrase.
3. Connect MetaMask to Ganache:
• In MetaMask, go to settings > networks > add network.
• Input the following:
o Network Name: Ganache Localhost
o RPC URL: http://127.0.0.1:7545
o Chain ID: 5777 (as shown in Ganache)
o Currency Symbol: ETH
8
• Save and switch to the newly added network.
4. Import Ganache Accounts to MetaMask:
• In Ganache, copy the private key of an account.
• In MetaMask, go to Import Account and paste the private key.
• Repeat for multiple accounts if needed.
5. Transfer ETH Using MetaMask:
• Select the sender account (e.g., Account 4).
• Click "Send," enter the recipient address (e.g., 0x3ff...0243b), and input the amount (e.g.,
20 ETH).
• Review the transaction, confirm the network fee, and click “Confirm” to complete
the transaction.
6. Verify the Transfer in Ganache:
• Switch to the Ganache GUI to verify that the balance has been deducted from the sender
and added to the recipient.
• Check the TX count and block number updates.
Output:
9
Result:
Successfully created MetaMask wallet, connected it to the local Ethereum network using
Ganache, and transferred 20 ETH from Account 4 to another account (0x3ff...0243b). The
transaction was processed with a minimal network fee, and the updated balances were reflected
in Ganache.
10
EX.NO:04
HYPERLEDGER FABRIC NETWORK DEPLOYMENT USING
DATE: JAVA SDK
Aim:
To create and deploy a blockchain network using Hyperledger Fabric SDK for Java,
initialize and channel, install and instantiate chaincode, and perform invoke/query transactions
on the blockchain.
Procedure:
Step 1: Install Prerequisites
• Docker and Docker Compose
• Node.js and npm
• Go Programming Language
• Java 8 or above
• Hyperledger Fabric Binaries and Docker images
11
Step 2: Setup a fabric network:
• Navigate to fabric-samples/test-network
• Run the network:
CODE
./network.sh up createChannel -c mychannel –ca
Step 3: Install and Approve Chaincode
Package chaincode:
CODE
peer lifecycle chaincode package basic.tar.gz --path ./chaincode/java/ --lang java --label basic_1
Install on peers and approve for orgs.
12
Step 4: Instantiate the Chaincode
Commit the chaincode definition to the channel:
CODE
peer lifecycle chaincode commit ...
13
Step 5: Configure Java SDK
• Use Fabric-Gateway-Java SDK.
• Create a Spring/Java app.
• Load connection profile (YAML/JSON).
• Example Java code snippet:
JAVA CODE
Gateway.Builder builder = Gateway.createBuilder();
builder.identity(wallet, "appUser").networkConfig(Paths.get("connection-org1.yaml"));
Step 6: Invoke and Query the
Blockchain Invoke transaction:
JAVA CODE
contract.submitTransaction("CreateAsset", "asset1", "blue", "10", "Tom");
14
Query transaction:
JAVA CODE
byte[] result = contract.evaluateTransaction("ReadAsset", "asset1");
Step 7: View Ledger State and Logs
Monitor logs via Docker
CODE
docker logs peer0.org1.example.com
15
Step 7: View Ledger State and Logs
Monitor logs via Docker
CODE
docker logs peer0.org1.example.com
Step 8: Shut Down the Network CODE
./network.sh down
Result
The blockchain network was successfully deployed, with the chaincode properly installed and
committed to the channel. Using the Hyperledger Fabric Java SDK, transactions were submitted
and evaluated effectively, demonstrating seamless interaction between the application and the
blockchain network
16
EX.NO:05
CREATE AND DEPLOY ERC20 TOKEN
DATE:
Aim:
To create and deploy an ERC20-compliant token named Aurora with symbol AR on the
Ethereum blockchain using the Remix IDE and OpenZeppelin library.
Procedure:
1. Open Remix IDE: Go to https://remix.ethereum.org
2. Create a New File:
• Click on the "contracts" folder.
• Create a new file named trillion.sol.
• Paste your code into the file.
3. Install OpenZeppelin (via Remix Plugin or GitHub Import):
4. Use the import
• import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
5. Ensure “OpenZeppelin Contracts” plugin is enabled (or import from GitHub if needed
using raw links).
6. Compile the Contract:
• Click the Solidity Compiler tab.
• Choose version 0.8.20.
• Click Compile trillion.sol.
7. Deploy the Contract:
• Go to the Deploy & Run Transactions tab.
• Select Injected Web3 (if deploying to testnet) or JavaScript VM (for local testing).
• Click Deploy.
• Confirm the MetaMask transaction (if using testn
17
Input:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract trillion is ERC20{
constructor() ERC20("Aurora", "ar"){
_mint(msg.sender, 100);
}
Output:
Result:
An ERC20 token named Aurora with symbol AR was successfully created and deployed using the
OpenZeppelin ERC20 standard.
18
EXNO USE BLOCKCHAIN TO TRACK FITNESS CLUB REWARDS.
: BUILD A WEBAPP THAT USES HYPERLEDGER FABRIC
DATE: TO TRACK AND TRACE MEMBER REWARDS
Aim:
To build a web app that tracks fitness club rewards using Hyperledger Fabric.
Procedure:
1. Set up Hyperledger Fabric network.
2. Define smart contracts for handling rewards.
3. Develop a web application frontend.
4. Connect the frontend to the Hyperledger Fabric network.
1. Set up Hyperledger Fabric network:
You need to set up a Hyperledger Fabric network with a few nodes. Refer to the official
documentation for detailed instructions.
2. Define smart contracts:
Define smart contracts to handle fitness club rewards. Here's a simple example in
Go: package main
import (
"encoding/json"
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
type RewardsContract struct {
contractapi.Contract
}
type Reward struct {
MemberID string `json:"memberID"
Points int json:"points"`
19
}
func (rc *RewardsContract) IssueReward(ctx contractapi.TransactionContextInterface, memberID
string, points int) error {
reward :=
Reward{
MemberID:
memberID,
Points: points,
}
rewardJSON, err :=
json.Marshal(reward) if err != nil {
return err
}
return ctx.GetStub().PutState(memberID, rewardJSON)
}
}
func (rc *RewardsContract) GetReward(ctx contractapi. TransactionContextInterface, memberID
string) (*Reward, error) {
rewardJSON, err :=
ctx.GetStub().GetState(memberID) if err != nil {
return nil, err
if rewardJSON == nil {
return nil, fmt.Errorf("reward for member %s not found", memberID)
}
var reward Reward
err = json.Unmarshal(rewardJSON,
&reward) if err != nil {
return nil, err
}
return & reward, nil
}
1. Develop a web application frontend:
You can use any frontend framework like React, Vue.js, etc. Here's a React component to
interact with the smart contract:
RewardsComponent.js
import React. { useState } from 'react':
import { useContract } from './useContract'; // Assume this hook connects to
20
the contract const RewardsComponent = () => {
const [memberID, setMemberID] = useState(");
const [points, setPoints] = useState(");
const { issueReward, getReward } = useContract();
const handleIssueReward = async () => {
await issueReward(memberID, points);
};
const handleGetReward = async () => {
const reward = await
getReward(memberID);
console.log(reward);
};
return (
<div>
<input type="text" placeholder="Member ID" value={memberID} onChange={(e) =>
setMemberID(e.target.value)} />
<input type="number" placeholder="Points" value={points) onChange={(e) =>
setPoints(e.target.value)} />
<button onClick={handleIssueReward} >Issue Reward</button>
<button onClick={handleGetReward}>Get Reward</button>
</div>
);
};
export default RewardsComponent;
1. Connect the frontend to the Hyperledger Fabric network:
Use a library like fabric-network to interact with the Hyperledger Fabric network.
Implement functions like issueReward and getReward to interact with the smart contract.
Now, integrate this frontend component into your web application. Here's a screenshot of what
the UI might look like:
In this example, users can input a member ID and points to issue rewards, and they can retrieve
rewards by providing the member ID.
Remember, this is a basic example. In a real-world application, you would need to consider
security, scalability, and other factors. Additionally, you'll need to handle user authentication,
21
authorization, and other functionalities as per your requirements.
Output:
Result:
Thus the blockchain to track fitness club rewards and build a web app that uses Hyperledger
Fabric to track and trace member rewards are executed successfully.
22
EX.NO:07 DEPLOY AN ASSET TRANSFER APP USING
BLOCKCHAIN – LEARN APP DEVELOPMENT WITH
DATE: HYPERLEDGER FABRIC NETWORK
Aim:
To deploy and test an Asset Transfer application on a Hyperledger Fabric blockchain network using
Docker and Ubuntu. The goal is to understand the setup and development of decentralized
applications (DApps) by transferring ownership of an asset securely and immutably through the
blockchain.
Algorithm:
Step 1: Navigate to the test network directory
Step 2: Shut down any existing network
Step 3: Clean up Docker containers and volumes
Step 4: Start the network with Certificate Authorities
Step 5: Create a new channel named mychannel
Step 6: Set environment variables for Org1 admin
Step 7: Deploy the chaincode for asset transfer
Step 8: Navigate back to the fabric-samples directory
Step 9: Set the Fabric configuration path
Step 10: Navigate back to the test-network directory
Step 11: Set user context for Org1 user
Step 12: Query the blockchain to read asset details
Step 13:The assets are transfer successfully.
Procedure:
Step 1: Install Docker on Windows
1. Visit https://www.docker.com/products/docker-desktop
2. Download Docker Desktop for Windows and install it.
3. After installation, launch Docker Desktop.
4. Enable WSL 2 backend when prompted.
5. Ensure that Ubuntu (from Microsoft Store) is installed and linked with Docker.
23
Step 2: Open Ubuntu via Docker / WSL2
1. From the Windows Start menu, search and open Ubuntu.
2. Confirm Docker is working:
docker –version
Step 3: Delete Existing Docker Networks and Volumes (Clean Slate)
cd fabric-samples/test-network
./network.sh down
docker rm -f $(docker ps -aq)
docker volume prune –f
24
Step 4: Start Docker Containers and Certificate Authorities
. /network.sh up –ca
This creates the Fabric network with CAs, peers, orderers, and sets up Docker containers.
Step 5: Create a Channel for Communication
./network.sh createChannel -c mychannel
Step 6: Set Environment for Org1 Admin
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"
export
CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.co
25
m/users/[email protected]/msp
export CORE_PEER_ADDRESS=localhost:7051
Step 7: Deploy Chaincode for Asset Transfer App
./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go/ -ccl go -cci
InitLedger
Step 8: Set Fabric Configuration Path
cd ~/fabric-samples
export FABRIC_CFG_PATH=${PWD}/config
cd test-network
Step 9: Set Environment Variables for Org1 User to Query Chaincode
export CORE_PEER_LOCALMSPID="Org1MSP"
export
CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.exampl
e.com/peers/peer0.org1.example.com/tls/ca.crt
export
CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.co
m/users/
[email protected]/msp
export CORE_PEER_ADDRESS=localhost:7051
export
ORDERER_CA=${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.ex
ample.com/msp/tlscacerts/tlsca.example.com-cert.pem
26
Step 10: Query the Blockchain to Confirm Asset Transfer
peer chaincode query \
-C mychannel \
-n basic \
-c '{"Args":["ReadAsset","asset1"]}'
After running the query, you should get a JSON output similar to:
{
"ID": "asset1",
"Color": "blue",
"Size": 5,
"Owner": "newOwner",
"AppraisedValue": 300
}
Result:
Thus, to deploy an asset transfer app using blockchain – learn app development with hyperledger
fabric network is created and executed successfully.
27
EX.NO:08 Car Auction Network using node js (block chain simulation )
DATE:
AIM:
To develop and simulate a Car Auction Network in Node.js using Visual Studio Code, by connecting
to an IBM Blockchain Starter Plan network and securely managing car and auction data through
smart contracts.
PROCEDURE:
1) Set up IBM Blockchain Starter Plan with 1 Org, 1 Peer, and 1 CA.
Develop Smart Contract with RegisterCar, CreateAuction, PlaceBid, CloseAuction
functions.
2) Deploy Smart Contract on IBM Blockchain network.
3) Create Node.js Application in VS Code.
4) Install Fabric SDK and connect using a wallet and connection profile.
5) Invoke Smart Contract Functions (Register car, Create auction, Place bid,
Close auction, Query data).
6) Test Simulation by adding cars, placing bids, closing auctions, and verifying
ledger entries.
CODE:
Program:
// app.js
const crypto = require("crypto"); // ⬛• w Import
›
class CarAuction {
constructor() {
this.cars = {};
this.auctions = {};
this.chain = [];
}
// ›
w Hash generator
⬛•
generateHash(data) {
return crypto
.createHash("sha256")
.update(JSON.stringify(data))
.digest("hex");
}
registerCar(carID, owner, model) {
this.cars[carID] = { owner, model };
console.log(`⬛ Car ${carID} registered successfully.`);
this.chain.push({
action: "registerCar",
data: { carID, owner, model },
timestamp: Date.now(),
hash: this.generateHash({ action: "registerCar", carID, owner, model }), // ⬛•
›
w Hash
});
}
createAuction(carID, startingBid) {
28
if (!this.cars[carID]) {
console.log(`+ Car ${carID} not found.`);
return;
}
this.auctions[carID] = {
startingBid,
highestBid: 0,
highestBidder: null,
isClosed: false,
};
console.log(
`⬛Auction created for car ${carID} with starting bid ₹${startingBid}.`
);
this.chain.push({
action: "createAuction",
data: { carID, startingBid },
timestamp: Date.now(),
hash: this.generateHash({ action: "createAuction", carID, startingBid }), // • ⬛w Hash
›
});
}
placeBid(carID, bidder, bidAmount) {
let auction = this.auctions[carID];
if (!auction || auction.isClosed) {
console.log(`+ Auction for car ${carID} is not available.`);
return;
}
if (bidAmount > auction.highestBid && bidAmount >= auction.startingBid) {
auction.highestBid = bidAmount;
auction.highestBidder = bidder;
console .l og(`⬛ New highest bid ₹${bidAmount} by ${bidder}.`); this.chain.push({
action: "placeBid",
data: { carID, bidder, bidAmount },
timestamp: Date.now(),
hash: this.generateHash({
action: "placeBid",
carID,
bidder,
bidAmount,
}), // ›
⬛ Hash
•
w
});
} else {
console.log(
`+ Bid too low. Current highest bid is ₹${auction.highestBid}.`
);
}
}
closeAuction(carID) {
let auction = this.auctions[carID];
if (!auction || auction.isClosed) {
console.log(
`+ Auction for car ${carID} is not available or already closed.`
);
29
return
}
auction.isClosed = true;
if (auction.highestBidder) {
console.log(
`±´
’ Auction closed. Winner: ${auction.highestBidder} with ₹${auction.highestBid}.`
ç_'
);
this.chain.push({
action: "closeAuction",
data: {
carID,
winner: auction.highestBidder,
finalBid: auction.highestBid,
},
timestamp: Date.now(),
hash: this.generateHash({
action: "closeAuction",
carID,
winner: auction.highestBidder,
finalBid: auction.highestBid,
}), // new Hash
});
} else {
console.log(`+ Auction closed. No valid bids.`);
this.chain.push({
action: "closeAuction",
data: { carID, winner: null, finalBid: null },
timestamp: Date.now(),
hash: this.generateHash({
action: "closeAuction",
carID,
winner: null,
finalBid: null,
}), // new Hash
});
}
}
}
const carAuction = new CarAuction();
carAuction.registerCar("CAR001", "Tamil Vani", "Tata Nexon");
carAuction.createAuction("CAR001", 5000);
carAuction.placeBid("CAR001", "Karthik", 6000);
carAuction.placeBid("CAR001", "Priya", 6500);
carAuction.closeAuction("CAR001");
c o n s o l e . l o g ( " \ n 궤̧
궧̂ Blockchain Ledger (Chain):");
console.log(JSON.stringify(carAuction.chain, null, 2));
30
OUTPUT:
RESULT:
The Car Auction Blockchain Simulation was successfully created.
31