Creating Your First Blockchain with Kotlin. Part 2: BlockChain

In previous part, we examined the basic unit of the blockchain — block. Now on we will build blockchain itself.

BlockChain structure

The heart of the blockchain class will be a list of blocks. Let’s create a blockchain class containing this list:

The class encapsulates the addition of a block to the blockchain using open public immutable list and add method. Basically, in the add method we could check the validity of the block, for example, check that the value of the previousHash field is really equal to the last block in the list and the value of the nonce field was correctly calculated, but for simplicity we omit these checks. However, let’s add a method to the blockchain with the help of which it will be possible to check the entire chain of blocks for validity. The method will compare hash value of each block stored in the previousHash field with the hash value of the previous block in the chain:

As a result, our blockchain class will look like this:

So we wrote the simplest blockchain with Kotlin language. All code fits in less than 50 lines. I hope that after reading these articles you will become a little clearer about the basic principles of the blockchain. Thanks 4 reading ;)

--

--