JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Bitcoin Mining Simulation


Mining involves the process of producing a hash whose value is less than the target value. When this hash has been found, it is called a valid hash and hence proof of work is achieved.

The mining algorithm uses a counter known as the nonce to generate the hash using the SHA256 cryptographic function. A hash algorithm always produces the same arbitrary length data given the same inputs. It is impossible to compute the same hash with two different inputs. It is also impossible to predict the output of any given data in advance.

The value of nonce is initialised to 0. Mining is finding the nonce, the only input that changes every time we run the hash function. The goal is to find a value for the nonce that will result in hash lower than the target. So, the mining node might need to try billions or trillions of nonce values before it gets a valid hash. As you can see, mining is like playing the slot machine, there is no way to predict when can you strike a jackpot.

We can create a bitcoin mining simulation using the setInterval() method to be used as the timer. For simulation purpose, I am not going to generate hash as it will be too time consuming, I used integer instead.

I declare a constant target and set its value as 12999. I also declare a variable nonce and initialise its value at 0.

Next, I created a JavaScript function mining()to generate random integers. The floor method and the random method is to generate random integers from 1 to 1000000 using the following syntax:

Math.floor( 1 + Math.random() * 1000000 )

Besides that, I created a JavaScript function StartMine() to set the interval of mining() to 20 milliseconds.

The HTML is as follows:

<div style="border:4px solid blue; width:100px; height:100px text-align:center;padding:0">
<h1 id="dice" style="font-size:300%">1</h1></div>
<br>
<button onclick="StartMine()">Start Mining</button>
<button onclick="stopMine()">Stop Mining</button>


The JavaScript is as follows:

<script>
const target=12999
var nonce

nonce=0;

function StartMine()
{
 document.getElementById("msg").innerHTML="Mining Result";
 document.getElementById("nonce").innerHTML="nonce value";
MyVar=setInterval(mining,20)
}

function mining()
{
var ranNum = Math.floor( 1 + Math.random() * 1000000 );
nonce=nonce+1;
document.getElementById("dice").innerHTML = ranNum;
	 if (ranNum<target)
	 
	 {  StopMine();
	 document.getElementById("msg").innerHTML ='Mining Successful, you got one bitcoin';
	 document.getElementById("nonce").innerHTML ='nonce value'+'='+nonce;}
	 	
	
}
function StopMine()
{clearInterval(MyVar);}
</script>

Click on the 'Start Mining' button to start the mining simulation

1


Mining Result


nonce value






Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy