0% found this document useful (0 votes)
5 views55 pages

Blockchain

The document is a laboratory manual for a Blockchain course, detailing practical work for creating both private and public blockchains using JavaScript. It includes code implementations for blockchain functionality, Redis for messaging, and API creation for data storage and retrieval. The manual also covers the necessary dependencies and provides instructions for running the server and interacting with the blockchain through API requests.

Uploaded by

parekhbhavika694
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)
5 views55 pages

Blockchain

The document is a laboratory manual for a Blockchain course, detailing practical work for creating both private and public blockchains using JavaScript. It includes code implementations for blockchain functionality, Redis for messaging, and API creation for data storage and retrieval. The manual also covers the necessary dependencies and provides instructions for running the server and interacting with the blockchain through API requests.

Uploaded by

parekhbhavika694
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/ 55

Laboratory Manual

Blockchain
(3171618)
B.E. Semester 7
(Information Technology)

Directorate of Technical Education, Gandhinagar,


Gujarat

Government Engineering College, Gandhinagar


CERTIFICATE

This is to certify that Ms. Parekh Janvi Himanshubhai


Enrollment No. 210130116029 of B.E. Semester in Information
Technology Department of Government Engineering College,
Gandhinagar, Institute has satisfactorily completed the
Practical / Tutorial work for the subject Blockchain (3171618)
for the academic year 2022-23.

Date:

Sign of Faculty Member Head of the Department


Experiment No: 1
Aim: Create Private Blockchain.

Introduction:
A private blockchain, often referred to as a permissioned
blockchain, is a type of blockchain network that is accessible only to authorized
participants or entities.
 Unlike public blockchains, where anyone can join and participate, private
blockchains restrict access to a defined group of users who are granted
permission to interact with the network.
 These users are typically known and trusted entities, such as organizations
or consortium members.
 Private blockchains are designed to provide enhanced privacy, control,
and scalability while maintaining the fundamental principles of blockchain
technology, including distributed ledger, immutability, and transparency.
 These networks are commonly used for various business and enterprise
applications, such as supply chain management, financial transactions,
and internal data sharing, where participants require a high degree of
control over access and governance.

Simple Blockchain Implementation


This code defines a basic blockchain and mining mechanism using
JavaScript. It includes classes for creating blocks, managing the blockchain, and
mining new blocks.
How to use:
 Create a blockchain instance: const blockchain = new Blockchain();
 Add blocks to the blockchain: blockchain.addBlock({ data: "Block data" });
 Check the validity of the blockchain: blockchain.isChainValid();
 Replace the chain with a longer or valid chain:
blockchain.replaceChain(newChain);
 The mineBlock function simulates the process of mining by repeatedly
calculating the hash of a block with varying nonces until the difficulty level
is met. This process is computationally intensive, similar to proof-of-work
in real blockchains.

Janvi Parekh (210130116029) 3


blockchain.js
const SHA256 = require("crypto-js/sha256");

class Block {
constructor(index, timestamp, data, previousHash = "") {
this.index = index; this.timestamp = timestamp;
this.data = data; this.previousHash = previousHash;
this.hash = this.calculateHash();
}

//For calculating the hash of block


calculateHash() {
return SHA256(
this.index + this.timestamp + JSON.stringify(this.data) +
this.previousHash).toString();
}
}

// Class of Blockchain
class Blockchain {
createGenesisBlock() {
return new Block(0, Date.now(), "Genesis Block", "0");
}

constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 100; // Adjust the difficulty for mining
this.pendingTransactions = [];
}

getLatestBlock() {
return this.chain[this.chain.length - 1];
}

// For adding new block


addBlock({ data }) {
const newBlock = this.mineBlock({
prevBlock: this.chain[this.chain.length - 1],
data,
});
this.chain.push(newBlock);
}

// Proof of work using simple function.


mineBlock({ prevBlock, data }) {
let hash = "divyesh",

Janvi Parekh (210130116029) 4


timestamp;
const prevHash = prevBlock.hash;
const index = prevBlock.index + 1;
let { difficulty } = prevBlock;
const nonce = Math.floor(Math.random() * 100) + 1;
console.log(nonce);
let temp = -1;
do {
temp++; timestamp = Date.now();
hash = SHA256(
hash, timestamp, nonce, difficulty, data, prevHash ).toString();
} while (temp != nonce);
console.log("mining");
return {
index, timestamp, prevHash, nonce, data, hash,
};
}

// For checking chain is valid or not.


isChainValid() {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}

// To replace the chain if any big chain is build


replaceChain(chain) {
if (chain.length <= this.chain.length) {
console.error("The incoming chain is not longer");
return;
}
if (!Blockchain.isValidChain(chain)) {
console.error("The incoming chain is not valid");
return;
}
this.chain = chain;
}
}
module.exports = Blockchain;

Janvi Parekh (210130116029) 5


Redis:
Redis, which stands for REmote DIctionary Server, is an open-source,
in-memory data structure store and caching system. It is often referred to as a
"data structure server" because it allows you to store various data structures
such as strings, hashes, lists, sets, and more. Redis is known for its exceptional
speed, high performance, and versatility, and it is widely used in various
applications and use cases.

Publishsubsciber.js
The "PubSub" class is a messaging system that enables communication between
different parts of a blockchain application. It uses the Redis library for messaging.
The class provides the ability to publish and subscribe to specific message
channels.

const redis = require("redis");

const CHANNEL = {
TEST: "TEST", BLOCKCHAIN: "BLOCKCHAIN",
};

class PubSub {
constructor(blockChain) {
this.blockChain = blockChain;
this.publisher = redis.createClient();
this.subscriber = redis.createClient();
this.subscriber.subscribe(CHANNEL.TEST);
this.subscriber.subscribe(CHANNEL.BLOCKCHAIN);

Janvi Parekh (210130116029) 6


this.subscriber.on("message", (channel, message) =>
this.handleMessage(channel, message)
);
}

handleMessage(channel, message) {
console.log(`Message "${message}" received on channel "${channel}"`);
const parseMessage = JSON.parse(message);
}

publish({ channel, message }) {


this.publisher.publish(channel, message);
}

broadcastChain() {
this.publish({
channel: CHANNEL.BLOCKCHAIN,
message: JSON.stringify(this.blockChain.chain),
});
}
}

