ArrayList will be the class to build our Blocks into a beautiful chain of Blocks.

 

This part will be a fairly sizable section. We created our Block. Then, we added our digital signature. Next, we will use the Java class ArrayList to complete the process of making a blockchain. Let's get started!


public static ArrayList<Block> blockchain = new ArrayList<Block>(); 

This uses the Java class ArrayList so we will need an import statement.


import java.util.ArrayList;

We will need to modify our block and add the digital signature functionality that we built in Part 2. We will take our Block code from Part 1 and modify it. Here is the new Block code:


import java.util.Date;
import java.security.MessageDigest;

public class Block
{
  // The variables we need to create a block.
  private String data;
  private String hash;
  private String previousHash; 
  private long timeStamp;

  // The constructor of a block. We need to give it data and a previous block's hash.
  public Block(String data, String previousHash)
  {
    // Initialize all the variables so the block is built correctly.  
      
    this.data = data;
    this.previousHash = previousHash;
    this.timeStamp = new Date().getTime();
    
    //Making sure we do this after we set the other values.
    this.hash = calculateHash();
  }
  
  // Getter method to return the value of the block's private hash.
  public String getHash()
  {
      return this.hash;
  }
  
  // This is a method to calculate the hash code for this block.
  // Note we add everything that we want to protect from tampering into the hash
  // in this situation we added data, timeStamp, and previousHash.
  public String calculateHash()
  {
      String calculatedhash = Block.applySha256(
        previousHash +
        Long.toString(timeStamp) +
        data);

    return calculatedhash;
  }
  
  // This is the SHA-256 algorithm. 
  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"));
    
            // This will contain hash as hexidecimal
            StringBuffer hexString = new StringBuffer(); 
    
            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);
        }
  }

}

Here is the new class we will create that will utilize the ArrayList that we talked about and chain the blocks together.


import java.util.ArrayList;

public class ExampleChain
{
    // This uses the Java ArrayList class to actually create a chain of blocks.
    public static ArrayList<Block> blockchain = new ArrayList<Block>();   
    
    
     public static void main(String[] args)
     {
	//add our blocks to the blockchain ArrayList:
	// Note we are making 3 blocks and we are passing the previous block's hash
	// into the next block.
	
	// Creating a block with a previousHash of "0" is what we call a genesis block.

	blockchain.add(new Block("Hi im the first block", "0"));		

	blockchain.add(new Block("Yo im the second block",blockchain.get(blockchain.size()-1).getHash())); 

	blockchain.add(new Block("Hey im the third block",blockchain.get(blockchain.size()-1).getHash()));

	System.out.println("Hash for block 1 : " + blockchain.get(0).getHash());
	System.out.println("Hash for block 2 : " + blockchain.get(1).getHash());
	System.out.println("Hash for block 3 : " + blockchain.get(2).getHash());
    		
    }
}

Ok, this is a sizable amount of code. To keep the lesson within reason, I am going to break down all this code and talk about it in Part 4. Both the Block.class and the ExampleChain.class are fully functional code and if you build the classes using this code. It will produce three blocks - chained together and you should see their hash codes when you run the Main Method after you compile the code.

Is your head spinning? Maybe not. Well, remember to comment, connect , and like if you enjoyed this Part of the tutorial. Don't panic. We can discuss all this code in the next part of the tutorial. Until then, have a great day!