0% found this document useful (0 votes)
7 views

Bct Lab Manual(Java)

The document outlines a series of Java implementations for blockchain technology, including Merkle trees, blocks, and ERC20 tokens. It details the source code for creating a Merkle tree, a block structure with mining capabilities, and a simple blockchain that validates transactions. Each week presents a new aim and corresponding code to build on the blockchain concept.

Uploaded by

dhruvthakar644
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Bct Lab Manual(Java)

The document outlines a series of Java implementations for blockchain technology, including Merkle trees, blocks, and ERC20 tokens. It details the source code for creating a Merkle tree, a block structure with mining capabilities, and a simple blockchain that validates transactions. Each week presents a new aim and corresponding code to build on the blockchain concept.

Uploaded by

dhruvthakar644
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

WEEK: 1

AIM: Creating Merkle tree

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) {

hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
private List<String> buildMerkleTree(List<String> transactions)
{ List<String> merkleTree = new ArrayList<>(transactions);
int levelOffset = 0;
for (int levelSize = transactions.size(); levelSize> 1; levelSize = (levelSize + 1) / 2)
{ for (int left = 0; left <levelSize; left += 2) {
int right = Math.min(left + 1, levelSize - 1);
String leftHash = merkleTree.get(levelOffset + left);
String rightHash = merkleTree.get(levelOffset + right);
String parentHash = calculateHash(leftHash + rightHash);
merkleTree.add(parentHash);
}
levelOffset += levelSize;
}
return merkleTree;
}
public List<String>getMerkleTree() {
return merkleTree;
}
public static void main(String[] args)
{ List<String> transactions = new
ArrayList<>();
transactions.add("Transaction 1");
transactions.add("Transaction 2");
transactions.add("Transaction 3");
transactions.add("Transaction 4");

MerkleTree merkleTree = new


MerkleTree(transactions); List<String> tree =
merkleTree.getMerkleTree();
for (String hash : tree)
{ System.out.println(has
h);
}}}

EXPECTED OUTPUT:

OUTPUT:
Faculty signature
WEEK : 2

AIM : Creation of 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");
String input = index + timestamp + previousHash + data + nonce;
byte[] hashBytes =
digest.digest(input.getBytes()); 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;
}
BCT 2023

byte[] hashBytes =
digest.digest(input.getBytes()); 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;
BCT 2023
}
BCT 2023

public String getHash() {return hash;


}
public String getData() {
return data;
}
public static void main(String args[]){
Block b=new
Block(1,"3a42c503953909637f78dd8c99b3b85ddde362415585afc11901bdefe8349102","hai");
b.calculateHash();
b.mineBlock(1);
b.getIndex();
b.getTimestamp();
b.getPreviousHash()
; b.getHash();
b.getData();
}}

EXPECTED OUTPUT:

OUTPUT:
BCT 2023
BCT 2023
BCT 2023
BCT 2023

WEEK:3

AIM : Block chain Implementation Programming code


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);
}

DEPT OF CSE 15 | P a g e
BCT 2023
public Block getLatestBlock() {
return chain.get(chain.size() -
1);
}
public void addBlock(Block newBlock)
{ newBlock.mineBlock(difficulty);
chain.add(newBlock);
}
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()))
{ System.out.println("Invalid hash for Block " +
currentBlock.getIndex()); return false;
}
if (!previousBlock.getHash().equals(currentBlock.getPreviousHash()))
{ System.out.println("Invalid previous hash for Block " + currentBlock.getIndex());
return false;
}}
return true;
}
public static void main(String[] args)
{ Blockchain blockchain = new Blockchain(4);
Block block1 = new Block(1, blockchain.getLatestBlock().getHash(), "Data 1");
blockchain.addBlock(block1);
Block block2 = new Block(2, blockchain.getLatestBlock().getHash(), "Data 2");
blockchain.addBlock(block2);
Block block3 = new Block(3, blockchain.getLatestBlock().getHash(), "Data 3");
blockchain.addBlock(block3);
System.out.println("Blockchain is valid: " + blockchain.isChainValid());
}
}
BCT 2023

EXPECTED OUTPUT:
BCT 2023
BCT 2023
BCT 2023
BCT 2023

WEEK:4

AIM : CreatingERC20 token


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);
}
BCT 2023
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:

OUTPUT:
BCT 2023
Faculty signature
BCT 2023
BCT 2023
BCT 2023
BCT 2023

WEEK:5

AIM: Java code to implement blockchain in Merkle Trees

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);
}
BCT 2023
level = nextLevel;
}
return level.get(0);
}
private String calculateHash(String input) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(input.getBytes());
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 String getRoot() {
return root;
}}
public class Blockchain1
{ private List<MerkleTree>
blocks; public Blockchain1()
{ this.blocks = new
ArrayList<>();
}
public void addBlock(List<String> transactions)
{ MerkleTree merkleTree = new
MerkleTree(transactions); blocks.add(merkleTree);
}
BCT 2023
BCT 2023
public String getBlockRoot(int blockIndex) {
if (blockIndex>= 0 &&blockIndex<blocks.size())
{ MerkleTree merkleTree = blocks.get(blockIndex);
return merkleTree.getRoot();
}
return null;
}
public static void main(String[] args)
{ Blockchain1 blockchain = new Blockchain1();
List<String> transactions1 = new ArrayList<>();
transactions1.add("Transaction 1");
transactions1.add("Transaction 2");
transactions1.add("Transaction 3");
blockchain.addBlock(transactions1);
List<String> transactions2 = new ArrayList<>();
transactions2.add("Transaction 4");
transactions2.add("Transaction 5");
blockchain.addBlock(transactions2);
String root1 = blockchain.getBlockRoot(0);
System.out.println("Block 1 Root: " + root1);
String root2 = blockchain.getBlockRoot(1);
System.out.println("Block 2 Root: " + root2);
}
}
BCT 2023

EXPECTED OUTPUT:

OUTPUT:
BCT 2023
BCT 2023
BCT 2023
BCT 2023

WEEK:6

AIM: Java Code to implement Mining using block chain

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() {

DEPT OF CSE 33 | P a g e
BCT 2023
try {
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 String getHash() {
return hash;
}
public String getPreviousHash()
{ return previousHash;
}}
class Transaction {
BCT 2023
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;
}
@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;
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);
}
BCT 2023
public boolean isChainValid()
{ for (int i = 1; i <chain.size(); i+
+) {

https://www.studocu.com/in/
document/vignans-foundation-for-
science-technology-and-research/
block-chain-technologies/bct-lab-
manual-in-python/72847533?
origin=organic-success-document-
viewer-cta
BCT 2023
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 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);
BCT 2023
// Add the second block to the
blockchain
blockchain.addBlock(block2);
// Validate the blockchain
BCT 2023
System.out.println("Is blockchain valid? " + blockchain.isChainValid());
}
}
EXPECTED OUTPUT:

OUTPUT:

You might also like