Javascript blockchain tutorial

Are you a big fan of cryptocurrencies? Do you fancy Javascript as much as I do? If that is the case, then you have reached the right place. In this tutorial we are going to study step by step how a cryptocurrency works and how we can use Javascript to build our own very tiny blockchain and cryptocurrency. This tutorial is intended to teach you how blockchain technology works and how we can use Javascript to implement our own version of Blockchain to create an online ledger. 

If you are not familiar with how a ledger works and how blockchain works. I strongly suggest you take a look at this video about a distributed ledger and how blockchain works. It's a 30 minute must-see explanation on cryptocurrencies and distributed ledger by the youtube channel 3blue1brown (a very good channel regarding IT and math knowledge) . If you don't know about cryptocurrencies or need a better understanding, this video will cover everything you need to start this tutorial.

before you begin

You need to understand the concept of a Hash Function, and you'll also need to have node js installed as well as an HTTP client, such as Postman or cURL. If you are not familiar with any of these don't worry. they are relatively easy to use. Regarding an IDE, you can use anyone you want, but I love Microsoft's Visual Code.

CMD your way into a folder and start your Node package with the command:

npm init

  • If at some point you feel lost with the code, at the end of this tutorial I will be providing the full code for the two files we are about to create. Remember to always npm install any packages that we use
    be zen, dont worry
    finished code is at the end of the document.

STEP 1 - Building the blockchain

Create a file and name it blockchain.js. We are going to be using two different files. One for the blockchain (blockchain.js) and one to represent the API that will serve as the blockchain node (index.js)

Representing the blockchain.

Our blockchain class requires two definitions, firstly, the definition of a block, and secondly the definition of the blockchain itself.

In order to create the hash, we will be using the crypto library for javascript. In your terminal, remember to run npm install crypto. More on that later. This is a basic block structure. As you can see we are using the new ES6 notation for classes.

About the getters

The getters and the setters are not really so necessary. Take into account that these project properties are initially not available in Javascript. (There is no such thing as public and/or private methods) and you cannot properly hide variables from javascript objects. However, we will be using them in order to keep the good practices.

About the block creation

This is an important thing to take into account. Whenever you create a new block in Javascript, it is very important to always create them in the same way in order to prevent inconsistent hashes. ¿What does this mean? The order of your variables within the scope of the block is not always ordered in the same way, and when you hash the block, if the order of the variables is different, then we will be having inconsistent hashes.  So, whenever we create a block, we must make sure that we use the constructor. We will not be using setters, since we will never be needing to modify a block once the block has been created (that is the whole point of the blockchain).​

The blockchain

Let's keep updating our blockchain.js file with the representation of our blockchain.

From now on, remember that the following methods are to be added within the blockchain class that we just created. The _chain parameter is going to be an empty [] array.  Whereas the _nodes we will use later to keep all of our nodes in order (we will be needing this later for our consesus algorithm).

When creating the blockchain, we will be adding the first Genesis block with the new_block(proof, previous_hash)  . Since this is our genesis block, there is no previous hash to validate and our proof (for the proof of work algorithm) will be a little bit different. More on this later. Bear in mind that all of these methods are to be written inside of the Blockchain class!!.

Adding transactions to a block

Our new_transaction() method is pretty straight forward. Once the transaction is added to the list, it returns the index of the block which the translation will be added to, or the next one to be mined.

The transactions [] list will contain all of the transactions that we have added to the block. Every time we create a new block, we must "flush" the list of transactions that we are currently keeping track of, since we are already inserting them in the block that we are adding to the blockchain.

At this point, the idea of a chain should be apparent—each new block contains within itself, the hash of the previous Block. This is crucial because it’s what gives blockchains immutability: If an attacker corrupted an earlier Block in the chain then all subsequent blocks will contain incorrect hashes.

If this makes sense for you, then you understand the core idea and the core principle behind blockchain.

Understanding proof of work

