Friday, 22 December 2017

Java Blockchain tutorial

This blog provides a working Blockchain example in Java.

Before we jump into the actual code, lets first understand the basics of Blockchain.

Introduction :


Lately, you might have herd a lot of buzz around different crypto-currencies emerging in market : Bitcoin, Etherium, Ripple, Dash ... and the list goes on. The market share of Bitcoin has gone exponentially up from $ 4000 to $ 17000 in just three months. Other currencies are also following the same trend.



The reason that these currencies are getting so much traction is the common architecture design they share : Blockchain

Bitcoin is not Blockchain and Blockchain is not Bitcoin. Bitcoin is just one implementation of crypto-currency use case that can be build on Blockchain.




As seen in the above image Bitcoin is just a implementation of Blockchain. There are many industries and subsequent use case where blockchain can be implemented and is getting implemented.


Blockchain data structure was conceptualized by a person or group of people called Satoshi Nakamoto in 2008 and its first implementation was Bitcoin in 2009. For more details about Bitcoin you can refer other blocks.

What is Blockchain?


Conceptually, Blockchain is a simple Singly-linked-list, where nodes are linked together to form a chain. Node here is called Block, hence the name BlockChain. A Singley-Linked-List looks like this:
Here the Node, holds data and a pointer to the next node. For more information on Singly LInked List and it working follow this blog : Singly Linked List

Now lets have a look at a BlockChain











Lets understand the key differences between a Singly Linked List and Block Chain:

Each node in a Block Chain as three essential elements, Data, Current Harsh and Previous Hash.

  1. Current Hash is a String element which is calculated (Hashed) from Data and Previous Hash
  2. Previous Hash holds the Current Hash of the previous block (node) 
  3. Data, can be any object, which represents the node

 As you can see theirs is no linking between the nodes using a pointer. Instead the Hash of the previous node is copied to the Previous Hash element of the next node.

Hashing is a mechanism to convert a data into a alphanumeric string.

For e,g : the hash of string abc will be 435LKJH3HJ4KHK34534LK5HJKJH and for def it can be HKJHKJH342H2K34HKKHK

Unlike encryption hashing can not be reversed. If a person has a hashed data, there is no way to find out the actual data that was hashed.

One more interesting thing with BlockChain is that the Current Hash is done on Data + the Previous Hash. So if Data of one block gets changed the Current Hash of all the subsequent block changes. This ensured the integrity of the BlockChain and reduces chances of tampering with old blocks.

This was not possible with Single Linked List. Any Node data could have been changed without other nodes getting affected. You can even delete the node or add a new Node in between the List in Single Line.

This can not happen with BlockChain, and if someone does that the complete Blockchain is notified. This is a important design principle of BlockChain. Any correction to be made in the blocks can be done in the next block, but the previous block can not be amended.

Blockchain provides four important features:

1. Decentralization (No individual administrator)
2. Integrity of data (No tampering)
3. Smart Contracts

We will see how Integrity is achieved in this blog. The rest of the features are discussed in furthers blogs.

Blockchain currently is in a phase where people know how it works but do not know how to use it., where to use it. Which use case is fit for Blockchain.

Even games are getting created just to prove that the maker understood how Blockchain works. Take a loot at CryptoKitties. Where participants can create unique, adorable, one-of-a-kind cats. They can send and receive cats. Of-course virtual cats.


Blockchain can be used in a public peer to peer network where participants are not aware about each other or in a private business where participants know each other and trust each other.

Creating Blockchain in Java


The block



public class Block {
 
 public String currentHash;
 public String previousHash; 
 private String data; 
 private long timeStamp;
}

This is a simple Block class, with 4 parameters as discussed above. Timestamp is to keep track of the time the block was created. The block needs to be created with data and previous block's hash.

here goes the Constructor

public Block(String data,String previousHash ) {
 this.data = data;
 this.previousHash = previousHash;
 this.timeStamp = new Date().getTime();
  
}

Hashing

To calculate the CurrentHash we will create a Utility class called HashUtil

import java.security.MessageDigest;

public class HashUtil {
 
 //Applies Sha256 to a string and returns the result. 
 public static String applySha256(String input){
  
  try {
   MessageDigest digest = MessageDigest.getInstance("SHA-256");
         
   //Applies sha256 to our input, 
   byte[] hash = digest.digest(input.getBytes("UTF-8"));
         
   StringBuffer hexString = new StringBuffer(); // This will contain hash as hexidecimal
   for (int i = 0; i < hash.length; i++) {
    String hex = Integer.toHexString(0xff & hash[i]);
    if(hex.length() == 1) hexString.append('0');
    hexString.append(hex);
   }
   return hexString.toString();
  }
  catch(Exception e) {
   throw new RuntimeException(e);
  }
 }
 
}

