bitcore-wallet-service/lib/wsapp.js

71 lines
1.9 KiB
JavaScript
Raw Normal View History

2015-03-23 14:26:47 -07:00
'use strict';
var $ = require('preconditions').singleton();
var _ = require('lodash');
var async = require('async');
var log = require('npmlog');
2015-03-30 15:44:16 -07:00
log.debug = log.verbose;
2015-03-23 14:26:47 -07:00
var Uuid = require('uuid');
var WalletUtils = require('bitcore-wallet-utils');
var Bitcore = WalletUtils.Bitcore;
2015-03-23 14:26:47 -07:00
var WalletService = require('./server');
2015-03-30 15:44:16 -07:00
var BlockchainMonitor = require('./blockchainmonitor')
var Notification = require('./model/notification');
2015-03-23 14:26:47 -07:00
log.level = 'debug';
2015-03-30 15:44:16 -07:00
var io, bcMonitor;
2015-03-23 14:26:47 -07:00
var WsApp = function() {};
2015-04-01 17:34:36 -07:00
WsApp._unauthorized = function(socket) {
2015-03-23 15:07:06 -07:00
socket.emit('unauthorized');
socket.disconnect();
};
2015-03-30 15:44:16 -07:00
WsApp.handleNotification = function(service, notification) {
if (notification.type == 'NewAddress') {
2015-03-30 15:44:16 -07:00
self.subscribeAddresses(notification.walletId, notification.data.address);
}
io.to(notification.walletId).emit('notification', notification);
};
2015-04-05 09:56:56 -07:00
WsApp.start = function(server, config) {
io = require('socket.io')(server);
2015-04-15 06:59:25 -07:00
bcMonitor = new BlockchainMonitor(config.blockchainExplorerOpts);
2015-03-23 14:26:47 -07:00
2015-03-30 15:44:16 -07:00
function handleNotification(notification) {
if (notification.type == 'NewAddress') {
bcMonitor.subscribeAddresses(notification.walletId, notification.data.address);
}
io.to(notification.walletId).emit('notification', notification);
};
2015-03-30 08:40:58 -07:00
2015-03-30 15:44:16 -07:00
bcMonitor.on('notification', handleNotification);
WalletService.onNotification(handleNotification);
2015-03-23 14:26:47 -07:00
io.on('connection', function(socket) {
socket.nonce = Uuid.v4();
socket.emit('challenge', socket.nonce);
socket.on('authorize', function(data) {
2015-04-01 17:34:36 -07:00
if (data.message != socket.nonce) return WsApp._unauthorized(socket);
2015-03-23 15:07:06 -07:00
WalletService.getInstanceWithAuth(data, function(err, service) {
2015-04-01 17:34:36 -07:00
if (err) return WsApp._unauthorized(socket);
2015-03-23 15:07:06 -07:00
socket.join(service.walletId);
2015-03-23 14:26:47 -07:00
socket.emit('authorized');
2015-03-30 08:40:58 -07:00
2015-03-31 08:04:02 -07:00
bcMonitor.subscribeWallet(service, function(err) {
if (err) log.warn(err.message);
});
2015-03-23 14:26:47 -07:00
});
});
});
};
module.exports = WsApp;