CCS339 cryptocurrency and block chain technologies lab v1.docx
CCS339 cryptocurrency and block chain technologies lab v1.docx
I INSTITUTE OF TECHNOLOGY
THOVALAI – 629302
CCS339
NAME :
REGISTER NO :
YEAR/SEM :
DEPARTMENT :
C.S.I INSTITUTE OF TECHNOLOGY
THOVALAI - 629302
LAB RECORD
University Register No
Certified that tins Record has been submitted for the Practical Examination held on .............................
Creation of Block
2
3 Blockchain implementation
Creating Merkle tree
4
Date :
1. Download the installer using the download button at the top of the page, or from the release notes.
2. Double-click Docker Desktop Installer.exe to run the installer. By default, Docker Desktop is installed
at C:\Program Files\Docker\Docker.
3. When prompted, ensure the Use WSL 2 instead of Hyper-V option on the Configuration page is
selected or not depending on your choice of backend. If your system only supports one of the two
4. Follow the instructions on the installation wizard to authorize the installer and proceed with the
install.
5. When the installation is successful, select Close to complete the installation process.
If your admin account is different to your user account, you must add the user to
4. Sign out and sign back in for the changes to take effect.
1. Search for Docker, and select Docker Desktop in the search results.
2. The Docker menu ( ) displays the Docker Subscription Service Agreement.
• Docker Desktop is free for small businesses (fewer than 250 employees AND less than
$10 million in annual revenue), personal use, education, and non-commercial open source
projects.
• The Docker Pro, Team, and Business subscriptions include commercial use of Docker Desktop.
3. Select Accept to continue. Docker Desktop starts after you accept the terms
RESULT :
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();
}
hexString.append(hex);
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
OUTPUT:
Result:
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();
}
if (!previousBlock.getHash().equals(currentBlock.getPreviousHash())) {
System.out.println("Invalid previous hash for Block " + currentBlock.getIndex()); return
false;
}}
return true;
}
}
OUTPUT:
Result:
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);
}
hexString.append(hex);
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
levelOffset += levelSize;
}
return merkleTree;
}
OUTPUT:
Result:
Thus the above Merkle tree Merkle is created and the Bit coin’s transactions is performed successfully.
Exp. No. 5 CreatingERC20 token
Date :
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;
}
OUTPUT:
Result:
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();
}
return level.get(0);
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}}
return null;
}
OUTPUT:
Result:
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();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
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;
}
@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();
}
if (!currentBlock.getPreviousHash().equals(previousBlock.getHash())) return
false;
}
return true;
}
OUTPUT:
Result:
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();
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
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;
}
class Blockchain {
private List<Block> chain;
private int difficulty;
public Blockchain(int difficulty) {
this.chain = new ArrayList<>();
this.difficulty = difficulty;
createGenesisBlock();
}
return true;
}
public List<Block>getChain() {
return chain;
}
class Node {
private Blockchain blockchain;
private List<Transaction>pendingTransactions;
public Node(Blockchain blockchain) { this.blockchain
= blockchain;
this.pendingTransactions = new ArrayList<>();
}
public List<Transaction>getPendingTransactions() {
return pendingTransactions;
}}
OUTPUT:
Result:
SOURCE CODE:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
public class CryptoWallet {
private PrivateKey privateKey;
private PublicKey publicKey;
public CryptoWallet() {
generateKeyPair();
}
OUTPUT:
Result:
To create and deploy a blockchain network using Hyperledger Fabric SOK (Stack Overflow
Knowledge) for Java.
Algorithms:
1. Set up Hyperledger Fabric environment: Install the necessary prerequisites such as Docker
and Docker Compose, download Hyperledger Fabric binaries, and set up your network by
generating cryptographic materials, creating channels, etc.
2. Develop chaincode: Write your chaincode logic in Java. Chaincode is the smart contract
that runs on the blockchain network and defines the rules and transactions.
3. Set up and initialize the channel: Use the Fabric Java SDK to set up and initialize the
channel. This involves creating channel artifacts and joining peers to the channel.
4. Install and instantiate chaincode: Install the Java chaincode onto peers and instantiate it
on the channel. This allows the chaincode to be executed and invoked by peers.
5. Perform invoke and query: Use the Fabric Java SDK to invoke chaincode functions to
perform transactions and query the ledger for information.
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
import java.nio.file.Path;
import java.nio.file.Paths;
// Submit a transaction
byte[] result = contract.submitTransaction("invoke", "arg1", "arg2");
// Evaluate a transaction
result = contract.evaluateTransaction("query", "arg1");
// Process result
System.out.println(new String(result));
}
}
}
Output:
Transaction submitted successfully.
Result: {"status": "success"}
Query result: {"key": "value"}
Result:
Thus the above blockchain network using Hyperledger Fabric SOK is created and deploed
Successfully.