Simple Java BlockChain Example

Github source code is : example code
Java version : 1.7
Project type: Maven
Project classes are  Block.java , StringUtil.java and MyChain3.java

Block.java is entity class of project.
StringUtils.java  is hashing class. this convert string to a hash code. This use SHA-256
MyChain3.java is implementation of blockchain. This Creates 4 block and print them as json to console. After all comleted it prints below output.




1. Create a maven project with quick-start archetype.

2. Create Block.java

package block.chain.simple.example;

import java.util.Date;
/**
 * In reality each miner will start iterating from a random point.
 * </p>Some miners may even try random numbers for nonce.
 * </p>Also it’s worth noting that at the harder difficulties solutions may require more than integer.MAX_VALUE,
 * </p>miners can then try changing the timestamp.
 *
 */
public class Block {

    private String hash;
    private String previousHash;
    private String data; //our data will be a simple message.
    private long timeStamp; //as number of milliseconds since 1/1/1970.
    private int nonce = 0;
   
    //Block Constructor.
    public Block(String data,String previousHash ) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = new Date().getTime();
        this.hash = calculateHash(); //Making sure we do this after we set the other values.
    }
   
    //Calculate new hash based on blocks contents
        public String calculateHash() {
            String calculatedhash = StringUtil.applySha256(
                    previousHash +
                    Long.toString(timeStamp) +
                    Integer.toString(nonce) +
                    data
                    );
            return calculatedhash;
    }
   
    public void mineBlock(int difficulty) {
        String target = new String(new char[difficulty]).replace('\0', '0'); //Create a string with difficulty * "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;
    }
}


3. Create StringUtils.java class.

package block.chain.simple.example;

import java.security.MessageDigest;

/***
 * Don’t worry too much if you don’t understand the contents of this helper method,
 * </p>All you need to know is that it takes a string and applies SHA256 algorithm to it, and returns the generated signature as a string.
 *
 */
public class StringUtil {
    //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);
        }
    }   
}



4. Create MyChain.java class.

package block.chain.simple.example;

import java.util.ArrayList;
import com.google.gson.GsonBuilder;

public class MyChain3 {
   
    public static int difficulty = 5;
    public static ArrayList<Block> blockchain = new ArrayList<Block>();

    public static void main(String[] args) {   
        //add our blocks to the blockchain ArrayList:
       
        String previousHash = "0";
        for (int i = 0; i < 4; i++) {
            Block block = new Block("Hi, Im " + i + ". block", previousHash);
            blockchain.add(block);

            System.out.println("Trying to Mine block " + i + " ... ");
            block.mineBlock(difficulty);
           
            previousHash = block.getHash();
        }
       
        System.out.println("\nBlockchain is Valid: " + isChainValid());
       
        String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
        System.out.println("\nThe block chain: ");
        System.out.println(blockchainJson);
    }
   
    public static Boolean isChainValid() {
        Block currentBlock;
        Block previousBlock;
        String hashTarget = new String(new char[difficulty]).replace('\0', '0');
       
        //loop through blockchain to check hashes:
        for(int i=1; i < blockchain.size(); i++) {
            currentBlock = blockchain.get(i);
            previousBlock = blockchain.get(i-1);
            //compare registered hash and calculated hash:
            if(!currentBlock.getHash().equals(currentBlock.calculateHash()) ){
                System.out.println("Current Hashes not equal");           
                return false;
            }
            //compare previous hash and registered previous hash
            if(!previousBlock.getHash().equals(currentBlock.getPreviousHash()) ) {
                System.out.println("Previous Hashes not equal");
                return false;
            }
            //check if hash is solved
            if(!currentBlock.getHash().substring( 0, difficulty).equals(hashTarget)) {
                System.out.println("This block hasn't been mined");
                return false;
            }
        }
        return true;
    }
} 


5. Run MyChain3.java it print 4 block.

6.  I explain what a block contains.

Hash is created from data, timeStamp(we use now for this), nonce and previous hash. Hash value provides blockchain's accurancy. Because if  one of above four value is change, hash chages.
Data is master value of chain, it keeps user's money value but at our example it only show block order.
Timestamps is long value of date, we use for  now date.
Nonce is used mining operation. it show how many hash conversion times real hash gotten.
Previoushash show previoush block's hash value.

7. All right, what is mining, it is done how to do. It is an operation of finding dificulty times zero of hash value by chaning nonce value.  In our example difficult is 5. If difficult is increased, nonce will increase and mining time extends. You can change difficult in MyChain.java.

8. All in all, blockchain is distributed database. It is verified by most of participant calculation. Blockchain  gives prize to participants when calculate itselft. Participants also named miners.