Skip to content Skip to sidebar Skip to footer

The term “blockchain” has been bandied about a lot in the last decade. Many cryptocurrencies are built on top of this foundational technology, which is widely regarded as one of the most significant discoveries of the twenty-first century.

Is it ok if you’ve heard of blockchain but aren’t quite sure what it is? Using only 40 lines of code, I’ll demonstrate how the Blockchain works in this article.

It’s critical to understand the process by which blockchains are created and maintained.

Each block contains the following information:

  • Data: this could be anything like transaction data
  • Hash Value: this is basically the ID of the block
  • Previous Hash Value: this keeps track of the previous block ID. For now, you just need to know that we use this value to form a chain between the current block and the previous block
  • Timestamp: this tells us when the block is created
  • Proof of Work: this is a number showing the effort to find the hash value of the current block. If you have heard of mining, this value represents how long it takes (in form of a number) for the machines to calculate the hash value

Creating Block class

Let’s create a class called “Block” inside an empty index.js file.

class Block {
  constructor(poreviousHash,data) {
    this.data = data;
    this.hash = this.calculateHash();
    this.previousHash = previousHash;
    this.timeStamp = new Date();
    this.proofOfWork = 0;
  }
}

This class’ constructor accepts 2 arguments. The first one is the hash value of the previous block, and the second one is the data of the current block.


Inside the constructor, we initialize the block data with the constructor arguments. We set timeStamp to the current time and proofOfWork to 0.
The hash value is not just a random string, we need to find the current hash value based on both current data and previous hash for security sake.


If a hacker changes the data of a block, they also have to recalculate hash values of all the blocks ahead to make the chain valid (this might take thousands of years if they use the same computer as I do).
For those who don’t know about hashing, it’s basically how we convert our data into a bunch of random characters.

For example, the word “hello” could be hashed into “e2d48e7bc…”. Because hashing only works in one direction, it’s easy to find the hash output given the input but it’s super hard to predict the input from the hash output.


Let’s take a look at the calculateHash function.

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

class Block {
  constructor(previousHash, data) {
}

  calculateHash() {
    return hash(
      this.previousHash +
        JSON.stringify(this.data) +
        this.timeStamp +
        this.proofOfWork
    ).toString();
}

This function basically generates a hash value based on the combination of the previous hash, current data, current timestamp, and proof of work.


We use the hash function from crypto-js npm package. This package basically allows us to use several hashing methods. We use Secure Hash Algorithm 256 (SHA 256) in this tutorial. As you can see, we import hash at the top of the file.


Let’s look at the final function of the Block class. The mine function.

class Block {
  constructor(previousHash, data) {
}

calculateHash() {
}

mine(difficulty) {
  // find the hash
  while (!this.hash.startsWith("0".repeat(difficulty))) {
     this.proofOfWork++;
     this.hash = this.calculateHash();
  }
 }
}

This mine function keeps increasing proofOfWork until we found a hash starting with our desired number of 0 (we called it difficulty). The higher difficulty is, the longer it takes for the hash to be created. This is because the only way to find the input from the hash output is to try different inputs one by one.

Fun fact: The hash value of a Bitcoin block requires 18 zeros, which takes about 10 minutes for all the computers in its blockchain network to create.

If you have heard people talking about mining crypto, this is how it works under the hood. They invest in powerful machines to calculate the hash for a new block and receive crypto as reward.

Imagine if creating a hash was simple and fast, data stored in the blockchain would be easily changed. Therefore, the hash value is created in such a complex way so that even if a block is hacked, it will take forever to update all the following blocks. This is why Blockchain is so secure.

The next part is creating the Blockchain to store all the blocks.

Creating Blockchain class

class Blockchain {
  constructor() {
    let genesisBlock = new Block("0", { isGenesis: true });
    this.chain = [genesisBlock];
  }

Our Blockchain store 1 array called chain . We will also add a genesisBlock to the chain. The genesis block is basically the first block in the chain. Therefore, we could pass “0” as the previous hash value as there’s no previous block.

Next, we will implement addBlock function which adds a new block to the chain.

class Blockchian {
  constructor() {
  }

  addBlock(data) {
    let lastBlock = this.chain[this.chain.length - 1];
    let newBlock - new Block(lastBlock.hash, data);
    newBlock.mine(2);
    this.chain.push(newBlock);
  }

This function accepts new data as a parameter and creates a new block based on that data and the previous block’s hash.

When we create a new block, we have to calculate its hash value using the mine function. To make it fast, I only set the diffifulty to 2 so the new hash value must start with 2 zeros.

After finding the hash value, we just need to add the new block to the chain.

Finally, we need isValid function to validate if the current chain is valid or not.

class Blockchain {
  constructor() {
}

  addBlock(data) {
  }

  isValid() {
    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;
   }
}

This function basically goes through each block (except the genesis one) and checks if there is any violation in the hash value. It returns true if there is no violation.

Congratulations, you have successfully built a blockchain 🙂

Usage Example

Let’s try to add 2 new blocks which contain transitions information to our blockchain.

let blockchain = new Blockchain();

blockchain.addBlock({
  from: "Alex",
  to: "Bobes",
  amount: 1000,
});

blockchain.addBlock({
  from: "Alex2",
  to: "Bobes2",
  amount: 100,
});

Leave a comment

> Newsletter <
Interested in Tech News and more?

Subscribe