module.exports = PubSub;

accessKey.js
This file have all the “accessKey” so when any one what’s to access the
blockchain he/she will need his/her own accesskey. It works same as the
password for authorizing the user for accessing the blockchain.
const keyL st = [
{
name: "Aashutosh",
key: "R220",
},
{
name: "Uttam",
key: "123455",
},
{
name: "D vyesh",
key: "098765",
},
];
module.exports = keyL st;

Janvi Parekh (210130116029) 7


index.js
For creating the APIs for storing and retrieving blockchain data.
This file uses the blockchain instance for storing the data.
Uses a publishSubciber class for publishing the blockchain data to all the nodes
with the help of Redis server.

const express = require("express");


const Blockchain = require("./blockchain");
const keyList = require("./accessKey");
const DEFAULT_PORT = 8080;
const app = express();
const PubSub = require("./publishsubscriber.js");
const request = require("request");
const ROOT_NODE_ADDRESS = `http://localhost:${DEFAULT_PORT}`;
const myChain = new Blockchain();
const pubSub = new PubSub(myChain);

setTimeout(() => pubSub.broadcastChain(), 1000);

app.use(express.json());

app.get("/blockchainData", (req, res) => {


res.json(myChain.chain);
});

app.post("/addDataToChain", (req, res) => {


const { accessKey, data } = req.body;
let isAuth = keyList.find((item) => item.key === accessKey);
if (isAuth != undefined) {
myChain.addBlock({ data });
pubSub.broadcastChain();
console.log("Done added");
res.json({ myChain });
} else {
res.json({ mess: "not found" });
}
});

const synChains = () => {


request({ url: `${ROOT_NODE_ADDRESS}/blockchainData` }, (err, res, body) => {
if (!err && res.statusCode === 200) {

Janvi Parekh (210130116029) 8


const rootChain = JSON.parse(body);
console.log(rootChain);
console.log("Rootchain:", rootChain);
}
});
};

let PEER_PORT;
if (process.env.GENERATE_PEER_PORT === "true") {
PEER_PORT = DEFAULT_PORT + Math.ceil(Math.random() * 1000);
}
const PORT = PEER_PORT || DEFAULT_PORT;

app.listen(PORT, () => {
console.log("Server is listening at :", PORT);
synChains();
});

These are the dependencies that you will need to execute the
program:
package.json
{
"name": "bc-2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev-peer": "cross-env GENERATE_PEER_PORT='true' nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"cross-env": "^5.2.0",
"crypto": "^1.0.1",
"crypto-js": "^4.1.1",
"express": "^4.18.2",
"hex-to-binary": "^1.0.1",
"redis": "^2.8.0",
"request": "^2.88.2"
}
}

Janvi Parekh (210130116029) 9


OUTPUT:
Step-1: Start the server.
Node index.js

Step-2: Open postman and send a request to API which is mention is index.js.
In a request there are two fields one is accesskey for accessing and authorizing
the user and second is data which you want to add.
When you send a request first it will check for the correct acesskey then if it is
correct then it will do mining using normal function and add a data to blockchain
else it will send you a message like access denied.
For example:
With wrong accesskye:

Janvi Parekh (210130116029) 10


With correct accesskey:

After successful mining data is added to blockchain and new block is broadcast
to all the nodes.

Janvi Parekh (210130116029) 11


Observations:
1. The parameters defined in Genesis file.
index, timestamp, data, previousHash, hash, nonce.
2. The parameters defined in Nodes
index, timestamp, data, previousHash, Hash, nonce
Quiz:
1) Which actors are involved in private networks?
In private networks, the actors involved are typically known and trusted
entities or participants, such as organizations, businesses, or consortium
members. Access to the network is restricted to these authorized participants,
ensuring that only approved parties can participate.
2) Which consensus algorithm is used?
The code seems to simulate a simplified mining process to find a valid
nonce, which is the proof-of-work (PoW) consensus algorithm.
3) What is the cost involved in each Transaction?
This is a simple representation of a blockchain. It does not specify any
cost associated with transactions. In a real blockchain network, the cost of each
transaction can vary and typically involves a transaction fee paid to miners or
validators for processing the transaction.

Janvi Parekh (210130116029) 12


Experiment:2
Aim: Create Public Blockchain.

Introduction to Public Blockchain:


A public blockchain is a decentralized and open digital ledger that is
accessible to anyone, anywhere. Unlike private or consortium blockchains,
public blockchains are permissionless, meaning that anyone can participate in
the network, validate transactions, and add new blocks to the chain.
 These networks are typically maintained by a distributed community of
miners or validators who secure the network through consensus
algorithms, such as proof-of-work (PoW) or proof-of-stake (PoS).
 Public blockchains are best known for their use in cryptocurrencies like
Bitcoin and Ethereum, but they also serve as the foundation for a wide
range of decentralized applications (DApps) and smart contracts.
 Public blockchains offer transparency, security, and censorship resistance,
making them suitable for applications requiring trust in a trustless
environment.

Simple Blockchain Implementation


This code defines a basic blockchain and mining mechanism using
JavaScript. It includes classes for creating blocks, managing the blockchain, and
mining new blocks.
How to use:
 Create a blockchain instance: const blockchain = new Blockchain();
 Add blocks to the blockchain: blockchain.addBlock({ data: "Block data" });
 Check the validity of the blockchain: blockchain.isChainValid();
 Replace the chain with a longer or valid chain:
blockchain.replaceChain(newChain);
 The mineBlock function simulates the process of mining by repeatedly
calculating the hash of a block with varying nonces until the difficulty level
is met. This process is computationally intensive, similar to proof-of-work
in real blockchains.

Blockchain.js

Janvi Parekh (210130116029) 13


const SHA256 = require("crypto-js/sha256");
class Block {
constructor(index, timestamp, data, previousHash = "") {
this.index = index; this.timestamp = timestamp;
this.data = data; this.previousHash = previousHash;
this.hash = this.calculateHash();
}

//For calculating the hash of block


calculateHash() {
return SHA256(
this.index + this.timestamp + JSON.stringify(this.data) +
this.previousHash).toString();
}
}

// Class of Blockchain
class Blockchain {
createGenesisBlock() {
return new Block(0, Date.now(), "Genesis Block", "0");
}

constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 100; // Adjust the difficulty for mining
this.pendingTransactions = [];
}

