Blockchain is a immutable globally distributed ledger which depends on the resources of a peer-to-peer network. Simply put, think of the Blockchain as a really long spreadsheet.
Read this for a primer on Blockchain. If you are already familiar, read along.
We’ll use Javascript to write a small blockchain. The point is to learn by doing and understand how a blockchain works. You can find a link to the complete code towards the end of this article.
I’m calling this Blockchain koreCoin. You can call it anything.
Step 1: Create the folder structure and main.js
Create a folder on your Desktop or the any other preferred location on your computer. In the folder, create a new Javascript file called main.js
Step 2: Create a block
In the file main.js create a new class called Block
In the Block class, we create a constructor and assign it some properties.
The constructor has the following properties
- index
This property is optional and tells you where the block sits on the chain. - timestamp
As the name indicates, this property assigns a time stamp to the block that is created. - data
This property stores any type of data that you might want to store like currency transactions such as how much money was transferred and who was the sender and recipient. You can also store other types of data like energy consumption, dog names, etc. - previousHash
We create a previousHash property that contains a string that stores the hash value of the previous block.
We will keep track of the properties in our constructor as follows. We also will add another property to our constructor called hash. We will set it as empty.
Step 3: Calculate the Hash value of the block
To assign a Hash value, we’ll need to calculate it. We’ll create a new function called calculateHash in the Block class as follows and add the function to our hash property.
The calculateHash function as the name suggests calculates the hash value of the block. In this case, we take the properties on the block mentioned earlier and run it through the hash function.
Simply put, the calculateHash function does the following:this.hash = this.index + this.previousHash + this.timestamp + this.data
The above function is too simplistic and would return an inconsistent datatype. To ensure consistency, we will convert the return value into a string:this.hash = ( this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) ).toString();
The above function too is not robust enough. So we run it through a hash function. In this case we’ll use a SHA256 hash function.
The SHA256 hash function doesn’t come preinstalled. Here’s how you’d install it.
- First you need to install node and npm. Here’s how to do it.
Mac
Windows
Linux - Now that you’ve installed npm. In the terminal app, go to the folder where you’ve saved your blockchain code and type the following command
sudo npm install --save crypto-js
Now that we have the SHA256 function installed, we need to import the library in our blockchain code as follows:
Our hash function now looks like thisthis.hash = SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
Our block code now looks like this
Step 4: Create a Blockchain class
The next step is to create a Blockchain class. This class consists of five functions viz. constructor, createGenesisBlock, getlatestBlock, addBlock and isChainValid.
- constructor
The constructor function initializes the blockchain.constructor(){
this.chain = [this.createGenesisBlock()];
}
In this function we initialize an array of blocks. - createGenesisBlock
The first block on the blockchain is called a genesis block. We add this block manually by calling the createGenesisBlock function.createGenesisBlock(){
The function returns a block with an index value, date of creation, any data (in this case we choose a string called Genesis Block) and a starting previousHash value of 0. All these values can be anything you want.
return new Block(0, “02/01/2018”, “Genesis Block”, “0”);
} - getlatestBlock
This is a really simple method which returns the latest block from the chain.getlatestBlock(){
return this.chain[this.chain.length — 1];
} - addBlock
This method adds a new block to the chain. However, we need to do a few things before a block can be added.
*
First we need to get the hash value of the previous block as follows:newBlock.previousHash = this.getlatestBlock().hash;
*
Then we need calculate the hash of the new blocknewBlock.hash = newBlock.calculateHash();
*
Now we can push this block to the chainthis.chain.push(newBlock);
*
Finally our method looks like thisaddBlock(newBlock){
newBlock.previousHash = this.getlatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
} - isChainValid
The most important property of the blockchain is it’s immutability. We use this method to verify the integrity of the blockchain. The method returns true if the chain is valid and false if the integrity of the chain is compromised.
In this method, we loop through the entire blockchain starting from the second block, since the first block is the genesis block and hence redundant.for(let i = 1; i < this.chain.length; i++)
{
//if something is wrong, then return false
} //else return true
*
We create two constants called currentBlock and previousBlock as follows in the for loop.const currentBlock = this.chain[i];
const previousBlock = this.chain[i-1];
*
In the for loop, we now check for validity of the hash calculations by tallying the currentBlock’s hash value in the chain with the calculated hash value of the currentBlockif(currentBlock.hash !== currentBlock.calculateHash())
*
{return false;}
Then we check whether the currentBlock points to the correct previousBlock. We do this by tallying the previousHash property of our current block with the previousBlock’s hash.if(currentBlock.previousHash !== previousBlock.hash)
{return false;}
*
If the blockchain passes through the for loop without returning a false value, we return true.return true;
*
Finally, this is how the isChainValid method looks like: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;
}
The Blockchain class now looks like this:
Step 5: Create a Blockchain
We can now create a blockchain. As promised, we’ll call it koreCoin :)
let koreCoin = new Blockchain();
We will add a few blocks to the koreCoin blockchain
We’ve just created a Blockchain.
Now it’s time for a stress test
Stress test
We’ll now check whether koreCoin performs as promised. First we log the data that the blockchain returns on the terminal by adding a console.log function in our blockchain code.
In the terminal app, go to the folder where you’ve saved your blockchain code and type the following commandnode main.js
Where main.js is the name of your blockchain file.
It will return a JSON somewhat like this
Tampering with the chain
Next we’ll attempt to tamper with the chain by changing the amount in one of the blocks. We will also check whether the validity of the chain by running a console log as follows
console.log(‘Is Blockchain valid? ‘ + koreCoin.isChainValid());
Result. On tampering with the chain and changing one of the values, the isChainValid function returns false implying that the chain is not valid.
Tampering with the chain smartly
When we tampered with the chain earlier, we changed the value of the data property of a block. This led to an incorrect calculation of the hash value and the chain was invalidated. What if we recalculate the hash value as well?
We’ll add the following lines of code
koreCoin.chain[1].data = { amount: 100 };
koreCoin.chain[1].hash = koreCoin.chain[1].calculateHash();
Result. On tampering with the chain and changing one of the values, the isChainValid function returns false implying that the chain is not valid. This is because even though we recalculate the hash value of the current block, it’s relationship with the previous block is broken. A hacker will have to recalculate the entire chain to edit or delete a value.
In case of a distributed blockchain like Bitcoin or Ethereum, the hacker would have to recalculate the hashes of all the blocks and it’s copies over the network to tamper with the blockchain even slightly. This would require the computing power of more than all the world’s supercomputers. This is practically impossible.
Read about Merkel trees to know more about how this works.
Congratulations! You have now implemented an almost immutable Blockchain on your machine.
Link to complete code
P.S. This was a proof of concept to understand how a blockchain works. The design of koreCoin lacks features like a peer to peer network, enabling rollback to a previous instance in case of tampering, etc. In reality we cannot add a new block so easily. There are numerous checks in place like ‘Proof of work’, ‘Proof of stake’ etc.
We will implement a proof of work going forward.
If you liked this article, please click the 👏 button (once, twice or more).
Share to help others find it!