diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index e5062e4b..6d1b2b43 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -370,7 +370,7 @@ Chain.prototype._saveBlock = function _saveBlock(block, callback) { var self = this; if (!this.blockdb) - return callback(); + return utils.nextTick(callback); this.blockdb.saveBlock(block, callback); }; @@ -379,7 +379,7 @@ Chain.prototype._removeBlock = function _removeBlock(tip, callback) { var self = this; if (!this.blockdb) - return callback(); + return utils.nextTick(callback); this.blockdb.removeBlock(tip, callback); }; @@ -829,6 +829,21 @@ Chain.prototype.revertHeight = function revertHeight(height, callback) { }); }; +Chain.prototype._revertLast = function _revertLast(existing, callback) { + var self = this; + return this._removeBlock(existing.hash, function(err, existingBlock) { + if (err) + return callback(err); + + self.resetHeight(existing.height - 1); + + if (existingBlock) + self.emit('remove block', existingBlock); + + return callback(); + }); +}; + Chain.prototype.syncHeight = function syncHeight(callback) { var self = this; var chainHeight; @@ -1077,15 +1092,10 @@ Chain.prototype.add = function add(initial, peer, callback) { // alternate tip). Reset the chain, find // a new peer, and wait to see who wins. // return self.revertHeight(existing.height - 1, function(err) { - return self._removeBlock(existing.hash, function(err, existingBlock) { + return self._revertLast(existing, function(err, existingBlock) { if (err) return done(err); - self.resetHeight(existing.height - 1); - - if (existingBlock) - self.emit('remove block', existingBlock); - self.emit('fork', block, { height: existing.height, expected: existing.hash,