If we look at the trends of the previous few years, we have heard about blockchain all the time, but not much about the specifics.
We’re all aware that cryptocurrencies such as Bitcoin, Ethereum, Dogecoin, Matic, and others rely on blockchain technology. Blockchain led the significant events that revolutionized numerous industries in 2021 and paved the way for new achievements.
Blockchain is a means of storing data in a way that is hard or impossible to edit, hack, or swindle. It is a digital ledger of transactions that are duplicated and spread across the blockchain’s entire network of computer systems.
It is the ground-breaking database technology that powers practically all cryptocurrencies. Blockchain makes it incredibly difficult to hack or cheat the system by spreading identical copies of a database across an entire network.
While Bitcoin is now the most prominent use for blockchain, the technology can serve a very broad variety of applications.
Cryptocurrencies and blockchains have been increasingly popular in recent years, and this trend is expected to continue.
We’ll make a simple blockchain with JavaScript in this tutorial. It will provide you with a basic understanding of how a blockchain works.
Let’s call it MelodyCoin and get right in on the action!
Creating A Block
To begin, we’ll create a new JavaScript file in which we’ll place all of our code.
Let’s call it main.js and start with a description of how a blockchain and blocks should look.
Create a Block class and give it a function Object() { [native code] } to begin with.
You must give a date, and the hash of the previous block when creating a new block:
Here are the definitions for each property:
- The timestamp indicates when the block was made. You can use whatever format you choose (in this case, a UNIX timestamp).
- Any form of data that you wish to connect to this block can be included in the data parameter. If you wish to create a cryptocurrency, you can keep transaction data such as the sender/receiver and the amount of money moved here.
- The previousHash is a string that holds the prior block’s hash. This is what will generate the chain of blocks, which will be critical in providing the integrity of our blockchain later.
Creating Hashes
Each block links to the preceding block (thus the previousHash property). That is, each block requires a hash. A hash is similar to a fingerprint. It is distinct for each block.
A block’s hash can be computed by passing all of its contents through a hash function.
So, let’s begin by implementing a function that computes the hash of the current block.
So, under the Block class, we define the calculateHash function:
However, the SHA256 hash is not supported by JavaScript and must be obtained from an external library.
Crypto-js is a fantastic package that includes secure implementations of several hash algorithms.
Then we can import it into our main.js code.
Now that we have our calculateHash() function, let’s put it to use in our Block’s function:
After describing what a Block looks like, we can define what a Blockchain should look like. So let’s create a new class.
In this scenario, the blockchain is a very simple object that has a property chain. This is an array holding all of the blocks on the chain.
Before we can add blocks, we must first create what is known as a “genesis block.” This is the first block in the chain, and it is unique in that it cannot point to a prior block (it is the first!).
So, to build the genesis block, I’ll add a function to our class named createGenesisBlock (). Back in the function Object() { [native code] } of our Blockchain class.
We can now include the genesis block anytime we build a new Blockchain instance:
Blockchain Methods
Now, let’s add methods to our Blockchain class that will allow us to do things like add new blocks and fetch the most recent block.
The getLatestBlock function is the most basic. It simply returns the final member of the chain array:
The addBlock technique is a little more involved.
Before we can add a new block to our chain, we must first appropriately set that block’s previousHash field.
It must be set to the hash of the most recently added block to our chain. We also need to compute the hash of the new block:
Testing
Let’s see how our MelodyCoin has come out.
Create a blockchain instance to accomplish this. Let’s add a couple more blocks:
We’ve made two new blocks there. Let’s take a peek at what our blockchain looks like currently.
MelodyCoin will be stringified and formatted with four spaces:
Verify The Blockchain’s Integrity
Blockchains are fantastic because once a block has been added, it cannot be modified without invalidating the remainder of the chain.
However, there is no method for me to check the integrity of our blockchain with this implementation.
Let’s introduce an isChainValid function to our blockchain. If the chain is legitimate, it will return true; otherwise, it will return false:
Testing Integrity
We can now put our blockchain’s integrity to the test. If we execute it now, it will confirm that our chain is genuine.
Let us now try to tamper with our blockchain. Let’s alter block 2 and overwrite its contents (let’s suppose we transferred 100 coins instead of four).
When we execute this, we can see that the software recognizes our effort to tamper with the chain.
However, you can believe that there is another method for me to meddle with this. I altered the contents in the block but did not recalculate the hash. So you can try to be clever and recalculate the hash of that same block.
That’s all there was to our tiny blockchain setup! It enables us to add new blocks and detect tampering with data within the chain.
There are two issues with our small blockchain that we must address:
- Modern computers are extremely fast and can add thousands of blocks to our chain in seconds. We obviously do not want anyone spamming our blockchain.
- Our blockchain is still vulnerable to tampering. You can update the contents of a block and then simply recalculate the hashes (and prior hashes) for all following blocks. Even if you mess with it, you’ll end up with a legitimate chain.
To address these concerns, blockchains use a technique known as “proof of work.” You must demonstrate that you used a significant amount of computational resources to create a block using this approach. This is also called mining.
Proof-of-work requires that a block’s hash begin with a specific amount of zeros. But how can you know whether your hash fits this rule?
The contents of a block determine its hash. So we always obtain the same hash, provided we don’t modify the contents.
Each block should have a nonce value added to it as a solution. This is essentially some random data that we can update until the hash of our block begins with enough zeros. Because you can’t alter a hash function’s output, you have to test a lot of different combinations and hope for the best.
Introduce Mining to The Blockchain
Let’s begin by including a nonce in our Block class. The nonce is the single value within our block that we can modify to impact the block’s hash.
We are unable to alter the timestamp or the data.
Next, let’s write a mineBlock() function that will do the actual mining of a block. This function will be sent the needed difficulty as a parameter and will continue to execute until the hash of our block begins with enough zeros.
I just made a basic while loop that would run until our hash begins with enough zeros. We use the difficulty to determine how many zeros are needed. With a difficulty of 5, our hash must begin with 5 zeros.
When our hash does not contain enough zeros, we raise the nonce by one and recalculate the hash. And if we find a hash that corresponds to the difficulty, we log it to the console.
There’s one more thing we need to do. We don’t really take the nonce variable into account in our calculateHash method, so here it is:
Blockchain Class
Let’s put this new approach to the test in our blockchain class and see how it goes.
To begin, I’ll define the difficulty of our blockchain in the function Object(). We define it here since we can use it somewhere later.
The addBlock function must then be modified such that it mines the block before adding it into our chain.
Use The Blockchain
Now, let’s put our new blockchain to use with the proof-of-work algorithm. Here, add a couple console.log statements.
When we execute this code, we can observe that the mining process is no longer particularly rapid.
It takes some time for the algorithm to generate blocks with hashes that begin with three zeros (as configured by difficulty).
So that was the end of our basic blockchain setup.
We can regulate how quickly new blocks are added to our blockchain thanks to the proof-of-work mechanism.
It’s the most significant security feature on blockchains. And now that you understand how it works, get on creating your own!
Leave a Reply