(message)
| 145 | }; |
| 146 | |
| 147 | var handleBlockchainResponse = (message) => { |
| 148 | var receivedBlocks = JSON.parse(message.data).sort((b1, b2) => (b1.index - b2.index)); |
| 149 | var latestBlockReceived = receivedBlocks[receivedBlocks.length - 1]; |
| 150 | var latestBlockHeld = getLatestBlock(); |
| 151 | if (latestBlockReceived.index > latestBlockHeld.index) { |
| 152 | console.log('blockchain possibly behind. We got: ' + latestBlockHeld.index + ' Peer got: ' + latestBlockReceived.index); |
| 153 | if (latestBlockHeld.hash === latestBlockReceived.previousHash) { |
| 154 | console.log("We can append the received block to our chain"); |
| 155 | blockchain.push(latestBlockReceived); |
| 156 | broadcast(responseLatestMsg()); |
| 157 | } else if (receivedBlocks.length === 1) { |
| 158 | console.log("We have to query the chain from our peer"); |
| 159 | broadcast(queryAllMsg()); |
| 160 | } else { |
| 161 | console.log("Received blockchain is longer than current blockchain"); |
| 162 | replaceChain(receivedBlocks); |
| 163 | } |
| 164 | } else { |
| 165 | console.log('received blockchain is not longer than current blockchain. Do nothing'); |
| 166 | } |
| 167 | }; |
| 168 | |
| 169 | var replaceChain = (newBlocks) => { |
| 170 | if (isValidChain(newBlocks) && newBlocks.length > blockchain.length) { |
no test coverage detected