diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index ecf97622..dedfc683 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -97,23 +97,36 @@ Chain.prototype._init = function _init() { utils.nextTick(function() { var count = self.db.count(); - var entry; + var lastEntry; var i = 1; - function done() { + function done(height) { + if (height != null) { + utils.debug( + 'Blockchain is corrupt after height %d. Resetting.', + height); + self.resetHeight(height); + } else { + utils.debug('Chain successfully loaded.'); + } self.loading = false; self.emit('load'); - - utils.debug('Chain successfully loaded.'); } (function next() { if (i >= count) return done(); + self.db.getAsync(i, function(err, entry) { if (err) throw err; + + // Do some paranoid checks. + if (lastEntry && entry.prevBlock !== lastEntry.hash) + return done(Math.max(0, i - 2)); + self._saveEntry(entry); + lastEntry = entry; i += 1; next(); });