If you have attended the 2017’s edition of Web Summit, you have surely heard a lot about Blockchain. Not only geeks from across the globe are super excited about it, but also investors are eager for Blockchain.

The main advantage that Blockchain offers when compared to a legacy storage of data is that on Blockchain pre-existing data (stored in blocks) can’t be tampered with or manipulated without breaking all the future blocks, and consequently crashing the whole system.

This happens because in Blockchain’s essence every block has a dependency on the previous one, meaning that if even a tiny bit is changed, the digital signature would be different and the whole future chain would break.

On a standard system, anyone with administrative access is able to change/manipulate the data stored. Although some may argue that he/she could be busted doing it or later audit checks may detect it, the fact is that on an early stage, no one would notice it and the system would, at least for a given timeframe, run with manipulated data.

In this tutorial, I’ll show you in practice some of the basic concepts of Blockchain, by creating a simple JavaScript application.

 

Installing required packages

First of all, we’ll need to install crypto-js, the only package we’ll need for this tutorial. You can install it via NPM:

npm install crypto-js

When the installation is completed, let’s create our Blockchain file blockchain.js and add the dependency we have just installed at the beginning.

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

 

Creating our Block Class

Transactions can be anything, from a value transfer (bitcoin blockchain), a right, or a contract (Ethereum). The important concept to retain/understand is that a block is a group of transactions, and transactions can be… anything!

Let’s define what a block really is by creating our block class. Our sample block is composed by:

1) Index of block (id)
2) Hash of the previous block
3) Current Timestamp
4) Data – Transactions to include in the block
5) Hash of current block

 

class Block {

  constructor(index, timestamp, data, previousHash = '') {

    this.index = index;

    this.previousHash = previousHash;

    this.timestamp = timestamp;

    this.data = data;

    this.hash = this.calculateHash();

  }



  calculateHash() {

      return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();

  }

}

 

Creating our Blockchain class

On our Blockchain, our chain will be a simple array of blocks.

Since one of the inputs of blocks is the hash of the previous block, we’ll need to hardcode our first block, adding to our array our first and only genesis block, before getting things rolling. The genesis block is the first block added to a Blockchain, which is added manually because there is no precedent:

class Blockchain{

    constructor() {

        this.chain = [this.createGenesisBlock()];

    }



    createGenesisBlock() {

        return new Block(0, "20/11/2017", "Genesis block by Cleverti", "0");

    }

}

Now after the genesis block is created, we are finally able to add blocks to our Blockchain, we do it by pushing new blocks to our array.

addBlock(newBlock) {

    newBlock.previousHash = this.getLatestBlock().hash;

    console.log(this.getLatestBlock().hash)

    newBlock.hash = newBlock.calculateHash();

    this.chain.push(newBlock);

}



getLatestBlock() {

    return this.chain[this.chain.length - 1];

}

 

Testing our Blockchain

We’ll now create 2 blocks, after our genesis block. This is how we can do it:

let clevertiblockchain = new Blockchain();

clevertiblockchain.addBlock(new Block(1, "20/07/2017", { sender: ‘cleverti’, receiver: ‘javascript community’, amount: 4 }));

clevertiblockchain.addBlock(new Block(2, "20/07/2017", { sender: ‘javascript community’, receiver: ‘cleverti’, amount: 8 }));

To check how our Blockchain looks like we can add the following lines inside the Blockchain class:

listblockchain() {

  return this.chain;

}

And then call it, to get the output that represents our Blockchain:

//listblockchain()

[ Block {

    index: 0,

    previousHash: '0',

    timestamp: '01/01/2017',

    data: 'Genesis block',

    hash: '4373c7fb1437035365d9228c77eca2cfd240523e274163e78c1eba11effd8b38' },

  Block {

    index: 1,

    previousHash: '4373c7fb1437035365d9228c77eca2cfd240523e274163e78c1eba11effd8b38',

    timestamp: '20/07/2017',

    data: 

     { sender: 'cleverti',

       receiver: 'javascript community',

       amount: 4 },

    hash: '30738c6079394b4b5ed9e838e8be4eab7e2384df871345fa0291d9e0d51387f2' },

  Block {

    index: 2,

    previousHash: '30738c6079394b4b5ed9e838e8be4eab7e2384df871345fa0291d9e0d51387f2',

    timestamp: '20/07/2017',

    data: 

     { sender: 'javascript community',

       receiver: 'cleverti',

       amount: 8 },

    hash: '70e06c3ac50b5e8ca64b738fdb0559501c1e9ccb07862bb904e85848d096e111'

}]

 

Verifying our Blockchain

Now that we have 3 blocks in our chain, we’ll create a script to help us verify that things are in order. Our verification algorithm will check if:

1) Hash of current block is equal to the hash of the previous block
2) Loop the array of blocks, and recalculate hash to check if the value is different

isChainValid() {

    for (let i = 1; i < this.chain.length; i++){

        const currentBlock = this.chain[i];

        const previousBlock = this.chain[i - 1];



        if (currentBlock.hash !== currentBlock.calculateHash()) {

            return false;

        }



        if (currentBlock.previousHash !== previousBlock.hash) {

            return false;

        }

    }



    return true;

}

If none of the conditions above occurs, it means that our Blockchain was not tampered with and data is authentic:

console.log('Blockchain valid? ' + clevertiblockchain.isChainValid());
//Blockchain valid? True

 

Manipulating data on Blockchain

If we manipulate any of the blocks previously added to our Blockchain, none of the following blocks will be valid because the hashes would be different.

Let’s change the block 2 altering the value of the transaction from amount 4 to 3:

clevertiblockchain.chain[1].data = { sender: 'cleverti', receiver: 'javascript community',  amount: 3 }

clevertiblockchain.chain[1].hash = savjeeCoin.chain[1].calculateHash();

After this tiny change, the hash of the block would be totally different, which would make all the succeeding blocks invalid – the chain would be broken because the value previous block of the next block wouldn’t match the new hash of the block.

console.log('Blockchain valid? ' + clevertiblockchain.isChainValid());
//Blockchain valid? False

 

And that’s it! I hope you found this tutorial useful to understand some basics on Blockchain. If predictions come true, you will probably need it in a near future.

 

Written by João Silva |  Business Development Manager at Cleverti