Skip to content

Commit

Permalink
Prevent Duplicate Transactions in Block
Browse files Browse the repository at this point in the history
  • Loading branch information
15Dkatz committed Sep 29, 2022
1 parent 6c5fc2c commit 4d98221
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
8 changes: 8 additions & 0 deletions blockchain/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class Blockchain {
validTransactionData({ chain }) {
for (let i=1; i<chain.length; i++) {
const block = chain[i];
const transactionSet = new Set();
let rewardTransactionCount = 0;

for (let transaction of block.data) {
Expand Down Expand Up @@ -67,6 +68,13 @@ class Blockchain {
console.error('Invalid input amount');
return false;
}

if (transactionSet.has(transaction)) {
console.error('An identical transaction appears more than once in the block');
return false;
} else {
transactionSet.add(transaction);
}
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions blockchain/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,12 @@ describe('Blockchain', () => {

describe('and a block contains multiple identical transactions', () => {
it('returns false and logs an error', () => {
newChain.addBlock({
data: [transaction, transaction, transaction, rewardTransaction]
});

expect(blockchain.validTransactionData({ chain: newChain.chain })).toBe(false);
expect(errorMock).toHaveBeenCalled();
});
});
});
Expand Down

0 comments on commit 4d98221

Please sign in to comment.