diff --git a/modules/transport.js b/modules/transport.js index 15ce68d7549..d46335e1d07 100644 --- a/modules/transport.js +++ b/modules/transport.js @@ -35,14 +35,10 @@ private.attachApi = function () { router.use(function (req, res, next) { if (modules && private.loaded) { - if (!private.open) library.logger.debug("Opening transport"); - private.open = true; - + modules.transport.open(true); return next(); } else { - if (private.open) library.logger.debug("Closing transport"); - private.open = false; - + modules.transport.close(true); res.status(500).send({success: false, error: "Blockchain is loading"}); } }); @@ -461,10 +457,46 @@ private.hashsum = function (obj) { } // Public methods -Transport.prototype.open = function () { +Transport.prototype.open = function (open) { + if (!private.open && open) { + library.logger.debug("Opening transport"); + private.open = true; + } + return private.open; } +Transport.prototype.close = function (close) { + if (private.open && close) { + library.logger.debug("Closing transport"); + private.open = false; + } + + return !private.open; +} + +Transport.prototype.closeOnStale = function () { + if (!private.open) { + return true; + } + + var lastReceipt = modules.blocks.lastReceipt(); + + if (!lastReceipt) { + return self.close(); + } else { + var timeOut = 30; + var timeNow = new Date(); + var seconds = (timeNow.getTime() - lastReceipt.getTime()) / 1000; + + if (seconds > timeOut) { + return self.close(); + } + } + + return false; +} + Transport.prototype.broadcast = function (config, options, cb) { // When client is not loaded, is syncing or round is ticking // Skip broadcast as client is not ready to make them @@ -643,6 +675,8 @@ Transport.prototype.onBind = function (scope) { Transport.prototype.onBlockchainReady = function () { private.loaded = true; + + setInterval(self.closeOnStale, 1000); } Transport.prototype.onSignature = function (signature, broadcast) {