Building a Minimal Blockchain in Haskell

Posted on October 14, 2017 by Kendrick Tan

I’ve been wanting to get my hands dirty with the innards of blockchain lately, combine that with my itch to do a project in Haskell, the bch project (blockchain in haskell) was born. This article will walk you through building a minimal blockchain in Haskell.

So what is a blockchain anyway?

According to google:

In layman terms, a blockchain is just an database. Data is stored in ‘blocks’, each block references their own previous block, forming a chain. The data can be anything ranging from transactions (bitcoin) to DNS records (namecoin).

Building a minimal blockchain in Haskell

Defining our types

Before doing anything, we need to define two data types to facilitate the blockchain. Specifically: Transaction to represent the type of data we want to store, and Block to store a set of said data.

Great, we now have the tools to construct a genesis block:

Blockchain tools

Now that we know how to construct a Block, the next step is to write a couple of functions to make our blockchain more complete. First up is a function that adds a new Transaction to the Block:

We also need a function that hashes the Block, giving the block an ID to be referenced in the future Block:

Lastly, a function which mines the Block, proving that some work has been done on the Block. I opted for a simple proof-of-work algorithm that just checks if the SHA256 of the Block + some nonce starts with a ‘0’. It is just an educational blockchain after all.

This should give you enough tools to play around with your blocks in ghci.

Playable REST API

Of course, playing around with the blockchain ghci isn’t that sexy, so I wrote a a REST API for the blockchain to interface with it.

The hardest bit was probably wrapping up the Blockchain state into a State monad (as I didn’t want to use a database). Luckily for me there was a reference guide on stackoverflow.

Anyways, thats about it, you can view bch’s source code here, and the original bitcoin whitepaper here.