DEV Community

Discussion on: Creating a blockchain in 60 lines of Javascript

Collapse
 
labzdjee profile image
Gérard Gauthier

Very interesting. I was with you until your mentioning log16(difficulty): where do you use this log16 function? As a parameter in the mine function? Elsewhere?

Collapse
 
freakcdev297 profile image
FreakCdev

What I meant was log base 16 of the difficulty, it is a better since the "real difficulty" should not drop or increase by a huge margin, and Bitcoin also uses it.

You can create a simple log16 function like this:

function log16(n) {
    return Math.log(n) / Math.log(16);
}
Enter fullscreen mode Exit fullscreen mode

So the new mine method should look like this:

    mine(difficulty) {
        while (!this.hash.startsWith(Array(Math.round(log16(difficulty)) + 1).join("0"))) {
            this.nonce++;
            this.hash = this.getHash();
        }
    }
Enter fullscreen mode Exit fullscreen mode

Also, for a little bonus, Bitcoin also requires 8 zeros by default so if you want to make it Bitcoin-like, it should be "00000000"+Array(Math.round(log16(difficulty)) + 1).join("0").

Collapse
 
labzdjee profile image
Gérard Gauthier

Thank you! That's is very clear. Effectively not as a parameter in the mine function as I mistakenly mentioned it but included in the calculation itself. It looks like the proof of work starts quite harsh with 8 zeroes and evolves quite slowly because of log16. Except maybe if one more "0" adds a lot of more difficulty in the computational demand.