Skip to content

Commit

Permalink
Adjust the Difficulty in MineBlock
Browse files Browse the repository at this point in the history
  • Loading branch information
15Dkatz committed Sep 27, 2022
1 parent 0dbb85d commit 3a468eb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
7 changes: 5 additions & 2 deletions block.js
Expand Up @@ -16,14 +16,15 @@ class Block {
}

static mineBlock({ lastBlock, data }) {
let hash, timestamp;
const lastHash = lastBlock.hash;
const { difficulty } = lastBlock;
let hash, timestamp;
let { difficulty } = lastBlock;
let nonce = 0;

do {
nonce++;
timestamp = Date.now();
difficulty = Block.adjustDifficulty({ originalBlock: lastBlock, timestamp });
hash = cryptoHash(timestamp, lastHash, data, nonce, difficulty);
} while (hash.substring(0, difficulty) !== '0'.repeat(difficulty));

Expand All @@ -33,6 +34,8 @@ class Block {
static adjustDifficulty({ originalBlock, timestamp }) {
const { difficulty } = originalBlock;

if (difficulty < 1) return 1;

if ((timestamp - originalBlock.timestamp) > MINE_RATE) return difficulty - 1;

return difficulty + 1;
Expand Down
12 changes: 12 additions & 0 deletions block.test.js
Expand Up @@ -70,6 +70,12 @@ describe('Block', () => {
expect(minedBlock.hash.substring(0, minedBlock.difficulty))
.toEqual('0'.repeat(minedBlock.difficulty));
});

it('adjusts the difficulty', () => {
const possibleResults = [lastBlock.difficulty+1, lastBlock.difficulty-1];

expect(possibleResults.includes(minedBlock.difficulty)).toBe(true);
});
});

describe('adjustDifficulty()', () => {
Expand All @@ -86,5 +92,11 @@ describe('Block', () => {
timestamp: block.timestamp + MINE_RATE + 100
})).toEqual(block.difficulty-1);
});

it('has a lower limit of 1', () => {
block.difficulty = -1;

expect(Block.adjustDifficulty({ originalBlock: block })).toEqual(1);
});
});
});

0 comments on commit 3a468eb

Please sign in to comment.