chain: spv reorganization.

This commit is contained in:
Christopher Jeffrey 2016-11-10 18:49:13 -08:00
parent ee19c7fee6
commit 3854f04624
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
2 changed files with 37 additions and 0 deletions

View File

@ -795,6 +795,36 @@ Chain.prototype.reorganize = co(function* reorganize(competitor, block) {
this.emit('reorganize', block, tip.height, tip.hash);
});
/**
* Reorganize the blockchain for SPV.
* @private
* @param {ChainEntry} competitor - The competing chain's tip.
* @param {Block|MerkleBlock} block - The being being added.
* @returns {Promise}
*/
Chain.prototype.reorganizeSPV = co(function* reorganizeSPV(competitor, block) {
var tip = this.tip;
var fork = yield this.findFork(tip, competitor);
var entry;
assert(fork);
// Blocks to disconnect.
entry = tip;
while (entry.hash !== fork.hash) {
this.emit('disconnect', entry, entry.toHeaders());
entry = yield entry.getPrevious();
assert(entry);
}
// Reset the main chain back
// to the fork block.
yield this._reset(fork.hash);
this.emit('reorganize', block, tip.height, tip.hash);
});
/**
* Disconnect an entry from the chain (updates the tip).
* @param {ChainEntry} entry
@ -883,6 +913,12 @@ Chain.prototype.setBestChain = co(function* setBestChain(entry, block, prev) {
// Time to reorganize the chain.
if (entry.prevBlock !== this.tip.hash) {
this.logger.warning('WARNING: Reorganizing chain.');
// In spv-mode, we reset the
// chain and redownload the blocks.
if (this.options.spv)
return yield this.reorganizeSPV(entry, block);
yield this.reorganize(entry, block);
}

View File

@ -1458,6 +1458,7 @@ ChainDB.prototype.removeChain = co(function* removeChain(hash) {
assert(!tip.isGenesis());
this.del(layout.a(tip.hash));
this.del(layout.h(tip.hash));
this.del(layout.e(tip.hash));
this.del(layout.b(tip.hash));