Creating a simple blockchain in Kotlin

blockchain in Kotlin

Blockchain is probably the most trending technology in recent months. It seems like it is on everyone’s tongue. And even if the masses tightly associate this technology with Bitcoin (and cryptocurrencies), it’s not really true that its the blockchain’s only adoption. For example, the Educhain blockchain credentials and academic passport solution will be launched with selected institutions in Dubai. I think we have this once in a lifetime opportunity to watch the whole world change because of more wide blockchain use.

Let’s build a simple blockchain in Kotlin

At first blockchain technology seems like a really complicated idea to embrace. And it is, if you dive deep into it. The basic idea isn’t that complex. But let’s start building KotCoin (that’s how I named the blockchain we’re going to build) and I’ll explain everything on the fly.

Step 1: Defining how blocks should look like

class Block(val index: Int,
            val previousHash: String,
            val data: Any) {
    val hash = calculateHash()
    val timestamp: Long = Date().time

    fun calculateHash(): String {
        val input = (index.toString() + previousHash + timestamp + data).toByteArray()
        return DigestUtils.sha256Hex(input)
    }
}

Each block in the chain should obligatory consist of timestamp, data that’s stored, hash of previous block and its own hash. A hash is basically a digital signature. Optionally we can add index. Note that every property is not nullable so each block will always know about the hash of the previous one. That’s what chains the blocks.
Hash is generated basing on every property value in the object. In this case we calculate hash using SHA-256. The SHA-256 crypthographic function is used in the implementation of Bitcoin. In this example I’ve used DigestUtils from Apache Commons Codec in order to avoid hodgepodge with converting SHA-256 ByteArray to hex.

Step 2: We have a block, but where’s the actual chain?

Next, we have to create another object that will represent the whole KotCoin’s blockchain. Rember that the object keyword in Kotlin always creates a singleton.

object Blockchain {
    val chain = mutableListOf<Block>()
    val latestBlock: Block
        get() = chain.last()

    fun addNewBlock(block: Block) {
        if (isNewBlockValid(block)) chain.add(block)
    }
}

Great! We have a basic functionality of blockchain implemented. But how to start it? There’s no first item in the chain?
Well, we need to hard code so-called genesis block which is just our usual block. Let’s modify the code:

object Blockchain {
    val chain = mutableListOf<Block>()
    val latestBlock: Block
        get() = chain.last()

    init {
        chain.add(Block(0, "0", "Genesis block"))
    }

    fun addNewBlock(block: Block) {
        if (isNewBlockValid(block)) chain.add(block)
    }
}

As you can see, the chain property is being initialized with the default element. The genesis block is of index 0, the obligatory previous hash is equal 0, and the data it contains can be anything.

We have built our first blockchain in Kotlin!

The basic functionality has been implemented. To make sure everything’s correctly connected and works, we can add few blocks and see what happens.

fun main(args: Array<String>) {
    val kotcoin = Blockchain

    for (i in 1..15) {
        kotcoin.addNewBlock("Block $i")
    }
    for (block in kotcoin.chain) {
        println("""Data: ${block.data}
            |Previous hash: ${block.previousHash}
            |Current hash: ${block.hash}
        |""".trimMargin())
    }
}

Let’s run the main method. It should print the results of loop.

Kotlin blockchain results

There you are! It seems like everything is in its right place and the blocks are linked with the previous ones. In the next episode of building a simple blockchain in Kotlin we’ll dive a little deeper and implement a proof of work and maybe a small transaction system for Kotcoin. Remember you can find the complete source code on GitHub: KotCoin source code

If you liked this post feel free to share it or follow me on Twitter: @a_mrszlk

6 thoughts on “Creating a simple blockchain in Kotlin

  1. Nicolas Frankel Reply

    Nice post. I have several questions:

    1. Why not pass the Block instead of the block’s hash to the Block constructor?
    2. Why not make the last block a property (instead of a function call)?
    3. Why create a createGenesisBlock() function instead of initializing the genesis block in an init block?

    • Adrian M. Post authorReply

      Hey Nicolas. Let me start from the end:
      ad2/3: I’m coming from pure Java background so in my Kotlin code there still may be some signs of Java 🙂 I’m going to update the post later today. Thanks for pointing those out.
      ad1: I guess you’re asking about previous block/previous hash. Everything a block needs to (and should) know about the previous one is its hash, that’s why only this property is passed.

  2. Barco Reply

    Cool idea! Your Block constructor call in the init of your Blockchain Object has the incorrect number of parameters.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.