This will be a comparitively longer tutorial. We will create a data structure to store block chain, write functions to mine new blocks, check validity of the block chain, calculate hash etc. Proof of work needs a bit of explanation so I will dedicate the next tutorial to proof of work.
A block chain is a chain of block where each block is linked to the previous one and contains some data. Each block contains the hash of previous block and its own data attributes. This way hashes are propagated in a block chain.
Firstly, import the required packges.
Now add the following code to index.js for Block class.
Create an array to save the block chain. An array is used because data order is maintained in an array.
The first block in a block chain is called Genesis Block. It has constant values for index,timeStamp, previousHash, data and nonce. Create a function to get genesis block and a function to calculate hash. Then call the getGenesisBlock function while creating the block chain.
Now, we need a function to add new blocks to the block chain. This function will accept some data and add a block to the block chain.
verifyBlockChain verifies whether the block chain is valid or not. It checks that the hash values are consistent. In next tutorial, we will check the proof of work condition also in this function.
Nodes broadcast there blockchain to other nodes if a new block is added to the block chain or on request of other node. In this case, the other node will compare its own block chain with the received block chain. The longer block chain is accepted and thus prevails. Therefore a function compareBlockChains is created which will compare two block chains.
Finally index.js looks something like this.
Now test the code which we just wrote by writing following lines of code at the end of the file.
Again run the file using either of the following commands: