identity now emits!

This commit is contained in:
Matias Alejo Garcia 2014-11-30 00:31:17 -03:00
parent 57299d675e
commit 3ae6378678
33 changed files with 384 additions and 354 deletions

View File

@ -50,7 +50,7 @@
<span translate> <strong class="size-16">Network Error</strong>.<br> Attempting to reconnect..</span>
</span>
<nav class="tab-bar" ng-if="$root.wallet &&
$root.wallet.isReady() && !$root.wallet.isLocked">
$root.wallet.isComplete() && !$root.wallet.isLocked">
<section class="left-small">
<a class="left-off-canvas-toggle menu-icon" ><span></span></a>
</section>
@ -91,7 +91,7 @@
<section ng-class="{'main':$root.iden && !$root.starting}" ng-view></section>
<div class="bottom-bar" ng-if="$root.wallet &&
$root.wallet.isReady() && !$root.wallet.isLocked">
$root.wallet.isComplete() && !$root.wallet.isLocked">
<div ng-include="'views/includes/bottombar-mobile.html'"></div>
</div>

View File

@ -3,7 +3,7 @@
angular.module('copayApp.controllers').controller('CopayersController',
function($scope, $rootScope, $location) {
if (!$rootScope.wallet.isReady()) {
if (!$rootScope.wallet.isComplete()) {
$rootScope.title = 'Waiting copayers for ' + $rootScope.wallet.getName();
}
$scope.loading = false;

View File

@ -44,7 +44,6 @@ angular.module('copayApp.controllers').controller('CreateController',
notification.error('Error', 'Please enter the required fields');
return;
}
$scope.loading = true;
var opts = {
requiredCopayers: $scope.requiredCopayers,
totalCopayers: $scope.totalCopayers,
@ -52,8 +51,14 @@ angular.module('copayApp.controllers').controller('CreateController',
privateKeyHex: $scope.private,
networkName: $scope.networkName,
};
identityService.createWallet(opts, function(){
$scope.loading = false;
$rootScope.starting = true;
identityService.createWallet(opts, function(err, wallet){
$rootScope.starting = false;
if (err || !wallet) {
copay.logger.debug(err);
$scope.error = 'Could not create wallet.' + err;
}
$rootScope.$digest()
});
};
});

View File

@ -10,7 +10,12 @@ angular.module('copayApp.controllers').controller('CreateProfileController', fun
$scope.error('Error', 'Please enter the required fields');
return;
}
identityService.create($scope, form);
identityService.create(
form.email.$modelValue, form.password.$modelValue, function(err) {
if (err) $scope.error('Error', err.toString());
$rootScope.$digest();
});
}
});

View File

