Programming Blockchain in Javascript

In the last few posts I talked about implementing Blockchain in iOS using Swift. A lot of people emailed me and asking about the Javascript implementation of the Blockchain. This post shows how to implement the core engine of the Blockchain in Javascript using Node.

Creating the Models

The first step is to define the models associated with domain objects, represented in the Blockchain. These models consists of the following:

Transaction: A transaction represents a transfer of value. This can be money, merchandise, medical records etc.

Block: A block is mined by a miner which is later filled with transactions and added to the blockchain.

Blockchain: A blockchain represents the linked list of blocks. A blockchain is immutable, which means once the block is added to the blockchain it cannot be altered.

Once, our basic models have been created we can move on to implementing the core functionality of the Blockchain.

Implementing the Blockchain Core Engine

We will start by allowing our blocks to add transactions. This is done by adding a “addTransaction” function to the Block class as shown below:

A block is mined based on its key which comprises of the following properties:

index: The current index of the block in the blockchain.

previousHash: The hash of the previous block in the blockchain.

hash: The current hash of the block.

nonce: The magic number which is incremented to find the secret hash which is used to sign the block.

transactions: A list of transactions added to the block.

The key property is a getter property on the Block class as shown below:

Next, we will move to the Blockchain class. Below you can find the complete implementation of the Blockchain class.

To generate a SHA256 hash we will use help from a node package “js-sha256”. You can install the package by running the following command:

npm install js-sha256

That’s pretty much it!

Let’s go ahead and test out our Blockchain by adding few transactions.

We initialize the Blockchain by passing the genesisBlock. In Bitcoin world genesis block contains the rewards for miners. Next, we mined few blocks using the getNextBlock function of the Blockchain. Once, the blocks are mined we add the transactions to the block and add them to the Blockchain.

The video shows blockchain running in action:

Source Code:

You can download the source code here.

Recommended Reading:

Enjoy and happy programming!

Like what you read? Give Mohammad Azam a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.