In this gist, I recreated the basic blockchain called smashingCoin from this wonderful tutorial. Working on the tutorial has been really fun. I got a feel of how a basic building block of the Blockchain really works.
Basically in this implementation, adding or chaining a new block of data to the blockchain ledger is not so easy because we need to solve the Proof-of-Work (PoW) before the newly created block can be added to the chain of blocks.
In this example, we only have one node called smashingCoin storing all the transactions or blocks in it. When a new block is being added, the node should solve the POW first with a certain difficulty level. If and only if the solution to POW is found, then we can add the new block to our chain of blocks.
If we have multiple of nodes, then these nodes will competing with each other to find the correct solution for the POW. Once the correct POW is found, the winning node will broadcast the answer to other nodes. After that, other nodes will start verifying the POW solution given by the winning node.
So what is a Proof of Work or POW? Let's quote it from the original white paper by Satoshi Nakamoto himself:
For our timestamp network, we implement the proof-of-work by incrementing a nonce in the block until a value is found that gives the block's hash the required zero bits. Once the CPU effort has been expended to make it satisfy the proof-of-work, the block cannot be changed without redoing the work. As later blocks are chained after it, the work to change the block would include redoing all the blocks after it.
So if you see in the code, we did exactly like Satoshi mentioned in his paper. Basically we first assign a hash based on our data and timestamp to the block. That new hash is actually only a temporary hash. After that given the difficulty level for the POW, we have to compute the correct hash for this blog which is a hash with zero bits length equal to the difficulty level. If we found the correct hash, then new block is addedd with this new hash calculated from the POW.
In our code, the block hash is calculated based on the transaction data. To guess the correct hash with correct zero bits in it, we increment nonce value which is used to calculate the new hash. The nonce will keep incrementing as long as the correct hash hasn't been found.
Anyway, please see the code and resulting logs for a clear details.