A Proof of Work ALgorithm (PoW) is the way new Blocks are created (or in this case, mined). The goal of PoW is to discover a number which solves a problem. This number that we have to find must be very difficult to find but very easy to verify computationally speaking - by anyone in the network. This is the core idea behind Proof of Work and it is what the consesus algorithm is built upon. The idea is not to trust any central authority, but to trust the computational power needed to make any chain valid. This is where hashing comes into place and why hash functions are so powerful and useful in this sort of situation. In our case we are using SHA256, which, given an input data , will return us a 256 bit string that will vary depending on the input in a completely random-like way.

The way proof of work works is relatively simple but yet powerful. PoW tries to make you solve a small puzzle that goes as follows:

Suppose we have a block that is ready to be inserted into the blockchain.  However, to validate the block computationally, we need to find a number X that, when added to the block and then hashed with the SHA256 algorithm, the resulting HASH will begin with N ceros. 

Since we know that SHA256 is a cryptographic function, meaning - for instance - that the number 393939 will output a completely different hash from 393940. There is no way that we can find out that number other than simply guessing each number one by one.

In bitcoin, the ammount of ceros varies and depends on the system and number of miners so that the expected time it takes to find that number is aproximately 10 minutes. In our case, we will be using 4 ceros. The more 0s we demand the string to start with, then the harder to find that number will be, and hence, the longer it will take for any computer to find the number..

blockchain and bitcoin


We will now implement a similar algorithm that we will use in our tiny blockchain. Our rule will be similar to the example we were talking about before.

  • Find a number p that when hashed with the previous block’s solution a hash with 4 leading 0s is produced.
    Our Basic proof of work

To adjust the difficulty of the algorithm, we could modify the number of ceroes, but for the time being, 4 will be sufficient. If you end up changing this value, you'll realize that the addition or removal of a single leading zero makes a big difference to the time that you need to find the answer to our small puzzle.

Our tiny blockchain is almost ready , let's keep firing the thing. One final step to make the whole thing work. Outside of the blockchain class , we need to add the following code snippet.

Why do we need to do this?

Well, since we are going to be exporting the module into another file, we need Javascript to understand this, hence we create an instance of the blockchain we just created and then we export it via module.exports so , when imported as a library from some other file, we have the blockchain ready to use. More on this later.

Our Blockchain as an API

In order to create our tiny blockchain, we will be using Express js as the framework to take care and handle the GET and POST requests. In order to do this, we will be creating the following methods.

Note: Remember to run npm install express​ to install the node modules required for the blockchain.

/transactions/new to create new transactions and add them to the block

/mine to tell our server to mine for a new block

/chain , or / ​ to simply return us the full blockchain.

Notice how we define the Blockchain variable from the requirement of the blockchain.js file and the Blockchain Variable directly is assigned to the Blockchain var we created and exported in the previous blockchain module. This is a nice and quick way of using dependency injection in our project.

Try to follow the code and  understand what's going on.  Our /mine endpoint checks if the Blockchain.last_block() returns a block or not. If the returned result is 0, then we assume that there is no proof . However, remember that when we created the Blockchain in the constructor , we already added the genesis block. 

Notice line 40 of our code. Check how we are adding a bitcoin ammount from the ledger to the miner. This bitcoin is given as a reward to the miner (hence the node_id being the recipient). 

The transactions endpoint

This is what the request for a transaction will look like.


"sender": "my address",
"recipient": "someone else's address",
"amount": 5


Interacting with our javascript blockchain

You can use cURL or Postman to interact with our little Blockchain API over our network.

Fire up the server by navigating through the command line to the blockchain folder and running node index.js 3000 

If you take a look at our code, we are making the app listen to the port that we instruct it to when whe invoke the program in the command line (line 58 of our little code).

 Let's try mining a block by making a GET request to http://localhost:3000/mine

Let’s create a new transaction by making a POST request to http://localhost:5000/transactions/new with a body containing our transaction structure:

blockchain image

If you aren’t using Postman, then you can make the equivalent request using cURL:

$ curl -X POST -H "Content-Type: application/json" -d '{
"sender": "d4ee26eee15148ee92c6cd394edd974e",
"recipient": "someone-other-address",
"amount": 5
}' "http://localhost:3000/transactions/new"