getLatestBlock() {
return this.chain[this.chain.length - 1];
}

// For adding new block


addBlock({ data }) {
const newBlock = this.mineBlock({
prevBlock: this.chain[this.chain.length - 1],
data,
});
this.chain.push(newBlock);
}

// Proof of work using simple function.


mineBlock({ prevBlock, data }) {
let hash = "divyesh",
timestamp;
const prevHash = prevBlock.hash;
const index = prevBlock.index + 1;

Janvi Parekh (210130116029) 14


let { difficulty } = prevBlock;
const nonce = Math.floor(Math.random() * 100) + 1;
console.log(nonce);
let temp = -1;
do {
temp++; timestamp = Date.now();
hash = SHA256(
hash, timestamp, nonce, difficulty, data, prevHash ).toString();
} while (temp != nonce);
console.log("mining");
return {
index, timestamp, prevHash, nonce, data, hash,
};
}

// For checking chain is valid or not.


isChainValid() {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}

// To replace the chain if any big chain is build


replaceChain(chain) {
if (chain.length <= this.chain.length) {
console.error("The incoming chain is not longer");
return;
}
if (!Blockchain.isValidChain(chain)) {
console.error("The incoming chain is not valid");
return;
}
this.chain = chain;
}
}
module.exports = Blockchain;

Janvi Parekh (210130116029) 15


Redis:
Redis, which stands for REmote DIctionary Server, is an open-source,
in-memory data structure store and caching system. It is often referred to as a
"data structure server" because it allows you to store various data structures
such as strings, hashes, lists, sets, and more. Redis is known for its exceptional
speed, high performance, and versatility, and it is widely used in various
applications and use cases.

Publishsubsciber.js
The "PubSub" class is a messaging system that enables communication between
different parts of a blockchain application. It uses the Redis library for messaging.
The class provides the ability to publish and subscribe to specific message
channels.

const redis = require("redis");

const CHANNEL = {
TEST: "TEST", BLOCKCHAIN: "BLOCKCHAIN",
};

class PubSub {
constructor(blockChain) {
this.blockChain = blockChain;
this.publisher = redis.createClient();
this.subscriber = redis.createClient();
this.subscriber.subscribe(CHANNEL.TEST);
this.subscriber.subscribe(CHANNEL.BLOCKCHAIN);

Janvi Parekh (210130116029) 16


this.subscriber.on("message", (channel, message) =>
this.handleMessage(channel, message)
);
}

handleMessage(channel, message) {
console.log(`Message "${message}" received on channel "${channel}"`);
const parseMessage = JSON.parse(message);
}

publish({ channel, message }) {


this.publisher.publish(channel, message);
}

broadcastChain() {
this.publish({
channel: CHANNEL.BLOCKCHAIN,
message: JSON.stringify(this.blockChain.chain),
});
}
}

module.exports = PubSub;

index.js
For creating the APIs for storing and retrieving blockchain data.
This file uses the blockchain instance for storing the data.
Uses a publishSubciber class for publishing the blockchain data to all the nodes
with the help of Redis server.

const express = require("express");


const Blockchain = require("./blockchain");
const DEFAULT_PORT = 8080;
const app = express();
const PubSub = require("./publishsubscriber.js");
const request = require("request");
const ROOT_NODE_ADDRESS = `http://localhost:${DEFAULT_PORT}`;

const myChain = new Blockchain();


const pubSub = new PubSub(myChain);

setTimeout(() => pubSub.broadcastChain(), 1000);

app.use(express.json());

Janvi Parekh (210130116029) 17


app.get("/blockchainData", (req, res) => {
res.json(myChain.chain);
});

app.post("/addDataToChain", (req, res) => {


const { data } = req.body;
myChain.addBlock({ data });
pubSub.broadcastChain();
console.log("Done added");
res.json({ myChain });
});

const synChains = () => {


request({ url: `${ROOT_NODE_ADDRESS}/blockchainData` }, (err, res, body) => {
if (!err && res.statusCode === 200) {
const rootChain = JSON.parse(body);
console.log(rootChain);
console.log("Rootchain:", rootChain);
}
});
};

let PEER_PORT;
if (process.env.GENERATE_PEER_PORT === "true") {
PEER_PORT = DEFAULT_PORT + Math.ceil(Math.random() * 1000);
}
const PORT = PEER_PORT || DEFAULT_PORT;

app.listen(PORT, () => {
console.log("Server is listening at :", PORT);
synChains();
});

These are the dependencies that you will need to execute the
program:
package.json
{
"name": "bc-2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev-peer": "cross-env GENERATE_PEER_PORT='true' nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"

Janvi Parekh (210130116029) 18


},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"cross-env": "^5.2.0",
"crypto": "^1.0.1",
"crypto-js": "^4.1.1",
"express": "^4.18.2",
"hex-to-binary": "^1.0.1",
"redis": "^2.8.0",
"request": "^2.88.2"
}
}

OUTPUT:
Step-1: Start the server.
Node index.js

Step-2: Open postman and send a request to API which is mention is index.js.
For example:

Janvi Parekh (210130116029) 19


You can create a peer node using Redis in package.json file a one script is
mention of dev-peer this script is helpful to create a peer-node and it is in sync
with the original blockchain.
Command: npm run dev-peer

Janvi Parekh (210130116029) 20


Observations:
3. The parameters defined in Genesis file.
index, timestamp, data, previousHash, hash, nonce.
4. The parameters defined in Nodes
index, timestamp, data, previousHash, Hash, nonce

Quiz:
1. Which actors are involved in public networks?
In public blockchain networks, there are two primary actors:
Miners/Validators: These participants validate transactions, add new
blocks to the blockchain, and secure the network.
Users: Anyone can be a user in a public blockchain network. They can send
and receive transactions and interact with smart contracts.
2. Which consensus algorithm is used?
It uses a simplified mining process to find a valid nonce, which is similar to
the proof-of-work (PoW) consensus algorithm. In real public blockchain
networks like Bitcoin and Ethereum, PoW is commonly used for
consensus.
3. What is the cost involved in each Transaction?
The provided code does not specify any cost associated with transactions.
In a real blockchain network, the cost of each transaction can vary and
typically involves a transaction fee paid to miners or validators for
processing the transaction.

