1
+ var difficulty = 4 ; // number of zeros required at front of hash
2
+ var maximumNonce = 500000 ; // limit the nonce to this so we don't mine too long
3
+
4
+ // NOTE: Because there are 16 possible characters in a hex value, each time you incrament
5
+ // the difficulty by one you make the puzzle 16 times harder. In my testing, a difficulty
6
+ // of 6 requires a maximumNonce well over 500,000,000.
7
+
8
+ /////////////////////////
9
+ // global variable setup
10
+ /////////////////////////
11
+ var pattern = '' ;
12
+ for ( var x = 0 ; x < difficulty ; x ++ ) {
13
+ pattern += '0' ;
14
+ }
15
+
16
+ /////////////////////////
17
+ // functions
18
+ /////////////////////////
1
19
function sha256 ( block , chain ) {
2
20
// calculate a SHA256 hash of the contents of the block
3
21
return CryptoJS . SHA256 ( getText ( block , chain ) ) ;
4
22
}
5
23
6
24
function updateState ( block , chain ) {
7
25
// set the well background red or green for this block
8
- if ( $ ( '#block' + block + 'chain' + chain + 'hash' ) . val ( ) . substr ( 0 , 4 ) === '0000' ) {
26
+ if ( $ ( '#block' + block + 'chain' + chain + 'hash' ) . val ( ) . substr ( 0 , difficulty ) === pattern ) {
9
27
$ ( '#block' + block + 'chain' + chain + 'well' ) . removeClass ( 'well-error' ) . addClass ( 'well-success' ) ;
10
28
}
11
29
else {
@@ -30,10 +48,10 @@ function updateChain(block, chain) {
30
48
}
31
49
32
50
function mine ( block , chain , isChain ) {
33
- for ( var x = 0 ; x <= 500000 ; x ++ ) {
51
+ for ( var x = 0 ; x <= maximumNonce ; x ++ ) {
34
52
$ ( '#block' + block + 'chain' + chain + 'nonce' ) . val ( x ) ;
35
53
$ ( '#block' + block + 'chain' + chain + 'hash' ) . val ( sha256 ( block , chain ) ) ;
36
- if ( $ ( '#block' + block + 'chain' + chain + 'hash' ) . val ( ) . substr ( 0 , 4 ) === '0000' ) {
54
+ if ( $ ( '#block' + block + 'chain' + chain + 'hash' ) . val ( ) . substr ( 0 , difficulty ) === pattern ) {
37
55
if ( isChain ) {
38
56
updateChain ( block , chain ) ;
39
57
}
0 commit comments