Creating a Simple Blockchain Application in Java

  • Last updated Apr 26, 2024

In this tutorial, you will learn how to create a simple blockchain application in Java. The program will use the SHA-256 hashing algorithm to create digital signatures for each block, and we will use a linked list data structure to connect the blocks together in a chain.

Here are the steps to create a simple blockchain application using the Java programming language:

  1. Start by creating a method for converting a transaction data into hash:
  2. import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    
    public class CryptoManager {
    
        public static final String convertToHash(String data) {
    
            try {
                MessageDigest digest = MessageDigest.getInstance("SHA-256");
                byte[] bytes = digest.digest(data.getBytes(StandardCharsets.UTF_8));
    
                StringBuffer hexBuffer = new StringBuffer();
    
                //Converting each character to a hexadecimal string
                for (byte b : bytes) {
                    hexBuffer.append(String.format("%02x", b));
                }
                return hexBuffer.toString();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    
    }
  3. Create a simple POJO class to represent the data of a block:
  4. import java.util.Arrays;
    
    public class Block {
        private String[] transaction;
        private long timestamp;
        private String previousBlockHash;
        private String blockHash;
    
        public Block(String[] transaction, long timestamp, String previousBlockHash) {
            super();
            this.transaction = transaction;
            this.timestamp = timestamp;
            this.previousBlockHash = previousBlockHash;
            this.blockHash = CryptoManager.convertToHash(previousBlockHash + timestamp + transaction);
        }
    
        public String[] getTransaction() {
            return transaction;
        }
    
        public void setTransaction(String[] transaction) {
            this.transaction = transaction;
        }
    
        public long getTimestamp() {
            return timestamp;
        }
    
        public void setTimestamp(long timestamp) {
            this.timestamp = timestamp;
        }
    
        public String getPreviousBlockHash() {
            return previousBlockHash;
        }
    
        public void setPreviousBlockHash(String previousBlockHash) {
            this.previousBlockHash = previousBlockHash;
        }
    
        public String getBlockHash() {
            return blockHash;
        }
    
        public void setBlockHash(String blockHash) {
            this.blockHash = blockHash;
        }
    
        @Override
        public String toString() {
            return "Block [transaction=" + Arrays.toString(transaction) + ", timestamp=" + timestamp
                    + ", previousBlockHash=" + previousBlockHash + ", blockHash=" + blockHash + "]";
        }
    
    }
  5. To test this sample code, create a class with the main method. Then, generate blocks containing transaction information and store them in an ArrayList, as demonstrated in the example below:
  6. import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    public class BlockchainExample {
    
        public static void main(String[] args) {
    
            List<Block> blockChain = new ArrayList<>();
    
            String[] firstTransaction = {"A has $20","A gives B $5"};
            Block firstBlock = new Block(firstTransaction, new Date().getTime(), "0");
            blockChain.add(firstBlock);
            System.out.println("First block = " + firstBlock.toString());
            System.out.println("Blockchain = " + blockChain.toString());
    
            String[] secondTransaction = {"A has $15","A gives C $5"};
            Block secondBlock = new Block(secondTransaction, new Date().getTime(),
                    firstBlock.getPreviousBlockHash());
            blockChain.add(secondBlock);
            System.out.println("Second block = " + secondBlock.toString());
            System.out.println("Blockchain = " + blockChain.toString());
    
    
            String[] thirdTransaction = {"A has $10","A gives D $5"};
            Block thirdBlock = new Block(thirdTransaction, new Date().getTime(),
                    secondBlock.getPreviousBlockHash());
            System.out.println("Third block = " + thirdBlock.toString());
            System.out.println("Blockchain = " + blockChain.toString());
    
            String[] fourthTransaction = {"A has $5","A gives E $2"};
            Block fourthBlock = new Block(fourthTransaction, new Date().getTime(),
                    thirdBlock.getPreviousBlockHash());
            System.out.println("Fourth block = " + fourthBlock.toString());
            System.out.println("Blockchain = " + blockChain.toString());
    
        }
    }