Understand the basics.
Pre-requisites: Some rudimentary knowledge of OOPs in JavaScript.
We are using Node for this exercise. You could use Python or Go for the same, but I am using this since I am going to show you how to integrate this with your Node app. I take heavy inspiration from Savjee, I am using his series on blockchain as inspiration and putting my best understanding out there.
If you don't have Node, feel free to install it from your favorite package manager or the internet. A little bit about Node first: Node is JavaScript outside of your browser. You don't need script tags to run this JS, all you need to do is-
node filename.js
This is because some madlad took Chrome's V8 engine out of Chrome and wrapped it in C and served us Node. Talk about *Jugaad.*
The first thing you'll need to do is make a new directory and CD into that. Then you need to init an NPM package, and create an index.js file.
mkdir blockchain-example
cd blockchain-example
npm init -y
vi index.js
I am using Vim because I am terribly lazy, feel free to use any text editor of choice. Now let's talk a little bit about what a blockchain is before we delve further into code. The best explanation I have read is this article by IHODL.
To quote from their website-
Blockchain is a distributed database existing on multiple computers at the same time. It is constantly growing as new sets of recordings or blocks, are added to it.
Each block contains a timestamp and a link to the previous block, so they actually form a chain.
The database is not managed by any particular body; instead, everyone in the network gets a copy of the whole database.
All blocks are encrypted in a special way, so everyone can have access to all the information but only a user who owns a special cryptographic key is able to add a new record to a particular chain.
In addition, cryptography is used to guarantee synchronization of copies of the blockchain on each computer (or node) in the network.
Read more at their website.
https://www.researchgate.net/figure/Simple-example-of-blockchain-technology_fig4_325486515
Look at the diagram above. All transactions are stored in Blocks, so every one knows what data is being transacted. Now before you are up in arms about security, this data is not open for everyone to see (It is in very few cases!). They are hashed, as we will see. You can only verify this transaction, verifying means that they can't be tampered with. For simplicity, these transactions are shown as currency here, but they could be any data.
Let's jump into code and from there explain a little here and there?
const sha256 = require('sha256');
class Block {
constructor(index, timestamp, data, prevHash) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.thisHash = sha256( this.index + this.timestamp + this.data + this.prevHash );
}}
Do you understand what happened? We made a goddamn block. This is the fundamental logic behind every blockchain unicorn founder that got rich. Pay attention.
First, we import SHA256, it's an encryption algorithm. As I said, it's to encrypt the data.
The class BLOCK is a block template we will use for every block.
Each block will have five elements: index, timestamp, data, Previous Hash and Present Hash.
For CryptoCurrencies (esp the earlier ones like Bitcoin), the data is the address of the sender, receiver of bitcoin and amount of Bitcoin transacted.
Now that you know what One block looks like, I am sure you have a better understanding. Let's move on to what would we do about the first block, right? Since our first block has no Previous Hash!
We create something called the Genesis Block.
All of this will come under a class called blockChain.
const createGenesisBlock = () => new Block(0, Date.now(), 'Genesis Block', '0');
What it do? Simple. Create an instance of the class with 0 as the index, present date as date, 'Genesis Block' as data (You can keep this as anything as long as you remember what your initial block is named) and 0 as the previous hash.
We will need two functions: getLatestBlock() and calculateHash().
getLatestBlock() {
return this.chain[this.chain.length - 1];}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();}
getLatestBlock() fetches the latest block from the chain. Out of context it might be confusing, check the GitHub, you'll get a better understanding.
calculateHash() calculates the Hash, we have talked about this before.
Now let's create an addBlock function.
addBlock(*newBlock*) {
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
This function takes in a parameter called newBlock, which is basically the block we will be adding. To use this function we will run it something like this:
let bkc_app=new blockChain();
bkc_app.addBlock(new Block(index, Date(), data))
Now addBlock will take that block we need to add as parameter, add a previousHash to it by getting the hash of the latestBlock, adds a present Hash to it by doing a calculateHash() on it and pushes it to the chain.
Yay, the simplest blockchain in the world is now ready!
Let's take it for a spin.
let bkc_app= new Blockchain();
data = {
'story':'Quick Brown Fox'
}
bkc_app.addBlock(new Block(1, Date(), data))
console.log(bkc_app, JSON.stringify(khbr, null, 4))
We created a very basic blockchain. In the next few tutorials I will talk about Bitcoins, Ethereums, Cosmos/Matic, Hyperledger and concepts like Proof of Work and Proof of Stake. Stay tuned, give me a follow and clap if you enjoyed.
Signing Off,
Top comments (0)