Creation of the first blockchain with Java code


We have all seen how big Bitcoins and other cryptocurrencies have become. While this type of online currency is notoriously volatile, the technology behind it has the potential to upset every industry from within. Because the blockchain has an endless scope, it is seen every day in new ways.

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

Image via Pexels

Understanding the Blockchain

First of all, we all need to be on the same page on what is blockchain and how it works before we try ourselves. The block has header information, and there is also a set or "block" of data. This data is usually a transaction in the world of cryptocurrency, but can be adapted. The chain then starts with a Genesis block and creates new blocks based on the number of transactions or sets of data stored in a block.

Once this threshold is reached, a new block is created. This new one is connected to the previous one, and that is where the term blockchain comes from. Blockchains are also immutable. This is because a SHA-256 hash is involved in every transaction or set of data. The content inside the blocks is also subjected to hashes. This means that there is a unique identifier for each block and that the hash of the linked blocks is archived and hash also in the header.

Because the blockchains are immutable, they are incredibly safe. Playing with one is practically impossible. Trying to falsify data or ownership of transactions would be a challenge. Even more, as the chain grows, it becomes even safer. The technology to destroy this system does not yet exist, and this is good news.

There are three types of blockchain:

  • Public – Public Blockchain is one that is open to anyone to see. Transactions and data are all displayed in the ledger, which means that everyone can participate in the consent process.
  • Federato – Contrary to a public blockchain, federated does not allow everyone to be part of the consensus process. Instead, there is a limited number of nodes with permission to access the ledger.
  • Private – Finally, private blockchains are mainly used in companies. These are reserved only for specific members who can access the blockchain and make transactions.


So, let's talk about transactions inside blockchain. Blockchain technology is distributed. Since they are just append, it is easy to duplicate blockchains between nodes on the network. While nodes usually communicate peer-to-peer (as with Bitcoin), they can also be decentralized with API via HTTP.

A transaction can be anything. It could have an execution code or simply store information. You can see this technology in action with the introduction of new smart contracts . In essence, these smart contracts are IT protocols that facilitate and verify digital contracts. They will probably become more mainstream in sectors such as manufacturing, banking and so on.

Let's take a look at Bitcoin as an example. With Bitcoin, there is a transaction with a certain amount that is transferred from a proprietary account to another account. This transaction has public keys and account IDs to make sure it is secure. These transactions are added to a network and are grouped together. Although they are in a shared network, they are not in a block or inside the chain itself.

How does it work? This is the consensus mechanism . You probably already know one of these mechanisms 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 are algorithms or schemas that collect transactions, construct a block and add these blocks to the chain to validate.

Getting Started

As noted above, a blockchain is a chain or list of blocks. Each block comes with its own digital signature and the digital signature of the blocks before it. Some may also contain data such as transaction information. The digital signature is known as hash. The hash of each block is calculated from the previous one. A change will affect all hashes from then on. By calculating and comparing these, we can see if a blockchain is valid.

Since any change in the data will result in a broken chain, we first create a Block class that will form the basis 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) { = data;

this.previousHash = previousHash;

[19659016] this.timeStamp = new Date (). GetTime ();


The code above starts with a String hash and this is where we will make our digital signature. As you can see, previousHash contains the last block hash and The string data will keep our entire block data. Because we have the basics, we can now generate a digital signature. This means that you will have to choose a cryptographic algorithm. For this example, we will use SHA256 . To achieve this, we will import .


public class StringUtil {
public static String applySha256 (input per string) {
try {
MessageDigest digest = MessageDigest.getInstance ("SHA-256");
byte [] hash = digest.digest (input.getBytes ("UTF-8"));
StringBuffer hexString = new StringBuffer (); // This will contain hashes as hexadecimal
for (int i = 0; i <hash.length; i ++) {
string hex = Integer.toHexString (0xff & hash [i]);
if (hex.length () == 1) hexString.append (& # 39; 0 & # 39;);
hexString.append (hex);
return hexString.toString ();
catch (Exception e) {
[19659016] [19659016] launch new RuntimeExceptions (e);

Create a utility class StringUtil that we will use later. This accepts a string and applies the SHA256 algorithm to return the generated signature. With the new helper, we can calculate the hash in our class Block . To calculate the hash, we must use all the parts of the block with which we do not want to be confused.

public String calculateHash () {
calculatehash = StringUtil. applySha256 (
previousHash +
Long.toString (timeStamp) +
calculated returnhash;

public Block (String data, String previousHash) { = data; [19659016]
this.previousHash = previousHash;
[19659016] this.timeStamp = new Date (). GetTime ();
this.hash = calculateHash (); /


Perfect! Now it's time for some tests. We have to create some blocks and reveal hashes on the screen. In this way, we will know that everything works as it should. Since there is no previous block in the genesis block (first), we will insert "0" as the value of the previous hash.

Public class test {

public static void main (String [] args) {
GenesisBlock block = 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);


The output should have three blocks each with the own digital signature. Your digital signature will have different values ​​depending on your unique timestamp, but you're coming somewhere. Now it's time to archive our blocks in an ArrayList . At the same time, we will go to input gson and display it as Json .

import java.util.ArrayList;
import GsonBuilder;

Public class test {

public static ArrayList blockchain = new ArrayList ();

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); [19659016]
System.out.println (blockchainJson);


Now we are doing much more process. Your output is much closer to what blockchain should look like. Finally, we will check how good our blockchain is. We will create a method isChain Valid () Boolean in our Test class . This will loop all the blocks we've created so far and compare the hash to see if it's equal to the calculated hash and so on.

public boolean static 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 ())) {
[19659016] System.out.println ("Unequal current currents");
return false; [19659016]
if (! PreviousBlock.hash.equals (currentBlock.previousHash)) {
System.out.println ("Previous Hash not Equal");
return false; [19659016]
return true;

With this code, if there are block changes, you will get a false return. If you get a true answer, you did it successfully. You've created blocks of data stored with a unique digital signature that links everything together. You are ready to start the extraction.

Final considerations

Because blockchains are decentralized, there is no authority that imposes rules for accepted transactions. Blockchain involves a level of trust because these transactions are stored on an open network. Although there is a lot of confusion around this technology, as you can see above, it is not as complicated as many show it.

As more and more developers try to tackle their mining efforts, we are seeing more tools to help them together. Software like Loggly and Microsoft Azure are designed to make blockchain easier and more accessible. There are many reasons for developers to explore the world of blockchain. Firstly, it is relatively simple to learn, as you can see above, and it is also expected that it will be a career in demand in the near future.

While blockchain is not a magical database in the clouds, it is a modern solution for complex and technical transactions. There is no doubt that this technology is here to stay. Only time will tell how it will continue to be applied in the future. The opinions expressed here by contributors are their own.

Senior Vice President of Business Intelligence Development, I assisted the Fortune 1000 with experience on the web as a whole, including zero-zero marketing efforts benefiting both consumers and sellers. I am a thinker, a communicator, a salesman, a competitor, a person, and an all-round bee. I am a tireless networker with several years of experience in the real world and two university titles under my belt. He is also a contributor to Esprittoday.

Published September 23, 2018

[ad_2]Source link