Blockchain technology using Javascript

Hello People. This article is about Blockchain technology using Javascript. As you already know, a blockchain is an open, digital, and duplicated ledger of transactions. Every new transaction history is recorded and stored in an encrypted way that is very difficult to modify. A copy of this recorded information is sent a cross the blockchain network. This makes it highly secure.

Blockchains are blocks of transaction data growing increasingly to create a chain of transaction occurrences. Valid transaction data is logged into the blockchain network following the peer-to-peer rule laid down by participants. Normally, the data in the databases are centralized. This means we operate based on only one server. Chances of risk are high due to failures of the system. Alternatively, decentralization allows data to be stored everywhere, thus making it faster, more secure and a better way of storing data.

We need to first install the crypto library using the command:

npm install --save crypto-js

We’ll use this library to import modules in our project.

We can start by creating a class BlockCypto as shown below:

const SHA256 = require('crypto-js/sha256');
class BlockCypto{
    constructor(index, current_time, info, nextHash=" "){
    this.index = index;
    this.current_time = current_time;
    this.info = info;
    this.nextHash = nextHash;
    this.hash = this.computeHash();     
    }
    computeHash(){
        return SHA256(this.info + this.nextHash + this.current_time + JSON.stringify(this.info)).toString();
    }   
}

Let us see each part of the code here:

We have created the class BlockCrytpo for our block and added a constructor just like any other JavaScript class.

In the constructor, we initialize its properties and assign parameters to it, as follows:

  • crypto-js/sha256: This is the module we’ve imported to calculate the hash of each block. We converted it to string using toString() method as the module will return the object.
  • index: This is a distinctive number tracking the index of every block in the blockchain.
  • current_time: As the name states, it keeps a record of the time when each transaction is completed.
  • info: All completed transactions data are recorded and stored by this method.
  • nexthash: It is pointing to the hash_key of the next block in the network chain. It’s mainly used to keep and maintain the integrity of the blockchain.
  • computeHash: Based on properties passed to this method, it is used to calculate the hashkey of the next block in the chain.
Blockchain technology using Javascript

What is blockchain theorem?

It is a type of database that stores a collection of data together in groups, with certain capacity of storage. The blocks are connected to the already created blocks, this forms a chain of a data tree.

The chain is irreversible as the system is decentralized. Here, each block is assigned a timestamp when added to the chain.

Now, let’s create a class Blockchain that will maintain this operation:

class Blockchain{
    constructor(){
        this.block1chain = [this.startGenesisBlock()];     
    }
    initGenesisBlock(){
        return new BlockCrypto(0, "06/04/2021", "Initial Block in the Chain", "0");
    }
    latestBlock(){
        return this.block1chain[this.block1chain.length - 1];
    }
    addNewBlock(newBlock){
        newBlock.nextHash = this.latestBlock().hash;
        newBlock.hash = newBlock.computeHash();        
        this.block1chain.push(newBlock);
    }
}

Let’s understand the code snippet above.

As usual, we have our constructor which instantiates the blockchain.

But this time, we passed it to the initGenesisBlock() method, which initializes the block in the chain. This property refers to an array of blocks in our case.

  • initGenesisBlock(): This is the first block created in the peer-to-peer network and has not been linked to any other. To our knowledge of indexing it’s at index 0.
  • latestBlock: As named, we use it for finding the last block added in the chain. As explained earlier, it helps to ensure the hash of the current block and map it to the hash of the previous block to ensure the chain integrity.
  • addNewBlock: A new block is added to the chain using this method. The previous hash block is matched to the current hash block to ensure minimal or no tampering with the chain.

Now that our blockchain is ready to work. We are missing something that is a core blockchain principle, the blockchain integrity.

Let’s see how to verify it and test our app.

Verifying blockchain integrity

The main characteristic of a blockchain is that once a block has been added to the network, it can’t be changed without invalidating the entire blockchain integrity.

To perform this, we use digital security or cryptographic hash, which ensures the securing and validation of the blockchain by producing a new hash every time a change is made in the block.

We’ll loop over the entire blockchain to check whether any hash has been tampered with, taking into account the exception of the first block, which is hardcoded.

Besides, this method verifies if the cryptographic-key of each two blocks in series are pointing to one another. If the integrity of the blockchain has been compromised, it returns false; otherwise, in case no anomalies are encountered, it returns true.

We’ll create this method inside the Blockchain class:

checkValidity(){
    // Checking validity
    for(let i = 1; i < this.block1chain.length; i++) {
        const currentBlock = this.block1chain[i];
        const nextBlock= this.blockchain[i-1];
    // Checking current blcok hash
    
    if(currentBlock.hash !== currentBlock.computeHash()) {
        return false;
    }
    // Comparing current block hash with the next block

    if(currentBlock.nextHash !== nextBlock.hash) {
        return false;
    }
    return true;
}

Now, we can test our app and see the results:

But, before we dive into running the code, let’s create a new instance of the Blockchain class and name it thecoin, and add some blocks in the blockchain using random values.

let thecoin = new Blockchain();

thecoin.addNewBlock(new BlockCrypto(1, "06/04/2021", {sender: "Rabin Yitzack", recipient: "Loyd Eve", quantity: 20}));

thecoin.addNewBlock(new BlockCrypto(2, "07/04/2021", {sender: "Anita Vyona", recipient: "Felix Mush", quantity: 349}));

console.log(JSON.stringify(thecoin, null, 4));

Hope this article on Blockchain technology using Javascript is useful to you. Please read Child Tracker IOT project architecture

Navigation

× Contact Us