From d85179e0b6d0f2ab48e18f91dd9aca4582d8e512 Mon Sep 17 00:00:00 2001 From: David Katz <15Dkatz@shcp.edu> Date: Wed, 28 Sep 2022 14:10:10 -0700 Subject: [PATCH] Validate Transaction Chain --- app/pubsub.js | 2 +- blockchain/index.js | 7 ++++++- blockchain/index.test.js | 13 +++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/app/pubsub.js b/app/pubsub.js index 5aa9e45..40ed6d9 100644 --- a/app/pubsub.js +++ b/app/pubsub.js @@ -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 }); diff --git a/blockchain/index.js b/blockchain/index.js index 00111ed..c6b6004 100644 --- a/blockchain/index.js +++ b/blockchain/index.js @@ -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; @@ -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; diff --git a/blockchain/index.test.js b/blockchain/index.test.js index 70a7907..cbecee0 100644 --- a/blockchain/index.test.js +++ b/blockchain/index.test.js @@ -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()', () => {