diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index 1281c958..867a4f9b 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -917,6 +917,8 @@ ChainDB.prototype.saveAsync = function saveAsync(entry, callback) { var self = this; var raw, offset; + callback = utils.asyncify(callback); + // Cache the past 1001 blocks in memory // (necessary for isSuperMajority) this.cache(entry); @@ -926,7 +928,7 @@ ChainDB.prototype.saveAsync = function saveAsync(entry, callback) { // it cancels. if (this._queue[entry.height]) { this._queue[entry.height] = entry; - return; + return callback(); } // Speed up writes by doing them asynchronously @@ -957,14 +959,15 @@ ChainDB.prototype.saveAsync = function saveAsync(entry, callback) { delete self._queue[entry.height]; - if (callback) - return callback(null, success); + return callback(null, success); }); }; ChainDB.prototype.remove = function remove(height) { assert(height >= 0); + // Potential race condition here. Not sure how + // to handle this. if (this._queue[height]) { utils.debug('Warning: write job in progress.'); delete this._queue[height]; @@ -1005,6 +1008,12 @@ ChainDB.prototype.has = function has(height) { if (this._queue[height] || this._cache[height]) return true; + if (height < 0 || height == null) + return false; + + if ((height + 1) * BLOCK_SIZE > this.size) + return false; + data = this._readSync(4, height * BLOCK_SIZE); if (!data) @@ -1033,6 +1042,7 @@ ChainDB.prototype._readSync = function _readSync(size, offset) { } } } catch (e) { + this._free(data); throw e; } @@ -1041,7 +1051,7 @@ ChainDB.prototype._readSync = function _readSync(size, offset) { throw new Error('_readSync() failed.'); }; -ChainDB.prototype._readAsync = function _readSync(size, offset, callback) { +ChainDB.prototype._readAsync = function _readAsync(size, offset, callback) { var self = this; var index = 0; var data, bytes;