HI WELCOME TO SIRIS

How To Create Blockchain In JavaScript

Leave a Comment
In this tutorial, we will see How To Create Blockchain In JavaScript. Blockchain keeps the record of all data exchanges — this record is referred to as the “ledger” in the cryptocurrency world, and each data exchange is the “transaction.“ Every verified transaction is added to the ledger as a “block.” It utilizes the distributed system to verify each transaction — the peer-to-peer network of nodes. Once signed and verified, a new transaction is added to the blockchain and cannot be altered.
The blockchain is a structure of data that represents the financial ledger entry, or a record of a transaction. Each transaction is digitally signed to ensure its authenticity and that no one tampers with it, so a ledger itself and the existing transactions within it are assumed to be of high integrity.
In this tutorial, we will create the simple blockchain in javascript in which we use Javascript as a language and Node.js as a backend to run the small project.
How To Create Blockchain In JavaScript
Now if we need to create a simple Blockchain in Node.js, then we need to have one Genesis Block
You can refer to Genesis Block as the first block of Blockchain because Blockchain is an array of blocks and Genesis is the first block of the Blockchain.

Genesis Block

The genesis block is the first block of the blockchain. The genesis block is generally hardcoded in the applications that utilize its blockchain. The Genesis Block is also known as Block Zero or Block 0. It is an ancestor that every Blockchain network’s block that can be traced to its origin back. Remember how every block in the Blockchain is linked back to the previous block using the hash in the block header? You keep going back, and you realize every block is hence connected to the genesis block.
Our Genesis Block contains the following fields or properties.
  1. timestamp
  2. lastHash
  3. hash
  4. data
So, if we combine all these properties into one object, then it will become a Genesis Block. So based on this block, we will mine the second block. Then from the second block, we will extract the third block and so on. That is why we need a Genesis Block to start a Blockchain.
Now, let us start a project by creating a project folder and then start building awesome blockchain using Javascript.

Step 1: Create a project and create a Genesis Data

The first step is to create a project. Type the following command.
mkdir cryptochain
Go inside that folder.
cd cryptochain
Now, generate the package.json file in the case in future, we need to install any node modules.
npm init -y
Remember, I am using Node v11.3.0. 
Next step is to create a new file inside the root called genesis.js and add the following code.
// genesis.js

const GENESIS_DATA = {
    timestamp: Date.now(),
    lastHash: '64b7edc786326651e031a4d12d9838d279571946d8c9a5d448c70db94b0e143f',
    hash: 'c671c84681b9d682b9fd43b2a2ef01a343eab7cfa410df9835f8165007d38467',
    data: 'krunal'
};

module.exports = { GENESIS_DATA };
Here, we have taken an object with its initial values.
As I have defined earlier, our block contains the four properties. This is a genesis data, so we need to hardcode this values.
The properties timestamp and data are you can understand. But I have used SHA256 algorithm to convert the simple text into hash text.
Actual text for lastHash is a krunal, and actual text for the hash is a krunalHash.
You can verify it by going to this URL: https://passwordsgenerator.net/sha256-hash-generator/
Here, you can enter my name as a text, and it will give the SHA256 hash of that text. Now, you need to convert that text to lowercase by using Javascript’s toLowercase(). That is it. You will find the exact hash like me. Cool!! So now, you have Genesis Data is ready. The next thing is to create a Block from this data.

Step 2: Create a Block

Inside your project root, create a file called block.js and add the following code.
// block.js

const { GENESIS_DATA } = require('./genesis.js');

class Block {
    constructor({timestamp, lastHash, hash, data}) {
        this.timestamp = timestamp;
        this.lastHash = lastHash;
        this.hash = hash;
        this.data = data;
    }

    static genesis() {
        return new this(GENESIS_DATA);
    }
}

module.exports = Block;
So, here we have imported the GENESIS_DATA for our block.
Then we have defined the Block class and passed the parameters to the constructor when we create an object of the Block.
We have also defined the static method called genesis() which is responsible for returning theGenesis Block for our blockchain.
Remember, we have previously defined the GENESIS_DATA not block. After creating an object of this class, it will become a Genesis Block.

Step 3: Create a hash based on a previous block.

We need to define a function that can create a hash based on the previous block’s hash.
So, first let us create a new file inside the root called crypto-hash.js and add the following code inside it.
// crypto-hash.js

const crypto = require('crypto');

const cryptoHash =(...inputs) => {
    const hash = crypto.createHash('sha256');
    hash.update(inputs.sort().join(' '));
    return hash.digest('hex');
}

module.exports = cryptoHash;
Now, to create a Hash, we need the three properties.
  1. timestamp
  2. lastHash
  3. data
So, we have first required the crypto module provided by the Node.js.
Then we have defined the function called cryptoHash() which will accept the inputs. Here we have used spread operator which is the syntax of ES6.
Inside that function, we have called the createHash() method and pass the sha256 as a parameter. That means we need to create a hash based on the sha256 algorithm.
Then we have sorted and join that three parameters and return its hex values.
So, finally, we can get the current block’s hash based on the previous block’s three properties.

Step 4: Mine a new Block based on a previous Block

So, we got the Genesis Block and the hash of that block. Now, we need to write the function that can generate a new Block based on the previous block. Right now, in our case, it is a Genesis Block.
Now, import the crypto-hash module inside the block.js file and create a new function called mineBlock() and pass the two parameters.
  1. lastBlock
  2. data
So, our final block.js file looks like this.
// block.js

const { GENESIS_DATA } = require('./genesis.js');
const cryptoHash = require('./crypto-hash');

class Block {
    constructor({timestamp, lastHash, hash, data}) {
        this.timestamp = timestamp;
        this.lastHash = lastHash;
        this.hash = hash;
        this.data = data;
    }

    static genesis() {
        return new this(GENESIS_DATA);
    }

    static mineBlock({lastBlock, data}) {
        const timestamp = Date.now();
        const lastHash = lastBlock.hash;
        return new this({
            timestamp,
            lastHash,
            data,
            hash: cryptoHash(timestamp, lastHash, data)
        });
    }
}
module.exports = Block;
So, here we have defined the method called mineBlock and pass the two parameters. The mineBlock() will return a complete new Block based on the previous block.
Now, it is the time to create a Blockchain from these blocks.

Step 5: Create a Blockchain

We have completed the step of creating a Genesis Block and mining a new Block. Now it is the time to develop a blockchain. That is why create a new file inside the root called blockchain.js and add the following code inside it.
// blockchain.js

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

class Blockchain {

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

    addBlock({ data }) {
        const newBlock = Block.mineBlock({
            lastBlock: this.chain[this.chain.length-1],
            data
        });

        this.chain.push(newBlock);
    }
}

module.exports = Blockchain;
So, first, we have imported the Block.js file and then create a class called Blockchain.
The Blockchain class is responsible for adding a new block inside the blockchain.
The blockchain is an array of the blocks starts with Genesis block.
So in the constructor, we have not defined an empty array. Instead, we have filled the chain array with the Genesis block.
Then we have defined one function called addBlock() which accepts the data.
Now, before adding a new block to the chain array, we need to mine it. That is why we have called the Block class’s mineBlock() method to extract a new block.
For mining a new block, we need a previous block and data. That is why we have used this code this.chain[this.chain.length-1] because it will return the last block in the blockchain and data is already we are passing to that function. So we get the new block based on the previous block and data.
Next step is to add that newly mined block inside our blockchain, and that is it.
The last step is to run this project and get the blockchain.

Step 6: Run the project and get the blockchain.

Now, the last step is to create a file inside the root of the project called server.js and add the following code.
// server.js

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

const blockchain = new Blockchain();

for(let i=0; i<5; i++) {
    const newData = 'krunal'+i;
    blockchain.addBlock({data: newData});
}

console.log(blockchain);

So, here we have imported both the block.js and blockchain.js file and created an object of the Blockchain.
Then we will loop through that blockchain and add the data to that blockchain and created the six blocks in the blockchain because one is Genesis and five based on previous blocks.
Go to the terminal and start the node server.
node server
You will see an output like this.

How To Create Blockchain In JavaScript
Finally, How To Create Blockchain In JavaScript Tutorial With Example is over. Now you have a clearunderstanding of Blockchain technology and how we can start coding in it. Above example is an elementary example of implementing a blockchain. Real-world examples are very complicated but this is the first step to enter the blockchain world and become a blockchain developer.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.