How to build a blockchain in elixir part-3

coding guy
2 min readSep 28, 2020

In this part, we are going to move further from our previous post and build our own blockchain and now we are going to validate our chain if it is valid and whatever we are doing is right & we are going into the right path.

So there are two very basic fundamental properties of blocks in a chain, i.e. next block should have the hash of the previous block and the current hash should be valid and not contains any tempered data. So let’s go ahead and write our tests for validation of our blockchain and then we will write our functions to make them pass.

Here we have added a simple test where we have created a new blockchain then added a new block with some-block-data string as data into the block.

We have to write some more tests so that we can test the negative cases also when we temper the data or hash into the blockchain.

Here we have created a new blockchain and added 3 more blocks and then in one test we temper the data and update the blockchain, in the second test we have tempered the hash of the block and we give to test.

mix test

Now obviously these three newly added tests should fail. So we should write some functions so that we can validate the tests. Update the file lib/blockchain.ex and update with the following changes.

Here we are iterating the chain and comparing the last block hash value with the last_hash value in the current block. The second validation we will do for the current block. We will take the current hash value and then we will generate a hash of that block on the fly and will compare in case the hash of the block is compromised.

Now if you run the tests then it should pass all the tests.

mix testsFinished in 0.1 seconds
10 tests, 0 failures

All of our tests should pass, Well done! we have now created a basic blockchain with the Merkel tree philosophy where the hash of current value is stored in further blocks so that we can tell that particular blockchain is valid or not.

We will stop here and then in the next post we will talk about the longest chain winsproperty of the blockchain and will implement it in our blockchain.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (5)

Write a response