Building a Simple Blockchain in JavaScript: From Scratch

Sandeep Singh
5 min readMay 5, 2023

--

Blockchain technology has been around for more than a decade and has become a revolutionary technology that is used in various industries. In simple terms, a blockchain is a distributed ledger that records transactions in a secure and transparent way. It is an open-source, decentralized database that is tamper-proof, immutable, and transparent.

In this blog post, we will learn how to create a simple blockchain in JavaScript.

Getting Started

To get started, we need to set up our environment. We will be using Node.js and npm to install our dependencies.

  1. First, create a new directory for our project and initialize it as a Node.js project using the following command in your terminal:
mkdir blockchain-js && cd blockchain-js
npm init -y
  1. Next, we need to install our dependencies. We will be using the crypto-js library to create our hashes and the express framework to create our API.
npm install crypto-js express --save

Building the Blockchain

Now that we have our environment set up, let’s create our blockchain. Our blockchain will consist of a chain of blocks that are linked together. Each block will contain a unique hash, the previous block’s hash, and some data.

Let’s create a Block class that will represent our block. Add the following code to a new file called block.js:

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

Here, we are importing the SHA256 function from the crypto-js library and defining our Block class. Each block has an index (which represents its position in the chain), a timestamp (which represents when it was created), some data, and a previousHash (which represents the hash of the previous block in the chain). The hash property represents the hash of the current block, which is calculated using the calculateHash function.

Next, let’s create our Blockchain class, which will represent our entire blockchain. Add the following code to a new file called blockchain.js:

const Block = require('./block');
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, '01/01/2021', '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;
}
}

The createGenesisBlock function creates the first block in our blockchain, which is also called the "genesis block". This block has a fixed previousHash value of "0".

The getLatestBlock function returns the most recently added block in our chain.

The addBlock function adds a new block to our chain. It sets the previousHash property of the new block to the hash of the most recently added block, and then calculates and sets the hash of the new block.

The isChainValid function checks the integrity of our chain. It loops through each block in the chain and checks that its hash is equal to the value returned by the calculateHash function. It also checks that the previousHash property of each block is equal to the hash of the previous block in the chain.

Creating an API

Now that we have our blockchain, let’s create an API to interact with it. We will be using the express framework to create our API.

Add the following code to a new file called server.js:

const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('./blockchain');
const app = express();
const blockchain = new Blockchain();
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.send(blockchain.chain);
});
app.post('/mineBlock', (req, res) => {
const newBlock = new Block(blockchain.chain.length, Date.now(), req.body.data);
blockchain.addBlock(newBlock);
res.send('Block mined successfully');
});
app.get('/isChainValid', (req, res) => {
const isValid = blockchain.isChainValid();
res.send({ isValid });
});
app.listen(3000, () => console.log('Server listening on port 3000'));

Here, we are importing the express and body-parser libraries and our Blockchain class. We are creating a new instance of Blockchain called blockchain.

We are defining three routes:

  • GET /blocks: Returns the entire blockchain.
  • POST /mineBlock: Adds a new block to the chain with the data provided in the request body.
  • GET /isChainValid: Checks the integrity of the chain and returns whether it is valid or not.

Finally, we are starting our server and listening on port 3000.

Testing our Blockchain

Now that we have our blockchain and API set up, let’s test it out.

  1. Start the server by running the following command in your terminal:
node server.js
  1. Open a new terminal window and use the curl command to make a POST request to add a new block to the chain:
curl -X POST -H "Content-Type: application/json" -d '{"data": "Hello, World!"}' http://localhost:3000/mineBlock

You should receive a response that says “Block mined successfully”.

  1. Use the curl command to make a GET request to retrieve the entire blockchain:
curl http://localhost:3000/blocks

You should receive a response that contains the block we just added.

  1. Use the curl command to make a GET request to check the integrity of the chain:
curl http://localhost:3000/isChainValid

You should receive a response that says the chain is valid.

Congratulations! You have created a simple blockchain in JavaScript and set up an API to interact with it.

Conclusion

In this blog post, we have learned how to create a simple blockchain in JavaScript using the crypto module and express framework. We have also set up an API to interact with our blockchain and tested it out using curl commands.

While this implementation is simple, it demonstrates the basic concepts of blockchain technology and how it can be applied in real-world scenarios. With further development and enhancements, this blockchain could be used for secure data storage, digital transactions, and more.

I hope you found this blog post informative and helpful in understanding blockchain technology in JavaScript. If you have any questions or feedback, feel free to leave a comment below if you like my work then you can buy me a coffee. Thank you for reading!

--

--