How to Create Your Own Cryptocurrency Blockchain in Node.js
Tags: cryptocurrency, blockchain, node, liveedu
Published: 2018-08-07 22:09:44

---
title: How to Create Your Own Cryptocurrency Blockchain in Node.js
published: true
description: 
tags: cryptocurrency, blockchain, node.js,liveedu
cover_image:  https://thepracticaldev.s3.amazonaws.com/i/9mocv9x04f5vlcfporf5.jpg
canonical_url: http://blog.liveedu.tv/how-to-create-your-own-cryptocurrency-blockchain-in-node-js/

---

(This article was originally published on my blog [here](http://blog.liveedu.tv/how-to-create-your-own-cryptocurrency-blockchain-in-node-js/) ).

The recent explosion of cryptocurrencies and their underlying blockchain technology has taken the world by storm.

As much as blockchain is a big buzz word these days, few people properly understand how the technology works to power the incredible growth of cryptos like Bitcoin and Ethereum.

Elliot Minns, who has more than six years of software development experience and currently teaches people skills on how to create cryptocurrencies, says that “making your hands dirty by learning how to create blockchain will assist you appreciate the technology and how it works.” 

You can check one of his practical-based projects [here](https://www.liveedu.tv/elliottminns/l3Xa0-how-to-create-your-own-cryptocurrency-in-c/).

In this article, we are going to explain how you can create your own simple blockchain in Node.js (and release it to the world, hopefully!). 

We’ll call it **liveEduCoin**. 

##Blockchains

A blockchain is a constantly increasing list of records, referred to as blocks, which are securely connected to each other using cryptography. 

The blocks are linked such that if any block within the blockchain is tampered with, the rest of the chain becomes invalid.

This immutability property is central to the growth of cryptocurrencies because it makes it difficult for people to alter their transactions after completing them. 

##Creating a block

As mentioned earlier, a blockchain comprises of several blocks that are connected to one another. Cryptographic hashes are used to maintain the integrity of the blockchain. 

Every block has a hash that is calculated based on its data. It also has the hash of the preceding block. If the hash of any block is changed, it would invalidate the rest of the blockchain.
 
Here is how a **Block** class would look like in Node.js:

```javascript
const SHA256 = require("crypto-js/sha256");
class Block {
    constructor(index, timestamp, data, previousHash = '') {
        this.index = index;
        this.previousHash = previousHash;
        this.timestamp = timestamp;
        this.data = data;
        this.hash = this.computeHash();
        this.nonce = 0;
    }
    computeHash() {
        return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();
    }
```

As you can see above, the **constructor** function, which instantiates the class, takes the following parameters:

+ index—it tracks the position of a block in a blockchain. 
+ timestamp—it places a timestamp of every transaction completed.
+ data—it provides information about the transactions completed, such as the quantity bought.
+ previousHash—it references the hash of the preceding block in the blockchain.

We used the computeHash function to generate the cryptographic hash of every block according to the above values. To do this, we imported the [crypto-js](https://www.npmjs.com/package/crypto-js) library and utilized its SHA256 hash function. 

The SHA256 is a strong, irreversible hash function that is used for ensuring the security of most cryptocurrencies.

To set up the crypto-js library, navigate to the terminal, and on the same folder as your project folder, install it using **npm**. 

Here is the code you can use:

```javascript

//remember to run npm init first
npm install --save crypto-js
```

##Creating the blockchain

Block-chain is based on a concept that the blocks are “chained” to one another. 

Therefore, we’ll begin chaining the blocks to each other in a **Blockchain** class. 
Here is the code:

```javascript
class Blockchain{
    constructor() {
        this.chain = [this.buildGenesisBlock()];
        this.complexity = 5;
    }
    buildGenesisBlock() {
        return new Block(0, "17/07/2018", "genesis block", "0");
    }
    obtainLatestBlock() {
        return this.chain[this.chain.length - 1];
    }
    addBlock(newBlock) {
        newBlock.previousHash = this.obtainLatestBlock().hash;
        newBlock.mineBlock(this.complexity);
        this.chain.push(newBlock);
    }
    }
```

As you can see on the above code, the class is composed of the following helper functions:

**a). Constructor function**

The blockchain is initialized by passing **buildGenesisBlock**. 

 **b). Building the genesis block**

In a blockchain, the genesis block is what signifies the start of the blockchain. This initial block doesn’t have any predecessors and the subsequent blocks are built on it. 

We’ll use the **buildGenesisBlock()** function to create it. 

**c). Getting the latest block**

To get the latest block in the blockchain, we’ll use the **obtainLatestBlock()** function. 

**d). Adding new block**

