Let’s Create A BlockChain On Node.js

Video Tutorial

Overview

A BlockChain is Originally a Fastly Growing Endless Chain Of Blocks Where Each Block represents an Immutable Data which makes it super powerful in terms of dealing with sensitive Data, Widely used For Cryptocurrencies (Bitcoin, Lithium…).

Uses Cryptography Algorithms to prevent Data foreign By block hashing where each block has its own unique hash on the chain, which allows the chain to be safe from unauthorized modifications. (SHA256, base64 Encoding…)

We will try to create a very basic BlockChain as well as explain how new blocks are being added to the chain and how cryptocurrency mining works.

Getting Started

For following along this tutorial you will need a brief knowledge about setting up node js, you may want to check this course series about it, also we are going to uses ES6 Javascript classes you can also learn more about it here.

Make sure to install block hash module that will allow us to create hashes for javascript objects

npm install object-hash --save

First, let’s start by creating the base BlockChain class that is going to hold all the chain blocks and allows us to add new blocks and currency transactions.

class BlockChain {

    constructor() {
        //Create
        this.chain = [];
        //Transaction
        this.curr_transactions = [];
    }

    lastBock() {
        return this.chain.slice(-1)[0]; ///< we return and element 0 index (since the has only one)
    }

    isEmpty() {
        return this.chain.length == 0; ///< returns true if empty else false
    }

}
module.exports = BlockChain;

So we creating an empty chain array (list) which going to hold the blocks and blocks are going to be objects with a specific data as well as we create an empty current transactions array we will add on it the currently queued transactions that have been added since the last block push, on each new block add we clear the transactions array.

We have two methods, lastBlock returns the last block from the chain we use the slice method in order to grab a portion of the chain array (-1 means start from the end and grab only one element). and isEmpty return the state of the chain.

Now let’s try to add the methods responsible for adding new transactions and new blocks to the chain

...
  addNewTransaction(sender, recipient, amount) {
     //Push the object to the Array
     this.curr_transactions.push({sender, recipient, amount});
     //Using ES6 the key and value pairs can be defined only by specifying the variable 
  }

Transactions is an object composed of the sender and recipient’s usernames as well as the amount of money (on the target Currency)

let hash = require("block-hash");
...
    addNewBlock(prevHash) {
        let block = {
            index: this.chain.length + 1,
            timestamp: Date.now(),
            transactions: this.curr_transactions,
            prevHash: prevHash,
        };
        //Put Hash
        this.hash = hash(block);
        //Add to Chain
        this.chain.push(block);
        this.curr_transactions = [];
        return block;
    }
...

We create the block which holds the index on the chain, timestamp the block has been added on (Date), transactions, and previous Block’s hash that way we can form a chain just by linking each block with the previous block’s hash.

And kind of change on the block’s data will force the hash to chain and that means a corrupted chain (the block’s referencing between the current and previous block is lost), that is the basic way how block chains can protect from data Foreign (Data Modifications).

The Last thing we need is to clear the current transactions since the block has got them stored for us, now it is time for adding new transactions and new block holds them.

Also, make sure to require the block hash module for using the hash method for creating the block’s hash.

Adding Blocks To The Chain (Mining)

So if you have heard about cryptocurrency mining (Bitcoin Mining) it is basically adding new blocks that hold new transactions in the Large Blocks Chain, but it is not that easy each currency has it own validation methods which allow you to add blocks only when finiding the right hash (and this is mining) where you try to use your GPU’s power for randamly generating a large set of hashes and check agains the right one (where you can’t actually view the right hash), you can learn more about mining in order to fully understand everything is tied up together.

So we are going to try to make a very basic way for hash checking where we are going to create a basic number composed of 3 numbers (for ex: 150) and create a counter, each time we hash the generated number and we check for the desired hash if everything is right then we can add a new block to the chain, simple.

//main.js
const PROOF = 1560; ///< Random Proof Number 

//Check if the Proof is Valid
let validProof = (proof) => {
  let guessHash = hash(proof); ///< hash the proof
  console.log("Hashing: ", guessHash);
  return guessHash == hash(PROOF); ///< check against the real proof hash
};

//Generate Proof
let proofOfWork = () => {
  let proof = 0;
  //Loop till you get into the real proof
  while(true) {
    //check proof (Not valid, increment)
    if(!validProof(proof)) {
      proof++;
    } else {
      //We have got the proof, get out of the infinite loop;
      break;
    }
  }
  //Send Proof Back 
  return proof;
}

As you can see on the main.js we have two methods one for checking if the provided proof is valid (in this case we use number just to make it simple) where in real life world you have a really long random generated characters string you need to hash and check against, so it would return true if everything matches else false.

Then we create the proofOfWord method that is going to allow us to loop and generate numbers that we can use for validating the real proof (1560) and since it numbers all we need to do is looping and check and then increment if not valid till we get into the right proof.

Now let’s try to add a new block but only after validating and getting the right proof.

//Add New Block (When Proof is OK!)
if (proofOfWork() == PROOF) {
    //if first block on chain (Previous hash is NULL)
    let prevHash = blockChain.lastBock() ? blockChain.lastBock().hash : null;
    //New Transactions 
    blockChain.addNewTransaction("islem", "penywis", 560);
    //Add Block
    blockChain.addNewBlock(prevHash);
}

//Log Our Chain after block adding 
console.log("Chain: ", blockChain.chain);

And if you tried to run the above code, you should be able to get mining and block adding simulator, just very quick thing but in the real world that would take more power and time than this in order to find the check for the right hash in order to add new hash in the blockChain.

Well, is my blockChain Secured?

The answer to this question depends on your BlockChain if you have a very small chain which only holds a couple of blocks as our example in here the answer would be it’s not, since blockChain’s security is all about how large it is the larger it gets the more secure it becomes, since trying to modify an already added block to the chain will cause the block’s hash change and that means the whole chain will be broken.

Also there some other ways of securing blockChain which makes super impossible to break is by saving copies on the network of servers and whenever there will be a breach you double check with the already safe saved copies.

What’s Next

So that was a very basic BlockChains and the basic system that powers this great technology if you are looking to learn more blockChain take a look at this Topic.

No Comments Yet