Skip to content

Commit

Permalink
Prevent Difficulty Jumps
Browse files Browse the repository at this point in the history
  • Loading branch information
15Dkatz committed Sep 27, 2022
1 parent ef4522f commit e926c95
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 3 additions & 1 deletion blockchain.js
Expand Up @@ -37,14 +37,16 @@ class Blockchain {

for (let i=1; i<chain.length; i++) {
const { timestamp, lastHash, hash, nonce, difficulty, data } = chain[i];

const actualLastHash = chain[i-1].hash;
const lastDifficulty = chain[i-1].difficulty;

if (lastHash !== actualLastHash) return false;

const validatedHash = cryptoHash(timestamp, lastHash, data, nonce, difficulty);

if (hash !== validatedHash) return false;

if (Math.abs(lastDifficulty - difficulty) > 1) return false;
}

return true;
Expand Down
22 changes: 22 additions & 0 deletions blockchain.test.js
@@ -1,5 +1,6 @@
const Blockchain = require('./blockchain');
const Block = require('./block');
const cryptoHash = require('./crypto-hash');

describe('Blockchain', () => {
let blockchain, newChain, originalChain;
Expand Down Expand Up @@ -58,6 +59,27 @@ describe('Blockchain', () => {
});
});

describe('and the chain contains a block with a jumped difficulty', () => {
it('returns false', () => {
const lastBlock = blockchain.chain[blockchain.chain.length-1];
const lastHash = lastBlock.hash;
const timestamp = Date.now();
const nonce = 0;
const data = [];
const difficulty = lastBlock.difficulty - 3;

const hash = cryptoHash(timestamp, lastHash, difficulty, nonce, data);

const badBlock = new Block({
timestamp, lastHash, hash, nonce, difficulty, data
});

blockchain.chain.push(badBlock);

expect(Blockchain.isValidChain(blockchain.chain)).toBe(false);
});
});

describe('and the chain does not contain any invalid blocks', () => {
it('returns true', () => {
expect(Blockchain.isValidChain(blockchain.chain)).toBe(true);
Expand Down

0 comments on commit e926c95

Please sign in to comment.