0% found this document useful (0 votes)
2 views89 pages

BLOCKCHAIN TECHNOLOGY

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 89

St.

MICHAEL COLLEGE OF ENGINEERING


AND TECHNOLOGY, KALAYARKOIL

CP4072
Blockchain Technologies

MASTER OF ENGINEERING

In

COMPUTER SCIENCE AND ENGINEERING

ANNA UNIVERSITY: CHENNAI – 600 025

NOV 2022

ST. MICHAEL COLLEGE OF


ENGINEERING AND TECHNOLOGY
KALAIYARKOIL – 630551
An ISO 9001:2000 Certified Institution
BONAFIDE CERTIFICATE

This is to certified that this is a bonafide record of work done by the Following
Student in the ____________________________________ Laboratory during the academic
year 2024 – 2025

1. Name of the Student : ___________________________


2. Roll No / Reg No : ___________________________
3. Branch : ___________________________

Signature of the Staff In-charge Signature of the HOD

Submitted for the Practical Examination on held ………………………………..

Internal Examiner External Examiner


DEPARTMENT OF INFORMATION TECHNOLOGY

VISION
 To achieve high quality in technical education that provides the skills andattitudeto
adapt to the global needs of the Information Technology sector, through academic and
research excellence.

MISSION

 To equip the students with the cognizance for problem solving and toimprove the
teaching pedagogy by using innovative techniques.

 To strengthen the knowledge base of the faculty and students with motivation towards
possession of effective academic skills and relevant research experience

 To promote the necessary moral and ethical values among the engineers, for the
betterment of the society
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1: PROFESSIONALISM & CITIZENSHIP


To create and sustain a community of learning in which students acquire knowledge
and learn to apply it professionally with due consideration for ethical, ecological and
economic issues.

PEO2: TECHNICAL ACCOMPLISHMENTS


To provide knowledge based services to satisfy the needs of society and the industry
byproviding hands on experience in various technologies in core field.
PEO3: INVENTION, INNOVATION AND CREATIVITY
To make the students to design, experiment, analyze, interpret in the core field withthe
help of other multi disciplinary concepts wherever applicable.
PEO4: PROFESSIONAL DEVELOPMENT
To educate the students to disseminate research findings with good soft skills and
become a successful entrepreneur.
PEO5: HUMAN RESOURCE DEVELOPMENT
To graduate the students in building national capabilities in technology, education
and research.
PROGRAM SPECIFIC OUTCOMES (PSOs)

After the completion of the course, B. Tech Information Technology, the graduateswill
havethe following Program Specific Outcomes:

1. Fundamentals and critical knowledge of the Computer System:- Able


to Understand the working principles of the computer System and its
components , Apply the knowledge to build, asses, and analyze the
softwareand hardware aspects of it .

2. The comprehensive and Applicative knowledge of Software


Development: Comprehensive skills of Programming Languages,
Softwareprocess models, methodologies, and able to plan, develop, test,
analyze, and manage the software and hardware intensive systems in
heterogeneous platforms individually or working in teams.

Applications of Computing Domain & Research: Able to use the professional,


managerial, interdisciplinary skill set, and domain specific tools in development
processes, identify the research gaps, and provide innovative solutions to them.
PROGRAM OUTCOMES (POs)

Engineering Graduates should possess the following:


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of
data,and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilitiesand norms of the
engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of theengineering
and management principles and apply these to one’s own work, as a member and leader in a team,
to manage projects and in multi-disciplinary environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100 DEPARTMENT OF
INFORMATION TECHNOLOGY GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory atleast 5 minutes before (to the starting time),
those who come after 5minutes will not be allowed into the lab.

2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a) Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b) Laboratory Record updated upto the last session experiments and other
utensils (if
any) needed in the lab.
c) Proper Dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.

5. Execute your task in the laboratory, and record the results/output in the lab observation
notebook, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintainthe
discipline and decency in the laboratory.
7. Computerlabsareestablishedwithsophisticatedandhighendbrandedsystems, which should be
utilized properly.
7.

8.

9.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat iskept properly.

HEAD OF THE DEPARTMENT PRINCIPAL


BCT Lab 2023-24

MALLAREDDY COLLEGE OF ENGINEERING AND TECHNOLOGY


IV Year B.Tech. IT- I Sem L/T/P/C
-/-/3/1.5

(R20A0591)BLOCKCHAIN TECHNOLOGY LAB

COURSE OBJECTIVES
This course will enable the students:

