Skip to content

Commit

Permalink
Validate Transaction Chain
Browse files Browse the repository at this point in the history
  • Loading branch information
15Dkatz committed Sep 29, 2022
1 parent 4d98221 commit d85179e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion app/pubsub.js
Expand Up @@ -29,7 +29,7 @@ class PubSub {

switch(channel) {
case CHANNELS.BLOCKCHAIN:
this.blockchain.replaceChain(parsedMessage, () => {
this.blockchain.replaceChain(parsedMessage, true, () => {
this.transactionPool.clearBlockchainTransactions({
chain: parsedMessage
});
Expand Down
7 changes: 6 additions & 1 deletion blockchain/index.js
Expand Up @@ -18,7 +18,7 @@ class Blockchain {
this.chain.push(newBlock);
}

replaceChain(chain, onSuccess) {
replaceChain(chain, validateTransactions, onSuccess) {
if (chain.length <= this.chain.length) {
console.error('The incoming chain must be longer');
return;
Expand All @@ -29,6 +29,11 @@ class Blockchain {
return;
}

if (validateTransactions && !this.validTransactionData({ chain })) {
console.error('The incoming chain has invalid data');
return;
}

if (onSuccess) onSuccess();
console.log('replacing chain with', chain);
this.chain = chain;
Expand Down
13 changes: 13 additions & 0 deletions blockchain/index.test.js
Expand Up @@ -156,6 +156,19 @@ describe('Blockchain', () => {
});
});
});

describe('and the `validateTransactions` flag is true', () => {
it('calls validateTransactionData()', () => {
const validateTransactionDataMock = jest.fn();

blockchain.validTransactionData = validateTransactionDataMock;

newChain.addBlock({ data: 'foo' });
blockchain.replaceChain(newChain.chain, true);

expect(validateTransactionDataMock).toHaveBeenCalled();
});
});
});

describe('validTransactionData()', () => {
Expand Down

0 comments on commit d85179e

Please sign in to comment.