Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 29, 2021 02:27 am GMT

Creating a blockchain in 60 lines of Javascript

In recent years, cryptocurrencies and blockchains are two uprising fields, so today, I will share my way of creating a blockchain in Javascript in just 60 lines of codes. I'm still new to the field, if I'm wrong with something, please remind me in the comment section.

What is a blockchain?

Before we do any coding, we need to understand what a blockchain is. Technically, a blockchain at its bare minimum is just a list containing objects that have some basic information on it like timestamp, transactions, hash,... Its data must be immutable and unhackable. Modern platforms like Ethereum, Cardano, Polkadot,... have way more complex stuff, but we are staying simple in this article.

Setup

We are using Node.js for this project, so be sure to install it if you haven't.

Throughout the article, I will be using the object-oriented programming style, so I expect you to know basic knowledge about it.

Creating a block

As I have said, a block is just an object that has some information on it, so we should have a Block class like this:

class Block {    constructor(timestamp = "", data = []) {        this.timestamp = timestamp;        // this.data should contain information like transactions.        this.data = data;    }}

So we have our timestamp and data, but a blockchain needs immutability. We can gain that effect by using a hashing function that hashes all of our properties in the block. I suggest reading about hasing on wikipedia, it plays an essential role in a blockchain.

I'm using the sha256 algorithm. To implement its hashing function, I'll just going to use the Nodejs' built-in crypto package:

const crypto = require("crypto"), SHA256 = message => crypto.createHash("sha256").update(message).digest("hex");

The above code should give us what we wanted, but if you want to know how it works, check out Node.js's official doc about the hash class.

We should have something like this:

// Get the sha256 hash function.const crypto = require("crypto"), SHA256 = message => crypto.createHash("sha256").update(message).digest("hex");class Block {    constructor(timestamp = "", data = []) {        this.timestamp = timestamp;        this.data = data;        this.hash = this.getHash();        this.prevHash = ""; // previous block's hash    }    // Our hash function.    getHash() {        return SHA256(this.timestamp + JSON.stringify(this.data));    }}

The prevHash property also plays a big role in immutability, it ensures that the blocks will stay unchanged along the blockchain's lifespan. It contains the hash of the previous block. You can see that it's empty, but we will do something with it later in this article.

The blockchain

Let's move over to the blockchain class.

Like I have said, a blockchain is a list with blocks, so we can have a basic form like this:

class Blockchain {    constructor() {        // This property will contain all the blocks.        this.chain = [];    }}

You must have a genesis block, which is technically just the first block:

class Blockchain {    constructor() {        // Create our genesis block        this.chain = [new Block(Date.now().toString())];    }}

Just for convenience, I'll create a function to get the latest block:

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

Now, we should have a way to add a block to the blockchain.

    addBlock(block) {        // Since we are adding a new block, prevHash will be the hash of the old latest block        block.prevHash = this.getLastBlock().hash;        this.chain.push(block);    }

Validation

We need to know whether the chain is still valid or not, so we need a method to check validation. The chain is valid if a block's hash is equal to what its hashing method returns, and a block's prevHash property should be equal to the previous block's hash.

    isValid() {        // Iterate over the chain        for (let i = 1; i < this.chain.length; i++) {            const currentBlock = this.chain[i];            const prevBlock = this.chain[i-1];            // Check validation            if (currentBlock.hash !== currentBlock.getHash() || prevBlock.hash !== currentBlock.prevHash) {                return false;            }        }        return true;    }

Proof-of-work

Turns out, hash and prevHash still have caveats, people can modify a previous block in the chain and then recompute each of the following blocks to coin out another valid chain, and we would also like to implement a way for users to come to a consensus on a single chronological history of the chain in the correct order in which the transactions were made. Bitcoin and many other cryptocurrencies have a proof-of-work system to solve this problem.

The system makes it much harder to perform the work required to create a new block. If you want to modify the previous block, you would have to redo the work of the block and all of the blocks that follow it. It requires scanning for a value that starts with a certain number of zero bits when hashed. The value is called the nonce value, the number of leading zero bits is known as the difficulty. By increasing the difficulty, it gets harder and harder to mine, and we can prevent modifications to the previous blocks because doing all the work again but still catching up to others is impossible.

We can implement this system by adding a mine method and a nonce property to our block:

class Block {    constructor(timestamp = "", data = []) {        this.timestamp = timestamp;        this.data = data;        this.hash = this.getHash();        this.prevHash = ""; // previous block's hash        this.nonce = 0;    }    // Our hash function.    getHash() {        return SHA256(this.timestamp + JSON.stringify(this.data) + this.nonce);    }    mine(difficulty) {        // Basically, it loops until the substring of the hash with length of 0, <difficulty>        // until it is equal to the string 0...000 with length of <difficulty>        while (this.hash.substring(0, difficulty) !== Array(difficulty).join("0")) {            // We increases our nonce so that we can get a whole different hash.            this.nonce++;            // Update our new hash with the new nonce value.            this.hash = this.getHash();        }    }}

Moving over to the Blockchain class, we should create a difficulty property:

    this.difficulty = 1;

I will set it to 1, the difficulty should update based on how many blocks mined.

We must update the addBlock method from the Blockchain too:

    addBlock(block) {        block.prevHash = this.getLastBlock().hash;        block.mine();        this.chain.push(block);    }

Now, all blocks need to be mined before being added to the chain.

Quick note

Because we are staying simple, so I used the proof-of-work system for this blockchain. Note that most modern blockchains use a way better system called proof-of-stake (or many of its upgraded variations).

Testing out the chain!

Create a new file, that file will be the entry file.

Let's use our freshly created blockchain! I'll call it JeChain for now.

const { Block, Blockchain } = require("./your-blockchain-file.js");const JeChain = new Blockchain();// Prints out the chainconsole.log(JeChain.chain);// Add a new blockJeChain.addBlock(new Block(Date.now().toString(), { from: "John", to: "Bob", amount: 100 }));// (This is just a fun example, real cryptocurrencies often have some more steps to implement).// Prints out the updated chainconsole.log(JeChain.chain); 

It should look like this:

Image description

Source code

You can get the full source code here.

Honorable mention

I have learnt a lot about blockchains from Simply Explained. Please check them out on Youtube, they have really good blockchain tutorial series.

I also grabbed some info on this article too. Check them out!

Off-topic

Should I continue the series? And if yes, what should I write about? Proof-of-stake? Full cryptocurrency? Smart contracts? Please let me know in the comment section.


Original Link: https://dev.to/freakcdev297/creating-a-blockchain-in-60-lines-of-javascript-5fka

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To