Learn Blockchain by building it

Learn Blockchain by Building OneHow to create a simple blockchain using JavaScript[Blockchain] is the biggest opportunity set we can think of over the next decade or so.~Bob GreifeldIf you are in the tech industry, then it is almost certain that you ha…


This content originally appeared on Level Up Coding - Medium and was authored by Ankan Bag

Learn Blockchain by Building One

How to create a simple blockchain using JavaScript

[Blockchain] is the biggest opportunity set we can think of over the next decade or so.
~Bob Greifeld

If you are in the tech industry, then it is almost certain that you have heard about Blockchain technology. Blockchains are the underlying technology behind all Cryptocurrencies and most decentralized applications. They are also considered to be one of the most important inventions of this generation and quickly gaining popularity among the masses.

Blockchain is the technology that keeps track of all digital data or assets exchanged in the network and this record is called a “ledger”. Each data exchanged is the “Transaction” and every verified transaction gets added as a Block in the ledger. Think of blocks as a box that contains some data and multiple of these blocks are put together to form a blockchain. In the same analogy, the blockchain can be imagined as a container that holds multiple boxes.

Today we will learn how blockchain works by building it in JavaScript. But before we start programming, why should we learn it in the first place?

Why Blockchain?

Blockchain started in 2008 as a way to store and secure digital currency. It was a part of a proposal made for Bitcoin by Satoshi Nakamoto. And Bitcoin was the first application of the Blockchain network. One of its primary benefits is that the recorded information is can not be changed without an agreement between all the involved parties or nodes.

Other benefits include:

  • Decentralized: Transactions happen on a network of computers.
  • Immutability: If a transaction is created, it can not be modified
  • Open: All the transactions are visible to all the nodes.
  • Security: Due to the encryption feature, Blockchain is almost always secure

Now, we know about its features, Let’s start building our own blockchain from scratch using NodeJS.

Prerequisites

To follow and understand this tutorial you should be familiar with these:

  • Working knowledge of classes and other ES6 features in JavaScript.
  • NodeJS installed on the machine.

Getting Started with the Block

We mentioned blocks earlier as a box containing some useful information. I like to think about blockchain as a LinkedList (data structures) and each block in the blockchain as a node in the LinkedList. It can be represented as an object in JavaScript which contains the following properties:

  • Data to record on the blockchain, e.g., transaction data.
  • A block hash — which is the ID of the block generated using cryptography techniques.
  • The previous block’s hash in the chain. It is recorded in every block to link it to the chain and improve its security.
  • A timestamp of when the block was created and added to the blockchain.
  • Proof of Work (PoW), which is the amount of effort taken to derive the current block’s hash (we will be using this consensus since proof of stake is beyond this article).

Defining the Block Class having the above properties.

Calculating the hash of the Block

The hash of the block is the Identifier generated using the cryptographic technique. We will get the block hash by hashing the previous block hash, current block data, timestamp, and PoW using the SHA256 algorithm. We will use crypto, a built-in library of NodeJS for hashing the data.

In the above code, we did the following:

  • Converted the block’s data to JSON format so that we can concat it with other information as a string.
  • Concatenated the block’s previous hash, data, timestamp, and proof of work (PoW).
  • Generating the hash for the earlier concatenation with the SHA256 algorithm.
  • Returned the hashing result in base 16, with lowercase letters for A-F.

Mining new Blocks

Mining new blocks involve generating the block’s hash with a certain number of leading zeros (0s). The number of leading zeros is provided by the difficulty level of the current Blockchain. This means that if the blockchain has a difficulty of 3, we have to generate a block that starts with three zeros “000” e.g. “000f34abad….”.

Since we derived the hash from the block’s content we can’t change the content but we can certainly increase the proof of work (PoW) value until we satisfy the mining condition.

To implement this, we will create a mine() method for theBlock class that will keep incrementing the PoW value and calculating the block hash until we get a valid hash.

Define the Blockchain class

As we mentioned earlier blockchain is the collection of several blocks, the blockchain class will have three properties i.e. a genesis block, an array containing other blocks in the chain, and a number denoting the difficulty level. The genesis block is the first block added to the blockchain.

We have also declared a static method inside the Blockchain so that we can initialize a blockchain directly using a difficulty like const blockchain = Blockchain.create(2) — will create a Blockchain instance with a difficulty of 2 along with a genesis block.

Adding new blocks to the blockchain

