MCPcopy
hub / github.com/lhartikk/naivechain / handleBlockchainResponse

Function handleBlockchainResponse

main.js:147–167  ·  view source on GitHub ↗
(message)

Source from the content-addressed store, hash-verified

145};
146
147var 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
169var replaceChain = (newBlocks) => {
170 if (isValidChain(newBlocks) && newBlocks.length > blockchain.length) {

Callers 1

initMessageHandlerFunction · 0.85

Calls 5

getLatestBlockFunction · 0.85
broadcastFunction · 0.85
responseLatestMsgFunction · 0.85
queryAllMsgFunction · 0.85
replaceChainFunction · 0.85

Tested by

no test coverage detected