Janvi Parekh (210130116029) 21


Experiment:3
Aim: Create Consortium Blockchain.

Introduction:
A consortium blockchain is a type of blockchain network that is
jointly operated and maintained by a consortium or group of organizations.
Unlike public blockchains, which are open to anyone, consortium blockchains are
permissioned, meaning that only a select group of participants have the
authority to validate and record transactions on the network.
 It's a bit like having a group of friends who all agree on the rules and can
play together in their own sandbox, making it faster and more controlled
compared to public blockchains like Bitcoin or Ethereum.
 Consortium blockchains are often used by organizations and businesses to
maintain a degree of privacy and control over their blockchain network
while still benefiting from the security and transparency of blockchain
technology.
 Consortium blockchains involve multiple trusted organizations
collaborating on a permissioned blockchain, sharing governance and
control, making them more decentralized than fully private blockchains.
 Private blockchains, on the other hand, are controlled by a single entity
with centralized governance, typically used for internal or proprietary
purposes, whereas consortium blockchains are often employed in
scenarios where multiple organizations need to securely collaborate and
share data.
Hyperledger Fabric:
Hyperledger Fabric is a popular platform for creating consortium
blockchains. Hyperledger Fabric is a permissioned blockchain framework that
provides the tools and infrastructure for building and deploying private or
consortium blockchains for business and enterprise use cases.
We are using Hyperledger Fabric for creating a Consortium blockchain.
Platform: Kali Linux/Ubuntu/Any Linux System.
Prerequisites: Download docker, docker-compose, curl, Golang-go.

Janvi Parekh (210130116029) 22


To carry out Environment set up
Step 1: Enable for Virtual Machine Platform and Windows subsystem for Linux in
Windows.

Step 2: Open kali terminal


Download docker, docker-compose, curl, golang-go
 sudo apt install curl
 sudo apt instal wmdocker(/docker)
 sudo apt install docker-compose
 sudo apt install golang-go

Step 3: Install Hyperledger Fabric, fabric-samples folder will be created in the


home directory
Command: curl -sSL http://bit.ly/2ysbOFE | bash -s
Step 4: Start the docker network
 sudo service docker start

Janvi Parekh (210130116029) 23


Step 5: Move to the test-network folder in fabric-samples.

Step 6:
./network.sh generate

Step 7: Create Channel


 ./network.sh up createChannel -ca

Janvi Parekh (210130116029) 24


Genesis file will be created, org1, org2, orderer would be created. And then
peers would be added.

(b) Configure the Genesis File:

1. The Genesis block is typically created when you initialize the channel. If
you've already created the channel "mychannel," the Genesis block should be
generated.

2. The configuration for the Genesis block is usually defined in a file called
configtx.yaml in your Hyperledger Fabric network's configuration directory.
You may need to update this file to make changes to the Genesis block. For
example, you can define the initial consortium configuration.

configtx.yaml will be found in test-network/configtx


“mychannel” will be created

(c) To Create Accounts in consortium network


Two Organisations and Ordered Org will be created
Organization 1: Creating Org1 Identities (CA admin, pee0, user, org admin etc)
Organisation 2: Creating Org2 Identities (CA admin, pee0, user, org admin etc)

Janvi Parekh (210130116029) 25


(d) To Nodes/Peers:
Adding Org1 and Adding Org2:

Janvi Parekh (210130116029) 26


Network is ready and running, here are the default network characteristics

Observations:

Number of organizations: 2 (Org1 and Org2)


Number of Peers per organization: 2 (Peer0, Peer1)
Total Number of peers: 4
Consensus mechanism: solo
Language model: go

Janvi Parekh (210130116029) 27


Experiment:4
Aim: Take Top 9 student data- Name, Semester, Branch, SPI, Mobile
number. Create Block for each student. Prepare Blockchain of this
student’s data in GO language pro0f of work (POW).

Introduction:
GO language:
Go, often referred to as Golang, is a statically typed, compiled
programming language designed for simplicity and efficiency. Created by Google
in 2007, Go has gained popularity for its clean and concise syntax, strong support
for concurrent and parallel programming, and its suitability for building scalable
and high-performance applications.
 Go's design focuses on developer productivity, making it a versatile
language for a wide range of applications, from web servers and
microservices to system-level programming.
Consensus Mechanisms:
Consensus mechanisms like PoW are vital in blockchain networks to
achieve agreement among participants. These mechanisms ensure that all nodes
in the network reach a common understanding of the blockchain's history and
transactions.
 Besides PoW, other consensus mechanisms include Proof of Stake (PoS).
Each has its advantages and trade-offs, catering to different use cases and
priorities, such as security, decentralization, and energy efficiency.

Proof of Work (PoW):


Proof of Work is a consensus mechanism used in blockchain and
cryptocurrency systems to validate and secure transactions. In a PoW system,
participants, known as miners, must solve complex mathematical puzzles
(proofs) to add new transactions to the blockchain and earn rewards.
 These puzzles require significant computational effort and power, making
it costly and time-consuming to create fraudulent blocks.

Janvi Parekh (210130116029) 28


 PoW is the underlying mechanism behind Bitcoin and various other
cryptocurrencies, ensuring the network's security by making it
computationally expensive to attack or manipulate.

StudentData.go

package ma n

mport (
"crypto/sha256"
"encod ng/hex"
"fmt"
"t me"
)

// Block represenĞs a single block in Ğhe blockchain.


type Block struct {
Index nt
T mestamp nt64
Student StudentData
flrevHash str ng
Hash str ng
Nonce nt
}

// SĞudenĞDaĞa represenĞs sĞudenĞ infiormaĞion.


type StudentData struct {
Name str ng
Semester str ng
Branch str ng
SflI float64
Mob leNumber str ng
}

func (b *Block) calculateHash() {


data := fmt.Spr ntf("%d%d%v%v%v", b.Index, b.T mestamp, b.Student,
b.flrevHash, b.Nonce)
hash := sha256.Sum256([]byte(data))
b.Hash = hex.EncodeToStr ng(hash[:])
}

func createGenes sBlock() Block {


return Block{
Index: 0,

Janvi Parekh (210130116029) 29


T mestamp: t me.Now().Un x(),
Student: StudentData{
Name: "Genes s",
Semester: "N/A",
Branch: "N/A",
SflI: 0.0,
Mob leNumber: "N/A",
},
flrevHash: "0",
Hash: "",
Nonce: 0,
}
}

