BCT Lab Manual
BCT Lab Manual
Regulations : R20
Program :
B.Tech
Course : Blockchain Technologies
Year & Sem : IV Year & I Sem
LAB MANUAL
Vision:
To produce eminent and ethical Engineers and Managers for society by imparting
quality professional education with emphasis on human values and holistic
excellence.
Mission:
PEO 1: Have a strong foundation in areas like mathematics, science and engineering fundamentals
so as to enable them to solve and analyse engineering problems and prepare them to careers, R&D
and studies of higher level.
PEO 2: Have an ability to analyse and understand the requirements of software, technical
specifications required and provide novel engineering solutions to the problems associated with
hardware and software.
PEO 3: Have exposure to cutting edge technologies thereby making them to achieve excellence in
the areas of their studies.
PEO 4: Work in teams on multi-disciplinary projects with effective communication skills and
leadership qualities.
PEO 5: Have a successful career wherein they strike a balance between ethical values and
commercial values.
PSO1: Application Development: Able to develop the business solutions through latest Software
Techniques and tools for real time Applications.
PSO2: Professional and Leadership: Able to practice the profession with ethical leadership as an
entrepreneur through participation in various events like Ideathon, Hackathon, project expos and
workshops.
PSO3: Computing Paradigms: Ability to identify the evolutionary changes in computing using
advanced Technologies.
Program Outcomes (POs)
Engineering knowledge: Apply the knowledge of mathematics, science,
PO 1
engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO 2
engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems
PO 3 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.
Conduct investigations of complex problems: Use research-based knowledge and
PO 4
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO 5
modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to
PO 6
assess 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
PO 7
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 responsibilities and
PO 8
norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a
PO 9
member or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
PO 10 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.
Project management and finance: Demonstrate knowledge and understanding of the
PO 11
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
PO 12 engage in independent and life-long learning in the broadest context of technological
change
COURSE OBJECTIVES
LIST OF EXPERIMENTS
Week 1: Creating Merkle tree
Week 2: Creation of Block
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.
CO-PO-PSO Mapping
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 3 2 2 2
CO2 3 2 2 3
CO3 3 2 3 1 2 2 2
CO4 2 2 2 2 3
CO5 2 2 3 1 2 2 2
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time), those
who come after 5 minutes 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:
Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
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 note
book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high-end branded systems, which should be
utilized properly.
8. 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 is
kept properly.
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.
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) {
EXPECTED OUTPUT:
Blocks are data structures within the blockchain database, where transaction data in a
cryptocurrency blockchain are permanently recorded. A block records some or all of the most recent
transactions not yet validated by the network. Once the data are validated, the block is closed. Then,
a new block is created for new transactions to be entered into and validated.
Blocks are created when miners or block validators successfully validate the encrypted
information in the blockheader, which prompts the creation of a new block.
SOURCE CODE:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
public class Block
{ private int index;
private long
timestamp;
private String
previousHash; private
String hash;
private String
data; private int
nonce;
public Block(int index, String previousHash, String data)
{ this.index = index;
this.timestamp = new
Date().getTime(); this.previousHash =
previousHash; this.data = data;
this.nonce = 0;
this.hash = calculateHash();
}
public String calculateHash()
{ try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
EXPECTED OUTPUT:
In order to understand Blockchain deeply, the concept of a Digital Signature or a Hash is important.
Digital Signature is basically a function that takes a string as input and returns a fixed-size
alphanumeric string. The output string is known as the Digital Signature or the Hash of the input
message. The important point is that the function via which we obtain the Digital Signature is
“irreversible” in that given an input string, it can compute the Hash. However, given the Hash, it is
virtually impossible to compute the input string. Further, it is also virtually impossible to find 2
values that have the same Hash.
Hash1=hash(input1)
Hash2=hash(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);
An ERC20 token is a standard used for creating and issuing smart contracts on the Ethereum
blockchain. 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);
}
Department of CSE Page 13
public String getName()
{ return name; }
public String getSymbol()
{ return symbol; }
public int getDecimals()
{ return decimals; }
public static void main(String[] args) {
ERC20Token token = new ERC20Token("MyToken", "MTK", 18);
// Set initial balances
token.balances.put("Alice",
1000);
token.balances.put("Bob", 500);
token.balances.put("Charlie", 200);
// Perform some transfers
token.transfer("Alice", "Bob",
200);
token.transfer("Charlie", "Alice", 100);
token.transfer("Bob", "Charlie", 50);
// Print final balances
System.out.println("Alice balance: " + token.balanceOf("Alice"));
System.out.println("Bob balance: " + token.balanceOf("Bob"));
System.out.println("Charlie balance: " +
token.balanceOf("Charlie"));
}}
EXPECTED OUTPUT:
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 peers
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 =
Department of CSE Page 15
calculateHash(combined);
nextLevel.add(hash);
}
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();
Department of CSE Page 19
}
public String calculateHash() {
if (!currentBlock.getPreviousHash().equals(previousBlock.getHash()))
return false;
}
return true;
}
public Block getLastBlock()
{ return chain.get(chain.size() -
1);
}}
public class BlockchainMiningExample
{ public static void main(String[] args) {
// Create a blockchain with difficulty 4
Blockchain blockchain = new Blockchain(4);
// Create some transactions and add them to a block
List<Transaction> transactions = new ArrayList<>();
transactions.add(new Transaction("Alice", "Bob", 10.0));
transactions.add(new Transaction("Charlie", "Alice",
5.0));
Block block1 = new Block(1, System.currentTimeMillis(), blockchain.getLastBlock().getHash(),
transactions);
// Add the block to the
blockchain
blockchain.addBlock(block1);
// Create another block with different transactions
List<Transaction> transactions2 = new ArrayList<>();
transactions2.add(new Transaction("Bob", "Charlie",
3.0)); transactions2.add(new Transaction("Alice", "Bob",
2.0));
Block block2 = new Block(2, System.currentTimeMillis(), blockchain.getLastBlock().getHash(),
transactions2);
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();
}
Department of CSE Page 26
public String calculateHash()
{ try {
EXPECTED OUTPUT:
SOURCE CODE:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
public class CryptoWallet {
private PrivateKey privateKey;
private PublicKey publicKey;
public CryptoWallet() {
generateKeyPair();
}
public void generateKeyPair()
{ try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
SecureRandom random = SecureRandom.getInstanceStrong();
ECGenParameterSpec ecSpec = new
ECGenParameterSpec("spec256k1"); keyGen.initialize(ecSpec, random);
KeyPair keyPair =
keyGen.generateKeyPair(); privateKey =
keyPair.getPrivate();
publicKey = keyPair.getPublic();
Department of CSE Page 34
} catch (Exception e) {