chain: refactor alt chain saving.

This commit is contained in:
Christopher Jeffrey 2016-10-21 00:34:28 -07:00
parent 21b2a12278
commit 10e959efde
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -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)