DSC RNGPIT
Published in

DSC RNGPIT

Build a simple Blockchain in Javascript

Easy way to comprehend how Blockchain work is to build one

Psyched about the rise of Cryptocurrencies ? And you want to know how Blockchain work — the fundamental technology behind it. After all, they are the trending and media’s favorite topics these days — the buzzwords of the year.

Comprehending Blockchain is not easy — or was not for me also! I go through tutorials, videos and dealt with the amplified frustration.

I like acquiring knowledge by doing. It forces me to deal with the subject matter at a code level. If you do the same, at the end of this guide you’ll have a functioning Blockchain with a solid grasp of how they work.

What is Blockchain ?

A blockchain, in simple terms, is a distributed database that maintains an immutable record of all transactions on a blockchain network. Blockchain is a distributed data structure comprising a chain of blocks. The transactions are timestamped and bundled into blocks where each block is identified by its cryptographic hash.

You can consider blockchain as just a book.

Blocks in a chain = Pages in a book

For analogy, a book is a chain of pages. Each page in a book contains:

The text: for example the story.

Information about itself: At the top of the page there is usually the title of the book; At the bottom is usually the page number which tells you where you are in the book. This ‘data about data’ is called Meta-data.

Similarly in a blockchain, each block has:

The contents of the block; for example : transactions

A ‘index’ which uniquely define the block.

A reference to the previous block, and a fingerprint (hash) of the data contained in this block, among other things.

Before you begin…

We assume that the reader is familiar with the Node.js and understood blockchain concepts, hash, as well as have understanding of how HTTP requests work, as we’ll be talking to our Blockchain over HTTP.

What will you need ? Ensure that Node.js is installed. Oh, you’ll also need an HTTP Client, like Postman.

Final source code ? Available here !

STEP 1 : Building A Blockchain

We are going to create a blockchian for a node only. Open up your favorite code editor or IDE, personally I ❤️ Atom. Create a new file, called blockchain.js.

Representing a Blockchain

We’ll create a Blockchain function which creates an initial empty list (to store our blockchain), and another to store transactions. Here’s the blueprint for our class:

Let’s start flashing out some methods.

How a block looks like ?

Each Block has an index, a timestamp, a list of transactions, a nonce, and the hash of the previous Block and current block.

Here’s an example of what a single Block looks like:

Each block contain the hash of previous block, which makes the information contain in the chain immutable. If an attacker tries to corrupt a block, all the subsequent blocks will contain incorrect hashes.

Create new Block

When our Blockchain is initiated we’ll need to seed it with a genesis block—the first block of the chain. We’ll also need to add a “nonce” to our genesis block which is the result of mining (or proof of work). We’ll talk more about mining later.

In addition to creating the genesis block, we’ll also flesh out the methods for createNewBlock(), getLastBlock() and hashBlock():

Create a new transaction

We’ll need a way of adding transactions to a Block. Our createNewTransaction() method is responsible for this, and it’s pretty straight-forward:

After createNewTransaction() adds a transaction to the list, it returns the index of the block which the transaction will be added to—the next one to be mined. This will be useful later on, to the user submitting the transaction.

We’re almost done with representing our blockchain. But at this point, you must be wondering how new blocks are created, forged or mined.

Understanding Proof of Work

A proof of work algorithm (PoW) confirms the transaction and produce a new block in chain. We can set some indexes of hash value of the blocks. Such as, we can set hash value followed by first four ‘0000’, so now our hash value becomes ‘0000rjzlvn…’. Now, assume if someone tries to change data of blocks then that modified data directly affect the hash value. Hence, hash value of modified data changed and it is not match with our condition as above. So that modified data is not allowed by the block chain and any block should not be accepted until it fulfil the condition of ProofofWork method.

With PoW, miners compete against each other to complete transactions on the network and get rewarded.In general, the difficulty is determined by the number of indexes set in a hash value.

Implementing basic Proof of Work

Let’s implement a similar algorithm for our blockchain. Our rule will be similar to the example above:

Find a number ‘nonce’ that when hashed with the previous block’s solution a hash with 4 leading 0's is produced.

To increase the difficulty of the algorithm, we can modify the number of leading zeroes. You’ll find out that the addition of a single leading zero makes a mammoth difference to the time required to find a solution.

Our class is almost complete and we’re ready to begin interacting with it using HTTP requests.

STEP 2 : Accessing the blockchain through API

We’re going to use the express Framework. Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications and it makes it easy to map endpoints. This allows us talk to our blockchain over the web using HTTP requests.

Install express using following command :

npm install express --save

We’ll create three methods:

  • /blockchain to return the entire Blockchain.
  • /transaction to create a new transaction in a block
  • /mine to tell our server to mine a new block.

Building API foundation :

Our “server” will form a single node in our blockchain network. Create a new file, called networkNode.js. Let’s create some boilerplate code:

The Transaction Endpoint

This is what the request for a transaction will look like. It’s what the user sends to the server:

{
"amount": 5;
"sender": "own address";
"recipient": "someone else's address"
}

Since we already have our method for adding transactions to a block, the rest is easy. Let’s write the function for adding transactions:

The Mining Endpoint

Our mining endpoint is where the magic happens, and it’s easy. It has to do three things:

  1. Calculate the Proof of Work
  2. Reward the miner (us) by adding a transaction granting 12.5 us coin
  3. Forge the new Block by adding it to the chain

At this point, we’re done, and can start interacting with our blockchain.

STEP 3 : Interacting with our Blockchain

You can use Postman to interact with our API over a network.

Fire up the server:

$ npm start
Running on http://localhost:3000/

Let’s create a new transaction by making a POST request tohttp://localhost:3000/transaction with a body containing our transaction structure:

Post request using POSTMAN

Let’s mine above requested transaction in a block making a GET request to http://localhost:3000/mine

GET request using POSTMAN

Let’s inspect the entire chain by requesting http://localhost:3000/blockchain in a browser

Entire blockchain

Amazing ! We’ve got a basic Blockchain that accepts transactions and allows us to mine new Blocks.

I hope that this has inspired you to create something new. I’m corny about Cryptocurrencies because I believe that Blockchain will rapidly change the way we think about economies, governments and record-keeping.

If you enjoyed this guide, or have any suggestions or questions, let me know in the comments. And if you’ve spotted any errors, feel free to contribute to the code here!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store