small refactor on rootScope

This commit is contained in:
Matias Alejo Garcia 2014-06-24 12:57:15 -03:00
commit 1abf1dc90d
4 changed files with 130 additions and 87 deletions

View file

@ -12,27 +12,27 @@ angular.module('copayApp.controllers').controller('AddressesController',
controllerUtils.setSocketHandlers(); controllerUtils.setSocketHandlers();
controllerUtils.updateAddressList(); controllerUtils.updateAddressList();
$scope.loading = false; $scope.loading = false;
},1); }, 1);
}); });
}; };
$scope.selectAddress = function (addr) { $scope.selectAddress = function(addr) {
$scope.selectedAddr = addr; $scope.selectedAddr = addr;
}; };
$rootScope.$watch('addrInfos', function() { $rootScope.$watch('addrInfos', function() {
$scope.addressList(); $scope.addressList();
}); });
$scope.addressList = function () { $scope.addressList = function() {
$scope.addresses = []; $scope.addresses = [];
var addrInfos = $rootScope.addrInfos; var addrInfos = $rootScope.addrInfos;
if (addrInfos) { if (addrInfos) {
for(var i=0;i<addrInfos.length;i++) { for (var i = 0; i < addrInfos.length; i++) {
var addrinfo = addrInfos[i]; var addrinfo = addrInfos[i];
$scope.addresses.push({ $scope.addresses.push({
'address' : addrinfo.address.toString(), 'address': addrinfo.addressStr,
'balance' : $rootScope.balanceByAddr ? $rootScope.balanceByAddr[addrinfo.address.toString()] : 0, 'balance': $rootScope.balanceByAddr ? $rootScope.balanceByAddr[addrinfo.addressStr] : 0,
'isChange': addrinfo.isChange 'isChange': addrinfo.isChange
}); });
} }
@ -41,5 +41,4 @@ angular.module('copayApp.controllers').controller('AddressesController',
$rootScope.receivedFund = null; $rootScope.receivedFund = null;
} }
} }
}); });

View file

@ -1,24 +1,23 @@
'use strict'; 'use strict';
var imports = require('soop').imports(); var imports = require('soop').imports();
var preconditions = require('preconditions').instance(); var preconditions = require('preconditions').instance();
var bitcore = require('bitcore'); var bitcore = require('bitcore');
var HK = bitcore.HierarchicalKey; var HK = bitcore.HierarchicalKey;
var PrivateKey = require('./PrivateKey'); var PrivateKey = require('./PrivateKey');
var Structure = require('./Structure'); var Structure = require('./Structure');
var AddressIndex= require('./AddressIndex'); var AddressIndex = require('./AddressIndex');
var Address = bitcore.Address; var Address = bitcore.Address;
var Script = bitcore.Script; var Script = bitcore.Script;
function PublicKeyRing(opts) { function PublicKeyRing(opts) {
opts = opts || {}; opts = opts || {};
this.walletId = opts.walletId; this.walletId = opts.walletId;
this.network = opts.networkName === 'livenet' ? this.network = opts.networkName === 'livenet' ?
bitcore.networks.livenet : bitcore.networks.testnet; bitcore.networks.livenet : bitcore.networks.testnet;
this.requiredCopayers = opts.requiredCopayers || 3; this.requiredCopayers = opts.requiredCopayers || 3;
this.totalCopayers = opts.totalCopayers || 5; this.totalCopayers = opts.totalCopayers || 5;
@ -33,11 +32,11 @@ function PublicKeyRing(opts) {
this.addressToPath = {}; this.addressToPath = {};
} }
PublicKeyRing.fromObj = function (data) { PublicKeyRing.fromObj = function(data) {
if (data instanceof PublicKeyRing) { if (data instanceof PublicKeyRing) {
throw new Error('bad data format: Did you use .toObj()?'); throw new Error('bad data format: Did you use .toObj()?');
} }
var ret = new PublicKeyRing(data); var ret = new PublicKeyRing(data);
for (var k in data.copayersExtPubKeys) { for (var k in data.copayersExtPubKeys) {
ret.addCopayer(data.copayersExtPubKeys[k]); ret.addCopayer(data.copayersExtPubKeys[k]);
@ -54,8 +53,8 @@ PublicKeyRing.prototype.toObj = function() {
totalCopayers: this.totalCopayers, totalCopayers: this.totalCopayers,
indexes: this.indexes.toObj(), indexes: this.indexes.toObj(),
copayersExtPubKeys: this.copayersHK.map( function (b) { copayersExtPubKeys: this.copayersHK.map(function(b) {
return b.extendedPublicKeyString(); return b.extendedPublicKeyString();
}), }),
nicknameFor: this.nicknameFor, nicknameFor: this.nicknameFor,
publicKeysCache: this.publicKeysCache publicKeysCache: this.publicKeysCache
@ -67,11 +66,11 @@ PublicKeyRing.prototype.getCopayerId = function(i) {
return this.copayerIds[i]; return this.copayerIds[i];
}; };
PublicKeyRing.prototype.registeredCopayers = function () { PublicKeyRing.prototype.registeredCopayers = function() {
return this.copayersHK.length; return this.copayersHK.length;
}; };
PublicKeyRing.prototype.isComplete = function () { PublicKeyRing.prototype.isComplete = function() {
return this.registeredCopayers() === this.totalCopayers; return this.registeredCopayers() === this.totalCopayers;
}; };
@ -86,21 +85,23 @@ PublicKeyRing.prototype.myCopayerId = function(i) {
PublicKeyRing.prototype._checkKeys = function() { PublicKeyRing.prototype._checkKeys = function() {
if (!this.isComplete()) if (!this.isComplete())
throw new Error('dont have required keys yet'); throw new Error('dont have required keys yet');
}; };
PublicKeyRing.prototype._newExtendedPublicKey = function () { PublicKeyRing.prototype._newExtendedPublicKey = function() {
return new PrivateKey({networkName: this.network.name}) return new PrivateKey({
networkName: this.network.name
})
.deriveBIP45Branch() .deriveBIP45Branch()
.extendedPublicKeyString(); .extendedPublicKeyString();
}; };
PublicKeyRing.prototype._updateBip = function (index) { PublicKeyRing.prototype._updateBip = function(index) {
var hk = this.copayersHK[index].derive(Structure.IdBranch); var hk = this.copayersHK[index].derive(Structure.IdBranch);
this.copayerIds[index]= hk.eckey.public.toString('hex'); this.copayerIds[index] = hk.eckey.public.toString('hex');
}; };
PublicKeyRing.prototype._setNicknameForIndex = function (index, nickname) { PublicKeyRing.prototype._setNicknameForIndex = function(index, nickname) {
this.nicknameFor[this.copayerIds[index]] = nickname; this.nicknameFor[this.copayerIds[index]] = nickname;
}; };
@ -114,9 +115,9 @@ PublicKeyRing.prototype.nicknameForCopayer = function(copayerId) {
PublicKeyRing.prototype.addCopayer = function(newEpk, nickname) { PublicKeyRing.prototype.addCopayer = function(newEpk, nickname) {
if (this.isComplete()) if (this.isComplete())
throw new Error('PKR already has all required key:' + this.totalCopayers); throw new Error('PKR already has all required key:' + this.totalCopayers);
this.copayersHK.forEach(function(b){ this.copayersHK.forEach(function(b) {
if (b.extendedPublicKeyString() === newEpk) if (b.extendedPublicKeyString() === newEpk)
throw new Error('PKR already has that key'); throw new Error('PKR already has that key');
}); });
@ -129,7 +130,7 @@ PublicKeyRing.prototype.addCopayer = function(newEpk, nickname) {
var bip = new HK(newEpk); var bip = new HK(newEpk);
this.copayersHK.push(bip); this.copayersHK.push(bip);
this._updateBip(i); this._updateBip(i);
if (nickname) { if (nickname) {
this._setNicknameForIndex(i, nickname); this._setNicknameForIndex(i, nickname);
} }
return newEpk; return newEpk;
@ -138,19 +139,22 @@ PublicKeyRing.prototype.addCopayer = function(newEpk, nickname) {
PublicKeyRing.prototype.getPubKeys = function(index, isChange) { PublicKeyRing.prototype.getPubKeys = function(index, isChange) {
this._checkKeys(); this._checkKeys();
var path = Structure.Branch(index, isChange); var path = Structure.Branch(index, isChange);
var pubKeys = this.publicKeysCache[path]; var pubKeys = this.publicKeysCache[path];
if (!pubKeys) { if (!pubKeys) {
pubKeys = []; pubKeys = [];
var l = this.copayersHK.length; var l = this.copayersHK.length;
for(var i=0; i<l; i++) { for (var i = 0; i < l; i++) {
var hk = this.copayersHK[i].derive(path); var hk = this.copayersHK[i].derive(path);
pubKeys[i] = hk.eckey.public; pubKeys[i] = hk.eckey.public;
} }
this.publicKeysCache[path] = pubKeys.map(function(pk){return pk.toString('hex');}); this.publicKeysCache[path] = pubKeys.map(function(pk) {
} return pk.toString('hex');
else { });
pubKeys = pubKeys.map(function(s){return new Buffer(s,'hex');}); } else {
pubKeys = pubKeys.map(function(s) {
return new Buffer(s, 'hex');
});
} }
@ -158,15 +162,15 @@ PublicKeyRing.prototype.getPubKeys = function(index, isChange) {
}; };
// TODO this could be cached // TODO this could be cached
PublicKeyRing.prototype.getRedeemScript = function (index, isChange) { PublicKeyRing.prototype.getRedeemScript = function(index, isChange) {
var pubKeys = this.getPubKeys(index, isChange); var pubKeys = this.getPubKeys(index, isChange);
var script = Script.createMultisig(this.requiredCopayers, pubKeys); var script = Script.createMultisig(this.requiredCopayers, pubKeys);
return script; return script;
}; };
// TODO this could be cached // TODO this could be cached
PublicKeyRing.prototype.getAddress = function (index, isChange) { PublicKeyRing.prototype.getAddress = function(index, isChange) {
var script = this.getRedeemScript(index,isChange); var script = this.getRedeemScript(index, isChange);
var address = Address.fromScript(script, this.network.name); var address = Address.fromScript(script, this.network.name);
this.addressToPath[address.toString()] = Structure.FullBranch(index, isChange); this.addressToPath[address.toString()] = Structure.FullBranch(index, isChange);
return address; return address;
@ -174,13 +178,13 @@ PublicKeyRing.prototype.getAddress = function (index, isChange) {
PublicKeyRing.prototype.pathForAddress = function(address) { PublicKeyRing.prototype.pathForAddress = function(address) {
var path = this.addressToPath[address]; var path = this.addressToPath[address];
if (!path) throw new Error('Couldn\'t find path for address '+address); if (!path) throw new Error('Couldn\'t find path for address ' + address);
return path; return path;
}; };
// TODO this could be cached // TODO this could be cached
PublicKeyRing.prototype.getScriptPubKeyHex = function (index, isChange) { PublicKeyRing.prototype.getScriptPubKeyHex = function(index, isChange) {
var addr = this.getAddress(index,isChange); var addr = this.getAddress(index, isChange);
return Script.createP2SH(addr.payload()).getBuffer().toString('hex'); return Script.createP2SH(addr.payload()).getBuffer().toString('hex');
}; };
@ -204,18 +208,22 @@ PublicKeyRing.prototype.getAddressesInfo = function(opts) {
var ret = []; var ret = [];
if (!opts.excludeChange) { if (!opts.excludeChange) {
for (var i=0; i<this.indexes.getChangeIndex(); i++) { for (var i = 0; i < this.indexes.getChangeIndex(); i++) {
var a = this.getAddress(i, true);
ret.unshift({ ret.unshift({
address: this.getAddress(i,true), address: this.getAddress(i, true),
addressStr: a.toString(),
isChange: true isChange: true
}); });
} }
} }
if (!opts.excludeMain) { if (!opts.excludeMain) {
for (var i=0; i<this.indexes.getReceiveIndex(); i++) { for (var i = 0; i < this.indexes.getReceiveIndex(); i++) {
var a = this.getAddress(i, false);
ret.unshift({ ret.unshift({
address: this.getAddress(i,false), address: a,
addressStr: a.toString(),
isChange: false isChange: false
}); });
} }
@ -225,59 +233,59 @@ PublicKeyRing.prototype.getAddressesInfo = function(opts) {
}; };
// TODO this could be cached // TODO this could be cached
PublicKeyRing.prototype._addScriptMap = function (map, index, isChange) { PublicKeyRing.prototype._addScriptMap = function(map, index, isChange) {
var script = this.getRedeemScript(index,isChange); var script = this.getRedeemScript(index, isChange);
map[Address.fromScript(script, this.network.name).toString()] = script.getBuffer().toString('hex'); map[Address.fromScript(script, this.network.name).toString()] = script.getBuffer().toString('hex');
}; };
PublicKeyRing.prototype.getRedeemScriptMap = function () { PublicKeyRing.prototype.getRedeemScriptMap = function() {
var ret = {}; var ret = {};
for (var i=0; i<this.indexes.getChangeIndex(); i++) { for (var i = 0; i < this.indexes.getChangeIndex(); i++) {
this._addScriptMap(ret,i,true); this._addScriptMap(ret, i, true);
} }
for (var i=0; i<this.indexes.getReceiveIndex(); i++) { for (var i = 0; i < this.indexes.getReceiveIndex(); i++) {
this._addScriptMap(ret,i,false); this._addScriptMap(ret, i, false);
} }
return ret; return ret;
}; };
PublicKeyRing.prototype._checkInPKR = function(inPKR, ignoreId) { PublicKeyRing.prototype._checkInPKR = function(inPKR, ignoreId) {
if (!ignoreId && this.walletId !== inPKR.walletId) { if (!ignoreId && this.walletId !== inPKR.walletId) {
throw new Error('inPKR walletId mismatch'); throw new Error('inPKR walletId mismatch');
} }
if (this.network.name !== inPKR.network.name) { if (this.network.name !== inPKR.network.name) {
throw new Error('Network mismatch. Should be '+this.network.name + throw new Error('Network mismatch. Should be ' + this.network.name +
' and found '+inPKR.network.name); ' and found ' + inPKR.network.name);
} }
if ( if (
this.requiredCopayers && inPKR.requiredCopayers && this.requiredCopayers && inPKR.requiredCopayers &&
(this.requiredCopayers !== inPKR.requiredCopayers)) (this.requiredCopayers !== inPKR.requiredCopayers))
throw new Error('inPKR requiredCopayers mismatch '+this.requiredCopayers+'!='+inPKR.requiredCopayers); throw new Error('inPKR requiredCopayers mismatch ' + this.requiredCopayers + '!=' + inPKR.requiredCopayers);
if ( if (
this.totalCopayers && inPKR.totalCopayers && this.totalCopayers && inPKR.totalCopayers &&
(this.totalCopayers !== inPKR.totalCopayers)) (this.totalCopayers !== inPKR.totalCopayers))
throw new Error('inPKR totalCopayers mismatch'+this.totalCopayers+'!='+inPKR.requiredCopayers); throw new Error('inPKR totalCopayers mismatch' + this.totalCopayers + '!=' + inPKR.requiredCopayers);
}; };
PublicKeyRing.prototype._mergePubkeys = function(inPKR) { PublicKeyRing.prototype._mergePubkeys = function(inPKR) {
var self = this; var self = this;
var hasChanged = false; var hasChanged = false;
var l= self.copayersHK.length; var l = self.copayersHK.length;
if (self.isComplete()) if (self.isComplete())
return; return;
inPKR.copayersHK.forEach( function(b) { inPKR.copayersHK.forEach(function(b) {
var haveIt = false; var haveIt = false;
var epk = b.extendedPublicKeyString(); var epk = b.extendedPublicKeyString();
for(var j=0; j<l; j++) { for (var j = 0; j < l; j++) {
if (self.copayersHK[j].extendedPublicKeyString() === epk) { if (self.copayersHK[j].extendedPublicKeyString() === epk) {
haveIt=true; haveIt = true;
break; break;
} }
} }
@ -289,8 +297,8 @@ PublicKeyRing.prototype._mergePubkeys = function(inPKR) {
self.copayersHK.push(new HK(epk)); self.copayersHK.push(new HK(epk));
self._updateBip(l2); self._updateBip(l2);
if (inPKR.nicknameFor[self.getCopayerId(l2)]) if (inPKR.nicknameFor[self.getCopayerId(l2)])
self._setNicknameForIndex(l2,inPKR.nicknameFor[self.getCopayerId(l2)]); self._setNicknameForIndex(l2, inPKR.nicknameFor[self.getCopayerId(l2)]);
hasChanged=true; hasChanged = true;
} }
}); });
return hasChanged; return hasChanged;

View file

@ -14,6 +14,8 @@ angular.module('copayApp.services')
}; };
root.logout = function() { root.logout = function() {
Socket.removeAllListeners();
$rootScope.wallet = null; $rootScope.wallet = null;
delete $rootScope['wallet']; delete $rootScope['wallet'];
video.close(); video.close();
@ -70,10 +72,35 @@ angular.module('copayApp.services')
}); });
}; };
root.setupRootVariables = function() {
$rootScope.unitName = config.unitName;
$rootScope.txAlertCount = 0;
$rootScope.insightError = 0;
$rootScope.isCollapsed = true;
$rootScope.$watch('insightError', function(status) {
if (status === -1) {
$rootScope.$flashMessage = {
type: 'success',
message: 'Networking Restored :)',
};
$rootScope.insightError = 0;
}
});
$rootScope.$watch('txAlertCount', function(txAlertCount) {
if (txAlertCount && txAlertCount > 0) {
notification.info('New Transaction', ($rootScope.txAlertCount == 1) ? 'You have a pending transaction proposal' : 'You have ' + $rootScope.txAlertCount + ' pending transaction proposals', txAlertCount);
}
});
};
root.startNetwork = function(w, $scope) { root.startNetwork = function(w, $scope) {
Socket.removeAllListeners();
root.setupRootVariables();
root.installStartupHandlers(w, $scope); root.installStartupHandlers(w, $scope);
root.setSocketHandlers();
var handlePeerVideo = function(err, peerID, url) { var handlePeerVideo = function(err, peerID, url) {
if (err) { if (err) {
@ -103,8 +130,8 @@ angular.module('copayApp.services')
}); });
w.on('publicKeyRingUpdated', function(dontDigest) { w.on('publicKeyRingUpdated', function(dontDigest) {
root.setSocketHandlers();
root.updateAddressList(); root.updateAddressList();
root.setSocketHandlers();
if (!dontDigest) { if (!dontDigest) {
$rootScope.$digest(); $rootScope.$digest();
} }
@ -122,7 +149,7 @@ angular.module('copayApp.services')
}); });
}, 3000); }, 3000);
}); });
w.on('txProposalEvent', function(e){ w.on('txProposalEvent', function(e) {
switch (e.type) { switch (e.type) {
case 'signed': case 'signed':
var user = w.publicKeyRing.nicknameForCopayer(e.cId); var user = w.publicKeyRing.nicknameForCopayer(e.cId);
@ -273,20 +300,23 @@ angular.module('copayApp.services')
if (!$rootScope.wallet) return; if (!$rootScope.wallet) return;
var currentAddrs = Socket.getListeners(); var currentAddrs = Socket.getListeners();
var addrs = $rootScope.wallet.getAddressesStr(); var allAddrs = $rootScope.addrInfos;
var newAddrs = []; var newAddrs = [];
for (var i in addrs) { for (var i in allAddrs) {
var a = addrs[i]; var a = allAddrs[i];
if (!currentAddrs[a]) if (!currentAddrs[a.addressStr])
newAddrs.push(a); newAddrs.push(a);
} }
for (var i = 0; i < newAddrs.length; i++) { for (var i = 0; i < newAddrs.length; i++) {
Socket.emit('subscribe', newAddrs[i]); Socket.emit('subscribe', newAddrs[i].addressStr);
} }
newAddrs.forEach(function(addr) { newAddrs.forEach(function(a) {
Socket.on(addr, function(txid) { Socket.on(a.addressStr, function(txid) {
$rootScope.receivedFund = [txid, addr];
if (!a.isChange)
notification.funds('Received fund', a.addressStr);
root.updateBalance(function() { root.updateBalance(function() {
$rootScope.$digest(); $rootScope.$digest();
}); });
@ -297,7 +327,7 @@ angular.module('copayApp.services')
Socket.emit('subscribe', 'inv'); Socket.emit('subscribe', 'inv');
Socket.on('block', function(block) { Socket.on('block', function(block) {
root.updateBalance(function() { root.updateBalance(function() {
$rootScope.$digest(); $rootScope.$digest();
}); });
}); });
} }

View file

@ -38,8 +38,12 @@ angular.module('copayApp.services').factory('Socket',
var ret = {}; var ret = {};
var addrList = listeners var addrList = listeners
.filter(function(i) { return i.event != 'block'; }) .filter(function(i) {
.map(function(i) {return i.event;}); return i.event != 'block';
})
.map(function(i) {
return i.event;
});
for (var i in addrList) { for (var i in addrList) {
ret[addrList[i]] = 1; ret[addrList[i]] = 1;
@ -47,7 +51,9 @@ angular.module('copayApp.services').factory('Socket',
return ret; return ret;
}, },
isListeningBlocks: function() { isListeningBlocks: function() {
return listeners.filter(function(i) { return i.event == 'block'; }).length > 0; return listeners.filter(function(i) {
return i.event == 'block';
}).length > 0;
}, },
emit: function(event, data, callback) { emit: function(event, data, callback) {
socket.emit(event, data, function() { socket.emit(event, data, function() {
@ -62,7 +68,7 @@ angular.module('copayApp.services').factory('Socket',
removeAllListeners: function() { removeAllListeners: function() {
for (var i = 0; i < listeners.length; i++) { for (var i = 0; i < listeners.length; i++) {
var details = listeners[i]; var details = listeners[i];
socket.removeListener(details.event, details.fn); socket.removeAllListeners(details.event);
} }
listeners = []; listeners = [];