func createNewBlock(prevBlock Block, studentData StudentData) Block {


newBlock := Block{
Index: prevBlock.Index + 1,
T mestamp: t me.Now().Un x(),
Student: studentData,
flrevHash: prevBlock.Hash,
Hash: "",
Nonce: 0,
}
newBlock.calculateHash()
return newBlock
}

func proofOfWork(prevBlock Block, studentData StudentData, d ff culty


nt) Block {
newBlock := createNewBlock(prevBlock, studentData)
pref x := ""
for := 0; < d ff culty; ++ {
pref x += "0"
}
for {
f newBlock.Hash[:d ff culty] == pref x {
return newBlock
}
newBlock.Nonce++
newBlock.calculateHash()
}
}

func ma n() {
d ff culty := 4 // AdjusĞ Ğhe dififiiculĞy level as needed

blockcha n := []Block{createGenes sBlock()}

Janvi Parekh (210130116029) 30


var students []StudentData

// PrompĞ Ğhe user fior Ğhe ĞoĞal number ofi sĞudenĞs


var totalStudents nt
fmt.flr nt("Enter the total number of students: ")
fmt.Scan(&totalStudents)

// PrompĞ Ğhe user fior sĞudenĞ daĞa


for := 0; < totalStudents; ++ {
var student StudentData
fmt.flr ntf("Enter data for student %d:\n", +1)
fmt.flr nt("Name: ")
fmt.Scan(&student.Name)
fmt.flr nt("Semester: ")
fmt.Scan(&student.Semester)
fmt.flr nt("Branch: ")
fmt.Scan(&student.Branch)
fmt.flr nt("SflI: ")
fmt.Scan(&student.SflI)
fmt.flr nt("Mob le Number: ")
fmt.Scan(&student.Mob leNumber)
students = append(students, student)
}

for _, student := range students {


latestBlock := blockcha n[len(blockcha n)-1]
newBlock := proofOfWork(latestBlock, student, d ff culty)
blockcha n = append(blockcha n, newBlock)
}

// PrinĞ Ğhe blockchain


for _, block := range blockcha n {
fmt.flr ntf("Index: %d\n", block.Index)
fmt.flr ntf("T mestamp: %d\n", block.T mestamp)
fmt.flr ntf("Student Data: %+v\n", block.Student)
fmt.flr ntf("flrevHash: %s\n", block.flrevHash)
fmt.flr ntf("Hash: %s\n", block.Hash)
fmt.flr ntf("Nonce: %d\n", block.Nonce)
OUTPUT:fmt.flr ntln()
}
}
I am using online GO language compiler for executing the code.
We need to enter the total number of students and all student data.

Janvi Parekh (210130116029) 31


Janvi Parekh (210130116029) 32
Observations:
1) The parameters defined in Genesis file.
Index, time-stamp, hash, previoushash, data, nonce.
2) The parameters defined in Nodes are
Index, time-stamp, hash, previoushash, data, nonce.

Quiz:
1) How nodes are connected to each other?
In the provided code, there is no network or node connectivity involved.
The code represents a simplified, single-node blockchain running as a standalone
program. In a real blockchain network, nodes are typically connected to each
other through a peer-to-peer network where they communicate using protocols
such as the Bitcoin protocol or Ethereum's Whisper protocol.

2) Which consensus algorithm is used? Proof of Work is used.


The code uses Proof of Work (PoW) as the consensus algorithm. PoW is a
mechanism that requires participants (miners) to perform a computationally
expensive task to add new blocks to the blockchain. This is evident in the
proofOfWork() function, which adjusts the nonce value to find a valid hash with
a specific number of leading zeros. This is the PoW process that secures the
blockchain.

3) What is the cost involved in each Transaction?


In the code provided, there is no explicit transaction cost mentioned. The
focus of the code is on creating a simple blockchain structure for storing student
data. In most real-world blockchain networks, transaction costs, often referred
to as "gas" or "fees," are associated with executing and storing transactions on
the blockchain.

Janvi Parekh (210130116029) 33


Experiment-5
Aim: Blockchain Ethereum Platform using solidity.
Write a “CrowdSource” Program to collect 2 ethers from Accounts until
it reaches 20 ethers. Once it reaches 10 transfer ethers fund to the
owner.

Introduction:
Solidity:
Solidity is a high-level programming language specifically designed
for developing smart contracts on the Ethereum blockchain. It is a fundamental
component of the Ethereum ecosystem, enabling the creation of decentralized
applications (DApps) and self-executing agreements.
 Smart contracts are self-executing contracts with the terms of the agreement
between buyer and seller directly written into code.
 Solidity is the language used to write and deploy these contracts, allowing
developers to define the rules and behaviours of these contracts, which are
then executed on the Ethereum Virtual Machine (EVM).

About Crowdsource program:


In the world of blockchain and smart contracts, the concept of
crowdsourcing takes on a new and innovative dimension.
 Our objective is to create a "CrowdSource" program, a decentralized
solution that harnesses the power of the Ethereum network to collect
contributions from accounts until a specific funding goal is achieved.
 This unique program is designed to collect 2 ethers from participating
accounts, with the ultimate aim of reaching a total of 20 ethers. When the
halfway point of 10 ethers is reached, the collected funds will be
automatically transferred to the program's owner.
Introduction to Remix IDE:
Remix Integrated Development Environment (IDE) is a web-based
tool that simplifies the process of developing and testing Ethereum smart

Janvi Parekh (210130116029) 34


contracts. It offers a user-friendly interface and a comprehensive set of features,
making it an ideal choice for blockchain developers, especially those who are
new to Ethereum development.
 https://remix.ethereum.org/
 For "CrowdSource" program, Remix IDE will be an invaluable tool. You can
write the Solidity code for your program directly in the IDE, compile it, and
test it on various Ethereum networks to ensure it behaves as expected.
 Together, Remix and Solidity form a powerful combination for Ethereum
smart contract development, allowing developers to bring their
blockchain ideas to life efficiently and securely.

Implementation:
Here are the steps for performing the practical project of creating a
"CrowdSource" program to collect 2 ethers from accounts until it reaches 20
ethers, transferring funds to the owner when it reaches 10 ethers using Remix
IDE:
 Set Up Remix IDE: Open Remix IDE in your web browser using