To add a new block to the blockchain Node.js example, we’ll use the **addBlock()** function. To achieve this, we’ll add the hash of the previous block to the new block—to maintain the blockchain’s integrity. 

Since we altered the details of the new block, it will be essential to compute its hash once more. After it is completed, we’ll push the block into the chain array. 

**e). Confirming the validity of the blockchain**

The **confirmValidity()** function is pivotal in assessing the integrity of the blockchain and ensuring that flaws are absent. This function employs a series of **if** statements to confirm whether the hash of every block is unaltered.

Additionally, it also checks if the hash values of every two successive blocks are pointing to each other. If everything is valid, it returns true; otherwise, it returns false. 

Here is the code:

```javascript
confirmValidity() {
        for (let i = 1; i < this.chain.length; i++){
            const currentBlock = this.chain[i];
            const previousBlock = this.chain[i - 1];
            if (currentBlock.hash !== currentBlock.computeHash()) {
                return false;
            }
            if (currentBlock.previousHash !== previousBlock.hash) {
                return false;
            }
        }
        return true;
    }
```

##Testing the blockchain

This is the most exciting section!

Here is the code:

```javascript
let liveEduCoin = new Blockchain();
console.log('<<Lets mine block 1>>');
liveEduCoin.addBlock(new Block(1, "27/07/2018", { quantity: 10 }));
console.log('<<Lets mine block 2>>');
liveEduCoin.addBlock(new Block(2, "27/07/2018", { quantity: 20 }));
```

We’ll create a new instance of the Blockchain class and name it **liveEduCoin**. 

Thereafter, we’ll add some arbitrary blocks into the blockchain. You can add any kind of data into the blocks. 

In this simple blockchain Node.js tutorial, we decided to add an object with the **quantity** property.

Here is the entire code for our blockchain project:

```javascript
const SHA256 = require("crypto-js/sha256");
class Block {
    constructor(index, timestamp, data, previousHash = '') {
        this.index = index;
        this.previousHash = previousHash;
        this.timestamp = timestamp;
        this.data = data;
        this.hash = this.computeHash();
        this.nonce = 0;
    }
    computeHash() {
        return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();
    }
    mineBlock(complexity) {
        while (this.hash.substring(0, complexity) !== Array(complexity + 1).join("0")) {
            this.nonce++;
            this.hash = this.computeHash();
        }
        console.log("Mining is taking place: " + this.hash);
    }
}
class Blockchain{
    constructor() {
        this.chain = [this.buildGenesisBlock()];
        this.complexity = 5;
    }

    buildGenesisBlock() {
        return new Block(0, "17/07/2018", "genesis block", "0");
    }

    obtainLatestBlock() {
        return this.chain[this.chain.length - 1];
    }

    addBlock(newBlock) {
        newBlock.previousHash = this.obtainLatestBlock().hash;
        newBlock.mineBlock(this.complexity);
        this.chain.push(newBlock);
    }

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

            if (currentBlock.hash !== currentBlock.computeHash()) {
                return false;
            }

            if (currentBlock.previousHash !== previousBlock.hash) {
                return false;
            }
        }
        return true;
    }
}

let liveEduCoin = new Blockchain();
console.log('<<Lets mine block 1>>');
liveEduCoin.addBlock(new Block(1, "27/07/2018", { quantity: 10 }));
console.log('<<Lets mine block 2>>');
liveEduCoin.addBlock(new Block(2, "27/07/2018", { quantity: 20 }));
```

If we save the code on a blockchain.js file and run it on the terminal, here is the output:

![cryptocurrency blockchain in Node.js](https://thepracticaldev.s3.amazonaws.com/i/iq4w64n1yhza0pgglrjr.jpg)

It works!

##Conclusion

The above cryptocurrency blockchain in Node.js is far from complete. In fact, if you go ahead and release it to the world, you can end up to be the only one using it!

For example, it lacks important tenets of a successful cryptocurrency such as proof-of-work and a peer-to-peer network.
 
Nonetheless, the blockchain node.js demo shows how a blockchain works. Contrary to what many people think, this simple project illustrates that the concepts of blockchain are simple and easy to implement.

Of course, if you are looking for a more advanced project to entirely immerse yourself in the world of cryptocurrencies, you can [click here](https://www.liveedu.tv/projects/premium/cryptocurrency/?q=crypto) to grab a tutorial from the LiveEdu website.