How to build a blockchain in Elixir part-2

coding guy
3 min readSep 26, 2020

So we are building a blockchain in Elixir, in case you have jumped here directly please make sure you have read the part-1.

I did some refactoring before we proceed to write code for the modules to make a bit cleaner. So you can make changes accordingly.

part-1 we created a block now let’s focus on connecting those block into a chain so let’s create a new file lib/blockchain.ex and test/blockchain_test.exs

Let’s write the test for blockchain_test.exs then we will write code to make our test cases pass, in our tests, we will test 2 functionalities first block should be genesis block in a new blockchain , a new block should added into the blockchain when we mine a block

Here in the test above we have taken the genesis block and we are comparing the first block in the blockchain with the genesis block, and the second test we have written so validate the block addition into the blockchain.

let’s take our tests for a spin and both tests should fail.

mix test

and obviously, you’ll see that your tests are failing so let’s start writing code to make both of them pass.

Here in blockchain.ex we have added a function to initialize our blockchain with the genesis block.

Let’s run our tests again and now our first test should pass, which validates our blockchain can be initialized nicely and it adds the genesis block in the blockchain properly.

mix test

Only 1 test should be failing right now, so let’s write code to add a block into our blockchain.

This function adds the block into our blockchain and now we can run our tests and check the happily all tests should be passing. You should get this nice green happy message that our all tests are passed :)

Now let’s check how our blockchain looks when we run it. Start the application with iex -S mix

when you run the application and try with the following command you should able to see our nice blockchain.

Cool! we have built our first basic blockchain, we will stop here & in the next post, we will discuss the validation of the blockchain that how to know our chain & data is valid. Long way to go but we are proceeding towards building our own blockchain step by step.

Third Post in this series post-3

--

--