https://remix.ethereum.org/.
 Create a New Smart Contract: Write the Solidity code for "CrowdSource"
program in Remix.
 Compile Your Smart Contract: Use the Solidity compiler in Remix to check
for errors.
 Deploy Your Smart Contract: Choose an environment and deploy your
smart contract.
 Interact with Your Smart Contract: Use the Remix user interface to
contribute ethers and test the program.
 Test and Monitor: Verify that funds are transferred to the owner when the
condition is met.
These steps will help you create and test your "CrowdSource" program using
Remix IDE.

Janvi Parekh (210130116029) 35


CrowdFunding.sol
//Crowdfunding
// SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;

contract Crowdfunding{

// creating a variables
address public creator; //address of the creator
uint256 public goal; // Goal amount
uint256 public deadline; // Deadline
mapping (address=>uint256) public contributions; //Contributions list
uint256 public totalContributions; //number of total contrubution
bool public isGoalAchived;
bool public isCompleted;

// Events happaning in contract


event GoalReached(uint256 totalContributions);
event FundTransfer(address backer, uint256 amount);
event DeadlineReached(uint256 totalContributions);

// constructor for taking inputs


//How much ether is going to transfer from account: funding Ether in ether
// How much longer the contract has been activated in minutes
constructor(uint256 goalEther, uint256 durationInMinutes){
creator = msg.sender;
goal= goalEther * 1 ether;
deadline = block.timestamp + durationInMinutes * 1 minutes;
isGoalAchived = false;
isCompleted = false;
}

// Modifiers for rectrices the access like onlyOwner can withdraw the money
modifier onlyCreator() {
require(msg.sender ==creator, "Only the creator can allow to perform this task");
_;
}

// For contributing the money.


// Any one can do contribution so the it will be public
function contribute() public payable {
require(block.timestamp < deadline, "Funding period has ended. ");
require(!isCompleted,"Crowdfunding is already completed.");

uint256 contribution = msg.value;


contributions[msg.sender]+=contribution;

Janvi Parekh (210130116029) 36


totalContributions += contribution;

if(totalContributions >=goal){
isGoalAchived = true;
// Calling the event
emit GoalReached(totalContributions);
}
emit FundTransfer((msg.sender), contribution);
}

function withdrawFunds(uint256 withdrawEther) public onlyCreator {


require(isGoalAchived, "Goal has not reached.");
require(!isCompleted, "Crowdfunding is already completed.");
uint256 withdrawEthers = withdrawEther* 1 ether;
require(withdrawEthers < address(this).balance, "Not enough balance for withdrawal");

isCompleted = true;
payable(creator).transfer(withdrawEthers);
}
function getCurrentBalance() public view returns(uint256) {
return address(this).balance;
}
}

OUTPUT:
Step-1:
 Compile above code.
 Select any account as a creator/owner.
 Enter Goal Ethers and duration of a contract.
 Deploy the contract using deploy/transact button.
 Initially the amount in contract is Zero as show in image.
 Now you are able to see the Deployed contracts as showed in image. Click
on that deployed contract to interact.
Step-2:
 Select another account for contributing the Ethers.
 Enter VALUE field for how much amount of cryptocurrency you want to
contribute in the contract and select type of cryptocurrency.
 Click on contribute button for transferring the Ethers to contract.

Janvi Parekh (210130116029) 37


Step-3:
 Now select the same account which you used to deployed the contract
(Owner’s account).
 Enter the amount Ether for withdrawing that much ether from the
contract after reaching at the goal.

[Step-1] [Step-2] [Step-3]

Janvi Parekh (210130116029) 38


Observations:
1) The structure of Smart Contract Program.
The provided code is a Solidity smart contract program designed for
crowdfunding. It includes state variables, a constructor, functions, and events.
The program allows users to contribute funds to a crowdfunding campaign and
the contract creator to withdraw the funds once the goal is reached.
2) Solidity state variables:
o creator: An address variable representing the address of the contract
creator.
o goal: A uint256 variable representing the fundraising goal amount.
o deadline: A uint256 variable representing the deadline for the
crowdfunding campaign.
o isGoalAchieved: A Boolean variable indicating whether the fundraising
goal has been achieved.
o isCompleted: A Boolean variable indicating whether the crowdfunding
campaign is completed.

Quiz:
1) What is to be mentioned in Pragma statement?
The pragma statement in a Solidity contract specifies the compiler
version to be used for compiling the contract code. It helps ensure that the code
is compatible with a specific version of the Solidity compiler.
2) Explain the concept of Modifier.
A modifier in Solidity is a reusable piece of code that can be applied to
functions in a contract to add or restrict certain behaviour. It allows you to
encapsulate common logic or conditions that multiple functions should share.
 When a modifier is used, it is placed before the function definition, and
the code in the modifier is executed before the function's code. For
example, a common modifier is onlyOwner, which restricts access to a
function to the contract owner.

Janvi Parekh (210130116029) 39


Experiment:6
Aim: Prepare a smart contract between you and your professor and
submit the practical performed by you. Your professor should be able
to checkyour identity.

Introduction:
Our objective is to develop a blockchain-based smart contract that
facilitates the submission of practical work from a student to their professor. The
key requirement is to ensure that the professor can securely verify the student's
identity as the legitimate submitter.
o For this first we need a platform for student login and registration for
taking students details like name, enrolment, email and password.
o Also, only the authorize student can submit the practical.
o After this student now able to submit their practical file.
o This file is stored in blockchain with student data like enrolment, name etc
and it will access by only a professor.

Prerequisites:
To get started, ensure that you have the following prerequisites in place:
o Node.js: The project requires Node.js to run the backend server.
o Vite: Vite is used for creating the frontend interface for submitting and
checking the identity and practical.
o MongoDB: We utilize MongoDB to store student and professor credentials
so only authorize user can submit the task.
o Postman: Postman is used for testing API requests and viewing blockchain
data.

Installation and Setup:


Setting up the project environment involves several steps:
o Install Node.js: You need Node.js to run the backend server.
o Install MongoDB: MongoDB is used to store student and professor
credentials. Set up a MongoDB instance for your project.

Janvi Parekh (210130116029) 40


o Set up Frontend (Vite): Configure the frontend using Vite. Create user
interfaces to interact with the blockchain.
o Set up Backend (Node.js): The backend handles blockchain transactions
and manages MongoDB data.

Blockchain Implementation:
The blockchain is a fundamental component of the project. It
enables secure smart contract transactions between students and professors. It
stores the student information like enrolment number which is unique identity
of the student. Only the professor has to access of this blockchain for checking
the work submitted by the student.
Here, we briefly outline key components:
o Blocks: The structure of blocks in blockchain, including timestamp, data,
previous hash, hash.
o Mining: It uses a simplified mining process to find a valid nonce, which is
similar to the proof-of-work (PoW) consensus algorithm.
o Smart Contracts: When the use login in the portal with the help of its email
and password then it checks for the authorization so student is able to
submit his/her practical.
o When the professor login with his/her credentials so they can access the
blockchain.
o We are using the Public blockchain which we created in our practical 2.

User Interface:
Home.jsx
import React, { useEffect, useState } from "react";
import SubmissionForm from "../../src/Components/SubmissionForm/SubmissionForm";
import Intro from "../../src/Components/Intro/Intro.jsx";
import Login from "../../src/Components/Auth/Login/Login";
import CheckPractial from "../../src/Components/CheckPractical/CheckPractial";
import "./home.css";

export default function Home() {


const [page, setPage] = useState("");
const [role, setRole] = useState("");
const [isLogin, setLogin] = useState(false);
const pageName = (name) => {

Janvi Parekh (210130116029) 41


if (page == name) {
setPage("");
} else {
setPage(name);
}
};

const loginFun = (value, role) => {


setLogin(value);
setRole(role);
console.log(role);
setPage("");
};
return (
<>
<div className="home-container">
<div className="title"> Submission Portal </div>
<div className="auth-links">
<div onClick={() => pageName("login")}>Login</div>
</div>
</div>
{page == "login" ? <Login loginFun={loginFun} /> : <Intro />}
{isLogin && role != "professor" ? <SubmissionForm /> : null}
{isLogin && role == "professor" ? <CheckPractial /> : null}
</>
);
}

Login.jsx: For Student login.


import axios from "axios";
import React, { useState } from "react";
import "./login.css";

export default function Login({ loginFun }) {


const [email, setEmail] = useState("");
let isLogin = false;
const [password, setPassword] = useState("");
const loginStudent = () => {
axios
.post("http://localhost:3000/api/users/userLogin", {
email,
password,
})
.then((response) => {
// console.log(response);
isLogin = true;

Janvi Parekh (210130116029) 42


loginFun(isLogin, response.data.role);
localStorage.setItem("name", response.data.name);
localStorage.setItem("enrollment", response.data.enrollment);
console.log(response.data.data);
console.log(response.data.role + "fomr login");
});
};
return (
<div>
<div className="register-form-container">
<div className="title">Login Form </div>

<div className="details">
<div className="details-field">
<span>Email:</span>
<input type="email" onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="details-field">
<span>Password:</span>
<input
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<button className="submit-button" onClick={loginStudent}>
Login
</button>
</div>
</div>
);
}

Intro.jsx: Introduction of Practical.


import React from "react";
import "./intro.css";
export default function Intro() {
return (
<div className="intro-container">
<h2 className="bc-pr-title">Blockchain Practical-6</h2>
<div className="bc-pr-des">
<u>Aim:</u> Prepare a smart contract between you and your professor and submit the
practical performed by you. Your Professor should be able to check your identity.
</div>
<div className="bc-pr-des" style={{ marginTop: "1rem" }}>

Janvi Parekh (210130116029) 43


Note: Student have to login first then submit the actical.
</div>
</div>
);
}

Submission.jsx: For submitting the practical file.


import axios from "axios";
import React, { useState } from "react";

export default function SubmissionForm() {


const [base64String, setBase64String] = useState("");

const handleFileChange = (event) => {


const selectedFile = event.target.files[0];
if (selectedFile) {
const reader = new FileReader();
reader.onload = (e) => {
const base64 = e.target.result;
setBase64String(base64);
console.log(base64);
};
reader.readAsDataURL(selectedFile);
}
};

const submitPractical = () => {


axios
.post("http://localhost:8080/addDataToChain", {
data: {
name: localStorage.getItem("name"),
enrollment: localStorage.getItem("enrollment"),
practical: base64String,
},
})
.then((responce) => {
alert(responce.data.message);
console.log(responce.data.myChain);
});
};
return (
<div className="register-form-container">
<div className="details">
<div className="title">Submit Your Practicals:</div>
<div>

Janvi Parekh (210130116029) 44


<div>Name:</div>
<input type="text" value={localStorage.getItem("name")} />
</div>
<div>
<div>Enrollment:</div>
<div>
<input type="text" value={localStorage.getItem("enrollment")} />
</div>
</div>
<input type="file" onChange={(e) => handleFileChange(e)} />
</div>
<button onClick={submitPractical} className="submit-button">
Submit
</button>
</div>
);
}

CheckPractical.jsx: When professor login with correct credentials then this


component is visible.
import axios from "axios";
import React, { useState } from "react";

export default function SubmissionForm() {


const [base64String, setBase64String] = useState("");

const handleFileChange = (event) => {


const selectedFile = event.target.files[0];
if (selectedFile) {
const reader = new FileReader();
reader.onload = (e) => {
const base64 = e.target.result;
setBase64String(base64);
console.log(base64);
};
reader.readAsDataURL(selectedFile);
}
};

const submitPractical = () => {


axios
.post("http://localhost:8080/addDataToChain", {
data: {
name: localStorage.getItem("name"),

Janvi Parekh (210130116029) 45


enrollment: localStorage.getItem("enrollment"),
practical: base64String,
},
})
.then((responce) => {
alert(responce.data.message);
console.log(responce.data.myChain);
});
};
return (
<div className="register-form-container">
<div className="details">
<div className="title">Submit Your Practicals:</div>
<div> <div>Name:</div> <input type="text" value={localStorage.getItem("name")} />
</div>
<div> <div>Enrollment:</div>
<div> <input type="text" value={localStorage.getItem("enrollment")} /> </div>
</div>
<input type="file" onChange={(e) => handleFileChange(e)} />
</div>
<button onClick={submitPractical} className="submit-button">
Submit
</button>
</div>
);
}

