Skip to content

Commit e42c75d

Browse files
committed
Make difficulty variable
1 parent 9c8160e commit e42c75d

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

public/javascripts/blockchain.js

+21-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,29 @@
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+
/////////////////////////
119
function sha256(block, chain) {
220
// calculate a SHA256 hash of the contents of the block
321
return CryptoJS.SHA256(getText(block, chain));
422
}
523

624
function updateState(block, chain) {
725
// 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) {
927
$('#block'+block+'chain'+chain+'well').removeClass('well-error').addClass('well-success');
1028
}
1129
else {
@@ -30,10 +48,10 @@ function updateChain(block, chain) {
3048
}
3149

3250
function mine(block, chain, isChain) {
33-
for (var x = 0; x <= 500000; x++) {
51+
for (var x = 0; x <= maximumNonce; x++) {
3452
$('#block'+block+'chain'+chain+'nonce').val(x);
3553
$('#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) {
3755
if (isChain) {
3856
updateChain(block, chain);
3957
}

0 commit comments

Comments
 (0)