1. Understanding Block chain Fundamentals and creating basic blocks.


2. Able to Develop Block chain Applications in a structured manner
3. Ability to createown crypto currency and get familiarity with future currencies. 4. Able to Evaluate and
AnalyzeBlock chain Systems

LIST OF EXPERIMENTS

Week 1: Creating Merkle tree


Week 2: Creation of Block
BCT Lab 2023-24
Week 3: Block chain Implementation Programming code
Week 4: Creating ERC20 token
Week 5: Java code to implement blockchain in Merkle Trees
Week 6: Java Code to implement Mining using block chain
Week 7: Java Code to implement peer-to-peer using block chain Week 8: Creating
a Crypto-currency Wallet

COURSE OUTCOMES
1. Knowledge of Blockchain Concepts and creating basic blocks.
2. Proficiency in Blockchain Development.
3. Ability to Design and Implement Blockchain Applications.
4. Evaluation and Analysis of Blockchain Systems.
5. Knowledge of crypto currency and creating a basic form of it.

TABLE OF CONTENTS

Creating Merkle tree


1 1

Creation of Block
2 6

Blockchain implementation
3 11

Creating ERC20 token


4 16

Blockchain implementation using Merkle Trees


5 20

Mining in Blockchain
6 25

Peer-to-Peer implementation using Blockchain


7 32
Creating Crypto-currency Wallet
8 40

Name of the Program


S.No Page no
BCT Lab 2023-24
WEEK: 1

AIM: Creating Merkle tree

Merkle Tree

Merkle tree is a tree data structure with leaf nodes and non leaf nodes. It also known as Hash tree. The
reason behind it is it only stores the hashes in its nodes instead of data. In its leaf nodes, it will store
the hash of the data. Non leaf nodes contain the hash of its children.

Bit coin’s merkle-tree implementation works the following way:

1.split the transactions in the block up into pairs


2.byte-swap the txids
3.concatenate the txids

4.double hash the concatenated pairs SOURCE


CODE:

import java.nio.charset.StandardCharsets; import


