How to build Consensus Algorithm for Blockchain Network in Javascript

How to build Consensus Algorithm for Blockchain Network in Javascript

During broadcasting Transactions over our Blockchain network, a certain node may not receive a piece of information, or even there is a bad actor who sent out false information or created fraudulent transactions and broadcasts them to the whole network, convinces everybody that they are legitimate transactions. So, the Consensus Algorithm provides us a way to compare one Node to all the other Nodes inside of the network to confirm that it has the correct data. In this tutorial, we’re gonna create a Consensus Algorithm that implements the Longest Chain rule.

Previous Post: How to Synchronize Blockchain Network in JavaScript

Next Post: How to explore Data inside of Blockchain Network in Javascript

Consensus Algorithm

Longest Chain rule

This rule simply compares the chain of the chosen Node with all the other chains inside of our Blockchain network.
If one of the other chains has longer length than the current chain, we simply replace the chain of the Node we are on with the longest chain in the network.

Why we use Longest Chain rule?
>> The longest chain has the most Blocks in it and each of those Blocks was mined by using Proof of Work. We can assume that the whole network contributed to the longest chain because of how much work went into that chain.

Implement Longest Chain rule

Validate chain

This method validates a Blockchain by comparing all of the hashes of all of the Blocks inside of the chain.

class Blockchain {
    isChainValid(blockchain) {
        // 1- validate Genesis Block

        // 2- forEach block in chain
        // 2.1 validate block Hash
        // 2.2 compare Hash with previous block Hash

Consensus Endpoint

We add an endpoint GET /consensus to our API. It will:
– make a request to every Node inside of our Blockchain network to get their copies of the Blockchain
– find the longest chain by comparing current chain with these chains
– use isChainValid() function to check if the longest chain found in previous step is valid
– if all things are validated, assign chain & transactions from the longest chain to this Blockchain

app.get('/consensus', function (req, res) {

    // forEach nodeUrl in networkNodes
    // GET 'nodeUrl/blockchain'
    // find longest chain
    // check if longest chain is valid
    // assign chain & transactions to this Blockchain


Validate Chain Method

Inside blockchain.js, add new method named isChainValid() to Blockchain class:

class Blockchain {
    isChainValid(blockchain) {
        const genesisBlock = blockchain[0];
        if ((genesisBlock.nonce !== 100) ||
            (genesisBlock.hash !== 'Genesis block') ||
            (genesisBlock.prevBlockHash !== '0') ||
            (genesisBlock.transactions.length !== 0)) {
            return false;

        for (let i = 1; i < blockchain.length; i++) {
            const currentBlock = blockchain[i];
            const previousBlock = blockchain[i - 1];

            const currentBlockData = {
                transactions: currentBlock.transactions,
                index: currentBlock.index
            const blockHash = this.hashBlock(previousBlock.hash, currentBlockData, currentBlock.nonce);

            if (blockHash.substring(0, 2) !== '00') {
                return false;

            console.log('previousHash: ', previousBlock.hash);
            console.log('currentHash: ', currentBlock.hash);
            if (currentBlock.prevBlockHash !== previousBlock.hash) {
                return false;

        return true;

Consensus Endpoint

Inside api.js, add new endpoint GET /consensus:

app.get('/consensus', function (req, res) {
    const requests = [];
    bitcoin.networkNodes.forEach(nodeUrl => {
        const requestOptions = {
            uri: nodeUrl + '/blockchain',
            method: 'GET',
            json: true

        .then(blockchains => {
            const currentChainLength = bitcoin.chain.length;
            let maxChainLength = currentChainLength;
            let longestChain = null;
            let pendingTransactions = null;

            blockchains.forEach(blockchain => {
                if (blockchain.chain.length > maxChainLength) {
                    maxChainLength = blockchain.chain.length;
                    longestChain = blockchain.chain;
                    pendingTransactions = blockchain.pendingTransactions;

            if (!longestChain ||
                (longestChain && !bitcoin.isChainValid(longestChain))) {
                    message: 'Current chain cannot be replaced!',
                    chain: bitcoin.chain
            } else if (longestChain && bitcoin.isChainValid(longestChain)) {
                bitcoin.chain = longestChain;
                bitcoin.pendingTransactions = pendingTransactions;

                    message: 'Chain is updated!',
                    chain: bitcoin.chain

Run & Check results

- Run the API on each Terminal with command:
npm run node1
npm run node2
npm run node3
npm run node4

- Register and broadcast node2, node3 (but NOT node4) with node1:


- Broadcast some Transactions and mine, then check a Node:


- Show node4 data (remember that we haven't register this Node with our Blockchain network):


- Register node4 with our Blockchain network using /register-and-broadcast-node:


- Run Consensus Algorithm on node4 with url http://localhost:3004/consensus:


- Show node4 data after running Consensus Algorithm:


Source Code


0 0 votes
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments