BlockChain CryptoCurrency Development Node.JS

A blockchain is a digital record of transactions that is shared among nodes of a computer network, powering cryptocurrencies and many decentralized applications. The blockchain is an innovative, decentralized, and distributed public ledger that keeps a record of a growing list of transactions known as blocks.

Transactions on the blockchain are recorded and secured cryptographically, reducing potential flaws and vulnerabilities. The blockchain is made up of chain-like connections of different blocks, hence the name blockchain.

Even though it is in its infancy, the blockchain has found applications in many industries like finance, government, collectibles, DeFi, security, artworks like NFTs, and more. It has also created lots of opportunities and new jobs for developers, content writers, NFT creators, and more. The blockchain is very important when building decentralized applications because it ensures security and data integrity, building trust in users.

A cryptocurrency is a digitally secured virtual currency developed using cryptographic techniques. Cryptography ensures the security and integrity of the currency. In this tutorial, we’ll learn how to develop a cryptocurrency using Node.js, a popular JavaScript server runtime engine.

Node.js is a JavaScript backend environment that runs JavaScript code outside of the browser. In this article, we’ll introduce Node.js developers to the blockchain space by creating a simple cryptocurrency. Let’s get started!

To follow along with this article, you’ll need:

  • Node.js installed on your computer
  • A basic understanding of Node.js
  • A basic understanding of the blockchain technology
  • A code editor

Properties of a block

Earlier, we mentioned that the blockchain is composed of several blocks. Let’s explore what the properties of each block are. Every block in the chain is made up of the following properties:

  • Proof of work: The amount of computational effort required to get a block hash
  • Block hash: Block ID derived through cryptographic calculation
  • Timestamp: Time when the block was created
  • Index: Block’s position on the chain
  • Data recorded on the blockchain
  • The previous block’s hash

Installing dependencies

Since we’re building a cryptocurrency with Node.js, we need to first install the JavaScript crypto.js package in our project folder. Create a folder and name it nodejscrypto, as shown below:

\"Blockchain:

To install the package, run the following command in your terminal:

// create a package.json file
npm init -y

//install the crypto-js dependency
npm install crypto-js

We’ll use a single file for this project. Create a file in the project folder named nodejsCoin.js, as show in the image above.

Creating our first block

Now that we have our project structure set up with our package installed, let‘s create our first block and subsequently build our own cryptocurrency. Go ahead and copy the following lines of code into the nodejsCoin.js file:

//import that secure hash algorithm from the crypto-js package
const SHA256 = require(“crypto-js/sha256”);

//create a JavaScript class to represent a Block
class Block{
  constructor(index, timestamp, data, previousHash){
    this.index = index;
    this.timestamp = timestamp;
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.generateHash();
  }

  generateHash(){
    return SHA256(this.index + this.timestamp + this.previousHash + JSON.stringify(this.data)).toString()
  }
}

First, I imported the Secure Hash Algorithm (SHA256) from the crypto-js package, which helps us to encrypt our block hash ID. Then, I created a JavaScript Block class to represent a template for every block on the chain.

As with JavaScript and other object oriented programming languages like Java, whenever a class is created, a constructor method is called by default. Whenever the Block object is called using the new keyword, we call the constructor method and pass the parameters needed to create a new block.

Inside the constructor method, we assigned the values of the parameters, arguments, to the field. The this keyword signifies that we’re referring to the field name that come after it. Lastly, we created a generateHash() method that generates and returns the hash of the block using the properties defined in the constructor. Now that we’ve created our first block, let’s create the blockchain.

Creating the blockchain

The blockchain is a system for recording a collection of data in a chain-like way, increasing data integrity, reducing vulnerabilities, and making the data nearly impossible to be hacked.

More specifically, a blockchain is a distributed database that stores transactions in groups known as blocks. Let’s create a blockchain class that will manage the chain of of blocks:

class Blockchain{
    constructor(){
        this.blockchain = [this.createGenesisBlock()];
    }
    createGenesisBlock(){
        return new Block(0, \"11/04/2022\", \"first block on the chain\", \"0\");
    }
    getTheLatestBlock(){
        return this.blockchain[this.blockchain.length - 1];
    }
    addNewBlock(newBlock){
        newBlock.previousHash = this.getLatestBlock().hash;
        newBlock.hash = newBlock.generateHash();
        this.blockchain.push(newBlock);
    }

    // testing the integrity of the chain
    validateChainIntegrity(){
        for(let i = 1; i<this.blockchain.length; i++){
            const currentBlock = this.blockchain[i];
            const previousBlock = this.blockchain[i-1];
            if(currentBlock.hash !== currentBlock.generateHash()){
                return false;
            }
            if(currentBlock.previousHash !== previousBlock.hash){
                return false;
            }
            return true;

        }
    }
} 

From the code snippet above, we created a class, Blockchain and invoked the no-argument constructor method, a constructor without parameters or arguments. Within the constructor block, we assigned an array containing the method that creates the genesis block, createGenesisBlock(). A genesis block is the initial block in a blockchain, which you can link other blocks to. You can also refer to the genesis block as the ancestor block.

Every block created on the blockchain always references the previous block on the chain. But the genesis block has no reference, so we have to hardcode its properties within the createGenesisBlock() method. Notice how I called the new keyword on the Block constructor and passed the required arguments to create a block:

  • Index: 0
  • Timestamp: 11/04/2022
  • Data: First block on the chain
  • Hash: 0

The getTheLastBlock() method returns the latest block on the blockchain, helping us keep track of the current and the previous hash on the blockchain.

The next method is the addNewBlock() method, which takes a parameter called newBlock. In the method body, the hash of the latest block on the chain is set to be equal to the new block’s previous hash. On the next line, I used generateHash() to calculate the hash of the new block and finally push the new block onto the blockchain, which is an array of blocks.

The validateChainIntegrity() method checks the validity of the chain. One core characteristic of the blockchain is that it is irreversible. If any information on a block in the blockchain is tampered with, the blockchain integrity is affected. The validateChainIntegrity() method helps us to check the integrity of the blockchain.

We started our check at index one (1), whereas our blockchain started at index zero (0) with the genesis block, which was hardcoded. In this method, we loop through the blockchain, checking the validity of each block by checking if the hashes between two consecutive block are pointing to each other.

Create an instance to test our blockchain

Now, we’ll create an instance of the blockchain, our coin, which I call logCoin. You can give yours any name. Write the following code:

let logCoin = new Blockchain();
console.log(\"mining logcoin in progress...\");
logCoin.addNewBlock(
    new Block(1, \"06/04/2022\", {
        sender: \"Frank Joseph\",
        recipient: \"LogRocket\",
        quantity: 25
    })
);

logCoin.addNewBlock(
    new Block(2, \"08/08/2022\", {
        sender: \"Paul val\",
        recipient: \"Young A\",
        quantity: 34
    })
);

logCoin.addNewBlock(
    new Block(3, \"13/08/2022\", {
        sender: \"Elena\",
        recipient: \"Mary\",
        quantity: 34
    })
);
console.log(JSON.stringify(logCoin, null, 5))

Now, run the code with the following command in the terminal:

node nodejscoin

The output should be something like the image below:

\"Create

In the code snippets above, we created an instance of the blockchain class, with which we’re able to call or invoke the the addNewBlock() method. Remember that the addNewBlock() method takes an argument, so we passed a new block with indextimestamp, and data as objects that contain the following information: senderreceiver, and quantity.

Lastly, we printed the output by using the JavaScript console.log() and converted the output to a JSON file with the JSON.stringify() method, which takes three arguments in this case:

  • Value = logCoin: The value we’re converting to JSON
  • Replacer = null: Set to null to get all the properties of the blockchain array
  • Space = 5: Creates the space between each object on the array, making the resulting output readable

We’ve successfully created our basic cryptocurrency called logCoin. The complete code is below:

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

//create a JavaScript class to represent a Block
class Block{
  constructor(index, timestamp, data, previousHash){
    this.index = index;
    this.timestamp = timestamp;
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.generateHash();
  }

  generateHash(){
    return SHA256(this.index + this.timestamp + this.previousHash + JSON.stringify(this.data)).toString()
  }
}

class Blockchain{
    constructor(){
        this.blockchain = [this.createGenesisBlock()];
    }
    createGenesisBlock(){
        return new Block(0, \"11/04/2022\", \"first block on the chain\", \"0\");
    }
    getTheLatestBlock(){
        return this.blockchain[this.blockchain.length - 1];
    }
    addNewBlock(newBlock){
        newBlock.previousHash = this.getLatestBlock().hash;
        newBlock.hash = newBlock.generateHash();
        this.blockchain.push(newBlock);
    }

    // testing the integrity of the chain
    validateChainIntegrity(){
        for(let i = 1; i<this.blockchain.length; i++){
            const currentBlock = this.blockchain[i];
            const previousBlock = this.blockchain[i-1];
            if(currentBlock.hash !== currentBlock.generateHash()){
                return false;
            }
            if(currentBlock.previousHash !== previousBlock.hash){
                return false;
            }
            return true;

        }
    }
} 

let logCoin = new Blockchain();
console.log(\"mining logcoin in progress...\");
logCoin.addNewBlock(
    new Block(1, \"06/04/2022\", {
        sender: \"Frank Joseph\",
        recipient: \"LogRocket\",
        quantity: 25
    })
);

logCoin.addNewBlock(
    new Block(2, \"08/08/2022\", {
        sender: \"Paul val\",
        recipient: \"Young A\",
        quantity: 34
    })
);

logCoin.addNewBlock(
    new Block(3, \"13/08/2022\", {
        sender: \"Elena\",
        recipient: \"Mary\",
        quantity: 34
    })
);
console.log(JSON.stringify(logCoin, null, 5))

Conclusion

With that, we\’re successfully built our simple cryptocurrency using Node.js. In this tutorial, we learned the basic concepts of the blockchain, illustrated how to develop a block, and finally developed our own cryptocurrency on the blockchain.

Although our coin logCoin doesn’t meet the cryptocurrency market standard, we’ve garnered from this tutorial the foundational knowledge required to get started as a blockchain developer. I hope you enjoyed this article, and be sure to leave a comment if you have any questions.

Leave a Comment

Your email address will not be published.

%d bloggers like this: