Trusted by millions

Blockchain Development Part 5: Build a blockchain network

Our discussion on crypto is now completed. Here we are going in action to build a blockchain network for our Howcoin system.  In the blockchain network every node or block has address of its previous block for ordering system. 

Let’s implement it in coding.

Create a file named block.rb In this file all the structure of our block is written

Now in this block.rb file make a class Blockchain with above mentioned methods.

Initialize Method
This method is used to create a new block in this network

Add_to_chain Method
This method is used to add the created block in network

Valid Method
Valid method validated that created block is valid or not before adding it to network

To_s Method
This method is to print output as string.

To create a block we will go to initialize the method and create the object of block class. We will define block class later in this tutorial

Inside initialize method create array to contain blocks and also initialize our Block class

Now create a class inside the same file named Block.rb which contains our block logic. As we know a block has a message and previous block address so make it happen.

Inside our block class we also need to add cryptographic puzzles as we learnt in our previous lectures. For this purpose add nonce code in block class

Here we complete our block class now moving back to Blockchain class. In blockchain’s add_to_chain method we need to add newly created block to the chain of blocks. For this purpose add the following code in this method.

We need to check that block is valid to make sure that each block is valid in the chain. Before going further first we now check if our code is working fine. For testing purpose we are going to add 4 blocks in this chain. So add these blocks after Blockchain class

b =“Main Block”)
b.add_to_chain(“Johns Block”)
b.add_to_chain(“Smith Block”)
b.add_to_chain(“Jorge Block”)

 Let’s run the code by running the following command in the terminal window.

ruby block.rb

After running the command you will get output as following.

This output verifies that each block has hash of its previous block. Here we have achieved our target. We had built a simple blockchain. Now we need to check the validation of the block. For this purpose we need to check following things in our  valid method of Blockchain class.

  1. Is newly created block an instance of block class?
  2. All the created blocks are valid?
  3. Are blocks in order?

For this purpose add following code in to is_valid method of Blockchain class

Here we have completed our blockchain code.  We have now covered all the parts of blockchain. Now in the next part we are really building our first digital coin.


Here you can download complete source code of each step