add preload option. better errors.

This commit is contained in:
Christopher Jeffrey 2016-02-08 21:05:27 -08:00
parent bcd68c4ed8
commit 05d4eab0d8
2 changed files with 22 additions and 14 deletions

View File

@ -96,12 +96,18 @@ Chain.prototype._init = function _init() {
utils.debug('Chain is loading.');
this.preload(function(start) {
this.preload(function(err, start) {
if (err) {
utils.debug('Preloading chain failed.');
utils.debug('Reason: %s', err.message);
}
utils.nextTick(function() {
var count = self.db.count();
var i = start || 1;
var lastEntry;
utils.debug('Starting chain load at height: %s', i);
function done(height) {
if (height != null) {
utils.debug(
@ -142,9 +148,12 @@ Chain.prototype.preload = function preload(callback) {
var url = 'https://headers.electrum.org/blockchain_headers';
var chainHeight, buf, height, stream;
if (this.options.preload === false)
if (!this.options.preload)
return callback();
if (network.type !== 'main')
return callback(new Error('Electrum.org only offers `main` headers.'));
utils.debug('Loading %s', url);
stream = request.get(url);
@ -157,18 +166,15 @@ Chain.prototype.preload = function preload(callback) {
stream.on('response', function(res) {
if (res.statusCode >= 400) {
utils.debug('Could not load electrum headers');
utils.debug('Status: %d', res.statusCode);
stream.destroy();
return callback();
return callback(new Error('Bad response code: ' + res.statusCode));
}
});
stream.on('error', function(err) {
utils.debug('Could not load electrum headers');
utils.debug(err.stack + '');
self.resetHeight(Math.max(0, height - 2));
return callback(Math.max(0, height - 2));
var start = Math.max(0, height - 2);
self.resetHeight(start);
return callback(err, start + 1);
});
stream.on('data', function(data) {
@ -196,13 +202,14 @@ Chain.prototype.preload = function preload(callback) {
blocks.forEach(function(data) {
var entry = bcoin.chainblock.fromRaw(self, height, data);
var start;
// Do some paranoid checks.
if (lastEntry && entry.prevBlock !== lastEntry.hash) {
utils.debug('Electrum headers are corrupt. Resetting.');
start = Math.max(0, height - 2);
stream.destroy();
self.resetHeight(Math.max(0, height - 2));
return callback(Math.max(0, height - 2));
self.resetHeight(start);
return callback(new Error('Corrupt headers.'), start + 1);
}
lastEntry = entry;
@ -226,7 +233,7 @@ Chain.prototype.preload = function preload(callback) {
});
stream.on('end', function() {
return callback(height + 1);
return callback(null, height + 1);
});
};

View File

@ -85,7 +85,8 @@ function Pool(options) {
this.chain = new bcoin.chain({
fullNode: this.options.fullNode,
multiplePeers: this.options.multiplePeers
multiplePeers: this.options.multiplePeers,
preload: this.options.preload
});
this.watchMap = {};