How To Build A Simple Cryptocurrency Blockchain In Node.js

By Jacob Dmn
Picture of the author
Published on
cryptocurrency illustration

Intro

Cryptocurrencies have become increasingly popular in recent years, with Bitcoin leading the charge. A blockchain is the foundation of any cryptocurrency, and understanding how it works is essential to understanding cryptocurrencies. In this article, we will walk through how to build a simple blockchain using Node.js, a popular server-side JavaScript runtime environment.


What is a Blockchain?

A blockchain is a decentralized, distributed ledger that records transactions across many computers in a secure and tamper-proof way. The ledger consists of blocks of transactions that are linked together in chronological order, forming a chain of blocks. Each block contains a cryptographic hash of the previous block, along with a timestamp and transaction data.


Building a Simple Blockchain in Node.js

We will start by creating a new Node.js project and installing the necessary dependencies. We will use the crypto-js library to perform hashing operations, and express.js to build a simple web server.

  1. Create a new directory for your project and initialize it with a package.json file:
  mkdir blockchain
  cd blockchain
  npm init
  1. Install the required dependencies:
  npm install crypto-js express
  1. Create a new file called block.js in the project root. This file will define the Block class, which will represent a block in our blockchain. Each block will have a timestamp, a data property, and a hash property.
const SHA256 = require('crypto-js/sha256')

class Block {
  constructor(timestamp, data, previousHash = '') {
    this.timestamp = timestamp
    this.data = data
    this.previousHash = previousHash
    this.hash = this.calculateHash()
  }

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

module.exports = Block
  1. Create a new file called blockchain.js in the project root. This file will define the Blockchain class, which will manage the blocks in our blockchain. The Blockchain class will have an array of blocks and methods to add new blocks and validate the blockchain.
const Block = require('./block')

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

  createGenesisBlock() {
    return new Block('01/01/2022', 'Genesis Block', '0')
  }

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

  addBlock(newBlock) {
    newBlock.previousHash = this.getLatestBlock().hash
    newBlock.hash = newBlock.calculateHash()
    this.chain.push(newBlock)
  }

  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
  }
}

module.exports = Blockchain
  1. Create a new file called main.js in the project root. This file will create a new instance of the Blockchain class and add some sample blocks to it. It will also define a simple web server that allows us to interact with the blockchain.
const express = require('express')
const Blockchain = require('./blockchain')
const Block = require('./block')

const app = express()
const port = 3000

const myBlockchain = new Blockchain()

myBlockchain.addBlock(new Block('02/01/2022', { amount: 4 }))
myBlockchain.addBlock(new Block('03/01/2022', { amount: 8 }))

app.get('/blockchain', (req, res) => {
  res.json(myBlockchain)
})

app.listen(port, () => {
  console.log(`Blockchain app listening at http://localhost:${port}`)
})
  1. Start the web server by running node main.js in the terminal. You should see the message "Blockchain app listening at http://localhost:3000".

  2. Open a web browser and go to http://localhost:3000/blockchain. You should see the JSON representation of the blockchain with the two sample blocks we added.


Congratulations! 🎉 You have just built a simple blockchain using Node.js. This is just a starting point, and there are many ways to extend and improve this blockchain. For example, you could add a proof-of-work algorithm to prevent spamming the blockchain with invalid blocks, or you could add transactions to the blocks to create a functioning cryptocurrency.


Did you enjoy reading?


Follow Me !

If you enjoyed this article, follow me on social media for more thoughts on full-stack development particularly in the web3 space!

Hi there! Want to support my work?

Buy Me A Coffee

Stay Tuned

Want to become a Web3 Pro?

The best articles, links and news related to web development delivered once a week to your inbox.