Blockchain Explained using JavaScript Blockchain Explained using JavaScript

Page content

In this article, we’ll learn how to implement Blockchain using Javascript.

Prerequisite

  • Download and install NodeJs to run our blockchain code
  • Download and install Visual Studio Code IDE for code development

Don’t worry if you don’t have prior experience with JavaScript, NodeJS, and VSCode. Just follow with me and you will learn basics of Blockchain which you can later implement in any other language.

Blockchain

Blockchain is nothing but a digital, distributed, immutable, and trusted ledger which can be used to record anything from financial transactions, government records to land titles, or even purchase orders.

Each transaction record is a block, which are linked together chronologically to form a chain of blocks. If you want to change record in a particular block, you don’t rewrite it. Instead, the change is recorded in a new block.

Also read Blockchain Basics and its Practical Use Cases

Block

Let’s see what a typical block in blockchain consist of:-

  1. Timestamp is date and time when the transaction took place.
  2. Record typically contains the details of a transaction like sender, receiver, amount. We are going to use actual names of sender and receiver in our program but in a practical use case like bitcoin, actual names are not revealed, a digital signature of sender and receiver is used instead.
  3. Hash is a digital fingerprint that represents the transaction in the block and is completely unique. If there is any change in transaction details, the hash would also change. Generally, it’s an alphanumeric sequence generated by applying some crypto algorithm like SHA-256 on transaction details.
  4. Previous Hash is the Hash of the previous block in blockchain. This is also used to generate Hash of the block.
  5. Nonce is an abbreviation for “number only used once,” which is a number added to a block in a blockchain that, when rehashed, meets the difficulty level restrictions. We will discuss more on this later

Step 1: Create Block (block.js)

Now we know the what block consist of, let’s create it

const SHA256 = require('crypto-js/sha256');

class Block {
    constructor(timestamp, previousHash, record, difficultyLevel) {
        this.timestamp = timestamp;
        this.record = record;
        this.previousHash = previousHash;
        const proofOfWork = this.proofOfWork(difficultyLevel);
        this.hash = proofOfWork.hash;
        this.nonce = proofOfWork.nonce;
    }

     /* Genesis Block */
    static genesis() {
        return new this(new Date(), 
            "",
            "GENESIS"
        );
    }

    /* Block Mining */
    static mineBlock(previousBlock, record, difficultyLevel) {
        const timestamp = new Date();
        const previousHash = previousBlock.hash;
        return new Block(timestamp, previousHash, record, difficultyLevel);
    }

    /* Generate Hash using SHA256 */
    static computeHash(message){
        return SHA256(message).toString();
    }

    /* Proof of Work */
    proofOfWork(difficultyLevel) {
        const message = this.timestamp + JSON.stringify(this.record) + this.previousHash;
        if(difficultyLevel){          
            const leadingZeros = "0".repeat(difficultyLevel);
            let nonce = 0;
            while(true){
                let hash =  Block.computeHash(message + nonce);
                if(hash.substring(0, difficultyLevel) == leadingZeros){             
                    return {
                        hash,
                        nonce
                    };
                }
                nonce++;
            }
        }else{
            return {
                hash: Block.computeHash(message),
                nonce: 0
            }
        }       
    }
}

module.exports = Block;

Let’s understand few more terms

  1. Genesis Block is the first block in blockchain which is not having any transaction details and previous hash. This is generally added at the time of creation of blockchain. Also known as Block Zero
  2. Difficulty Level is the restriction to generate hash of the block. More difficulty level, more time it takes to generate a hash.
  3. Block Mining is a process of adding a new block to the blockchain. Who adds new block is called Block Miner, also known as bitcoin miner in case of bitcoin. Anyone can register their computer to become one of the bitcoin miner in case of a public blockchain like bitcoin. All the bitcoin miners in bitcoin network get a copy of whole blockchain and each receives a notification when a new block is added to the blockchain.
  4. Proof of Work is a cryptographic hash puzzle which each Block Miner in the blockchain tries to solve. As soon as one of the Block Miner solves the puzzle, essentially means generated the hash of the block with said difficulty level, they broadcast this to the blockchain network and hash is validated by all the other Block Miners in the network.
What is Proof of Work for us?

Out Proof of Work is to generate a hash with leading zeros based on difficulty level.
Difficulty level of 5 means, generate a hash with 5 leading zeros, e.g. 00000b4d7m3h1s0k2s8bw0hn382

How we are going to achieve?

We are going to calculate the hash by applying SHA-256 algorithm on the transaction details and nonce value. We will start with nonce value of 0 and keep incrementing it until we find the hash with leading zeros of difficulty level.

Step 2: Create Blockchain (blockchain.js)

Now we have learned a lot of terms, let’s quickly create a blockchain

const Block = require('./block');

class Blockchain {

    constructor() {
        this.difficultyLevel = 1;
        this.chain = [Block.genesis()];
    }

    addBlock(record) {
        const newBlock = Block.mineBlock(this.chain[this.chain.length-1], record, this.difficultyLevel);
        this.chain.push(newBlock);
    }
}

module.exports = Blockchain;

Step 3: Test Blockchain (server.js)

Let’s create few blocks of transaction with random sender, receiver and amount details. Also, let’s increase the difficulty level after every 2 transactions.

const Blockchain = require('./blockchain')
const { performance } = require('perf_hooks');

const blockchain = new Blockchain();

const userList = ["Alice", "Bob", "Charlie", "David", "Eric", "Franklin", "Gavin", "Harry", "Iris", 
                "Joey", "Kate", "Leo", "Monica", "Nancy", "Oscar", "Phoebe", "Quinn", "Ross", 
                "Sofia", "Tyler", "Umar", "Victor", "Wilson", "Xena", "Yasmine", "Zara"];

const addNBlocks = (n) => {
    for(let i = 0; i < n; i++) {
        blockchain.addBlock({
            sender: userList[Math.floor(Math.random() * userList.length)],
            receiver: userList[Math.floor(Math.random() * userList.length)],
            amount: Math.floor(Math.random() * 1000)
        });
    }
}

const t0 = performance.now();
addNBlocks(2);
var t1 = performance.now()
console.log("[Difficulty Level 1] Added first 2 blocks in  " + (t1 - t0) + " milliseconds.")

blockchain.difficultyLevel = 3;
addNBlocks(2);
var t2 = performance.now()
console.log("[Difficulty Level 3] Added next 2 blocks in  " + (t2 - t1) + " milliseconds.")

blockchain.difficultyLevel = 5;
addNBlocks(2);
var t3 = performance.now()
console.log("[Difficulty Level 5] Added next 2 blocks in  " + (t3 - t2) + " milliseconds.")

/* Print Blockchain*/
console.log(blockchain.chain);

Now everything is ready, go to terminal and run following commands

npm install --save crypto-js
node server

You will see an output like this.

Output
[Difficulty Level 1] Added first 2 blocks in 6.2153230011463165 milliseconds. [Difficulty Level 3] Added next 2 blocks in 175.92524899542332 milliseconds. [Difficulty Level 5] Added next 2 blocks in 2065.910447001457 milliseconds. [ Block { timestamp: 2020-05-18T17:05:37.501Z, record: 'GENESIS', previousHash: '', hash: '9636ccb176c9f4825d24e1b8db51e3ffb5d448ba112ec0db9672e80f6dc855c3', nonce: 0 }, Block { timestamp: 2020-05-18T17:05:37.504Z, record: { sender: 'Xena', receiver: 'Umar', amount: 770 }, previousHash: '9636ccb176c9f4825d24e1b8db51e3ffb5d448ba112ec0db9672e80f6dc855c3', hash: '0329bb14cb5d59a2ddce485019de8041c6790b4483afbad91516ec78e21a70f4', nonce: 24 }, Block { timestamp: 2020-05-18T17:05:37.509Z, record: { sender: 'Harry', receiver: 'Wilson', amount: 601 }, previousHash: '0329bb14cb5d59a2ddce485019de8041c6790b4483afbad91516ec78e21a70f4', hash: '05187dd8fa18b1ebd50565f1607e43ab9ad081955a71fb6f542cb91755192b49', nonce: 12 }, Block { timestamp: 2020-05-18T17:05:37.512Z, record: { sender: 'David', receiver: 'Quinn', amount: 600 }, previousHash: '05187dd8fa18b1ebd50565f1607e43ab9ad081955a71fb6f542cb91755192b49', hash: '000a0f95e605831a1fa0178351a195fc6f60752fd59e251ea56b1c0d464b8920', nonce: 7947 }, Block { timestamp: 2020-05-18T17:05:37.620Z, record: { sender: 'Yasmine', receiver: 'Umar', amount: 918 }, previousHash: '000a0f95e605831a1fa0178351a195fc6f60752fd59e251ea56b1c0d464b8920', hash: '000e8a70d4b6673f3a10cc68fdc21e0cda7a71aa0fe56d31a13cf95832596a45', nonce: 5384 }, Block { timestamp: 2020-05-18T17:05:37.686Z, record: { sender: 'Phoebe', receiver: 'Victor', amount: 336 }, previousHash: '000e8a70d4b6673f3a10cc68fdc21e0cda7a71aa0fe56d31a13cf95832596a45', hash: '000005b737aaa4faa3b87b56474dec9537eee843c2881cb5f6432ca9708bd7b5', nonce: 45944 }, Block { timestamp: 2020-05-18T17:05:38.178Z, record: { sender: 'Umar', receiver: 'Oscar', amount: 239 }, previousHash: '000005b737aaa4faa3b87b56474dec9537eee843c2881cb5f6432ca9708bd7b5', hash: '0000057a7a4c7caea164b4e5672a3c38fcf12c6c8bfb4b1c503ca876664f2660', nonce: 150796 } ]

Observations from Output

  1. As we increased difficulty level from 1, 3, to 5, it took more time to generate the hash and add new blocks. Blockchain technologies like bitcoin require to solve hash puzzle with the difficulty level of somewhere starting from 18 to 30. You can imagine the time requires to solve those puzzles.
  2. The first block of blockchain is GENESIS block with no transaction info and no previous hash value
  3. See the hash generated with 1, 3, and 5 leading zeros based on difficulty level
  4. See the variable nonce value keeps increasing with difficulty level, also tells us the number of attempts our hash algorithm took to generate hash.

Summary

I hope you have now a basic understanding of Blockchain technology and how we can implement it. Please note that the above example is a very basic implementation of Blockchain. Real-world examples are very complicated but this is the first step to enter the Blockchain world.

Please find the source code for this example on github