We have successfully implemented the functionalities for our blocks to calculate their hash and mine themselves. Now let’s define a method inside the Blockchain class to add new blocks to the chain property.

Here we added the addBlockmethod to the prototype of the Blockchain class. It is similar to defining the addBlock method directly inside the class.

Explanation of the addBlock method:

  • Collects the details of a transaction (sender, receiver, and transfer amount) from the parameter.
  • Creates a new block with the transaction details.
  • Mines the new block with the mine method of the Block class.
  • Push the newly created block to the chain property of the blockchain.

Validating the Blockchain

Now that we have implemented all the functionality of our Blockchain, we need to check for the authenticity of the blockchain so that we can validate the blockchain has not been tampered with. We will add the isValid method to the Blockchain prototype.

Here we recalculated the hash of each block on the chain and compared them with the stored hash id in them and also compare the previousHash property of the next block that should be equal to the current block’s hash ID. Since the hash is calculated using the content of the block, a slight change in the content will generate a completely different hash value.

Testing the Blockchain

Since we have a fully functioning blockchain, let’s test all the features we have implemented so far. Add the test function in the files and run it using node <filename.js> from the command line.

The result should be similar to the image below but expect the hash value to be different since the timestamp will differ.

Bonus: Block time and difficulty adjustment

Block Time is the estimated time it takes for a new block to be added to the chain after mining. It is a constant value. Block time of some common platforms is 10 minutes for Bitcoin and around 13 seconds for Ethereum.

Bitcoin adjusts its block time for every 2016 block mined based on the time it took. At the desired rate of one block every 10 minutes, 2016 blocks would take exactly two weeks to find. If the previous 2016 blocks took more than two weeks to find, the difficulty is reduced else increased. The change in difficulty is in proportion to the amount of time over or under two weeks the previous 2016 blocks took to find. It goes like this →

new difficulty = old difficulty * (2016 blocks * 10 minutes) / mining time of the previous 2016 blocks

For our simple blockchain, we will adjust the difficulty if the new block takes more time than the block time. If it takes more time, we will reduce it by 1 else increase it by 1.

We will declare our block time to 10 seconds or 10000 milliseconds. Add the blockTime property on the Blockchain constructor and give it a fixed value like 10000. Then edit the addBlock method to adjust the difficulty after each transaction.

NOTE: Don’t forget to add the blockTime property to the Blockchain constructor. Otherwise, the code will throw an error.

Conclusion

Today we learned how blockchains work under the hood and how to create our own blockchain from scratch using JavaScript. The source code is available as a GitHub Gist including the difficulty adjustments. A more interactive code is available in the GitHub repository and it uses TypeScript-run the program in a terminal to interact with the blockchain we created today.

GitHub - ankanbag101/blockchain-demo: a bare minimum implementation of the blockchain technology

Next up: I will be writing about how to create a cryptocurrency utilizing the blockchain we learned today. Then make a peer-to-peer connected network and launch the currency (maybe). To get notified about the next tutorials, follow my account.

Happy Hacking!


Learn Blockchain by building it was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Ankan Bag


Print Share Comment Cite Upload Translate Updates
APA

Ankan Bag | Sciencx (2022-02-07T00:30:00+00:00) Learn Blockchain by building it. Retrieved from https://www.scien.cx/2022/02/07/learn-blockchain-by-building-it/

MLA
" » Learn Blockchain by building it." Ankan Bag | Sciencx - Monday February 7, 2022, https://www.scien.cx/2022/02/07/learn-blockchain-by-building-it/
HARVARD
Ankan Bag | Sciencx Monday February 7, 2022 » Learn Blockchain by building it., viewed ,<https://www.scien.cx/2022/02/07/learn-blockchain-by-building-it/>
VANCOUVER
Ankan Bag | Sciencx - » Learn Blockchain by building it. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/07/learn-blockchain-by-building-it/
CHICAGO
" » Learn Blockchain by building it." Ankan Bag | Sciencx - Accessed . https://www.scien.cx/2022/02/07/learn-blockchain-by-building-it/
IEEE
" » Learn Blockchain by building it." Ankan Bag | Sciencx [Online]. Available: https://www.scien.cx/2022/02/07/learn-blockchain-by-building-it/. [Accessed: ]
rf:citation
» Learn Blockchain by building it | Ankan Bag | Sciencx | https://www.scien.cx/2022/02/07/learn-blockchain-by-building-it/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.