Block Chain Technology


Understanding Block Chain Concept using Simple Java Program

The Block Chain is a decentralized and distributed digital ledger that is used to record transactions across many computers so that the record cannot be altered retroactively without the alteration of all subsequent blocks and the collusion of the network.

Are you a Block Chain geek ?

Here is the easy way of understanding Block Chain concept using a simple java program for you.

A Java program to understand the simple BLOCKCHAIN network.
( how blocks are added with previous hash & current hash)

---------------- Block.java -------------------------------------------------------------------
package com.dharani.blockchain.simplenetwork;

import com.dharani.blockchain.cryptography.SHA256Hashing;

public class Block {

private int index;
private String timeStamp;
private String previousBlockHash;
private String currentBlockHash;
private String blockData;
public Block(String blockData) {
this.blockData = blockData;
this.currentBlockHash = calculateHash(blockData);
}

public Block(String timeStamp,String blockData) {
this.timeStamp = timeStamp;
this.blockData = blockData;
this.currentBlockHash = calculateHash(blockData);
}
public Block(int index, String timeStamp,String previousBlockHash,String blockData) {
this.index = index;
this.timeStamp = timeStamp;
this.blockData = blockData;
this.previousBlockHash = previousBlockHash;
this.currentBlockHash = calculateHash(blockData);
}

public String calculateHash(String inData) {
return SHA256Hashing.hashTheDataBySHA256(inData);
}

public int getIndex() {
return index;
}

public void setIndex(int index) {
this.index = index;
}

public String getTimeStamp() {
return timeStamp;
}

public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}

public String getPreviousBlockHash() {
return previousBlockHash;
}

public void setPreviousBlockHash(String previousBlockHash) {
this.previousBlockHash = previousBlockHash;
}

public String getCurrentBlockHash() {
return currentBlockHash;
}

public void setCurrentBlockHash(String currentBlockHash) {
this.currentBlockHash = currentBlockHash;
}

public String getBlockData() {
return blockData;
}

public void setBlockData(String blockData) {
this.blockData = blockData;
}

@Override
public String toString() {
return    " {\n index = " + index 
+ ",\n timeStamp = " + timeStamp
+ ",\n previousBlockHash = " + previousBlockHash
+ ",\n currentBlockHash = " + currentBlockHash 
+ ",\n blockData = " + blockData
+ "\n }";
}

}

---------------- BlockChainNetwork.java ------------------------------------------------------
package com.dharani.blockchain.simplenetwork;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;

public class BlockChainNetwork {

public static Set <Block> blockChain;
public BlockChainNetwork() {
blockChain = new LinkedHashSet<Block>();
blockChain.add(createTheGenesisBlock());
}
   
public Block createTheGenesisBlock(){
// The Genesis block is the first block created while creating the blockchain network.
String timestamp =new SimpleDateFormat("MMM dd,yyyy HH:mm:ss.SSS").format(new Date());
int index=0;
String previousHash="null"; // consider previous hash of Genesis block is zero
String data = "This is the Genesis Block";
return new Block(index,timestamp,previousHash,data);
}
public Block getTheLatestBlock(){
return (Block) blockChain.toArray()[blockChain.size()-1]; 
}
public void addNewBlock(Block newBlock){
Block latestBlock = getTheLatestBlock();
newBlock.setIndex(latestBlock.getIndex()+1);
newBlock.setTimeStamp(getCurrentTime());
newBlock.setPreviousBlockHash(latestBlock.getCurrentBlockHash());
newBlock.setCurrentBlockHash(newBlock.calculateHash(newBlock.getBlockData()));
/*
To make the hash more stronger, we can calculate it along with index, time stamp and previous hash. 
i.e., this.calculateHash(timeStamp+previousBlockHash+blockData)
*/
blockChain.add(newBlock);
}

public static String getCurrentTime(){
return new SimpleDateFormat("MMM dd,yyyy HH:mm:ss.SSS").format(new Date());
}


}

--------------- SHA256Hashing.java ------------------------------------------------------
package com.dharani.blockchain.cryptography;

/* SHA 256 -- (Secure Hash Algorithm)
 The SHA (Secure Hash Algorithm) is one of a number of cryptographic hash functions. 
 A cryptographic hash is like a signature for a text or a data file. 
 SHA-256 algorithm generates an almost-unique, fixed size 256-bit (32-byte) hash. 
 Hash is a one way function – it cannot be decrypted back.
 This makes it suitable for password validation, challenge hash authentication, anti-tamper, digital signatures.
 */
import java.security.MessageDigest;
import java.util.Scanner;

import javax.xml.bind.DatatypeConverter;

public class SHA256Hashing {

public static String hashTheDataBySHA256(String inputData) {
// Returns a hexadecimal encoded SHA-256 hash for the input String.
String hashedData = null;
try {
MessageDigest digestedMessage = MessageDigest.getInstance("SHA-256");
byte[] hashedByteArray = digestedMessage.digest(inputData.getBytes("UTF-8"));
return convertBytesToHexaDecimal(hashedByteArray); 
} catch (Exception ex) {
ex.printStackTrace();
}
return hashedData;
}

public static String convertBytesToHexaDecimal(byte[] hash) {
/* 
Use javax.xml.bind.DatatypeConverter class in JDK to convert byte
array to a hexadecimal string. This generates hexadecimal in upper case
*/
return DatatypeConverter.printHexBinary(hash);
}

@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.print("Enter data for which SHA256 is required:");
String inData = sn.nextLine();
String hashedData = hashTheDataBySHA256(inData);
System.out.println("The SHA256 (hexadecimal encoded) hash is:" + hashedData);

}


}
--------------- BlockChainNetworkTest.java ------------------------------------------------------

package com.dharani.blockchain.simplenetwork;


public class BlockChainNetworkTest {
public static void main(String[] args) {
System.out.println("******** Welcome to the demonstration of simple BlockChain Network ******** \n");
BlockChainNetwork blockChainNetwork = new BlockChainNetwork();
blockChainNetwork.addNewBlock(new Block("{Operations : Credit}"));
blockChainNetwork.addNewBlock(new Block("{Operations : Debit}"));
blockChainNetwork.addNewBlock(new Block("{Operations : Transfer}"));

for(Block blocks : BlockChainNetwork.blockChain){
System.out.println(blocks.toString());
}
System.out.println("*****************************************************************************************");
}
}

------------------------------------------------------------------------------------------------------------------------


Get the source code here,