Design and Create the Blocks for the Blockchain

First, we are going to design the Blocks for the Blockchain. Basically, a block contains the following information :

Index

Timestamp to store the creation date of the Block

Hash of the previous Block

Data stored in the Block. For the Bitcoin and the other crypto currencies, data are transactions

Hash of the current Block to ensure integrity of its content

This gives us the following code for the properties of the Block :

SHA-256 Cryptographic Hash Function

The hash of the blocks of our Blockchain will be calculated by relying on the cryptographic hashing algorithm SHA-256 which you will find all the details on wikipedia : https://en.wikipedia.org/wiki/SHA-2 . Luckily, the Java language SDK offers a standard implementation of this algorithm. It will not be necessary to code it ourselves. The cryptography algorithms offered by Java are recoverable via the MessageDigest class, which allows you to retrieve the instance of an algorithm by entering the name of the getInstance() method.

It then remains to enter in parameter of the digest() method a textual representation of the blocks’s content to hash for getting the result of its hashing via the SHA-256 algorithm in the form of an array of bytes. To finish, we transform this array of bytes into a string of characters and we return this last function output :

Mining the Blocks

Our block is practically functional. It only remains to add a method to carry out its mining. The mining process will allow us to solve the enigma posed by the famous “Proof of Work”. Given some difficulty passed as input, we will have to find a hash for the block starting with a given number of zeros :

The attentive reader will have noticed the presence of the static method zeros of the class Utils in this code. This method returns a string containing the number of zeros passed as an input parameter. As for the nonce property, it will contain the number of tests performed before solving the proof of work during the block mining.

Complete code for the Block class

To end this first part, you will find the complete code for the Block class just below :