Power of Eloquence

Writing blockhain in Javascript/NodeJS - Part 1

| Comments

Earlier in 2018, I posted about several major tech trends that developers will need to get their eyes and ears checked for, and one of them is about blockchain.

I went ahead to follow this blog post to quickly learn and build blockchain in record speed using Python!

After playing around their sample code, I decided to give myself a crack of this - to write blockchain implementation in NodeJS.

Before I continue writing the rest of the post, I just want to reaffirm my point that I don’t know a lot about them upfront and their useful practicalities in real life scenarios.

I’m sure there’s plenty of online blogs and forums out there will be ongoing discussions amongst blockchain enthusiasts, exploits and the like on how the technology can ‘revolutionalise’ the way people do online transaction.

I will cover some of those in my future post one day perhaps.

But today, I simply want to cover the basics of writing blockchain for anybody that is interested to know and how it what works under the hood.

At its core, blockchains are simply singly linked list data structure.

If you recall from my last year’s post on common data structures software engineers/developers alike oughta know, they work around the concepts of having a node that’s linked to one after another. In each node, it carries some important data or information about itself. In particular, it holds referencing information about the next sibling/successor node. Thus we have a chain of nodes linking together that’s ever-expanding or elongating.

If you can understand this core concept, you’re more than halfway done to fully grasp what blockchain truly is!

Currently, there are two types of blockchain implementations out there present.

  • Proof of Work
  • Proof of Stake

Proof of Work(POW)

What is POW?

POW is a protocol whose goal is to deter cyber attacks such as distributed DDoS. Its purpose is to exhaust all of the computing power within the resource system by sending multiple fake requests. These grunt work of sending fake requests would be dubbed as the ‘miners’. Miners would have to perform a lot of mining to create a new group of transactions that do not involve any third-party trusts, which in this case they’re simply called blockchains. Miners’ primary responsibility is to

  • Verify the legitimacy of a transaction, and avoid so-called double spending
  • Create new digital currencies by rewarding miners for performing the previous task.
  • Once those tasks of solving mathematical problems are completed, the miners get rewarded for completing them.

Thus in our POW demonstrate this, we define the following function class to describe our block (or node, if you will) structure.

Our POW block data structure
function POWBlock(index, prevHash, timeStamp, data, currentHash) { let index = index, prevHash = prevHash, timeStamp = timeStamp, data = data, currentHash = currentHash; } ... module.exports = POWBlock

What we’re saying here is we have the block’s logical structure that holds certain pieces of important information. Each block will record the amount of transaction and timestamp of the transaction that occurred. Also, like the singly-linked list data structure, it contains references to its own hash as well as the previous block’s hash.

Hashes are calculated because it helps to maintain the integrity of the data thus SHA-256 is the common hashing algorithm for this exercise.

To perform such hashing we do the following;

Calculate its hash
const calculateHash = (index, prevHash, timeStamp, data) => { return CryptoJS.SHA256(index + prevHash + timeStamp + data).toString(); };

Once you’re done creating the hash, we need to generate a block that kicks off the block-chaining operation. To do that, we grab the hash of the previous block that was calculated previously and create the rest of the content from here.

Generate next block..
const generateNextBlock = (blockData = {}) => { const previousBlock = getLatestBlock(), nextIndex = previousBlock.index + 1, nextTimeStamp = new Date().getTime() / 1000, nextHash = this.calculateHash(nextIndex, previousBlock.hash, nextTimeStamp, blockData); return POWBlock(nextIndex, previousBlock.hash, nextTimeStamp, blockData, nextHash); };

That’s it! That’s the main premise of how blockchain works.

Next, we move onto Proof of Stake.

Proof of Stake(POS)

Proof of Stake is similarly to Proof of Work but its goals are different. The algorithm used to make blockchain is the same. However, miners do not get the reward at the mining so no block reward is given but rather block creation are determined and distributed to the block creator depending on the buildup history of their original wealth thus they will be given a stake. Miners do not get rewarded for solving mathematical problems, but they take transaction fees instead.

For the code level, it looks the same as POW, but with one minor difference. We just add a validator.

Our POS block data structure
function POSBlock(index, prevHash, timeStamp, data, currentHash, validator) { let index = index, prevHash = prevHash, timeStamp = timeStamp, data = data, currentHash = currentHash, validator = validator; } ... module.exports = POSBlock

To generate the blockchain, nothing much different other than just adding one attribute there.

Generate the next block..
const generateBlock = (oldBlock, data, address) => { const newBlock = POSBlock(); const t = new Date(); newBlock.index = oldBlock.index + 1; newBlock.timeStamp = t.getString(); newBlock.data = data; newBlock.prevHash = oldBlock.prevHash; newBlock.currentHash = oldBlock.currentHash; newBlock.validator = address; return newBlock; };

Conclusion:

In my next post, I will write up a simulated blockchain ‘economy’ that will demonstrate how the two blockchain implementations will work on their own. I’m looking to using cool NodeJS features such as web sockets and event emitters that will help me to accomplish this goal.

Stay tuned!

Till then, Happy Coding!

Learning Resources:

Comments