@ -14,14 +14,14 @@ angular.module('copayApp.controllers').controller('HeadController', function($sc
$scope.signout = function() {
$rootScope.signingOut = true;
identityService.logout();
identityService.signout();
};
$scope.refresh = function() {
var w = $rootScope.wallet;
if (!w) return;
if (w.isReady()) {
if (w.isComplete()) {
w.sendWalletReady();
balanceService.clearBalanceCache(w);
balanceService.update(w, function() {

View File

@ -22,7 +22,19 @@ angular.module('copayApp.controllers').controller('HomeController', function($sc
$scope.error = 'Please enter the required fields';
return;
}
identityService.open($scope, form);
$rootScope.starting = true;
identityService.open(form.email.$modelValue, form.password.$modelValue, function(err) {
$rootScope.starting = false;
if (err) {
copay.logger.warn(err);
if ((err.toString() || '').match('PNOTFOUND')) {
$scope.error = 'Invalid email or password';
} else {
$scope.error = 'Unknown error';
}
$rootScope.$digest()
}
});
}
function getParam(sname) {

View File

@ -125,6 +125,19 @@ angular.module('copayApp.controllers').controller('JoinController',
privateHex: $scope.private,
}, function(err) {
$scope.loading = false;
if (err) {
if (err === 'joinError')
notification.error('Fatal error connecting to Insight server');
else if (err === 'walletFull')
notification.error('The wallet is full');
else if (err === 'badNetwork')
notification.error('Network Error', 'Wallet network configuration missmatch');
else if (err === 'badSecret')
notification.error('Bad secret', 'The secret string you entered is invalid');
else {
notification.error('Error', err.message || err);
}
}
});
}
});

View File

@ -20,7 +20,6 @@ angular.module('copayApp.controllers').controller('ProfileController', function(
identityService.deleteWallet(w.id,function() {
$scope.loading = false;
$scope.getWallets();
});
};

View File

@ -1,6 +1,6 @@
'use strict';
angular.module('copayApp.controllers').controller('SettingsController', function($scope, $rootScope, $window, $route, $location, $anchorScroll, notification) {
angular.module('copayApp.controllers').controller('SettingsController', function($scope, $rootScope, $window, $route, $location, $anchorScroll, notification, applicationService) {
$scope.title = 'Settings';
$scope.defaultLanguage = config.defaultLanguage || 'en';
$scope.insightLivenet = config.network.livenet.url;
@ -94,16 +94,13 @@ angular.module('copayApp.controllers').controller('SettingsController', function
}),
}));
// Go home reloading the application
var hashIndex = window.location.href.indexOf('#!/');
window.location = window.location.href.substr(0, hashIndex);
applicationService.restart();
};
$scope.reset = function() {
localStorage.removeItem('config');
// Go home reloading the application
window.location.reload();
applicationService.reload();
};
});

View File

@ -8,7 +8,7 @@ angular.module('copayApp.controllers').controller('WarningController', function(
};
$scope.signout = function() {
identityService.logout();
identityService.signout();
};
$scope.ignoreLock = function() {

View File

@ -28,7 +28,6 @@ function Network(opts) {
if (opts.transports) {
this.socketOptions['transports'] = opts.transports;
}
this.socket = this.createSocket();
}
nodeUtil.inherits(Network, EventEmitter);
@ -236,7 +235,7 @@ Network.prototype._onMessage = function(enc) {
}
};
Network.prototype._setupConnectionHandlers = function(opts, cb) {
Network.prototype._setupSocketHandlers = function(opts, cb) {
preconditions.checkState(this.socket);
log.debug('setting up connection', opts);
var self = this;
@ -274,10 +273,7 @@ Network.prototype._setupConnectionHandlers = function(opts, cb) {
});
self.socket.on('error', self._onError.bind(self));
self.socket.on('no messages', self.emit.bind(self, 'no messages'));
var pubkey = self.getKey().public.toString('hex');
self.socket.on('no_messages', self.emit.bind(self, 'no_messages'));
self.socket.on('connect', function() {
var pubkey = self.getKey().public.toString('hex');
log.debug('Async subscribing to pubkey:', pubkey);
@ -287,13 +283,8 @@ Network.prototype._setupConnectionHandlers = function(opts, cb) {
self.socket.on('disconnect', function() {
self.socket.emit('subscribe', pubkey);
});
log.debug('Async subs done');
if (typeof cb === 'function') cb();
});
};
Network.prototype._onError = function(err) {
@ -350,7 +341,9 @@ Network.prototype.start = function(opts, openCallback) {
this.privkey = opts.privkey;
this.setCopayerId(opts.copayerId);
this.maxPeers = opts.maxPeers || this.maxPeers;
this._setupConnectionHandlers(opts, openCallback);
this.socket = this.createSocket();
this._setupSocketHandlers(opts, openCallback);
};
Network.prototype.createSocket = function() {

View File

@ -1,19 +1,22 @@
'use strict';
var preconditions = require('preconditions').singleton();
var _ = require('lodash');
var bitcore = require('bitcore');
var preconditions = require('preconditions').singleton();
var inherits = require('inherits');
var events = require('events');
var log = require('../log');
var async = require('async');
var cryptoUtil = require('../util/crypto');
var version = require('../../version').version;
var bitcore = require('bitcore');
var TxProposals = require('./TxProposals');
var PublicKeyRing = require('./PublicKeyRing');
var PrivateKey = require('./PrivateKey');
var Wallet = require('./Wallet');
var PluginManager = require('./PluginManager');
var Async = module.exports.Async = require('./Async');
var Async = require('./Async');
var version = require('../../version').version;
var cryptoUtil = require('../util/crypto');
/**
* @desc
@ -56,9 +59,14 @@ function Identity(opts) {
this.walletDefaults = opts.walletDefaults || {};
this.version = opts.version || version;
this.walletIds = opts.walletIds || {};
this.wallets = opts.wallets || {};
this.focusedTimestamps = opts.focusedTimestamps || {};
};
inherits(Identity, events.EventEmitter);
Identity.getStoragePrefix = function() {
return 'profile::';
};
@ -96,7 +104,11 @@ Identity.create = function(opts, cb) {
/**
* Open an Identity from the given storage
* Open an Identity from the given storage.
*
* After opening a profile, and setting its wallet event handlers,
* the client must run .netStart on each
* wallet (or call Identity.netStart())
*
* @param {Object} opts
* @param {Object} opts.storage
@ -105,62 +117,96 @@ Identity.create = function(opts, cb) {
* @param {Function} cb
*/
Identity.open = function(opts, cb) {
preconditions.checkArgument(_.isObject(opts));
preconditions.checkArgument(_.isFunction(cb));
var storage = opts.storage || opts.pluginManager.get('DB');
storage.setCredentials(opts.email, opts.password, opts);
storage.getItem(Identity.getKeyForEmail(opts.email), function(err, data) {
var exported;
if (err) {
return cb(err);
}
return Identity.createFromPartialJson(data, opts, cb);
try {
exported = JSON.parse(data);
} catch (e) {
return cb(e);
}
return cb(null, new Identity(_.extend(opts, exported)));
});
};
/**
* Creates an Identity, retrieves all Wallets remotely, and activates network
*
* @param {string} jsonString - a string containing a json object with options to rebuild the identity
* @param {Object} opts
* @param {Function} cb
*/
Identity.createFromPartialJson = function(jsonString, opts, callback) {
var exported;
try {
exported = JSON.parse(jsonString);
} catch (e) {
return callback('Invalid JSON');
}
var identity = new Identity(_.extend(opts, exported));
async.map(exported.walletIds, function(walletId, callback) {
identity.retrieveWalletFromStorage(walletId, {}, function(error, wallet) {
if (!error) {
console.log('[Identity.js.136] GOT:', wallet.getName()); //TODO
identity.wallets[wallet.getId()] = wallet;
identity.bindWallet(wallet);
wallet.netStart();
console.log('[Identity.js.136] STARTED:', wallet.getName()); //TODO
}
callback(error, wallet);
});
}, function(err) {
return callback(err, identity);
/**
* readAndBindWallet
*
* @param {string} wid walletId to be readed
* @param {function} cb
*
*/
Identity.prototype.readAndBindWallet = function(walletId, cb) {
var self = this;
self.retrieveWalletFromStorage(walletId, {}, function(error, wallet) {
if (!error) {
self.bindWallet(wallet);
}
return cb(error);
});
};
Identity.prototype.emitAndKeepAlive = function(args) {
var args = Array.prototype.slice.call(arguments);
log.debug('Ident Emitting:', args);
//this.keepAlive(); // TODO
this.emit.apply(this, arguments);
};
/**
* @desc open profile's wallets. Call it AFTER setting
* the proper even listeners
*
* @param cb
*/
Identity.prototype.openWallets = function(cb) {
var self = this;
if (_.isEmpty(self.walletIds)) {
self.emitAndKeepAlive('noWallets')
return cb();
}
// First read the lastFocused wallet
self.walletIds.sort(function(a, b) {
var va = self.focusedTimestamps[a] || 0;
var vb = self.focusedTimestamps[b] || 0;
return va < vb ? 1 : (va === vb ? 0 : -1);
});
console.log('[Identity.js.188]', self.walletIds, self.focusedTimestamps); //TODO
// Then read the rest of the wallets...
async.eachSeries(self.walletIds, function(walletId, a_cb) {
self.readAndBindWallet(walletId, a_cb);
}, cb);
};
/**
* @param {string} walletId
* @param {} opts
* opts.importWallet
* @param {Function} callback
* @param {Function} cb
*/
Identity.prototype.retrieveWalletFromStorage = function(walletId, opts, callback) {
Identity.prototype.retrieveWalletFromStorage = function(walletId, opts, cb) {
var self = this;
var importFunction = opts.importWallet || Wallet.fromUntrustedObj;
this.storage.getItem(Wallet.getStorageKey(walletId), function(error, walletData) {
if (error) {
return callback(error);
return cb(error);
}
try {
log.info('## OPENING Wallet:', walletId);
@ -175,12 +221,12 @@ Identity.prototype.retrieveWalletFromStorage = function(walletId, opts, callback
} catch (e) {
log.debug("ERROR: ", e.message);
if (e && e.message && e.message.indexOf('MISSOPTS') !== -1) {
return callback(new Error('WERROR: Could not read: ' + walletId + ': ' + e.message));
return cb(new Error('WERROR: Could not read: ' + walletId + ': ' + e.message));
} else {
return callback(e);
return cb(e);
}
}
return callback(null, importFunction(walletData, readOpts));
return cb(null, importFunction(walletData, readOpts));
});
};
@ -219,9 +265,9 @@ Identity.storeWalletDebounced = _.debounce(function(identity, wallet, cb) {
Identity.prototype.toObj = function() {
return _.extend({
walletIds: _.keys(this.wallets)
walletIds: _.isEmpty(this.wallets) ? this.walletsIds : _.keys(this.wallets),
},
_.pick(this, 'version', 'fullName', 'password', 'email'));
_.pick(this, 'version', 'fullName', 'password', 'email', 'focusedTimestamps'));
};
Identity.prototype.exportEncryptedWithWalletInfo = function(opts) {
@ -270,15 +316,15 @@ Identity.prototype._cleanUp = function() {
/**
* @desc Closes the wallet and disconnects all services
*/
Identity.prototype.close = function(cb) {
async.map(this.wallets, function(wallet, callback) {
wallet.close(callback);
}, cb);
Identity.prototype.close = function() {
var self = this;
self.store({}, function(err) {
self.emitAndKeepAlive('closed');
});
};
// TODO: Add feedback function
//
Identity.prototype.importWalletFromObj = function(obj, opts, cb) {
var self = this;
preconditions.checkArgument(cb);
@ -298,7 +344,7 @@ Identity.prototype.importWalletFromObj = function(obj, opts, cb) {
log.debug('Updating Indexes for wallet:' + w.getName());
w.updateIndexes(function(err) {
log.debug('Adding wallet to profile:' + w.getName());
self.addWallet(w);
self.updateFocusedTimestamp(w.getId());
self.bindWallet(w);
var writeOpts = _.extend({
@ -321,8 +367,8 @@ Identity.prototype.importWalletFromObj = function(obj, opts, cb) {
Identity.prototype.closeWallet = function(wallet, cb) {
preconditions.checkState(wallet, 'Wallet not found');
var self = this;
wallet.close(function(err) {
delete self.wallets[wid];
return cb(err);
});
};
@ -371,15 +417,15 @@ Identity.importFromFullJson = function(str, password, opts, cb) {
if (err) return cb(err); //profile already exists
opts.failIfExists = false;
async.map(json.wallets, function(walletData, callback) {
async.map(json.wallets, function(walletData, cb) {
if (!walletData)
return callback();
return cb();
iden.importWalletFromObj(walletData, opts, function(err, w) {
if (err) return callback(err);
if (err) return cb(err);
log.debug('Wallet ' + w.getId() + ' imported');
callback();
cb();
});
}, function(err, results) {
if (err) return cb(err);
@ -394,10 +440,13 @@ Identity.importFromFullJson = function(str, password, opts, cb) {
};
/**
* @desc binds a wallet's events and emits 'newWallet'
* @param {string} walletId Wallet id to be binded
* @emits newWallet (walletId)
*/
Identity.prototype.bindWallet = function(w) {
var self = this;
self.wallets[w.getId()] = w;
this.wallets[w.getId()] = w;
log.debug('Binding wallet:' + w.getName());
w.on('txProposalsUpdated', function() {
@ -421,6 +470,8 @@ Identity.prototype.bindWallet = function(w) {
w.on('publicKeyRingUpdated', function() {
Identity.storeWalletDebounced(self, w);
});
this.emitAndKeepAlive('newWallet', w.getId());
};
/**
@ -494,12 +545,10 @@ Identity.prototype.createWallet = function(opts, cb) {
var self = this;
var w = new walletClass(opts);
this.addWallet(w);
self.updateFocusedTimestamp(w.getId());
self.bindWallet(w);
w.netStart();
self.storeWallet(w, function(err) {
if (err) return cb(err);
self.store({
noWallets: true
}, function(err) {
@ -508,12 +557,6 @@ Identity.prototype.createWallet = function(opts, cb) {
});
};
Identity.prototype.addWallet = function(wallet) {
preconditions.checkArgument(wallet);
preconditions.checkArgument(wallet.getId);
this.wallets[wallet.getId()] = wallet;
};
/**
* @desc Checks if a version is compatible with the current version
* @param {string} inVersion - a version, with major, minor, and revision, period-separated (x.y.z)
@ -565,10 +608,13 @@ Identity.prototype.deleteWallet = function(walletId, cb) {
w.close();
delete this.wallets[walletId];
delete this.focusedTimestamps[walletId];
this.storage.removeItem(Wallet.getStorageKey(walletId), function(err) {
if (err) {
return cb(err);
}
self.emitAndKeepAlive('deletedWallet', walletId);
self.store(null, cb);
});
};
@ -584,11 +630,26 @@ Identity.prototype.decodeSecret = function(secret) {
}
};
Identity.prototype.getLastFocusedWallet = function() {
if (_.keys(this.wallets).length == 0) return;
return _.max(this.wallets, function(wallet) {
return wallet.focusedTimestamp || 0;
});
/**
* getLastFocusedWalletId
*
* @return {string} walletId
*/
Identity.prototype.getLastFocusedWalletId = function() {
var max = _.max(this.focusedTimestamp);
var aId = this.wallets[0] ? this.wallets[0].getId() : this.walletIds[0];
if (!max)
return aId;
return _.findKey(this.focusedTimestamps, function(ts) {
return ts == max;
}) || aId;
};
Identity.prototype.updateFocusedTimestamp = function(wid) {
preconditions.checkArgument(wid && this.wallets[wid]);
this.focusedTimestamps[wid] = Date.now();
};
/**

View File

@ -226,9 +226,6 @@ Insight.prototype.subscribe = function(addresses) {
s.on(address, handler);
}
});
console.log('[Insight.js.202] subscribe ENDED'); //TODO
};
Insight.prototype.getSubscriptions = function(addresses) {
@ -291,7 +288,6 @@ Insight.prototype.getTransactions = function(addresses, from, to, cb) {
};
Insight.prototype.getUnspent = function(addresses, cb) {
console.log('[Insight.js.296:addresses:]',addresses); //TODO
preconditions.shouldBeArray(addresses);
preconditions.shouldBeFunction(cb);

View File

@ -95,7 +95,6 @@ function Wallet(opts) {
this.registeredPeerIds = [];
this.addressBook = opts.addressBook || {};
this.publicKey = this.privateKey.publicHex;
this.focusedTimestamp = opts.focusedTimestamp || 0;
this.syncedTimestamp = opts.syncedTimestamp || 0;
this.lastMessageFrom = {};
@ -126,7 +125,7 @@ Wallet.TX_SIGNED_AND_BROADCASTED = 'txSignedAndBroadcasted';
Wallet.prototype.emitAndKeepAlive = function(args) {
var args = Array.prototype.slice.call(arguments);
log.debug('Wallet Emitting:', args);
log.debug('Wallet:'+ this.getName() + ' Emitting:', args);
this.keepAlive();
this.emit.apply(this, arguments);
};
@ -158,7 +157,6 @@ Wallet.PERSISTED_PROPERTIES = [
'txProposals',
'privateKey',
'addressBook',
'focusedTimestamp',
'syncedTimestamp',
'secretNumber',
];
@ -647,18 +645,6 @@ Wallet.prototype._onAddressBook = function(senderId, data) {
}
};
/**
* @desc Updates the wallet's last modified timestamp and triggers a save
* @param {number} ts - the timestamp
*/
Wallet.prototype.updateFocusedTimestamp = function(ts) {
preconditions.checkArgument(ts);
preconditions.checkArgument(_.isNumber(ts));
preconditions.checkArgument(ts > 2999999999, 'use miliseconds');
this.focusedTimestamp = ts;
};
Wallet.prototype.updateSyncedTimestamp = function(ts) {
preconditions.checkArgument(ts);
preconditions.checkArgument(_.isNumber(ts));
@ -877,15 +863,8 @@ Wallet.decodeSecret = function(secretB) {
}
};
/**
* @desc Locks other sessions from connecting to the wallet
* @see Async#lockIncommingConnections
*/
Wallet.prototype._lockIncomming = function() {
this.network.lockIncommingConnections(this.publicKeyRing.getAllCopayerIds());
};
Wallet.prototype._setBlockchainListeners = function() {
Wallet.prototype._setupBlockchainHandlers = function() {
var self = this;
self.blockchain.removeAllListeners();
@ -915,7 +894,18 @@ Wallet.prototype._setBlockchainListeners = function() {
}
}
Wallet.prototype._setupNetworkHandlers = function() {
var self = this;
var net = this.network;
net.removeAllListeners();
net.on('connect', self._onConnect.bind(self));
net.on('data', self._onData.bind(self));
net.on('no_messages', self._onNoMessages.bind(self));
net.on('connect_error', function() {
self.emitAndKeepAlive('connectionError');
});
};
/**
* @desc Sets up the networking with other peers.
@ -926,43 +916,26 @@ Wallet.prototype._setBlockchainListeners = function() {
* @emits ready
* @emits txProposalsUpdated
*
* @TODO: FIX PROTOCOL -- emit with a space is shitty
* @emits no messages
*/
Wallet.prototype.netStart = function() {
var self = this;
if (self.netStarted)
return;
self._setupBlockchainHandlers();
self.netStarted= true;
if (!this.isShared()) {
self.emitAndKeepAlive('ready');
return;
}
var net = this.network;
net.removeAllListeners();
net.on('connect', self._onConnect.bind(self));
net.on('data', self._onData.bind(self));
net.on('no messages', self._onNoMessages.bind(self));
net.on('connect_error', function() {
self.emitAndKeepAlive('connectionError');
});
if (this.publicKeyRing.isComplete()) {
this._lockIncomming();
}
if (net.started) {
log.debug('Wallet:' + self.getName() + ': Wallet networking was ready')
self.emitAndKeepAlive('ready', net.getPeer());
return;
}
self._setupNetworkHandlers();
var myId = self.getMyCopayerId();
var myIdPriv = self.getMyCopayerIdPriv();
var startOpts = {
copayerId: myId,
privkey: myIdPriv,
@ -971,11 +944,12 @@ Wallet.prototype.netStart = function() {
secretNumber: self.secretNumber,
};
if (this.publicKeyRing.isComplete()) {
this.network.lockIncommingConnections(this.publicKeyRing.getAllCopayerIds());
}
log.debug('Wallet:' + self.id + ' Starting network.');
net.start(startOpts, function() {
self._setBlockchainListeners();
self.emitAndKeepAlive('ready', net.getPeer());
this.network.start(startOpts, function() {
self.emitAndKeepAlive('ready');
});
};
@ -1059,7 +1033,6 @@ Wallet.prototype.toObj = function() {
privateKey: this.privateKey ? this.privateKey.toObj() : undefined,
addressBook: this.addressBook,
syncedTimestamp: this.syncedTimestamp || 0,
focusedTimestamp: this.focusedTimestamp || 0,
secretNumber: this.secretNumber,
};
@ -1103,7 +1076,6 @@ Wallet.fromUntrustedObj = function(obj, readOpts) {
* @param {string} o.networkName - 'livenet' or 'testnet'
* @param {Object} o.publicKeyRing - PublicKeyRing to be deserialized by {@link PublicKeyRing#fromObj}
* @param {number} o.syncedTimestamp - ts of the last synced message with insifht (in microseconds, as insight returns ts)
* @param {number} o.focusedTimestamp - last time this wallet was focused (open) by a user (in miliseconds)
* @param {Object} o.txProposals - TxProposals to be deserialized by {@link TxProposals#fromObj}
* @param {string} o.nickname - user's nickname
*
@ -1180,8 +1152,6 @@ Wallet.fromObj = function(o, readOpts) {
}
opts.syncedTimestamp = o.syncedTimestamp || 0;
opts.focusedTimestamp = o.focusedTimestamp || 0;
opts.blockchainOpts = readOpts.blockchainOpts;
opts.networkOpts = readOpts.networkOpts;
@ -2114,7 +2084,11 @@ Wallet.prototype.maxRejectCount = function() {
// TODO: Can we add cache to getUnspent?
Wallet.prototype.getUnspent = function(cb) {
var self = this;
this.blockchain.getUnspent(this.getAddresses(), function(err, unspentList) {
var addresses = this.getAddresses();
log.debug('Wallet ' + this.getName() + ': Getting unspents from ' + addresses.length + ' addresses');
this.blockchain.getUnspent(addresses, function(err, unspentList) {
if (err) {
return cb(err);
@ -2322,7 +2296,7 @@ Wallet.prototype._createTxProposal = function(toAddress, amountSat, comment, utx
*/
Wallet.prototype.updateIndexes = function(callback) {
var self = this;
if (!self.isReady())
if (!self.isComplete())
return callback();
log.debug('Wallet:' + this.id + ' Updating indexes...');
var tasks = this.publicKeyRing.indexes.map(function(index) {
@ -2440,12 +2414,12 @@ Wallet.prototype.indexDiscovery = function(start, change, copayerIndex, gap, cb)
* @desc Closes the wallet and disconnects all services
*/
Wallet.prototype.close = function(cb) {
log.debug('## CLOSING Wallet: ' + this.id);
this.network.removeAllListeners();
this.network.cleanUp();
this.blockchain.removeAllListeners();
this.blockchain.destroy();
log.debug('## CLOSING Wallet: ' + this.id);
// TODO
// this.lock.release(function() {
if (cb) return cb();
@ -2521,7 +2495,7 @@ Wallet.prototype.requiresMultipleSignatures = function() {
* @desc Returns true if the keyring is complete
* @return {boolean}
*/
Wallet.prototype.isReady = function() {
Wallet.prototype.isComplete = function() {
return this.publicKeyRing.isComplete();
};

View File

@ -85,7 +85,6 @@ InsightStorage.prototype._makeGetRequest = function(passphrase, key, callback) {
'Authorization': authHeader
}
};
log.debug('Insight request', getParams);
this.request.get(getParams,
function(err, response, body) {
if (err) {

View File

@ -47,32 +47,32 @@ angular
})
.when('/homeWallet', {
templateUrl: 'views/homeWallet.html',
walletShouldBeReady: true,
walletShouldBeComplete: true,
logged: true
})
.when('/receive', {
templateUrl: 'views/receive.html',
walletShouldBeReady: true,
walletShouldBeComplete: true,
logged: true
})
.when('/history', {
templateUrl: 'views/history.html',
walletShouldBeReady: true,
walletShouldBeComplete: true,
logged: true
})
.when('/send', {
templateUrl: 'views/send.html',
walletShouldBeReady: true,
walletShouldBeComplete: true,
logged: true
})
.when('/more', {
templateUrl: 'views/more.html',
walletShouldBeReady: true,
walletShouldBeComplete: true,
logged: true
})
.when('/settings', {
templateUrl: 'views/settings.html',
walletShouldBeReady: true,
walletShouldBeComplete: true,
logged: false
})
.when('/warning', {
@ -125,7 +125,7 @@ angular
$idle.unwatch();
$location.path('/');
}
if ($rootScope.wallet && !$rootScope.wallet.isReady() && next.walletShouldBeReady) {
if ($rootScope.wallet && !$rootScope.wallet.isComplete() && next.walletShouldBeComplete) {
$location.path('/copayers');
}
}

View File

@ -0,0 +1,17 @@
'use strict';
angular.module('copayApp.services')
.factory('applicationService', function() {
var root = {};
root.restart = function() {
// Go home reloading the application
var hashIndex = window.location.href.indexOf('#!/');
window.location = window.location.href.substr(0, hashIndex);
};
root.reload = function() {
window.location.reload();
};
return root;
});

View File

@ -13,8 +13,6 @@ angular.module('copayApp.services')
cb = cb || function() {};
var satToUnit = 1 / w.settings.unitToSatoshi;
var COIN = bitcore.util.COIN;
console.log('[balanceS.js.257] FETCH BALANCE: ', w.getName()); //TODO
w.getBalance(function(err, balanceSat, balanceByAddrSat, safeBalanceSat, safeUnspentCount) {
if (err) return cb(err);
@ -55,26 +53,32 @@ angular.module('copayApp.services')
};
root.update = function(w, cb, isFocused) {
console.log(' UPDATE BALANCE!!!!', w ? w.getName() : 'current'); //TODO
w = w || $rootScope.wallet;
if (!w || !w.isReady()) return;
if (!w || !w.isComplete()) return;
console.log('DO UPDATE BALANCE!!!!', w.getName()); //TODO
copay.logger.debug('Updating balance of:', w.getName(), isFocused);
var wid = w.getId();
// cache available? Set the cached values until we updated them
if (_balanceCache[wid]) {
w.balanceInfo = _balanceCache[wid];
} else {
$rootScope.updatingBalance = true;
if (isFocused)
$rootScope.updatingBalance = true;
}
w.balanceInfo = w.balanceInfo || {};
w.balanceInfo.updating = true;
root._fetchBalance(w, function(err, res) {
if (err) throw err;
w.balanceInfo=_balanceCache[wid] = res;
$rootScope.updatingBalance = false;
w.balanceInfo.updating = false;
if (isFocused) {
_.extend($rootScope, w.balanceInfo);
$rootScope.updatingBalance = false;
}
if (cb) cb();
});

View File

@ -1,9 +1,9 @@
'use strict';
angular.module('copayApp.services')
.factory('identityService', function($rootScope, $location, $timeout, $filter, pluginManager, notification, pendingTxsService, balanceService) {
var root = {};
.factory('identityService', function($rootScope, $location, $timeout, $filter, pluginManager, notification, pendingTxsService, balanceService, applicationService) {
notification.enableHtml5Mode(); // for chrome: if support, enable it
var root = {};
root.check = function(scope) {
copay.Identity.checkIfExistsAny({
pluginManager: pluginManager,
@ -25,7 +25,7 @@ angular.module('copayApp.services')
root.goWalletHome = function() {
var w = $rootScope.wallet;
if (w) {
if (!w.isReady()) {
if (!w.isComplete()) {
$location.path('/copayers');
} else {
if ($rootScope.pendingPayment) {
@ -37,8 +37,7 @@ angular.module('copayApp.services')
}
};
root.create = function(scope, form) {
$rootScope.starting = true;
root.create = function(email, password) {
copay.Identity.create({
email: form.email.$modelValue,
password: form.password.$modelValue,
@ -49,19 +48,9 @@ angular.module('copayApp.services')
passphraseConfig: config.passphraseConfig,
failIfExists: true,
}, function(err, iden) {
if (err || !iden) {
copay.logger.debug(err);
if (err && (err.match('EEXISTS') || err.match('BADCREDENTIALS'))) {
scope.error = 'User already exists!';
} else {
scope.error = 'Unknown error when connecting Insight Server';
}
$rootScope.starting = false;
$timeout(function() {
$rootScope.$digest()
}, 1);
return;
}
if (err) return cb(err);
preconditions.checkState(iden);
var walletOptions = {
nickname: iden.fullName,
networkName: config.networkName,
@ -71,61 +60,37 @@ angular.module('copayApp.services')
name: 'My wallet',
};
iden.createWallet(walletOptions, function(err, wallet) {
if (err || !wallet) {
copay.logger.debug(err);
scope.error = 'Could not create default wallet';
$rootScope.starting = false;
$timeout(function() {
$rootScope.$digest()
}, 1);
return;
}
root.bind(scope, iden, wallet.id);
if (err) return cb(err);
root.bind(iden);
return cb();
});
});
};
root.open = function(scope, form) {
$rootScope.starting = true;
copay.Identity.open({
email: form.email.$modelValue,
password: form.password.$modelValue,
root.open = function(email, password, cb) {
var opts = {
email: email,
password: password,
pluginManager: pluginManager,
network: config.network,
networkName: config.networkName,
walletDefaults: config.wallet,
passphraseConfig: config.passphraseConfig,
}, function(err, iden) {
$rootScope.starting = false;
if (err && !iden) {
if ((err.toString() || '').match('PNOTFOUND')) {
scope.error = 'Invalid email or password';
} else {
scope.error = 'Unknown error';
}
$timeout(function() {
$rootScope.$digest()
}, 1);
} else {
};
console.log('[identityService.js.95] LISTO OPEN!!'); //TODO
var firstWallet = iden.getLastFocusedWallet();
root.bind(scope, iden, firstWallet);
}
copay.Identity.open(opts, function(err, iden) {
if (err) return cb(err);
console.log('[identityService.js.95] LISTO OPEN!!'); //TODO
root.bind(iden);
return iden.openWallets(cb);
});
};
root.deleteWallet = function($scope, iden, w) {
$rootScope.iden.deleteWallet(w.id, function() {
notification.info(name + ' deleted', $filter('translate')('This wallet was deleted'));
if ($rootScope.wallet.id === w.id) {
$rootScope.wallet = null;
var lastFocused = $rootScope.iden.getLastFocusedWallet();
root.bind($scope, $rootScope.iden, lastFocused);
}
});
$rootScope.iden.deleteWallet(w.id);
};
root.isFocused = function(wid) {
@ -133,13 +98,8 @@ angular.module('copayApp.services')
};
root.setupGlobalVariables = function(iden) {
notification.enableHtml5Mode(); // for chrome: if support, enable it
$rootScope.unitName = config.unitName;
$rootScope.pendingTxCount = 0;
$rootScope.initialConnection = true;
$rootScope.reconnecting = false;
$rootScope.isCollapsed = true;
$rootScope.iden = iden;
};
@ -151,20 +111,20 @@ angular.module('copayApp.services')
root.setFocusedWallet = function(w) {
if (!_.isObject(w))
w = $rootScope.iden.getWalletById(w);
preconditions.checkState(w && _.isObject(w));
copay.logger.debug('Set focus:', w.getName());
$rootScope.wallet = w;
w.updateFocusedTimestamp(Date.now());
root.goWalletHome();
$rootScope.iden.updateFocusedTimestamp(w.getId());
pendingTxsService.update();
console.log('[controllerUtils.js.221] SET FOCUS'); //TODO
balanceService.update(w, function() {
$timeout(function() {
$rootScope.$digest();
}, true)
})
};
root.installWalletHandlers = function($scope, w) {
root.installWalletHandlers = function(w) {
var wid = w.getId();
w.on('connectionError', function() {
console.log('err', w.getName()); //TODO
@ -181,12 +141,12 @@ angular.module('copayApp.services')
}
});
w.on('ready', function() {
console.log('read', w.getName()); //TODO
$scope.loading = false;
if ($rootScope.initialConnection) {
$rootScope.initialConnection = false;
root.goWalletHome();
}
var isFocused = root.isFocused(wid);
console.log('GOT READY [identityService.js.184:isFocused:]', w.getName(), isFocused); //TODO
balanceService.update(w, function() {
$rootScope.$digest();
}, isFocused);
});
w.on('tx', function(address, isChange) {
@ -282,85 +242,79 @@ angular.module('copayApp.services')
// w.on('locked',);
};
root.rebindWallets = function($scope, iden) {
_.each(iden.listWallets(), function(wallet) {
preconditions.checkState(wallet);
root.installWalletHandlers($scope, wallet);
root.bind = function(iden) {
console.log('[identityService.js.250] PROFILE BINE'); //TODO
preconditions.checkArgument(_.isObject(iden));
var self = this;
root.setupGlobalVariables(iden);
iden.on('newWallet', function(wid) {
var w = iden.getWalletById(wid);
copay.logger.debug('newWallet:', w.getName());
root.installWalletHandlers(w);
w.netStart();
if (wid == iden.getLastFocusedWalletId()) {
copay.logger.debug('GOT Focused wallet!', w.getName());
root.setFocusedWallet(w);
root.goWalletHome();
$rootScope.$digest()
}
});
iden.on('noWallets', function() {
$location.path('/create');
$rootScope.$digest()
});
iden.on('deletedWallet', function(wid) {
notification.info('Wallet deleted', $filter('translate')('This wallet was deleted'));
if ($rootScope.wallet.id === wid) {
$rootScope.wallet = null;
var lastFocused = iden.getLastFocusedWalletId();
self.setFocusedWallet(lastFocused);
}
});
iden.on('closed', function() {
delete $rootScope['wallet'];
delete $rootScope['iden'];
applicationService.restart();
});
};
root.bind = function($scope, iden, w) {
console.log('ident bind Globals'); //TODO
root.setupGlobalVariables(iden);
root.rebindWallets($scope, iden);
if (w) {
root.setFocusedWallet(w);
} else {
$location.path('/create');
}
$timeout(function() {
console.log('[controllerUtils.js.242] DIGEST'); //TODO
$rootScope.$digest()
console.log('[controllerUtils.js.242] DIGEST DONE'); //TODO
}, 1);
};
root.logout = function() {
root.signout = function() {
if ($rootScope.iden) {
$rootScope.iden.store(null, function() {
$rootScope.iden.close();
delete $rootScope['wallet'];
delete $rootScope['iden'];
// Go home reloading the application
var hashIndex = window.location.href.indexOf('#!/');
window.location = window.location.href.substr(0, hashIndex);
});
$rootScope.iden.close();
}
};
root.createWallet = function(opts, cb) {
$rootScope.iden.createWallet(opts, function(err, w) {
root.installWalletHandlers($scope, w);
root.setFocusedWallet(w);
return cb();
});
$rootScope.iden.createWallet(opts, cb);
};
root.importWallet = function(encryptedObj, pass, opts, cb) {
copay.Compatibility.importEncryptedWallet($rootScope.iden, encryptedObj,
pass, opts, function(err, wallet) {
if (err) return cb(err);
root.installWalletHandlers($scope, wallet);
root.setFocusedWallet(wallet);
return cb();
});
copay.Compatibility.importEncryptedWallet($rootScope.iden, encryptedObj, pass, opts);
};
root.joinWallet = function(opts, cb) {
$rootScope.iden.joinWallet(opts, function(err, w) {
$scope.loading = false;
if (err || !w) {
if (err === 'joinError')
notification.error('Fatal error connecting to Insight server');
else if (err === 'walletFull')
notification.error('The wallet is full');
else if (err === 'badNetwork')
notification.error('Network Error', 'Wallet network configuration missmatch');
else if (err === 'badSecret')
notification.error('Bad secret', 'The secret string you entered is invalid');
else {
notification.error('Error', err.message || err);
}
} else {
root.installWalletHandlers($scope, w);
root.setFocusedWallet(w);
}
return cb(err);
});
};
root.importProfile = function(str, password, cb){
copay.Identity.importFromEncryptedFullJson(str, password, {
pluginManager: pluginManager,
network: config.network,
networkName: config.networkName,
walletDefaults: config.wallet,
passphraseConfig: config.passphraseConfig,
}, function(err, iden) {
if (err) return cb(err);
});
};
return root;
});

View File

@ -0,0 +1,11 @@
'use strict';
angular.module('copayApp.services')
.factory('pendingTxsService', function($rootScope, $sce, $location, $filter, notification, $timeout, rateService) {
var root = {};
root.update = function(w) {
console.log('[pendingTxsService.js.8] TODO updade pending Txs'); //TODO
};
return root;
});

View File

@ -524,14 +524,14 @@ describe('Wallet model', function() {
it('#isReady', function() {
it('#isComplete', function() {
var w = createW();
w.publicKeyRing.isComplete().should.equal(false);
w.isReady().should.equal(false);
w.isComplete().should.equal(false);
var w2 = createW2();
w2.publicKeyRing.isComplete().should.equal(true);
w2.isReady().should.equal(true);
w2.isComplete().should.equal(true);
});
it('handle network indexes correctly', function() {
@ -2497,7 +2497,7 @@ describe('Wallet model', function() {
blockchainOpts: {},
}, function(err, w) {
should.exist(w);
w.isReady().should.equal(true);
w.isComplete().should.equal(true);
var wo = w.toObj();
wo.opts.id.should.equal('48ba2f1ffdfe9708');
wo.opts.spendUnconfirmed.should.equal(true);

View File

@ -50,7 +50,7 @@ describe("Unit: Controllers", function() {
var w = {};
w.id = 1234;
w.isReady = sinon.stub().returns(true);
w.isComplete = sinon.stub().returns(true);
w.privateKey = {};
w.settings = {
unitToSatoshi: 100,

View File

@ -10,7 +10,7 @@ describe("Unit: Testing Directives", function() {
beforeEach(inject(function($rootScope) {
var w = {};
w.isReady = sinon.stub().returns(true);
w.isComplete = sinon.stub().returns(true);
w.privateKey = {};
w.settings = {
unitToSatoshi: 100,

View File

@ -9,7 +9,7 @@ describe('Angular Filters', function() {
beforeEach(inject(function($rootScope) {
var w = {};
w.isReady = sinon.stub().returns(true);
w.isComplete = sinon.stub().returns(true);
w.privateKey = {};
w.settings = {
unitToSatoshi: 100,

View File

@ -26,7 +26,7 @@ describe("Angular services", function() {
beforeEach(inject(function($rootScope) {
var w = {};
w.isReady = sinon.stub().returns(true);
w.isComplete = sinon.stub().returns(true);
w.privateKey = {};
w.settings = {
unitToSatoshi: 100,

View File

@ -1,5 +1,5 @@
<div ng-controller="CopayersController">
<div ng-if='$root.wallet && $root.wallet.isReady()' ng-init="goToWallet()"></div>
<div ng-if='$root.wallet && $root.wallet.isComplete()' ng-init="goToWallet()"></div>
<div class="row hide-for-large-up">
<div class="medium-12 small-12 columns">
@ -11,7 +11,7 @@
</div>
<div class="row">
<div class="large-12 columns">
<div ng-if="!$root.wallet.isReady()">
<div ng-if="!$root.wallet.isComplete()">
<div class="panel oh">
<h2 class="line-b">
Share this secret with your other copayers
@ -27,7 +27,7 @@
</div>
<div class="panel oh">
<div ng-include="'views/includes/copayer.html'"></div>
<div class="copay-box" ng-if="!$root.wallet.isReady()">
<div class="copay-box" ng-if="!$root.wallet.isComplete()">
<span ng-include="'views/includes/photo.html'"></span>
<p class="size-12 text-white text-light m0">
<i class="fi-loop icon-rotate spinner"></i>

View File

@ -1,5 +1,4 @@
<div class="transactions" data-ng-controller="HistoryController" data-ng-init="update()">
<div ng-show='$root.wallet.isReady()'>
<div class="row">
<div class="large-12 medium-12 small-12 columns">
<h1 class="hide-for-large-up">{{$root.title}}</h1>
@ -140,5 +139,4 @@
</div>
</div>
</div>
</div>
</div>

View File

@ -1,5 +1,4 @@
<div class="home-wallet" ng-controller="HomeWalletController">
<div ng-show='$root.wallet.isReady()'>
<div class="row hide-for-large-up">
<div class="medium-12 small-12 columns">
<h1 translate>Home</h1>
@ -60,7 +59,5 @@
</div>
</div>
</div>
</div>
</div>

View File

@ -12,8 +12,8 @@
</div>
</div>
<div class="founds size-12">
<span ng-if="!$root.wallet.isReady()">Waiting for copayers...</span>
<div ng-if="$root.wallet.isReady()">
<span ng-if="!$root.wallet.isComplete()">Waiting for copayers...</span>
<div ng-if="$root.wallet.isComplete()">
<span ng-if="$root.updatingBalance"><i class="fi-bitcoin-circle icon-rotate spinner"></i></span>
<div ng-if="$root.wallet && !$root.updatingBalance" data-options="disable_for_touch:true">
<b class="m5r">{{totalBalance || 0 |noFractionNumber}} {{$root.wallet.settings.unitName}}</b>
@ -56,12 +56,12 @@
<div class="ellipsis name-wallet">{{item.name || item.id}}</div>
</div>
<div class="oh">
<span ng-if="item.isReady() && item.balanceInfo.updatingBalance"><i class="fi-bitcoin-circle icon-rotate spinner"></i></span>
<div ng-if="item.isReady() && !item.balanceInfo.updatingBalance" data-options="disable_for_touch:true">
<span ng-if="item.isComplete() && item.balanceInfo.updatingBalance"><i class="fi-bitcoin-circle icon-rotate spinner"></i></span>
<div ng-if="item.isComplete() && !item.balanceInfo.updatingBalance" data-options="disable_for_touch:true">
<b class="m5r size-12">{{item.balanceInfo.totalBalance || 0 |noFractionNumber}} {{item.settings.unitName}}</b>
<span class="alt-currency size-10">{{item.balanceInfo.totalBalanceAlternative |noFractionNumber:2}} {{item.balanceInfo.alternativeIsoCode}}</span>
</div>
<span ng-if="!item.isReady()">Waiting for copayers...</span>
<span ng-if="!item.isComplete()">Waiting for copayers...</span>
</div>
</a>
</div>

View File

@ -11,8 +11,8 @@
</div>
</div>
<div class="founds size-12">
<span ng-if="!$root.wallet.isReady()">Waiting for copayers...</span>
<div ng-if="$root.wallet.isReady()">
<span ng-if="!$root.wallet.isComplete()">Waiting for copayers...</span>
<div ng-if="$root.wallet.isComplete()">
<span ng-if="$root.updatingBalance"><i class="fi-bitcoin-circle icon-rotate spinner"></i></span>
<div ng-if="$root.wallet && !$root.updatingBalance" data-options="disable_for_touch:true">
<b class="m5r">{{totalBalance || 0 |noFractionNumber}} {{$root.wallet.settings.unitName}}</b>
@ -62,12 +62,12 @@
<div class="ellipsis name-wallet">{{item.name || item.id}}</div>
</div>
<div class="oh">
<span ng-if="item.isReady() && item.balanceInfo.updatingBalance"><i class="fi-bitcoin-circle icon-rotate spinner"></i></span>
<div ng-if="item.isReady() && !item.balanceInfo.updatingBalance" data-options="disable_for_touch:true">
<span ng-if="item.isComplete() && item.balanceInfo.updatingBalance"><i class="fi-bitcoin-circle icon-rotate spinner"></i></span>
<div ng-if="item.isComplete() && !item.balanceInfo.updatingBalance" data-options="disable_for_touch:true">
<b class="m5r size-12">{{item.balanceInfo.totalBalance || 0 |noFractionNumber}} {{item.settings.unitName}}</b>
<span class="alt-currency size-10">{{item.balanceInfo.totalBalanceAlternative |noFractionNumber:2}} {{item.balanceInfo.alternativeIsoCode}}</span>
</div>
<span ng-if="!item.isReady()">Waiting for copayers...</span>
<span ng-if="!item.isComplete()">Waiting for copayers...</span>
</div>
</a>
</div>
@ -75,7 +75,7 @@
</ul>
</div>
<ul class="side-nav" ng-if="(!walletSelection || !wallets[0]) && $root.wallet.isReady()">
<ul class="side-nav" ng-if="(!walletSelection || !wallets[0]) && $root.wallet.isComplete()">
<li data-ng-repeat="item in menu" ui-route="{{item.link}}" class="nav-item" data-ng-class="{active: isActive(item)}">
<a href="#!/{{item.link}}" ng-click="toggleCollapse()" class="db p20h">
<i class="size-21 m20r {{item.icon}}"></i> {{item.title|translate}}

View File

@ -55,17 +55,17 @@
<tbody>
<tr
data-ng-repeat="item in wallets | orderBy:'name'"
ng-init="isReady = item.isReady();
ng-init="isComplete = item.isComplete();
networkName = item.getNetworkName()"
ng-class="{'deleting':loading==item.id}">
<td>{{item.name || item.id }}</td>
<td>{{item.requiredCopayers}} of {{item.totalCopayers}} - {{networkName}}</td>
<td class="hide-for-small-only">
{{isReady ? 'Complete' : 'Waiting for copayers...'}}
{{isComplete ? 'Complete' : 'Waiting for copayers...'}}
</td>
<td>
<span ng-if="!isReady">-</span>
<span ng-if="isReady">
<span ng-if="!isComplete">-</span>
<span ng-if="isComplete">
{{item.balanceInfo.totalBalance || 0 |noFractionNumber}} {{item.settings.unitName}}
</span>
</td>

View File

@ -1,5 +1,4 @@
<div class="addresses" ng-controller="ReceiveController">
<div ng-show='$root.wallet.isReady()'>
<div class="row">
<div class="large-12 medium-12 small-12 columns">
<h1 class="hide-for-large-up">{{$root.title}}</h1>
@ -64,6 +63,5 @@
</a>
</div>
</div>
</div>
</div>

View File

@ -1,6 +1,4 @@
<div class="send" ng-controller="SendController" ng-init="loadTxs()">
<div ng-show='$root.wallet.isReady()'>
<div class="row" ng-show="txps.length != 0">
<div class="large-12 columns">
<h2 translate>Pending Transactions Proposals</h2>
@ -230,6 +228,5 @@
<i class="fi-plus m5r"></i> Add</button>
</div>
</div>
</div>
</div>