Creating Your First Blockchain with Java Code

We’ve all seen how big Bitcoin and other cryptocurrencies have become. While this type of online currency is notoriously volatile, the technology behind it has the potential to disrupt every industry from the inside out. Because blockchain has an endless application scope, it’s being seen in new ways every day.

In this post, we’ll go into the architecture behind blockchain and how a distributed ledger works. Once you see it for yourself, you’ll see why so many developers are embracing blockchain as a new normal. We’ll also dive into a short tutorial for how to create your own (basic) blockchain sequence and use a proof of work (mining) system.

Image via Pexels

Understanding Blockchain

First, we all need to be on the same page about what blockchain is and how it works before we attempt it ourselves. The block has header information, and there is also a set or a “block” of data. This data is usually a transaction in the world of cryptocurrency, but it can be adapted. The chain then starts with a Genesis block, and new blocks are created depending on just how many transactions or sets of data are stored within a block.

Once that threshold is reached, a new block is created. This new one is linked to the previous one, and that’s where the term blockchain comes from. Blockchains are also immutable. This is because a SHA-256 hash is involved with every transaction or set of data. The content within the blocks is also hashed. This means there’s a unique identifier for every block, and the hash from the linked blocks are stored and hashed in the header as well.

Because blockchains are immutable, they’re incredibly secure. Messing with one is basically impossible. Trying to fake transaction data or property would be a challenge. Even more so, as the chain grows, it gets even more secure. The technology to disrupt this system just doesn’t exist yet, and that’s good news.

There are three types of blockchain:

  • Public – Public blockchain is one that’s open for anyone to see. The transactions and data all appear on the ledger, and that means everyone can participate in the consensus process.
  • Federated – Contrary to a public blockchain, federated does not allow everyone to be a part of the consensus process. Instead, there are a limited number of nodes with permission to access the ledger.
  • Private – Finally, private blockchains are mainly used inside companies. These are restricted to only specific members who can access the blockchain and carry out transactions.

Transactions

Next, let’s talk about transactions within blockchain. Blockchain technology is distributed. Because they’re append-only, it’s easy to duplicate blockchains across nodes in the network. While nodes usually communicate peer-to-peer (like with Bitcoin), they can also be decentralized with APIs via HTTP.

A transaction can be anything. It could have an execution code or just store information. You can see this technology in action with the introduction of new smart contracts. Essentially, these smart contracts are computer protocols which facilitate and verify digital contracts. They’ll likely become more mainstream in industries like manufacturing, banking, and so on.

Let’s look at Bitcoin as an example. With Bitcoin, there is a transaction with a certain amount that is transferred from an owner account into another account. This transaction has public keys and account IDs to make sure it’s secure. These transactions are added to a network, and they’re pooled together. Though they’re in a shared network, they’re not in a block or within the chain itself.

How does this work? It comes down to the Consensus Mechanism. You probably already know of one such mechanism known as Mining, which is used by Bitcoin. There’s an endless list of Consensus Mechanisms and it would take too long to list them all. All you need to know is that they’re algorithms or patterns that gather transactions, build a block and add these blocks to the chain to validate.

Getting Started

As you read above, a blockchain is a chain or list of blocks. Each block comes with its own digital signature as well as the digital signature of the blocks before it. Some might also contain data like transaction information. The digital signature is known as a hash. Each block’s own hash is calculated from the previous one. One change will affect all of the hashes thereafter. By calculating and comparing these, we can see if a blockchain is valid.

Because any changes in data will result in a broken chain, let’s first create a class Block that will form the foundation for the blockchain.

public class Block {

    public String hash;

    Public String previousHash;

    Private String data;

    Private long timeStamp;

    //Block Constructor.

