Creating Your First Blockchain with Kotlin. Part 1: Block
A blockchain is a chain of related blocks. Thanks cap)) In this article we will write our first block with Kotlin.
What is the structure of the block?
In the simplest case, a block consists of a list of transactions (in our example, we will use the string value data to simplify), a hash of the previous block in the chain, and a certain nonce value which the miner should receive in such a way as to prove that the work spent on block mining has been completed. Read more about nonce and proof-of-work here and here.
Let’s write a class for a block:
Also, the block should be able to get its own hash. Let’s add this functionality to our block:
Like BitCoin, we use cryptographic algorithm SHA256 for hash calculating. About cryptographic hash function you can read here.
And that’s almost all. There is one moment left. Just using a constructor is unlikely to create a valid block. Let’s add a method that will provide the ability to mine a block, in other words, select a valid nonce value for a certain difficulty value:
About mining and difficulty you can read here and here.
In the end, we should get this class:
Congratulations! You wrote a block class for a simple blockchain with Kotlin. In the next article, we will build a blockchain based on this block.