Implementing a simple ‘proof of work’ algorithm for the Blockchain

Kore
Game of Life
Published in
5 min readJan 20, 2018

--

Refer to previous article for a boilerplate blockchain code.

  1. Reference article
  2. Boilerplate code

In the earlier example, we implemented a mechanism to add blocks In reality we cannot add a new block so easily. There are numerous checks in place like ‘Proof of work’, ‘Proof of stake’ etc.

The first blockchain was conceptualized by an anonymous person or group known as Satoshi Nakamoto in 2008. It was implemented in 2009 as a core component of Bitcoin. Like our Fruit spreadsheet example, the words block and chain were used separately in Satoshi Nakamoto’s original paper, but were eventually popularized as a single word, blockchain.

Satoshi leveraged the existing peer-to-peer networks with clever cryptography to create a consensus mechanism that could solve the double-spend problem as well as, if not better than a trusted third party. To achieve this, the bitcoin network uses a Proof of work (PoW) mechanism. Miners or participants on the network who run bitcoin nodes gather up recent transactions as a block of data where each block must refer to the previous block. This process repeats every 10 minutes. The problem is that there are multiple miners trying to solve for the same block. To select a miner who will be assigned to solve a block of transactions, we create a mathematical puzzle that is hard to solve, i.e. it takes a lot of work. The puzzle often is to find a really long number (hash value) where the computer tries to guess each number. Whoever solves the puzzle first gets to mine the block. In exchange for mining the block, the miner receives bitcoin as a reward. After every successful transaction, the puzzle starts increasing in complexity i.e. miners need to look for an even larger hash value. The complexity of the puzzle also depends on the number of miners in the network. Finding the hash statistically takes about 10 minutes. The first version of the Ethereum blockchain also used proof of work. There are however other consensus mechanisms that exist.

Read this article for a brief introduction of consensus mechanisms.

Previously, we created an almost immutable blockchain. We could create new blocks really quickly. However, we do not want our blockchain to be bombarded with millions of blocks each second, thereby spamming and slowing down the system.

For our prototype, we’ll implement a ‘proof of work’. Here you have to prove that you have spent a lot of computing power in making a block. This process is called mining. The fact that some work was done to create a block, provides value to the system. Bitcoin for example, requires the hash of a block to begin with a certain amount of 0s. Since you cannot influence a hash function, the system has to try multiple combinations to arrive at a hash value that begins with that number of 0s. This is the puzzle that miners need to solve which requires a lot of computing power. The number of 0s defines the difficulty of the function. Solving this puzzle takes around 10 minutes. As computers improve, they’ll be able to solve these puzzles faster. To compensate for that, the difficulty of the blockchain is periodically increased.

Less difficult : 001
More difficult: 000000000001

Trending Cryptocurrency Hub Articles:

1. Decentraland’s Virtual LAND Sale Stats

2. Three best blockchain stocks investors should watch out for

3. WePower ICO — block platform for green energy trading

Let’s implement ‘proof of work (PoW)’ on our earlier example.

Step 1: Creating a method to mine blocks

In our Block class, first we’ll create a new method called mineBlock which takes a property called diffculty.

mineBlock(difficulty) {
some code in here…}

Inside the method, we want to make the hash of our blocks to begin with a certain amount of 0s. We’ll create a while loop that runs until our hash starts with enough number of 0s.

while(run till our hash begins with a certain number of 0s){
some code in here...}

To do this, we take a substring of our hash that starts with 0 and keeps running till the entire substring consists of all 0s.

For difficulty 5:

Try 02345xhash…
Try
00345xhash…
Try
00375xhash…
Try
00045xhash…
Try
00085xhash…
Try
00000xhash………

Block mined
:)

In the while loop, we take a substring of the hash and tally it with a string that contains sufficient number of 0s as defined by the difficulty.

Inside the method, we’ll calculate the hash of the block until we reach an appropriate hash value (the one with the number of 0s). However, the hash calculation of our block won’t change if we don’t change the contents of our block. However, we cannot change the any of the existing contents of the block like index, timestamp, data or previousHash. Essentially the while loop will run infinitely. We do not want that.

To solve this, the Blockchain provides a property called nonce. It is a random value that can be changed. We will assign a nonce property to our Block class and increment the same in our while loop. Simultaneously we’ll use the nonce value in our calculateHash function.

Now we’ll use the mineBlock method in our Blockchain class. Go to the addBlock method in the Blockchain class and comment or remove the line that adds a new block. Instead of adding a block directly, we want to mine it. To do that use the mineBlock method and pass it a difficulty value.

Ideally we would want the difficulty value to be customizable, so we add a property to our Blockchain class in the constructor method.

This is how our Blockchain class now looks like.

Now let’s run our blockchain. We will remove the code after the Blockchain class in the previous example and replace it with the following:

let koreCoin = new Blockchain();

console.log(‘Mining block 1…’);
koreCoin.addBlock(new Block (1, “01/01/2018”, {amount: 20}));

console.log(‘Mining block 2…’);
koreCoin.addBlock(new Block (2, “02/01/2018”, {amount: 40}));

console.log(‘Mining block 3…’);
koreCoin.addBlock(new Block (3, “02/01/2018”, {amount: 40}));

Here we mine three blocks.

Run the main.js file in the terminal
node main.js

We’ve set our difficulty level to 4 so it takes a bit more time than earlier to find the block. You’ll also notice that all our hash values begin with four 0s.

Now we’ll increase the difficult level to 15, you’ll notice it takes forever for the blockchain to mine a block.

Congratulations! You’ve just implemented a blockchain on your machine with a ‘proof of work’ consensus mechanism.

Link to complete code

If you liked this article, please click the 👏 button (once, twice or more).
Share to help others find it!

--

--