This class uses MessageDigest from Java library to create hash. The algorithm used is SHA-256. Don't worry about this too much.

We will call this method from the constructor of Block to generate the Current Hash.

 
public Block(String data,String previousHash ) {
 this.data = data;
 this.previousHash = previousHash;
 this.timeStamp = new Date().getTime();
 this.currentHash = HashUtil.applySha256(previousHash +Long.toString(timeStamp) + data );
}

As mentioned before we are using the Data + the Previous hash to generate the Current Hash

lets create a private method in Block to calculate the Hash and use it.

public String calculateHash() {
 String calculatedhash = HashUtil.applySha256( 
   previousHash +
   Long.toString(timeStamp) +
   data 
   );
 return calculatedhash;
}

Test you Blockchain


Lets create a ArrayList and add Blocks to it.
For this we will create a TestBlockChain class.

import java.util.ArrayList;
import java.util.List;

public class TestBlockChain {

 public static void main(String[] args) {
  List<Block> blockChain = new ArrayList<Block>();
  
  Block block1 = new Block("First Block", "0");
  blockChain.add(block1);
  Block block2 = new Block("Second Block", block1.currentHash);
  blockChain.add(block2);
  Block block3 = new Block("Third Block", block2.currentHash);
  blockChain.add(block3);
  
  
  for(Block b : blockChain) {
   System.out.println(b);
  }
  
 }
}
Here we are simply adding 3 blocks in a ArrayList and printing them. Note that the hash of the previous block is passed in the constructor of the next block. For the first block we pass 0 as the previous hash since their is not previous block to the first one.

{ 
  currentHash=ca228390fec7b8e03ee8fbf0996b33c91a2c9dc9c03395327fa33503fa06ebfd
  previousHash=0
  data=First Block
  timeStamp=1513857247881
}
{ 
  currentHash=dd8d83fbd96419dca0e2696553daac1756fe0d563571434e8ea547786a26cc1f
  previousHash=ca228390fec7b8e03ee8fbf0996b33c91a2c9dc9c03395327fa33503fa06ebfd
  data=Second Block
  timeStamp=1513857247896
}
{ 
  currentHash=1d4e89d2d179fcfa94fe4235d75976f70cb99dfafb5105c93973ed2bdd1393a6
  previousHash=dd8d83fbd96419dca0e2696553daac1756fe0d563571434e8ea547786a26cc1f
  data=Third Block
  timeStamp=1513857247896
}
In the output, it can be seen that the previousHash of the second block is the currentHash of the first block.

Validate the Block


One crucial step is still missing here. We need to validate the blockchain every time a new block is added.

Lets do it.

Now what if someone try to add a new block in the middle or tries to edit the data of a existing block. We will need to validate the blockchain to catch the thief. Lets do that :

private static boolean isBlockChainValid(List blockChain) {
 if (blockChain.size() > 1) {
  for (int i = 1; i <= blockChain.size()-1; i++) {
   Block currentBlock = blockChain.get(i-1);
   Block nextBlock = blockChain.get(i);
   if (!(nextBlock.previousHash.equals(currentBlock.currentHash))) {
    return false;
  }
   }
 }
 return true;
}

This method iterates through the blockchain and checks if the current and previous blocks hash match.

The complete Test Class looks like this now

import java.util.ArrayList;
import java.util.List;

public class TestBlockChain {

 static List blockChain = new ArrayList();

 public static void main(String[] args) {

  addBlock(new Block("First Block", "0"));
  addBlock(new Block("Second Block", blockChain.get(blockChain.size() - 1).currentHash));
  addBlock(new Block("Third Block", blockChain.get(blockChain.size() - 1).currentHash));

  for (Block b : blockChain) {
   System.out.println(b);
  }
  
 }

 private static boolean isBlockChainValid(List blockChain) {
  if (blockChain.size() > 1) {
   for (int i = 1; i <= blockChain.size()-1; i++) {
    Block currentBlock = blockChain.get(i-1);
    Block nextBlock = blockChain.get(i);
    if (!(nextBlock.previousHash.equals(currentBlock.currentHash))) {
     return false;
    }
   }
  }
  return true;
 }

 public static void addBlock(Block b) {
  blockChain.add(b);
  System.out.println(isBlockChainValid(blockChain));
 }

}
Here after every block is added we validated the complete blockchain.

Test tampering

Now lets try to add a block in between a existing block chain. This can be done by adding below code at the end of the main method

addBlock(new Block("Thief Block",blockChain.get(blockChain.size() - 2).currentHash));

This code adds a block in the middle of the block. The isBlockChainValid will give a false output in this case.

That is it. We have completed our own Block Chain.

There is more to block chain though  : Minning, Transactions etc..

We will get to it in the next blog : Java Blockchain Mining

Please share your comments below.

Also don't forget to like and share this page.

No comments:

Post a Comment

Share the post