Blockchain explained with javascript, node.js

We all have been aware of the terms blockchain and bitcoin recently. People usually confuse between the two terms and don't really realise that both are not "equal". Let us now figure out what these actually mean and how do they function.

A blockchain, is simply a list of blocks/nodes that are linked using cryptography. The blocks in this chain are interconnected with each other using a cryptographic hash. Hence each block contains a cryptographic hash of the previous block, a timestamp and the transaction data. The blockchain basically acts as a public ledger which records the transactions.

Bitcoin is a cryptocurrency. It is a decentralised digital currency which does not offer/require a central point of administration. Here the transactions can be carried out without the help of an intermediate authority like a bank. The bitcoin is one of many cryptocurrencies which uses the blockchain ledger.


Typical Usage Scenario

Now let us dig deeper into blockchain. First of all consider a normal scenario where you are transferring some amount of money from your bank in UK to one in the US. First, we request a 3rd trusted party(a bank) to transfer some amount to certain bank account in US. The trusted 3rd party then identifies the bank account in US and transfers the requested amount to the particular account. For doing this, the trusted third party(your bank) charges a certain amount of money as a transaction fee. Also, the entire operation may consume a lot of time(may be even days). Here is where the blockchain comes in, where we completely get rid of the third party. The transaction will take place directly between the sender and receiver. The transaction fee now becomes almost negligible and the time gets reduced from days to seconds! yes just seconds!

Time and transaction fees are definitely the two most advantages of a blockchain powered cryptographic system.

Open Ledger

Consider a blockchain which consists of some nodes A,B,C,D. Now let us assume that A wish to perform a transaction with B , B would like to perform a transaction with C and so on. All this transaction appears on a ledger which is public. The importance of an open/public ledger is that everyone on the network can easily know how much money each node in the network has, also each node in the network can decide whether a transaction is valid or not.

Suppose that A had 10$ during the initial condition and it has already transferred a sum of 5$ with B. Once the transaction is complete and the entry has been successfully created in the public ledger, the data is now public and everyone in the network now knows that A only has a remaining balance of  5$. Now if A again initiates a transaction of 10$ to D, all the nodes in the network easily invalidates the transaction as A only has a balance of 5$ and it is practically impossible to transfer an amount of 10$.

As a result every new transaction in a blockchain needs to be validated by all the participating nodes

Distributed Ledger(decentralised)

In the concept of open ledger we have seen that it is centralised, but we need to get rid of its centralised architecture to match the blockchain principles. So we would be having a copy of the ledger on each node. Here the goal is to keep all the ledgers synchronised. So each of the node will be updating the ledger whenever a transaction takes place in the network. 

Miners

Suppose a scenario where a node A wants to perform a transaction with node B. So what basically A does is that it publishes/broadcasts an intended transaction message on the network. As of now this transaction is an invalidated one. So here is where the miners comes in. Miners are special nodes in the network who has access to the ledger. As soon as an intended transaction is created in the network, the miners will compete among themselves to validate the transaction and add it to the ledger. The first miner to do so will get a financial reward, in the case of a bitcoin network they will be awarded a certain amount of bitcoin.

In order to successfully add a transaction to the ledger, the miners will have to two things :
  • Check if the transaction is valid. This step is easy, since the ledger is open and the miners could easily analyse if the node has enough funds to perform the transaction.
  • Find the unique key which can be used to lock the current transaction with the previous transaction. In order to find the key the miner needs to invest huge computational power and time since the key is completely random. This process of investing huge computational power and time to find the unique key which links a new transaction to the chain successfully is called as mining.
As soon as key for the current transaction is mined by a miner, all the other miners now will have to stop mining the key for that transaction since it is already mined and added to the blockchain. Now what all the miners will do is that, all of them will update their ledger with the new transaction so that they could start mining the key for next transaction. There is no point in searching the key for a transaction which is already validated since the financial reward is already claimed by someone(of course another miner!) . All the nodes will have to update their copy of ledger to mine for further transactions.

Now let us see how can we give a programatic explanation to the bitcoin architecture :

First of all create a new javascript file and name it blockchain.js. Now create a class named Block that takes in index, timestamp, data and previousHash through its constructor as shown below


Now we will need to create the calculateHash() shown above. For that we will need SHA256  as a hash function. In order to import this library, first navigate to the blockchain.js file using terminal and type in the following command :

npm install --save crypto-js
Now update the blockchain.js file with the following code

In the above code you can see that calculateHash() is used to create a SHA256 hash using the index, timestamp, data, previousHash of the current block. This creates the key hash for the current block

If you check the addBlock(newBlock) method in Blockchain class, you can see that we have set the previousHash value of new block to hash value of the latest block, which means that each node in the blockchain points to the next node using a unique key hash.

Also inorder to make the blockchain hack proof, we have written a check isChainValid(). This function basically returns that the block chain is not valid when the chain is tampered with. For example, if we update a block with a new amount value and recalculate the hash, the isChainValid() function would return as false.

Now open your terminal and try running

node blockchain.js

You will be able to see your blockchain like shown below

blockchain that we created

Now, let us check if our blockchain is valid by adding the following console.log statement at the bottom of blockchain.js

console.log('Is chain valid? ' + navneetCoin.isChainValid()); 

If we run the code and check the output you can see that it gives the output as true, which means that our blockchain is valid and hence no tampering has been done.

Now let us try tampering with the blockchain by adding the following at the bottom of blockchain.js file

navneetCoin.chain[1].data  = { amount: 100 };
console.log('Is chain valid? ' + navneetCoin.isChainValid()); 
Now if we run the code we can see that it gives the output as false. Now if we try being clever and recalculate the hash, still the output will be false since the node has lost its relationship with the adjacent nodes when we tampered the hash value

2 comments:

  1. I have read many blogs in the net but have never come across such a well written blog. You can also visit viral Nexter website here for more currency news. Good work keep it up

    ReplyDelete
  2. I wish more writers of this sort of substance would take the time you did to investigate and compose so well. I am exceptionally awed with your vision and knowledge. contract for artists

    ReplyDelete