Try adding a couple of transactions and mining new blocks. Notice that when mining a new block, the request might take some time. This is due to the fact that the machine is still trying to figure out what the magic number is before the blockchain is completed. Try to play with our nodes and our transactions to check how the api checks with the blockchain.

Setting up the consensus

Before we can implement a Consensus Algorithm, we are going to need a way to let a node know about the other nodes in the network. Each node in our network should keep a registry of other nodes on the network. Thus, we’ll need some more endpoints:

/nodes/register to accept a list of new nodes in the form of URLs

/nodes/resolve  to implement our Consensus Algorithm, which resolves any conflicts to ensure that a node has the correct chain.

We will need to modify our Blockchain to provide for a method that allows to register nodes in our blockchain.

Note that we are using a set() to hold the list of our nodes. This is a very cheap way of ensuring that the addition of any new nodes is idempotent - this means that no matter how many times we add a specific node, it will appear exactly once.

Implementing the consensus algorithm

As we talked about before, a conflict is when one node has a different chain to another node. To resolve this, we'll make the rule that "the longest valid chain is authoritative". This is because if a chain is longer and still valid, then it must have more computational input power into it. Using this algorithm, we reach consensus algorithm amongst the nodes in our network.

Note our validation function. This method is responsbible for checking wether or not if a chain is valid by looping through each block and verifying both the hash and the proof.

On the other hand, resolve_conflicts() is a method with loops through all of the neighbouring nodes, downloads their chains and verifies them using the above method. If a valid chain is found with a greater length than the one the node has, then the chain is replaced.

We now need to add this consensus to the API endpoint. Let's head back to index.js

At this point, we can grab a different machine (or fire up several different nodes in our network. ). 

blockchain image

Registering a new node

And now you can add several blocks to each chain and check how they interact and how they update their blockchains. 

I hope you have enjoyed this tutorial and this inspires you to create new and attractive things. Let me know in the comments if you notice any bugs or mistakes. I'll follow up now with both complete codes just in case you got lost while adding or removing code to your blockchain as we moved along this tutorial.

There are many improvements that can be made to this tutorial, for example. Blockchains may need the ability to only download the latest X blocks of their chains instead of the whole chain.

Another noticeable improvement would be if you convert the blockchain into a hash table, that way, finding  specific nodes by their hash result would result in much faster operations. However, as a tutorial starting point this should be fine. Happy coding!

Full complete code

​Here are the codes for Blockchain.js and index.js

Our reader's favorite picks

Joomla Docker Tutorial - Create your first joomla docker container

Creating a Joomla Docker container.

Leave review
In this tutorial we are going to learn how to set up a docker container and...
Read More
Lamp Docker Tutorial

LAMP Docker Tutorial

Leave review
Today we bring you a small pill of knowledge with the hand of Docker for we...
Read More
If you want to work remote then don't make these mistakes!

If you want to work remote then don't make these mistakes!

Leave review
Read More
Telegram Creator acuses Whatsapp of having backdoors for syping

Telegram Creator acuses Whatsapp of having backdoors for syping

Leave review
According to Durov, Whatsapp has never been secure and it has been done lik...
Read More
How app development works in developing countries

How app development works in developing countries

Leave review
Read More
Using Redis and Node js 101

Node and Redis via Docker

Leave review
In this tutorial we are going to learn how to set up a small redis developm...
Read More
Suscribe to our mailing list

What is this about?

Our latest posts.

Javascript blockchain tutorial

Javascript blockchain tutorial

Leave review
Are you a big fan of cryptocurrencies? Do you fancy Javascript as much as I...
Read More
Creating business barriers when they don't exist

Creating business barriers when they don't exist

Leave review
he business question we are going to answer today is "How can one prevent o...
Read More
Joomla vs Wordpress

Joomla vs Wordpress

Leave review
In Hamro Dev we are experts in both Joomla and Wordpress, and in today's po...
Read More
How to use docker and wordpress

Wordpress and Docker Tutorial

Leave review
Using docker allows us to run all of our project straight in our own machin...
Read More
Using Redis and Node js 101

Node and Redis via Docker

Leave review
In this tutorial we are going to learn how to set up a small redis developm...
Read More

Related topics

Our categories.