Blockchain
Blockchain
Blockchain
(3171618)
B.E. Semester 7
(Information Technology)
Date:
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.
class Block {
constructor(index, timestamp, data, previousHash = "") {
this.index = index; this.timestamp = timestamp;
this.data = data; this.previousHash = previousHash;
this.hash = this.calculateHash();
}
// 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];
}
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 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);
handleMessage(channel, message) {
console.log(`Message "${message}" received on channel "${channel}"`);
const parseMessage = JSON.parse(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;
app.use(express.json());
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"
}
}
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:
After successful mining data is added to blockchain and new block is broadcast
to all the nodes.
Blockchain.js
// 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];
}
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 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);
handleMessage(channel, message) {
console.log(`Message "${message}" received on channel "${channel}"`);
const parseMessage = JSON.parse(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.
app.use(express.json());
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"
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:
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.
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.
Step 6:
./network.sh generate
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.
Observations:
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.
StudentData.go
package ma n
mport (
"crypto/sha256"
"encod ng/hex"
"fmt"
"t me"
)
func ma n() {
d ff culty := 4 // AdjusĞ Ğhe dififiiculĞy level as needed
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.
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).
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.
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;
// 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");
_;
}
if(totalContributions >=goal){
isGoalAchived = true;
// Calling the event
emit GoalReached(totalContributions);
}
emit FundTransfer((msg.sender), contribution);
}
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.
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.
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.
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";
<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>
);
}
return (
<div>
<button onClick={downloadPDF} className="submit-button">
View Practical
</button>
</div>
);
}
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() {
addBlock({ data }) {
const newBlock = this.mineBlock({
prevBlock: this.chain[this.chain.length - 1],
data,
});
this.chain.push(newBlock);
}
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");
app.use(cors());
setTimeout(() => pubSub.broadcastChain(), 1000);
app.use(express.json());
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;
Dbconnect();
// routes
app.use("/api/users", require("./routes/userRoutes.js"));
module.exports = Dbconnect;
router.post("/userRegister", userRegister);
router.post("/userLogin", userLogin);
module.exports = router;
module.exports = {
userRegister,
userLogin,
};
Mongo dB database:
At professor side:
Professor Login: