From 14a08f2e0fa5cc3a9b6789c48a97ec6f52abab1f Mon Sep 17 00:00:00 2001 From: Ivan Socolsky Date: Tue, 4 Aug 2015 16:10:48 -0300 Subject: [PATCH] listen for new blocks and raise notification --- lib/blockchainmonitor.js | 33 +++++++++++++++++++++++++-------- lib/wsapp.js | 3 ++- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/lib/blockchainmonitor.js b/lib/blockchainmonitor.js index 0300b3c..ea59a30 100644 --- a/lib/blockchainmonitor.js +++ b/lib/blockchainmonitor.js @@ -83,6 +83,7 @@ BlockchainMonitor.prototype._initExplorer = function(explorer) { log.error('Error connecting to ' + explorer.getConnectionInfo()); }); socket.on('tx', _.bind(self._handleIncommingTx, self)); + socket.on('block', _.bind(self._handleNewBlock, self)); }; BlockchainMonitor.prototype._handleIncommingTx = function(data) { @@ -112,26 +113,42 @@ BlockchainMonitor.prototype._handleIncommingTx = function(data) { var walletId = address.walletId; log.info('Incoming tx for wallet ' + walletId + ' [' + out.amount + 'sat -> ' + out.address + ']'); - self._createNotification(walletId, data.txid, out.address, out.amount, next); + + var notification = Notification.create({ + type: 'NewIncomingTx', + data: { + txid: data.txid, + address: out.address, + amount: out.amount, + }, + walletId: walletId, + }); + self._storeAndBroadcastNotification(notification, next); }); }, function(err) { return; }); }; -BlockchainMonitor.prototype._createNotification = function(walletId, txid, address, amount, cb) { +BlockchainMonitor.prototype._handleNewBlock = function(hash) { var self = this; + log.info('New block: ', hash); var notification = Notification.create({ - type: 'NewIncomingTx', + type: 'NewBlock', data: { - txid: txid, - address: address, - amount: amount, + hash: hash, }, - walletId: walletId, }); - self.storage.storeNotification(walletId, notification, function() { + self._storeAndBroadcastNotification(notification, function(err) { + return; + }); +}; + +BlockchainMonitor.prototype._storeAndBroadcastNotification = function(notification, cb) { + var self = this; + + self.storage.storeNotification(notification.walletId, notification, function() { self.messageBroker.send(notification) return cb(); }); diff --git a/lib/wsapp.js b/lib/wsapp.js index da325f8..2fd2193 100644 --- a/lib/wsapp.js +++ b/lib/wsapp.js @@ -20,7 +20,8 @@ WsApp.prototype._unauthorized = function(socket) { }; WsApp.prototype._handleNotification = function(notification) { - this.io.to(notification.walletId).emit('notification', notification); + var room = notification.walletId ? this.io.to(notification.walletId) : this.io; + room.emit('notification', notification); }; WsApp.prototype.start = function(server, opts, cb) {