Skip to content

Commit

Permalink
Make difficulty variable
Browse files Browse the repository at this point in the history
  • Loading branch information
anders94 committed Sep 12, 2017
1 parent 9c8160e commit e42c75d
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions public/javascripts/blockchain.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
var difficulty = 4; // number of zeros required at front of hash
var maximumNonce = 500000; // limit the nonce to this so we don't mine too long

// NOTE: Because there are 16 possible characters in a hex value, each time you incrament
// the difficulty by one you make the puzzle 16 times harder. In my testing, a difficulty
// of 6 requires a maximumNonce well over 500,000,000.

/////////////////////////
// global variable setup
/////////////////////////
var pattern = '';
for (var x=0; x<difficulty; x++) {
pattern += '0';
}

/////////////////////////
// functions
/////////////////////////
function sha256(block, chain) {
// calculate a SHA256 hash of the contents of the block
return CryptoJS.SHA256(getText(block, chain));
}

function updateState(block, chain) {
// set the well background red or green for this block
if ($('#block'+block+'chain'+chain+'hash').val().substr(0, 4) === '0000') {
if ($('#block'+block+'chain'+chain+'hash').val().substr(0, difficulty) === pattern) {
$('#block'+block+'chain'+chain+'well').removeClass('well-error').addClass('well-success');
}
else {
Expand All @@ -30,10 +48,10 @@ function updateChain(block, chain) {
}

function mine(block, chain, isChain) {
for (var x = 0; x <= 500000; x++) {
for (var x = 0; x <= maximumNonce; x++) {
$('#block'+block+'chain'+chain+'nonce').val(x);
$('#block'+block+'chain'+chain+'hash').val(sha256(block, chain));
if ($('#block'+block+'chain'+chain+'hash').val().substr(0, 4) === '0000') {
if ($('#block'+block+'chain'+chain+'hash').val().substr(0, difficulty) === pattern) {
if (isChain) {
updateChain(block, chain);
}
Expand Down

0 comments on commit e42c75d

Please sign in to comment.