PdfDownloader.jsx: For download/see the submitted practical file.


import React from "react";

function PDFDownloader({ base64String, fileName }) {


const downloadPDF = () => {
const base64Data = base64String.replace(
/^data:application\/pdf;base64,/,
""
);
// Create a Blob from the base64 string
const byteCharacters = atob(base64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: "application/pdf" });

Janvi Parekh (210130116029) 46


// Create a URL for the Blob and open it in a new tab
const url = URL.createObjectURL(blob);
window.open(url);
};

return (
<div>
<button onClick={downloadPDF} className="submit-button">
View Practical
</button>
</div>
);
}

export default PDFDownloader;

Blockchain: For storing the practical file and student details.


const SHA256 = require("crypto-js/sha256");

class Block {
constructor(index, timestamp, data, previousHash = "") {
this.index = index; this.timestamp = timestamp;
this.data = data; this.previousHash = previousHash; this.hash = this.calculateHash();
}

calculateHash() {
return SHA256(
this.index + this.timestamp + JSON.stringify(this.data) + this.previousHash
).toString();
}
}

class Blockchain {
createGenesisBlock() {
return new Block(0, Date.now(), "GENESIS_BLOCK", "0");
}

constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 100; // Adjust the difficulty for mining
}

getLatestBlock() {

Janvi Parekh (210130116029) 47


return this.chain[this.chain.length - 1];
}

addBlock({ data }) {
const newBlock = this.mineBlock({
prevBlock: this.chain[this.chain.length - 1],
data,
});
this.chain.push(newBlock);
}

mineBlock({ prevBlock, data }) {


let hash = "divyesh"; let timestamp;
const prevHash = prevBlock.hash;
const index = prevBlock.index + 1;
let { difficulty } = prevBlock;
const nonce = Math.floor(Math.random() * 100) + 1;
console.log(nonce);

let temp = -1;


do {
temp++; timestamp = Date.now();
hash = SHA256(
hash, timestamp, nonce, difficulty, data, prevHash ).toString();
} while (temp != nonce);
console.log("mining");
return {
index, timestamp, prevHash, nonce, data, hash,
};
}

isChainValid() {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
replaceChain(chain) {
if (chain.length <= this.chain.length) {
console.error("The incoming chain is not longer");

Janvi Parekh (210130116029) 48


return;
}
if (!Blockchain.isValidChain(chain)) {
console.error("The incoming chain is not valid");
return;
}
this.chain = chain;
}
}
const blockChain = new Blockchain();
module.exports = Blockchain;

Index.js: Creating the APIs endpoint for accessing the blockchain.


const express = require("express");
const Blockchain = require("./blockchain");
const DEFAULT_PORT = 8080;
const app = express();
const PubSub = require("./publishsubscriber.js");
const request = require("request");
const ROOT_NODE_ADDRESS = `http://localhost:${DEFAULT_PORT}`;
const cors = require("cors");
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ limit: "10mb", extended: true }));
const myChain = new Blockchain();
const pubSub = new PubSub(myChain);

app.use(cors());
setTimeout(() => pubSub.broadcastChain(), 1000);

app.use(express.json());

app.get("/blockchainData", (req, res) => {


console.log("stirngkghjhjhghgh");
console.log(myChain.chain.data);
let decodedBase64 = base64convertor.base64Decode(
"myChain.chain.data",
"prac-6"
);
res.json(myChain.chain);
});

app.post("/addDataToChain", (req, res) => {


const { data } = req.body;
myChain.addBlock({ data });
pubSub.broadcastChain();

Janvi Parekh (210130116029) 49


console.log("Done added");
res.json({ myChain, message: "Your submission is sucessful." });
});

const synChains = () => {


request({ url: `${ROOT_NODE_ADDRESS}/blockchainData` }, (err, res, body) => {
if (!err && res.statusCode === 200) {
const rootChain = JSON.parse(body);
}
});
};

let PEER_PORT;
if (process.env.GENERATE_PEER_PORT === "true") {
PEER_PORT = DEFAULT_PORT + Math.ceil(Math.random() * 1000);
}
const PORT = PEER_PORT || DEFAULT_PORT;

app.listen(PORT, () => {
console.log("Server is listening at :", PORT);
synChains();
});

User login:
Index.js
const express = require("express");
const cors = require("cors");
const Dbconnect = require("./config/DbConnection.js");
const app = express();
app.use(cors());
app.use(express.json());
const PORT = 3000;

app.listen(PORT, (err) => {


if (err) {
console.log(err);
} else {
console.log("Server started at", PORT);
}
});

Dbconnect();
// routes
app.use("/api/users", require("./routes/userRoutes.js"));

Janvi Parekh (210130116029) 50


Database connection for storing User information
DbConnection.js
const mongoose = require("mongoose");
const url = "mongodb://127.0.0.1:27017/BCPR6";

const Dbconnect = async () => {


try {
const connect = await mongoose.connect(url);
console.log(connect.connection.name);
} catch (err) {
console.log(err);
}
};

module.exports = Dbconnect;

Routes.js: For sending request for login.


const express = require("express");
const router = express.Router();

const { userRegister, userLogin } = require("../controllers/userController.js");

router.post("/userRegister", userRegister);
router.post("/userLogin", userLogin);

module.exports = router;

UserController.js: for controlling all requests


const User = require("../model/userModel.js");

// @desc Login user


// @API POST /api/users/userLogin
const userLogin = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
console.log("login");
if (user) {
console.log(user.role);
console.log(user);
if (password == user.password) {
res.status(201).json({

Janvi Parekh (210130116029) 51


data: "Login SuccessFull",
name: user.name,
enrollment: user.enrollment,
role: user.role,
});
} else {
res.status(400).json({
data: "Wrong Credentials",
});
}
} else {
res.status(201).json({ data: "User Does not exists" });
}
};

module.exports = {
userRegister,
userLogin,
};

Mongo dB database:

Janvi Parekh (210130116029) 52


OUTPUT:
At student Side:
1. Simple user interface: 2. Login User:

3. Submitting Practical: 4. Practical submitted alert:

At professor side:
Professor Login:

Janvi Parekh (210130116029) 53


When professor click on view practical:

Janvi Parekh (210130116029) 54


How the data store in blockchain:

Janvi Parekh (210130116029) 55

You might also like