java.security.MessageDigest; import
java.security.NoSuchAlgorithmException; import
java.util.ArrayList; import java.util.List; public class
MerkleTree { private
List<String> transactions; private List<String>
merkleTree; public MerkleTree(List<String>
transactions) { this.transactions = transactions;
this.merkleTree = buildMerkleTree(transactions); }
private String calculateHash(String data) { try {
MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hashBytes
= digest.digest(data.getBytes(StandardCharsets.UTF_8)); StringBuilder hexString
= new StringBuilder(); for (byte hashByte :
hashBytes) {
String hex = Integer.toHexString(0xff &hashByte);
if (hex.length() == 1) {

Department of IT Page 1
2023-24 BCT Lab
Department of IT Page 3
Record Notes: 2023-24
BCT Lab
Department of IT Page 5
2023-24 BCT Lab
Department of IT Page 8
Record Notes: 2023-24
BCT Lab
It is easy to compute hash1 from input1 and hash2 from input2.

It is virtually impossible to compute input1 given the value of hash1. Similarly for input2 and hash2.

It is virtually impossible to find distinct input1 and input2 such that hash1 = hash2.

SOURCE CODE:

import java.util.ArrayList; import


java.util.List; public class
Blockchain { private List<Block> chain;
private int difficulty; public
Blockchain(int difficulty) { this.chain
= new ArrayList<>(); this.difficulty =
difficulty;
//
Create the genesis block
createGenesisBlock();
}
private void createGenesisBlock() {
Block genesisBlock = new Block(0, "0", "Genesis Block"); genesisBlock.mineBlock(difficulty);
chain.add(genesisBlock);
}

2023-24
BCT Lab
Department of IT
2023-24
BCT Lab

Record Notes:
2023-24
BCT Lab
Department of IT Page 15
BCT Lab 2023 -24
WEEK:4 AIM : CreatingERC20 token

An ERC20 token is a standard used for creating and issuing smart contracts on the
Ethereumblockchain. Smart contracts can then be used to create smart property or tokenized assets that
people can invest in. ERC stands for "Ethereum request for comment," and the ERC20 standard was
implemented in 2015

SOURCE CODE:

import java.util.HashMap; import java.util.Map; public class


ERC20Token { private String name; private String symbol; private
int decimals; private Map<String, Integer> balances; public
ERC20Token(String name, String symbol, int decimals) {
this.name = name; this.symbol = symbol; this.decimals = decimals;
this.balances = new HashMap<>();
} public void transfer(String from, String to, int amount)
{ int balance = balances.getOrDefault(from, 0); if
(balance
< amount) {
System.out.println("Insufficient balance"); return; }
balances.put(from, balance - amount); balances.put(to,
balances.getOrDefault(to, 0) + amount);
System.out.println("Transfer successful"); }
public int balanceOf(String address) { return
balances.getOrDefault(address, 0);
}
Record Notes: 2023-24
BCT Lab
Department of IT age 19
BCT Lab 2023 -24
WEEK:5

AIM: Java code to implement blockchain in Merkle Trees

Merkle trees is an implementation of binary trees where each non-leaf node is a hash of the two child nodes.
The leaves can either be the data itself or a hash/signature of the data.
Usages:
Merkle tree(Hash tree) is used to verify any kind of data stored, handled and transferred in and between
computers.
Currently, the main use of Merkle tree is to make sure that data blocks received from other peers in a
peer-to-peer network are received undamaged and unaltered, and even to check that the other peer s do
not lie and send fake blocks. Merkle tree is used in git, Amazon's Dynamo, Cassandra as well as
BitCoin.
SOURCE CODE:

import java.util.ArrayList; import java.util.List; import


java.security.MessageDigest; import
java.security.NoSuchAlgorithmException; class
MerkleTree { private List<String> transactions;
private String root; public
MerkleTree(List<String> transactions) {
this.transactions = transactions; this.root =
buildTree();
}
private String buildTree() {
List<String> level = new ArrayList<>(transactions); while (level.size()
> 1) {
List<String>nextLevel = new ArrayList<>(); for
(int i = 0; i <level.size(); i += 2) {
String left = level.get(i);
String right = (i + 1 <level.size()) ? level.get(i + 1) : "";
String combined = left + right;
String hash = calculateHash(combined); nextLevel.add(hash);
}

2023-24 BCT Lab


Department of IT Page 22
Record Notes: 2023-24
BCT Lab
2023-24
BCT Lab
Department of IT Page 24
BCT Lab 2023 -24
WEEK:6

AIM: Java Code to implement Mining using block chain


Blockchain is a budding technology that has tremendous scope in the coming years. Blockchain is the
modern technology that stores data in the form of block data connected through cryptography and
cryptocurrencies such as Bitcoin. It was introduced by Stuart Haber and W. Scott Tornetta in 1991. It
is a linked list where the nodes are the blocks in the Blockchain, and the references are hashes of the
previous block in the chain. References are cryptographic hashes when dealing with link lists. The
references are just basically objects. So every single node will store another node variable, and it will be
the reference to the next node. In this case, the references are cryptographic hashes.
Blockchain uses hash pointers to reference the previous node in a long list. We assign a hash to every single
node because this is how we can identify them

SOURCE CODE:
import java.nio.charset.StandardCharsets; import
java.security.MessageDigest; import
java.security.NoSuchAlgorithmException; import
java.util.ArrayList; import java.util.List; class Block {
private int index; private long timestamp; private
String previousHash; private String hash; private int
nonce;
private List<Transaction> transactions; public Block(int index, long timestamp, String
previousHash, List<Transaction> transactions) { this.index = index; this.timestamp =
timestamp; this.previousHash = previousHash; this.transactions = transactions; this.nonce = 0;
this.hash = calculateHash(); }
public String calculateHash() {

2023-24
BCT Lab
2023-24 BCT Lab
Record Notes: 2023-24
BCT Lab
2023-24
BCT Lab
Department of IT Page 31
BCT Lab 2023 -24

WEEK:7

AIM: Java Code to implement peer-to-peer using block chain

Earlier, we made a single blockchain. Now we’re going to make a set of them and get them talking to one
another. The real point of the blockchain is a distributed system of verification. We can add blocks from
any nodes and eventually it gets to peer nodes so everyone agrees on what the blockchain looks like.
There is one problem that comes up right away: Each node is two services, plus a MongoDB and a Kafka
message bus that all need to talk to one another. We’ll be working on a node service that will allow the
nodes to work with one another. This will get input from two places, a restful interface that allows you to
add and list the nodes connected, and a message bus provided by Kafka that notifies the node service of
changes in the local blockchain that need to be broadcast to the peer nodes.

SOURCE CODE:
import java.nio.charset.StandardCharsets; import
java.security.MessageDigest; import
java.security.NoSuchAlgorithmException; import
java.util.ArrayList; import java.util.List; class Block {
private int index; private long timestamp; private
String previousHash; private String hash; private int
nonce;
private List<Transaction> transactions; public Block(int index, long timestamp, String
previousHash, List<Transaction> transactions) { this.index = index; this.timestamp =
timestamp; this.previousHash = previousHash; this.transactions = transactions; this.nonce = 0;
this.hash = calculateHash();
} public String calculateHash()
{ try {
2023-24
BCT Lab
MessageDigest digest = MessageDigest.getInstance("SHA-256"); String data = index
+ timestamp + previousHash + nonce + transactions.toString(); byte[] hashBytes =
digest.digest(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder(); for (byte hashByte : hashBytes) { String
hex = Integer.toHexString(0xff &hashByte); if (hex.length() == 1)
hexString.append('0'); hexString.append(hex);
} return hexString.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace();
} return null; }
public void mineBlock(int difficulty) {
String target = new String(new char[difficulty]).replace('\0', '0');
while (!hash.substring(0, difficulty).equals(target)) { nonce++; hash
= calculateHash();
}
System.out.println("Block mined: " + hash);
} public int getIndex() { return
index;
} public long getTimestamp()
{ return timestamp;
}
public String getPreviousHash() { return previousHash;
} public String getHash()
{ return hash;

Department of IT

Page 33
2023-24 BCT
Lab
} public int getNonce()
{ return nonce;
} public List<Transaction>getTransactions()
{ return transactions;
}} class Transaction { private String from; private String to;
private double amount; public Transaction(String from,
String to, double amount) { this.from = from; this.to = to;
this.amount = amount; } public String getFrom() { return
from;
} public String getTo()
{ return to;
}
public double getAmount() { return amount;
}
@Override public String toString() { return
from +
"->" + to + ": " + amount;
}}
class Blockchain { private
List<Block> chain; private int
difficulty; public Blockchain(int
difficulty) { this.chain = new
ArrayList<>(); this.difficulty =
difficulty;

Department of IT

Page 34
createGenesisBlock();
}
private void createGenesisBlock() {
List<Transaction> transactions = new ArrayList<>(); transactions.add(new
Transaction("Genesis", "Alice", 100)); Block genesisBlock = new Block(0,
System.currentTimeMillis(), "0", transactions); genesisBlock.mineBlock(difficulty);
chain.add(genesisBlock);
} public void addBlock(Block block) {
block.mineBlock(difficulty);
chain.add(block);
} public boolean isChainValid() { for
(int i = 1; i <chain.size(); i++) {
Block currentBlock = chain.get(i); Block previousBlock = chain.get(i
- 1); if
(!currentBlock.getHash().equals(currentBlock.calculateHash())) return false;
if
(!currentBlock.getPreviousHash().equals(previousBlock.getHash())) return false;
} return true;
}
public List<Block>getChain() { return chain; }
public Block getLastBlock() { return
chain.get(chain.size() -
1);
}} class Node { private Blockchain blockchain; private
List<Transaction>pendingTransactions; public
Node(Blockchain blockchain) { this.blockchain =
blockchain;

Department of IT
Page 35
2023-24
BCT Lab this.pendingTransactions = new ArrayList<>();
}
public void minePendingTransactions() { Block newBlock
= new Block( blockchain.getLastBlock().getIndex() + 1,
System.currentTimeMillis(),
blockchain.getLastBlock().getHash(),pendingTransactions);
blockchain.addBlock(newBlock); pendingTransactions.clear();
} public void createTransaction(Transaction transaction)
{ pendingTransactions.add(transaction);
} public Blockchain getBlockchain()
{ return blockchain;
} public List<Transaction>getPendingTransactions()
{ return pendingTransactions;
}} public class PeerToPeerBlockchain { public
static void main(String[] args)
{
// Create a blockchain with difficulty 4
Blockchain blockchain = new Blockchain(4);
// Create two nodes
Node node1 = new Node(blockchain); Node node2
= new Node(blockchain);
// Node 1 creates a transaction
Transaction transaction1 = new Transaction("Alice", "Bob", 10.0);
node1.createTransaction(transaction1);
// Node 2 creates a transaction
Transaction transaction2 = new Transaction("Bob", "Charlie", 5.0);
node2.createTransaction(transaction2); // Node 1 mines the pending
transactions node1.minePendingTransactions(); // Node 2 mines the
pending transactions

Department of IT

Page 36
Record Notes: 2023-24
BCT Lab
2023-24
BCT Lab
Department of IT Page 39
2023-24
BCT Lab

Record Notes:
Department of IT Page 43

You might also like