From 10e959efdeee5b4a09603994b719ebf2bd86a64d Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Fri, 21 Oct 2016 00:34:28 -0700 Subject: [PATCH] chain: refactor alt chain saving. --- lib/chain/chain.js | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/lib/chain/chain.js b/lib/chain/chain.js index 338e6a3c..ac70a02c 100644 --- a/lib/chain/chain.js +++ b/lib/chain/chain.js @@ -913,6 +913,37 @@ Chain.prototype.setBestChain = co(function* setBestChain(entry, block, prev) { this.emit('tip', entry); }); +/** + * Save block on an alternate chain. + * @private + * @param {ChainEntry} entry + * @param {Block|MerkleBlock} block + * @param {ChainEntry} prev + * @returns {Promise} + */ + +Chain.prototype.saveAlternate = co(function* saveAlternate(entry, block, prev) { + try { + // Do as much verification + // as we can before saving. + yield this.verify(block, prev); + } catch (e) { + // Couldn't verify block. + // Revert the height. + block.setHeight(-1); + + if (e.type === 'VerifyError') { + if (!e.malleated) + this.invalid[entry.hash] = true; + this.emit('invalid', block, entry.height); + } + + throw e; + } + + yield this.db.save(entry, block); +}); + /** * Reset the chain to the desired height. This * is useful for replaying the blockchain download @@ -1188,19 +1219,10 @@ Chain.prototype._add = co(function* add(block) { // our tip's. Add the block but do _not_ // connect the inputs. if (entry.chainwork.cmp(this.tip.chainwork) <= 0) { - try { - yield this.verify(block, prev); - } catch (e) { - if (e.type === 'VerifyError') { - if (!e.malleated) - this.invalid[entry.hash] = true; - this.emit('invalid', block, entry.height); - } - throw e; - } - - yield this.db.save(entry, block); + // Save block to an alternate chain. + yield this.saveAlternate(entry, block, prev); + // Emit as a "competitor" block. this.emit('competitor', block, entry); if (!initial)