0% found this document useful (0 votes)
4 views11 pages

Blockchain Technology

The document outlines the creation and implementation of various blockchain components, including Merkle trees, blocks, and ERC20 tokens. It provides source code examples in Java for building these components, detailing their functionality and structure. The document is structured into weekly sections, each focusing on a specific aspect of blockchain technology.

Uploaded by

Jangam Swathi
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)
4 views11 pages

Blockchain Technology

The document outlines the creation and implementation of various blockchain components, including Merkle trees, blocks, and ERC20 tokens. It provides source code examples in Java for building these components, detailing their functionality and structure. The document is structured into weekly sections, each focusing on a specific aspect of blockchain technology.

Uploaded by

Jangam Swathi
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/ 11

Blockchain Technology 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 EMERGING TECHNOLOGIES Page 1


Blockchain Technology Lab 2023-24

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

DEPARTMENT OF EMERGING TECHNOLOGIES Page 2


Blockchain Technology Lab 2023-24

MerkleTree merkleTree = new MerkleTree(transactions);


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

EXPECTED OUTPUT:

OUTPUT:

DEPARTMENT OF EMERGING TECHNOLOGIES Page 3


Blockchain Technology Lab 2023-24

WEEK : 2

AIM : Creation of Block

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");
String input = index + timestamp + previousHash + data + nonce;
byte[] hashBytes = digest.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();

DEPARTMENT OF EMERGING TECHNOLOGIES Page 4


Blockchain Technology Lab 2023-24

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;
}
public String getData() {

DEPARTMENT OF EMERGING TECHNOLOGIES Page 5


Blockchain Technology Lab 2023-24

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:

DEPARTMENT OF EMERGING TECHNOLOGIES Page 6


Blockchain Technology Lab 2023-24

WEEK:3

AIM : Blockchain Implementation Programming code

Blockchain programming fundamentals:

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

DEPARTMENT OF EMERGING TECHNOLOGIES Page 7


Blockchain Technology Lab 2023-24

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

DEPARTMENT OF EMERGING TECHNOLOGIES Page 8


Blockchain Technology Lab 2023-24

EXPECTED OUTPUT:

OUTPUT:

DEPARTMENT OF EMERGING TECHNOLOGIES Page 9


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

DEPARTMENT OF EMERGING TECHNOLOGIES Page 10


Blockchain Technology Lab 2023-24

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:

DEPARTMENT OF EMERGING TECHNOLOGIES Page 11

You might also like