copay/js/models/core/Wallet.js

522 lines
13 KiB
JavaScript
Raw Normal View History

2014-04-10 13:57:41 -07:00
'use strict';
2014-04-15 14:23:35 -07:00
var imports = require('soop').imports();
2014-04-14 13:17:56 -07:00
2014-04-15 14:23:35 -07:00
var bitcore = require('bitcore');
var coinUtil = bitcore.util;
2014-04-14 14:30:08 -07:00
var buffertools = bitcore.buffertools;
2014-04-15 14:23:35 -07:00
var Builder = bitcore.TransactionBuilder;
var http = require('http');
2014-04-16 13:50:10 -07:00
var EventEmitter= imports.EventEmitter || require('events').EventEmitter;
var copay = copay || require('../../../copay');
2014-04-10 13:57:41 -07:00
2014-04-16 13:50:10 -07:00
function Wallet(opts) {
var self = this;
2014-04-14 13:17:56 -07:00
2014-04-16 13:50:10 -07:00
//required params
['storage', 'network', 'blockchain',
'requiredCopayers', 'totalCopayers', 'spendUnconfirmed',
'publicKeyRing', 'txProposals', 'privateKey'
].forEach( function(k){
if (typeof opts[k] === 'undefined') throw new Error('missing key:' + k);
self[k] = opts[k];
});
2014-04-14 13:17:56 -07:00
this.log('creating '+opts.requiredCopayers+' of '+opts.totalCopayers+' wallet');
2014-04-16 15:45:22 -07:00
2014-04-16 13:50:10 -07:00
this.id = opts.id || Wallet.getRandomId();
2014-04-16 18:12:30 -07:00
this.verbose = opts.verbose;
2014-04-16 13:50:10 -07:00
this.publicKeyRing.walletId = this.id;
this.txProposals.walletId = this.id;
2014-04-16 18:12:30 -07:00
2014-04-14 13:42:10 -07:00
}
2014-04-10 13:57:41 -07:00
2014-04-16 13:50:10 -07:00
Wallet.parent=EventEmitter;
2014-04-15 10:28:49 -07:00
Wallet.prototype.log = function(){
if (!this.verbose) return;
2014-04-20 16:24:24 -07:00
if (console)
console.log.apply(console, arguments);
2014-04-16 13:50:10 -07:00
};
2014-04-15 10:28:49 -07:00
2014-04-16 13:50:10 -07:00
Wallet.getRandomId = function() {
var r = buffertools.toHex(coinUtil.generateNonce());
return r;
};
2014-04-15 10:28:49 -07:00
2014-04-16 13:50:10 -07:00
Wallet.prototype._handlePublicKeyRing = function(senderId, data, isInbound) {
this.log('RECV PUBLICKEYRING:',data);
var shouldSend = false;
var recipients, pkr = this.publicKeyRing;
var inPKR = copay.PublicKeyRing.fromObj(data.publicKeyRing);
2014-04-18 14:25:51 -07:00
var hasChanged = pkr.merge(inPKR, true);
2014-04-20 12:34:46 -07:00
if (hasChanged) {
2014-04-16 13:50:10 -07:00
this.log('### BROADCASTING PKR');
recipients = null;
shouldSend = true;
}
2014-04-20 12:34:46 -07:00
// else if (isInbound && !data.isBroadcast) {
// // always replying to connecting peer
// this.log('### REPLYING PKR TO:', senderId);
// recipients = senderId;
// shouldSend = true;
// }
2014-04-15 08:52:28 -07:00
2014-04-16 13:50:10 -07:00
if (shouldSend) {
this.sendPublicKeyRing(recipients);
}
this.store();
2014-04-14 13:42:10 -07:00
};
2014-04-14 13:17:56 -07:00
2014-04-14 14:30:08 -07:00
2014-04-16 13:50:10 -07:00
Wallet.prototype._handleTxProposals = function(senderId, data, isInbound) {
this.log('RECV TXPROPOSAL:',data); //TODO
2014-04-14 13:17:56 -07:00
2014-04-16 13:50:10 -07:00
var shouldSend = false;
var recipients;
var inTxp = copay.TxProposals.fromObj(data.txProposals);
var mergeInfo = this.txProposals.merge(inTxp, true);
var addSeen = this.addSeenToTxProposals();
2014-04-20 16:24:24 -07:00
if (mergeInfo.hasChanged || addSeen) {
2014-04-16 13:50:10 -07:00
this.log('### BROADCASTING txProposals. ' );
recipients = null;
shouldSend = true;
}
2014-04-20 12:34:46 -07:00
// else if (isInbound && !data.isBroadcast) {
// // always replying to connecting peer
// this.log('### REPLYING txProposals TO:', senderId);
// recipients = senderId;
// shouldSend = true;
// }
2014-04-14 13:17:56 -07:00
2014-04-16 13:50:10 -07:00
if (shouldSend)
this.sendTxProposals(recipients);
this.store();
2014-04-14 13:42:10 -07:00
};
2014-04-16 13:50:10 -07:00
Wallet.prototype._handleData = function(senderId, data, isInbound) {
2014-04-20 12:16:09 -07:00
// TODO check message signature
if (this.id !== data.walletId) {
this.emit('badMessage',senderId);
this.log('badMessage FROM:', senderId); //TODO
return;
}
this.log('[Wallet.js.98]' , data.type); //TODO
2014-04-16 13:50:10 -07:00
switch(data.type) {
2014-04-20 13:16:21 -07:00
// This handler is repeaded on WalletFactory (#join). TODO
case 'walletId':
this.sendWalletReady(senderId);
break;
2014-04-20 12:16:09 -07:00
case 'walletReady':
this.sendPublicKeyRing(senderId);
this.sendTxProposals(senderId);
break;
2014-04-16 13:50:10 -07:00
case 'publicKeyRing':
this._handlePublicKeyRing(senderId, data, isInbound);
break;
case 'txProposals':
this._handleTxProposals(senderId, data, isInbound);
break;
}
};
2014-04-14 13:42:10 -07:00
2014-04-20 12:16:09 -07:00
Wallet.prototype._handleNetworkChange = function(newPeerId) {
if (newPeerId) {
this.log('#### Setting new PEER:', newPeerId);
this.sendWalletId(newPeerId);
}
2014-04-17 07:46:49 -07:00
this.emit('refresh');
2014-04-14 13:42:10 -07:00
};
2014-04-20 12:16:09 -07:00
2014-04-17 14:02:20 -07:00
Wallet.prototype._optsToObj = function () {
var obj = {
id: this.id,
spendUnconfirmed: this.spendUnconfirmed,
requiredCopayers: this.requiredCopayers,
totalCopayers: this.totalCopayers,
};
return obj;
};
2014-04-18 10:40:16 -07:00
2014-04-20 08:41:28 -07:00
Wallet.prototype.getPeerId = function(index) {
return this.publicKeyRing.getCopayerId(index || 0);
2014-04-20 08:41:28 -07:00
};
2014-04-18 14:25:51 -07:00
2014-04-20 08:41:28 -07:00
Wallet.prototype.getMyPeerId = function() {
return this.getPeerId(0);
2014-04-18 10:40:16 -07:00
};
2014-04-16 15:18:19 -07:00
Wallet.prototype.netStart = function() {
2014-04-16 13:50:10 -07:00
var self = this;
var net = this.network;
2014-04-17 12:50:48 -07:00
net.removeAllListeners();
2014-04-16 16:58:57 -07:00
net.on('networkChange', self._handleNetworkChange.bind(self) );
net.on('data', self._handleData.bind(self) );
2014-04-16 13:50:10 -07:00
net.on('open', function() {}); // TODO
net.on('openError', function() {
2014-04-18 14:25:51 -07:00
self.log('[Wallet.js.132:openError:] GOT openError'); //TODO
self.emit('openError');
});
net.on('close', function() {
self.emit('close');
});
2014-04-20 08:41:28 -07:00
var myPeerId = self.getMyPeerId();
2014-04-18 10:40:16 -07:00
var startOpts = {
2014-04-20 08:41:28 -07:00
peerId: myPeerId
};
net.start(function() {
2014-04-16 13:50:10 -07:00
self.emit('created');
2014-04-18 14:25:51 -07:00
for (var i=0; i<self.publicKeyRing.registeredCopayers(); i++) {
2014-04-20 08:41:28 -07:00
var otherPeerId = self.getPeerId(i);
if (otherPeerId !== myPeerId) {
2014-04-18 14:25:51 -07:00
net.connectTo(otherPeerId);
}
2014-04-20 16:24:24 -07:00
self.sendWalletReady(self.firstPeerId);
self.firstPeerId = null;
2014-04-20 13:16:21 -07:00
self.emit('refresh');
2014-04-18 14:25:51 -07:00
}
2014-04-18 10:40:16 -07:00
}, startOpts);
2014-04-16 13:50:10 -07:00
};
2014-04-15 06:22:50 -07:00
2014-04-18 09:20:35 -07:00
Wallet.prototype.store = function(isSync) {
this.log('[Wallet.js.135:store:]'); //TODO
2014-04-17 14:02:20 -07:00
var wallet = this.toObj();
this.storage.setFromObj(this.id, wallet);
2014-04-16 18:12:30 -07:00
2014-04-18 09:20:35 -07:00
if (isSync) {
this.log('Wallet stored.'); //TODO
2014-04-20 16:24:24 -07:00
}
else {
2014-04-18 09:20:35 -07:00
this.log('Wallet stored. REFRESH Emitted'); //TODO
this.emit('refresh');
}
2014-04-17 14:02:20 -07:00
};
Wallet.prototype.toObj = function() {
var optsObj = this._optsToObj();
var walletObj = {
opts: optsObj,
publicKeyRing: this.publicKeyRing.toObj(),
2014-04-17 14:02:20 -07:00
txProposals: this.txProposals.toObj(),
privateKey: this.privateKey.toObj()
};
return walletObj;
2014-04-15 06:22:50 -07:00
};
2014-04-17 14:02:20 -07:00
Wallet.fromObj = function(wallet) {
var opts = wallet.opts;
opts['publicKeyRing'] = this.publicKeyring.fromObj(wallet.publicKeyRing);
opts['txProposals'] = this.txProposal.fromObj(wallet.txProposals);
opts['privateKey'] = this.privateKey.fromObj(wallet.privateKey);
var w = new Wallet(opts);
return w;
};
2014-04-15 08:17:28 -07:00
Wallet.prototype.sendTxProposals = function(recipients) {
2014-04-15 10:28:49 -07:00
this.log('### SENDING txProposals TO:', recipients||'All', this.txProposals);
2014-04-15 08:17:28 -07:00
this.network.send( recipients, {
type: 'txProposals',
txProposals: this.txProposals.toObj(),
walletId: this.id,
});
2014-04-16 13:50:10 -07:00
this.emit('txProposalsUpdated', this.txProposals);
2014-04-15 08:17:28 -07:00
};
2014-04-20 12:16:09 -07:00
Wallet.prototype.sendWalletReady = function(recipients) {
this.log('### SENDING WalletReady TO:', recipients);
this.network.send( recipients, {
type: 'walletReady',
walletId: this.id,
});
this.emit('walletReady');
};
2014-04-16 16:58:57 -07:00
Wallet.prototype.sendWalletId = function(recipients) {
this.log('### SENDING walletId TO:', recipients||'All', this.walletId);
this.network.send(recipients, {
type: 'walletId',
walletId: this.id,
2014-04-18 14:25:51 -07:00
opts: this._optsToObj()
2014-04-16 16:58:57 -07:00
});
};
2014-04-15 08:17:28 -07:00
Wallet.prototype.sendPublicKeyRing = function(recipients) {
2014-04-15 10:28:49 -07:00
this.log('### SENDING publicKeyRing TO:', recipients||'All', this.publicKeyRing.toObj());
2014-04-15 08:17:28 -07:00
this.network.send(recipients, {
type: 'publicKeyRing',
publicKeyRing: this.publicKeyRing.toObj(),
walletId: this.id,
});
2014-04-16 13:50:10 -07:00
this.emit('publicKeyRingUpdated', this.publicKeyRing);
2014-04-15 08:17:28 -07:00
};
2014-04-21 07:28:25 -07:00
Wallet.prototype.generateAddress = function(isChange) {
var addr = this.publicKeyRing.generateAddress(isChange);
2014-04-16 13:50:10 -07:00
this.sendPublicKeyRing();
2014-04-18 09:20:35 -07:00
this.store(true);
2014-04-15 12:50:16 -07:00
return addr;
};
2014-04-15 08:17:28 -07:00
2014-04-22 22:01:54 -07:00
2014-04-15 11:25:55 -07:00
Wallet.prototype.getTxProposals = function() {
var ret = [];
2014-04-18 15:28:28 -07:00
for(var k in this.txProposals.txps) {
2014-04-22 22:01:54 -07:00
var i = this.txProposals.getTxProposal(k);
i.signedByUs = i.signedBy[this.getMyPeerId()]?true:false;
i.rejectedByUs = i.rejectedBy[this.getMyPeerId()]?true:false;
if (this.totalCopayers-i.rejectCount < this.requiredCopayers)
i.finallyRejected=true;
2014-04-21 03:27:45 -07:00
2014-04-15 11:25:55 -07:00
ret.push(i);
2014-04-16 13:50:10 -07:00
}
return ret;
};
2014-04-22 22:01:54 -07:00
Wallet.prototype.reject = function(ntxid) {
var myId=this.getMyPeerId();
2014-04-18 15:28:28 -07:00
var txp = this.txProposals.txps[ntxid];
2014-04-22 22:01:54 -07:00
if (!txp || txp.rejectedBy[myId] || txp.signedBy[myId]) return;
txp.rejectedBy[myId] = Date.now();
this.sendTxProposals();
this.store(true);
2014-04-18 15:28:28 -07:00
};
2014-04-16 13:50:10 -07:00
2014-04-22 22:01:54 -07:00
2014-04-16 13:50:10 -07:00
Wallet.prototype.sign = function(ntxid) {
2014-04-18 15:28:28 -07:00
var self = this;
2014-04-22 22:01:54 -07:00
var myId=this.getMyPeerId();
2014-04-18 15:28:28 -07:00
var txp = self.txProposals.txps[ntxid];
2014-04-22 22:01:54 -07:00
if (!txp || txp.rejectedBy[myId] || txp.signedBy[myId]) return;
2014-04-16 13:50:10 -07:00
2014-04-18 15:28:28 -07:00
var pkr = self.publicKeyRing;
var keys = self.privateKey.getAll(pkr.addressIndex, pkr.changeAddressIndex);
var b = txp.builder;
var before = b.signaturesAdded;
b.sign(keys);
var ret = false;
if (b.signaturesAdded > before) {
2014-04-22 22:01:54 -07:00
txp.signedBy[myId] = Date.now();
2014-04-18 15:28:28 -07:00
this.sendTxProposals();
this.store(true);
ret = true;
2014-04-16 13:50:10 -07:00
}
2014-04-15 11:25:55 -07:00
return ret;
};
2014-04-20 17:53:54 -07:00
Wallet.prototype.sendTx = function(ntxid, cb) {
2014-04-18 15:28:28 -07:00
var txp = this.txProposals.txps[ntxid];
if (!txp) return;
var tx = txp.builder.build();
if (!tx.isComplete()) return;
this.log('[Wallet.js.231] BROADCASTING TX!!!'); //TODO
var txHex = tx.serialize().toString('hex');
this.log('[Wallet.js.261:txHex:]',txHex); //TODO
var self = this;
2014-04-21 07:28:25 -07:00
2014-04-18 15:28:28 -07:00
this.blockchain.sendRawTransaction(txHex, function(txid) {
self.log('BITCOND txid:',txid); //TODO
if (txid) {
2014-04-21 03:30:46 -07:00
self.txProposals.setSent(ntxid, txid);
2014-04-18 15:28:28 -07:00
}
2014-04-20 17:53:54 -07:00
self.sendTxProposals();
self.store();
return cb(txid);
2014-04-18 15:28:28 -07:00
});
};
2014-04-15 11:25:55 -07:00
Wallet.prototype.addSeenToTxProposals = function() {
var ret=false;
2014-04-20 16:24:24 -07:00
var myId=this.getMyPeerId();
2014-04-16 13:50:10 -07:00
2014-04-18 15:28:28 -07:00
for(var k in this.txProposals.txps) {
var txp = this.txProposals.txps[k];
2014-04-20 16:24:24 -07:00
if (!txp.seenBy[myId]) {
txp.seenBy[myId] = Date.now();
2014-04-15 11:25:55 -07:00
ret = true;
}
2014-04-18 15:28:28 -07:00
}
2014-04-15 11:25:55 -07:00
return ret;
};
Wallet.prototype.getAddresses = function(onlyMain) {
return this.publicKeyRing.getAddresses(onlyMain);
2014-04-15 11:50:22 -07:00
};
Wallet.prototype.getAddressesStr = function(onlyMain) {
2014-04-15 14:23:35 -07:00
var ret = [];
this.publicKeyRing.getAddresses(onlyMain).forEach(function(a) {
2014-04-15 14:23:35 -07:00
ret.push(a.toString());
});
return ret;
};
2014-04-18 07:19:39 -07:00
Wallet.prototype.addressIsOwn = function(addrStr) {
var addrList = this.getAddressesStr();
var l = addrList.length;
var ret = false;
for(var i=0; i<l; i++) {
if (addrList[i] === addrStr) {
ret = true;
break;
}
}
return ret;
};
2014-04-21 08:37:32 -07:00
Wallet.prototype.getBalance = function(safe, cb) {
2014-04-18 09:20:35 -07:00
var balance = 0;
var balanceByAddr = {};
2014-04-21 07:28:25 -07:00
var isMain = {};
2014-04-18 09:20:35 -07:00
var COIN = bitcore.util.COIN;
2014-04-18 15:28:28 -07:00
var addresses = this.getAddressesStr(true);
if (!addresses.length) return cb(0,[]);
2014-04-18 07:19:39 -07:00
2014-04-18 09:20:35 -07:00
// Prefill balanceByAddr with main address
2014-04-18 15:28:28 -07:00
addresses.forEach(function(a){
2014-04-18 09:20:35 -07:00
balanceByAddr[a]=0;
2014-04-21 07:28:25 -07:00
isMain[a]=1;
2014-04-17 12:42:27 -07:00
});
2014-04-21 08:37:32 -07:00
var f = safe ? this.getSafeUnspent.bind(this):this.getUnspent.bind(this);
f(function(utxos) {
2014-04-17 13:01:45 -07:00
for(var i=0;i<utxos.length; i++) {
2014-04-18 09:20:35 -07:00
var u= utxos[i];
var amt = u.amount * COIN;
balance = balance + amt;
balanceByAddr[u.address] = (balanceByAddr[u.address]||0) + amt;
2014-04-17 07:51:56 -07:00
}
2014-04-18 15:28:28 -07:00
for(var a in balanceByAddr){
2014-04-18 09:20:35 -07:00
balanceByAddr[a] = balanceByAddr[a]/COIN;
2014-04-21 08:00:14 -07:00
}
2014-04-21 07:28:25 -07:00
return cb(balance / COIN, balanceByAddr, isMain);
});
};
2014-04-15 14:23:35 -07:00
2014-04-18 09:20:35 -07:00
Wallet.prototype.getUnspent = function(cb) {
this.blockchain.getUnspent(this.getAddressesStr(), function(unspentList) {
return cb(unspentList);
2014-04-17 12:42:27 -07:00
});
2014-04-15 14:23:35 -07:00
};
2014-04-21 08:37:32 -07:00
Wallet.prototype.getSafeUnspent = function(cb) {
var self = this;
this.blockchain.getUnspent(this.getAddressesStr(), function(unspentList) {
var ret=[];
2014-04-22 22:01:54 -07:00
var maxRejectCount = self.totalCopayers - self.requiredCopayers;
var uu = self.txProposals.getUsedUnspent(maxRejectCount);
2014-04-21 08:37:32 -07:00
for(var i in unspentList){
if (uu.indexOf(unspentList[i].txid) === -1)
ret.push(unspentList[i]);
}
return cb(ret);
});
};
2014-04-16 13:50:10 -07:00
Wallet.prototype.createTx = function(toAddress, amountSatStr, opts, cb) {
var self = this;
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
opts = opts || {};
if (typeof opts.spendUnconfirmed === 'undefined') {
opts.spendUnconfirmed = this.spendUnconfirmed;
}
2014-04-21 08:37:32 -07:00
self.getSafeUnspent(function(unspentList) {
2014-04-22 18:07:18 -07:00
if (self.createTxSync(toAddress, amountSatStr, unspentList, opts)) {
self.sendPublicKeyRing(); // Change Address
self.sendTxProposals();
self.store();
}
2014-04-16 13:50:10 -07:00
return cb();
});
};
Wallet.prototype.createTxSync = function(toAddress, amountSatStr, utxos, opts) {
2014-04-15 14:23:35 -07:00
var pkr = this.publicKeyRing;
var priv = this.privateKey;
opts = opts || {};
var amountSat = bitcore.bignum(amountSatStr);
if (! pkr.isComplete() ) {
throw new Error('publicKeyRing is not complete');
}
if (!opts.remainderOut) {
2014-04-21 07:28:25 -07:00
opts.remainderOut ={ address: this.generateAddress(true).toString() };
}
2014-04-15 14:23:35 -07:00
var b = new Builder(opts)
.setUnspent(utxos)
.setHashToScriptMap(pkr.getRedeemScriptMap())
.setOutputs([{address: toAddress, amountSat: amountSat}])
;
var signRet;
if (priv) {
2014-04-22 18:07:18 -07:00
b.sign( priv.getAll(pkr.addressIndex, pkr.changeAddressIndex) );
2014-04-15 14:23:35 -07:00
}
2014-04-20 16:24:24 -07:00
var myId = this.getMyPeerId();
var now = Date.now();
2014-04-22 22:01:54 -07:00
var me = {};
if (priv && b.signaturesAdded) me[myId] = now;
var meSeen = {};
if (priv) meSeen[myId] = now;
2014-04-20 16:24:24 -07:00
var data = {
2014-04-22 22:01:54 -07:00
signedBy: me,
seenBy: meSeen,
2014-04-20 16:24:24 -07:00
creator: myId,
createdTs: now,
2014-04-15 14:23:35 -07:00
builder: b,
2014-04-20 16:24:24 -07:00
};
this.txProposals.add(data);
2014-04-22 22:01:54 -07:00
return true;
2014-04-15 14:23:35 -07:00
};
2014-04-16 13:50:10 -07:00
Wallet.prototype.connectTo = function(peerId) {
2014-04-16 16:58:57 -07:00
throw new Error('Wallet.connectTo.. not yet implemented!');
2014-04-15 11:50:22 -07:00
};
2014-04-16 16:58:57 -07:00
Wallet.prototype.disconnect = function() {
this.network.disconnect();
};
2014-04-14 14:30:08 -07:00
module.exports = require('soop')(Wallet);