How to implement difficulty calculation in my code

0

0

So let's say we have to produce a hash that start with "0000"

I hash a block over and over by changing the nonce inside it.

Eventualy I will find a hash that start with "0000".

What is difficulty here? Is it the ammount of zéros we require the hash to start with? More zero's would be more difficult? Does it have to do with the nonce?

I understand that the higher the difficulty the more hashes it will take to find it.

If my difficulty is one how do I apply the difficulty in the hashing process.

Right now all im doing is hashihing a block everytime I add 1 to the nonce wich represent the number of hash.

So how do I implement the difficulty in the hash calculation.

I am programming a blockchain from scratch!

Exemple of my code;

generateHash(block) {

     let hash = sha256(block.key)       // key contain the block data

     while(!hash.startsWith("f07a")) {  // we hash until the hash start with f07a
       block.nonce += 1                 // add 1 to nonce for each try
       hash = sha256(block.key)         // Trying with the new nonce         
       //console.log(hash)             
     }

     return hash

   }

So how would I implement difficulty here? I know i would have to do more math acording to network hashrate but to understand it in my case how would I use a difficulty of 1 here?

MadeInDreams

Posted 2018-11-05T18:33:57.527

Reputation: 101

Question was closed 2018-11-05T19:10:14.313

No answers