    Public Block(String data,String previousHash ) {

        this.data = data;

        this.previousHash = previousHash;

        this.timeStamp = new Date().getTime();

}

The code above starts with a String hash, and this is where we’ll make our digital signature. As you can see, previousHash will hold the last block’s hash and String data will hold our entire block data. Because we have the foundation, we can now generate a digital signature. This means you’ll have to choose a cryptographic algorithm. For this example, we’ll be using SHA256. To get this, we’ll import the java.security.MessageDigest.

import java.security.MessageDigest;

public class StringUtil {
    public static String applySha256(String input){       
        try {
            MessageDigest digest = MessageDigest.getInstance(“SHA-256”);           
            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 creates a StringUtil utility class which we’ll use later on. This takes a string and applies the SHA256 algorithm to return the generated signature. With the new helper, we can calculate the hash in our Block class. To calculate the hash, we need to use all parts of the block we don’t want to be messed with.

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

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

    }

Perfect! Now it’s time for some testing. We need to create some blocks and reveal the hashes on the screen. That way, we’ll know that everything is actually working as it should. Because there’s no previous block in the genesis (first) block, we’ll enter “0” as the value of the previous hash.

public class Test {

    public static void main(String[] args) {
       
        Block genesisBlock = new Block(“Genesis block”, “0”);
        System.out.println(“Hash for block 1 : ” + genesisBlock.hash);
       
        Block secondBlock = new Block(“Second block”,genesisBlock.hash);
        System.out.println(“Hash for block 2 : ” + secondBlock.hash);
       
        Block thirdBlock = new Block(“Third block”,secondBlock.hash);
        System.out.println(“Hash for block 3 : ” + thirdBlock.hash);
       
    }
}

Your output should have three blocks each with their own digital signature. Your digital signature will have different values depending on your unique timestamp, but you’re getting somewhere. Now, it’s time to store our blocks in an ArrayList. At the same time, we’re going to input gson and view it as Json.

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

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

    public static void main(String[] args) {   
        blockchain.add(new Block(“Genesis block”, “0”));       
        blockchain.add(new Block(“Second    block”,blockchain.get(blockchain.size()-1).hash));
        blockchain.add(new Block(“Third  block”,blockchain.get(blockchain.size()-1).hash));
       
        String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);       
        System.out.println(blockchainJson);
    }

}

Now we’re making much more process. Your output is much closer to what blockchain is expected to look like. Finally, we’re going to check how valid our blockchain is. We’ll create an isChain Valid () Boolean method in our Test class. This will loop through all of the blocks we’ve created so far, and it will compare the hash to see if it’s equal to the calculated hash and so on.

public static Boolean isChainValid() {
    Block currentBlock;
    Block previousBlock;
   
    for(int i=1; i < blockchain.size(); i++) {
        currentBlock = blockchain.get(i);
        previousBlock = blockchain.get(i-1);
        if(!currentBlock.hash.equals(currentBlock.calculateHash()) ){
            System.out.println(“Current Hashes not equal”);           
            return false;
        }
        if(!previousBlock.hash.equals(currentBlock.previousHash) ) {
            System.out.println(“Previous Hashes not equal”);
            return false;
        }
    }
    return true;
}

With this code, if there is any change to the blocks then you’ll get a false return. If you get a true response, you’ve successfully done it. You made blocks of stored data with a unique digital signature that ties the whole thing together. You’re ready to start mining.

Final Thoughts

Because blockchains are decentralized, there’s no one authority to set rules for accepted transactions. Blockchain involves a level of trust since these transactions are stored on an open network. Though there is a lot of confusion around this technology, as you can see above, it’s not as complicated as many make it out to be.

As more developers try to tackle their own mining endeavors, we’re seeing more tools to help them along. Software like Loggly and Microsoft Azure are designed to make blockchains easier and more accessible. There’s a lot of reasons for developers to explore the world of blockchain. First, it’s relatively simple to learn, as you can see above, and it also is expected to be an in-demand career in the near future.  

While blockchain isn’t some magical database in the clouds, it is a modern solution for complex and technical transactions. There’s no doubt that this technology is here to stay. Only time will tell just how it will continue to be applied in the future.

This is a Contributor Post. Opinions expressed here are opinions of the Contributor. Influencive does not endorse or review brands mentioned; does not and cannot investigate relationships with brands, products, and people mentioned and is up to the Contributor to disclose. Contributors, amongst other accounts and articles may be professional fee-based.

Tagged with: