Blockchain with JavaScript

Spread the love

In this tutorial, we at Rpc Technology will write a very small blockchain in JavaScript. It won’t be long or complicated, but it will be more than enough to give you a very good idea on how to build a blockchain with JavaScript and how a blockchain works.

We will name this Blockchain RpcHost, so Let’s start our tutorial;

Blockchain with Javascript

Set up the Blockchain

First We’ll begin by creating a new JavaScript file to store in it all the created code. We will name it start.js and now we begin to define a blockchain and blocks.

We begin with creating a BLOCK class with a constructor. When you first create a new block, you need to pass it a parameter timestamp, as well as some data and the hash of the block:

class Block{
  constructor(timestamp, data, previousHash = '') {
    this.previousHash = previousHash;
    this.timestamp = timestamp; = data;

Definition of every property:

  • The timestamp means when the block was created. In this tutorial we will use UNIX timestamp.
  • The data parameter can contain any type of data that will be associated with this block. If this Blockchain is for cryptocurrency you can save transaction details like sender/receiver and the transferred amount of money .
  • The previousHash is a string that contains the hash of the previous block. The previousHash is the chain that will join the blocks and will preserve the integrity of our blockchain.

Each block points towards the previous block (previousHash attribute), what means that each block needs a hash.

A hash is like a fingerprint. Every block has its own fingerprint or identity (hash). The hash of a block is calculated by taking the contents of the block and applying a hash function to this block content.

We will write a routine that can calculate the hash of the current block.
Inside the Block class, we create a  CalcHash function:

CalcHash() {
    return SHA256(this.previousHash + this.timestamp + JSON.stringify(;

Remember that we choose to use the SHA256 hash function. However, the SHA256 hash is not available in JavaScript and we should use an external library in order to make this SHA256 hash available in JavaScript. crypto-js is a library containing implementations for various hashes. Install it with npm like this:

npm install crypto-js

After that we can import it in main.js file:

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

CalcHash() routine can be used now in the constructor of the Block:

class Block{
  constructor(timestamp, data, previousHash = '') {
    this.previousHash = previousHash;
    this.timestamp = timestamp; = data;
        // When creating a new Block, automatically calculate its hash.
    this.hash = this.CalcHash();

Blockchain class

After creating a Block, we can define now the Blockchain. A new Blockchain class :

class Blockchain{
  constructor() {
    this.chain = [];

In this example, the blockchain is just an object that contains a property chain. chain is an array containing all the blocks on the chain.

Before we add any new blocks, we should add a “genesis block”. A “genesis block” is the first block on the chain and because it is the first block it cannot point to a previous hash (block).

GenesisBlock() is a method to create the first block on a chain

  return new Block("01/01/2021", "Create Genesis block", "0");

In the constructor of Blockchain class, we add the the GenesisBlock() method :

class Blockchain{
  constructor() {
    this.chain = [this.GenesisBlock()];

Additional Blockchain functions

We can add new functionality to the Blockchain class to allow to create new blocks and to return the latest element (block)

The getLatestElement method will return the last element on the chain array:

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

The InsertBlock method will add a new block to the chain, but before adding new block we have to set the previousHash property of that block. It has to be set to the hash of the latest block on our chain. And we also have to calculate the hash of the new block:


    // The new block needs to point to the hash of the latest block on the chain.
  newBlock.previousHash = this.getLatestElement().hash;
    // Calculate the hash of the new block
  newBlock.hash = newBlock.CalcHash();

    // Now the block is ready and can be added to chain!

Blockchain testing

In order to test, we need create an instance of the blockchain

let RpcHost = new Blockchain();
RpcHost.addBlock(new Block("20/08/2021", { amount: 5 }));
RpcHost.addBlock(new Block("22/08/2021", { amount: 10 }));

After we created new blocks, we will stringify RpcHost Blockchain to see how it looks like;

console.log(JSON.stringify(RpcHost, null, 5));

The output is what our blockchain looks like. The blockchain contains a property an array, which contains the blocks.

Blockchain integrity verification

Blockchains are amazing models because once a block is inserted, it cannot be edited without braking the rest of the chain.

Let us add a new method to our blockchain, called isBlockChainValid. This will return true if the chain is valid or false if something is wrong:


In order to verify the integrity, we need to iterate over the entire chain, and while looping we need to check the following:

  • Block’s hash still valid? To check this validity we will recalculate the hash of each block. If any element changed inside a block, then the hash will be changed of that block it will change the hash of that block.
  • Every block point to the correct previous block? To check this, we will see if the previousHash of the block, equals the hash property of the block that went before it.
  • Is the genesis block still intact?

Here is the full program routine:

  for (let i = 1; i < this.chain.length; i++){
    const currentBlock = this.chain[i];
    const previousBlock = this.chain[i - 1];}

    // Recalculate the hash of the block.
    if (currentBlock.hash !== currentBlock.CalcHash()) {
      return false;

    // Check if this block points to the previous hash(Block)
    if (currentBlock.previousHash !== previousBlock.hash) {
        	return false;
    // Check the genesis block
    if(this.chain[0] !== this.GenesisBlock()){
    	return false;
    // Chain is valid!
    return true;

Blockchain integrity test

Test the blockchain integrity:

console.log('Blockchain valid? ' + RpcHost.isBlockChainValid());

Now, if we try to change our blockchain. Let’s change block 2 and edit its content(data) (for example change 5 to 100):

// Change the chain!
RpcHost.chain[1].data = { amount: 100 };

// Check validity
console.log('Blockchain valid? ' + RpcHost.isChainValid()); // will return false!


It is a really simple and easy Blockchain we just created it, it can add new elements(blocks) and detect if someone change the data inside the chain, and it will invalidate the Blockchain if data changed or manipulated.

Leave a Comment

Your email address will not be published. Required fields are marked *