diff --git a/lib/services/db.js b/lib/services/db.js index 732e4fc5..62ec179c 100644 --- a/lib/services/db.js +++ b/lib/services/db.js @@ -136,8 +136,16 @@ DB.prototype.start = function(callback) { }; DB.prototype.stop = function(callback) { - // TODO Figure out how to call this.store.close() without issues - setImmediate(callback); + var self = this; + + // Wait until syncing stops and all db operations are completed before closing leveldb + async.whilst(function() { + return self.bitcoindSyncing; + }, function(next) { + setTimeout(next, 10); + }, function() { + self.store.close(callback); + }); }; DB.prototype.getInfo = function(callback) { @@ -389,7 +397,6 @@ DB.prototype.runAllBlockHandlers = function(block, add, callback) { } log.debug('Updating the database with operations', operations); - self.store.batch(operations, callback); } ); @@ -525,11 +532,7 @@ DB.prototype.syncRewind = function(block, done) { DB.prototype.sync = function() { var self = this; - if (self.bitcoindSyncing) { - return; - } - - if (!self.tip) { + if (self.bitcoindSyncing || self.node.stopping || !self.tip) { return; } @@ -592,13 +595,12 @@ DB.prototype.sync = function() { return self.node.emit('error', err); } + self.bitcoindSyncing = false; + if(self.node.stopping) { return; } - self.bitcoindSyncing = false; - self.saveMetadata(); - // If bitcoind is completely synced if (self.node.services.bitcoind.isSynced()) { self.node.emit('synced'); diff --git a/test/services/db.unit.js b/test/services/db.unit.js index 867f49cb..5102b9d2 100644 --- a/test/services/db.unit.js +++ b/test/services/db.unit.js @@ -276,13 +276,21 @@ describe('DB Service', function() { }); describe('#stop', function() { - it('should immediately call the callback', function(done) { + it('should wait until db has stopped syncing before closing leveldb', function(done) { var db = new DB(baseConfig); + db.store = { + close: sinon.stub().callsArg(0) + }; + db.bitcoindSyncing = true; db.stop(function(err) { should.not.exist(err); done(); }); + + setTimeout(function() { + db.bitcoindSyncing = false; + }, 15); }); });